var pasoActual = 1;
var sUnidades="unidades";
var iNivelUsu = 2;
var bUserLoged = false;
// Datos prohibidos
var sTlds="(ac|ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|info|int|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|travel|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)";
var	sPrefijosAdicionales="900|901|902|905|906|803|805|807|806";
var sPrefijosTelf1="6";
var sPrefijosTelf2="96|98|93|91|95|94";
var sPrefijosTelf3="945|967|950|920|924|971|947|927|956|942|964|956|926|957|981|969|943|972|958|949|959|974|953|941|928|987|973|982|968|948|988|979|986|923|922|921|975|977|978|925|983|980|976";
var sCaracteresNoPermitidos = "(http(s)?|@)";
var	sEndWordLine="([ ]+|$)";
var	sSeparator="(\\(|\\)|\\-|\\.|[ ]|\\s)";
var	sNumLetras="(cero|uno|dos|tres|cuatro|cinco|seis|siete|ocho|nueve|[0-9])";
// Función que comprueba si la variable texto contiene un email
function existeMail(texto) {
	var textoLimpio = limpiarTexto(texto,'mail');
	var sRegExp=new RegExp("[A-Za-z0-9ñÑ ]+@[A-Za-z0-9ñÑ ]+[.][A-Za-zñÑ ]{2,}(\.[A-Za-zñÑ ]{2,})?");
	//Devolvemos true o false en función de si existe un mail o no en el textoLimpio
	if((sRegExp.test(textoLimpio))||(textoLimpio.match(sCaracteresNoPermitidos)))return 1;
	else 
	return 0;
}
// Función que comprueba si la variable texto contiene una URL
function existeURL(texto) {
	var textoLimpio = limpiarTexto(texto,'url');
	var sRegExp01 = new RegExp("([Ww( _)*]{3,}|3w|w3)\.?[A-Za-z0-9ñÑ.-_ ]\.?[A-Za-zñÑ ]{2,}(\.[A-Za-zñÑ ]{2,})?");
	var sRegExp02 = new RegExp("[Ww( _)*]{3,}");
	//Devolvemos true o false en función de si una dirección de mail o no en el textoLimpio
	if((sRegExp01.test(textoLimpio))||(sRegExp02.test(textoLimpio))) return 1;
	else 
	return 0;
}
// Función que comprueba si la variable texto contiene un Telf
function existeTelf(texto) {
	var textoLimpio = limpiarTexto(texto,'telf');
	var sRegExp01=new RegExp("("+sPrefijosTelf2+")[\.]?\-?[0-9]{3}[\.]?\-?[0-9]{2}[\.]?\-?[0-9]{2}");
	var sRegExp02=new RegExp("("+sPrefijosTelf3+"|"+sPrefijosAdicionales+")[\.]?\-?[0-9]{2}[\.]?\-?[0-9]{2}[\.]?\-?[0-9]{2}");
	var sRegExp03=new RegExp("("+sPrefijosTelf1+")[0-9]{2}[\.]?\-?[0-9]{2}[\.]?\-?[0-9]{2}[\.]?\-?[0-9]{2}");	
	//Devolvemos true o false en función de si un teléfono o no en el textoLimpio
	if(sRegExp01.test(textoLimpio) || sRegExp02.test(textoLimpio) || sRegExp03.test(textoLimpio))return 1;
	else 
	return 0;
}
// Función que limpia el texto pasado por parámetro. Limpiando todos los saltos de linea, espacios en blanco,...
function limpiarTexto(texto, tipo) {
	var textoLimpio = texto.toLowerCase();
	textoLimpio = unescape(escape(textoLimpio).replace(/(%0A)|(%20)|(%A0)+/g,""));
	
	if (tipo == 'mail'){
		//Limpiamos todos los caracteres no permitidos en los mails
		textoLimpio = textoLimpio.replace(/[^a-z-_@.]+/g,"");
		textoLimpio = textoLimpio.replace(/\.{2,}/g, ".");
		textoLimpio = textoLimpio.replace(/@{2,}/g, "@");
		textoLimpio = textoLimpio.replace(/(@\.)/g, "@");
		textoLimpio = textoLimpio.replace(/(\.@)/g, "@");
	}
	
	if (tipo == 'url'){
		//Limpiamos todos los caracteres no permitidos en las url's
		textoLimpio = textoLimpio.replace(/[^-\.\/_a-z0-9ñÑ]+/g,".");
		textoLimpio = textoLimpio.replace(/\.{2,}/g, ".");
	}
	
	if (tipo == 'telf'){
		//Limpiamos todos los caracteres no permitidos en los números de telefono
		textoLimpio = textoLimpio.replace(/[^0-9a-z\.\-,\(\)%€/]+/g,"");
		textoLimpio = textoLimpio.replace(/\.{2,}/g, ".");
		textoLimpio = textoLimpio.replace(/\-{2,}/g, "-");
	}
	return (textoLimpio);
}
 /*******************************************************************/
function funcOnLoad(iMercadoSelected,txtSectores){
	try{
		$("#desc_breve").focus();
		if(iMercadoSelected != "" && txtSectores != "") accionSelectMercado(iMercadoSelected,txtSectores);
	}catch(ex){}
}

function getKey(e){
	if(e == null) return null;
	var keynum
	if(window.event) // IE
		keynum = e.keyCode
	else if(e.which) // Netscape/Firefox/Opera
		keynum = e.which
	return keynum;
}
function setSelectionRange(input, selectionStart, selectionEnd){
	if (input.setSelectionRange) {
		input.setSelectionRange(selectionStart, selectionEnd);
	}else if (input.createTextRange) {
		var range = input.createTextRange();
		range.moveStart('character', selectionStart);
		range.moveEnd('character', selectionEnd);
		range.select();
	}
}

