var windowLoaded = false;

function Asc(String)
{
	return String.charCodeAt(0);
}

function Chr(AsciiNum)
{
	return String.fromCharCode(AsciiNum);
}

function $(ID){
	return document.getElementById(ID);
}

function $F(ID){
        return document.getElementById(ID).value;
}


function trim(texto)
{
	texto.replace(/\s/,'');	
	return texto;
}

function O_History(parametro)
{
	if (!parametro)
		parametro=1;

	var myAjax = new Ajax.Request(
			'../templates/Order_History_Table.php', 
					{
						method: 'post', 
						parameters: {parametro1: parametro}, 
						onComplete: 'Eval_H'

					});
	return true;
}

function recalculateTotal(){
	tab = $('ShopCart'); 
	Total=0;
	TotalDisc="";
	for (i=0; fila = tab.getElementsByTagName('tr')[i]; i++)
		for (j=0; celda = fila.getElementsByTagName('td')[j]; j++)
			if (celda.className=='S_TotalC')
				Total+=parseFloat(celda.innerHTML.substring(2).replace(",",""));
	
           tab = document.getElementById('Coupons');
		   
                for (i=0; fila = tab.getElementsByTagName('tr')[i]; i++)
                  for (j=0; celda = fila.getElementsByTagName('td')[j]; j++)
                        if (celda.className=='Coupon_Amount'){
				DiscType=celda.innerHTML.substring(0,1);
				if (DiscType=='$')
					Total-=parseFloat(celda.innerHTML.substring(1).replace(",",""));
				else
				{
					var pDescuento = parseFloat(celda.innerHTML);
					Total-=(Total*(pDescuento/100));
				}
					
			}
	if (Total<0)
		Total=0;
	$('GTotal').innerHTML= '$ '+number_format(Total,2,".",",");
}

			

function CheckCoupons(Coupon)
{
		tab = document.getElementById('Coupons');
		if (tab.rows.length<2){
			for (i=0; i < tab.rows.length; i++){
					fila=tab.rows[i];
					if (fila.cells[1].innerHTML.toUpperCase()==Coupon.toUpperCase()){
	                                    alert("This coupon has already been used");
					    return false;
					}
			}
		}
		else
		{
			alert ("Sorry, only two coupon discount per orden");
			return false;
		}

return true;
}

function C_Discount(parametro)
{
	if (parametro=="")
		$("Coupon").style.borderColor="#FF0000";
	else
	{
		$("Coupon").value="";
		
		if (CheckCoupons(parametro))
		{
			
			var myAjax = new Ajax.Request(
				'/templates/general.php', 
				{
					method: 'post', 
					parameters: {parametro1: 5, parametro2: parametro}, 
					onComplete: 'Eval_H'
				});
			return true;
		}	
	}
}

function DeleteCoupon(C_code){
	var myAjax = new Ajax.Request(
                        '/templates/general.php',
                                        {
                                                method: 'post',
                                                parameters: {parametro1: '10',parametro2: C_code},
                                                onComplete: 'Eval_H'

                                        });
        return true;
}

function Get_News()
{
	var myAjax = new Ajax.Request(
			'templates/general.php', 
					{
						method: 'post', 
						parameters: {parametro1: 6}, 
						onComplete: 'Eval_H'

					});
	return true;
}


function isHide(element)
{
	var hide = false;
	if( typeof (element) == 'string' )
	{
		element = $(element);
	}
	if(element == undefined)
		return null;
		
	return(element.style.display == 'none' || element.style.visible == 'false')
}


function loadingCart()
{
	var contenedor = $('tbCartItems');
	removeElements(contenedor);
	return true;
}

function Show_Order(parametro)
{
	var myAjax = new Ajax.Request(
					'../templates/S_Order.php', 
					{
						method: 'post', 
						parameters: {Parameter: parametro}, 
						onComplete: 'Load_Order'
					});
	return true;	
}

function Load_Order(response){
	eval(response.responseText);
     	return true;
}

function Eval_H(response){
	eval(response.responseText);
	return true;
}

function SCart()
{
	var myAjax = new Ajax.Request(
					'/templates/general.php', 
					{
						method: 'post', 
						parameters: {parametro1: '4'}, 
						onComplete: 'ShoppinCart'
					});
	return true;
}

function ShoppinCart(response){
	eval(response.responseText);
	return true;
}

