var prendasG = new Array();
var gastosE;
var totalC;

$(document).ready(function(){
	$(window).resize( function() {window_resize()});
	leeCookies();
	//eraseCookie('prendasF');
});

function enviarPaypal(){
	
}

function total(envio){
	
	var prendasF;
	//var envio = document.getElementByName('envio');
	var tot = document.getElementById('total');
	var gastos = document.getElementById('gastos');
	prendasF = readCookie('prendasF');
	totalC = obtenTotal(prendasF);
	
	gastosE = parseFloat(envio);
	totalC += parseFloat(gastosE);
	tot.innerHTML = formatCurrency(totalC);
	gastos.innerHTML = formatCurrency(gastosE);
		
	var item_name = document.getElementById('name');	
	var item_number = document.getElementById('number');	
	var amount = document.getElementById('cantidad');
	
	
	var nombres, claves, talla, edad;
	claves = nombres = "";
	definePrendas(prendasF);
	for(i = 0; i < prendasG.length; i++){
		talla = prendasG[i][1].split('-');
		if(talla[1] == 'n'){
				edad = 'anos';
		}else{
				edad = 'meses';	
		}
		
		claves += " -" + prendasG[i][0] + " Talla: " + talla[0] + " " + edad + "- ";
		nombres += " -" + prendasG[i][4] + " Talla: " + talla[0] + " " + edad + "-";
	}
	
	
	item_name.innerHTML = "<input type='hidden' name='item_name' value='" + nombres + "'>";
	item_number.innerHTML = "<input type='hidden' name='item_number' value='" + claves + "'>";
	amount.innerHTML = "<input type='hidden' name='amount' value='" + totalC + "'>";
	
	

}


function cargaCarrito(){
	var prendasF, talla, edad;
	
	prendasF = readCookie('prendasF');
	
	if(prendasF != null && prendasF != ""){
	
		definePrendas(prendasF);
		gastosE = 0;	
		
		var prendas = document.getElementById('prendas');
		var menu = document.getElementById('menuCarritos');
		var titulo = document.getElementById('tituloCarrito');
		var subtotal = document.getElementById('subtotal');
		var total = document.getElementById('total');
		var gastos = document.getElementById('gastos');
		
		var html = '';
		html = "<a onclick='removerTodos()' style='text-decoration:underline; cursor:pointer; color:blue; left:75px; position:relative;'>Eliminar todos los &iacute;tems</a>";
		
		titulo.innerHTML = html;
		
		
		html = '';
		
		//alert(prendasG.length);
		for(i = 0; i < prendasG.length; i++){
			talla = prendasG[i][1].split('-');
			if(talla[1] == 'n'){
				edad = 'a&ntilde;os';
			}else{
				edad = 'meses';	
			}
			//alert(prendasG[i][3]);
			html += '<li>';
			//for(j = 0; j < prendasG[i].length; j++){
			html += "<img style='float:left;' src='imgsRopa/fmed/" + prendasG[i][3] + "'>";
			html += "<div style='display:block; float:left; height:inherit;'><span class='nombreP'><h3>" + prendasG[i][4] + "</h3></span><br/><br/>";
			html += "<span class='claveP'>Clave: " + prendasG[i][0] + "</span><br/>";
			html += "<span class='tallaP'>Talla: " + talla[0] + " " + edad + "</span><br/><br/>";
			html += "<span class='claveP'><h5>Precio: " + formatCurrency(prendasG[i][2]) + "</h5></span>";
			html += "<a style='position:relative;' class='redondeado5' id='removerP'onclick='removerItem(" + prendasG[i][0] + ")'>Eliminar &iacute;tem</a>";
			//}
			html += '</div></li>';
			
		}
		
		prendas.innerHTML = html;	
		
		html = "";
		
		var nombres, claves, talla, edad;
		claves = nombres = "";
		
		for(i = 0; i < prendasG.length; i++){
		talla = prendasG[i][1].split('-');
		if(talla[1] == 'n'){
				edad = 'anos';
		}else{
				edad = 'meses';	
		}
		
		claves += " -" + prendasG[i][0] + " Talla: " + talla[0] + " " + edad + "- ";
		nombres += " -" + prendasG[i][4] + " Talla: " + talla[0] + " " + edad + "-";
		}
		
		
		
		var subt = obtenTotal(prendasF);
		var tot = parseFloat(subt) + 50;
		
		html = "<div class='redondeado5' id='menuCarrito'><h4>Subtotal: <br/><span id='subtotal'>" + formatCurrency(subt) + "</span> MXN</h4><br/><hr /><br/><h4>Pa&iacute;s o ciudad a enviar:</h4><br/><INPUT TYPE=RADIO NAME='envio' VALUE='50' onchange='total(this.value)' checked='checked'> M&eacute;xico<BR><INPUT TYPE=RADIO NAME='envio' VALUE='162' onchange='total(this.value)'> Canad&aacute; y E.U.A.<BR><INPUT TYPE=RADIO NAME='envio' VALUE='249' onchange='total(this.value)'> Madrid, Espa&ntilde;a<P><INPUT TYPE=RADIO NAME='envio' VALUE='311' onchange='total(this.value)'> Resto del mundo</P> <br/><h5>Gastos de Env&iacute;o: <br/><span id='gastos'>" + formatCurrency(50) + "</span> MXN</h5><br/><hr /><br/><h4>Total: <br/><span id='total'>" + formatCurrency(tot) + "</span> MXN</h4><br/><div id='paypal'><form target='_self' action='https://www.paypal.com/cgi-bin/webscr' method='post'><input type='hidden' name='cmd' value='_cart'><input type='hidden' name='business' value='ZU7RS24XY9HF8'><input type='hidden' name='lc' value='MX'><div id='name'><input type='hidden' name='item_name' value='" + nombres + "'></div><span id='number'><input type='hidden' name='item_number' value='" + claves + "'></span> <span id='cantidad'><input type='hidden' name='amount' value='" + tot + "'></span><input type='hidden' name='currency_code' value='MXN'><input type='hidden' name='button_subtype' value='products'><input type='hidden' name='no_note' value='0'><input type='hidden' name='cn' value='Añadir instrucciones especiales para el vendedor'><input type='hidden' name='no_shipping' value='2'><input type='hidden' name='rm' value='1'><input type='hidden' name='return' value='http://www.arrozconleche.com.mx'><input type='hidden' name='cancel_return' value='http://www.arrozconleche.com.mx'><input type='hidden' name='add' value='1'><input type='hidden' name='bn' value='PP-ShopCartBF:btn_cart_LG.gif:NonHosted'><input type='submit' onclick='removerTodos()' border='0' name='submit' id='btnPaypal' class='redondeado5' value='Comprar ahora' style='padding:3px;'><img alt='' border='0' src='https://www.paypalobjects.com/es_XC/i/scr/pixel.gif' width='1' height='1'></form></div></div>";
		
		menu.innerHTML = html;
		
		
		
		html = "";
		subtotal.innerHTML = formatCurrency(obtenTotal(prendasF));
		
		
		
		
	}else{
		var titulo = document.getElementById('tituloCarrito');
		var html = "<div style='height:200px; width:100%; text-align:center; color:#888888;'><br/><br/><br/><h3>No hay prendas en el carrito de compras.</h3><div>";
		titulo.innerHTML = html;
	}	
	
	
}