function accionSelectMercadoPublicacion(iMercadoSelected,txtSectores){
	if(iMercadoSelected == "999999"){
		document.getElementById("iMercado").value=iMercadoSelected;
		$('#iFamilia, #iSubFamilia').val("");
	}else{
		document.getElementById("iMercado").value=iMercadoSelected.substring(0,2)+"0000";
		if(iMercadoSelected.substring(2,4) != "00" && iMercadoSelected.substring(2,4) != "99") document.getElementById("iFamilia").value=iMercadoSelected.substring(0,4)+"00";
		else if(iMercadoSelected.substring(2,4) == "99") document.getElementById("iFamilia").value=iMercadoSelected;
		else document.getElementById("iFamilia").value="";
		if(iMercadoSelected.substring(4,6) != "00" && iMercadoSelected.substring(2,4) != "99") document.getElementById("iSubFamilia").value=iMercadoSelected;
		else document.getElementById("iSubFamilia").value="";
	}
	document.getElementById("txtSector").innerHTML=txtSectores;
	document.getElementById("sTxtSector").value=txtSectores; // Campo hidden para ir pasando por los pasos del alta
	$("#arbolCategoriasGeneral").hide();
	$('#containerFormP1Product, #btnPublicacion').show()
	document.getElementById("containerPaso1").style.height="400px";
	if(document.getElementById("desc_breve").value != "") document.getElementById("desc_detallada").focus();
	else document.getElementById("desc_breve").focus();
	if(iMercadoSelected.substring(0,2) == "10"){
		document.getElementById("iAnuncio").value="1";
		document.getElementById("lblUniLote").innerHTML="Unidades por lote:";
		$('#Paso2, #divPlazoEntrega, #divNumLotes, #divFichaDatosProductoLotesUnits, #chkBC, #fichaDatosProducto').show();
		$('#divFichaDatosProductoCantidad, #numlotesunitsub1, #numlotesunitsubotra').hide();
		// Muestro la etiqueta de unidades
		document.getElementById("numlotesunit1").style.display="inline";
		sUnidades="unidades";
		document.getElementById("chkBuyCom").disabled=false;
		document.getElementById("msgTitOrigen").innerHTML="¿Desde dónde envías el producto?";
		document.getElementById("commentPrecio1").innerHTML="Indica el precio unitario, no el precio del lote completo.";
		document.getElementById("commentUniLote1").innerHTML="Las unidades por lote no pueden ser negativas, tener puntos, ni comas.";
		document.getElementById("commentReferencia").innerHTML="Indica tu referencia interna del producto. Sólo es para tu uso personal.";
	}else if(iMercadoSelected.substring(0,2) == "80"){
		document.getElementById("Paso2").style.display="none"; // Si es del sector Servicios
		document.getElementById("divPlazoEntrega").style.display="none";
		document.getElementById("iAnuncio").value="2";
		document.getElementById("chkBC").style.display="none"; 
		document.getElementById("chkBuyCom").disabled="disabled";
		document.getElementById("msgTitOrigen").innerHTML="¿Desde dónde se presta el servicio?";
		document.getElementById("commentReferencia").innerHTML="Indica tu referencia interna para este servicio. Sólo es para tu uso personal.";
		document.getElementById("fichaDatosProducto").style.display="none"; // Oculto capa de precio y lotes
	}else if(iMercadoSelected.substring(0,2) == "81"){ // En el caso de ser subproductos
		$('#Paso2, #divPlazoEntrega, #fichaDatosProducto, #divFichaDatosProductoCantidad').show();
		$('#divNumLotes, #divFichaDatosProductoLotesUnits, #chkBC, #numlotesunit1').hide();
		document.getElementById("iAnuncio").value="3";
		document.getElementById("lblUniLote").innerHTML="Cantidad:";
		document.getElementById("chkBuyCom").disabled="disabled";
		document.getElementById("msgTitOrigen").innerHTML="¿Desde dónde envías el producto?";
		document.getElementById("commentPrecio1").innerHTML="Indica el precio unitario en función de la unidad de medida que selecciones en el desplegable.";
		document.getElementById("commentUniLote1").innerHTML="La cantidad no puede ser negativa, tener puntos, ni comas.";
		document.getElementById("commentReferencia").innerHTML="Indica tu referencia interna del producto. Sólo es para tu uso personal.";
		document.getElementById("numlotes").value="0";
		// Y muestro el combo de unidades
		document.getElementById("numlotesunitsub1").style.display="inline";
	}else{
		document.getElementById("iAnuncio").value="1";
		$('#Paso2, #divPlazoEntrega, #divNumLotes, #divFichaDatosProductoLotesUnits, #fichaDatosProducto').show();
		$('#divFichaDatosProductoCantidad, #numlotesunitsub1, #numlotesunitsubotra').hide();
		document.getElementById("lblUniLote").innerHTML="Unidades por lote:";
		// Muestro la etiqueta de unidades
		document.getElementById("numlotesunit1").style.display="inline";
		// Oculto el combo de unidades
		sUnidades="unidades";
		document.getElementById("chkBuyCom").disabled="disabled";
		document.getElementById("msgTitOrigen").innerHTML="¿Desde dónde envías el producto?";
		document.getElementById("commentPrecio1").innerHTML="Indica el precio unitario, no el precio del lote completo.";
		document.getElementById("commentUniLote1").innerHTML="Las unidades por lote no pueden ser negativas, tener puntos, ni comas.";
		document.getElementById("commentReferencia").innerHTML="Indica tu referencia interna del producto. Sólo es para tu uso personal.";
	}
}

function volverSelectMercado(){
	$('#containerFormP1Product, #iFrameFotos, #btnPublicacion').hide();
	document.getElementById("containerPaso1").style.height="525px";
	document.getElementById("arbolCategoriasGeneral").style.display="block";
}

function cambioUnidades(combo){
	if(combo.options[combo.selectedIndex].value == "999")// Otra unidad seleccionada
		document.getElementById("numlotesunitsubotra").style.display="inline";
	else
		document.getElementById("numlotesunitsubotra").style.display="none";
	//document.getElementById("numlotesunitsub2").innerHTML=combo.options[combo.selectedIndex].text;
	document.getElementById("totalUnLote").value=document.getElementById("totalUnLote").value.replace(sUnidades,combo.options[combo.selectedIndex].text);
	sUnidades=combo.options[combo.selectedIndex].text;
}

function textMedida(input){
	//document.getElementById("numlotesunitsub2").innerHTML=input.value;
	sUnidades=input.value;
}

/*Función para controlar el número de caracteres en Mayúsculas introducidos por el usuario, en la cual
  no permite que todo el título esté en mayúsculas y no permite más de 16 caracteres en Mayúsculas.
  Transformando la primera a mayúscula y las siguientes en minúsculas en caso contrario.
  */
function controlMayusculas(textField){
	//Caracteres a controlar
	var letrasMayusculas="ABCDEFGHIYJKLMNÑOPQRSTUVWXYZ";
	//Capturamos el objeto
	var textControl = document.getElementById(textField); 
	var texto = textControl.value;
	//Quitamos todos los espacios en blanco del texto
	var textoSinEspacios = textControl.value.replace(/ /g, "");
	var numMayusculas = 0;
	var longTexto = textoSinEspacios.length;
	//Recorremos el texto en busca de caracteres a controlar
	for(i = 0; i < textoSinEspacios.length; i++){
		if ((letrasMayusculas.indexOf(textoSinEspacios.charAt(i),0)!=-1))	
	  	 	numMayusculas = numMayusculas + 1;
	}
	if ((textField == 'desc_breve') && (longTexto > 1)){
		//Si todo el texto está en Mayúsculas hacemos la transformación de la primera en Mayúscula y las demás en Minúsculas 
		if (numMayusculas == longTexto){
			textControl.value = textControl.value.substring(0,1).toUpperCase()+textControl.value.substring(1).toLowerCase();
		//Si no está todo el texto en Mayúsculas pero superamos el máximo de mayúsculas permitido
		}else{
			if (numMayusculas > 16)
				textControl.value = textControl.value.substring(0,1).toUpperCase()+textControl.value.substring(1).toLowerCase();
			else
				textControl.value = textControl.value.substring(0,1).toUpperCase()+textControl.value.substring(1);
		}
	}else if ((textField == 'desc_detallada') && (longTexto > 1)){
	
		//Si todo el texto está en Mayúsculas hacemos la transformación de la primera en Mayúscula y las demás en Minúsculas 
		if (numMayusculas == longTexto){
			alert('No se puede especificar toda la descripción detallada en Mayúsculas');
			textControl.value = textControl.value.substring(0,1).toUpperCase()+textControl.value.substring(1).toLowerCase();
		//Si no está todo el texto en Mayúsculas pero superamos el máximo de mayúsculas permitido
		}
	}
}

