/*
 * 	Functions js
 * 	Necessita prototype
 */

// canvia la quantitat d'un producte a la pàgina de
// customer.cart.view.php
function customerAddProduct(idProduct) {
	var quantity = $F('units-'+idProduct);
	
	
	var param = 'cantidad=' + quantity + '&id_product=' + idProduct + '&return=customer_cart';
	var url = 'customer.cart.add.php';
	 
	var ajaxRequest = new Ajax.Request(
                        url,
                        {
                                method: 'get',
                                parameters: param,
                                asynchronous: true,
                                onComplete: showResponse

                        });

function showResponse(xmlHttpRequest, responseHeader)
{// Función que recibe el resultado de la petición
	
	
}
	

}

 /* validateForm: Comprova els camps buits i els númerics. Si tot està correcte, envia les dades del formulari  */
function validateForm()
{
	var error=false;
	var errorMessage="";
	
	var numbers=document.getElementsByClassName('number-text');
	var noEmptys=document.getElementsByClassName('no-empty-text');
	
	for (var i=0; i< numbers.length; i++)
	{
		
		if (checkInt(numbers[i].value)) 
		{
			
			$('message').style.display='block';
			$(numbers[i]).style.border='1px solid red';
			
			// para obtener el nombre se debe coger el valor del label del input. El id del label se compone de "label-" mas el id del input.
			errorMessage+="<div>El campo <strong>"+$('label-'+numbers[i].id).innerHTML +"</strong> debe ser numerico</div>";
			error=true;
		}
	}
	
	for (var i=0; i < noEmptys.length; i++)
	{
		if (checkEmpty(noEmptys[i].value)) 
		{
			$('message').style.display='block';
			$(noEmptys[i]).style.border='1px solid red';
			errorMessage+="<div>El campo <strong>"+$('label-'+noEmptys[i].id).innerHTML +"</strong> no puede estar vacio</div>";
			error=true;
		}
	}
	
	
	
	if (error)
	{
		$('message').innerHTML=errorMessage;
	}
	
	if (error==false)
	{
		document.getElementById('form').submit();
	}
}

function validateEditForm() {
	var error = false;
	var noEmptys = document.getElementsByClassName('no-empty-text');
	var noNumber = document.getElementsByClassName('no-number-text');
	
	// valida els camps buits
	/*
	for (i=0; i<noEmptys.length; i++) {
		if (checkEmpty(noEmptys[i].value)) {
			$('alert-'+noEmptys[i].id).style.display='block';
			error=true;
		} else {
			$('alert-'+noEmptys[i].id).style.display='none';
		}
	}
	*/
	
	// valida els camps numerics
	for (i=0; i<noNumber.length; i++) {
		if (checkInt(noNumber[i].value)) {
			$('alert-'+noNumber[i].id).style.display='block';
			error=true;
		} else {
			$('alert-'+noNumber[i].id).style.display='none';
		}
	}
	
	// valida telefon
	var phone = $('phone').value;
	if (phone.length != 9 || !isInteger(phone)) {
		$('alert-phone2').style.display='block';
		error=true;
	} else {
		$('alert-phone2').style.display='none';
	}
	
	// valida cp
	var cp = $('cp').value;
	if (cp.length != 5 || !isInteger(cp)) {
		$('alert-cp').style.display='block';
		error=true;
	} else {
		$('alert-cp').style.display='none';
	}
	
	// valida email
	var email = $('email').value;
	if (!isValidEmail(email)) {
		$('alert-email').style.display='block';
		error=true;
	} else {
		$('alert-email').style.display='none';
	}
	
	
	if (error==false) {
		document.getElementById('edit-form').submit();
	}
} 
 
/* comprova si es buit  */  
function checkEmpty(q) {
        for ( i = 0; i < q.length; i++ ) {  
                if ( q.charAt(i) != " " ) {  
                        return false  
                }  
        }  
        return true
	//return !isNaN(valor);
}

