/*
.........................
:: Javascript a medida. ::
.........................
*/

/*Sistema de Drag*/
var dragElements    =new Object();
var dragElement     =0;
var mousemoveFunc   =function(event){ funcionDrag(event); return false; };
var mouseupFunc     =function(){ finDrag(); };

function hazDrag(id,func){
    dragElements[id]=func;
    dragElement=id;
    iniDrag();
    return false;
}

function iniDrag(){
    addEvent(document.body,"mousemove",mousemoveFunc);
    addEvent(document.body,"mouseup",mouseupFunc);
}
function finDrag(){
    removeEvent(document.body,"mousemove",mousemoveFunc);
    removeEvent(document.body,"mouseup",mouseupFunc);
}
function funcionDrag(e){
    dragElements[dragElement](e);
}
/*Fin sistema de Drag*/


// by Vadim
function catTabClick(num){
	$('catalog_container').classNames().grep(/^active-tabState/, function(it){
		$('catalog_container').removeClassName(it)
	})
	$('catalog_container').addClassName('active-tabState'+num)
	layerOpen='pc'+num
	iniTermo('pc'+num)
	
	var h = location.hash.substr(1).toQueryParams()
	if (h['cat']!=num)
		location.hash = '#cat='+num
}
// by Vadim
var sortDir = 1
function sortBuffItems() {
	var divs = $$('#bufflist .buff-item').sortBy(function(d){
		return sortDir * parseInt(d.down('span.artikul').innerHTML, 10)
	})
	
	$$('#bufflist .buff-item').invoke('remove')
	divs.each(function(it){
		$('bufflist').insert({bottom: it})
	})
	
	sortDir = -sortDir
	$('sortbar').down('a').update(sortDir > 0 ? 'по возрастанию' : 'по убыванию')
}

function sortBuffs(a, f) {
	
	var divs = $$('#bufflist .buff-item').sortBy(function(d){
		return f=='artikul'
			? sortDir * parseInt(d.down('span.artikul').innerHTML, 10)
			: d.down('span.name').innerHTML
	})
	
	$$('#bufflist .buff-item').invoke('remove')
	$$('#bufflist br').invoke('remove')
	var n = 0
	divs.each(function(it){
		$('bufflist').insert({bottom: it})
		n++
		if (n%4==0)
			$('bufflist').insert({bottom: new Element('br', {'class':'clear'})})
	})
	$$('#sortbar a.selected').each(function(it){ it.removeClassName('selected') })
	$(a).addClassName('selected')
	
	return false
}

// by Vadim
function ctgClick(id) {
	var h = location.hash.substr(1).toQueryParams()
	h['ctg'] = id
	location.hash = $H(h).toQueryString()
	loadCtgInfo(id)
	return false
}

// by Vadim
function loadCtgInfo(id) {
	new Ajax.Request('cat.php?id='+id, {
		method: 'get',
		onSuccess: function(resp) {
			$('ficha').update(resp.responseText)
			Effect.ScrollTo('ficha')
			Shadowbox.init()
		}
	})
}

function bigImage(a) {
	$('invisible').src = $(a).down('img').readAttribute('src') 
	Shadowbox.open({
		content: $('invisible').src,
		player: 'img'
	})
	return false
}


function iniTermo(idCapa){
    obj=document.getElementById(idCapa);
    posOld=obj.style.left;
    if(posOld=="") posOld="30px";
    posOld=posOld.substring(0,(posOld.length-2));

    setLeft(idCapa,posOld); 
    //termoPosEnd=capaLeft2termoLeft(document.getElementById(layerOpen),posOld);
    //slideTermo();
}

function setLeft(id,pos){
    capa=document.getElementById(id);
    ter=document.getElementById('termo-square');

    //primero el termometro
    posTer=capaLeft2termoLeft(capa,pos);
    if(posTer<15 || posTer>523){
        return 0; //Nos hemos pasado por fuera
    }
   ter.style.left=posTer+"px";
   termoPosNow=posTer;

    //ahora la capa
    capa.style.display="none";
    capa.style.left=pos+'px';
    capa.style.display="block";
}

function capaLeft2termoLeft(capa,pos){
	if (isNaN(15-(pos-30)*(508/((capa.quantity-3)*250)))) return 0;
	else  return 15-(pos-30)*(508/((capa.quantity-3)*250));
}
function termoLeft2capaLeft(capa,pos){
    return 30-(((capa.quantity-3)*250*(pos-15)/508));
}


