// Instancia XMLHttpRequest
var xmlHttp = createXmlHttpRequestObject();
// Mostrar error (true) o comportamiento AJAX (false)
var showErrors = true;
// Muestra el estado de Place Order, falso en otro caso
var placingOrder = false;
// Link de la accion del usuario
var actionObject = '';
// Crear un XMLHttpRequest instancia
function createXmlHttpRequestObject(){
    // Objeto XMLHttpRequest
    var xmlHttp;
    // Crear el objecto XMLHttpRequest
    try {
        // Create native XMLHttpRequest object
        xmlHttp = new XMLHttpRequest();
    } catch(e) {
        // Asumir Explorer 6 o menor
        var XmlHttpVersions = new Array("MSXML2.XMLHTTP.6.0", "MSXML2.XMLHTTP.5.0", "MSXML2.XMLHTTP.4.0","MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP");
        // Buscar la version
        for (i = 0; i < XmlHttpVersions.length && !xmlHttp; i++){
            try{
                // Intentamos crear el objeto
                xmlHttp = new ActiveXObject(XmlHttpVersions[i]);
            }
            catch (e) {} // Ignorar el error potencial
        }
    }

    // Devuelvo el objeto XMLHttpRequest creado satisfactoriamente
    if (xmlHttp){
        return xmlHttp;
    }
    // Si un error aparece lo paso a la funcion
    else{
        handleError("Error creando el objeto XMLHttpRequest.");
    }
}


// Muestro un mensaje de error o un comportamiento non-AJAX
function handleError($message){
    // Ignoro el error si es false
    if (showErrors){
        alert("Error encontrado: \n" + $message);
        return false;
    }
    // Comportamiento non-AJAX
    else if (!actionObject.tagName){
        return true;
    }
    // Comportamiento non-AJAX
    else if (actionObject.tagName == 'A'){
        window.location = actionObject.href;
    }
    // Comportamiento non-AJAX
    else if (actionObject.tagName == 'FORM'){
        actionObject.submit();
    }
}
/******************************************************/
//FUNCIONES CARRITO DE COMPRAS VENTANA PEQUEÑA
// Agregar un producto al Shopping cart
function addProductToCart(form,sel1,sel2){
	var ban;
	ban=0;
	
	if ( sel1.value == 0 && sel1.value != "")
	{
		alert("Please select your color from the pull down menu");
		ban=1;
	}
	if (sel2.value==0 && sel2.value != "")
	{
		alert("Please select your size from the pull down menu");
		ban=1;
	}
	
	if (ban==1)
	{
		return false;
	}
	else
	{
		// Muestro el mensaje de "Actualizando"
		document.getElementById('updating').style.visibility = 'hidden';
		// Vuelvo al form clasico si no existe el objeto XMLHttpRequest
		if (!xmlHttp)
			return true;
	
		// Crear la URL del request
		request = form.action + '&AjaxRequest';
		params = '';
		
		// Obtener atributos
		params ="&attr_Color=" + sel1.options[sel1.selectedIndex].text + "&attr_Size=" + sel2.options[sel2.selectedIndex].text;
	
		// Conectarse al servidor
		try{
		// Continuar si el objeto no esta ocupado
			if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0){
				// Enviar la peticion
				xmlHttp.open("POST", request, true);
				xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
				xmlHttp.onreadystatechange = addToCartStateChange;
				xmlHttp.send(params);
			}
		}catch (e){
			// Muestro el error si existe
			handleError(e.toString());
		}
		// Salgo de la funcion si todo esta bien
		return false;
	}
}

/******************************************************/
//FUNCIONES CARRITO DE COMPRAS VENTANA PEQUEÑA
// Funcion para recibir la respuesta
function addToCartStateChange(){
    // Leemos la respuesta cuando el estado es 4
    if (xmlHttp.readyState == 4){
        // Continuo si el HTTP status es OK
        if (xmlHttp.status == 200){
            try {
                //funcion para mostrar que se agrego
                updateCartSummary();
            }
            catch (e){
                handleError(e.toString());
            }
        }else{
            handleError(xmlHttp.statusText);
        }
    }
}

/******************************************************/
//FUNCIONES CARRITO DE COMPRAS VENTANA PEQUEÑA
// Agregar el producto al carrito
function updateCartSummary(){
    // Leo la respuest
    response = xmlHttp.responseText;
    // Si existe un error lo muestro
    if (response.indexOf("ERRNO") >= 0 || response.indexOf("error") >= 0) {
        handleError(response);
    }else{
        document.getElementById("cart-summary").innerHTML = response;
        // Escondo el mensaje de actualizando
        document.getElementById('updating').style.visibility = 'visible';
    }
}

