var cabRotAct = 0;
var infoBoxT;

function infoBox(e, txt) {
    var contenedor = new Element('div', {'class':'info_box', 'id':e.id+'_infobox'});
    var contenido = new Element('div', {'class':'info_box_cont'});
    var cumulativeOffsetT = e.cumulativeOffset()[1];
    var cumulativeOffsetL = e.cumulativeOffset()[0];
    var posL = getPosL(cumulativeOffsetL, e)+e.offsetWidth;

    contenido.innerHTML = txt;
    contenedor.insert(contenido);
    contenedor.style.left = posL+'px';
    $('body').insert(contenedor);
    var posT = getPosT(cumulativeOffsetT, e)-(contenedor.offsetHeight/2)+(e.offsetHeight/2);
    contenedor.style.top = posT+'px';
    contenedor.style.display='none';
    contenedor.appear({ duration: 0.5 });
}

function infoBoxDestroy(e) {
    new Effect.Fade(e.id+'_infobox', {duration: 0.5, afterFinish: function () {$(e.id+'_infobox').remove();}} );
}

function getPosT(posicionTop, capa) {
    var posicionRespectoViewport = posicionTop - document.viewport.getScrollOffsets()[1] + capa.offsetHeight;
    if (posicionRespectoViewport > document.viewport.getDimensions().height) {
        posicionTop = document.viewport.getDimensions().height + document.viewport.getScrollOffsets()[1] - capa.offsetHeight;
    }
    return posicionTop;
}

function getPosL(posicionLeft, capa) {
    var posicionRespectoViewport = posicionLeft - document.viewport.getScrollOffsets()[0] + capa.offseWidth;
    if (posicionRespectoViewport > document.viewport.getDimensions().width) {
        posicionLeft = document.viewport.getDimensions().width + document.viewport.getScrollOffsets()[0] - capa.offsetWidth;
    }
    return posicionLeft;
}

function anunShowPas(p) {

    $('boton_paso_'+paso).className = 'boton_pasos';
    $('boton_paso_'+p).className = 'boton_pasos canun_pasos_focus';

    Effect.Fade('paso_'+paso,{duration: 0.3, queue: 'end'});
    Effect.Appear('paso_'+p,{duration: 0.3, queue: 'end'})

    paso = p;
}

function loadYTiFrame(id) {
    var yid = $(id).innerHTML;
    if (yid.length > 0 && yid != 'sin definir... ' && yid != 'Error al guardar, faltan datos ')  {
        $('video_box').style.display='block';
        $('iframe_youtube').src = 'http://www.youtube.com/embed/'+yid
    } else {
        $('video_box').style.display='none';
        $('iframe_youtube').src = '';
    }
}

function SWFqueueComplete() {
    var url = SWFRoot+'site/crearAnuncioPics/'+SWFAnun;
    cargar(url, 'anunciosPics');
}


function cargar(url, e) {
    new Ajax.Updater(
			 e,url,
			 {
				asynchronous:true,
				evalScripts:true,
				onLoading:function(request, json)
				{
					$('loadingContImg').style.display='block';
				},
				onComplete:function(request, json)
				{
					setTimeout("$('loadingContImg').style.display='none'", 100);
				},
				requestHeaders:['X-Update', e]
			}
		);
}

function setCatAnun(padre, val, cat, anun, exp, up) {

    if (padre) {
        var precursor = $(cat).parentNode.parentNode.id;
        var precursor_id = precursor.replace('hijos_', '');
        var desactivar = true;
        var inputs = $A($(precursor).getElementsByTagName('input'));
        inputs.each( function(o) {if (o.checked && o.id != cat) { desactivar=false; } });

        if (desactivar) {
            $(precursor_id).disabled=val;
        }
    }

    if (exp>0) {
        if (val) {
            Effect.BlindDown('hijos_'+cat, {duration: 0.3, queue: 'end'});

        } else {
            Effect.BlindUp('hijos_'+cat, {duration: 0.3, queue: 'end'});
        }
    }

    if (up) {
        var accion = (val) ? 1 : 2;
        var url = '/site/crearAnuncioCatSave/'+anun+'/'+cat+'/'+accion
        cargar(url, 'anunioCatsDump');
    }
}

