function FocusField(formInst,elementInst){
	if(document.forms.length>0){document.forms[formInst].elements[elementInst].focus();}
}

/*========================================================
Validación de formulario basica
onSubmit="MM_validateForm('nombre','','R','ciudad','','R','email','','RisEmail','usuario','','R','password1','','R','password2','','R');return document.MM_returnValue"
=========================================================*/

function MM_findObj(n,d){
	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_validateForm(){
	var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
	for(i=0;i<(args.length-2);i+=3){
		test=args[i+2];val=MM_findObj(args[i]);
		if(val){
			nm=val.name;
			if((val=val.value)!=""){
				if(test.indexOf('isEmail')!=-1){
					p=val.indexOf('@');
					if(p<1||p==(val.length-1))errors+='- '+nm+' must contain an e-mail address.\n';
				}else if(test.indexOf('checklegal')!=-1){
					
				}else if(test!='R'){
					num=parseFloat(val);
					if(isNaN(val))errors+='- '+nm+' must contain a number.\n';
					if(test.indexOf('inRange')!=-1){
						p=test.indexOf(':');
						min=test.substring(8,p);max=test.substring(p+1);
						if(num<min||max<num)errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';
					}
				}
				if(test.indexOf('isDataActual')!=-1){
					var v_DateErrors=isValidDate();
					if (v_DateErrors) {errors=v_DateErrors;}
				}
				if(test.indexOf('checklegal')!=-1){
					if (document.formPost.condiciones.checked == false){errors+='Para continuar debe aceptar las condiciones legales.';}i
				}
			}else if(test.charAt(0)=='R'){
				errors+=' \n';
			}
		}
	}
	if(errors){alert('ATENCIÓ: Heu d\'omplir tots els camps marcats amb *\n'+errors);
	document.MM_returnValue=(errors=='');} else { document.MM_returnValue=(submitonce(1)); }
}

function getZonesList(sel){
	var countryCode = sel.options[sel.selectedIndex].value;
	document.getElementById('id_zone').options.length = 0;
	if(countryCode.length>0){
		contentObj = document.getElementById('id_zone');
		ajax.requestFile = webroot+'js/GetZones.php?id_country='+countryCode;
		//ajax.onLoading = contentObj.innerHTML = 'Loading list, please wait...';
		ajax.onLoading = ShowLoadingSel;
		ajax.onCompletion = createZones;
		ajax.runAJAX();
	}
}

function createZones()
{
	var obj = document.getElementById('id_zone');
	document.getElementById('id_zone').options.length = 0;
	eval(ajax.response);
}




function getZonesList_S(sel)
{
	var countryCode = sel.options[sel.selectedIndex].value;
	document.getElementById('id_zone_Sf').options.length = 0;
	if(countryCode.length>0){
		contentObj = document.getElementById('id_zone_Sf');
		ajax.requestFile = common_js+'GetZones.php?id_country='+countryCode;
		ajax.onLoading = eval("contentObj.options[contentObj.options.length] = new Option('Loading...','0');");
		ajax.onCompletion = createZones_S;
		ajax.runAJAX();
	}
}

function createZones_S()
{
	var obj = document.getElementById('id_zone_Sf');
	document.getElementById('id_zone_Sf').options.length = 0;
	eval("obj.options[obj.options.length] = new Option('...Todas','Todas');"+ajax.response);
}

function getProvincesList(sel, path){
	var provinceCode = sel.options[sel.selectedIndex].value;
	document.getElementById('id_loc_province').options.length = 0;
	document.getElementById('id_loc_city').options.length = 0;
	if(provinceCode.length>0){
		contentObj = document.getElementById('id_loc_province');
		ajax.requestFile = path+'js/GetProvinces.php?id_zone='+provinceCode;
		ajax.onLoading = eval("contentObj.options[contentObj.options.length] = new Option('Actualizando...','0');");
		ajax.onCompletion = createProvinces;
		ajax.runAJAX();
	}
}
function createProvinces(){
	var obj = document.getElementById('id_loc_province');
	document.getElementById('id_loc_province').options.length = 0;
	eval(ajax.response);
}

function getCitiesList(sel, path){
	var cityCode = sel.options[sel.selectedIndex].value;
	document.getElementById('id_loc_city').options.length = 0;
	if(cityCode.length>0){
		contentObj = document.getElementById('id_loc_city');
		ajax.requestFile = path+'js/GetCities.php?id_loc_province='+cityCode;
		ajax.onLoading = eval("contentObj.options[contentObj.options.length] = new Option('Actualizando...','0');");
		ajax.onCompletion = createCities;
		ajax.runAJAX();
	}
}
function createCities(){
	var obj = document.getElementById('id_loc_city');
	document.getElementById('id_loc_city').options.length = 0;
	eval(ajax.response);
}

function getZonesList_S(sel)
{
	var countryCode = sel.options[sel.selectedIndex].value;
	document.getElementById('id_zone_Sf').options.length = 0;
	if(countryCode.length>0){
		contentObj = document.getElementById('id_zone_Sf');
		ajax.requestFile = common_js+'GetZones.php?id_country='+countryCode;
		ajax.onLoading = eval("contentObj.options[contentObj.options.length] = new Option('Loading...','0');");
		ajax.onCompletion = createZones_S;
		ajax.runAJAX();
	}
}

function createZones_S()
{
	var obj = document.getElementById('id_zone_Sf');
	document.getElementById('id_zone_Sf').options.length = 0;
	eval("obj.options[obj.options.length] = new Option('...Todas','Todas');"+ajax.response);
}

function OnlyNum(myfield,e){
var keycode;
if (window.event) keycode = window.event.keyCode;
else if (e) keycode = e.which;
else return true;
if (keycode == 13) {
		var i;
		for (i = 0; i < myfield.form.elements.length; i++)
			if (myfield == myfield.form.elements[i])
				break;
		i = (i + 1) % myfield.form.elements.length;
		myfield.form.elements[i].focus();
		return false;
	} 
else
if (((keycode>47) && (keycode<58) )  || (keycode==46) || (keycode==44) || (keycode==45) || (keycode==8) || (keycode == 13)) {EnableSave(); return true;}
else return false;
}

function NoKeyReturn(myfield,e){
	var keycode;
	if (window.event) keycode = window.event.keyCode;
	else if (e) keycode = e.which;
	else return true;
	if (keycode == 13) {
			var i;
			for (i = 0; i < myfield.form.elements.length; i++)
				if (myfield == myfield.form.elements[i])
					break;
			i = (i + 1) % myfield.form.elements.length;
			myfield.form.elements[i].focus();
			return false;
	} 
	
}
function submitonce(valor){
	if (valor==1) {
		document.getElementById('SubmitButton').style.display="none"
		document.getElementById('ProcessMsg').style.display="block"
	} else {
		document.getElementById('SubmitButton').style.display="block"
		document.getElementById('ProcessMsg').style.display="none"
	}
}

// JavaScript Document
/*
Open Centered Popup Window Script-
© DHTML Shock (www.dhtmlshock.com)
To add more shock to your site, visit www.DHTML Shock.com
*/
function OpenBrWindow(theURL,winName,features,myWidth,myHeight,isCenter){//v3.0
if(window.screen)if(isCenter)if(isCenter=="true"){
var myLeft=(screen.width-myWidth)/2;
var myTop=(screen.height-myHeight-120)/2;
features+=(features!='')?',':'';
features+=',left='+myLeft+',top='+myTop;
}
window.open(theURL,winName,features+((features!='')?',':'')+'width='+myWidth+',height='+myHeight);
}
function RefrescarCerrar()
{
window.opener.location.reload();
window.close()
}
function CerrarVentana()
{
window.close()
}
function RedireccionarCerrar(r_url)
{
window.opener.location=r_url;
window.close()
}

function toggleDisplay() {
var elements = Array.prototype.slice.call(arguments);
arrayEach(elements, function (arg) {
var element = ref(arg);
if (element) {
element.style.display = (element.style.display != "none" ? "none" : "");
}
});
}

function toggleDispOnLoad(r_id_bloc, r_cookie){
	//var elements = Array.prototype.slice.call(arguments);
	//alert(elements);
	//arrayEach(elements, function (arg) {
		//var element = ref(arg);
		
		if (Get_Cookie(r_cookie)==0){
			//element.style.display="none";
			document.getElementById(r_id_bloc).style.display="none";
			document.getElementById(r_id_bloc+'open').style.display="none";
			document.getElementById(r_id_bloc+'closed').style.display="";
		}else{
			//alert(arg);
			//element.style.display="";
			document.getElementById(r_id_bloc).style.display="";
			document.getElementById(r_id_bloc+'open').style.display="";
			document.getElementById(r_id_bloc+'closed').style.display="none";
		}
	//});
}
function toggleDisplayJQ(r_id) {
	//$("#aj_blk"+r_id+"open").hide();
	//$("#loading_"+r_id).show();
	$("#"+r_id).toggle("fast");
	$("."+r_id+"openclose").toggle();
}

function arrayEach(array, func) {
for (var i = 0; i < array.length; i++) func(array[i]);
}

function ref(instance_or_id) {
return (typeof(instance_or_id) == "string") ? document.getElementById(instance_or_id) : instance_or_id;
}

// onclick="Set_Cookie( 'IdIngredientOpen' , '{{IdIngredient}}' , 0 , '/' , false );"
function Set_Cookie(name,value,expires,path,domain,secure) {
	var cookieString = name + "=" +escape(value) +
   ( (expires) ? ";expires=" + expires.toGMTString() : "") +
   ( (path) ? ";path=" + path : "") +
   ( (domain) ? ";domain=" + domain : "") +
   ( (secure) ? ";secure" : "");
	document.cookie = cookieString;
}

//t.SetVariable "OpenedFolders", "<script type='text/javascript'>toggleDispOnLoad('d'+Get_Cookie('IdIngredientOpen'));"
function Get_Cookie(name) {
   var start = document.cookie.indexOf(name+"=");
   var len = start+name.length+1;
   if ((!start) && (name != document.cookie.substring(0,name.length))) return null;
   if (start == -1) return null;
   var end = document.cookie.indexOf(";",len);
   if (end == -1) end = document.cookie.length;
   return unescape(document.cookie.substring(len,end));
} 
function tczShowAjaxJQ(sUrl, DIVdestino, JS_action_1, JS_action_2){
	if(JS_action_1=='JToggle'){
		$("."+DIVdestino+'openclose').toggle();
	}
	$("#"+DIVdestino).fadeTo("fast",0.40);
	$.ajax({
		method:"get",url: sUrl,
		success:function(html){
			$("#"+DIVdestino).html(html);
			//$("#"+DIVdestino).effect("highlight", {}, 2000);
			$("#"+DIVdestino).show();
			$("#"+DIVdestino).fadeTo("slow",1.0);
			//$('#AjaxForm').validate();
			if(JS_action_2=='fancybox'){
				$(".galleryMagnify a").fancybox({"hideOnContentClick":true,"overlayColor":"#000"});
			}
		}
	});
}

function load_google_map(r_initLat,r_initLong,r_zoom,r_map_type){
	if (GBrowserIsCompatible()){
		if(r_zoom==undefined){r_zoom=15;}
        var map = new GMap2(document.getElementById("GMap"));
        map.addControl(new GLargeMapControl());
        map.addControl(new GMapTypeControl());
        var center = new GLatLng(r_initLat,r_initLong);
        map.setCenter(center,parseFloat(r_zoom));
        switch(r_map_type){
        	case "":
        	map.setMapType(G_NORMAL_MAP);
        	break;
        	case "1":
        	map.setMapType(G_NORMAL_MAP);
        	break;
        	case "2":
        	map.setMapType(G_SATELLITE_MAP);
        	break;
        	case "3":
        	map.setMapType(G_HYBRID_MAP);
        	break;
        }
        geocoder = new GClientGeocoder();
        var marker = new GMarker(center, {draggable: false});  
        map.addOverlay(marker);
	}
}

function TczJQWindow(sUrl,r_width,r_title){
	/*$.blockUI({css:{
		border:'none',padding:'15px',backgroundColor:'#000', 
		'-webkit-border-radius':'10px','-moz-border-radius':'10px',opacity: .8,color: '#fff'},
		overlayCSS:{opacity:0},
		message:'<p>Obteniendo datos...</p>'
	}); */
	$('#Dialogo').load(sUrl,function(){
	$('#Dialogo').dialog({
		title:r_title,
		width:r_width,
		resizable:false,
		modal:true,
		open:function(){
			//$.unblockUI();
			
		},
		close:function(){$(this).dialog('destroy');}
    });
});
}

function TczJQWindowUpload(sUrl,r_width,r_title,r_id_item,r_url_dest,r_IdDivDest,r_type){
	/*$.blockUI({css:{
		border:'none',padding:'15px',backgroundColor:'#000', 
		'-webkit-border-radius':'10px','-moz-border-radius':'10px',opacity: .8,color: '#fff'},
		overlayCSS:{opacity:0},
		message:'<p>Obteniendo datos...</p>'
	}); */
	$('#Dialogo').load(sUrl,function(){
	$('#Dialogo').dialog({
		title:r_title,
		width:r_width,
		resizable:false,
		modal:true,
		open:function(){
			//$.unblockUI();
			if($('#uploadify').length){
				$('#uploadify').uploadify({
				uploader:'/js/jquery.uploadify-v2.1.0/uploadify.swf',
				script:'/js/jquery.uploadify-v2.1.0/uploadify.php',
				scriptData:{'type': r_type,'id_item': r_id_item},
				cancelImg:'/js/jquery.uploadify-v2.1.0/cancel.png',
				folder:'/media',
				queueID:'fileQueue',
				auto:true,
				multi:false,
				onError:function(a, b, c, d) {
					//if (d.status == 404)alert('Could not find upload script. Use a path relative to: <?= getcwd() ?>');
					//else if (d.type === "HTTP")alert('error '+d.type+': '+d.status);
					//else if (d.type ==="File Size")alert(c.name+' '+d.type+' Limit: '+Math.round(d.sizeLimit/1024)+'KB');
					//else alert('error '+d.type+': '+d.text);
					alert('error '+d.type+': '+d.info);
				},
				//alert('Error al subir el archivo'+d.type + ': ' + d.info)},
				onAllComplete:function(){
					$.ajax({
					method:"get",url: r_url_dest,
					success:function(html){
						$("#"+r_IdDivDest).html(html);
  						
						}
					});
					$('#Dialogo').dialog('close');
					$('#Dialogo').dialog('destroy');
				}
				});
			}
		},
		close:function(){$(this).dialog('destroy');}
    });
});
}

function ConfirmActionJQ(sUrl, DIVdestino){
	var dialog=$('<div>&iquest; Eliminar los elementos seleccionados ?</div>').insertAfter('#Dialogo');
	$(dialog).dialog({
		title:'Atenci&oacute;n',
		resizable:false,
		modal:true,
		buttons:{
			'Eliminar': function(){
				var arr_IdItemsD=[]; 
				$('input:checkbox:checked').each(function(){arr_IdItemsD.push($(this).val());}); 
				tczShowAjaxJQ(sUrl,DIVdestino);
				$(this).dialog('close');
				return false;
			},
			Cancel: function() {
				$(this).dialog('close');
			}
		}
	});
}

function JQAjaxPost(r_URL, r_divDest, r_type){
	//r_fields=r_fields.replace(',','","');
	//r_fields='"'+r_fields+'"';
	//alert(r_fields);
	//var aryTest=[r_fields];
	//var aryTest=r_fields.split(',');
	//var v_fields="{";
	//for (i=0;i<aryTest.length;i++){
	//alert(aryTest[i]+'_val');
	//document.write(aryTest[i]);
	//v_fields = v_fields+""+aryTest[i]+":\""+$("#"+aryTest[i]).val()+"\",";
	//}
	//var strLen = v_fields.length;
	//v_fields = v_fields.slice(0,strLen-1); 
	//v_fields=v_fields+"}";
	//alert(v_fields);
	//return false;
	$.ajax({
		type:"POST",
		url:r_URL,
		//contentType: "application/x-www-form-urlencoded; charset=utf-8",
		scriptCharset:"iso-8859-1",
        cache:false,
		data:{id_ar:$("#id_ar").val(), is_submit:$("#is_submit").val(), from_email:$("#from_email").val(), to_email:$("#to_email").val(), aditional_message:encodeURIComponent($("#aditional_message").val())},
		success:function(data){
			//reset_new_contact_form();
			$("#"+r_divDest).html(data);
		}
	});
}
function hide_share_email(r_id){
	$("#EmailBox_"+r_id).hide();
}
function setupLabel(){
	if ($('.label_check input').length){
		$('.label_check').each(function(){ 
		$(this).removeClass('c_on');
		});
		$('.label_check input:checked').each(function(){ 
		$(this).parent('label').addClass('c_on');
		});                
	};
	if ($('.label_radio input').length) {
		$('.label_radio').each(function(){ 
		$(this).removeClass('r_on');
		});
		$('.label_radio input:checked').each(function(){ 
		$(this).parent('label').addClass('r_on');
		});
	};
}
function tnzAjaxAddBasket(r_divMsg, r_id_prod, r_quantity, r_prod_options){
	$("#tnzAddBsk"+r_id_prod).fadeTo("fast",0.3);
	$.ajax({
		method:"get",url: "/cesta/addcesta_ajax.php?a="+r_id_prod+"&b="+r_quantity+"&c="+r_prod_options,
		success:function(html){
			$("#"+r_divMsg).hide();
			$("#"+r_divMsg).html("<div class='msg_ok'>El producto se a&ntilde;adi&oacute; a la cesta<br/><a href='/?view=2'>Ir a la cesta</a></div>");
			tczShowAjaxJQ("/cesta/basket_resume.php?t=2", "tnzBasketResume");
			$("#"+r_divMsg).fadeTo("fast",1.0);
			$("#tnzAddBsk"+r_id_prod).fadeTo("fast",1.0);
		}
	});
}
function tnz_LoadSelSizes(r_idprod, r_idprodattr, r_prod_round){
	$("#tnzSelSizes").fadeTo("fast",0.4);
	// Sumamos todos los que son m.2 para pasar el precio al selector de medidas
	var tnz_priceadd=0;
	var tnz_priceaddT=0;
	var arr_idprodattr=r_idprodattr.split(',');
	var len=(arr_idprodattr.length)-1;
	for(var i=0; i<len; i++){
		tnz_priceaddT=$("#id_prod_attr"+arr_idprodattr[i]+r_idprod).val();
		tnz_arr_priceadd=tnz_priceaddT.split('|');
		if(tnz_arr_priceadd[1].match(/m/gi)){
			var cl_priceadd=tnz_arr_priceadd[1].replace('m', '');
			tnz_priceadd+=parseFloat(cl_priceadd);
		}
	}
	$.ajax({
		method:"get",url: "/constructor/products/sel_sizes.php?product="+r_idprod+"&productd="+r_idprodattr+"&ump="+tnz_priceadd,
		success:function(html){
			$("#tnzSelSizes").html(html);
			$("#tnzSelSizes").fadeTo("fast",1.0);
			tnz_updateprice(r_idprod,r_idprodattr,r_prod_round);
		}
	});
}
function tnz_updateprice(r_idprod, r_idprodattr, r_prod_round){
	//$("#tnz_ProdPrice"+r_idprod).fadeTo("fast",0);
	var tnz_priceval=$("#prodPriceVal"+r_idprod).val();
	var tnz_priceadd=0;
	var arr_idprodattr=r_idprodattr.split(',');
	// Por cada uno sumamos el precio
	var len=arr_idprodattr.length;
	for(var i=0; i<len; i++){
		tnz_priceaddT=$("#id_prod_attr"+arr_idprodattr[i]+r_idprod).val();
		tnz_arr_priceadd=tnz_priceaddT.split('|');
		// Quitamos los que son m.2
		if(!tnz_arr_priceadd[1].match(/m/gi)){
			var cl_priceadd=tnz_arr_priceadd[1].replace('u', '');
			tnz_priceadd+=parseFloat(cl_priceadd);
		}
	}	
	tnz_calc_price=parseFloat(tnz_priceval)+parseFloat(tnz_priceadd);
	if(r_prod_round=='1'){
		tnz_calc_price=tnz_addSeparatorsNF(tnz_calc_price.toFixed(0),'.',',',',');
	}else{
		tnz_calc_price=tnz_addSeparatorsNF(tnz_calc_price.toFixed(2),'.',',',',');
	}
	$("#tnz_ProdPrice"+r_idprod).html(tnz_calc_price+" &euro;");
	//$("#tnz_ProdPrice"+r_idprod).effect("highlight", {}, 3000);
}

function tnz_setColor(r_idprod,r_idprodattr,r_InputField,r_ColVal,r_colId,r_colCode){
	$("#id_prod_attr"+r_InputField+r_idprod).val(r_ColVal);
	// Primero quitamos el class Active a todos
	$(".tnz_AddBasketOptions div").removeClass('tnz_colorActive');
	$(".tnz_AddBasketOptions div").addClass('tnz_colorNormal');
	$("#tnz_colBlock"+r_colId).removeClass('tnz_colorNormal');
	$("#tnz_colBlock"+r_colId).addClass('tnz_colorActive');
	tnz_LoadSelSizes(r_idprod,r_idprodattr);
	Set_Cookie('VinilColor',r_colCode,0,'/',false);
	tnz_UpdatePicColor(r_colCode);
}

function tnz_addSeparatorsNF(nStr, inD, outD, sep){
	nStr += '';
	var dpos = nStr.indexOf(inD);
	var nStrEnd = '';
	if (dpos != -1) {
		nStrEnd = outD + nStr.substring(dpos + 1, nStr.length);
		nStr = nStr.substring(0, dpos);
	}
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(nStr)) {
		nStr = nStr.replace(rgx, '$1' + sep + '$2');
	}
	return nStr + nStrEnd;
}

jQuery.cookie=function(name,value,options){if(typeof value!='undefined'){options=options||{};if(value===null){value='';options.expires=-1}var expires='';if(options.expires&&(typeof options.expires=='number'||options.expires.toUTCString)){var date;if(typeof options.expires=='number'){date=new Date();date.setTime(date.getTime()+(options.expires*24*60*60*1000))}else{date=options.expires}expires='; expires='+date.toUTCString()}var path=options.path?'; path='+(options.path):'';var domain=options.domain?'; domain='+(options.domain):'';var secure=options.secure?'; secure':'';document.cookie=[name,'=',encodeURIComponent(value),expires,path,domain,secure].join('')}else{var cookieValue=null;if(document.cookie&&document.cookie!=''){var cookies=document.cookie.split(';');for(var i=0;i<cookies.length;i++){var cookie=jQuery.trim(cookies[i]);if(cookie.substring(0,name.length+1)==(name+'=')){cookieValue=decodeURIComponent(cookie.substring(name.length+1));break}}}return cookieValue}};

