// contentG front end Script



// Funciones Portal


// a) uid
// b) uid=cid
// d) 
var http_request = false;
var cWorkshop=false;

window.onload=function() {

	// why Ajax if contentG is better
//	document.write();
//			<iframe id="contentgw" name="contentgw" style="display:block;overflow:auto;" src="/portal/portalg.pl"></iframe>
//		<!-- / contentG workshop -->
//	document.open();
//	document.write('<iframe id="contentGWorkshop" name="contentGWorkshop" style="display:block;overflow:auto;"></iframe>');
//	document.close();
if(document.getElementById("contentGWorkshop")) {
	cWorkshop=top.frames["contentGWorkshop"];
//	try{
//		alert("cW; "+cWorkshop.document.location);
//		alert("cWcDoc: "+document.getElementById("contentGWorkshop").contentDocument);
//	}
//	catch (e){
//		alert("cW ERR: "+e);
//	}

	//cWorkshop.document.open("text/html", "replace");
//	cWorkshop.document.open();
}

	var miSes=leeCookie("userSession");
	if (miSes == null){
		//alert('null session');
		// Display Adult BANNER 
		// What about no cookies

		adultosDisplay();
	}


	

	var getSession='/portal/portalg.pl?getSession=1&doc='+document.location+'&ref='+document.referrer+'&getCarrito=5';
	var content=httpRead(getSession);
//	miSes=leeCookie("userSession");

	//if (cWorkshop)	{
	//	cWorkshop.document.write('Iniciando Sesión...'+miSes);
	//	cWorkshop.document.write('<input type="button" onClick="alert(document.cookie+\':\'+document.cookie.length);" value="cookiesalert">');
	//}
	
//	alert(miSes);
//	lasCookiesAlert();
//	refreshCarrito();


	if (document.getElementById("pedidoFinalResult")){
		if (document.getElementById("pedidoFinalResult").value==1){
			cleanCarrito();
			var ngetSession='/portal/portalg.pl?getLogin=1&doc='+document.location+'&ref='+document.referrer+'';
			var ncontent=httpRead(ngetSession);
		}
	}

	if (document.getElementById("CL_RF_PAIS")){
			cambiaPaisProvincia();
	}


	if (document.getElementById("cgTransporte")) {

//		var updateURL='/portal/portalg.pl?getCarrito=5';
//		var contentUpdate=httpRead(updateURL);

	}

	if (document.getElementById("transTarifa")){
		cambiaTransPago();
	}
	if (document.getElementById("fpagoDescDiv")){
		chkFormaPago();
	}
	if (document.getElementById('dirEnvID')){
		cambiaDir('E');
		cambiaDir('F');
	}


}


function fnEnciendeRow(src,clrOver) {
	 if (!src.contains(event.fromElement)) {
		 src.style.cursor = 'hand';
		 src.className = clrOver;
	 }
}

function fnApagaRow(src,clrIn) {
	if (!src.contains(event.toElement)) {
		src.style.cursor = 'hand';
		src.className = clrIn;
	}
}



		function showHide(elBloque) {
		

			var miB=document.getElementById(elBloque);
			//alert("localizando "+elBloque+" "+miB);
			if (miB.style.display == "" ) {
				miB.style.display="none";
			}
			if (miB.style.display == "none") {
				miB.style.display="block";
			}
			else {
				miB.style.display="none";
			}
			//frameMaximize(this);
		}


function refreshPage () {


	var miUID=leeCookie('userID');
	if (miUID == null || miUID == 0 ){
		// sin Login ...
		if (document.getElementById("ulLogin")){
		
			var miLoginDiv=document.getElementById("ulLogin");
			var miLoginResult=document.getElementById("loginError");
			var miLoginLogout=document.getElementById("doLogout");
			var miLoginOK=document.getElementById("loginOK");
			miLoginLogout.style.display="none";
	//		miLoginRestult.style.display
			miLoginDiv.style.display="block";
			var loginTry=document.cookie.indexOf("userLG");
			if (loginTry>0)	{
				//miLoginResult.innerHTML="<p><span>Error.</span></p>";
				miLoginResult.style.display="block";
				//borraCookieSize("userLG");
				//borraCookieSize("userNM");
				//borraCookieSize("userIG");
			}
			else {
				miLoginResult.style.display="none";
				miLoginOK.style.display="none";
				miLoginLogout.style.display="none";
			}
			var miLoginForm=document.getElementById("fLogin");
			miLoginForm.reset();
		}
	}
	else {
		var miNA=leeCookie('userNA');
		if (document.getElementById("ulLogin")){
			var miLoginDiv=document.getElementById("ulLogin");
			var miLoginResult=document.getElementById("loginError");
			var miLoginOK=document.getElementById("loginOK");
			var miLoginLogout=document.getElementById("doLogout");
			//miLoginResult.innerHTML="<p><span><a href=\"/clientes.html\">Cuenta de "+miNM+"</a></span></p>";
			// miLoginDiv.innerHTML="<p><span><a href=\"/cuenta.html\">Cuenta de "+miNM+"</a></span></p>";
			//miLoginLogout.innerHTML="<p><span><a href=\"#\" onClick=\"doLogout();\">Salir</a></span></p>";
			var miOKHTML=miLoginOK.innerHTML;
			if (miNA){
				miNA.replace(/\+/g," ");
			}
			else { 
				miNA="";
			}

			miLoginOK.innerHTML="Bienvenido * "+unescape(miNA);
		
			miLoginLogout.style.display="block";
			miLoginLogout.style.cursor="pointer";
			miLoginOK.style.display="block";
			miLoginDiv.style.display="none";
			miLoginResult.style.display="none";

		}
	}

	if (document.getElementById("cgLogin"))	{
		document.getElementById("cgLogin").style.display="block";
	}

	var miAlert=leeCookie('alarmText');
	if (miAlert != "" && miAlert != null ){
		//miAlert=unescape(miAlert);
		miAlert=miAlert.replace(/\+/gi, " ");
		alert(miAlert);
		borraCookieSize("alarmText");
	}

	refreshCarrito();
}

function doLogout() {
	borraCookieSize("userID");
	borraCookieSize("userLG");
	borraCookieSize("userIG");
	borraCookieSize("userNM");
	borraCookieSize("userNA");
	borraCookieSize("userSession");
	var getSession='/portal/portalg.pl?getSession=1&doc='+document.location+'&ref='+document.referrer;
	var content=httpRead(getSession);


}
function doLogin() {

//	var laF=document.forms["fLogin"];
	var inL=document.getElementById("inLogin").value;

	var inP=document.getElementById("inPwd").value;

	var inR=document.getElementById("inRemember").checked;
	if (inR == false){
	}
	else {
		inR="s";
	}
	//alert ("Login : "+inL+" P: "+inP+" R:"+inR);


	var cURL="/portal/portalg.pl?getLogin=1&emLogin="+inL+"&pwdLogin="+inP+"&remLogin="+inR;
	var content=httpRead(cURL);
	return false;
}