function prepareShowCatAnun(ids) {
    var cats = ids.split(';');
    cats.each( function(o) { if (o.length>0) showCatAnun(o) });
}

function showCatAnun(id) {

    if ($('hijos_'+id)) {
        $('hijos_'+id).style.display='block';
    }

    $(id).checked = true;

    var precursor = $(id).parentNode.parentNode.id;
    if (precursor!='menuCats') {
        var precursor_id = precursor.replace('hijos_', '');
        var desactivar = true;
        var inputs = $A($(precursor).getElementsByTagName('input'));
        inputs.each( function(o) { if (o.checked && o.id != id) { desactivar=false; } });

        if (desactivar) {
            $(precursor_id).disabled=1;
        }
    }
}

function anunFin(id) {
    if ($('publicar_ahora').checked) {
        location.href='/site/publicarAnuncio/'+id;
    } else {
        location.href='/site/misAnuncios';
    }
}

function addToCart(id, e, d) {
	var a = $(e).clone(2);
	a.style.zIndex = '10';
	Element.absolutize(a)

    if (d==1) {
        a.clonePosition(e, {offsetLeft: -5, offsetTop: -5});
        //a.style.width = '227px';
        //a.style.height = '345px';
    } else if (d==2) {
        a.clonePosition(e);
        a.style.width = '120px';
        a.style.height = '15px';
    } else {
        a.clonePosition(e);
    }

	a.style.overflow = 'hidden';
	$('body').insert(a);

	var destino = $('cestaCompra').cumulativeOffset();
	
	new Effect.Morph(a, {
		style: 'opacity:0; top:'+destino[1]+'px; left:'+(destino[0]-50)+'px;', // CSS Properties
		duration: 0.8, // Core Effect properties
		afterFinish: function () { a.style.display = 'none'; }
	});
	

    var url = '/site/cestaAct/add/'+id;
    cargar(url, 'bloqueCarritoData');

}

function transProds(s) {
	if (s == 1) {
		new Effect.Parallel([
			new Effect.Move('productosLayout', { sync: true, x: -775, y: 0, mode: 'relative' }),
			new Effect.Opacity('productosLayout', { sync: true, from: 1, to: 0 })
		], {
			duration: 0.2
		});
	} else if (s == 0) {
		new Effect.Parallel([
			new Effect.Move('productosLayout', { sync: true, x: -775, y: 0, mode: 'relative' }),
		], {
		  duration: 0.2
		});
	} else if (s == 2) {
	    	new Effect.Parallel([
			new Effect.Move('productosLayout', { sync: true, x: 0, y:  -775, mode: 'relative' }),
			new Effect.Opacity('productosLayout', { sync: true, from: 1, to: 0 })
		], {
			duration: 0.2
		});
	}
}

function cestaUpd() {
    var url = '/site/cestaUpd/';
    cargar(url, 'contenedorCesta');
}

function actCart(cant, id) {
    var url = '/site/cestaAct/act/'+id+'/'+cant;

    new Ajax.Updater(
		'bloqueCarritoData',url,
		{
		    asynchronous:true,
		    evalScripts:true,
		    onLoading:function(request, json)
		    {
			$('cargandoMicroCesta').style.display='block';
			$$(".cestaCantidad").each( function(input) {input.disabled=true; });
		    },
		    onComplete:function(request, json)
		    {
			$('cargandoMicroCesta').style.display='none';
			actCartData('/site/cestaUpd/', 'contenedorCesta');
		    },
                    requestHeaders:['X-Update', 'bloqueCarritoData']
		}
    );
}

function actCartData(url, e) {
    new Ajax.Updater(
			 e,url,
			 {
				asynchronous:true,
				evalScripts:true,
				onLoading:function(request, json)
				{
				    $('cargandoMicroCesta').style.display='block';
				},
				onComplete:function(request, json)
				{
				    $('cargandoMicroCesta').style.display='none';
				    $$(".cestaCantidad").each( function(input) {input.disabled=false; });
				},
				requestHeaders:['X-Update', e]
			}
		);
}