/* 	Función para controlar las descripciones de las ofertas de los productos.
 	Controlando el número caracteres en Mayúsculas introducidos por el usuario,
 	No permitiendo todo el título en mayúsculas y no más de 16 caracteres en Mayúsculas en la des_breve.
 	Transformando la primera a mayúscula y las siguientes en minúsculas en caso contrario.
 	No permitiendo en la desc_detallada introducir más del X% de caracteres en Mayúsculas.
 	*/
function controlDescripciones(textField){
	//Caracteres a controlar
	var letrasMayusculas="ABCDEFGHIYJKLMNÑOPQRSTUVWXYZ";
	//Capturamos el objeto
	var textControl = document.getElementById(textField);
	var texto = textControl.value;
	//Quitamos todos los espacios en blanco
	var textoSinEspacios = texto.replace(/ |&nbsp;|\r|\n/g, "");
	var numMayusculas = 0;
	var longTexto = textoSinEspacios.length;
	//Recorremos el texto en busca de caracteres a controlar
	for(i = 0; i < textoSinEspacios.length; i++){
		if ((letrasMayusculas.indexOf(textoSinEspacios.charAt(i),0)!=-1))
	  	 	numMayusculas = numMayusculas + 1;
	}
	if ((textField == 'desc_breve') && (longTexto > 1)){
		//Si todo el texto está en Mayúsculas hacemos la transformación de la primera en Mayúscula y las demás en Minúsculas 
		if (numMayusculas == longTexto){
			alert('No puede ser el título todo en Mayúsculas');
			textControl.focus();
			return(false);
		//Si no está todo el texto en Mayúsculas pero superamos el máximo de mayúsculas permitido
		}else{
			if (numMayusculas > 16){
				alert('No se puede introducir más de 16 mayúsculas en el título');
				textControl.focus();
				return(false);
			}else
				textControl.value = textControl.value.substring(0,1).toUpperCase()+textControl.value.substring(1);
		}
	}else if ((textField == 'desc_detallada') && (longTexto > 1)){
		var porcentajeMayusculas = (numMayusculas / longTexto);
		//Si todo el texto está en Mayúsculas hacemos la transformación de la primera en Mayúscula y las demás en Minúsculas 
		if (porcentajeMayusculas > 0.2 ){
			textControl.focus();
			return(false);
		}
	}
}

function charSeguidos(textField){
	//Longitud máximo por palabra
	var maxLenPalabra = 40;
	
	var palabras = document.getElementById(textField).value.split(" ");
	//Recorremos por palabra para controlar [maxLenPalabra]
	for(i = 0; i < palabras.length; i++){
		if (palabras[i].length > maxLenPalabra){
			document.getElementById(textField).focus();
			return false;
		}
	}
}

/*Para no mostrar el limitarMayusculas por problemas de maquetación una vez escogido el mercado y
  submercado quedaba el div oculto bajo el botón cambiar.*/
function textCounter(field,counter,maxlimit){
	var longField = field.value.length;        
	if (longField <= maxlimit){
		//Introducimos el número de carácteres restantes en el elemento flotante correspondiente
		document.getElementById(counter).innerHTML = maxlimit - longField + ' car&aacute;cteres disponibles';
	}
}
/* Actualmente no se utiliza esta función */
function limitarMayusculas(field,charValue,bar){
	var iNumMay = (charValue.match(/[A-Z]/g) == null) ? 0 : charValue.match(/[A-Z]/g).length;
	if(iNumMay > 16)
		field.value = field.value.substring(0, field.value.length-1);
	else if(iNumMay > 15)
		showBar(bar);
	else
		hideBar(bar);
}

function isOnlyOne(cantidad){
	if(cantidad != "" && iNivelUsu != 3){
		cantidad=Number(cantidad);
		if (cantidad <= 1){ 
			showBar("unitsBar","SoloStocks es un mercado mayorista. El número de unidades por lote debe ser superior.");
			return true;
		}
	}
	return false;
}

function validarForm(){
	if(document.getElementById("iAnuncio").value == "1" || document.getElementById("iAnuncio").value == "3") return (validarPaso1() && validarPaso2() && validarPaso3());
	else return (validarPaso1() && validarPaso3()); // Servicios
}

function validarPaso1(){
	var bReturn=true;
	$("#tituloBar, #descBar, #refBar").hide();
	$("#desc_breve").val($("#desc_breve").val().replace("\"","''")).css("border-color", "#bbbbbb");
	$("#desc_detallada").css("border-color", "#bbb");
	if($.trim(document.getElementById("desc_breve").value).length == 0){
		$("#desc_breve").css("border-color", "#f00");
		$("#tituloBar").html("Es necesario indicar el título del anuncio.").show();
		bReturn=false;
	}
	if(existeMail($("#desc_breve").val()) || existeURL($("#desc_breve").val()) || existeTelf($("#desc_breve").val())){
		document.getElementById("desc_breve").style.borderColor = "#f00";
		$("#tituloBar").html("El título de la oferta no debe contener datos de contacto").show();
		bReturn=false;
	}
	if($.trim(document.getElementById("desc_detallada").value).length == 0){
		document.getElementById("desc_detallada").style.borderColor = "#f00";
		$("#descBar").html("Es necesario indicar la descripción detallada del anuncio.").show();
		bReturn=false;
	}
	if(existeMail($("#desc_detallada").val()) || existeURL($("#desc_detallada").val()) || existeTelf($("#desc_detallada").val())){
		document.getElementById("desc_detallada").style.borderColor = "#f00";
		$("#descBar").html("La descripción detallada de la oferta no debe contener datos de contacto").show();
		bReturn=false;
	}
	if(controlDescripciones('desc_detallada') == false){
		document.getElementById("desc_detallada").style.borderColor = "#f00";
		$("#descBar").html("Has excedido el número de mayúsculas permitido.").show();
		bReturn=false;
	}
	if(controlDescripciones('desc_breve') == false){
		document.getElementById("desc_breve").style.borderColor = "#f00";
		bReturn=false;
	}
	if(charSeguidos('desc_detallada') == false){
		document.getElementById("desc_detallada").style.borderColor = "#f00";
		$("#descBar").html("Has excedido el máximo de carácteres seguidos").show();
		bReturn=false;
	}
	if(charSeguidos('desc_breve') == false){
		document.getElementById("desc_breve").style.borderColor = "#f00";
		$("#tituloBar").html("Excedido el máximo de carácteres seguidos").show();
		bReturn=false;
	}
	if(document.getElementById("desc_breve").value.length > 128){
		document.getElementById("desc_breve").style.borderColor = "#f00";
		$("#tituloBar").html("El título de la oferta no se deben sobrepasar los 80 caracteres.").show();
		bReturn=false;
	}
	if(document.getElementById("desc_detallada").value.length > 3300){
		document.getElementById("desc_detallada").style.borderColor = "#f00";
		$("#descBar").html("La descripción detallada de la oferta es demasiado larga. No se deben sobrepasar los 3300 caracteres.").show();
		bReturn=false;
	}
	if(document.getElementById("referencia").value.length > 64){
		document.getElementById("referencia").style.borderColor = "#f00";
		$("#refBar").html("La referencia de la oferta no debe sobrepasar los 64 caracteres.").show();
		bReturn=false;
	}
	if(document.getElementById("iMercado").value.length == 0 && document.getElementById("iFamilia").value.length == 0 && document.getElementById("iSubFamilia").value.length == 0){
		$("#sectorBar").html("Es necesario indicar el sector al que pertenece el anuncio.").show();
		bReturn=false;	
	}
	return bReturn;
}

