function getLeftCharacters(actual, maximo, destino) {
       destino.html(maximo-actual);
}
function maximaLongitudTextArea(obj, maxlong) {
	var in_value, out_value;
	if (obj.value.length > maxlong) {
		in_value = obj.value;
		out_value = in_value.substring(0,maxlong);
		obj.value = out_value;
	}
}

function loadFile(identificador) {
	var nombre_archivo = $("#"+identificador).val();
	$("#text_"+identificador+"_info").html(nombre_archivo);
	$("#capa_txt_"+identificador).show();
	$("#capa_file_"+identificador).hide();
	eval('document.producto.show_'+identificador+'.value="'+nombre_archivo+'";');
}

function deleteFile(identificador, hazSubmit) {
	$("#text_"+identificador+"_info").html('');
	$("#capa_txt_"+identificador).hide();
	$("#capa_file_"+identificador).show();
	if(hazSubmit == 1) {
		eval("var fichero = document.producto.show_"+identificador+".value;");
		eval('document.producto.delete_file.value="'+fichero+'";');
		eval('document.producto.show_'+identificador+'.value="";');
		doSubmit();
	}
	eval('document.producto.show_'+identificador+'.value="";');
}

function deleteFileOferta(identificador, hazSubmit) {
	$("#text_"+identificador+"_info").html('');
	$("#capa_txt_"+identificador).hide();
	$("#capa_file_"+identificador).show();
	if(hazSubmit == 1) {
		eval("var fichero = document.oferta.show_"+identificador+".value;");
		eval('document.oferta.delete_file.value="'+fichero+'";');
		eval('document.oferta.show_'+identificador+'.value="";');
		document.oferta.submit();
	}
	eval('document.oferta.show_'+identificador+'.value="";');
}

function existsFile(identificador) {
	var nombre_archivo = $("#show_"+identificador).val();
	$("#capa_txt_"+identificador).show();
	$("#capa_file_"+identificador).hide();
}

function existsFile_antigua(identificador) {
	var nombre_archivo = $("#show_"+identificador).val();
	$("#text_"+identificador+"_info").html(nombre_archivo);
	$("#capa_txt_"+identificador).show();
	$("#capa_file_"+identificador).hide();
}

function notExistsFile(identificador) {
	$("#capa_txt_"+identificador).hide();
	$("#capa_file_"+identificador).show();
}

function AbrirCentrado(Url,NombreVentana,width,height,extras) {

	var largo = width;
	var altura = height;
	var adicionales= extras;
	var top = (screen.height-altura)/2;
	var izquierda = (screen.width-largo)/2;

	var nuevaVentana=window.open(''+ Url + '','','scrollbars=1,width=' + largo + ',height=' + altura + ',top=' + top + ',left=' + izquierda + ',features=' + adicionales + '');
	nuevaVentana.focus();
}

function popupRefresh() {
	if(document.reload.refresh.value==1) {
		document.reload.submit();
	}
}

var muestraComentarios = function (elem){
	if (typeof elem == 'object'){
		if (elem.siblings('div[class^=comentario]:first').is(':visible')){
			elem.siblings('div[class^=comentario]').slideUp('fast');
		}else{
			elem.queue(function(){
				$('body').find('div[class^=comentario]:visible').slideUp('fast');
				$(this).dequeue().siblings('div[class^=comentario]').slideDown('fast')
			});
		}
	}
}

var debugImg = function(event,queueID,fileObj,response,data){
	var nombre_elem = $(event.target).attr('name');
	//$("#capa_txt_"+nombre_elem).show().find("img:first").attr('src','/temp/'+response).next().html(fileObj.name);
	var auxTamanio = Math.round((fileObj.size/1024)*100)/100;
	$("#capa_txt_"+nombre_elem).show().find("img.miniatura").attr('src','/temp/'+response).next().html(fileObj.name+" ("+ auxTamanio +"KB)");
	$("#capa_file_"+nombre_elem).hide();
	$("#delete_"+nombre_elem).val("");
	$("#show_"+nombre_elem).val(response);

}

