/****************************************CProductAttribute******************************/
CProductAttribute=function(options){
	if(options.ne != null || options.qt != null || options.po != null){
		options.hs			= options.hs;
		options.id			= options.id;
		options.nome		= options.ne;
		options.fr              = options.fr;
		options.pt		= options.pt;
		options.quant		= options.qt;
		options.preco		= options.po;
	}
	var opt	= options != null ? options : {};

	this.hs	= opt.hs != null	? opt.hs	: ++CProductAttribute.hash;//hash code, must be unique
	this.id	= opt.id != null	? opt.id	: 0;
	this.ne	= opt.nome != null	? opt.nome	: '';
	this.fr = opt.fr !=null		?opt.fr		:'';
	this.pt = opt.pt !=null		?opt.pt		:'';
	this.qt	= opt.quant != null	? opt.quant	: 1;
	
	this.po	= opt.preco != null	? opt.preco	: 0.0;//type  0-pequena,1-media,2-grande
}
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;
}
var x = readCookie('lang');

CProductAttribute.hash = 0; //static
CProductAttribute.prototype.getHash			= function(){return this.hs;}
CProductAttribute.prototype.getId			= function(){return this.id;}
CProductAttribute.prototype.getNome			= function(){return this.ne;}
CProductAttribute.prototype.getFR			= function(){return this.fr;}
CProductAttribute.prototype.getPT			= function(){return this.pt;}
CProductAttribute.prototype.getQuant		= function(){return parseInt(this.qt);}
CProductAttribute.prototype.getPreco		= function(){return parseFloat(this.po).toFixed(2);}
CProductAttribute.prototype.getPrecoTotal	= function(){return parseFloat(this.po*this.getQuant());}

CProductAttribute.prototype.setPreco		= function(p){this.po = parseFloat(p);}
CProductAttribute.prototype.setQuant		= function(q){this.qt = parseInt(q);}
/****************************************CProductAttribute******************************/

/****************************************CProduct******************************/
CProduct=function(options){
	if(options.ne != null || options.ca != null || options.mo != null || options.qt != null){
		options.hs			= options.hs;
		options.id			= options.id;
		options.categoria	= options.ca;
		options.nome		= options.ne;
		options.pt		= options.pt;
		options.fr		= options.fr;
		options.modelo		= options.mo;
		options.tipo		= options.to;
		options.quant		= options.qt;
		options.preco		= options.po;
	}
	var opt = options != null ? options : {};
	
	this.hs	= opt.hs != null	? opt.hs				: ++CProduct.hash;//hash code, must be unique
	this.id	= opt.id != null		? opt.id			: 0;//id
	this.ca	= opt.categoria != null	? opt.categoria		: '';//categoria
	this.ne	= opt.nome != null		? opt.nome			: '';//nome
	this.pt	= opt.pt != null		? opt.pt			: '';//pt
	this.fr	= opt.fr != null		? opt.fr			: '';//fr
	this.mo	= opt.modelo != null	? opt.modelo		: '';//modelo
	this.to	= opt.tipo != null		? opt.tipo			: 0;//type  0-pequena,1-media,2-grande
	this.qt	= opt.quant != null		? opt.quant			: 1;//quantidade
	this.po	= opt.preco != null		? opt.preco			: 0.0;//type  0-pequena,1-media,2-grande
	this.at	= [];
}
CProduct.hash = 0; //static
//getters
CProduct.prototype.getHash		= function(){return this.hs;}
CProduct.prototype.getId		= function(){return this.id;}
CProduct.prototype.getCategoria	= function(){return this.ca;}
CProduct.prototype.getNome		= function(){return this.ne;}
CProduct.prototype.getPT		= function(){return this.pt;}
CProduct.prototype.getFR		= function(){return this.fr;}
CProduct.prototype.getModelo	= function(){return this.mo;}
CProduct.prototype.getTipo		= function(){return parseInt(this.to);}
CProduct.prototype.getQuant		= function(){return parseInt(this.qt);}
CProduct.prototype.getPreco		= function(){return parseFloat(this.po).toFixed(2);}
CProduct.prototype.getPrecoTotal= function(){return parseFloat(this.getPreco()*this.getQuant()+this.calcPrecoTotalAttributes());}
//setters
CProduct.prototype.setId		= function(v){this.id=v;}
CProduct.prototype.setCategoria	= function(v){this.ca=v;}
CProduct.prototype.setNome		= function(v){this.ne=v;}
CProduct.prototype.setPT		= function(v){this.pt=v;}
CProduct.prototype.setFR		= function(v){this.fr=v;}
CProduct.prototype.setModelo	= function(v){this.mo=v;}
CProduct.prototype.setTipo		= function(v){this.to=v;}
CProduct.prototype.setQuant		= function(v){this.qt=v;}
CProduct.prototype.setPreco		= function(v){this.po=v;}
CProduct.prototype.numAttributes= function(){return this.at.length;}