function showCompletarPedido(s) {
    try {
        if (s) {
            Effect.Appear('completarPedido',{duration: 0.3, queue: 'end'})
        } else {
            Effect.Fade('completarPedido',{duration: 0.3, queue: 'end'})
        }
    } catch(e) {}
}




function initCabRot() {
    document.observe("dom:loaded", CabRot);
}

function CabRot() {
    $('linkCabecera').href = $('fotocabecera_0').alt;
    setInterval('rotarImagenesCabecera()', 5000);
    Effect.Appear('fotocabecera_0',{duration: 0.8, queue: 'end'})
}

function rotarImagenesCabecera() {

    var imagen_ocultar = cabRotAct;
    
    var imagen_mostrar = cabRotAct+1;
    if (imagen_mostrar > CabRotTot) {
        imagen_mostrar = 0;
        cabRotAct = 0;
    } else {
        cabRotAct = imagen_mostrar;
    }
    $('linkCabecera').href = $('fotocabecera_'+imagen_mostrar).alt;
    Effect.Appear('fotocabecera_'+imagen_mostrar,{duration: 0.8, queue: 'end'})
    Effect.Fade('fotocabecera_'+imagen_ocultar,{duration: 0.8, queue: 'end'});
    
}



function resetVentanaFlotante() {
        // Ocultar y limpiar
        //vfLoad(false);
        Effect.Fade('ventanaFlotante',{duration: 0.5, afterFinish: limpiarVentanaFlotante});
}

function ventanaFlotante(titulo, ancho, top) {
        // Alineacion
        $('ventanaFlotante').style.width = ancho+'px';
        $('ventanaFlotante').style.marginLeft = '-'+(ancho/2)+'px';
        $('ventanaFlotante').style.top = top+'px';
        // Ancho
        $('ventanaFlotanteTop').style.width = (ancho-20)+'px';
        $('ventanaFlotanteBot').style.width = (ancho-20)+'px';
        // Preparando contenidos
        limpiarVentanaFlotante();
        $('ventanaFlotanteTituloSpan').innerHTML = titulo;
        // Mostrar imagen cargando
        vfLoad(true);
        // Mostrar ventana
        //new Draggable('ventanaFlotante', { scroll: window });
        Effect.Appear('ventanaFlotante',{duration: 0.5 });
}

function vfLoad(s) {
    if (s)
        $('ventanaFlotanteCargando').style.display = 'block';
    else {
        $('ventanaFlotanteCargando').style.display = 'none';
    }
}

function limpiarVentanaFlotante() {
        $('ventanaFlotanteTituloSpan').innerHTML = '';
        $('ventanaFlotanteMain').innerHTML = '';
}


function chkselpfr(p) {
    if (p==1) {
        $('selProvs').style.display='block';
        UsuarioOldProvincia = new LiveValidation('UsuarioOldProvincia', { validMessage: 'Correcto' });
        UsuarioOldProvincia.add( Validate.Presence, { failureMessage: 'No puedes dejar este campo vacio' } );
    } else {
        $('selProvs').style.display='none';
        UsuarioOldProvincia.destroy();
    }
}

function infoBoxAcceso(s) {
    if (s) {
        if (infoBoxT) {
            clearTimeout(infoBoxT);
        } else {
            Effect.Appear('infoBoxAcceso',{duration: 0.5, queue: 'end' });
        }
    } else {
        if (infoBoxT) {
            clearTimeout(infoBoxT);
            infoBoxT = setTimeout("Effect.Fade('infoBoxAcceso',{duration: 0.5, queue: 'end' });", 2000);
        } else {
            infoBoxT = setTimeout("Effect.Fade('infoBoxAcceso',{duration: 0.5, queue: 'end' });", 2000);
        }
    }
}