function validarPaso2(){
	var bReturn=true;
	hideBar("precioBar");
	hideBar("unitsBar");
	hideBar("lotsBar");
	//
	document.getElementById("uniprecio").style.borderColor = "#bbbbbb";
	document.getElementById("unilote").style.borderColor = "#bbbbbb";
	document.getElementById("numlotes").style.borderColor = "#bbbbbb";
	document.getElementById("medida").style.borderColor = "#bbbbbb";
	document.getElementById("otramedida").style.borderColor = "#bbbbbb";
	//
	if(document.getElementById("uniprecio").value.length == 0){
		document.getElementById("precioBar").innerHTML="Es necesario indicar el precio del producto.";
		document.getElementById("uniprecio").style.borderColor = "#ff0000";
		showBar("precioBar");
		bReturn=false;
	}else if(!validPrice(document.getElementById("uniprecio"),null)) bReturn=false;
	if(document.getElementById("unilote").value.length == 0){
		document.getElementById("unitsBar").innerHTML="Es necesario indicar las unidades por lote del producto.";
		document.getElementById("unilote").style.borderColor = "#ff0000";
		showBar("unitsBar");
		bReturn=false;
	}else if(!validUnits(document.getElementById("unilote"),null)) bReturn=false;
	if(document.getElementById("numlotes").value.length == 0){
		document.getElementById("lotsBar").innerHTML="Es necesario indicar el número de lotes del producto.";
		document.getElementById("numlotes").style.borderColor = "#ff0000";
		showBar("lotsBar");
		bReturn=false;
	}else if(!validUnitDisp(document.getElementById("numlotes"),null)) bReturn=false;
	if(bReturn && isOnlyOne(document.getElementById("unilote").value)){
		bReturn=false;
	}
	if(document.getElementById("iAnuncio").value == 3 && document.getElementById("medida")[document.getElementById("medida").selectedIndex].value == 0){// Si es subproducto compruebo si ha seleccionado unidad
		document.getElementById("unitsBar").innerHTML="Es necesario seleccionar una unidad.";
		document.getElementById("medida").style.borderColor = "#ff0000";
		showBar("unitsBar");
		bReturn=false;
	}
	if(document.getElementById("iAnuncio").value == 3 && document.getElementById("medida")[document.getElementById("medida").selectedIndex].value == 999 && document.getElementById("otramedida").value == ""){// Si es subproducto y ha seleccionado Otra compruebo que haya escrito algo en otra unidad
		document.getElementById("unitsBar").innerHTML="Es necesario seleccionar una unidad de medida.";
		document.getElementById("otramedida").style.borderColor = "#ff0000";
		showBar("unitsBar");
		bReturn=false;
	}
	return bReturn;
}

function validarPaso3(){
	var bReturn=true;
	hideBar("entregaBar");
	hideBar("paisBar");
	hideBar("provinciaBar");
	hideBar("localidadBar");
	//
	document.getElementById("localidad").style.borderColor = "#bbbbbb";
	//
	if(document.getElementById("iMercado").value.substring(0,2) != "80" && document.getElementById("pla_entrega")[document.getElementById("pla_entrega").selectedIndex].value == "0"){
		document.getElementById("entregaBar").innerHTML="Es necesario indicar el plazo de entrega del producto.";
		showBar("entregaBar");
		bReturn=false;
	}
	if(document.getElementById("CodigoPais")[document.getElementById("CodigoPais").selectedIndex].value == "0"){
		if(document.getElementById("iAnuncio").value == "2") document.getElementById("paisBar").innerHTML="Es necesario indicar el país desde dónde se presta el servicio.";
		else document.getElementById("paisBar").innerHTML="Es necesario indicar el país desde dónde envías el producto.";
		showBar("paisBar");
		bReturn=false;
	}
	if(document.getElementById("CodigoProvincia")[document.getElementById("CodigoProvincia").selectedIndex].value == "0"){
		if(document.getElementById("iAnuncio").value == "2") document.getElementById("provinciaBar").innerHTML="Es necesario indicar la provincia desde dónde se presta el servicio.";
		else document.getElementById("provinciaBar").innerHTML="Es necesario indicar la provincia desde dónde envías el producto.";
		showBar("provinciaBar");
		bReturn=false;
	}
	if(document.getElementById("localidad").value.length == 0){
		if(document.getElementById("iAnuncio").value == "2") document.getElementById("localidadBar").innerHTML="Es necesario indicar la localidad desde dónde se presta el servicio.";
		else document.getElementById("localidadBar").innerHTML="Es necesario indicar la localidad desde dónde envias el producto.";
		document.getElementById("localidad").style.borderColor = "#ff0000";
		showBar("localidadBar");
		bReturn=false;
	}
	
	if(existeMail(document.getElementById("localidad").value) || existeURL(document.getElementById("localidad").value) || existeTelf(document.getElementById("localidad").value)){
		document.getElementById("localidad").style.borderColor = "#ff0000";
		document.getElementById("localidadBar").innerHTML="La localidad de la oferta no debe contener datos de contacto";
		showBar("localidadBar");
		bReturn=false;
	}
	
	
	var sPhoto1=document.getElementById("pathPhoto1").value;
	var sPhoto2=document.getElementById("pathPhoto2").value;
	if((sPhoto1.length != 0 && sPhoto1 == "-1") || (sPhoto2.length != 0 && sPhoto2 == "-1")){
		document.getElementById("imgBar").innerHTML="Por favor, espera a que las imágenes sean adjuntadas a tu anuncio.";
		showBar("imgBar");
		bReturn=false;
	}
	return bReturn;
}

