function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}
function MM_showHideLayers() { //v6.0
  var i,p,v,obj,args=MM_showHideLayers.arguments;
  for (i=0; i<(args.length-2); i+=3) if ((obj=MM_findObj(args[i]))!=null) { v=args[i+2];
                if (obj.style) { obj=obj.style; v=(v=='show')?'visible':(v=='hide')?'hidden':v; }
    obj.visibility=v; }
}
function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}
function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

// JavaScript Document
function login() {
	f = document.forms[0];
	if (f.usuari.value=="soci@22network.net" && f.contrasenya.value=="22network") {
		document.location.href="socis/index.html";
	}
	else {
		alert("Dades d'accés no vàlides");
		f.usuari.value="";
		f.contrasenya.value="";
		return false;
	}
}
function ValidarEMail(pEMail) {
    return (pEMail.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) != -1);
}
//funcio que valida quins camps volem que siguin obligatoris. Ja siguin de tipus text, textarea, checkboxes o radio
//Nomenclatura: "Nom del input"|"Nom que surtira al alert"|"Tipus"
//Utilitzar el caracter $ per comprovar dos camps alhora(arxiu_old)
function validate_submit() {
	var form_name = validate_submit.arguments[0];
	var str = "";
	var ok = false;

	for (var i = 1;i<validate_submit.arguments.length;i++) {
		var temp = validate_submit.arguments[i].split("|");
		var tipo = temp[2];
		var nom = temp[0];
		var descr = temp[1];
		var nom_alternatiu = "";
		var longitud = 0;

		if (nom.indexOf("$") >0) {
			temp = nom.split("$");
			nom = temp[0];
			nom_alternatiu = temp[1];
		}
		if (tipo.indexOf("$") >0) {
			temp = tipo.split("$");
			tipo = temp[0];
			longitud = temp[1];
		}
		switch (tipo) {
			case "text":
				ok = eval("document."+form_name+"."+nom+".value!=''");
				if (ok && longitud >0) {
					ok = eval("document."+form_name+"."+nom+".value.length >= longitud");
				}
				if (!ok && nom_alternatiu.length>0) ok = eval("ok || (document."+form_name+"."+nom_alternatiu+".value!='')");
			break;
			case "textarea": ok = eval("document."+form_name+"."+nom+".value!=''");
			break;
			case "radio":
				ok=false;
				for(var j=0;!ok && j<eval("document."+form_name+"."+nom+".length");j++){
				ok = eval("document."+form_name+"."+nom+"["+j+"].checked!=false");
				//if (!ok && nom_alternatiu.length>0) ok = eval("ok || ("+form_name+"."+nom_alternatiu+".value!='')");
				}
			break;
			case "checkbox":
				var msg = document.getElementById(nom);
				ok = (msg!=null && msg.checked!=false);
			break;
			case "select":
				ok = eval("document."+form_name+"."+nom+".value!=''");
				if (!ok && nom_alternatiu.length>0) ok = eval("ok || (document."+form_name+"."+nom_alternatiu+".value!='')");
			break;
			case "email":
				var valor = eval("document."+form_name+"."+nom+".value");
				ok = ValidarEMail(valor);
			break;
			default:
		}
		if (!ok) {if (str.length==0){str =descr} else if(str.indexOf(descr)<0){str +=","+descr}}
	}
	
	if (str.length>0) {alert("Los siguientes campos son obligatorios: "+str)} else eval("document."+form_name+".submit()");
	return false;
}

