// JavaScript Document

/*/////////////////
/////////////////
Main Script for Future Dogs Shopping cart
V.01
11/11/09
Hugo Rodrigues
Inovadesign
/////////////////
////////////////*/

/*
////////////
Initial Set Up
/////////////
*/
var products = new Array();
var total;

$(document).ready(function() {
						   
						   
						   
	Setbutton = function(x){		
		// x stock Control if less 1 active if 0 inactive
	
		if(x){
			
			numproct = $(".direito_loja b");
			numb = numproct.length;
			
			
			actcat = $(".L2_Active img").attr("alt");
			
			if(numb > 1){
				
				var singleprod = "<input type='hidden' name='ProdGroup' value='"+actcat+"' /><select name='ProdType'>";
				for(i=0;i<numb;i++){
					
					var htmlStr = $(numproct[i]).html()
					singleprod = singleprod + "<option value='" + htmlStr + "'>" + htmlStr + "</option>";
					
				}
				singleprod = singleprod + "Qt: <input type='text' name='Qty' class='qty' value='1' size='3'  /><input type='submit' class='comprar' name='Comprar' value='Comprar' />";
				$("#buybutton").append(singleprod);
			}else{
				var singleprod = "<input type='hidden' name='ProdGroup' value='"+actcat+"' /><input type='hidden' class='qty' name='ProdType' value='single' /><input type='text' class='qty' name='Qty' value='1' size='3'  /><input type='submit' name='Comprar' class='comprar' value='Comprar' />"
				$("#buybutton").append(singleprod);
	
				
			}
		}else{
			 
		}
	}

	
});



/*
////////////
Get Vars from URL
/////////////
*/

treUrl = function (){


x = decodeURI(document.location.href);
keys = x.split("?");	


	if(keys[1]){
			
		var kval = keys[1];
		
		
		kvalarr = kval.split("+");
		
		var valor1 = "";
	
		for(a=0;a<kvalarr.length;a++){
			
			valor1 += kvalarr[a] + ' ';
	
		}
		
		
		keysval = valor1.split("&");
		var newprod =  new Array();
		
		for(b=0;b<keysval.length;b++){

			keysval2 = keysval[b].split("=");

			if(keysval2[0] != "Comprar"){
				newprod[b] = keysval2[1];
			}
			
		}
		

	}
	
	

ProdctContr(newprod);
displayCart();
}
	

	
/*
////////////
Coockie Control
/////////////
*/

ProdctContr = function(newprod){

/// Get number of products

	var numbprod = getCookie('numbproducts');

	if(numbprod){
		
	// 0-ProdId;		
	// 1-ProdImage
	// 2-ProdURL;
	// 3-ProdName;
	// 4-ProdPrice;
	// 5-ProdGroup;
	// 6-ProdType;
	// 7-Qty;
	// 8-ProdPriceTotal;
	// products[produto][detalhesproduto]
		
		
		/// create 2d array

		/// loop to get each product
		for(a=0;a<numbprod;a++){
			
			var newArray =  new Array();			
			var cookeiname = "product" + a;
			
			product = getCookie(cookeiname);
			
			if(product){
				
				keys = product.split("&");
				for(b=0;b<keys.length;b++){
					
					newArray[b] = keys[b];
					
				}

				products.push( newArray );
				
			}
			
		}
		
		if(newprod){
			// Check if produc exits add more
			updateProduct(newprod, "add");
			
		}else{
			
		}	
	
	}else{

		// No cookei so lets create a new set
		// Check if produc exits add more
		if(newprod){
			updateProduct(newprod, "add");

		}else{

	}

	}
	//$(".text3_escola").append(valeu);
	//displayCart();
}


/*
////////////
Update Product
/////////////
*/