CProduct.prototype.calcPrecoTotalAttributes= function(){
	var total = 0;
	for(var k=0;k<this.at.length;k++){
		total += this.at[k].getPrecoTotal();
	}
	return total;
}
CProduct.prototype.setAttributesQuant= function(q){
	for(var i=0;i<this.at.length;i++){
		this.at[i].setQuant(q);
	}
}
CProduct.prototype.addAttribute	= function(obj){
	if(typeof(obj) != 'object'){
		return;
	}
	for(var i=0;i<this.at.length;i++){
		if(this.at[i].getId() == obj.getId()){
			return;
		}
	}
	this.at.push(obj);
}
CProduct.prototype.removeAttribute	= function(hash){
	for(var k=0;k<this.at.length;k++){
		if(this.at[k].getHash() == hash){
			this.at.splice(k,1);
			return;
		}
	}
}
/****************************************CProduct******************************/

/****************************************ShoppingCart******************************/
/*Contrói a class*/
function ShoppingCart() {
	this.initialize();
}

ShoppingCart.instance = null; // Will contain the one and only instance of the class

// This function ensures that I always use the same instance of the object
ShoppingCart.getInstance = function() {
	if (ShoppingCart.instance == null) {
		ShoppingCart.instance = new ShoppingCart();
	}
	return ShoppingCart.instance;
}

ShoppingCart.prototype.initialize = function(){

	this.m_arProdutos = new Array();
	this.COOKIE_NAME = 'CART';
	this.ID_DIV_CART = 'idMyShoppingCart';
	this.ID_DIV_CART_ELEMENTS = 'idMyShoppingCartElements';
}

ShoppingCart.prototype.addProduct = function(elem){
	for(var k=0;k<this.m_arProdutos;k++){
		if(this.m_arProdutos[k].getId() == elem.getId() && this.m_arProdutos[k].getTipo() == elem.getTipo()){
			this.m_arProdutos[k].setQuant(parseInt(this.m_arProdutos[k].getQuant()) + 1);
			this.buildList();
			this.save();
			return;
		}
	}
	this.m_arProdutos.push(elem);
	this.save();
	this.buildList();
}

ShoppingCart.prototype.addProductAttribute = function(prod_hash, elem){
	for(var key in this.m_arProdutos){
		if(this.m_arProdutos[key].getHash() == prod_hash){
			this.m_arProdutos[key].addAttribute(elem);
			this.buildList();
			this.save();
			return;
		}
	}
}
ShoppingCart.prototype.removeProductAttribute = function(prod_hash, prod_at_hash){
	for(var k=0;k<this.m_arProdutos.length;k++){
		if(this.m_arProdutos[k].getHash() == prod_hash){
			this.m_arProdutos[k].removeAttribute(prod_at_hash);
			this.buildList();
			this.save();
			return;
		}
	}
}
ShoppingCart.prototype.load = function () {
	this.initialize();
	var the_cookie = this.getCookie(this.COOKIE_NAME);
	if (the_cookie != '[]' && the_cookie != '' && the_cookie != null) {
		var tempArray = eval(the_cookie);
		var at = null, p = null, pHash=0, paHash=0;
		for(var i=0;i<tempArray.length;i++){
			if(tempArray[i].hs > pHash)
				pHash = tempArray[i].hs;
			at = tempArray[i].at;
			p = new CProduct(tempArray[i]);
			for(var ii=0;ii<at.length;ii++){
				if(at[ii].hs > paHash)
					paHash = at[ii].hs;
				p.addAttribute(new CProductAttribute(at[ii]));
			}
			this.m_arProdutos.push(p);
		}
		CProduct.hash = pHash; //static
		CProductAttribute.hash = paHash; //static
	}
	this.buildList();
}

ShoppingCart.prototype.del = function () {
	this.deleteCookie(this.COOKIE_NAME);
	this.initialize();
	this.buildList();
}