function moveStripTo(id,increment){ // para el movimiento desde las flechas laterales
    obj=document.getElementById(id);
    posOld=obj.style.left;
    if(posOld=="") posOld="30px";
    posOld=posOld.substring(0,(posOld.length-2));
    steps=50;
    for(i=1;i<=steps;i++){
        paso=Math.sin(i/steps * Math.PI/2);
        pos=parseInt(posOld) + parseInt(increment*paso*paso);
        setTimeout('setLeft("'+id+'",'+pos+')',i*20);
    }    
}

var termoInMotion=0;
var termoPosEnd=0;
var termoPosNow=15;

function termoMove(e){  //para el movimiento desde el termometro
    strip=document.getElementById('termo-strip');
    offsetStrip=offsetXElement(strip);
    posTermo=e.clientX-offsetStrip-13;
    if(posTermo<15)         posTermo=15;
    else if(posTermo>523)   posTermo=523;

    termoPosEnd=posTermo;
    if(!termoInMotion){
        slideTermo();
    }
}

function offsetXElement(element){
    var valueL = 0;
    do {
      valueL += element.offsetLeft || 0;
      element = element.offsetParent;
    } while (element);
    return valueL;
}


function slideTermo(){
    termoInMotion=1;
    posTermo=parseInt(termoPosNow+Math.ceil((termoPosEnd-termoPosNow)*0.3));
    if(Math.abs((termoPosEnd-termoPosNow)*0.3)<1){
        if(termoPosEnd>termoPosNow) posTermo++;
        else                        posTermo--;
    }
    posCapa=termoLeft2capaLeft(document.getElementById(layerOpen),posTermo);
    setLeft(layerOpen,posCapa);

    if(posTermo==termoPosEnd){
        termoInMotion=0;
        //document.getElementById('line_footer').innerHTML="<a>0</a>";
    }else{
        //document.getElementById('line_footer').innerHTML="<a>1</a>";
        setTimeout('slideTermo('+posTermo+')',20);
    }
}


/* FUNCIONES PARA LA FICHA y DISENOS */

function cambiaFeaturesDisenyos(){
    f=document.getElementById('features');
    d=document.getElementById('disenyos');
    tabs=document.getElementById('ficha_up');

    if(f.style.display=="none"){
        d.style.display="none";
        f.style.display="block";
        tabs.style.background='url(../img/back_ficha_up.gif) no-repeat top left';
    }else{
        d.style.display="block";
        f.style.display="none";
        tabs.style.background='url(../img/back_ficha_up2.gif) no-repeat top left';
    }
}

/* funciones para cargar la ficha via ajax */

var totalDisenyos=0;
var sizexDisenyo=0;


/* funciones de movimiento de la tira de tejidos */
var tiraPos=0;
var velocidadTira=0;


/*funciones para hacer zoom en los tejidos*/
var idTejidoAmpliado=0;

function redimensiona(id,newx,newy,oldx,oldy){
    if(idTejidoAmpliado==id)    //para evitar eventos dobles
        return false;

    //primero zoom-out el actualmente ampliado
    if(idTejidoAmpliado){
        obj=document.getElementById(idTejidoAmpliado);
        steps=10;
        for(i=1;i<=steps;i++){
            paso=Math.sin(i/steps * Math.PI/2);
            setTimeout('redimensionaTejido("'+idTejidoAmpliado+'",'+(Math.round(obj.width+(obj.oldx-obj.width)*paso ))+','+(Math.round(obj.height+(obj.oldy-obj.height)*paso ))+')',i*20);
        }
        document.getElementById('info'+idTejidoAmpliado).style.display="none";
		$('muestras').style.width=oldWidth+"px";
		
    }
    // guardamos la informacion del nuevo tejido a ampliar, para poder luego hacer el zoom-out
    idTejidoAmpliado=id;
    obj=document.getElementById(id);
    obj.oldx=oldx; //guardo en el propio objeto el tamano original
    obj.oldy=oldy;

    // hacemos el zoom-in del nuevo tejido
    steps=10;
    for(i=1;i<=steps;i++){
        paso=Math.sin(i/steps * Math.PI/2);
        setTimeout('redimensionaTejido("'+id+'",'+(Math.round(oldx+(newx-oldx)*paso ))+','+(Math.round(oldy+(newy-oldy)*paso ))+')',i*20);
    }   
    document.getElementById('info'+id).style.display="block";
	
	oldWidth=parseInt($('muestras').style.width);
	$('muestras').style.width=oldWidth +(newx) + "px";
	
	
}