updateProduct = function(newprod, y){
	
	var profound = "notfound";
	
	
	if(newprod[6] != "" && newprod[6] != "single" && newprod[6].match("-")){
			
		// Remove the Euro sign and -
		newprod[4] = newprod[6];
		
		valwitheuro = newprod[4];
		var valhtmlStr = valwitheuro.split("-");
		var valhtmlStrsplit = valhtmlStr[1].split(".");
		var euroval = valhtmlStrsplit[1].replace(/[^a-zA-Z 0-9]+/g,'');
		var crrval = valhtmlStrsplit[0]+"."+euroval;

		newprod[4] = crrval;	
		newprod[6] = valhtmlStr[0];

						
	}else if(newprod[6] == "single"){

		
		var valhtmlStrsplit = newprod[4].split(".");
		var euroval = valhtmlStrsplit[1].replace(/[^a-zA-Z 0-9]+/g,'');
		var crrval = valhtmlStrsplit[0]+"."+euroval;
		
		newprod[4] = crrval;
		}
	

	
	
	
	for(a=0;a<products.length;a++){
		if(products[a][0] == newprod[0] && products[a][6] == newprod[6] ){
			// 0-ProdId;		
			// 1-ProdImage
			// 2-ProdURL;
			// 3-ProdName;
			// 4-ProdPrice;
			// 5-ProdGroup;
			// 6-ProdType;
			// 7-Qty;
			// 8-ProdPriceTotal;
			// products[produto][detalhesproduto]
			//found it lets add the corresponding  QTY[7]
			if(y == "add"){
				products[a][7] = parseInt(products[a][7]) + parseInt(newprod[7]);
				profound = "found";
				createCookie();
				
				
				
			}else{
				products[a][7] = parseInt(products[a][7]) - parseInt(newprod[7]);
				if(products[a][7] < 1){
					removeProduct(a);
				}

				profound = "found";
				createCookie();
			}
			break;
			
		}
			
	}
	
	if(profound != "found"){

		
			if(newprod[6] != "" && newprod[6] != "single" && newprod[6].match("-")){
			
				// Remove the Euro sign and -
				newprod[4] = newprod[6];
				
				valwitheuro = newprod[4]
				var valhtmlStr = valwitheuro.split("-");
				var valhtmlStrsplit = valhtmlStr[1].split(".");
				var euroval = valhtmlStrsplit[1].replace(/[^a-zA-Z 0-9]+/g,'');
				var crrval = valhtmlStrsplit[0]+"."+euroval;

				newprod[4] = crrval;	
				newprod[6] = valhtmlStr[0];
	
								
			}else  if(newprod[6] == "single"){
						
				valwitheuro = newprod[4]
				var valhtmlStrsplit = valwitheuro.split(".");
				var euroval = valhtmlStrsplit[1].replace(/[^a-zA-Z 0-9]+/g,'');
				var crrval = valhtmlStrsplit[0]+"."+euroval;
				
				
				newprod[4] =crrval;
				newprod[6] = "single";		
	
				
			}	
					
		
		addProduct(newprod);
		createCookie();
		
		
		}
}

/*
////////////
Add Product
/////////////
*/

addProduct = function(newprod){
	
	products.push(newprod);
	
}


/*
////////////
Remove Product
/////////////
*/

removeProduct = function(newprod){
	//$(".text3_escola").append(newprod);
	
	var newproducts = new Array();
	var cookeiname;
	
	for(a=0;a<products.length;a++){
		
		if(products[a][0] == products[newprod][0]){
		
		cookeiname = "product" + a;
			
			
		}else{
		
			newproducts[a] = products[a];	
		
		}
			
	}
	
	products = newproducts;
	
	delCookie(cookeiname)
}