function validPrice(field,e){
	var keynum;
	keynum=getKey(e);
	if(keynum != 9){
		var price = new String(field.value);
		price=price.replace(/\./g,",");
		field.value=new String(field.value).replace(".",",");
		var iNumComas=0;
		var aParts=price.split(",");
		if(price.indexOf(",") != -1){// Si hay alguna coma en el precio
			iNumComas = aParts.length - 1;
			if(iNumComas == 1 && aParts[1] == ""){ // Si acabo de escribir una coma y no existe ninguna otra
				field.value=field.value.replace(",",",00");
				setSelectionRange(field,field.value.length-2, field.value.length);
			}else if(iNumComas > 1 || aParts[1].length > 2){// Si he escrito una coma y no es la primera o el número de decimales es superior a 2
				field.value=field.value.substring(0,field.value.length-1);
			}
		}
		price = new String(field.value);
		document.getElementById("uniprecio").style.borderColor = "#bbbbbb";
		if(price == "undefined"){
			document.getElementById("precioBar").innerHTML="Es necesario indicar el precio del producto.";
			document.getElementById("uniprecio").style.borderColor = "#ff0000";
			showBar("precioBar");
			return false;
		}else if(isNaN(price.replace(/,/g,"."))){
			showBar("precioBar");
			document.getElementById("precioBar").innerHTML="El precio debe ser un valor numérico.";
			document.getElementById("uniprecio").style.borderColor = "#ff0000";
			return false;
		}else if(price.indexOf("-") != -1){
			showBar("precioBar");
			document.getElementById("precioBar").innerHTML="El precio debe ser un valor positivo.";
			document.getElementById("uniprecio").style.borderColor = "#ff0000";
			return false;
		}else if(Number(price.replace(/,/g,".")) == 0){
			showBar("precioBar");
			document.getElementById("precioBar").innerHTML="El precio no puede ser \"cero\".";
			document.getElementById("uniprecio").style.borderColor = "#ff0000";
			return false;
		}else if(price.length > 20){
			showBar("precioBar");
			document.getElementById("precioBar").innerHTML="Has superado el valor máximo permitido para el precio.";
			document.getElementById("uniprecio").style.borderColor = "#ff0000";
			return false;
		}else{
			hideBar("precioBar");
			document.getElementById("uniprecio").style.borderColor = "#bbbbbb";
			return true;
		}
	}
}

function validUnits(field,e){
	var keynum;
	keynum=getKey(e);
	if(keynum != 9){
		var units = new String(field.value);
		units=units.replace(/\./g,",");
		var regLetra =  new RegExp("[a-zA-Z]");
		document.getElementById("unilote").style.borderColor = "#bbbbbb";
		if(units == "undefined"){
			if(document.getElementById("iAnuncio").value == "3") $('#unitsBar').html("Es necesario indicar la cantidad del producto.").show();
			else $('#unitsBar').html("Es necesario indicar las unidades por lote del producto.").show();
			document.getElementById("unilote").style.borderColor = "#ff0000";
			return false;
		}else if(units.indexOf(",") != -1){// Si hay alguna coma en la cantidad mínima
			if(document.getElementById("iAnuncio").value == "3") $('#unitsBar').html("La cantidad no debe incluir decimales.").show();	
			else $('#unitsBar').html("Las unidades por lote no deben incluir decimales.").show();	
			document.getElementById("unilote").style.borderColor = "#ff0000";
			document.getElementById("totalUnLote").value="-";
			return false;
		}else if(isNaN(units)){
			if(document.getElementById("iAnuncio").value == "3") $('#unitsBar').html("La cantidad debe ser numérica.").show();
			else $('#unitsBar').html("Las unidades por lote deben ser numéricas.").show();
			document.getElementById("unilote").style.borderColor = "#ff0000";
			document.getElementById("totalUnLote").value="-";
			return false;
		}else if(units.indexOf("-") != -1){
			if(document.getElementById("iAnuncio").value == "3") $('#unitsBar').html("La cantidad no puede ser negativa.").show();
			else $('#unitsBar').html("Las unidades por lote deben ser positivas.").show();
			document.getElementById("unilote").style.borderColor = "#ff0000";
			document.getElementById("totalUnLote").value="-";
			return false;
		}else if(units == 0){
			if(document.getElementById("iAnuncio").value == "3") $('#unitsBar').html("La cantidad no puede ser \"cero\".").show();
			else $('#unitsBar').html("Las unidades por lote no pueden ser \"cero\".").show();
			document.getElementById("unilote").style.borderColor = "#ff0000";
			document.getElementById("totalUnLote").value="-";
			return false;
		}else if(units.length > 20 && document.getElementById("iAnuncio").value != 3){// No subproductos
			$('#unitsBar').html("Has superado el valor máximo permitido para el número de unidades por lote.").show();
			document.getElementById("unilote").style.borderColor = "#ff0000";
			document.getElementById("totalUnLote").value="-";
			return false;
		}else if(units.length > 20 && document.getElementById("iAnuncio").value == 3){// Subproductos
			$('#unitsBar').html("Has superado el valor máximo permitido para la Cantidad. Puedes seleccionar otra unidad de medida.").show();
			document.getElementById("unilote").style.borderColor = "#ff0000";
			document.getElementById("totalUnLote").value="-";
			return false;
		}else{
			hideBar("unitsBar");
			if(isNaN(Number(document.getElementById("numlotes").value)) && document.getElementById("iAnuncio").value != 3) iTotalLote="-";
			else if(document.getElementById("iAnuncio").value == 3) iTotalLote=Number(document.getElementById("unilote").value);
			else iTotalLote=Number(document.getElementById("unilote").value)*Number(document.getElementById("numlotes").value);
			document.getElementById("totalUnLote").value=iTotalLote+" "+sUnidades;
			document.getElementById("spanFichaDatosProductoCantidadUnit").innerHTML=iTotalLote+" "+sUnidades;
			return true;
		}
	}
}

function validUnitDisp(field,e){
	var keynum;
	keynum=getKey(e);
	if(keynum != 9){
		if(document.getElementById("iAnuncio").value != 3){// Se trata de un producto o subproducto
			var uniLote = Number(document.getElementById("unilote").value);
			//var numLote = Number(field.value);
			var numLote = new String(field.value).replace(/\./g,",");
			document.getElementById("numlotes").style.borderColor = "#bbbbbb";
			if(numLote == "undefined"){
				$('#lotsBar').html("Es necesario indicar el número de lotes del producto.").show();
				document.getElementById("numlotes").style.borderColor = "#ff0000";
				bReturn=false;
			}else if(numLote.indexOf(",") != -1){// Si hay alguna coma en el número de lotes
				$('#lotsBar').html("El número de lotes no debe incluir decimales.").show();	
				document.getElementById("numlotes").style.borderColor = "#ff0000";
				document.getElementById("totalUnLote").value="-";
				return false;
			}else if(isNaN(uniLote)){
				document.getElementById("totalUnLote").value="-";
				return false;
			}else if(isNaN(numLote)){
				$('#lotsBar').html("El número de lotes debe ser numérico.").show();	
				document.getElementById("numlotes").style.borderColor = "#ff0000";		
				document.getElementById("totalUnLote").value="-";
				return false;
			}else if(numLote.indexOf("-") != -1){
				$('#lotsBar').html("El número de lotes debe ser positivo.").show();
				document.getElementById("numlotes").style.borderColor = "#ff0000";
				document.getElementById("totalUnLote").value="-";
				return false;
			}else if(numLote == 0){
				$('#lotsBar').html("El número de lotes no puede ser \"cero\".").show();
				document.getElementById("numlotes").style.borderColor = "#ff0000";
				document.getElementById("totalUnLote").value="-";
				return false;
			}else if(numLote.length > 20){
				$('#lotsBar').html("Has superado el valor máximo permitido para el número de lotes.").show();
				document.getElementById("numlotes").style.borderColor = "#ff0000";
				document.getElementById("totalUnLote").value="-";
				return false;
			}else{
				hideBar("lotsBar");
				iTotalLote=Number(document.getElementById("unilote").value)*Number(document.getElementById("numlotes").value);
				document.getElementById("totalUnLote").value=iTotalLote+" "+sUnidades;
				return true;
			}
		}else{ // Se trata de un subproducto
			document.getElementById("numlotes").value="0";
			return true;
		}
	}
}