function valida_nif_cif_nie(a) 
{
	var temp=a.toUpperCase();
	var cadenadni="TRWAGMYFPDXBNJZSQVHLCKE";
 
	if (temp!==''){
		//si no tiene un formato valido devuelve error
		if ((!/^[A-Z]{1}[0-9]{7}[A-Z0-9]{1}$/.test(temp) && !/^[T]{1}[A-Z0-9]{8}$/.test(temp)) && !/^[0-9]{8}[A-Z]{1}$/.test(temp))
		{
			return 0;
		}
 
		//comprobacion de NIFs estandar
		if (/^[0-9]{8}[A-Z]{1}$/.test(temp))
		{
			posicion = a.substring(8,0) % 23;
			letra = cadenadni.charAt(posicion);
			var letradni=temp.charAt(8);
			if (letra == letradni)
			{
			   	return 1;
			}
			else
			{
				return -1;
			}
		}
 
		//algoritmo para comprobacion de codigos tipo CIF
		suma = parseInt(a[2])+parseInt(a[4])+parseInt(a[6]);
		for (i = 1; i < 8; i += 2)
		{
			temp1 = 2 * parseInt(a[i]);
			temp1 += '';
			temp1 = temp1.substring(0,1);
			temp2 = 2 * parseInt(a[i]);
			temp2 += '';
			temp2 = temp2.substring(1,2);
			if (temp2 == '')
			{
				temp2 = '0';
			}
 
			suma += (parseInt(temp1) + parseInt(temp2));
		}
		suma += '';
		n = 10 - parseInt(suma.substring(suma.length-1, suma.length));
 
		//comprobacion de NIFs especiales (se calculan como CIFs)
		if (/^[KLM]{1}/.test(temp))
		{
			if (a[8] == String.fromCharCode(64 + n))
			{
				return 1;
			}
			else
			{
				return -1;
			}
		}
 
		//comprobacion de CIFs
		if (/^[ABCDEFGHJNPQRSUVW]{1}/.test(temp))
		{
			temp = n + '';
			if (a[8] == String.fromCharCode(64 + n) || a[8] == parseInt(temp.substring(temp.length-1, temp.length)))
			{
				return 2;
			}
			else
			{
				return -2;
			}
		}
 
		//comprobacion de NIEs
		//T
		if (/^[T]{1}/.test(temp))
		{
			if (a[8] == /^[T]{1}[A-Z0-9]{8}$/.test(temp))
			{
				return 3;
			}
			else
			{
				return -3;
			}
		}
 
		//XYZ
		if (/^[XYZ]{1}/.test(temp))
		{
			pos = str_replace(['X', 'Y', 'Z'], ['0','1','2'], temp).substring(0, 8) % 23;
			if (a[8] == cadenadni.substring(pos, pos + 1))
			{
				return 3;
			}
			else
			{
				return -3;
			}
		}
	}
 
	return 0;
}

function str_replace(search, replace, subject) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Gabriel Paderni
    // +   improved by: Philip Peterson
    // +   improved by: Simon Willison (http://simonwillison.net)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   bugfixed by: Anton Ongson
    // +      input by: Onno Marsman
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    tweaked by: Onno Marsman
    // *     example 1: str_replace(' ', '.', 'Kevin van Zonneveld');
    // *     returns 1: 'Kevin.van.Zonneveld'
    // *     example 2: str_replace(['{name}', 'l'], ['hello', 'm'], '{name}, lars');
    // *     returns 2: 'hemmo, mars'
 
    var f = search, r = replace, s = subject;
    var ra = r instanceof Array, sa = s instanceof Array, f = [].concat(f), r = [].concat(r), i = (s = [].concat(s)).length;
 
    while (j = 0, i--) {
        if (s[i]) {
            while (s[i] = s[i].split(f[j]).join(ra ? r[j] || "" : r[0]), ++j in f){};
        }
    };
 
    return sa ? s : s[0];
}