//funcio que valida quins camps volem que siguin obligatoris. Ja siguin de tipus text, textarea, checkboxes o radio
//Nomenclatura: "Nom del input"|"Nom que surtira al alert"|"Tipus"
//Utilitzar el caracter $ per comprovar dos camps alhora(arxiu_old)
function validate_not_submit() {
	var form_name = validate_not_submit.arguments[0];
	var str = "";
	var ok = false;

	for (var i = 1;i<validate_not_submit.arguments.length;i++) {
		var temp = validate_not_submit.arguments[i].split("|");
		var tipo = temp[2];
		var nom = temp[0];
		var descr = temp[1];
		var nom_alternatiu = "";
		var longitud = 0;

		if (nom.indexOf("$") >0) {
			temp = nom.split("$");
			nom = temp[0];
			nom_alternatiu = temp[1];
		}
		if (tipo.indexOf("$") >0) {
			temp = tipo.split("$");
			tipo = temp[0];
			longitud = temp[1];
		}
		switch (tipo) {
			case "text":
				ok = eval("document."+form_name+"."+nom+".value!=''");
				if (ok && longitud >0) {
					ok = eval("document."+form_name+"."+nom+".value.length >= longitud");
				}
				if (!ok && nom_alternatiu.length>0) ok = eval("ok || (document."+form_name+"."+nom_alternatiu+".value!='')");
			break;
			case "textarea": ok = eval("document."+form_name+"."+nom+".value!=''");
			break;
			case "radio":
				ok=false;
				for(var j=0;!ok && j<eval("document."+form_name+"."+nom+".length");j++){
				ok = eval("document."+form_name+"."+nom+"["+j+"].checked!=false");
				//if (!ok && nom_alternatiu.length>0) ok = eval("ok || ("+form_name+"."+nom_alternatiu+".value!='')");
				}
			break;
			case "checkbox":
				var msg = document.getElementById(nom);
				ok = (msg!=null && msg.checked!=false);
			break;
			case "select":
				ok = eval("document."+form_name+"."+nom+".value!=''");
				if (!ok && nom_alternatiu.length>0) ok = eval("ok || (document."+form_name+"."+nom_alternatiu+".value!='')");
			break;
			case "email":
				var valor = eval("document."+form_name+"."+nom+".value");
				ok = ValidarEMail(valor);
			break;
			default:
		}
		if (!ok) {if (str.length==0){str =descr} else if(str.indexOf(descr)<0){str +=","+descr}}
	}
	
	
	if (str.length>0) {alert("Los siguientes campos no son válidos: "+str)};
	return str.length==0;
}

//Funcio que comprova que la hora introduida sigui correcte
function formatFecha(valor) {
	var str=valor;
	if(str.indexOf(":")>0){		//Conte el caracter :
		fecha=str.split(":");			//Splita en 2 parts
		var hora=fecha[0];
		var minuts=fecha[1];
		if((parseInt(hora)>=24) || (isNaN(parseInt(hora)))) { alert("Hora incorrecte: "+hora); }
		if((parseInt(minuts)>=60) || (minuts.length!=2) || (isNaN(parseInt(minuts)))) { alert("Minuts incorrectes: "+minuts); }
		if(hora.length!=2) {
			var zero="0"
			hora.concat(zero)
		}
	}
	else	{ alert("Format HH:MM"); }
}

function writeToLayer(id, sHTML) {
  var el = (document.getElementById)? document.getElementById(id): (document.all)? document.all[id]: (document.layers)? document.layers[id]: null;
  if (!el) return;
  var cntnt = '<div class="info">' + sHTML + '</div>';
  if (typeof el.innerHTML!="undefined") {
      el.innerHTML = cntnt;
  } else if (document.layers) {
			el.document.write(cntnt);
			el.document.close();
  }
}

function Validate_Email_Address(email_address)
{
 //Assumes that valid email addresses consist of user_name@domain.tld
 at = email_address.indexOf('@');
 dot = email_address.lastIndexOf('.');
 if(at == -1 || 
    dot == -1 || 
    dot <= at + 1 ||
    dot == 0 || 
    dot == email_address.length - 1){
    alert("Email incorrecto");
	return(false);}
 user_name = email_address.substr(0, at);
 domain_name = email_address.substr(at + 1, email_address.length);  
 if(Validate_String(user_name) === false || 
    Validate_String(domain_name) === false)
    {alert("Email incorrecto");return(false);}
 return(true);
}