/*
////////////
create Cookie Function
/////////////
*/
createCookie = function(){
	
	var numbproducts = products.length;
	setCookie('numbproducts', numbproducts);
	
	var curr;
	var valeu ="";
	
	var a=0;
	for(a=0;a<products.length;a++)
	{
		var b=0;
		for(b=0;b<products[a].length;b++)
		{
			if(products[a][b]=="undefined")products[a][b]="";
		}
		valeu = products[a][0] +"&"+ products[a][1] + "&" +products[a][2] + "&" + products[a][3] + "&" + products[a][4] + "&" + products[a][5] +"&"+ products[a][6] +"&"+ products[a][7] +"&"+ products[a][8];
	
		
		
		var cookeiname = "product" + a;
		
		product = setCookie(cookeiname, valeu);
		
			
	}

}
/*
////////////
clean Cookie Function
/////////////
*/
cleanCookies = function(){
	
	var numbprod = getCookie('numbproducts');

	
	for(a=0;a<numbprod;a++){

		
		var cookeiname = "product" + a;
		
		delCookie(cookeiname)
		
			
	}
	delCookie('numbproducts')
	
}



/*
////////////
Remove display
/////////////
*/

remdispl = function(x){
		
		y = "#"+ x +" .ldetalhes .lqt input";
			
		z="#"+x;
		$(y).val(0)
		$(z).slideUp().remove();
		removeProduct(x);	
		calcTotals();

}

/*
////////////
calculate Sub Totals
/////////////
*/
calcTotals = function(){
	
	//x = produto
	//y = qtyldetalhes
	

	totalp = $(".linhaprod");
	var toltal = 0;
	var found="notfound";
	//$(".text3_escola").append(totalp.length);
	
	for(a=0;a<totalp.length;a++){
		found="found";
		x = "#"+ a +" .ldetalhes .lqt input";
		
		qty = parseFloat($(x).val());
		
		if(qty ==0){
			$(x).val(0);
		}
		
		y = "#"+ a +" .ldetalhes .lsubtotal span";
		
		//subtot = parseFloat($(y).html());

		subtot = parseFloat(products[a][4]);

		linetotal = subtot  * qty;
		
		linetotal = roundNumber(linetotal, 2)
		
		products[a][7] = qty;
		products[a][8] = linetotal;		
		
		$(y).html(linetotal)
		
		toltal = parseFloat(toltal) + parseFloat(linetotal);
		
		toltal = roundNumber(toltal, 2)
		
		$(".ttotalv").html(toltal+" &euro;");
		if(toltal>0){$(".confirmar").show();}
	}
	
	if(found=="notfound"){$(".ttotalv").html("0 &euro;");$(".confirmar").fadeOut();}
	
	
	createCookie();	

	

	
}