function SendMail(Mail)
{
	var myAjax = new Ajax.Request(
					'email.php', 
					{
						method: 'post', 
						parameters: {parametro1: '1', parametro2: Mail, parametro3: 1}, 
						onComplete: 'setEmail'
					});
	return true;
}

function setEmail(response)
{
	if (response.responseText!="")
		alert(response.responseText);
	return true;
}


function removeFromCart(parametro1,parametro2)
{
	loadingCart();
	var parametro2 = parseInt(parametro2);
	if(isNaN(parametro2))
		parametro2 = -1;
	var myAjax = new Ajax.Request(
					'/templates/general.php', 
					{
						method: 'post', 
						parameters: {parametro1: '3', parametro2: parametro1, parametro3: parametro2}, 
						onComplete: 'setCart'
					});
}


function showError(ajax,error)
{
	alert('Error ocurred: ' + error);
	return true;
}

function number_format( number, decimals, dec_point, thousands_sep ) {
    var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals;
    var d = dec_point == undefined ? "." : dec_point;
    var t = thousands_sep == undefined ? "," : thousands_sep, s = n < 0 ? "-" : "";
    var i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
    
    return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
}




function setCart(response)
{
	eval(response.responseText);
	return true;
}

function removeElements(idE)
{
	if(typeof(idE) == 'object')
	{
		var fila = idE
	}
	else
	{
		var fila = $(idE);
	}
	if(fila != undefined)
		while (fila.firstChild) 
		{
			fila.removeChild(fila.firstChild);
		}
	return true;
}

function elementRemove(element)
{
/*
Element.prototype.remove = function()
{
	element = this;
*/
	if(element != undefined)
		if(element.parentNode != undefined)
			element.parentNode.removeChild(element);
		else
		{
			alert('Parent null');
			return false;
		}
	else
	{
		alert('Element null');
		return false;
	}

	return element;
}

function elementisHide(element)
{
/*Element.prototype.isHide = function()
{
*/
	return(element.style.display == 'none' || element.style.visible == 'false');
}

function MM_jumpMenu(targ,selObj,restore)
{ //v3.0
  eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
  if (restore) selObj.selectedIndex=0;
}

function listen(event, elem, func) 
{

  if( typeof(elem) == "string" ) 
        elem = $(elem);

    if (elem.addEventListener)  // W3C DOM
        elem.addEventListener(event,func,false);
    else if (elem.attachEvent) { // IE DOM
         var r = elem.attachEvent("on"+event, func);
        return r;
    }
    else throw 'Error adding event handler';
}


function init()
{
        loadExpiryYears();

        //loadDays();

        loadCountries();
 
        //listen('click','package1', setShippingOptionHandler);
        //listen('click','package2', setShippingOptionHandler);
        //listen('change', 'billingCountry', setPaymentCountryHandler);
        listen('change', 'shippingCountry', setShippingOptionHandler);

        //listen('click', 'payment1', setPaymentDataHandler);
        //listen('click', 'payment2', setPaymentDataHandler);

        updateDivResumen();

        setValidations();
 
        listen('click','btnSubmit', sendData);
        //listen('click','ckSameBilling', sameAsBillingHandler);

        // boton submit

        loadDataCliente();
 
        return true;
}

function validateProducts()
{

	var nBlockedProducts = 0;
	var shippingC = $('shippingCountry1');
	var paisUE = parseInt(shippingC.options[shippingC.selectedIndex].getAttribute('ue'));

	if(paisUE == 1)
	{
		var tbContenedor = $('ShopCart');
		var nFilas = tbContenedor.rows;
		for(x=0;x<nFilas.length;x++)
		{
			var isUE = parseInt(nFilas[x].getAttribute('ue'));
			if(isUE == 1)
			{
				nFilas[x].className = 'blockedProduct';
				nBlockedProducts = nBlockedProducts + 1;
			}
			
		}
		
	}
	else
	{
		var tbContenedor = $('ShopCart');
		var nFilas = tbContenedor.rows;
		for(x=0;x<nFilas.length;x++){ nFilas[x].className = '';}
	}
	
	
	if(nBlockedProducts > 0)
	{
		alert('The products highligthed in you cart, can not been send to your shipping country.');
		return false;
	}
	else{ saveSession('checkout.php?co='+shippingC.value)}
	
	
}

// function redirect()
// {
// 	url = document.location.href ; 
// 	orig = url.split('?'); 
// 	if(orig.length==2)
// 	window.location.href=orig[0];
// }