function masCarrito() {

	 //alert("Añadir a carrito por URL: \n"+cURL);
	 // cgCLASE_SELECTOR
	var todoSel=document.getElementsByTagName("select");
	var masString="";
	var selNumber=0;
	for (t=0;t<todoSel.length;t++ ) {
		if (todoSel[t].id.indexOf("cgCLASE_SELECTOR")>-1 ){
			//var tArr=todoSel[t].id
			//alert("selector "+todoSel[t].id+" "+todoSel[t].value);
			masString=masString+"&cgSel"+selNumber+"="+todoSel[t].value;
			selNumber++;
		}
	}
	var cURL="/portal/portalg.pl?getCarrito=1&doc="+document.location+""+masString;
	var content=httpRead(cURL);
	//alert("Se ha añadido el artículo a su carrito.\nSi el carrito no se actualiza autmáticamente,\nrecargue esta página.");

	
}
function anadeCarrito(idA,clA) {

	var cURL="/portal/portalg.pl?getCarrito=3&idA="+idA+"&clA="+clA;
	// alert("Añadir a carrito por ID : \n"+cURL);
	var content=httpRead(cURL);
	
}

function quitaCarrito(idA,clA) {
	var cURL="/portal/portalg.pl?getCarrito=4&idA="+idA+"&clA="+clA;
	 //alert("Quitar a carrito por ID : \n"+cURL);
	var content=httpRead(cURL);
}
function borraCarrito(idA,clA) {
	//alert("x c:"+idA);
	var cURL="/portal/portalg.pl?getCarrito=2&idA="+idA+"&clA="+clA;
	 //alert("Borrar carrito por ID: \n"+cURL);
	var content=httpRead(cURL);
}
function refreshCarrito() {

//	if (idArt == "" || idArt == 0 || idArt==null){
		// asumiendo refresco
//	var cURL="/admin/gest/portalg.pl?getCarriro=1&idA="+idArt+"&op="+oper;


//	}


	// Cookies Carrito::::::::::::::::::
	//	&conf::SetCookies('carritoID',$idC,'carritoC',$caC,'carritoN',$noC,'carritoP',$pvC);
//			$cN.="idA:$dataCarrito->[$t][0]|";
//			$cN.="caA:$dataCarrito->[$t][1]|";
//			$cN.="noA:$dataCarrito->[$t][2]|";
//			$cN.="pvA:$dataCarrito->[$t][3]|";
		
//	var idA=leeCompCookie('carritoID');
		if (miC=document.getElementById("cgCarrito")){
			var miC=document.getElementById("cgCarrito");
			//miC.style.display="none";
		}
		//alert('refresh carrito '+miC.id);
		if (document.getElementById("cgCarrito")){
			//alert('si hay cgCarrito');
			var divCarrito=document.getElementById("cgCarrito");
			var ulCarrito;
			if (document.getElementById("ulCarrito")){
				ulCarrito=document.getElementById("ulCarrito");
			}
			if (document.getElementById("ulCarritoPage")){
				ulCarrito=document.getElementById("ulCarritoPage");
			}
			//ulCarrito.innerHTML="";
			var idC=new Array;
			var caC=new Array;
			var noC=new Array;
			var pvC=new Array;
			var pvI=new Array;
			var clA=new Array;
			var pvT=new Array;
			var totalCarrito=0;
			var totalCarritoIVA=0;
			if (leeCookie("carrito") && leeCookie("carrito") != ""){

				var tempCookie=leeCookie("carrito");
				var arrVars=tempCookie.split('|');
				var resCookie;
				var cookPos=0;
				for (var i=0;i<arrVars.length;i++)	{
					var arrVals=arrVars[i].split(":");
					var cField=arrVals[0];
					var cValue=arrVals[1];
					if (cField == 'idA'){
						idC[cookPos]=cValue;
					}
					else if (cField == 'caA'){
						caC[cookPos]=cValue;
					}
					else if (cField == 'noA'){
						noC[cookPos]=cValue;
					}
					else if (cField=='clA')	{
						clA[cookPos]=cValue;
					}

					else if (cField=='pvA')	{
						
						var tempTotal=(caC[cookPos]*cValue).toFixed(2);
						totalCarrito+=caC[cookPos]*cValue;
						pvC[cookPos]=tempTotal;
					}
					
					else if (cField=='pvI') {
						var tempTotalIVA=(caC[cookPos]*cValue).toFixed(2);
						totalCarritoIVA+=caC[cookPos]*cValue;
						pvI[cookPos]=tempTotalIVA;
						
					}
					else if (cField=='pvC')	{
						var tempTotalConIVA=(caC[cookPos]*cValue).toFixed(2);
						pvT[cookPos]=tempTotalConIVA;
						cookPos+=1;
					}
					
				}
				var resHTML='<ul class="carritoCarrito">';

				for (var a=0;a<cookPos;a++)	{
					var lsRegExp = /\+/g;
					//totalCarrito=totalCarrito+pvC[a];
					noC[a]=unescape(String(noC[a]).replace(lsRegExp, " "));
					if (document.getElementById("ulCarrito")){
						resHTML+='<li class="carritoLineaCarrito"><ul class="carritoLineaArticulo"><li class="carritoNombreArticulo"><span><a title="'+noC[a]+'" onClick="goURLART('+idC[a]+');">'+noC[a]+'</a></span></li><li class="carritoBotonesAritulo"><button class="borraCarrito" title="Borrar" onclick="borraCarrito(\''+idC[a]+'\',\''+clA[a]+'\');"><span>x</span></button> <button class="masCarrito" title="Añadir" onclick="anadeCarrito(\''+idC[a]+'\',\''+clA[a]+'\');" ><span>+</span></button> <button class="menosCarrito" title="Restar" onclick="quitaCarrito(\''+idC[a]+'\',\''+clA[a]+'\');" ><span>-</span></button></li><li class="carritoCantidadArticulo"><span>'+caC[a]+'</span></li><li class="carritoPrecioArticulo"><span title=" IVA '+pvI[a]+'">'+pvC[a]+'&euro;</span></li></ul></li>';
					}
					if (document.getElementById("ulCarritoPage")){

						resHTML+='<li class="carritoLineaCarrito"><ul class="carritoLineaArticulo"><li class="carritoBotonesArticulo"><button class="borraCarrito" title="Borrar" onclick="borraCarrito(\''+idC[a]+'\',\''+clA[a]+'\');"><span>x</span></button> <button class="masCarrito" title="Añadir" onclick="anadeCarrito(\''+idC[a]+'\',\''+clA[a]+'\');" ><span>+</span></button> <button class="menosCarrito" title="Restar" onclick="quitaCarrito(\''+idC[a]+'\',\''+clA[a]+'\');" ><span>-</span></button></li><li class="carritoCantidadArticulo"><span>'+caC[a]+'</span></li><li class="carritoNombreArticulo"><span><a title="'+noC[a]+'" onClick="goURLART('+idC[a]+');">'+noC[a]+'</a></span></li><li class="carritoPrecioArticulo">'+pvC[a]+' &euro;</span></li><li class="carritoPrecioArticuloIVA">'+pvI[a]+' &euro;</li><li class="carritoPrecioArticuloConIVA">'+pvT[a]+' &euro;</li><li class="carritoBreakLine"></li></ul></li>';
					}
					
				}
				//totalCarrito=totalCarrito.toFixed(2);
				if (document.getElementById("ulCarrito")){
					resHTML+='<li class="carritoTotalCarrito"><span title=" Total Carrito "> Total <strong>'+totalCarrito.toFixed(2)+'&euro;</strong></span></li><li class="carritoTotalCarritoIVA"><span title=" Total Carrito IVA "> Total IVA <strong>'+(totalCarrito+totalCarritoIVA).toFixed(2)+'&euro;</strong></span></li>';
				}

				resHTML+='</ul>';


				totalCarritoIVA.toFixed(2)
//				cWorkshop=top.frames["contentGWorkshop"];
//				cWorkshop.document.open("text/html", "replace");
//				cWorkshop.document.write(resHTML);
//				cWorkshop.document.close();
				ulCarrito.innerHTML=resHTML;

				if (document.getElementById("cgTransporte"))	{

					//var miTransporteDiv=document.getElementById("cgTransporte");
					//var tURL="/portal/portalg.pl?getTransporte=1";
					calcCarritoPage();
				//	var content=httpRead(tURL);
				//	alert("Transporte");
				}
//				alert("ahora: "+miC.style.display);
				//miC.style.display="block";
			}
			else {
				ulCarrito.innerHTML="";
//				alert("ahora: "+miC.style.display);
				//miC.style.display="none";
			}
		}

		if (document.getElementById("cgMonedero")){
		
				var mtempCookie=leeCookie("monedero");
				var arrVars=mtempCookie.split('|');
				var resCookie;
				var cookPos=0;
				for (var i=0;i<arrVars.length;i++)	{

					var arrVals=arrVars[i].split(":");
					var cField=arrVals[0];
					var cValue=arrVals[1];
					if (cField == 'esteM'){
						
						if (document.getElementById("monederoActual")){
							document.getElementById("monederoActual").innerHTML=cValue;
						}

					}

					if (cField == 'porcM'){
						if (document.getElementById("monederoPorcentaje")){
							document.getElementById("monederoPorcentaje").innerHTML=cValue;
						}

					}

					if (cField == 'totalM'){
						if (document.getElementById("monederoCompra")){
							document.getElementById("monederoCompra").innerHTML=cValue;
						}

					}


					if (cField == 'actualM'){
						if (document.getElementById("monederoAcumulado")){
							document.getElementById("monederoAcumulado").innerHTML=cValue;
						}

					}

				}

		}


}


