
// It is assumed that AJAX is supported in the web browser being used
var httpRequestSupported = true;

var rutaImagenNG = "";

var timeNow = "";
///////////////////////////////////////////////////////////
// Returns true if AJAX requests are supported by the 
// clients web browser.  Else false.
// On a true result, the object returned is an 
// Active-X XMLHTTP object.
//
// In Internet Explorer, you create an http object using 
// new ActiveXObject("Msxml2.XMLHTTP") or 
// new ActiveXObject("Microsoft.XMLHTTP") 
// depending on the version of MSXML installed. 
//
// In Mozilla and Safari (Gecko engine) you use 
// new XMLHttpRequest()
//
// IceBrowser is not supported in this code
//
// @return boolean
///////////////////////////////////////////////////////////
function isHttpRequestSupported() {
	
	if (window.XMLHttpRequest) {   
		// Test if the Gecko engine is running.  Gecko supports AJAX
		httpRequest = new XMLHttpRequest(); 
		if (httpRequest.overrideMimeType) { 
			httpRequest.overrideMimeType('text/xml'); 
		} 
	} else if (window.ActiveXObject) { 
		// Test if an IE engine is running
		try { 
			httpRequest = new ActiveXObject("Msxml2.XMLHTTP"); 
		} catch (e) { 
			try { 
				httpRequest = new ActiveXObject("Microsoft.XMLHTTP"); 
			} catch (e) {} 
		} 
	} 
	
	if (!httpRequest) { 
		httpRequestSupported = false;
	} 
	
	
	return httpRequest;
} // end function

function ocultarDiv(id){
	
	document.getElementById(id).style.position = "";
	document.getElementById(id).style.display = "none";
   	primerDiv=1;

}

var primerDiv=1;

function creatediv(id, width, height, left, top) {
   
   	var newdiv = document.createElement('div');
   	newdiv.setAttribute('id', id); 
   
   	var w=50;
   	var h=50
   
   	if (width) {
    	newdiv.style.width = w;
  	}
   
   	if (height) {
		newdiv.style.height = h;
   	}
   
   	var winWidth= (screen.width-w)/2; 
	var winHeight = (screen.height-h)/2-180; 
	
   	if ((left || top) || (left && top)) {
       	newdiv.style.position = "absolute";
       
       	if (left) {
        	newdiv.style.left = winWidth;
       	}
       
       	if (top) {
        	newdiv.style.top = winHeight;
		}
   	}
   	html="<img src='"+rutaImagenNG+"botonGuardar002.png' id='espera' name='espera' width='100%' height='100%' border='0'>";
   
   	if (html) {
       	newdiv.innerHTML = html;
   	} else {
    	newdiv.innerHTML = "nothing";
   	}
   
   	document.body.appendChild(newdiv);
   	primerDiv=0;
	
} 



///////////////////////////////////////////////////////////
// Makes a HTTP request back to the server given a URL.
//
// callbackFunction is a string value containing the name
// of a method to call when the HTTP request is completed.
// The resulting output of the HTTP request is passed in
// as a variable to the callback function.  The callback
// function formats the response to be displayed in 
// a web browser.
//
// if returnData is specified, the response is retruned
// in xml
//
// @param url
// @param callbackFunction
// @param returnData
///////////////////////////////////////////////////////////
function makeHttpRequest(url, callbackFunction, origen ,returnData) 
{ 
	
	var httpRequest = false; 
	
	// Exit if this function is not supported
	if (!httpRequestSupported) {
		//alert('Exit if this function is not supported')
		return;  
	}
	
	// check if supported
	httpRequest = isHttpRequestSupported();
	
	
	if (!httpRequest) { 
	
		httpRequestSupported = false;
		return false; 
	} 
   
	// Map the response to the callback function
	httpRequest.onreadystatechange = function() { 
		
		switch (httpRequest.readyState){	
			case 1: 	        	
	        		
	            break;
			case 4:
	        	if (origen==1){
		        	hideCDivs();		        	
		        }
				if (httpRequest.status == 200) { 
					
					if (returnData) { 
						
						eval(callbackFunction + '(httpRequest.responseXML)'); 
					} else { 
						eval(callbackFunction + '(httpRequest.responseText)'); 
						
					} 
				} else { 
					// TODO:  Keep this line commented in production.  The user will have no idea what this means.
					//alert('The AJAX request was made to our backend server and the following error occurred: ' + httpRequest.status); 
					eval(callbackFunction + '("")'); 
				} 
				break;		
			
			
		} 
	}
	
	httpRequest.open('GET', url, true); 
	
	httpRequest.send(null); 
} // end function