function isInteger (s) {
      var i;

      if (isEmpty(s))
      if (isInteger.arguments.length == 1) return 0;
      else return (isInteger.arguments[1] == true);

      for (i = 0; i < s.length; i++)
      {
         var c = s.charAt(i);

         if (!isDigit(c)) return false;
      }

      return true;
}

function isEmpty(s) {
	return ((s == null) || (s.length == 0))
}

function isDigit (c) {
	return ((c >= "0") && (c <= "9"))
}

function isValidEmail(str) {
	return (str.indexOf(".") > 2) && (str.indexOf("@") > 0);
}


/* comprova si es enter */ 
/* false -> no error*/
/* true -> error */
function checkInt(valor)
{
	
	// 1 si esta vacio dejamos pasar
	if (!isNaN(valor)) {	return false; }	
	else
	{
		//si era un entero no le afecta, si no lo era lo intenta convertir
		valor = parseInt(valor);
		if (isNaN(valor)) 	{	return true;	}	// En caso de no ser valor numerico, el parseInt no devuelve nada
		else				{   return false;	} 	// En caso contrario (Si era un número) devuelvo cierto
	}
  
} 
function resize(id,width,height)
{
  
  $(id).width=width;
  $(id).height=height;
}

function getMes(id) {
var mes="";
    switch (id) {
        case 0 : mes="Gener"; break;
        case 1 : mes="Febrer"; break; 
        case 2 : mes="Març"; break; 
        case 3 : mes="Abril"; break; 
        case 4 : mes="Maig"; break; 
        case 5 : mes="Juny"; break; 
        case 6 : mes="Juliol"; break; 
        case 7 : mes="Agost"; break; 
        case 8 : mes="Setembre"; break; 
        case 9 : mes="Octubre"; break; 
        case 10 : mes="Novembre"; break;
        case 11 : mes="Desembre"; break; 
    }
    return mes;
}

function montre(id) {
var d = document.getElementById(id);
	for (var i = 1; i<=10; i++) {
		if (document.getElementById('smenu'+i)) {
		document.getElementById('smenu'+i).style.display='none';}
	}
if (d) {d.style.display='block';}
}
function setUploadFlash()
{
	if ( hasProductInstall && !hasRequestedVersion ) {
  var MMPlayerType = (isIE == true) ? "ActiveX" : "PlugIn";
  var MMredirectURL = window.location;
    document.title = document.title.slice(0, 47) + " - Flash Player Installation";
    var MMdoctitle = document.title;

  AC_FL_RunContent(
    "src", "flash/playerProductInstall",
    "FlashVars", "MMredirectURL="+MMredirectURL+'&MMplayerType='+MMPlayerType+'&MMdoctitle='+MMdoctitle+"",
    "width", "420",
    "height", "240",
    "align", "middle",
    "id", "flashFileHelper",
    "quality", "high",
    "bgcolor", "#ffffff",
    "name", "flashFileHelper",
    "allowScriptAccess","sameDomain",
    "type", "application/x-shockwave-flash",
    "pluginspage", "http://www.adobe.com/go/getflashplayer"
  );
} else if (hasRequestedVersion) {
  // if we've detected an acceptable version
  // embed the Flash Content SWF when all tests are passed
  AC_FL_RunContent(
      "src", "flash/flashFileHelper",
      "width", "420",
      "height", "240",
      "align", "middle",
      "id", "flashFileHelper",
      "quality", "high",
      "bgcolor", "#ffffff",
      "name", "flashFileHelper",
      "flashvars",'fileLabel=Image+Files&fileExtensions=%2A.gif%3B%2A.png%3B%2A.jpg&maximumFileBytes=5242880&maximumFilesOnServer=500&maximumBytesOnServer=524288000&flashCSS=flash%2Fcss%2Fsiu.swf&uploadURL=demo%2Fupload_file.php&removeFileURL=demo%2Fremove_files.php&width=420&height=240&applicationToken=&fileListURL=%2Fmulti_bit_shift_php_plugin%2Ffiles_on_server.php&renameFileURL=%2Fmulti_bit_shift_php_plugin%2Frename_file.php&doneURL=%2Findex.php',
      "allowScriptAccess","sameDomain",
      "type", "application/x-shockwave-flash",
      "pluginspage", "http://www.adobe.com/go/getflashplayer"
  );
  } else {  // flash is too old or we can't detect the plugin
    var alternateContent = 'Alternate HTML content should be placed here. '
    + 'This content requires the Adobe Flash Player. '
    + '<a href=http://www.adobe.com/go/getflash/>Get Flash</a>';
    document.write(alternateContent);  // insert non-flash content
  }
	
}