function validPlazoEntrega(field){
	var bReturn=true;
	var iPlazoEntrega=field[field.selectedIndex].value;
	if(document.getElementById("iMercado").value.substring(0,2) != "80" && iPlazoEntrega == "0"){
		document.getElementById("entregaBar").innerHTML="Es necesario indicar el plazo de entrega del producto.";
		showBar("entregaBar");
		bReturn=false;
	}else{
		hideBar("entregaBar");
	}
	return bReturn;
}

function validPais(field){
	var bReturn=true;
	var iPais=field[field.selectedIndex].value;
	if(iPais == "0"){
		if(document.getElementById("iAnuncio").value == "2") document.getElementById("paisBar").innerHTML="Es necesario indicar el país desde dónde se presta el servicio.";
		else document.getElementById("paisBar").innerHTML="Es necesario indicar el país desde dónde envías el producto.";
		showBar("paisBar");
		bReturn=false;
	}else{
		hideBar("paisBar");
	}
	return bReturn;
}

function validProvincia(field){
	var bReturn=true;
	var iProvincia=field[field.selectedIndex].value;
	if(iProvincia == "0"){
		if(document.getElementById("iAnuncio").value == "2") document.getElementById("provinciaBar").innerHTML="Es necesario indicar la provincia desde dónde se presta el servicio.";
		else document.getElementById("provinciaBar").innerHTML="Es necesario indicar la provincia desde dónde envías el producto.";
		showBar("provinciaBar");
		bReturn=false;
	}else{
		hideBar("provinciaBar");
	}
	return bReturn;
}

function validLocalidad(field,e){
	var bReturn=true;
	var keynum;
	keynum=getKey(e);
	if(keynum != 9){
		var sLocalidad = document.getElementById("localidad").value;
		if(sLocalidad.length == 0){
		if(document.getElementById("iAnuncio").value == "2") document.getElementById("localidadBar").innerHTML="Es necesario indicar la localidad desde dónde se presta el servicio.";
		else document.getElementById("localidadBar").innerHTML="Es necesario indicar la localidad desde dónde envias el producto.";
			document.getElementById("localidad").style.borderColor = "#ff0000";
			showBar("localidadBar");
			bReturn=false;
		}else{
			hideBar("localidadBar");
		}
	}
	return bReturn;
}

function setcolor(obj,percentage,prop) {
	if(percentage == null) percentage=100;
	obj.style[prop] = "rgb("+Math.round((90/100)*255)+","+Math.round((percentage/100)*255)+","+Math.round((percentage/100)*255)+")";
}