var debugArch = function(event,queueID,fileObj,response,data){
	var nombre_elem = $(event.target).attr('name');
	//$("#capa_txt_"+nombre_elem).show().find("img:first").attr('src','/temp/'+response).next().html(fileObj.name);
	var auxTamanio = Math.round((fileObj.size/1024)*100)/100;
	$("#capa_txt_"+nombre_elem).show().find("span.fileName").html(fileObj.name+" ("+ auxTamanio +"KB)");
	$("#capa_file_"+nombre_elem).hide();
	$("#delete_"+nombre_elem).val("");
	$("#show_"+nombre_elem).val(response);
}

$(document).ready(function () {
	var LOCK_AUTOCOMPLETE = false;

	function generate_box(elem,search) {
		$("#autocomplete_box").remove();
		if (search == "null") return;
		var res = eval("("+search+");");
		$("body").prepend("<div id='autocomplete_box'></div>");
		var offset = elem.offset();
		for (i in res) {
			$("#autocomplete_box").append('<p id="categoria'+i+'">'+res[i]['nombre']+"</p>");
		}
		if (elem.is("#autocomplete_search")) {
			$("#autocomplete_box").css({
				top: (offset.top+elem.outerHeight())+"px",
				left: (offset.left-$("#autocomplete_box").outerWidth()+elem.outerWidth())+"px"
			});
		}
		else {
			$("#autocomplete_box").css({
				top: (offset.top+elem.outerHeight())+"px",
				left: offset.left+"px"
			});
		}
		$("#autocomplete_box p").click(function () {
			elem.val($(this).html());
			var values = {
				estado_producto_1_a	:1,
				estado_producto_2_a	:1,
				d_a			:60,
				z_a			:3,
				adv_s			:true,
				c			:1
			};
			var n = $(this).attr("id");
			n = parseInt(n.replace("categoria",""));
			for (i in res[n]["categorias"]) {
				values[i+"_a"] = res[n]["categorias"][i];
			}
			form_append(elem,values);
			$("#autocomplete_box").remove();
		});
	}
	function form_append(elem,values) {
		var form = elem.closest("form");
		for (i in values) {
			form.find("[name="+i+"]").remove();
			form.append('<input type="hidden" name="'+i+'" value="'+values[i]+'" style="display: none;"/>');
		}
	}

	$("#autocomplete_search,#autocomplete_search2").attr("autocomplete","off");
	$("#autocomplete_search,#autocomplete_search2").keydown(function (e) {
		e.stopPropagation();
		if (e.keyCode != 13) $(this).closest("form").find("[name=c]").remove();
		if (LOCK_AUTOCOMPLETE) return;
		else LOCK_AUTOCOMPLETE = true;
		var self = this;
		if (e.keyCode == 13) { // ENTER
			e.preventDefault();
			$("#autocomplete_box p.selected").click();
		}
		if (e.keyCode == 27) { // ESCAPE
			$("#autocomplete_box").remove();
			LOCK_AUTOCOMPLETE = false;
			return;
		}
		if (e.keyCode == 38) { // UP
			if ($("#autocomplete_box p.selected").size() > 0) {
				var p = $("#autocomplete_box p.selected").prev("p").each(function () {
					$("#autocomplete_box p.selected").removeClass("selected");
					$(this).addClass("selected");
				});
			}
			$("#autocomplete_box p.selected").each(function () {
				var index = $(this).prevAll("p").size();
				$("#autocomplete_box").scrollTop(index*13);
			});
			LOCK_AUTOCOMPLETE = false;
			return;
		}
		if (e.keyCode == 40) { // DOWN
			if ($("#autocomplete_box p.selected").size() == 0) {
				$("#autocomplete_box p:first").addClass("selected");
			}
			else {
				var p = $("#autocomplete_box p.selected").next("p").each(function () {
					$("#autocomplete_box p.selected").removeClass("selected");
					$(this).addClass("selected");
				});
			}
			$("#autocomplete_box p.selected").each(function () {
				var index = $(this).prevAll("p").size();
				$("#autocomplete_box").scrollTop(index*13);
			});
			LOCK_AUTOCOMPLETE = false;
			return;
		}
		setTimeout(function () {
			var search = $(self).val();
			$.ajax({
				type: "post",
				url: "/doAutocomplete.php",
				data: {'search': search},
				success: function (response) {
					generate_box($(self),response);
					LOCK_AUTOCOMPLETE = false;
				}
			});
		}, 1000);
	});
});