function startList(){
	if (document.all&&document.getElementById) {
		navRoot = document.getElementById("nav");
		for (i=0; i<navRoot.childNodes.length; i++) {
			node = navRoot.childNodes[i];
			if (node.nodeName=="LI") {
				node.onmouseover=function() {
					this.className+=" over";
				}
				node.onmouseout=function() {
					this.className=this.className.replace(" over", "");
				}
			}
		}
	}
}


function printDate() {
    Fecha = new Date();
    document.write(Fecha.getDate()+' de ');
    document.write(getMes(Fecha.getMonth())+' de ');
    document.write(Fecha.getFullYear());
}

function startTime()
{
    var today=new Date()
    var h=today.getHours()
    var m=today.getMinutes()
    var s=today.getSeconds()
    // add a zero in front of numbers<10
    m=checkTime(m)
    s=checkTime(s)
    document.getElementById('hora').innerHTML=h+":"+m+":"+s
    t=setTimeout('startTime()',500)
}

function checkTime(i)
{
    if (i<10) 
      {i="0" + i}
      return i
}



function aceptar(mensage)
{
	if (confirm(mensage)) return true; 
	else return false;
}


function toggle(idCheckbox, idElement) {
	if ($(idCheckbox).checked=='checked') {
		$(idElement).style.display='block';
	} else {
		$(idElement).style.display='none';
	}
}


function addProductCart(idProduct) {
	$('id_product').value = idProduct;
	$('operation').value = 'add';
	$('search_add_product').submit();
}

function removeProductCart(idProduct) {
	$('id_product').value = idProduct;
	$('operation').value = 'remove';
	$('search_add_product').submit();
}

/**
 * Funcio que mostra i amaga les respostes del FAQ
 * @param {Object} index
 */
function showAnswer(index) {
	if ($('question'+index).className == 'row question_resolved') {
		$('question'+index).className = 'row question';
		$('answer'+index).style.display = 'none';
	} else {
		$('question'+index).className = 'row question_resolved';
		$('answer'+index).style.display = 'block';	
	}
}

/**
 * Comprova que com a mínim hi hagi una foto seleccionada
 */
function checkCart() {
	
	// mirem que com a minim hi hagi una seleccionada 
	count = 1;
	error = false;
	while (checkPhotos("quantity_photos"+count) != -1) {
		if (checkPhotos("quantity_photos"+count) == 0) {
			error = true;		
		} 
		count++;	
	}
	if (error == false) {
		$("edit-form2").submit();
		return true;
	}
	// en cas que no hagi seleccionat cap fotografia mostrem un missatge d'avis
	alert($("please_select_photo").value);
	
	
		
}
/**
 * retorna 1 es trobat
 * retorna 0 no es trobat
 * retorna -1 no existeix
 * @param {Object} id
 */
function checkPhotos(id) {
	var count = 0;
	
	var selects = document.getElementsByClassName(id);
	if (selects.length > 0) {
		for (i=0; i<selects.length; i++) {
			if (selects[i].value > 0) {
				return 1;
			}
		}	
		return 0;
	} else {
		return -1;
	}
	
}

/* Funcion autoejecutable */
( 
	function() 
	{ 
		function addEvent( obj, type, fn )
		{  
			if (obj.addEventListener)
			{  
				obj.addEventListener( type, fn, false ); 
			} 
			else if (obj.attachEvent)
			{  
				obj["e"+type+fn] = fn;  
				obj[type+fn] = function(){ obj["e"+type+fn]( window.event ); }  
				obj.attachEvent( "on"+type, obj[type+fn] );  
			}  
		}  
  
	addEvent(window, 'load', startList); 
   } 
)(); 