function showBar(barName,txtMessage) {
	if(txtMessage != null) document.getElementById(barName).innerHTML = txtMessage;
	document.getElementById(barName).style.display = "block";
}
function hideBar(barName) {
	document.getElementById(barName).style.display = "none";
}
function focusField(fieldName) {
	document.getElementById(fieldName).style.background = "#FFFFDD";
	if(fieldName == "desc_detallada"){
		if(document.getElementById("iAnuncio").value == "2") document.getElementById("descBar").innerHTML="Si incluyes tus datos en la descripción del servicio o utilizas mayúsculas exclusivamente, tu anuncio <strong>será eliminada sin previo aviso.</strong>";
		else document.getElementById("descBar").innerHTML="No incluyas datos de contacto en la descripción ni utilices mayúsculas si no es estrictamente necesario.";
		showBar("descBar");
	}
}
function blurField(fieldName) {
	document.getElementById(fieldName).style.background = "";
	document.getElementById(fieldName).style.borderColor = "#bbbbbb";
	// Las primeras ramas contendrá cuando pierde el foco y el contenido es Ok
	if(fieldName == "desc_detallada" && $.trim(document.getElementById(fieldName).value) != "")
		$('#descBar').hide();
	else if(fieldName == "desc_breve" && $.trim(document.getElementById(fieldName).value).length == 0){
		$('#tituloBar').html("Es necesario indicar el título del anuncio.").show();
		$('#'+fieldName).css('border-color', '#f00');
	}else if(fieldName == "desc_detallada" && $.trim(document.getElementById(fieldName).value).length == 0){
		$('#descBar').html("Es necesario indicar la descripción detallada del anuncio.").show();
		$('#'+fieldName).css('border-color', '#f00');
	}else if(fieldName == "desc_detallada" && document.getElementById(fieldName).value.length > 3300){
		$('#descBar').html("La descripción detallada de la oferta es demasiado larga. No se deben sobrepasar los 3300 caracteres.").show();
		$('#'+fieldName).css('border-color', '#f00');
	}else if(fieldName == "uniprecio")
		validPrice(document.getElementById(fieldName),null);
	else if(fieldName == "unilote" && isOnlyOne(document.getElementById("unilote").value))
		$('#unitsBar').show;
	else if(fieldName == "unilote")
		validUnits(document.getElementById(fieldName),null);
	else if(fieldName == "numlotes")
		validUnitDisp(document.getElementById(fieldName),null);
	else if(fieldName == "pla_entrega")
		validPlazoEntrega(document.getElementById(fieldName));
	else if(fieldName == "CodigoPais")
		validPais(document.getElementById(fieldName));
	else if(fieldName == "CodigoProvincia")
		validProvincia(document.getElementById(fieldName));
	else if(fieldName == "localidad")
		validLocalidad(document.getElementById(fieldName),null);
}
//-----
function showDIV(divName) {
	document.getElementById(divName).style.display = "block";
}
function hideDIV(divName) {
	document.getElementById(divName).style.display = "none";
}
function showHideDIV(divName) {	
	if (document.getElementById(divName).style.display == "block"){
		document.getElementById(divName).style.display = "none";
	}else if (document.getElementById(divName).style.display == "none"){
		document.getElementById(divName).style.display = "block";
	} 
}
function proximoPaso () {
	switch (pasoActual){
		case 1:
			if(validarPaso1()){
				$('#tituloBar, #descBar, #containerPaso1').hide();
				$('#desc_breve, #desc_detallada').css('border-color', '#bbb')
				document.getElementById("imgPaso1").src = "http://imagenesweb.solostocks.com/paso1off.gif";
				if(document.getElementById("iMercado").value.substring(0,2) == "80"){// Servicios
					pasoActual+=2;
					document.getElementById("imgPaso3").src = "http://imagenesweb.solostocks.com/paso3on.gif";
					showDIV("containerPaso3");
				}else{
					pasoActual++;
					document.getElementById("imgPaso2").src = "http://imagenesweb.solostocks.com/paso2on.gif";
					showDIV("containerPaso2");
				}
				document.getElementById("btnAnterior").src = "http://imagenesweb2.solostocks.com/btnAnteriorOn.gif";
				document.getElementById('botonPasoAnterior').style.display="block";
				document.getElementById("uniprecio").focus();
			}
			break;
		case 2:
			if(validarPaso2()){
				$('#precioBar, #unitsBar, #lotsBar, #containerPaso2').hide();
				document.getElementById('imgPaso2').src = "http://imagenesweb.solostocks.com/paso2off.gif";
				pasoActual++;
				document.getElementById('imgPaso3').src = "http://imagenesweb.solostocks.com/paso3on.gif";
				$('#containerPaso3, #botonPasoAnterior').show();
				document.getElementById("pla_entrega").focus();
			}
			break;
		case 3:
			if(validarPaso3()){
				$('#entregaBar, #paisBar, #provinciaBar, #localidadBar, #containerPaso3, #botonAgregarFotos, #iFrameFotos').hide();
				document.getElementById('imgPaso3').src = "http://imagenesweb.solostocks.com/paso3off.gif";
				pasoActual++;
				document.getElementById('imgPaso4').src = "http://imagenesweb.solostocks.com/paso4on.gif";
				$('#containerPaso4, #botonPasoAnterior').show();
				actualizarVistaPrevia();
				if(bUserLoged) document.getElementById('btnSiguiente').src = "http://imagenesweb2.solostocks.com/btnPublicarOferta.gif";
				setImgOferta();
			}
			break;
		case 4:
			document.getElementById("formNuevaOf").submit();
			break;
		case 5:
			break;
		default:;
	}
}
function anteriorPaso () {
	cerrarImgZoom();
	switch (pasoActual){
		case 1:
			break
		case 2:
			$('#containerPaso2, #botonPasoAnterior').hide();
			document.getElementById('imgPaso2').src = "http://imagenesweb.solostocks.com/paso2off.gif";
			pasoActual--;
			document.getElementById('imgPaso1').src = "http://imagenesweb.solostocks.com/paso1on.gif";
			showDIV('containerPaso1');
			document.getElementById("desc_breve").focus();
			break;
		case 3:
			hideDIV('containerPaso3');
			document.getElementById('imgPaso3').src = "http://imagenesweb.solostocks.com/paso3off.gif";
			if(document.getElementById("iMercado").value.substring(0,2) == "80"){// Servicios
				pasoActual-=2;
				document.getElementById("imgPaso1").src = "http://imagenesweb.solostocks.com/paso1on.gif";
				showDIV("containerPaso1");
			}else{
				pasoActual--;
				document.getElementById("imgPaso2").src = "http://imagenesweb.solostocks.com/paso2on.gif";
				showDIV("containerPaso2");
			}
			document.getElementById('botonPasoAnterior').style.display="block";
			document.getElementById("uniprecio").focus();
			break
		case 4:
			hideDIV('containerPaso4');
			document.getElementById('imgPaso4').src = "http://imagenesweb.solostocks.com/paso4off.gif";
			pasoActual--;
			document.getElementById('imgPaso3').src = "http://imagenesweb.solostocks.com/paso3on.gif";
			document.getElementById('btnSiguiente').src = "http://imagenesweb2.solostocks.com/btnSiguienteOn.gif";
			$('#containerPaso3, #iFrameFotos, #botonPasoAnterior, #botonAgregarFotos').show()
			document.getElementById("pla_entrega").focus();
			break
		case 5:
			hideDIV('containerPaso5');
			pasoActual--;
			showDIV('containerPaso4');
			document.getElementById('btnSiguiente').src = "http://imagenesweb2.solostocks.com/btnSiguienteOn.gif";
			break
		default:;
	}
}
function actualizarVistaPrevia(){
	document.getElementById("fichaTituloProducto").innerHTML = document.getElementById("desc_breve").value;
	sPrecio=new String(document.getElementById("uniprecio").value);
	if(sPrecio.indexOf(",") == -1) sPrecio+=",00";
	sPrecioFinal=sPrecio.substring(sPrecio.length-3,sPrecio.length);
	// Salto los decimales
	z=0;
	for(i=sPrecio.length-4;i>=0;i--){
		sPrecioFinal=sPrecio.charAt(i)+sPrecioFinal;
		if(++z % 3 == 0) sPrecioFinal="."+sPrecioFinal;
	}
	// Si en la última vuelta puse un punto lo elimino
	if(z % 3 == 0) sPrecioFinal=sPrecioFinal.substring(1,sPrecioFinal.length);
	if(document.getElementById("iAnuncio").value == "1") {	// Producto
		document.getElementById("divFichaDatosProductoCantidad").style.display="none";
		$('#divFichaDatosProductoLotesUnits, #fichaVentaCondicionesProducto').show();
		document.getElementById("spanFichaDatosProductoUnits").innerHTML = document.getElementById("unilote").value + " unidades / lote";
		document.getElementById("spanFichaDatosProductoLotes").innerHTML = document.getElementById("numlotes").value;
		document.getElementById("spanFichaDatosProductoPrecio").innerHTML = sPrecioFinal + " &euro; / unidad";
	}else if(document.getElementById("iAnuncio").value == "3") {	// Subproducto
		$('#divFichaDatosProductoCantidad, #fichaVentaCondicionesProducto').show();
		document.getElementById("divFichaDatosProductoLotesUnits").style.display="none";
		document.getElementById("spanFichaDatosProductoPrecio").innerHTML = sPrecioFinal + " &euro;"
	}else	// Servicio
		$('#divFichaDatosProductoLotesUnits, #fichaVentaCondicionesProducto').hide();
	
	//Substitución de caracteres de cambios de línea y de más de 1 espacio en blanco, para que se muestre bien en el proceso de publicación.
	var inputDetalle = escape($("#desc_detallada").val());	
	inputDetalle = inputDetalle.replace(/(%0A)/g,"<br />");
	inputDetalle = inputDetalle.replace(/(%20){2}/g,"&nbsp;&nbsp;");
	$("#pFichaDescripcionProducto").html(unescape(inputDetalle));
	
	document.getElementById("spanFichaVentaCondicionesProductoEntrega").innerHTML = document.getElementById("pla_entrega").options[document.getElementById("pla_entrega").selectedIndex].text;
	// Elimino los comentarios de las formas de pago para la preview
	sFormaPago=new String(document.getElementById("formaPagoInfo").innerHTML);
	sFormaPago=sFormaPago.replace(document.getElementById("formaPagoComment").innerHTML,"");
	if(document.getElementById("formaPagoInfo") != null) document.getElementById("spanFichaVentaCondicionesProductoPago").innerHTML = sFormaPago;
	else document.getElementById("spanFichaVentaCondicionesProductoPago").innerHTML = "Información no disponible";
	document.getElementById("spanFichaVentaCondicionesProductoOrigen").innerHTML = document.getElementById("localidad").value+ " - "+document.getElementById("CodigoProvincia").options[document.getElementById("CodigoProvincia").selectedIndex].text+" - "+document.getElementById("CodigoPais").options[document.getElementById("CodigoPais").selectedIndex].text;
}
function saltarAlPaso(cualPaso) {
	cerrarImgZoom();
	var bSaltar=true;
	if(cualPaso == 2 && !validarPaso1()) bSaltar=false;
	if(cualPaso == 3 && (!validarPaso1() || !validarPaso2())){
		if(pasoActual == 1 && validarPaso1()){
			hideDIV('containerPaso1');
			document.getElementById('imgPaso1').src = "http://imagenesweb.solostocks.com/paso1off.gif";
			pasoActual=2;
			showDIV('containerPaso2');
			document.getElementById('imgPaso2').src = "http://imagenesweb.solostocks.com/paso2on.gif";
			document.getElementById('btnAnterior').src = "http://imagenesweb2.solostocks.com/btnAnteriorOn.gif";
			document.getElementById('btnSiguiente').src = "http://imagenesweb2.solostocks.com/btnSiguienteOn.gif";			
		}
		bSaltar=false;
	}
	if(cualPaso == 4 && (!validarPaso1() || !validarPaso2() || !validarPaso3())) bSaltar=false;
	if(bSaltar) {
		// Oculto todas las barras de aviso
		$("#tituloBar, #descBar, #precioBar, #unitsBar, #lotsBar, #entregaBar, #paisBar, #provinciaBar, #localidadBar, #containerPaso1, #containerPaso2, #containerPaso3, #containerPaso4, #botonPasoSiguiente, #botonPasoAnterior, #iFrameFotos").hide();
		document.getElementById('imgPaso1').src = "http://imagenesweb.solostocks.com/paso1off.gif";
		document.getElementById('imgPaso2').src = "http://imagenesweb.solostocks.com/paso2off.gif";
		document.getElementById('imgPaso3').src = "http://imagenesweb.solostocks.com/paso3off.gif";
		document.getElementById('imgPaso4').src = "http://imagenesweb.solostocks.com/paso4off.gif";
		switch (cualPaso){
			case 1:
				pasoActual=1;
				document.getElementById('imgPaso1').src = "http://imagenesweb.solostocks.com/paso1on.gif";
				document.getElementById('btnAnterior').src = "http://imagenesweb2.solostocks.com/btnAnteriorOff.gif";
				$('#botonAgregarFotos, #containerPaso1, #botonPasoSiguiente').show();
				$('#botonPasoAnterior').hide();
				document.getElementById('btnSiguiente').src = "http://imagenesweb2.solostocks.com/btnSiguienteOn.gif";
				document.getElementById("desc_breve").focus();
				break
			case 2:
				pasoActual=2;
				document.getElementById('imgPaso2').src = "http://imagenesweb.solostocks.com/paso2on.gif";
				document.getElementById('btnAnterior').src = "http://imagenesweb2.solostocks.com/btnAnteriorOn.gif";
				$('#botonAgregarFotos, #botonPasoAnterior, #containerPaso2, #botonPasoSiguiente').show();
				document.getElementById('btnSiguiente').src = "http://imagenesweb2.solostocks.com/btnSiguienteOn.gif";
				document.getElementById("uniprecio").focus();
				break
			case 3:
				pasoActual=3;
				document.getElementById('imgPaso3').src = "http://imagenesweb.solostocks.com/paso3on.gif";
				document.getElementById('btnAnterior').src = "http://imagenesweb2.solostocks.com/btnAnteriorOn.gif";
				$('#botonAgregarFotos, #botonPasoAnterior, #containerPaso3, #botonPasoSiguiente').show();
				document.getElementById('btnSiguiente').src = "http://imagenesweb2.solostocks.com/btnSiguienteOn.gif";
				document.getElementById("pla_entrega").focus();
				break
			case 4:
				pasoActual=4;
				$('#containerPaso4, #botonPasoAnterior').show();
				$('#iFrameFotos, #botonAgregarFotos').hide();
				document.getElementById('imgPaso4').src = "http://imagenesweb.solostocks.com/paso4on.gif";
				document.getElementById('btnAnterior').src = "http://imagenesweb2.solostocks.com/btnAnteriorOn.gif";
				if(bUserLoged) document.getElementById('btnSiguiente').src = "http://imagenesweb2.solostocks.com/btnPublicarOferta.gif";
				actualizarVistaPrevia();
				setImgOferta();
				break
			default:;
		}
	}
}