function removerTodos(){
	eraseCookie('prendasF');
	window.location = 'carrito.php';	
}

function removerItem(clave){
	
	var prendasF, nuevasF, talla, edad;
	
	prendasF = readCookie('prendasF');
	
	nuevasF = "";
	
	if(prendasF != null && prendasF != ""){
	
		definePrendas(prendasF);
		
		for(i = 0; i < prendasG.length; i++){
			if(prendasG[i][0] != clave)
				nuevasF += clave + '$$' + prendasG[i][1] + '$$' + prendasG[i][2] +  '$$' + prendasG[i][3] +  '$$' + prendasG[i][4] + '///';
		}
		
		eraseCookie('prendasF');
		createCookie('prendasF', nuevasF, 30);
		
		definePrendas(nuevasF);
		var prendas = document.getElementById('prendas');
		
		window.location = "carrito.php";
		
		
		
	}else{
		var titulo = document.getElementById('tituloCarrito');
		var html = "<div style='height:200px; width:100%; text-align:center; color:#888888;'><br/><br/><br/><h3>No hay prendas en el carrito de compras.</h3><div>";
		titulo.innerHTML = html;
	}	
	
}

function definePrendas(prendas){
	//alert(prendas);
	
	var prenda, i, j;
	//prendasG = new Array(5);
	prendas = prendas.split('///');
	
	for (i = 0; i < prendas.length - 1; i++){
		
		prenda = prendas[i].split('$$');
		prendasG[i] = new Array();
		
		for(j = 0; j < prenda.length; j++){
			
			prendasG[i][j] = prenda[j];
			//alert(prendasG[i][j]);
			//alert("i:" + i + " j:" + prendasG[i][j]);
		}
	}
}

function limpia(inp){
var input = document.getElementById(inp);
input.value = '';	
}

function catalogo(num, genero, edad){
 	window.location = 'catalogo.php?cat=' + num + '&g=' + genero + '&e=' + edad;
}

function detalles(clave, genero, edad, cat){
	window.location = 'detalles.php?det=' + clave + '&g=' + genero + '&e=' + edad + '&cat=' + cat;
}