function Validate_String(string, return_invalid_chars)
         {
         valid_chars = '1234567890-_.^~abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
         invalid_chars = '';
         if(string == null || string == '')
            return(true);
         //For every character on the string.   
         for(index = 0; index < string.length; index++)
            {
            ch = string.substr(index, 1);                        
            //Is it a valid character?
            if(valid_chars.indexOf(ch) == -1)
              {
              //If not, is it already on the list of invalid characters?
              if(invalid_chars.indexOf(ch) == -1)
                {
                //If it's not, add it.
                if(invalid_chars == '')
                   invalid_chars += ch;
                else
                   invalid_chars += ', ' + ch;
                }
              }
            }                     
         //If the string does not contain invalid characters, the function will return true.
         //If it does, it will either return false or a list of the invalid characters used
         //in the string, depending on the value of the second parameter.
         if(return_invalid_chars == true && invalid_chars != '')
           {
           last_comma = invalid_chars.lastIndexOf(',');
           if(last_comma != -1)
              invalid_chars = invalid_chars.substr(0, $last_comma) + 
              ' and ' + invalid_chars.substr(last_comma + 1, invalid_chars.length);
           return(invalid_chars);
           }
         else
           return(invalid_chars == ''); 
         }




// xScrollTop r4, Copyright 2001-2009 Michael Foster (Cross-Browser.com)
// Part of X, a Cross-Browser Javascript Library, Distributed under the terms of the GNU LGPL

function xScrollTop(e, bWin)
{
  var w, offset=0;
  if (!xDef(e) || bWin || e == document || e.tagName.toLowerCase() == 'html' || e.tagName.toLowerCase() == 'body') {
    w = window;
    if (bWin && e) w = e;
    if(w.document.documentElement && w.document.documentElement.scrollTop) offset=w.document.documentElement.scrollTop;
    else if(w.document.body && xDef(w.document.body.scrollTop)) offset=w.document.body.scrollTop;
  }
  else {
    e = xGetElementById(e);
    if (e && xNum(e.scrollTop)) offset = e.scrollTop;
  }
  return offset;
}

// xGetElementById r2, Copyright 2001-2007 Michael Foster (Cross-Browser.com)
// Part of X, a Cross-Browser Javascript Library, Distributed under the terms of the GNU LGPL

function xGetElementById(e)
{
  if(typeof(e)=='string') {
    if(document.getElementById) e=document.getElementById(e);
    else if(document.all) e=document.all[e];
    else e=null;
  }
  return e;
}

// xNum r2, Copyright 2001-2007 Michael Foster (Cross-Browser.com)
// Part of X, a Cross-Browser Javascript Library, Distributed under the terms of the GNU LGPL

function xNum()
{
  for(var i=0; i<arguments.length; ++i){if(isNaN(arguments[i]) || typeof(arguments[i])!='number') return false;}
  return true;
}

// xDef r1, Copyright 2001-2007 Michael Foster (Cross-Browser.com)
// Part of X, a Cross-Browser Javascript Library, Distributed under the terms of the GNU LGPL

function xDef()
{
  for(var i=0; i<arguments.length; ++i){if(typeof(arguments[i])=='undefined') return false;}
  return true;
}


// xTop r2, Copyright 2001-2007 Michael Foster (Cross-Browser.com)
// Part of X, a Cross-Browser Javascript Library, Distributed under the terms of the GNU LGPL

function xTop(e, iY)
{
  if(!(e=xGetElementById(e))) return 0;
  var css=xDef(e.style);
  if(css && xStr(e.style.top)) {
    if(xNum(iY)) e.style.top=iY+'px';
    else {
      iY=parseInt(e.style.top);
      if(isNaN(iY)) iY=xGetComputedStyle(e,'top',1);
      if(isNaN(iY)) iY=0;
    }
  
  }
  else if(css && xDef(e.style.pixelTop)) {
    if(xNum(iY)) e.style.pixelTop=iY;
    else iY=e.style.pixelTop;
  }
  return iY;
}

// xGetComputedStyle r7, Copyright 2002-2007 Michael Foster (Cross-Browser.com)
// Part of X, a Cross-Browser Javascript Library, Distributed under the terms of the GNU LGPL

function xGetComputedStyle(e, p, i)
{
  if(!(e=xGetElementById(e))) return null;
  var s, v = 'undefined', dv = document.defaultView;
  if(dv && dv.getComputedStyle){
    s = dv.getComputedStyle(e,'');
    if (s) v = s.getPropertyValue(p);
  }
  else if(e.currentStyle) {
    v = e.currentStyle[xCamelize(p)];
  }
  else return null;
  return i ? (parseInt(v) || 0) : v;
}