function checkDNI(v) {
    var pais = $('UsuarioOldPais').value;
    checkDataInUse(1, v);
    if (pais==1) {
        var valido = valida_nif_cif_nie(v);
        if (valido) {
            return true;
        } else {
            return false;
        }
    } else {
        if (v.length>5) {
            return true;
        } else {
            return false;
        }
    }
}

function checkProvReg(v) {
    var pais = $('UsuarioOldPais').value;
    if (pais==1) {
        return false;
    } else {
        return true;
    }
}

function checkLogin(v) {
    checkDataInUse(2, v);
    return true;
}

function checkDataInUse(m, v) {
    switch (m) {
        case 1:
            new Ajax.Request('/site/checkData/1/'+v, {
                        method: 'get',
                        onSuccess:  function (peticion) {
                                                if (200 == peticion.status) {
                                                    if (peticion.responseText == 1) {
                                                        $('botonSubmit').disabled=true;
                                                        $('logNif').innerHTML = 'El documento indicado ya esta registrado, indique uno diferente por favor.';
                                                        $('logNif').style.display = 'block';
                                                    }
                                                    if (peticion.responseText == 2) {
                                                        if ($('logLog').innerHTML.length == 0) {
                                                            $('botonSubmit').disabled=false;
                                                        }
                                                        $('logNif').innerHTML = '';
                                                        $('logNif').style.display = 'none';
                                                    }
                                                }
                                            }
            });
        break;
    
        case 2:
            new Ajax.Request('/site/checkData/2/'+v, {
                        method: 'get',
                        onSuccess:  function (peticion) {
                                                if (200 == peticion.status) {
                                                    if (peticion.responseText == 1) {
                                                        $('botonSubmit').disabled=true;
                                                        $('logLog').innerHTML = 'La direccion de correo indicada ya esta registrada, utilice otra por favor.';
                                                        $('logLog').style.display = 'block';
                                                    }
                                                    if (peticion.responseText == 2) {
                                                        if ($('logNif').innerHTML.length == 0) {
                                                            $('botonSubmit').disabled=false;
                                                        }
                                                        $('logLog').innerHTML = '';
                                                        $('logLog').style.display = 'none';
                                                    }
                                                }
                                            }
            });
        break;
    }
}

function validDirForm() {
    var provincia = $('provincia').value;
    var direccion = $('direccion').value;
    var poblacion = $('poblacion').value;
    var cp = $('cp').value;
    var pais = $('pais').value;
    
    if (pais == 1) {
        if (provincia.length<1 || direccion.length<1 || poblacion.length<1 || cp.length<1) {
            alert('Por favor, complete todos los campos.')
            return false;
        } else {
            return true;
        }    
    } else {
        if (direccion.length<1 || poblacion.length<1 || cp.length<1) {
            alert('Por favor, complete todos los campos.')
            return false;
        } else {
            return true;
        }    
    }
}

function selAccesBoxCesta(v) {
    if (v==1) {
	$('accesCestaBox').style.display='none';
	$('accesCestaRegBox').style.display='none';
	$('accesCestaLoginBox').style.display='block';
    } else if (v==2) {
	$('accesCestaBox').style.display='none';
	$('accesCestaLoginBox').style.display='none';
	$('accesCestaRegBox').style.display='block';
    }
}

function setMailing(v) {
    var valor = (v) ? 1 : 0;
    var url = '/site/modificarPerfilSave/1/'+valor
    cargar(url, 'dumpModPerf');
}

function ApEsE() {
    $('boxSupSearchAutoCom_autoComplete').style.display='block';
}

function checkFormPed() {

    var valid = true;
    if ($('pagoControl').value.length==0) {
        //error += 'Seleccione la forma de pago\n';
        $('form_cesta_error_pago').style.display='table-cell';
        valid = false;
    } else {
        $('form_cesta_error_pago').style.display='none';
    }
    if ($('envioControl').value.length==0) {
        //error += 'Seleccione la forma de envio\n';
        $('form_cesta_error_envio').style.display='table-cell';
        valid = false;
    } else {
        $('form_cesta_error_envio').style.display='none';
    }
    return valid;
}