/////////////////////////////////////////////////////////////////////
// Funcion que se utiliza el metodo makeHttpRequest, enviando una URL
/////////////////////////////////////////////////////////////////////
function sendDataAjax1Modelo(urlvar) {
		
	toggleBox('div1',0);  // hide the input box now until it is loaded
	
	//Llamada al metodo funcionPrueba
	makeHttpRequest(urlvar, 'funcionPrueba','');
	
	//se muestra el elemento		
	document.getElementById("ifrBgr").style.visibility='visible';
	
	toggleObj('ifrBgr',1);	//show the input box
	
}	


/////////////////////////////////////////////////////////////////////
//Funcion que utiliza dojo. Sirve para la utilizacion de formularios
/////////////////////////////////////////////////////////////////////
function sendDataAjax2Modelo(formName, functionCallbak) {
	var actionURL = document.getElementById(formName).action;	
	var kw = {
		url: actionURL,
		handleAs : "text",
		load: functionCallbak,
		error: function(data){
			alert("An error occurred: ", data);
		},
		timeout: 2000,
		form: formName
	};
	dojo.xhrGet(kw);
}

function pausecomp(millis) 
{
	var date = new Date();
	var curDate = null;

	do { 
		curDate = new Date(); 
	} 
	while(curDate-date < millis);
} 

var salir;

function refrescar(address, time){   

	salir = setTimeout("window.location.href='"+address+"'", time);
	
}




//Oculta o muestra el div
function toggleBox(szDivID, iState) // 1 visible, 0 hidden
{
	//alert(iState);
	if(iState==0){				
		pausecomp(1500);		
	}
	
	var obj = document.layers ? document.layers[szDivID] :
	document.getElementById ?  document.getElementById(szDivID).style :
	document.all[szDivID].style;
	obj.visibility = document.layers ? (iState ? "show" : "hide") : (iState ? "visible" : "hidden");
	estaEnDiv=0;

}

//Oculta o muestra un objeto html cualquiera
function toggleObj(objectId,iState) // 1 visible, 0 hidden
{
		
	var obj =  document.getElementById(objectId);
	if( obj != null ){
		obj.style.display = ( iState ? "" : "none" );
	}	
}

	
function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
}

//Login rapido
function senddataDojo(isShopCart,enlace, formulario) {
	
	var callback = function(data){
		
		if ( data.indexOf("variable=ERROR")>-1 ){			
				//document.getElementById("divPrueba2").innerHTML = data;
				//Se retira la marca de error <!-- variable=ERROR -->
				data2 = data.substring( 0, data.indexOf("<!--"));
				alert(trim(data2));
		}else{
		
			var linkLogin1 = window.location.href;
			var linkLogin2 = linkLogin1.substring( linkLogin1.indexOf("/servlet/") + 9, linkLogin1.length);
			
			//Verificacion en caso sea: Category
			if ( linkLogin2.indexOf("CategoryDisplay?")>-1 ){
				//procesar el category
				linkLogin2 = "CategoryDisplay?categoryId="+linkLogin2.substr(linkLogin2.indexOf("categoryId")+11, 5);
			}
			//Verificacion en caso sea: Home
			if ( linkLogin2.indexOf("StoreCatalogDisplay?")>-1 ){
				//procesar el category
				linkLogin2 = "StoreCatalogDisplay";
			}
			//Verificacion en caso sea: Bolsa de Compras
			if (isShopCart==1){
				linkLogin2 = enlace;
			}
			
			formulario.URL.value = linkLogin2;
			formulario.nextURL.value = linkLogin2;
			
			formulario.submit();
		}
	};
	sendDataAjaxDojo("logon", callback);
	/*
	var address; 
	// 1: bolsa de compras 0: otra pagina
	var flag ;
	
	if (isShopCart==0)
		address= window.location.href;
	else
		address=enlace;
	alert("address = " + address)
	BrowserDetect.init();
	var navegador=BrowserDetect.browser;
	//por confirmar
	if (navegador=="Safari")
		address="http://localhost:8080/webapp/wcs/stores/servlet/StoreCatalogDisplay?storeId=10051&catalogId=10051";
	
	refrescar(address,500)
			
	return false;
	*/
}

function trim(str){
	return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}

function sendDataAjaxDojo(formName, functionCallbak) {
	
	var actionURL = document.getElementById(formName).action;

	var kw = {
		url: actionURL,
		handleAs : "text",
		load: functionCallbak,
		error: function(data){
			alert("an error occurred: " + data, data);
			isDeshabilitaCamposCantidad(false);

		},
		timeout: 10000,
		form: formName
	};

	dojo.xhrGet(kw);
}

function mostrarMiniShopCart(text) {

	document.getElementById("listaProductos").innerHTML = text;
	toggleBox('div1',1);	
}



//funcion que se llama para mostrar el minishopcart con la informacion que se requiere