function redimensionaTejido(id,x,y){
    obj=document.getElementById(id);
    obj.width=x;
    obj.height=y;
    obj.style.marginTop=Math.round((380-y)/2)+'px';
}





/* E M P R E S A */

function resetEmpresa() {
	
	for(x=1; x<=4; x++) {
		document.getElementById('empresa_tab' + x).className = '';
		document.getElementById('empresa_contenido' + x).style.display = 'none';
	}
}

function empresa(opc) {
	resetEmpresa();
	document.getElementById('empresa_tab' + opc).className = 'abierto';
	document.getElementById('empresa_contenido' + opc).style.display = 'block';
    document.getElementById('empresa_tabs').style.backgroundImage = 'url(../img/back_empresa'+opc+'.gif)';
}


/* QUALITY */

function resetQuality() {
	
	for(x=1; x<=4; x++) {
		document.getElementById('quality_tab' + x).className = '';
		document.getElementById('quality_contenido' + x).style.display = 'none';
	}
}

function quality(opc) {
	resetQuality();
	document.getElementById('quality_tab' + opc).className = 'abierto';
	document.getElementById('quality_contenido' + opc).style.display = 'block';
    document.getElementById('quality_tabs').style.backgroundImage = 'url(../img/back_empresa'+opc+'.gif)';
}


// INI CAMBIAR LA FOTO DE EMPRESA //
var cambiandoFlag=0;

function cambiaFotoEmpresa(contenedor,num){
    if(!cambiandoFlag){
        workDiv = contenedor.getElementsByTagName('DIV')[0];

        // posicionamos absolutamente la imagen vieja
        imgActual = workDiv.getElementsByTagName('IMG')[0];
        imgActual.style.position="absolute";
        imgActual.style.zIndex="3";

        //creamos la otra imagen
        newImg = document.createElement('IMG');
        newImg.src=imgActual.src.replace(/[0-9]/,num);
        newImg.style.position="absolute";
        newImg.style.zIndex="2";
        workDiv.appendChild(newImg);   

        //Ejecutamos la animacion
        imgActual.id="imagen1";
        newImg.id="imagen2";
        cambiandoFlag=1;
        fundidoFotos(0);

        //cambiamos los thumbnails
        anchors = contenedor.getElementsByTagName('A');
        for(i=0;i<anchors.length;i++)
            if(i+1==num)
                anchors[i].style.background="#999";
            else
                anchors[i].style.background="#CCC";                
    }
}

// "val" entre 0 y 1
function fundidoFotos(val){
    Element.setStyle('imagen1',{opacity:(1-val).toString()});
    Element.setStyle('imagen2',{opacity:val.toString()});

    if(val>=1){
        //destruimos la imagen vieja
        Element.remove('imagen1');
        cambiandoFlag=0;
    }else{
        val=val+0.05;
        val=Math.round(val*100)/100;
        setTimeout('fundidoFotos('+val+')',50);
    }
}
// FIN CAMBIAR LA FOTO DE EMPRESA //


function isDNI( dni )
{
    dni    = dni.toUpperCase();
    primeraletra = dni.substr( 0 , 1 );
    if( primeraletra == "X" || primeraletra == "Y" ) { dni = "0" + dni.substr( 1 , dni.length ); } 
    numero = dni.substr( 0 , dni.length - 1 );
    let    = dni.substr( dni.length - 1 , 1 );
    numero = numero % 23;
    letra  = 'TRWAGMYFPDXBNJZSQVHLCKET';
    letra  = letra.substring( numero , numero + 1 );

    if( letra != let )
    {
        return false;
    }
    else
    {
        return true;
    }
}


function isNIE ( nie )
{
	
			dni=nie
			dni=dni.toUpperCase();
			pre=dni.substr(0, 1);
			var prev = '0';
			if (pre == 'X') prev = '0';
				else if (pre == 'Y')
						prev = '1';
   			 				else if (pre == 'Z')
      							 prev = '2';
    		numero = prev + dni.substr(1,dni.length-1);
			
			dni=numero;
			numero = dni.substr(0,dni.length-1);
			let = dni.substr(dni.length-1,1);
			let=let.toUpperCase();
			numero = numero % 23;
			letra='TRWAGMYFPDXBNJZSQVHLCKET';
			lletra=letra.charAt(numero); 
		  
			if (lletra!=let) return false;
			else return true;
									
}