function getCarritoTotal() {

			var idC=new Array;
			var caC=new Array;
			var noC=new Array;
			var pvC=new Array;
			var pvI=new Array;
			var clA=new Array;
			var pvT=new Array;
			var totalCarrito=0;
			var totalCarritoIVA=0;
			if (leeCookie("carrito") && leeCookie("carrito") != ""){

				var tempCookie=leeCookie("carrito");
				var arrVars=tempCookie.split('|');
				var resCookie;
				var cookPos=0;
				for (var i=0;i<arrVars.length;i++)	{
					var arrVals=arrVars[i].split(":");
					var cField=arrVals[0];
					var cValue=arrVals[1];
					if (cField == 'idA'){
						idC[cookPos]=cValue;
					}
					else if (cField == 'caA'){
						caC[cookPos]=cValue;
					}
					else if (cField == 'noA'){
						noC[cookPos]=cValue;
					}
					else if (cField=='clA')	{
						clA[cookPos]=cValue;
					}

					else if (cField=='pvA')	{
						
						var tempTotal=(caC[cookPos]*cValue).toFixed(2);
						totalCarrito+=caC[cookPos]*cValue;
						pvC[cookPos]=tempTotal;
					}
					
					else if (cField=='pvI') {
						var tempTotalIVA=(caC[cookPos]*cValue).toFixed(2);
						totalCarritoIVA+=caC[cookPos]*cValue;
						pvI[cookPos]=tempTotalIVA;
						
					}
					else if (cField=='pvC')	{
						var tempTotalConIVA=(caC[cookPos]*cValue).toFixed(2);
						pvT[cookPos]=tempTotalConIVA;
						cookPos+=1;
					}
					
				}
			}

			return totalCarrito+"-"+totalCarritoIVA;;

}
function goBuscador(bDest,bInput,bParams) {

	var realText=document.getElementById("buscadorVal").value;

	var formURL=bDest+"?"+bInput+"="+realText+"&"+bParams;
	try	{
		
		document.location=formURL;		
	}
	catch (e) {
		alert("newDocLoc "+e);
	}


}