ShoppingCart.prototype.save = function () {
	var jsonText = JSON.stringify(this.m_arProdutos);
	this.setCookie(this.COOKIE_NAME, jsonText,60,'','',false);//1 hora
}

ShoppingCart.prototype.contarElementos = function(){
	return this.m_arProdutos.length;
}

ShoppingCart.prototype.removeAll = function(){
	this.m_arProdutos=new Array();
	this.buildList();
}
/*Remove do Array pela chave*/
ShoppingCart.prototype.removeProductQuantByHash = function(h){
	for(var k=0;k<this.m_arProdutos.length;k++){
		if(this.m_arProdutos[k].getHash() == h){
			if(this.m_arProdutos[k].getQuant()>1){
				this.m_arProdutos[k].setQuant(this.m_arProdutos[k].getQuant()-1);
				this.m_arProdutos[k].setAttributesQuant(this.m_arProdutos[k].getQuant());
			}else{
				this.m_arProdutos.splice(k,1);
			}
			this.save();
			this.buildList();
			return;
		}
	}
}
/*Adiciona no Array pela chave*/
ShoppingCart.prototype.addProductQuantByHash = function(h){
	for(var k=0;k<this.m_arProdutos.length;k++){
		if(this.m_arProdutos[k].getHash() == h){
			if(this.m_arProdutos[k].getQuant()>0){
				this.m_arProdutos[k].setQuant(this.m_arProdutos[k].getQuant()+1);
				this.m_arProdutos[k].setAttributesQuant(this.m_arProdutos[k].getQuant());
			}else{
				this.m_arProdutos.splice(k,1);
			}
			this.save();
			this.buildList();
			return;
		}
	}
}
/*Contrói lista do carrinho*/
ShoppingCart.prototype.buildList = function(){
	var showPrecos = false;
	var idshoppingcart=document.getElementById(this.ID_DIV_CART);
	var idshoppingcartelements = document.getElementById(this.ID_DIV_CART_ELEMENTS);
	if(!idshoppingcart || !idshoppingcartelements){
		alert('Elementos \''+ this.ID_DIV_CART +'\' e \''+ this.ID_DIV_CART_ELEMENTS +'\' não existem!');
		return;
	}
	if(this.contarElementos() > 0 &&  idshoppingcart.style.display == 'none'){
		idshoppingcart.style.display='';
		idshoppingcart.style.visibility='visible';
	}
	if(this.contarElementos() == 0){
		idshoppingcart.style.display='none';
		idshoppingcart.style.visibility='hidden';
		return;
	} 
	var table = '<br /><table cellpadding="2" cellspacing="2" width="100%">'+
		'<tr style="color:#fff;">'+
			'<th>'+(x=='pt'?'Produtos':'Produits')+'</th>'+
			'<th title="quantidade">Q</th>'+
			(showPrecos ? '<td title="pre&ccedil;o">P</th>' : '')+
			'<th></th>'+
		'</tr>';
	var total = 0;
	var produto = null;
	for(var i=0;i<this.m_arProdutos.length;i++){
		produto = this.m_arProdutos[i];
		//var newDiv = document.createElement('div');
		//newDiv.setAttribute("id","id_"+this.m_arProdutos[key].getId());
		//newDiv.innerHTML= '<tr class="shoppingcartline"><td>' + this.m_arProdutos[key].getNome()+ '</td><td>'+this.m_arProdutos[key].getQuant()+'</td><td>'+ this.m_arProdutos[key].getPreco() +'</td><td><a href="javascript:ShoppingCart.getInstance().removeProductQuantByKey('+key+');" style="text-align:right;font-size:9px;font-family:verdana;">remover</a></td></tr>';
		table += 
		'<tr class="'+ ((i % 2 == 0 ? 'MyShoppingCartLine' : 'MyShoppingCartLineAlt')) +'" style="font-size:9px;font-family:verdana,arial,sans-serif;">'+
			'<td>' + (x=='pt'?produto.getPT():produto.getFR())+ '</td>'+
			'<td>'+produto.getQuant()+'</td>'+
			(showPrecos ? '<td>&euro;'+ produto.getPreco() +'</td>' : '')+
			'<td>'+
			'<a href="javascript:ShoppingCart.getInstance().removeProductQuantByHash('+ produto.getHash() +');" style="font-size:9px;" title="remover">-</a> '+
			'<a href="javascript:ShoppingCart.getInstance().addProductQuantByHash('+ produto.getHash() +');" style="font-size:9px;" title="adicionar">+</a>'+
			'</td>'+
		'</tr>';
		for(var ii=0;ii<produto.numAttributes();ii++){
			table += 
			'<tr class="'+ ((i % 2 == 0 ? 'MyShoppingCartLine' : 'MyShoppingCartLineAlt')) +'" style="font-size:9px;font-family:verdana,arial,sans-serif;font-style:italic;color:#00f;">'+
				'<td> &nbsp; '+ produto.at[ii].getNome() +'</td>'+
				'<td>'+ produto.at[ii].getQuant() +'</td>'+
				(showPrecos ? '<td>&euro;'+ produto.at[ii].getPreco() +'</td>' : '')+
				'<td>'+
					'<a href="javascript:ShoppingCart.getInstance().removeProductAttribute('+ produto.getHash() +','+ produto.at[ii].getHash() +');" style="text-align:right;font-size:9px;font-family:verdana;" title="remover">x</a> '+
				'</td>'+
			'</tr>';
		}
		total += produto.getPrecoTotal();
		//idshoppingcart.appendChild(newDiv);
		//alert(produto.toSource());
	}
	if(showPrecos){
		table += '<tr><td colspan="4" style="font-weight:bold;font-size:10px;">Total: &euro;'+ total.toFixed(2) +'</td></tr>';
	}
	//table += '<tr><td colspan="4"><a href="" style="text-align:right;">Finalizar</a></td></tr>';
	table += '</table>';
	idshoppingcartelements.innerHTML = table;
}
ShoppingCart.prototype.addLoadEvent = function (func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	} else {
		window.onload = function() {
		if (oldonload) {
			oldonload();
		}
		func();
		}
	}
}
		/*
   name - name of the cookie
   value - value of the cookie
   [expires] - number of minutes until expire
	 (defaults to end of current session)
   [path] - path for which the cookie is valid
	 (defaults to path of calling document)
   [domain] - domain for which the cookie is valid
	 (defaults to domain of calling document)
   [secure] - Boolean value indicating if the cookie transmission requires a secure transmission
   * an argument defaults when it is assigned null as a placeholder
   * a null placeholder is not required for trailing omitted arguments
*/
ShoppingCart.prototype.setCookie = function (name, value, expires, path, domain, secure) {
		// set time, it's in milliseconds
		var today = new Date();
		today.setTime( today.getTime() );
		
		if ( expires ){
			expires = expires * 1000 * 60;
		}
		
		var expires_date = new Date( today.getTime() + (expires) );
		
	  var curCookie = name + "=" + escape(value) +
	  //var curCookie = name + "=" + value +
		  ((expires) ? "; expires=" + expires_date.toGMTString() : "") +
		  ((path) ? "; path=" + path : "") +
		  ((domain) ? "; domain=" + domain : "") +
		  ((secure) ? "; secure" : "");
	  document.cookie = curCookie;
	}
