/*

Global JS

*/


/* Window Popper */

function pop(u,n,f, w, h, c) {
  if(window.screen)if(c)if(c=="1"){
    var l = (screen.width-w)/2;
    var t = (screen.height-h)/2;
    f+=(f!='')?',':'';
    f+='left='+l+',top='+t;
  }
  flop=window.open(u,n,f+((f!='')?',':'')+'width='+w+',height='+h);
  flop.focus();
}


/* Switch Div */

function switchDiv(divNum){
	x=document.getElementById("s" + divNum);
	y=document.getElementById("i" + divNum);
	if(x.style.display != "block"){
		x.style.display="block";
		y.src="img/menuOpen.gif";
	}else{
		x.style.display="none";
		y.src="img/menuClosed.gif";
    }
}


/* The xRollovers */

function xOn(theId) {
	xfile=document.getElementById(theId)
	xname=xfile.getAttribute('src')
	x=xname.length
	xext=xname.substring(x-4,xname.length)
	xname=xname.substring(0,x-4)
	xfile.src=xname+".on"+xext
}

function xOff(theId) {
	xfile=document.getElementById(theId)
	xname=xfile.getAttribute('src')
	x=xname.length
	xext=xname.substring(x-4,xname.length)
	xname=xname.substring(0,x-7)
	xfile.src=xname+xext
}


/* Cookie Recipes */

function saveCookie(name,value,days) {
        if (days) {
                var date = new Date();
                date.setTime(date.getTime()+(days*24*60*60*1000))
                var expires = "; expires="+date.toGMTString()
        }
        else expires = ""
        document.cookie = name+"="+value+expires+"; path=/"
}

function readCookie(name) {
        var nameEQ = name + "="
        var ca = document.cookie.split(';')
        for(var i=0;i<ca.length;i++) {
                var c = ca[i];
                while (c.charAt(0)==' ') c = c.substring(1,c.length)
                if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length)
        }
        return null
}

function deleteCookie(name) {
        saveCookie(name,"",-1)
}


/* Event Listener Interface */

function addEvent(obj, evType, fn, useCapture){
  if (obj.addEventListener){
    obj.addEventListener(evType, fn, useCapture);
    return true;
  } else if (obj.attachEvent){
    var r = obj.attachEvent("on"+evType, fn);
    return r;
  } else {
    //alert("Handler could not be attached");
  }
}

function removeEvent(obj, evType, fn, useCapture){
  if (obj.removeEventListener){
    obj.removeEventListener(evType, fn, useCapture);
    return true;
  } else if (obj.detachEvent){
    var r = obj.detachEvent("on"+evType, fn);
    return r;
  } else {
    //alert("Handler could not be removed");
  }
}


/* 	Limita el texto introducido en un TEXTAREA 

	La función debe ser llamada desde el TEXTAREA con un 'onkeyup', por ejemplo:
		<textarea name="nombreCampo" cols="40" rows="5" onkeyup="limitaTextarea(this,250)">	
	Como parámetros le pasamos 'this' para este campo y el máximo de caracteres
*/

function limitaTextarea(campo, maximo) {
	campo.value = campo.value.slice(0, maximo)
}

function var_dump(obj){
    info="<table border='1'>";
    for( el in obj)
        info+="<tr><td valign='top'><strong>"+el+"</strong></td><td>"+obj[el]+"</td></tr>";
    info+="</table>";
    nueva=window.open();
    nueva.document.write(info);
}


//Corregir PNG en Explorer
function correctPNG() 
   {
   for(var i=0; i<document.images.length; i++)
      {
	  var img = document.images[i]
	  var imgName = img.src.toUpperCase()
	  if (imgName.substring(imgName.length-3, imgName.length) == "PNG")
	     {
		 var imgID = (img.id) ? "id='" + img.id + "' " : ""
		 var imgClass = (img.className) ? "class='" + img.className + "' " : ""
		 var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
		 var imgStyle = "display:inline-block;" + img.style.cssText 
		 if (img.align == "left") imgStyle = "float:left;" + imgStyle
		 if (img.align == "right") imgStyle = "float:right;" + imgStyle
		 if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle		
		 var strNewHTML = "<span " + imgID + imgClass + imgTitle
		 + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
	     + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
		 + "(src=\'" + img.src + "\', sizingMethod='image');\"></span>" 
		 img.outerHTML = strNewHTML
		 i = i-1
	     }
      }
   }

if (window.attachEvent && navigator.userAgent.indexOf('MSIE 6')!=-1) window.attachEvent("onload", correctPNG);



function abreSeccion(id,claseAOcultar){
    obj=document.getElementById(id);

    if(obj.style.display=="block"){
        obj.style.display="none";

    }else{
        resto=document.getElementById('articles').getElementsByTagName('DIV');
        for(i=0;i<resto.length;i++){
            if(resto[i].className==claseAOcultar)
                resto[i].style.display="none";
        }
        obj.style.display="block";
    }    

    return false;
}

function addToTheBasket(id,nombre,precio,imagenURL){
    divbasket=document.getElementById('basket');
    divitem=document.getElementById('order-'+id);
    if(divitem){
        inputobj=divitem.getElementsByTagName('INPUT')[0];
        valor=parseInt(inputobj.value)+1;
        inputobj.value=valor.toString();
    }else{
        divitem=document.createElement('DIV');
        divitem.id="order-"+id;    
        divbasket.appendChild(divitem);
        
        iconos="";
        if(imagenURL.length)
            iconos='<a href="'+imagenURL+'" target="_blank" title="See the picture"><img src="img/lupa.gif" style="border:0"/></a> ';
        iconos+='<img src="img/trashcan.gif" title="Delete item" alt="Delete item" onclick="borraItem(this)"/>';
        
        divitem.innerHTML=' <span class="precio" id="precio-'+id+'">'+parseFloat(precio).toFixed(2)+' &euro;</span> '+
                        '<input type="text" name="order['+id+']" id="cantidad-'+id+'" value="1" onkeyup="actualizaPrecio()"/> '+
                        '<span class="referencia">Ref.'+id+'</span> | <span class="articulo">'+nombre+'</span> '+
                        iconos;
    }

    actualizaPrecio();
}

function actualizaPrecio(){
    divbasket=document.getElementById('basket');
    spans=divbasket.getElementsByTagName('SPAN');
    precio= new Object();
    for(i=0;i<spans.length;i++){
        if(spans[i].className=="precio"){
            id=spans[i].id.substring(7);
            precio[id]=parseFloat(spans[i].innerHTML);
        }
    }
    var total=0.00;
    for(id in precio){
        cantidad=parseInt(document.getElementById('cantidad-'+id).value);
        if(isNaN(cantidad))
            cantidad=0;
        total+=cantidad*precio[id];
    }
    document.getElementById('total').innerHTML='Total: '+total.toFixed(2)+' &euro;';
}

function borraItem(obj){
    obj.parentNode.parentNode.removeChild(obj.parentNode);
    actualizaPrecio();
}