function isCIF( cif )
{
    par = 0;
    non = 0;
    letras = "ABCDEFGHKLMNPQS";
    let = cif.charAt(0);
 
    if( cif.length != 9 )
    {
        // El CIF debe tener 9 digitos.
        return false;
    }
 
    if( letras.indexOf( let.toUpperCase() ) == -1 )
    {
        // El comienzo del CIF no es valido.
        return false;
    }



    for( i = 2 ; i < 8 ; i += 2 )
    {
        par = par + parseInt( cif.charAt( i ) );
    }

    for( i = 1 ; i < 9 ; i += 2 )
    {
        nn = 2 * parseInt( cif.charAt( i ) );
        if( nn > 9 )
        {
            nn = 1 + (nn - 10);
        }
        non = non + nn;
    }
 
    parcial = par + non;
    control = (10 - ( parcial % 10));
    if( control == 10 )
    {
        control = 0;
    }

    if( control != cif.charAt(8))
    {
        return false;
    }

    return true;
}


function validarFormsPagina_checkout1_php( msjError1 , msjError2 , msjError3 , msjError4 )
{
    var error   = 0;
    var mensaje = "";

    if( $('entrarPorIdentificacion').value == -1 )
    {
        // El usuario esta tratando de darse de alta como nuevo cliente. 

        aVerificar = [ 'nif' , 'nombre' , 'apellidos' , 'edad', 'email' , 'contrasena' , 'contrasena2' , 'poblacion' , 'provincia' , 'direccion' , 'codigoPostal' , 'telefono1' ];
        aVerificar.each(
            function( e )
            {
                if( $(e).value.length == 0 )
                {
                    $(e).style.borderColor = 'red';
                    error                  = 1;
                }
                else
                {
                    $(e).style.borderColor = '#B7B7BB';
                }
            }
        );


        var paisOrigen = readCookie("p");
        
        if( paisOrigen != "DEU" )
        {
            if( $('nif').value != "" && !isDNI( $('nif').value ) && !isNIE( $('nif').value) && !isCIF( $('nif').value ) )
            {
                $('nif').style.borderColor = 'red';
                error                      = 1;
    
                mensaje += msjError1 + "<br/>";
            }
        }

		
		 if( $( 'sexo' ).selectedIndex == 0 )
        {
            $( 'sexo' ).style.borderColor = 'red';
            error                         = 1;
        }
        else
        {
            $( 'sexo' ).style.borderColor = '#B7B7BB';
        }
		
		

        if( $('email').value != "" && ! /^[a-zA-Z]+([\.]?[a-zA-Z0-9_-]+)*@[a-zA-Z0-9]+([\.-]+[a-zA-Z0-9]+)*\.[a-z]{2,}$/.test( $('email').value ) )
        {
            $('email').style.borderColor = 'red';
            error                        = 1;

            mensaje += msjError2 + "<br/>";
        }



        if( $('contrasena').value != $('contrasena2').value )
        {
            $('contrasena' ).style.borderColor = 'red';
            $('contrasena2').style.borderColor = 'red';
            error                              = 1;

            mensaje += msjError3 + "<br/>";
        }



        if( $( 'pais' ).selectedIndex == 0 )
        {
            $( 'pais' ).style.borderColor = 'red';
            error                         = 1;
        }
        else
        {
            $( 'pais' ).style.borderColor = '#B7B7BB';
        }
		
		



        if( error )
        {
            if( mensaje != "" )
            {
                mensaje += "<br/>";
            }

            $('mensajeError').innerHTML     = mensaje + msjError4;
            $('mensajeError').style.display = "block";
        }
    }
    else
    {
        // El usuario esta tratando de acceder como cliente ya registrado.

        aVerificar = [ 'emailIdentificativo' , 'pwIdentificativo' ];
        aVerificar.each(
            function( e )
            {
                if( $(e).value.length == 0 )
                {
                    $(e).style.borderColor = 'red';
                    error                  = 1;
                }
                else
                {
                    $(e).style.borderColor = '#B7B7BB';
                }
            }
        );


        if( $('emailIdentificativo').value != "" && ! /^[^@]+@[^\.]+\.[a-z]+$/.test( $('emailIdentificativo').value ) )
        {
            $('emailIdentificativo').style.borderColor = 'red';
            error                                      = 1;

            mensaje += msjError2 + "<br/>";
        }



        if( error )
        {
            if( mensaje != "" )
            {
                mensaje += "<br/>";
            }

            $('mensajeErrorAccesoIdentificativo').innerHTML     = mensaje + msjError4;
            $('mensajeErrorAccesoIdentificativo').style.display = "block";
        }
    }

    return !error;
}