/*
////////////
Shopping cart display Function
/////////////
*/
displayCart = function(){
	
	var cartHeading = "<div class='produto'>Produto</div><div class='qt'>Qt</div><div class='subtotal'>SubTotal</div><br clear='all' />";
	var cartElemt;
	var cartButts = "<div class='ttotalv'>&nbsp;</div><div class='ttotal'>Total</div><br clear='all' /><br /><div class='voltar'>Adicionar Mais Produtos</div><div class='confirmar'>Confirmar Encomenda</div><br clear='all' />";
	$(".text2_escola").append(cartHeading);
	
	
	/// loop to get each product
	// 0-ProdId;		
	// 1-ProdImage
	// 2-ProdURL;
	// 3-ProdName;
	// 4-ProdPrice;
	// 5-ProdGroup;
	// 6-ProdType;
	// 7-Qty;
	// 8-ProdPriceTotal;
	// products[produto][detalhesproduto]
	
	for(a=0;a<products.length;a++){
		 prodtype = products[a][6];
		 
		 if(prodtype == "single"){}else{prodtype = "<small>(&nbsp;"+ products[a][6] +"&nbsp;)</small>";}
		
		cartElemt = "<div class='linhaprod' id="+ a +"><div class='lfoto'> <img src='"+ products[a][1] +"' Width='76' Height='58' /></div><div class='ldetalhes'><div class='lproduto'>&nbsp;"+ products[a][3] +"</div><div class='lqt'><input type='text' value='"+ products[a][7] +"' /> "+ unescape(prodtype) +"</div><div class='lsubtotal'><span>"+ products[a][4] +"</span>&euro;&nbsp;</div><br clear='all' /><div class='lgroup'>"+ products[a][5] +"</div><div class='remover'>Remover</div></div><br clear='all' /></div>"
		$(".text2_escola").append(cartElemt);
		
	}
	
	$(".text2_escola").append(cartButts);
	
	calcTotals();
	//setup Buttons
	$(".remover").click(function(){
								 
		prod = $(this).parent().parent().attr("id");
		remdispl(prod);
		//$(".text3_escola").append(prod);
		calcTotals();
								
	});
	
	$(".lqt").change(function () {
		calcTotals();
	});


	$(".voltar").click(function(){
		history.back(1);
	});
	
	$(".confirmar").click(function(){
		createCookie();
		window.location="http://www.futuredogs.com/Dados-Pessoais.aspx";
	});
	
}
/*
////////////
Message display Function
/////////////
*/
displayCartMsg = function(){
	

	var totalcart = "";
	var totalall=0;
	
	
	/// loop to get each product
	// 0-ProdId;		
	// 1-ProdImage
	// 2-ProdURL;
	// 3-ProdName;
	// 4-ProdPrice;
	// 5-ProdGroup;
	// 6-ProdType;
	// 7-Qty;
	// 8-ProdPriceTotal;
	// products[produto][detalhesproduto]
	
    var a = 0;
    for (a = 0; a < products.length; a++) {
        /*
        kvalarr = products[a][1].split("+");

        var valor1 = "";

        for (b = 0; b < kvalarr.length; b++) {

            valor1 += kvalarr[b] + ' ';

        }
        */
        //var valor1 = "/Files/System/Logotipos/logotipo_futuredogs_branco.png";
        var valor1 = products[a][1];
        valor1 = valor1.replace(/ /g, '%20');
        valor1 = valor1.replace(/%2F/g, '/');
			
		totalcart += "<div class='linhaprod' id="+ a +"><div class='lfoto' style='float:left; width:80px;'> <img src='http://www.futuredogs.com"+ valor1 +"' Width='76' Height='58' /></div><div class='ldetalhes' style='float:left; width:250px;'><div class='lproduto'>&nbsp;"+ products[a][3] +" <small>(&nbsp;"+ products[a][6] +"&nbsp;) - "+ products[a][5] +"</small></div><div class='lqt'>"+ products[a][7] +" - <span>"+ products[a][8] +"</span>&euro;&nbsp;</div></div><br clear='all' /></div>"
		totalall = parseFloat(totalall) + parseFloat(products[a][8]);
		
	}
	
	totalcart += "<div class='ttotal'>Total</div><div class='ttotalv'>" + totalall + "&euro;&nbsp;</div>";
	return totalcart;

}
/*
////////////
Generate Client message
/////////////
*/


clientmessage = function(){
	
	
	
	
	ProdctContr();
	
	$("input[name=Detalhes]").val(displayCartMsg()); 
	
	
	
	}
	
/*
////////////
Round number for output
/////////////
*/	
function roundNumber(num, dec) {
	var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
	return result;
}


/*
////////////
get Function
/////////////
*/

function getCookie(c_name)
{
if (document.cookie.length>0)
  {
  c_start=document.cookie.indexOf(c_name + "=");
  if (c_start!=-1)
    {
    c_start=c_start + c_name.length+1;
    c_end=document.cookie.indexOf(";",c_start);
    if (c_end==-1) c_end=document.cookie.length;
    return unescape(document.cookie.substring(c_start,c_end));
    }
  }
return "";
}

/*
////////////
set Function
/////////////
*/

function setCookie(c_name,value,expiredays)
{
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+
	((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}

/*
////////////
delete Function
/////////////
*/
// this deletes the cookie when called
function delCookie( name, path, domain ) {
if ( getCookie( name ) ) document.cookie = name + "=" +
	( ( path ) ? ";path=" + path : "") +
	( ( domain ) ? ";domain=" + domain : "" ) +
	";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