// xCamelize r1, Copyright 2007-2009 Michael Foster (Cross-Browser.com)
// Part of X, a Cross-Browser Javascript Library, Distributed under the terms of the GNU LGPL

function xCamelize(cssPropStr)
{
  var i, c, a, s;
  a = cssPropStr.split('-');
  s = a[0];
  for (i=1; i<a.length; ++i) {
    c = a[i].charAt(0);
    s += a[i].replace(c, c.toUpperCase());
  }
  return s;
}


// xStr r1, Copyright 2001-2007 Michael Foster (Cross-Browser.com)
// Part of X, a Cross-Browser Javascript Library, Distributed under the terms of the GNU LGPL

function xStr(s)
{
  for(var i=0; i<arguments.length; ++i){if(typeof(arguments[i])!='string') return false;}
  return true;
}

// xOffsetTop r1, Copyright 2001-2007 Michael Foster (Cross-Browser.com)
// Part of X, a Cross-Browser Javascript Library, Distributed under the terms of the GNU LGPL

function xOffsetTop(e)
{
  if (!(e=xGetElementById(e))) return 0;
  if (xDef(e.offsetTop)) return e.offsetTop;
  else return 0;
}


function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}
function showhide(layer_ref, estado) {
	obj = MM_findObj(layer_ref);
	if (estado!=null) {
		loading_state=estado;
	} else {
		loading_state = obj.style.visibility;
		if (loading_state == 'visible') {
			loading_state = 'hidden';
		}
		else {
			loading_state = 'visible';
		}
	}
	
	if (document.layers) { //IS NETSCAPE 4 or below
		document.layers[layer_ref].visibility = loading_state;
	}
	if (document.getElementById && !document.all) {
		maxwell_smart = document.getElementById(layer_ref);
		maxwell_smart.style.visibility = loading_state;
	}
	xTop(layer_ref,xOffsetTop(layer_ref)+document.documentElement.scrollTop);


}

function isInt(x) {
   var y=parseInt(x);
   if (isNaN(y)) return false;
   return x==y && x.toString()==y.toString();
}

function validar_unidades(se_repone,enviar) {
	if (document.forms['f1'].cantidad.value=="" || isNaN(document.forms['f1'].cantidad.value)) {
		alert("Debes introducir una cantidad");
		document.forms['f1'].cantidad.focus();
		return false;
	}
	if(document.forms['f1'].cantidad.value <= 0 || !isInt(document.forms['f1'].cantidad.value)){
		alert(document.forms['f1'].cantidad.value+" no es una cantidad válida");
		return false;
	}
	if (!se_repone) {
		if (cas==2) {
			color = document.forms['f1'].id_color[document.forms['f1'].id_color.selectedIndex].value;
			unidades_disponibles = arr_unidades[color];
		}
		if (cas==3) {
			color = document.forms['f1'].id_color[document.forms['f1'].id_color.selectedIndex].value;
			talla = document.forms['f1'].id_grupo_tallas[document.forms['f1'].id_grupo_tallas.selectedIndex].value;
			//alert(color+" "+talla);
			unidades_disponibles = arr_colores[color][talla];
		}
		if (cas==4) {
			talla = document.forms['f1'].id_grupo_tallas[document.forms['f1'].id_grupo_tallas.selectedIndex].value;
			unidades_disponibles = arr_unidades[talla];
		}
		if (document.forms['f1'].cantidad.value>unidades_disponibles) {
			if (unidades_disponibles <= 0) alert("El producto está agotado para esta configuración del producto");
			else alert("Sólo disponemos de "+unidades_disponibles+" unidades disponibles para esta configuración del producto");
			document.forms['f1'].cantidad.value=(unidades_disponibles>0?unidades_disponibles:0);
			document.forms['f1'].cantidad.focus();
			return false;
		}
	}
	if (enviar) document.f1.submit();
	return true;
}
function deshabilitar(id){
	obj=document.getElementById(id);
	obj.disabled = "disabled";
}
function habilitar(id){
	obj=document.getElementById(id);
	obj.disabled = "";
}