function leeCookies(){
	
	var prendasF, cant, total;
	var carro = document.getElementById('carritodecompras');
	
	prendasF = readCookie('prendasF');
	if(prendasF != null) {
	
	//alert(prendasF);
	cant = cantidad(prendasF);
	total = obtenTotal(prendasF);
	}else{
	cant = 0;
	total = "0.00";	
	}
		
	carro.innerHTML = "<a href='carrito.php' title='Ver carrito'><img src='http://www.arrozconleche.com.mx/imgs/shopping_cart.png' /><span style='color:#333333;position:relative; top:-35px; left:16px;'>&nbsp;Mi carrito</span><span style='position:absolute; top:21px; left:66px;'>" + cant + "</span><span> </span><span style='position:absolute; top:21px; left:88px;'>&iacute;tem(s)</span><span style='position:absolute; top:42px; left:52px;'>Total:</span><span style='position:absolute; top:42px; left:104px;'>" + formatCurrency(total) + "</span></a>";
		
}

function formatCurrency(num) {
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
	num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
	cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
	num = num.substring(0,num.length-(4*i+3))+','+
	num.substring(num.length-(4*i+3));
	return (((sign)?'':'-') + '$' + num + '.' + cents);
}

function cantidad(prendas){
	prendas = prendas.split('///');
	return prendas.length - 1;	
}

function obtenTotal(prendas){
	var prenda, total, i;
	total = 0;
	prendas = prendas.split('///');
	
	for (i = 0; i < prendas.length - 1; i++){
		prenda = prendas[i].split('$$');
		total += parseFloat(prenda[2].toString());
	}
	
	return total;
}

function anadir(clave, precio, foto, nombre){
	
	var checksF = document.getElementsByName('tallasF');
	var checksM = document.getElementsByName('tallasM');
	var checksB = document.getElementsByName('tallasB');
	
	
	var prendasF;
	var fF, fM, fB;
	fF = fB = fM = false;
	prendasF = readCookie('prendasF');
	
	
	if(prendasF == null)
		prendasF = '';
	
	
	for (i = 0; i < checksF.length; i++){
		if(checksF[i].checked){	
			prendasF += clave + '$$' + checksF[i].value + '$$' + precio +  '$$' + foto +  '$$' + nombre + '///';
			fF = true;
		}
	}
	for (i = 0; i < checksM.length; i++){
		if(checksM[i].checked){	
			prendasF += clave + '$$' + checksM[i].value + '$$' + precio +  '$$' + foto +  '$$' + nombre + '///';
			fM = true;	
		}
	}
	for (i = 0; i < checksB.length; i++){
		if(checksB[i].checked){
			prendasF += clave + '$$' + checksB[i].value + '$$' + precio +  '$$' + foto +  '$$' + nombre + '///';
			fB = true;	
		}
	}
	
	
	if(!fF && !fM && !fB){
		/*var alerta = document.createElement('span');
		alerta.innerHTML = "Por favor seleccione una talla del producto antes de a&ntilde;adirlo al carrito.";
		alert(alerta.innerHTML);*/
		DisplayAlert('pedidoVacio',315,210);
	}else{
	
		createCookie('prendasF', prendasF, 30);
		limpiaChecks();
		DisplayAlert('pedidoExito',315,210);
		leeCookies();
	}
}

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(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 eraseCookie(name) {
	createCookie(name,"",-1);
}

function DisplayAlert(id,left,top) {
var width =	$(window).width();
var height =	$(window).height();

var overgris = document.getElementById('overgris');
overgris.style.width = (width * 2)+'px';
overgris.style.height = height+'px';
overgris.style.backgroundPosition = '0 0';
overgris.style.display = 'block';
overgris.style.left= (width * -1)+'px';
	
document.getElementById(id).style.left=left+'px';
document.getElementById(id).style.top=top+'px';
document.getElementById(id).style.display='block';
}

function limpiaChecks(){
	var checksF = document.getElementsByName('tallasF');
	var checksM = document.getElementsByName('tallasM');
	var checksB = document.getElementsByName('tallasB');
	
	for (i = 0; i < checksF.length; i++){
		checksF[i].checked = false;
	}
	for (i = 0; i < checksM.length; i++){
		checksM[i].checked = false;
	}
	for (i = 0; i < checksB.length; i++){
		checksB[i].checked = false;
	}
}

function window_resize(){
	var width =	$(window).width();
	var height =	$(window).height();
	var overgris = document.getElementById('overgris');
	overgris.style.width = (width * 2)+'px';
	overgris.style.height = height+'px';
	overgris.style.backgroundPosition = '0 0';
	overgris.style.left= (width * -1)+'px';
}
