var loadedobjects=""
var rootdomain="http://"+window.location.hostname

function ajaxpage(url, containerid){
var page_request = false
if (window.XMLHttpRequest) // if Mozilla, Safari etc
page_request = new XMLHttpRequest()
else if (window.ActiveXObject){ // if IE
try {
page_request = new ActiveXObject("Msxml2.XMLHTTP")
} 
catch (e){
try{
page_request = new ActiveXObject("Microsoft.XMLHTTP")
}
catch (e){}
}
}
else
return false
page_request.onreadystatechange=function(){
loadpage(page_request, containerid)
}
page_request.open('GET', url, true)
page_request.send(null)
}

function loadpage(page_request, containerid){
if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1))
document.getElementById(containerid).innerHTML=page_request.responseText
}

function loadobjs(){
if (!document.getElementById)
return
for (i=0; i<arguments.length; i++){
var file=arguments[i]
var fileref=""
if (loadedobjects.indexOf(file)==-1){ //Check to see if this object has not already been added to page before proceeding
if (file.indexOf(".js")!=-1){ //If object is a js file
fileref=document.createElement('script')
fileref.setAttribute("type","text/javascript");
fileref.setAttribute("src", file);
}
else if (file.indexOf(".css")!=-1){ //If object is a css file
fileref=document.createElement("link")
fileref.setAttribute("rel", "stylesheet");
fileref.setAttribute("type", "text/css");
fileref.setAttribute("href", file);
}
}
if (fileref!=""){
document.getElementsByTagName("head").item(0).appendChild(fileref)
loadedobjects+=file+" " //Remember this object as being already added to page
}
}
}




function popUp(URL) {
day = new Date();
id = "nueva";
eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=390,height=385,left = 10,top = 10');");
}


function popUp2(URL) {
day = new Date();
id = "nueva";
eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=440,height=530,left = 5,top = 5');");
}


function enviar()  {
        bFormError = false;   //Boolean variable to store form state

        strErrorList = "";    //String list of missing/errorsum fields

        if( document.forma.contacto.value==''  ) {bFormError = true;  strErrorList += "Name, ";}
        if( document.forma.ciudad.value==''   ) {bFormError = true;  strErrorList += "City, ";}
        if( document.forma.pais.value==''  ) {bFormError = true;  strErrorList += "Country, ";}
		if( document.forma.email.value=='@'  ) {bFormError = true;  strErrorList += "Email, ";}        
        if( document.forma.telefono.value==''  ) {bFormError = true;  strErrorList += "Phone, ";}

		contact = document.forma.contacto.value;
		ciudad = document.forma.ciudad.value;
		pais = document.forma.pais.value
		email = document.forma.email.value;
		telefono = document.forma.telefono.value;
		comentarios = document.forma.comentario.value;
		
		cadena = contact + '|' +  ciudad + '|' + pais + '|' + email + '|' + telefono + '|' + comentarios;

		var URL = 'contacto.php?valor=' + cadena;

        if( bFormError == true ) {
                alert("Lo siento, Debe diligenciar los siguientes campos:\n"
                     +strErrorList
                     +"\n\n");
                return false;
        } else {
			day = new Date();
			id = "SEND";
			eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=200,height=200,left = 5,top = 5');");
		}
//      return needComments();                      ||  
} 


//---------------------------------------------------------------------||
// FUNCTION:    checkForm                                              ||
// PARAMETERS:  Form object, and true/false if we should check for     ||
//              a credit card number. You shouldn't accept credit cards||
//              via email.  Only use that when you are connected to a  ||
//              secure server.                                         ||
// RETURNS:     boolean (True form is correct, False form is in error) ||
// PURPOSE:     To check form elements                                 ||
//---------------------------------------------------------------------||

//---------------------------------------------------------------------||
// FUNCTION:    CKquantity                                             ||
// PARAMETERS:  Quantity to                                            ||
// RETURNS:     Quantity as a number, and possible alert               ||
// PURPOSE:     Make sure quantity is represented as a number          ||
//---------------------------------------------------------------------||
function CKquantity(checkString) {

        strNewcantidad = "";    // String Adjusted Item Quantity
        count     = 0;          // Generic Loop Counter

        for (i = 0; i < checkString.length; i++) {
                ch = checkString.substring(i, i+1);

                if ((ch >= "0" && ch <= "9") || (ch == '.')) {
                        strNewcantidad += ch;
                }
        }

        if (strNewcantidad.length < 1)
                strNewcantidad = "1";

        return strNewcantidad;
}