/*
  name - name of the desired cookie
  return string containing value of specified cookie or null if cookie does not exist
*/
ShoppingCart.prototype.getCookie = function (name) {
	  var dc = document.cookie;
	  var prefix = name + "=";
	  var begin = dc.indexOf("; " + prefix);
	  if (begin == -1) {
		begin = dc.indexOf(prefix);
		if (begin != 0) return null;
	  } else
		begin += 2;
	  var end = document.cookie.indexOf(";", begin);
	  if (end == -1)
		end = dc.length;
	  return unescape(dc.substring(begin + prefix.length, end));
	  //return dc.substring(begin + prefix.length, end);
	}


/*
   name - name of the cookie
   [path] - path of the cookie (must be same as path used to create cookie)
   [domain] - domain of the cookie (must be same as domain used to create cookie)
   path and domain default if assigned null or omitted if no explicit argument proceeds
*/
ShoppingCart.prototype.deleteCookie = function (name, path, domain) {
	  if (this.getCookie(name)) {
		document.cookie = name + "=" +
		((path) ? "; path=" + path : "") +
		((domain) ? "; domain=" + domain : "") +
		"; expires=Thu, 01-Jan-70 00:00:01 GMT";
	  }
}

ShoppingCart.getInstance().addLoadEvent(function(){ShoppingCart.getInstance().load();});
/****************************************ShoppingCart******************************/