var move = false;
var mouse = {x: 0, y: 0};
var dif = {x: 0, y: 0};
document.onmousemove = function(e) {
      if(!e) e = window.event;
      mouse.x = e.clientX;
      mouse.y = e.clientY;
      if (move) {
	  		$('#fotoZoom').css({
				top: mouse.y - dif.y + 'px',
				left: mouse.x - dif.x + 'px',
				margin: '0'
			});
      }
}
 
function mouseDown(e) {
      if (typeof document.body.onselectstart!="undefined") document.body.onselectstart=function(){ return false; } //IE route
      else document.onmousedown = function(){ return false; }
      move = true;
      el = document.getElementById('fotoZoom');
      var ini = {x: el.offsetLeft, y: el.offsetTop};
      while(el = el.offsetParent){
            ini.x += el.offsetLeft;
            ini.y += el.offsetTop;
      }
      dif = {x: mouse.x - ini.x, y: mouse.y - ini.y};
}
 
function dragable() {
      document.getElementById('fotoZoom')['onmouseover'] = function() { document.getElementById('fotoZoom').style.cursor = "move"; }   
      document.getElementById('fotoZoom')['onmousedown'] = function(e) {
      	mouseDown(e);
      }
      document.getElementById('fotoZoom')['onmouseout'] = function() {
      	move = false;
      	if (typeof document.body.onselectstart!="undefined") document.body.onselectstart=function(){ return true; } //IE route
      	else document.onmousedown = function(){ return true; }
      }
      document.getElementById('fotoZoom')['onmouseup'] = function() {
      	move = false;
      	if (typeof document.body.onselectstart!="undefined") document.body.onselectstart=function(){ return true; } //IE route
      	else document.onmousedown = function(){ return true; }
      }     
}

function cerrarImgZoom() {
	document.getElementById('barraFotoZoom').style.width = "100%";
	$('#fotoZoom').css({height: "100px", 'margin-top': "-50px", 'margin-left': "-100px", width: "200px"}).hide();
    $("#capaImgZoom").css({width: '50px', height: '40px', background: 'transparent'}).hide();
    document.getElementById('imgZoom').style.visibility = "visible";
}

function cargaImgZoom(url, maxTam){
	winWidth = (document.all) ? document.documentElement.clientWidth : window.innerWidth;
	winHeight = (document.all) ? document.documentElement.clientHeight : window.innerHeight;
	$("fotoZoom").css({top: winHeight / 2 + 'px', left: winWidth / 2 + 'px'}).show();
	var aux = new Image();
	obj = document.getElementById('imgZoom');
	aux.onload = function() {
		w = aux.width;
		h = aux.height;
		if (winWidth <= w)
		      $("fotoZoom").css({left: '0px', 'margin-left': '0px'});
		else
		      $("fotoZoom").css('margin-left', ((w+16)/2-8)*(-1)+'px');
		
		if (winHeight <= h)
		      $("fotoZoom").css({top: '0px', 'margin-top': '0px'});
		else
		      $("fotoZoom").css('margin-top', ((h+34)/2-8)*(-1)+'px');;
		$("#fotoZoom").css({width: w+16+'px', height: h+34+'px'});
		document.getElementById("barraFotoZoom").style.width = w+16+'px';
		$("#capaImgZoom").css({width: w+'px', height: h+'px', background: "url("+aux.src+")"}).show();
		obj.style.visibility = 'hidden';
	}
	aux.src = url;
}

function setImgOferta() {
	$('#imgFichaDatos').css({
		"margin-top": ($('#imgFichaDatos').height()/2)*(-1)+'px',
		"margin-left": ($('#imgFichaDatos').width()/2)*(-1)+'px'
	});
}