/*
.........................
:: Javascript a medida. ::
.........................
*/


/* 参数说明 : 536 -- 拖动游标宽度   783 -- 游标移动对应的图片框宽度       总之,就改这两个参数就可以了 */
/*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*/



/* FUNCIONES PARA EL TERMOMETRO */

function showSize(x){
        for(i=1;i<=3;i++){
            obj1=document.getElementById('buttons'+i);
            obj2=document.getElementById('catalog_'+i);
            if(i==x){
                obj1.style.display="block";
                obj2.style.display="block";
                layerOpen='pc'+i;
                iniTermo('pc'+i);

                //corrige las flechas en Explorer 6
                if (window.attachEvent && navigator.userAgent.indexOf('MSIE 6')!=-1){
                    document.getElementById('arrowl'+i).innerHTML='<a href="javascript:moveStripTo(\'pc'+i+'\',783);"><img src="../img/left-arrow.png"/></a>';
                    document.getElementById('arrowr'+i).innerHTML='<a href="javascript:moveStripTo(\'pc'+i+'\',-783);"><img src="../img/right-arrow.png"/></a>';
                    correctPNG();
                }

            }else{
                obj1.style.display="none";
                obj2.style.display="none";
            }
        }
}

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<0 || posTer>536){
        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){
    return 0-(pos-0)*(502/((capa.quantity-3)*783));
}
function termoLeft2capaLeft(capa,pos){
    return 0-(((capa.quantity-3)*783*(pos-0)/502));
}


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=0;

function termoMove(e){  //para el movimiento desde el termómetro
    strip=document.getElementById('termo-strip');
    offsetStrip=offsetXElement(strip);
    posTermo=e.clientX-offsetStrip-13;
    if(posTermo<0)         posTermo=0;
    else if(posTermo>536)   posTermo=536;

    termoPosEnd=posTermo;
    if(!termoInMotion){
        slideTermo();
    }
}
function termoMov11e(e){  //para el movimiento desde el termómetro
    strip=document.getElementById('termo-strip11');
    offsetStrip=offsetXElement(strip);
    posTermo=e.clientX-offsetStrip-13;
    if(posTermo<0)         posTermo=0;
    else if(posTermo>536)   posTermo=536;

    termoPosEnd=posTermo;
    if(!termoInMotion){
        slideTermo11();
    }
}
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);
    }
}
function slideTermo11(){
    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 DISEÑOS */

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;

function cargarFicha(id,img){

    pos=Position.cumulativeOffset(img);
    $('ajaxLoader').style.left=(pos[0]+110)+'px';
    $('ajaxLoader').style.top=(pos[1]+90)+'px';
    $('ajaxLoader').style.display="block";

    var miAjo = new Ajax.Request(
	        'ficha.php',
	        { method: 'get',
			parameters: 'id='+id+'&sinCabecera=1',
			onComplete: fichaRecibida  }
		);
    return false;
}
function fichaRecibida(ajo){
    $("fichaAjax").innerHTML=ajo.responseText;
    if (window.attachEvent && navigator.userAgent.indexOf('MSIE 6')!=-1) correctPNG();  
    document.getElementById('disenyos').style.display="none";
    scrolea(565);
    $('ajaxLoader').style.display="none";
    tiraPos=0;
    velocidadTira=0;
    idTejidoAmpliado=0;
    totalDisenyos=parseInt($('totalDisenyos').innerHTML);
    sizexDisenyo=parseInt($('sizexDisenyo').innerHTML);
    $('muestras').style.width=(totalDisenyos * (sizexDisenyo + 15) + (783-sizexDisenyo)) +50+ "px"; //el 15 es el margin entre cada disenyo, el 783 es un extra por ancho máximo de la ampliación, 50 es un extra
}

function getIniScroll(){
    return (window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop);
}

function scrolea(end){
    ini=getIniScroll();
    steps=20;
    for(i=1;i<=steps;i++){
        paso=Math.sin(i/steps * Math.PI/2);
        setTimeout('window.scrollTo(0,'+(Math.round(ini+(end-ini)*paso ))+')',i*40);
    }
}



/* funciones de movimiento de la tira de tejidos */
var tiraPos=0;
var velocidadTira=0;

function eventoTiraMuestras(e){
    t=document.getElementById('tira_muestras');
    m=document.getElementById('muestras');

    //calculamos la posicion del ratón dentro de la tira
    posEnTira=e.clientX-offsetXElement(t);

    //La tira tiene 740 pixels. Si el ratón está cerca de los extremos, se moverá más rápido, que si está en el centro. De -3 pixes a +3 pixels de velocidad.
    nuevaVelocidad=Math.round( (740-posEnTira)/(740/6) ) -3;

    if(velocidadTira==0 && nuevaVelocidad!=0){  //arrancamos el movedor
        velocidadTira=nuevaVelocidad;
        movedorTiraMuestras();
    }else{                                      //el movedor ya estará vivo
        velocidadTira=nuevaVelocidad;
    }
}

function movedorTiraMuestras(){
    m=document.getElementById('muestras');
    tiraPos+=velocidadTira;
    
    if(tiraPos>0){     //tope izquierda
        velocidadTira=0;
        tiraPos=0;
    }
    max=(totalDisenyos * (sizexDisenyo + 15)) - 740 + (783-sizexDisenyo); //el 15 es el margin entre disenyos, el 783 es un extra por ancho máximo de la ampliación
    if(tiraPos<-max){    //tope derecha
        velocidadTira=0;
        tiraPos=-max;
    }
    m.style.left=tiraPos+"px";

    s=document.getElementById('scroll-square');
    posScroll=-Math.round(tiraPos*507/max); //regla de 3, siendo 507 el ancho del scroll
    s.style.left=posScroll+'px';

    if(velocidadTira!=0)
        setTimeout('movedorTiraMuestras()',20);
}

/* scroll gris de los tejidos */
function eventoScroll(e){
    offsetScroll=offsetXElement(document.getElementById('scroll'));
    posScroll=e.clientX-offsetScroll-13; //13 es la mitad del ancho del rectángulo negro

    if(posScroll<0)
        posScroll=0;
    else if(posScroll>507)
        posScroll=507;
 
    s=document.getElementById('scroll-square');
    s.style.left=posScroll+'px';

    max=(totalDisenyos * (sizexDisenyo + 15)) - 740 + (783-sizexDisenyo); //el 15 es el margin entre disenyos, el 783 es un extra por ancho máximo de la ampliación
    tiraPos=-Math.round(posScroll*max/507);  //507 es el ancho del scroll gris
    velocidadTira=0;
    m=document.getElementById('muestras');
    m.style.left=tiraPos+"px";
}




/*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";
    }
    // guardamos la información 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 tamaño 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";
}


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)';
}


// 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 //