function sendData(urlvar, time) {
	//Se envia un valor aleatorio la primera vez que se carga el minicarro en una pagina.
	var aleatorio;	
	if (timeNow==""){
		timeNow = time;
		aleatorio=Math.random();
	}else{
		aleatorio = "";
	}
	
	var w=450; // altura div
	var h=500; // ancho div
	
	var imagen = document.getElementById("carrito");
	var coordenadasImagen = findPos(imagen);
	
	var altoCarrito = 23;
	
	var winl = (screen.width-w)/2; 
	var wint = coordenadasImagen[1]+altoCarrito;
	
	document.getElementById("div1").style.top=wint+'px';	
	document.getElementById("div1").style.right=winl+'px';
	
	var url = urlvar;
	
	makeHttpRequest(url+aleatorio, 'mostrarMiniShopCart','');
		
	//Inicio cargar iframe que acompańa al div como fondo.
	document.getElementById("ifrBgr").style.top=document.getElementById("div1").style.top;
	document.getElementById("ifrBgr").style.right=document.getElementById("div1").style.right;	
	document.getElementById("ifrBgr").style.visibility='visible';

	toggleObj('ifrBgr',1);
	
}

function senddataDojoShopCart(formName) {
	
	var callback = function (data){
		document.getElementById("listaItems").innerHTML = data;
		document.getElementById("busy").value = '0';
	};

	sendDataAjaxDojo(formName, callback);
	return false;
}

function sendDataShopCart(urlvar, rutaImagen) {
	var aleatorio=Math.random(); 
	rutaImagenNG = rutaImagen;
	makeHttpRequest(urlvar+aleatorio, 'shopCart',1);
}

function shopCart(text) {
	document.getElementById("listaItems").innerHTML = text;
}

function sendDataBillingAddress(urlvar) {
	var aleatorio=Math.random(); 
	makeHttpRequest(urlvar+'&aleatorio='+aleatorio, 'billingAddress','');
}

function billingAddress(text) {
	document.getElementById("divAddressDetail").innerHTML = text;
}

function sendDataProducts(urlvar) {
	var aleatorio=Math.random(); 
	makeHttpRequest(urlvar+'&aleatorio='+aleatorio, 'products','');
}

function products(text) {
	document.getElementById("divProducts").innerHTML = text;
	RevisarDespachosSeleccionados();
}

function senddataDojoAddress (formName) {
	var callback = function (data){
			document.getElementById("divAddressDetail").innerHTML = data;
			//cargarProducts();
	};
	sendDataAjaxDojo(formName, callback);
	return false;
}

function sendDataShippingMethod (urlvar) {
	var aleatorio=Math.random(); 
	isDeshabilitaSelectDespacho(true);
	makeHttpRequest(urlvar+'&aleatorio='+aleatorio, 'shippingMethod','');
	//makeHttpRequest(urlvar, 'shippingMethod','');
}

function shippingMethod(text) {
	document.getElementById("divTotalesCompra").innerHTML = text;
	
	//al actualizar la seccion de montos totales de compra, tambien actualizar la seccion de montos de TRE si es necesario.
	cargarSeccionMontoTRE();
	
	//Al actualizar la seccion de montos totales de compra, tambien actualizar la seccion de simulador de pago con tarjeta CAR.
	cargarSeccionSimuladorCuotas();
	
	isDeshabilitaSelectDespacho(false);
}

function sendDataSeccionMontoTRE (urlvar) {
		
	var aleatorio=Math.random(); 
	makeHttpRequest(urlvar+'&aleatorio='+aleatorio, 'divSeccionMontoTRE', '');
}

function divSeccionMontoTRE(text) {
		
	document.getElementById("divSaldoTRE").innerHTML = text;
	document.getElementById("montoPagarTRE").onblur();
}

function senddataDojoRegalo (formName) {
	alert("AjaxUtil - senddataDojoRegalo - formName1 = " + formName);
	var callback = function (data){
			document.getElementById("divRegalos").innerHTML = data;
	};
	alert("AjaxUtil - senddataDojoRegalo - formName2 = " + formName);
	sendDataAjaxDojo(formName, callback);
	return false;
}


// codigo para determinar el navegador, version y SO
var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};

cDivs = new Array();


//bloqueo de elementos cuando se esta actualizando pagina con ajax
function disableDivs()
{
	d = document.getElementsByTagName("BODY")[0];
	for(x=0;x<arguments.length;x++)
	{
	    if (document.getElementById(arguments[x]))
	    {
	    xPos = 0;
	    yPos = 0;
	    oWidth = screen.width-50;
	    oHeight = screen.height;
	    cDivs[cDivs.length] = document.createElement("DIV");
	    cDivs[cDivs.length-1].style.width = oWidth+"px";
	    cDivs[cDivs.length-1].style.height = oHeight+"px";
	    cDivs[cDivs.length-1].style.position = "absolute";
	    cDivs[cDivs.length-1].style.left = xPos+"px";
	    cDivs[cDivs.length-1].style.top = yPos+"px";
	    d.appendChild(cDivs[cDivs.length-1]);
	    }
	}
}