//---------------------------------------------------------------------||
// FUNCTION:    AddToCart                                              ||
// PARAMETERS:  Form Object                                            ||
// RETURNS:     Cookie to user's browser, with prompt                  ||
// PURPOSE:     Adds a product to the user's shopping cart             ||
//---------------------------------------------------------------------||
function AddToCart(thisForm) {
elem1 =  thisForm.cantidad.value;
elem2 =  thisForm.producto.value;
if (elem1 == '' || elem2 == '') {		
	alert ("Debe asegurarse en escojer un producto con su respectiva cantidad!!");
} else {
		
	
        iNumberOrdered = 0;  //Integer number of products already ordered

        iNumberOrdered = GetCookie("NumberOrdered");
        iNumberOrdered++;

        if ( iNumberOrdered > 6 )
                alert("Disculpe, su carro esta lleno. Por favor efectúe su pedido.");
        else {
                dbUpdatedOrder = thisForm.cantidad.value + "|"
                                 + thisForm.producto.value;

                NewOrder = "Order." + iNumberOrdered;
                SetCookie (NewOrder, dbUpdatedOrder, null, "/");
                SetCookie ("NumberOrdered", iNumberOrdered, null, "/");

                
				nombre = thisForm.producto.value;
				//alert (nombre);
                arreglo = nombre.split('|');
                
                notice = thisForm.cantidad.value + " "
                         + arreglo[2]
                         + " se ha incluido en el shopping car de SVELTE.";

                alert(notice);
        }
}
}

//---------------------------------------------------------------------||
// FUNCTION:    getCookieVal                                           ||
// PARAMETERS:  offset                                                 ||
// RETURNS:     URL unescaped Cookie Value                             ||
// PURPOSE:     Get a specific value from a cookie                     ||
//---------------------------------------------------------------------||
function getCookieVal (offset) {
        var endstr = document.cookie.indexOf (";", offset);
        if (endstr == -1)
                endstr = document.cookie.length;
        return unescape(document.cookie.substring(offset, endstr));
}


//---------------------------------------------------------------------||
// FUNCTION:    FixCookieDate                                          ||
// PARAMETERS:  date                                                   ||
// RETURNS:     date                                                   ||
// PURPOSE:     Fixes cookie date, stores back in date                 ||
//---------------------------------------------------------------------||
function FixCookieDate (date) {
        var base = new Date(0);
        var skew = base.getTime();
        date.setTime (date.getTime() - skew);
}


//---------------------------------------------------------------------||
// FUNCTION:    GetCookie                                              ||
// PARAMETERS:  Name                                                   ||
// RETURNS:     Value in Cookie                                        ||
// PURPOSE:     Retrieves cookie from users browser                    ||
//---------------------------------------------------------------------||
function GetCookie (name) {
        var arg = name + "=";
        var alen = arg.length;
        var clen = document.cookie.length;
        var i = 0;
        while (i < clen)
                {
                var j = i + alen;
                if (document.cookie.substring(i, j) == arg) return getCookieVal (j);
                i = document.cookie.indexOf(" ", i) + 1;
                if (i == 0) break;
                }

        return null;
}


//---------------------------------------------------------------------||
// FUNCTION:    SetCookie                                              ||
// PARAMETERS:  name, value, expiration date, path, domain, security   ||
// RETURNS:     Null                                                   ||
// PURPOSE:     Stores a cookie in the users browser                   ||
//---------------------------------------------------------------------||
function SetCookie (name,value,expires,path,domain,secure) {
        document.cookie = name + "=" + escape (value) +
                        ((expires) ? "; expires=" + expires.toGMTString() : "") +
                        ((path) ? "; path=" + path : "") +
                        ((domain) ? "; domain=" + domain : "") +
                        ((secure) ? "; secure" : "");
}


//---------------------------------------------------------------------||
// FUNCTION:    DeleteCookie                                           ||
// PARAMETERS:  Cookie name, path, domain                              ||
// RETURNS:     null                                                   ||
// PURPOSE:     Removes a cookie from users browser.                   ||
//---------------------------------------------------------------------||
function DeleteCookie (name,path,domain) {
        if (GetCookie(name)) {
                document.cookie = name + "=" +
                                ((path) ? "; path=" + path : "") +
                                ((domain) ? "; domain=" + domain : "") +
                                "; expires=Thu, 01-Jan-70 00:00:01 GMT";
        }
}