function validarFormPagina_checkout2_php( msjError2 , msjError1 )
{
    var error   = 0;
    var mensaje = "";
    var paisOrigen = readCookie("p");

    aVerificar = [ 'pais' , 'poblacion' , 'provincia' , 'direccion' , 'codigoPostal' ]; // Estos campos deben tener tamano minimo.
    aVerificar.each( function(e){
                if( $(e).value.length == 0 )
                {
                    $(e).style.borderColor = 'red';
                    error                  = 1;
                }
                else
                {
                    if( e == "pais" && $(e).value != paisOrigen )
                    {
	                    $(e).style.borderColor = 'red';
	                    error                  = 1;
                        mensaje                = msjError2 + "<br/><br/>";
                    }
                    else
                    {
                        $(e).style.borderColor = '#B7B7BB';
                    }
                }
            }
        );

    if( error )
    {
        $('mensajeError').innerHTML     = mensaje + msjError1;
        $('mensajeError').style.display = "block";
    }

    return !error;
}

/*-------------------------------------------------------------------------------------------------------------------------------------------*/

function validarFormPagina_checkout3_php()
{
    $('navegacionFlechas').style.display = "none";
    $('ajaxLoader').style.display        = "block";

    var factura = 1;
    if( document.forms[ 'formularioInformacionCompra' ][ 'factura' ][1].checked )
    {
        factura = 0;
    }

    var ajax = new Ajax.Request( 'llamarServidorBuff.php',
                                 {
                                     method:     'post' ,
                                     parameters: "idSistemaPago=" + $('idSistemaPago').value + "&factura=" + factura + "&idPedido=" + $( 'Ds_Merchant_Order' ).value ,
                                     onComplete: actualizarStock ,
                                     onFailure: function()
                                     {
                                        $('mensajeError').style.display      = "block";
                                        $('navegacionFlechas').style.display = "block";
                                        $('ajaxLoader').style.display        = "none";
                                     }
                                 }
                               );
}

function actualizarStock( r )
{
    if( r.responseText == "1" )
    {
        $('conectarConBancSabadell').submit();
    }
    else
    {
        if( r.responseText == "0" )
        {
            location.href = "resumenCarrito.php?sinStock=true";
        }
    }
}

/*------------------------------------------------------------------------------------------------------------------------------------------*/

function validarFormPagina_contrasena_php( msjError2 )
{
    var error   = 0;
    var mensaje = "";


    if( !/^[^@]+@[^\.]+\.[a-z]+$/.test( $('email').value ) )
    {
        $('email').style.borderColor = 'red';
        error = 1;
        
        mensaje += msjError2 + "<br/>";
    }
    else
    {
        $( 'email' ).style.borderColor = '#B7B7BB';
    }

    if( error )
    {
        $('mensajeError').innerHTML     = mensaje;
        $('mensajeError').style.display = "block";
    }


    return !error;
}

/*------------------------------------------------------------------------------------------------------------------------------------------*/

//Preguntas frecuentes

function fundidoFaq(val,i) {
	for (a=1;a<=12;a++) {
		document.getElementById('faq'+a).style.display="none";
	}
	document.getElementById('faq'+i).style.opacity=val;
	document.getElementById('faq'+i).style.filter= 'alpha(opacity='+val*100+')';
	document.getElementById('faq'+i).style.display="block";
  
    if(val>=1){
        cambiandoFlag=0;
    }else{
        val=val+0.05;
        val=Math.round(val*100)/100;
        setTimeout('fundidoFaq('+val+','+i+')',5);
    }
}

function fundidoFaqOnline(val,i) {
	
	for (a=1;a<=9;a++) {
		document.getElementById('faq_on'+a).style.display="none";
	}
	document.getElementById('faq_on'+i).style.opacity=val;
	document.getElementById('faq_on'+i).style.filter= 'alpha(opacity='+val*100+')';
	document.getElementById('faq_on'+i).style.display="block";

    if(val>=1){
        cambiandoFlag=0;
    }else{
        val=val+0.05;
        val=Math.round(val*100)/100;
        setTimeout('fundidoFaqOnline('+val+','+i+')',5);
    }
}