/******************************************************/
//FUNCIONES DETALLES CARRITO DE COMPRAS
// Called on shopping cart update actions
function executeCartAction(obj){
    // Mostrar el mensaje "Actualizando..."
    
    // Salir si es  oprimido el boton Ordenar
    if (placingOrder)
        return true;


    document.getElementById('updating').style.visibility = 'visible';
    // Volvemos al classic submit si no soporta AJAX
    if (!xmlHttp)
        return true;

    // Referencia al objeto
    actionObject = obj;
    // Inicializar variables
    response = '';
    params = '';
    // Si click el link entonces enviamos el request
    if (obj.tagName == 'A'){
        url = obj.href + '&AjaxRequest';
    }
    // oBtenemos los elementos enviados en el form
    else {
        url = obj.action + '&AjaxRequest';
        formElements = obj.getElementsByTagName('INPUT');

        if (formElements){
            for (i = 0; i < formElements.length; i++){
                if (formElements[i].name != 'place_order'){
                    params += '&' + formElements[i].name + '=';
                    params += encodeURIComponent(formElements[i].value);
                }
            }
        }
    }

    // Conectar al servidro
    try {
        // Miramos is no esta ocupado
        if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0){
            xmlHttp.open("POST", url, true);
            xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
            xmlHttp.onreadystatechange = cartActionStateChange;
            xmlHttp.send(params);
        }
    }
    catch (e){
        // Manejo de errores
        handleError(e.toString());
    }
    // Para el envio del clasico submit si ajax lo logro
    return false;
}


// Respuesta del servidro
function cartActionStateChange(){
    if (xmlHttp.readyState == 4){
        // Continuar solo si el estatus es "OK"
        if (xmlHttp.status == 200){
            try {
                // Leer la respuesta
                response = xmlHttp.responseText;
                // Si hubo error
                if (response.indexOf("ERRNO") >= 0 || response.indexOf("error") >= 0){
                    handleError(response);
                }else{
                    // Actualizo el carro
                    document.getElementById("contents").innerHTML = response;
                    // Escondo el mensaje de "Actualizando..."
                    document.getElementById('updating').style.visibility = 'hidden';
                 }
            } catch (e) {
                // Manejo de errores
                handleError(e.toString());
            }
        }else{
            // Manejo de errores
            handleError(xmlHttp.statusText);
        }
    }
}



function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}
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_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_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];}
}

function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}

function changeImage(nombre_imagen,path,selectcolor,imagendefecto){
/*	alert("Imagen: " + nombre_imagen + "\nDefecto: " + imagendefecto);*/
	if(selectcolor.value==0)
	{
		divMensaje=document.getElementById('div_ima');
		divMensaje.innerHTML='<img src="'+imagendefecto+'" alt="" width="290" height="400" border="0" />';
	}
	else
	{
		divMensaje=document.getElementById('div_ima');
		divMensaje.innerHTML='<img src="'+path+nombre_imagen+'" alt="" width="290" height="400" border="0" />';
	}
}

/*Funcion que me permite ocultar o mostrar parte de la informacion de envio de la orden dependiendo del Checked del checkboxbilling*/
function ocumosdiv(valcheck)
{
	miobj = document.getElementById('trbilling');
	if(valcheck.checked)
		miobj.style.display = "none";
	else
		miobj.style.display = "block";
}


//POPUP IMAGENES
var newwindow;
var wheight = 0, wwidth = 0;
function popimg(url, title, iwidth, iheight, colour) {
	var pwidth, pheight;
	//alert("entro"+url)
	if ( !newwindow || newwindow.closed ) {
		pwidth=iwidth+30;
		pheight=iheight+30;
		newwindow=window.open('','htmlname','width=' + pwidth +',height=' +pheight + ',resizable=1,top=50,left=10');
		wheight=iheight;
		wwidth=iwidth;
	}
	
	if (wheight!=iheight || wwidth!=iwidth ) {
		pwidth=iwidth+30;
		pheight=iheight+60;
		newwindow.resizeTo(pwidth, pheight);
		wheight=iheight;
		wwidth=iwidth;
	}
	
	newwindow.document.clear();
	newwindow.focus();
	newwindow.document.writeln('<html> <head> <title>' + title + '<\/title> <\/head> <body bgcolor= \"' + colour + '\"> <center>');
	newwindow.document.writeln('<a title="click para cerrar!" href="javascript:window.close();"><img src="' + url + '" border=0></a>');
	newwindow.document.writeln('<\/center> <\/body> <\/html>');
	newwindow.document.close();
	newwindow.focus();
}

//Funcion que me valida que el pais y los datos de envio del shipping method esten completos
function validaCartDetails(url){
	var msg;
	msg ="";
	selectPaisj = document.getElementById('selectPais');
	if(selectPaisj.value=="") msg ="Please choose country";
	if(msg=="") location.href = url ;
	else alert(msg)
}

//Funcion que me valida si el usuario realmente quiere eliminar la orden
function validar_eliminar_orden($url){
	if(confirm('Seguro que desea eliminar esta orden ?')){
		location.href = $url;
	}
}