//---------------------------------------------------------------------||
// FUNCTION:    MoneyFormat                                            ||
// PARAMETERS:  Number to be formatted                                 ||
// RETURNS:     Formatted Number                                       ||
// PURPOSE:     Reformats Dollar Amount to #.## format                 ||
//---------------------------------------------------------------------||
function moneyFormat(input) {
        var dollars = Math.floor(input)
        var tmp = new String(input)
        for (var decimalAt = 0; decimalAt < tmp.length; decimalAt++) {
                if (tmp.charAt(decimalAt)==".")
                        break;
        }

        var cents  = "" + Math.round(input * 100)
        cents = cents.substring(cents.length-2, cents.length)
        dollars += ((tmp.charAt(decimalAt+2)=="9")&&(cents=="00"))? 1 : 0;

        return dollars + "." + cents
}


function guarda(){
	var cantidad;
	cantidad = forma.detalleprod.length; 
	if(cantidad==undefined){
		var nombre = forma.detalleprod.value ;
		parent.document.order.producto.value = nombre;
	} else {
		var i;
		for (i=0;i< forma.detalleprod.length;i++){ 
       	if (forma.detalleprod[i].checked) 
        	break; 
    	} 
		var nombre = forma.detalleprod[i].value ;
		parent.document.order.producto.value = nombre;
	}
}


//---------------------------------------------------------------------||
// FUNCTION:    checkForm                                              ||
// PARAMETERS:  Form object, and true/false if we should check for     ||
//              a credit card number. You shouldn't accept credit cards||
//              via email.  Only use that when you are connected to a  ||
//              secure server.                                         ||
// RETURNS:     boolean (True form is correct, False form is in error) ||
// PURPOSE:     To check form elements                                 ||
//---------------------------------------------------------------------||
function checkForm(thisForm, checkForCreditCard)  {
        bFormError = false;   //Boolean variable to store form state
        bIsValidCard = false; //Boolean variable to store CC state
        strErrorList = "";    //String list of missing/errorsum fields

        if( thisForm.contacto.value==''  ) {bFormError = true;  strErrorList += "Nombre, ";}
        if( thisForm.ciudad.value==''   ) {bFormError = true;  strErrorList += "Ciudad, ";}
        if( thisForm.pais.value==''  ) {bFormError = true;  strErrorList += "Pais, ";}
		if( thisForm.email.value=='@'  ) {bFormError = true;  strErrorList += "Email, ";}        
        if( thisForm.telefono.value==''  ) {bFormError = true;  strErrorList += "Telefono, ";}
        if( bFormError == true ) {
                alert("Lo siento, pero debe ingresar los datos completos.\n"
                     +"Por favor digite todos los campos: \n\n"
                     +strErrorList
                     +"\n\n");
                return false;
        }
//      return needComments();                      ||  
} 




//---------------------------------------------------------------------||
// FUNCTION:    RemoveFromCart                                         ||
// PARAMETERS:  Order Number to Remove                                 ||
// RETURNS:     Null                                                   ||
// PURPOSE:     Removes an item from a users shopping cart             ||
//---------------------------------------------------------------------||
function RemoveFromCart(RemOrder) {
        if (confirm("Presiona 'Aceptar' y removeras el producto del shopping car.")) {
                NumberOrdered = GetCookie("NumberOrdered");
                for(i=RemOrder; i <  NumberOrdered; i++) {
                        NewOrder1 = "Order." + (i+1);
                        NewOrder2 = "Order." + (i);
                        database = GetCookie(NewOrder1);
                        SetCookie (NewOrder2, database, null, "/");
                }
                NewOrder = "Order." + NumberOrdered;
                SetCookie ("NumberOrdered", NumberOrdered-1, null, "/");
                DeleteCookie(NewOrder, "/");
                location.href=location.href;
        }
}