function goURLART(idART) {

	//alert("go see "+idART);
	var cURL="/portal/portalg.pl?getURL=1&idA="+idART;
	var content=httpRead(cURL);

	

}
function httpRead(url) {

	// alert("go...");
	if (window.XMLHttpRequest) { // Mozilla, Safari, ...
    
		http_request = new XMLHttpRequest();
	
		if (http_request.overrideMimeType) {
			http_request.overrideMimeType('text/xml');
		}

	} 
	else if (window.ActiveXObject) { // IE
		try {
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
		} 
		catch (e) {
			try {
				http_request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}

	var ranNum= Math.floor(Math.random()*999999999);
	url+="&rn="+ranNum;

	//alert("ob HTTP: " +http_request);

	if (!http_request) {
		// No se puede crear instancia httprequest ... 
		// Pasamos al IFRAME WorkFrame la URL ?? 
		// sig
		//alert("No HTTP Avail");
		if (document.getElementById("contentGWorkshop")){
			//alert("Loading... dcID");
			var miFDoc=document.getElementById("contentGWorkshop");
			//alert ("doc: "+miFDoc);
			
			//alert("src "+miFDoc.src);
			//alert("cDoc "+miFDoc.contentDocument);
			try	{
				miFDoc.contentWindow.src=url;

			}
			catch (e){
				//alert("src except! "+e);
				try	{
					frames[miFDoc.name].document.location=url;
				}
				catch (e){
					alert("frames.document.location: "+e);
					try	{
						frames[miFDoc.name].location=url;
					}
					catch (e) {
						alert("frames.location: "+e);

						try	{
							var iDoc=miFDoc.contentWindow.document;
							
						}
						catch (e) {
							alert ("iDoc :"+e);
							try	{
								miFDoc.contentWindow.document.location=url;
							
							}
							catch (e) {
								alert("cWin document.location: "+e);
	
								try	{
									miFDoc.contentWindow.location=url;
							
								}
								catch (e) {
									alert("cWin location: "+e);
								}

							}	

						}
									
					}

				}

			}

			//document.getElmentById("contentGWorkshop").document.location=url;
			return document.getElmentById("contentGWorkshop").document.innerHTML;
		}
//		else if (document.all["contentGWorkshop"]) {
			//document.all["contentGWorkshop"].document.location=url;
//			alert("Loading...dcALL");
			//return document.all["contentGWorkshop"].document.innerHTML;
//		}
//		else if (top.frames["contentGWorkshop"]){
			//top.frames["contentGWorkshop"].src=url;
//			alert("Loading...dcAR");

//		}
		else {
			alert("Not Found !");
			return false;
		}
		
	}

	else {

		http_request.onreadystatechange = httpChange;

		http_request.open('GET', url, true);
		http_request.setRequestHeader( "If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT" );
		//alert("init request :"+url);
		http_request.send(null);
	}
}

function httpChange() {

// http_request.readyState 
//					= 0 no init
//					= 1 reading
//					= 2 read
//					= 3 interactive
//					= 4 done

// http_request.status == HTTP ERROR CODE == 200 OK == 404 NOT FOUND == 500 Internal Server Error ...
	// alert(" httpChange: "+http_request.readyState);
	if (http_request.readyState==4)	{
		
		if (http_request.status == 200) {
//			if(document.getElementById("contentGWorkshop")) {
//				var cWorkshop=top.frames["contentGWorkshop"];
//				cWorkshop.document.open();
//				cWorkshop.close();
//			}
			//alert(" httpStatus = OK (200): \n"+http_request.responseText);
			if (http_request.responseText.indexOf("url:")==0){
				var arrURL;
				arrURL=http_request.responseText.split(":");
				document.location=arrURL[1];
			}
			if (http_request.responseText.indexOf("transSelect:")==0){

				var arrSelect;
				arrSelect=http_request.responseText.split(":");
				if (document.getElementById("cgTransporte")){
					document.getElementById("cgTransporte").innerHTML=arrSelect[1];

				}

			}
			if (cWorkshop){
				// alert(" Escribiendo en cWorkshop");
				//cWorkshop.document.write(http_request.responseText);
				//cWorkshop.document.close();
			}
			refreshPage();
//			refreshCarrito();
//			refreshLogin();

		} else {
			alert('... Error Grave. No Response:'+http_request.status);
		}
	}

}
function verBackImagen(imagenID,frontURL,backURL) {


	var obImg=document.getElementById(imagenID);

//	var miDocumentRoot=document.location.href;


	var miDomain="";
	if (frontURL.indexOf("http")==0){
	}
	else {
		var miLocation=window.location.toString(); 
		var splitURL=miLocation.split('/'); 
		miDomain=splitURL[0]+"//"+splitURL[2];
	}
	// http://www.sexshopwayup.net/extfiles/imagen.jpg
	// http
	// www.sexshopwayup.net
	// extfiles
	// imagen.jpg
//	var chain="";
//	for (var p=0;p<splitURL.length;p++){
//		chain+=" "+splitURL[p];
//	}
//	alert(chain);
	//document.write(campos_url [2]); 
	
	//var url="http://"+campos_url [2]+"/"; 


	var lastSRC=obImg.src;
	var domainFront=miDomain+frontURL;

	if (obImg.src == domainFront)	{
		obImg.src=backURL;
	}
	else {
		obImg.src=frontURL;
	}
//	var Url = location.href; 
//	Url = Url.replace(/.*\?(.*?)/,"$1"); 
//	Variables = Url.split ("&"); 

	//alert("id:"+imagenID+"\nF:"+frontURL+"\nFf: "+domainFront+"\nT:"+backURL+"\nNow:"+obImg.src+"\nb4:"+lastSRC);
}




// Librería


function leeCookie(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 creaCookieSize(name,value,days)
{

	
	if (days)	{
		if (days>0)	{
			var date = new Date();
			date.setTime(date.getTime()+(days*24*60*60*1000));
			var expires = "; expires="+date.toGMTString();
		} else var expires = "";
	} else var expires = "";
	

	document.cookie = name+"="+value+expires+"; path=/";

}
function leeCompCookie (cookie,name) {

//	var cookval=leeCookie(cookie);
	if (leeCookie(cookie))	{
		var tempCookie=leeCookie(cookie);
		var arrVars=tempCookie.split('|');
		for (var i=0;i<arrVars.length;i++)	{
			var arrVals=arrVars[i].split(":");
			// alert('lee:'+cookie+':'+name+'  v:'+arrVals[0]+' v:'+arrVals[1]);
			if (arrVals[0]==name){
				return arrVals[1];
			}
		}
	}
	else {
		return null;
	}
}


function borraCompCookie (cookie,name) {

//	var cookval=leeCookie(cookie);
	var tempCookie=leeCookie(cookie);
	var arrVars=tempCookie.split('|');
	var resCookie;
	var cookPos;
	for (var i=0;i<arrVars.length;i++)	{
		var arrVals=arrVars[i].split(":");
		if (arrVals[0]==name){
			// resCookie=tempCookie.substring(0,tempCookie.indexOf('|'+name+':'));
			cookPos=i;
			var repString=arrVals[0]+":"+arrVals[1]+"|";
			resCookie=replaceSubstring(tempCookie,repString,"");
//			resCookie.replace(repString);
//			resCookie=tempCookie.substring(0,tempCookie.indexOf(repString));
//			resCookie=resCookie+tempCookie.substring(tempCookie.indexOf(repString)+repString.length,tempCookie.length-repString.length);
			//alert('ins: '+tempCookie+'\nstr:'+repString+'\nres:'+resCookie);
			creaCookieSize(cookie,resCookie);

		}
	}

}
function grabaCompCookie (cookie,name,value) {


// articulos=form1:val1|form2:val2|form3:val3|form4:val4|

	var tempCookie="";
	var resCookie="";
	if (name !=null){

		if (leeCookie(cookie)){
			tempCookie=leeCookie(cookie);
			var arrVars=tempCookie.split('|');
			for (var i=0;i<arrVars.length;i++ )	{
				var parVals=arrVars[i].split(":");
				if (parVals[0]==name){
					// existe 
//					borraCompCookie(cookie,name);

					var repString=parVals[0]+":"+parVals[1]+"|";
					tempCookie=replaceSubstring(tempCookie,repString,"");


				}
			}

		}
		tempCookie+=name+':'+value+'|';
		creaCookieSize(cookie,tempCookie);
	}
}

function borraCookieSize(name)
{

	creaCookieSize(name,"",-1);
}


function lasCookiesAlert() {

	alert(document.cookie+"\n"+document.cookie.length);
}


function replaceSubstring(inputString, fromString, toString) {
   // Goes through the inputString and replaces every occurrence of fromString with toString
   var temp = inputString;
   if (fromString == "") {
      return inputString;
   }
   if (toString.indexOf(fromString) == -1) { // If the string being replaced is not a part of the replacement string (normal situation)
      while (temp.indexOf(fromString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(fromString));
         var toTheRight = temp.substring(temp.indexOf(fromString)+fromString.length, temp.length);
         temp = toTheLeft + toString + toTheRight;
      }
   } else { // String being replaced is part of replacement string (like "+" being replaced with "++") - prevent an infinite loop
      var midStrings = new Array("~", "`", "_", "^", "#");
      var midStringLen = 1;
      var midString = "";
      // Find a string that doesn't exist in the inputString to be used
      // as an "inbetween" string
      while (midString == "") {
         for (var i=0; i < midStrings.length; i++) {
            var tempMidString = "";
            for (var j=0; j < midStringLen; j++) { tempMidString += midStrings[i]; }
            if (fromString.indexOf(tempMidString) == -1) {
               midString = tempMidString;
               i = midStrings.length + 1;
            }
         }
      } // Keep on going until we build an "inbetween" string that doesn't exist
      // Now go through and do two replaces - first, replace the "fromString" with the "inbetween" string
      while (temp.indexOf(fromString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(fromString));
         var toTheRight = temp.substring(temp.indexOf(fromString)+fromString.length, temp.length);
         temp = toTheLeft + midString + toTheRight;
      }
      // Next, replace the "inbetween" string with the "toString"
      while (temp.indexOf(midString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(midString));
         var toTheRight = temp.substring(temp.indexOf(midString)+midString.length, temp.length);
         temp = toTheLeft + toString + toTheRight;
      }
   } // Ends the check to see if the string being replaced is part of the replacement string or not
   return temp; // Send the updated string back to the user
} // Ends the "replaceSubstring" function



function thisFrameHeight() {

		
	laFrame=self.name;
	var oIframe=parent.document.getElementById(laFrame);
	// alert("laFrame:"+laFrame+" oIframe:"+oIframe+" oICN:"+oIframe.className);
	document.body.className=oIframe.className;
	var miBHeight=oIframe.scrollHeight;
	var minHeight=4;
	oIframe.style.height=miBHeight+minHeight+"px";
	

}

function ClientesLoad() {

	// getPaises
	// getProvincias


	laFrame=self.name;
	id=self.name;
if (!window.opera && !document.mimeType && document.all && document.getElementById){
	var oH=parseInt(this.document.body.offsetHeight+10);
parent.document.getElementById(id).style.height=oH+"px";
}
else if(document.getElementById) {
	var sH=parseInt(this.document.body.scrollHeight+10);
parent.document.getElementById(id).style.height=sH+"px"
}
}
function formClientesLoad() {

	// getPaises
	// getProvincias


	laFrame=self.name;
	id=self.name;
if (!window.opera && !document.mimeType && document.all && document.getElementById){
	var oH=parseInt(this.document.body.offsetHeight+10);
parent.document.getElementById(id).style.height=oH+"px";
}
else if(document.getElementById) {
	var sH=parseInt(this.document.body.scrollHeight+10);
parent.document.getElementById(id).style.height=sH+"px"
}


cambiaPaisProvincia();	
}

function obtenPaises() {
	var cURL="/portal/portalg.pl?getPaises=1";
	var content=httpRead(cURL);


}

function formClientesSubmitDirAlt() {

	if (confirm("¿Modificar Dirección Alternativa?")){
		return true;
	}
	else {
		return false;
	}
}
function nuevaDA () {

	document.getElementById("IDDA").value="";
	document.getElementById("idDADel").value="";
	document.getElementById("adpProvincia").value="";
	document.getElementById("AD_NOMBRE").value="";
	document.getElementById("AD_DOMICILIO").value="";
	document.getElementById("adpPais").value=0;
	document.getElementById("AD_PROVINCIA").value="";
	document.getElementById("AD_CODIGOPOS").value="";
	document.getElementById("AD_LOCALIDAD").value="";
	document.getElementById("AD_SUBMIT").value="Insertar Dirección";
	document.getElementById("BDA_SUBMIT").enabled=false;

}
function editDA (idDA) {


	var nombreDir=document.getElementById("nombreDir:"+idDA).innerHTML;
	var domicilioDir=document.getElementById("domicilioDir:"+idDA).innerHTML;
	var paisDir=document.getElementById("paisDir:"+idDA).innerHTML;
	var provinciaDir=document.getElementById("provinciaDir:"+idDA).innerHTML;
	var localidadDir=document.getElementById("localidadDir:"+idDA).innerHTML;
	var cpDir=document.getElementById("cpDir:"+idDA).innerHTML;
	var rfPaisDir=document.getElementById("adRF_PAIS:"+idDA).innerHTML;


	document.getElementById("IDDA").value=idDA;
	document.getElementById("adpProvincia").value=provinciaDir;
	document.getElementById("AD_NOMBRE").value=nombreDir;
	document.getElementById("AD_DOMICILIO").value=domicilioDir;
	document.getElementById("adpPais").value=rfPaisDir;
	document.getElementById("AD_PROVINCIA").value=provinciaDir;
	document.getElementById("AD_CODIGOPOS").value=cpDir;
	document.getElementById("AD_LOCALIDAD").value=localidadDir;
	document.getElementById("AD_SUBMIT").value="Modificar Dirección";
	document.getElementById("idDADel").value=idDA;
	document.getElementById("BDA_SUBMIT").enabled=true;
	checkPaisProvinciaDA();
	cambiaPaisProvinciaDA();
	checkProvinciaDA();

}

function checkProvinciaDA() {

	var clProvincia=document.getElementById("AD_PROVINCIA");
	var prSelect=document.getElementById("AD_RF_PROVINCIA");
	if (document.getElementById("adpProvincia")){

		laProvincia=document.getElementById("adpProvincia").value;
//		alert(laProvincia); c.substring(1,c.length);
		var tProvincia=laProvincia.substring(0,laProvincia.length-1);
		if (prSelect.options.length>0){
			for (var i=0;i<prSelect.options.length;i++){
				//alert("Sel:"+prSelect.options[i].text+" Par:"+laProvincia+" Bool:"+(prSelect.options[i].text == laProvincia)+" lenS:"+prSelect.options[i].text.length+" lenP:"+laProvincia.length);
				if (prSelect.options[i].text == tProvincia || prSelect.options[i].text == laProvincia){
					prSelect.options[i].selected=true;
					break;
				}
			}	
		}
		else {
			clProvincia.value=laProvincia;
		}
	}
}

function checkPaisProvinciaDA() {

		elPais=document.getElementById("adpPais").value;

		if (elPais != ""){
			var paisSel=document.getElementById("AD_RF_PAIS");
			for (var i=0; i<paisSel.options.length; i++) {
				if (paisSel.options[i].value==elPais){
					paisSel.options[i].selected=true;
				}

			}
		}
//		checkProvincia(laProvincia);

}


function cambiaPaisProvinciaDA() {

	var paisID=document.getElementById("AD_RF_PAIS").value;
	var prSelect=document.getElementById("AD_RF_PROVINCIA");
	prSelect.style.display="none";
	var clProvincia=document.getElementById("AD_PROVINCIA");
	clProvincia.style.display="none";
	clProvincia.value="";
	removeAllOptions(prSelect);

	if (document.getElementById("PR-"+paisID)){
		var prSel=document.getElementById("PR-"+paisID);
		prSelect.style.display="block";
		clProvincia.style.display="none";
		// copySelectedOptions(prSel,prSelect);
		// selectAllOptions(prSel);
		for (var i=0; i<prSel.options.length; i++) {
		// alert(obj.options[i].text);
			var isSelected=false;
			if (document.getElementById("adpProvincia")){
				laProvincia=document.getElementById("adpProvincia").value;
				if (laProvincia != ""){
					if (prSel.options[i].text==laProvincia){
						isSelected=true;
					}

				}
			}

			addOption(prSelect,prSel.options[i].text,prSel.options[i].value,isSelected);
			//obj.options[i].selected = true;
		}
		

	}
	else {
		prSelect.style.display="none";
		clProvincia.style.display="block";
	}
	cambiaProvinciaDA();
}

function cambiaProvinciaDA() {
	var clProvincia=document.getElementById("AD_PROVINCIA");
	var prSelect=document.getElementById("AD_RF_PROVINCIA");
	if (prSelect.options.length>0){
		clProvincia.value=prSelect.options[prSelect.selectedIndex].text;
	}
}








function borraDA (idDA) {

}

function formClientesModiSubmit() {

	cambiaProvincia();
	if (confirm("¿Modificar sus Datos de Cliente?")){
		return true;
	}
	else {
		return false;
	}


}


function formClientesSubmit(laUrl) {


	var passReal=document.getElementById("CL_PASSWORD");
	var passChk=document.getElementById("CL_PASSWORDCHK");
	var clEmail=document.getElementById("CL_EMAIL").value;

	var clNombre=document.getElementById("CL_NOMBRE").value;
	var clApellidos=document.getElementById("CL_APELLIDOS").value;
	var clDomicilio=document.getElementById("CL_DOMICILIO").value;

	
	if (passReal.value.length < 6)	{
		alert("Error. La contraseña debe tener al menos 6 caracteres.\nPor favor revise la contraseña.");
		return false;
	}

	if (passReal.value != passChk.value)	{

		alert("Error. La contraseña y su comprobación no coinciden.\nPor favor revise la contraseña.");
		return false;
	}

	if (clEmail == '' || clEmail.indexOf('@') ==-1 || clEmail.indexOf(".")==-1 )	{
	
		alert("Error. La dirección E-Mail no parece ser una dirección válida.\nPor favor compruebe su dirección de E-Mail.");
		return false;

	}
	if (clNombre == '' || clApellidos=='' || clDomicilio==''){
		alert("Error. Debe introducir sus datos de cliente.\nPor favor, asegúrese de introducir su nombre, apellidos y domicilio.");
		return false;
	}
	
	return true;
}
function obtenProvincias() {

}


function hasOptions(obj) {
	if (obj!=null && obj.options!=null) { return true; }
	return false;
}


function removeAllOptions(from) { 
	if (!hasOptions(from)) { return; }
	for (var i=(from.options.length-1); i>=0; i--) { 
		from.options[i] = null; 
		} 
	from.selectedIndex = -1; 
} 

function copyAllOptions(from,to) {
	selectAllOptions(from);
//	if (arguments.length==2) {
		copySelectedOptions(from,to);
//		}
//	else if (arguments.length==3) {
//		copySelectedOptions(from,to,arguments[2]);
//		}
	}

function selectAllOptions(obj) {
	if (!hasOptions(obj)) { return; }
	for (var i=0; i<obj.options.length; i++) {
		// alert(obj.options[i].text);
		obj.options[i].selected = true;
		}
	}
	
function copySelectedOptions(from,to) {
	var options = new Object();
	if (hasOptions(to)) {
		for (var i=0; i<to.options.length; i++) {
			options[to.options[i].value] = to.options[i].text;
			}
		}
	if (!hasOptions(from)) { return; }
	for (var i=0; i<from.options.length; i++) {
		var o = from.options[i];
		if (o.selected) {
			if (options[o.value] == null || options[o.value] == "undefined" || options[o.value]!=o.text) {
				if (!hasOptions(to)) { var index = 0; } else { var index=to.options.length; }
				to.options[index] = new Option( o.text, o.value, false, false);
				}
			}
		}
	from.selectedIndex = -1;
	to.selectedIndex = -1;
	}


function addOption(obj,text,value,selected) {
	if (obj!=null && obj.options!=null) {
		obj.options[obj.options.length] = new Option(text, value, false, selected);
		}
	}




function moveOptionUp(obj) {
	if (!hasOptions(obj)) { return; }
	for (i=0; i<obj.options.length; i++) {
		if (obj.options[i].selected) {
			if (i != 0 && !obj.options[i-1].selected) {
				swapOptions(obj,i,i-1);
				obj.options[i-1].selected = true;
				}
			}
		}
	}

function moveOptionDown(obj) {
	if (!hasOptions(obj)) { return; }
	for (i=obj.options.length-1; i>=0; i--) {
		if (obj.options[i].selected) {
			if (i != (obj.options.length-1) && ! obj.options[i+1].selected) {
				swapOptions(obj,i,i+1);
				obj.options[i+1].selected = true;
				}
			}
		}
	}

function swapOptions(obj,i,j) {
	var o = obj.options;
	var i_selected = o[i].selected;
	var j_selected = o[j].selected;
	var temp = new Option(o[i].text, o[i].value, o[i].defaultSelected, o[i].selected);
	var temp2= new Option(o[j].text, o[j].value, o[j].defaultSelected, o[j].selected);
	o[i] = temp2;
	o[j] = temp;
	o[i].selected = j_selected;
	o[j].selected = i_selected;
	}

function removeSelectedOptions(from) { 
	if (!hasOptions(from)) { return; }
	if (from.type=="select-one") {
		from.options[from.selectedIndex] = null;
		}
	else {
		for (var i=(from.options.length-1); i>=0; i--) { 
			var o=from.options[i]; 
			if (o.selected) { 
				from.options[i] = null; 
				} 
			}
		}
	from.selectedIndex = -1; 
	} 
function addOption(obj,text,value,selected) {
	if (obj!=null && obj.options!=null) {
		obj.options[obj.options.length] = new Option(text, value, false, selected);
		}
	}



function cambiaPaisProvincia() {



	var paisID=document.getElementById("CL_RF_PAIS").value;
	var prSelect=document.getElementById("RF_PROVINCIA");
	prSelect.style.display="none";
	var clProvincia=document.getElementById("CL_PROVINCIA");
	clProvincia.style.display="none";
	//clProvincia.value="";
	removeAllOptions(prSelect);

	if (document.getElementById("PR-"+paisID)){
		var prSel=document.getElementById("PR-"+paisID);
		prSelect.style.display="block";
		clProvincia.style.display="none";
		// copySelectedOptions(prSel,prSelect);
		// selectAllOptions(prSel);
		for (var i=0; i<prSel.options.length; i++) {
		// alert(obj.options[i].text);
			var isSelected=false;
			if (document.getElementById("pProvincia")){
				laProvincia=document.getElementById("pProvincia").value;
				if (laProvincia != ""){
					if (prSel.options[i].text==laProvincia){
						isSelected=true;
					}

				}
			}

			addOption(prSelect,prSel.options[i].text,prSel.options[i].value,isSelected);
			//obj.options[i].selected = true;
		}
		

	}
	else {
		prSelect.style.display="none";
		clProvincia.style.display="block";
	}
	//cambiaProvincia();
}


function cambiaProvincia() {

	var clProvincia=document.getElementById("CL_PROVINCIA");
	var prSelect=document.getElementById("RF_PROVINCIA");



		if (prSelect.options.length>0){
			clProvincia.value=prSelect.options[prSelect.selectedIndex].text;
		}


}


function checkPaisProvincia() {

		elPais=document.getElementById("pPais").value;

		if (elPais != ""){
			var paisSel=document.getElementById("CL_RF_PAIS");
			for (var i=0; i<paisSel.options.length; i++) {
				if (paisSel.options[i].value==elPais){
					paisSel.options[i].selected=true;
				}

			}
		}
//		checkProvincia(laProvincia);

}
function checkProvincia() {

			
	var clProvincia=document.getElementById("CL_PROVINCIA");
	var prSelect=document.getElementById("RF_PROVINCIA");
	if (document.getElementById("pProvincia")){

		laProvincia=document.getElementById("pProvincia").value;
		alert(laProvincia);
		if (laProvincia != ""){
			if (prSelect.options.length>0){
				for (var i=0;i<prSelect.options.length;i++){
					//alert("Sel:"+prSelect.options[i].text+" Par: "+laProvincia);
					if (prSelect.options[i].text==laProvincia){
						prSelect.options[i].selected=true;
					}
				}	
			}
		}
		else {
			if (prSelect.options.length>0){
				clProvincia.value=prSelect.options[prSelect.selectedIndex].text;
			}
		}
	}
		

}


function refrescaList() {

	// Página CARRITO Refrescar Listado ...
}

function anadeCarritoPage(idA,clA) {

	var cURL="/portal/portalg.pl?getCarrito=3&idA="+idA+"&clA="+clA;
	// alert("Añadir a carrito por ID : \n"+cURL);
	var content=httpRead(cURL);
	
	var miCant=document.getElementById("artCant-"+idA);
	var miIva=document.getElementById("artIVA-"+idA);
	var miPrec=document.getElementById("artPrecio-"+idA);
	var miIvaP=document.getElementById("artIVAp-"+idA);
	var miPVP=document.getElementById("artPVP-"+idA);


	var miCantInt=parseInt(miCant.innerHTML);
	miCantInt++;

	var miPrecioArray=miPrec.innerHTML.split(" ");

	var miPrecioFloat=parseFloat(miPrecioArray[0]);
	var miIVAArray=miIva.innerHTML.split(" ");
	var miIVAPArray=miIvaP.innerHTML.split(" ");


	var miIVA=parseFloat(miIVAArray[0]);
	var miIVAP=parseFloat(miIVAPArray[0]);

	var miRealPrice=miCantInt*miPrecioFloat;

	var miIVAAPFloat=((miRealPrice*miIVAP)/100);

//	var miTotal=parseFloat(miRealPrice+miIVAAPFloat);
//	miTotal=parseFloat(miTotal+miIVAAPFloat);
//	miTotal+=miIVAAPFloat;
	var vs = miIVAAPFloat.toString()
	var dl = vs.indexOf(".")
	var miRIVA=vs.substring(0,dl+3);
	miIVAAPFloat=parseFloat(miRIVA);
   
	alert("mRP:" +miRealPrice+" mIVA:"+miIVAAPFloat);
	miCant.innerHTML=miCantInt+'';
	miIva.innerHTML=miIVAAPFloat+' &euro;';

	var newTotal=(parseFloat(miRealPrice)+parseFloat(miIVAAPFloat));

	//var rNewTotal=round_decimals(newTotal,2);
	
	miPVP.innerHTML=newTotal+' &euro;';

	calcCarritoPage();

}

function redondeoDec(cant) {

	


}


function quitaCarritoPage(idA,clA) {

	var cURL="/portal/portalg.pl?getCarrito=4&idA="+idA+"&clA="+clA;

	// alert("Añadir a carrito por ID : \n"+cURL);
	var content=httpRead(cURL);
	
	var miCant=document.getElementById("artCant-"+idA);
	var miIva=document.getElementById("artIVA-"+idA);
	var miPrec=document.getElementById("artPrecio-"+idA);
	var miIvaP=document.getElementById("artIVAp-"+idA);
	var miPVP=document.getElementById("artPVP-"+idA);


	var miCantInt=parseInt(miCant.innerHTML);
	miCantInt--;

	if (miCantInt>0) {
	
		var miPrecioArray=miPrec.innerHTML.split(" ");

		var miPrecioFloat=parseFloat(miPrecioArray[0]);
		var miIVAArray=miIva.innerHTML.split(" ");
		var miIVAPArray=miIvaP.innerHTML.split(" ");


		var miIVA=parseFloat(miIVAArray[0]);
		var miIVAP=parseFloat(miIVAPArray[0]);
	
		var miRealPrice=miCantInt*miPrecioFloat;

		var miIVAAPFloat=((miRealPrice*miIVAP)/100).toFixed(2);
		miIVAAPFloat=round_decimals(miIVAAPFloat,2);

		miCant.innerHTML=miCantInt+'';
		miIva.innerHTML=miIVAAPFloat+' &euro;';

		var newTotal=parseFloat(miRealPrice)+parseFloat(miIVAAPFloat);
		var rNewTotal=round_decimals(newTotal,2);
		miPVP.innerHTML=rNewTotal+' &euro;';


	}

	calcCarritoPage();

}

function carritoCompraBodyLoad() {


	calcCarritoPage();
}
function calcCarritoPage() {




	if (document.getElementById("selTrans")){
	
		var generalTotalCarrito=getCarritoTotal();
		var splitTotal=new Array;
		splitTotal=generalTotalCarrito.split("-");

		var totalCarrito=parseFloat(splitTotal[0],2);
		var totalCarritoIVA=parseFloat(splitTotal[1],2);

		var selT=document.getElementById("selTrans");
		var lT=document.getElementById("cgTempList");
		//var sT=document.getElementById("sumaCarrito");
		//var tT=document.getElementById("totalCarrito");

		//var valSuma=parseFloat(sT.innerHTML);
	
		var valTr=selT.options[selT.selectedIndex].value;
		var arrTr=valTr.split("-");
		var impTr=parseFloat(arrTr[1],2);

		var valSumaIVA=(parseFloat(totalCarrito,2)+parseFloat(totalCarritoIVA,2));

		var valSuma=parseFloat(totalCarrito);

		
		valSuma+=impTr;


		var valTotalCarrito=parseFloat(valSumaIVA+impTr).toFixed(2);
//		valTotalCarrito=round_decimals(valTotalCarrito,2);
//		impTr=round_decimals(impTr,2);
//		valSuma=round_decimals(valSuma,2);

		totalCarrito=totalCarrito.toFixed(2);
		totalCarritoIVA=totalCarritoIVA.toFixed(2);
		impTr=impTr.toFixed(2);
		valSumaIVA=valSumaIVA.toFixed(2);
		//valTotalCarrito=valTotalCarrito.toFixed(2);
	}
		// lT.innerHTML='Importe Transporte '+impTr+' &euro; Total : '+valSuma+' &euro; Total IVA:'+totalCarritoIVA+' &euro; Total Compra: '+valTotalCarrito+' &euro;';
		//	tT.innerHTML=valSuma+'';
		
		if (document.getElementById("cgSubTotalArticulos"))	{
			document.getElementById("cgSubTotalArticulos").innerHTML=totalCarrito+' &euro;';
		}
		if (document.getElementById("cgSubTotalIVA"))	{
			document.getElementById("cgSubTotalIVA").innerHTML=totalCarritoIVA+' &euro;';
		}
		if (document.getElementById("cgSubTotal"))	{
			document.getElementById("cgSubTotal").innerHTML=''+valSumaIVA+' &euro;';
		}

		if (document.getElementById("cgTransporteCarrito"))	{
			document.getElementById("cgTransporteCarrito").innerHTML=impTr+' &euro;';
		}
		if (document.getElementById("cgTotales"))	{
			document.getElementById("cgTotales").innerHTML=valTotalCarrito+' &euro;';
		}


		//lT.innerHTML='<ul><li><span>Total '+totalCarrito+' &euro;</span></li><li><span>IVA '+totalCarritoIVA+' &euro;</span></li><li><span>Subtotal '+valSumaIVA+' &euro;</span></li><li><span>Transporte '+impTr+' &euro;</span></li><li><span>Total Compra '+valTotalCarrito+' &euro;</span></li></ul>';
	
	

	
}

function comprar(elPaso) {


	if (elPaso='paso1') {
		// estamos en el carrito o qué
		var selT=document.getElementById("selTrans");
		var valTr=selT.options[selT.selectedIndex].value;
		var arrTr=valTr.split("-");
		var impTr=parseFloat(arrTr[1]);
		document.getElementById("transSelectF").value=impTr;

		if (document.getElementById("despurse")){
		
			var ckDescontar=document.getElementById("despurse").checked;
			var isDescontar;
			if (ckDescontar==true){
				document.getElementById("descontarMVF").value="1";
			}
			else {
				document.getElementById("descontarMVF").value="0";
			}
		}
		else {
			document.getElementById("descontarMVF").value="0";
		}

		if (document.getElementById("selregalo")){
			var selR=document.getElementById("selregalo").value;
			document.getElementById("regaloSelectF"),value=selR;
		}
		else {
			document.getElementById("regaloSelectF"),value="";
		}

		document.getElementById("formCompraF").submit();

	}

}


function round_decimals(original_number, decimals) {
    var result1 = original_number * Math.pow(10, decimals)
    var result2 = Math.round(result1)
    var result3 = result2 / Math.pow(10, decimals)
    return pad_with_zeros(result3, decimals)
}

function pad_with_zeros(rounded_value, decimal_places) {

    // Convert the number to a string
    var value_string = rounded_value.toString()
    
    // Locate the decimal point
    var decimal_location = value_string.indexOf(".")

    // Is there a decimal point?
    if (decimal_location == -1) {
        
        // If no, then all decimal places will be padded with 0s
        decimal_part_length = 0
        
        // If decimal_places is greater than zero, tack on a decimal point
        value_string += decimal_places > 0 ? "." : ""
    }
    else {

        // If yes, then only the extra decimal places will be padded with 0s
        decimal_part_length = value_string.length - decimal_location - 1
    }
    
    // Calculate the number of decimal places that need to be padded with 0s
    var pad_total = decimal_places - decimal_part_length
    
    if (pad_total > 0) {
        
        // Pad the string with 0s
        for (var counter = 1; counter <= pad_total; counter++) 
            value_string += "0"
        }
    return value_string
}



function cgGal(imgRuta,imgLeyenda) {

	if (document.getElementById("cg-Gallery-bigPicture")){
	
		var contenedorImg=document.getElementById("cg-Gallery-bigPicture");
		contenedorImg.innerHTML='<p><span><img id="cgGaleriaPic" title="'+imgLeyenda+'" alt="'+imgLeyenda+'" src="'+imgRuta+'"/></span></p>';

	}



}



function cambiaDir(which) {

	//var framePedido=top.frames["framePedidoM"];

	if (which=='F'){
		document.getElementById('marcoFacturaInfo').innerHTML="";
		var miOptVal=document.getElementById('dirFraID').value;
		//var arrVals=miOptVal.split('-');
		document.getElementById('marcoFacturaInfo').innerHTML=document.getElementById('dir-'+miOptVal).value;
		creaCookieSize('dirF',miOptVal);
		borraCookieSize('selFP');
		//document.getElementById("rfIDDirF").value=arrVals[0];
		//document.getElementById("rfPRDirF").value=arrVals[1];
		//document.getElementById("rfPADirF").value=arrVals[2];
		

	}
	if (which=='E'){

		document.getElementById('marcoEnvioInfo').innerHTML="";
		var miOptVal=document.getElementById('dirEnvID').value;
		//var arrVals=miOptVal.split('-');
		document.getElementById('marcoEnvioInfo').innerHTML=document.getElementById('dir-'+miOptVal).value;
		creaCookieSize('dirE',miOptVal);
		borraCookieSize('selTR');
		//document.getElementById("rfIDDirE").value=arrVals[0];
		//document.getElementById("rfPRDirE").value=arrVals[1];
		//document.getElementById("rfPADirE").value=arrVals[2];

	}


//	refrescaPedido();
}
function cgGoShop(elPaso) {

	var elPasoURL=new Array;
	elPasoURL[0]="/compras/carrito.html";
	elPasoURL[1]="/compras/compras_paso_1.html";
	elPasoURL[2]="/compras/compras_paso_2.html";
	elPasoURL[3]="/compras/compras_paso_3.html";
	elPasoURL[4]="/compras/compras_final.html";
	if (elPaso==2){
		// Grabar Direcciones y continuar a formas de pago
		creaCookieSize('dirE',document.getElementById('dirEnvID').value);
		creaCookieSize('dirF',document.getElementById('dirFraID').value);
//		document.location=elPasoURL[elPaso];
		return true;
	}
	if (elPaso==3){
		// Grabar forma de pago y continuar a final
		var valFP=-1;
		for (var i=0;i<document.fpagoSelect.selFP.length;i++){
		//	alert("i "+i+" v "+document.getElementById("selFP").value+" vv "+document.fpagoSelect.selFP[i].value);
			if (document.fpagoSelect.selFP[i].checked){
				valFP=document.fpagoSelect.selFP[i].value;
				creaCookieSize('selFP',valFP);
				break;
			}
		}
//		alert("FP "+valFP);
		if (valFP==-1){
			alert("Debe seleccionar una Forma de Pago para este pedido.");
			return false;
		}
		else {
			var selTR=document.getElementById("selTrans").value;
			var selTArray=selTR.split("-");
			creaCookieSize('selTR',selTArray[0]);

			//document.location=elPasoURL[elPaso];
			return true;
		}

	}
	if (elPaso==4){

		// check condiciones
		var pasaCheck=0;
		var alertTextF="";
		if (document.getElementById("mayorok").checked)	{
			if (document.getElementById("condicionesok").checked){
				pasaCheck=1;
			}
			else {
				pasaCheck=0;
				alertTextF="Debe aceptar las condicones de compra.";
			}

		}
		else {
			pasaCheck=0;
			alertTextF="Debe certificar que es mayor de edad.";
		}
		if (pasaCheck==0)	{

			var nowColor;

			if (document.getElementById("condicionesCompra")){
				nowColor=document.getElementById("condicionesCompra").style.backgroundColor;
				document.getElementById("condicionesCompra").style.backgroundColor="#FFCCCC";
			}
			alert(alertTextF);
			if (document.getElementById("condicionesCompra")){
				document.getElementById("condicionesCompra").style.backgroundColor=nowColor;
			}
			return false;


		}
		else {
				// submitFinalForm??
				// document.location=elPasoURL[elPaso]+"?obsCliente="+document.getElementById("obsCliente").value;
				return true;

		}

	}


}
function cambiaTransPago(){

	var miSel=document.getElementById("selTrans").value;
	var selTarray=miSel.split("-");
	var selTarifa=parseFloat(selTarray[1],2).toFixed(2);
	creaCookieSize('selTR',selTarray[0]);
	document.getElementById("transTarifa").innerHTML=selTarifa+" &euro;";


}
function chkFormaPago() {

		var valFP=-1;
		for (var i=0;i<document.fpagoSelect.selFP.length;i++){
		//	alert("i "+i+" v "+document.getElementById("selFP").value+" vv "+document.fpagoSelect.selFP[i].value);
			if (document.getElementById("fpagoDesc:"+document.fpagoSelect.selFP[i].value))	{
				//document.getElementById("fpagoDesc:"+document.fpagoSelect.selFP[i].value).style.display="none";
			}
			if (document.fpagoSelect.selFP[i].checked){

				creaCookieSize('selFP',document.fpagoSelect.selFP[i].value);
				valFP=i;
			}
		}
		if (valFP>-1){
			document.getElementById("fpagoDescDiv").innerHTML=document.getElementById("fpagoDesc:"+document.fpagoSelect.selFP[valFP].value).innerHTML;
		}


}

function cleanCarrito() {

	borraCookieSize("carrito");
	borraCookieSize("userSession");
}


function adultosDisplay() {

	if (document.getElementById("adultos-ban")){

		var miDiv=document.getElementById("adultos-ban");
		miDiv.style.left="20%";
		miDiv.style.top="20%";
		miDiv.style.display="block";


	}


}

function adultosAceptar() {

	if (document.getElementById("adultos-ban")){

		var miDiv=document.getElementById("adultos-ban");
		miDiv.style.display="none";

	}
}

function adultosCancelar() {

	borraCookieSize("userSession");
	document.location="http://es.wikipedia.org";

}