//desbloqueo de elementos luego de actulizarse con ajax
function hideCDivs()
{
	for (hippopotamus=0;hippopotamus<cDivs.length;hippopotamus++)
	{
		document.getElementsByTagName("BODY")[0].removeChild(cDivs[hippopotamus]);
	}
	cDivs = [];
}

function verificaUsuario(form){
	if (form.rut.value != '') {
		if (form.dv.value != '') {
			if (form.logonPassword.value != '') {
				return true;
			} else {
				alert("Ingrese su clave secreta");
				form.logonPassword.focus();
				return false;     
			}
		} else {
			alert("El parametro 'digito verificador' es obligatorio");
			form.dv.focus();
			return false;     
		}
	} else {
		alert("El parametro 'rut' es obligatorio");
		form.rut.focus();
		return false;     
	}
}


function loginRapido(isShopCart,enlace, formulario) {

	if (!verificaUsuario(formulario)){
		return false;
	}
	
	//Valida que el RUT este bien construido. 05-03-2009 INI
	if(!valida_RUT()){
		return false;
	}
	
	//Valida que el RUT este bien construido. 05-03-2009 FIN
	
	var linkLogin1 = window.location.href;
	var linkLogin2 = linkLogin1.substring( linkLogin1.indexOf("/servlet/") + 9, linkLogin1.length);
	
	//Verificacion en caso sea: Category
	if ( linkLogin2.indexOf("CategoryDisplay?")>-1 ){
		//procesar el category
		//linkLogin2 = "CategoryDisplay?categoryId="+linkLogin2.substr(linkLogin2.indexOf("categoryId")+11, 5);
	}
	//Verificacion en caso sea: Home
	if ( linkLogin2.indexOf("StoreCatalogDisplay?")>-1 ){
		//procesar el category
		//linkLogin2 = "StoreCatalogDisplayView";
	}
	//Verificacion en caso sea: Bolsa de Compras
	if (isShopCart==1){
		linkLogin2 = enlace;
	}
		
	formulario.URL.value = linkLogin2;
	formulario.nextURL.value = linkLogin2;
		
	formulario.submit();
}



/* -------------------------------------------------------------------
FORMULARIO LOGON DE RIPLEY
---------------------------------------------------------------------*/
function valida_RUT(){

	var ElRut = document.logon.rut.value.toUpperCase();	
	var ElDv = document.logon.dv.value.toUpperCase();
	
	var largo_rut = ElRut.length;
	var largo_dv = ElDv.length;
	var RutC = ElRut+ElDv;

	var pwd= document.logon.logonPassword.value;

	var largo_pwd= pwd.length;

	var rut00 = "000000000";

	if (ElRut.substring(0, 1) == "0"){
            alert("El RUT \""+ElRut+"\" no es válido para el dígito verificador \""+ElDv+"\".");
            return (false);
	}

	if (rut00.substring(0, largo_rut) == ElRut){
            alert("El RUT \""+ElRut+"\" no es válido para el dígito verificador \""+ElDv+"\".");
            return (false);
	}
	
	for(i=0;i<largo_rut;i++){
		c=ElRut.charAt(i);
		if (c<"0" || c>"9"){
    		alert("El parámetro \"rut\" no debe tomar el valor \""+ElRut+"\".");
        
        return (false);
		}
	}

        c=ElDv.charAt(0);
	if ( (c<"0" || c>"9") && c!="K" ){
           alert("El RUT \""+ElRut+"\" no es válido para el dígito verificador \""+ElDv+"\".  ");
           
           return (false);
	}

	var suma=0;
	var mult=2;
	
	if (ElDv=="K") ElDv="10";
	for (i=largo_rut-1;i>=0;i--){
		c=ElRut.charAt(i);
		suma+=parseInt(c,10)*mult;
		mult++;
		if (mult>7) mult=2;
	}

	var calculado=11-suma%11;
	if (calculado==11) calculado=0;
	if(parseInt(ElDv)!=calculado){           
           alert("El RUT \""+ElRut+"\" no es válido para el dígito verificador \""+document.logon.dv.value.toUpperCase()+"\".  ");
           
           return (false);
        }

	
 return (true);
}

/* -------------------------------------------------------------------
METODO PARA GUARGAR DATOS DEL MENSAJE DE REGALO
---------------------------------------------------------------------*/
function sendDataRegalo(urlvar) {
	makeHttpRequest(urlvar, 'divRegalosMostrar','');
}
function divRegalosMostrar(text) {
	document.getElementById("divRegalos").innerHTML = "";
}