//---------------------------------------------------------------------||
// FUNCTION:    GetFromCart                                            ||
// PARAMETERS:  Null                                                   ||
// RETURNS:     Product Table Written to Document                      ||
// PURPOSE:     Draws current cart product table on HTML page          ||
//---------------------------------------------------------------------||
function GetFromCart() {
        NumberOrdered = 0;
        Total=0;
        TOTotal=0;
        TOquantity = " ";
        TOprice = " ";
        TOid_num = " ";
        TOname = " ";
        NumberOrdered = GetCookie("NumberOrdered");
        whattowrite = "";

        for (i = 1; i <= NumberOrdered; i++) {
                NewOrder = "Order." + i;
                database = "";
                database = GetCookie(NewOrder);

                Token0 = database.indexOf("|", 0);
                Token1 = database.indexOf("|", Token0+1);
                Token2 = database.indexOf("|", Token1+1);

                fields = new Array;
                fields[0] = database.substring( 0, Token0 );
                fields[1] = database.substring( Token0+1, Token1 );
                fields[2] = database.substring( Token1+1, Token2 );
                fields[3] = database.substring( Token2+1, database.length );

                Total = Total + (fields[1] * fields[0]);
                TOTotal = moneyFormat(Total);

                whattowrite += "<tr><td>" + fields[2] + "</td><td><font size=-1>"
                                + fields[3] + "</font></td><td>$" + fields[1]
                                + "</td><td><input type=text size=2 name=\"cantidad_"+ i +"\" value=\""
                                + fields[0] + "\"></td>"
                                + "<td><input type=button value=\"  Remover  \" onClick=\"RemoveFromCart("+i+")\"></td>"
                                + "<input type=hidden name=\"talla_"+ i +"\" value=\"" + fields[2] + "\">"
                                + "<input type=hidden name=\"referencia_"+ i +"\" value=\"" + fields[3] + "\">"
                                + "<input type=hidden name=\"precio_"+ i +"\" value=\"" + fields[1] + "\">";
        }

        document.write(whattowrite);
        document.write("</td></tr><tr><td colspan=2><b>SUBTOTAL</b></td><td>$");
        document.write(TOTotal);
        document.write("</td><td></td>");
}


//---------------------------------------------------------------------||
// FUNCTION:    WriteToForm                                            ||
// PARAMETERS:  Null                                                   ||
// RETURNS:     Product hidden fields Written to Document              ||
// PURPOSE:     Draws current cart product hidden fields on HTML form  ||
//---------------------------------------------------------------------||
function WriteToForm() {
        NumberOrdered = 0;
        Total=0;
        TOTotal=0;
        TOquantity = " ";
        TOprice = " ";
        TOid_num = " ";
        TOname = " ";
        NumberOrdered = GetCookie("NumberOrdered");
        whattowrite = "";

        for (i = 1; i <= NumberOrdered; i++) {
                NewOrder = "Order." + i;
                database = "";
                database = GetCookie(NewOrder);

                Token0 = database.indexOf("|", 0);
                Token1 = database.indexOf("|", Token0+1);
                Token2 = database.indexOf("|", Token1+1);

                fields = new Array;
                fields[0] = database.substring( 0, Token0 );
                fields[1] = database.substring( Token0+1, Token1 );
                fields[2] = database.substring( Token1+1, Token2 );
                fields[3] = database.substring( Token2+1, database.length );

                Total = Total + (fields[1] * fields[0]);
                TOTotal = moneyFormat(Total);

                document.write("<input type=hidden name=\"talla_"+ i +"\" value=\"" + fields[2] + "\">");
                document.write("<input type=hidden name=\"referencia_"+ i +"\" value=\"" + fields[3] + "\">");
                document.write("<input type=hidden name=\"precio_"+ i +"\" value=\"" + fields[1] + "\">");
                document.write("<input type=hidden name=\"cantidad_"+ i +"\" value=\"" + fields[0] + "\">");
        }
}



function comprobar(cadena1,cadena2,elementos,modo){

	fiels = new Array;
	fielsname = new Array;
	fiels = (cadena1.split("|"));
	fielsname = (cadena2.split("|"));

	var formerror = false;
	var strError = '';

	if (modo != 'buscar'){

		for(var j = 0; j < elementos; j++){

			valor = "texto=document.forma."+fiels[j]+".value";
			eval(valor);
			if(texto=='') {
				formerror = true;
				strError += fielsname[j];
				if(j != ((elementos*1)-1)){
					strError += " - ";
				}
			}
		}
		if (formerror == true) {
			alert("Lo siento, pero debe ingresar los datos completos.\n"
			+"Por favor digite todos los campos: \n\n"
			+strError
			+"\n\n");
			return false;
		}
	}
	return true;
}





