/*
   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
*/

function setCookie(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) +
      ((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
*/

function getCookie(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));
}


/*
   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
*/

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";
  }
}


/****************************************Nome do Cookie***********/
var NOME_COOKIE_CARRINHO='carrinho';


/****************************************CPRODUTO******************************/
if(CProduto==undefined)
	var CProduto={};//definindo espaço de nomes

CProduto=function(id,cat,nome,modelo,quant){
	this.m_nId			=id;
	this.m_strNome		=nome;
	this.m_strModelo	=modelo;
	this.m_strCategoria	=cat;
	this.m_nQuant		= quant;
}

CProduto.prototype.m_nId			=	null;
CProduto.prototype.m_strNome		=	null;
CProduto.prototype.m_strModelo		=	null;
CProduto.prototype.m_strCategoria	=	null;
CProduto.prototype.m_nQuant			=	null;

CProduto.prototype.getId		=function(){return this.m_nId;}
CProduto.prototype.getNome		=function(){return this.m_strNome;}
CProduto.prototype.getModelo	=function(){return this.m_strModelo;}
CProduto.prototype.getCategoria	=function(){return this.m_strCategoria;}
CProduto.prototype.getQuant		=function(){return this.m_nQuant;}

CProduto.prototype.setId		=function(v){this.m_nId				=v;}
CProduto.prototype.setNome		=function(v){this.m_strNome			=v;}
CProduto.prototype.setModelo	=function(v){this.m_strModelo		=v;}
CProduto.prototype.setCategoria	=function(v){this.m_strCategoria	=v;}
CProduto.prototype.setQuant		=function(v){this.m_nQuant			=v;}

CProduto.prototype.print=function(){
	alert('id='+this.m_nId+' Nome='+this.m_strNome+' Modelo='+this.m_strModelo);
}

/****************************************CPRODUTO******************************/

/****************************************CCARRINHO******************************/

if(CCarrinho==undefined)
	var CCarrinho={};//definindo espaço de nomes

CCarrinho=function(){
}

CCarrinho.prototype.m_arProdutos 	= new Array();
CCarrinho.prototype.m_nNumElementos = 0;



CCarrinho.prototype.escreveTotal=function(){
	document.getElementById('total').innerHTML=this.m_nNumElementos;
}


CCarrinho.prototype.addElemento		=function(elem){

	for(var key in this.m_arProdutos){
		if(this.m_arProdutos[key].getId() == elem.getId()){
			this.m_arProdutos[key].setQuant(parseInt(this.m_arProdutos[key].getQuant()) + parseInt(elem.getQuant()));
			this.buildList();
			return;
		}
	}
	
	this.m_nNumElementos = this.m_arProdutos.push(elem);
	this.buildList();
}

CCarrinho.prototype.changeQuantForElemento	=function(id,quant){

	for(var key in this.m_arProdutos){
		if(this.m_arProdutos[key].getId() == id){
			this.m_arProdutos[key].setQuant(parseInt(quant));
			this.buildList();
			return;
		}
	}
}

/*
CCarrinho.prototype.loadFromCookie	=function(){
	var str = getCookie(NOME_COOKIE_CARRINHO);
	var result,res;
	var arArgs=new Array();
	
	
	var myRegExp= /\[([0-9a-z| ]+)\]/ig;
	var myRegExp2= /([0-9]+)|([0-9]+)/ig;

	
	while((result = myRegExp.exec(str)) != null){
	//	alert(result[1]);
		
		while((res = myRegExp2.exec(result[1])) != null){
			//alert(res[0]);
			arArgs.push(res[0]);
		}
		if(arArgs.length == 4){
			//alert(arArgs[0]+arArgs[1]+arArgs[2]+arArgs[3]);
			this.addElemento(new CProduto(arArgs[0],arArgs[1],arArgs[2],arArgs[3]));
			arArgs = new Array();
		}
		
		//alert('Tamanho do resultado = ' + result.length);
	}
}
*/
CCarrinho.prototype.setToCookie		=function(){
	setCookie(NOME_COOKIE_CARRINHO, this.convertToString(),60*2,'','',false);
}

CCarrinho.prototype.printAll=function(){
	for(var key in this.m_arProdutos){
		this.m_arProdutos[key].print();
	}
}

CCarrinho.prototype.contarElementos=function(){
	return this.m_nNumElementos;
}

CCarrinho.prototype.removeAll=function(){
	/*var i,len=this.m_nNumElementos;

		for(i=0;i<len;i++){
			this.removeFromArrayByKey(0);
		}*/
	this.m_arProdutos=new Array();
	this.buildList();
	
}

CCarrinho.prototype.convertToArray=function(){
	var i;
	var array=new Array();
	
	for(var key in this.m_arProdutos){
		array.push(this.m_arProdutos[key].getId());
	}
	return array;
}
/* Converte os elementos para uam string que irá ser guardada no cookie*/
CCarrinho.prototype.convertToString=function(){
	var i;
	var str='';
	i=0;
	for(var key in this.m_arProdutos){
			str = str + '['+this.m_arProdutos[key].getId()+'|'+this.m_arProdutos[key].getQuant()+'] ';
		i++;
	}
	return str;
}

/*Remove do Array pela chave*/
CCarrinho.prototype.removeFromArrayByKey=function(k){

	this.removeAllDivs();
	
	if(!this.m_arProdutos[k]){
		alert('Key='+k+' Não existe');
		return;
	}
	
	if(this.m_arProdutos[k].getQuant()){
		this.m_arProdutos[k].setQuant(this.m_arProdutos[k].getQuant()-1);
	}
	
	if(this.m_arProdutos[k].getQuant() == 0){
		this.m_arProdutos.splice(k,1);
		this.m_nNumElementos--;
	}
	
	this.buildList();
}
/*Remove Todos os Divs*/
CCarrinho.prototype.removeAllDivs=function(){
	var idcarrinho=document.getElementById("idcarrinho-elementos");
	
	if(this.m_nNumElementos > 0)
		for(var key in this.m_arProdutos){
			if(document.getElementById("id_"+this.m_arProdutos[key].getId()))
				idcarrinho.removeChild(document.getElementById("id_"+this.m_arProdutos[key].getId()));
		}
}
/**/
CCarrinho.prototype.buildList=function(){
	
	this.removeAllDivs();

	var idcarrinho=document.getElementById("idcarrinho-elementos");
	
	if(this.contarElementos() &&  document.getElementById('idcarrinho').style.display == 'none'){
		 document.getElementById('idcarrinho').style.display='';
		 document.getElementById('idcarrinho').style.visibility='visible';
	}
	
	if(this.contarElementos()==0){
		 document.getElementById('idcarrinho').style.display='none';
		 document.getElementById('idcarrinho').style.visibility='hidden';
	}

	for(var key in this.m_arProdutos){
		
		var newDiv = document.createElement('div');
		
		newDiv.setAttribute("id","id_"+this.m_arProdutos[key].getId());
		
		newDiv.innerHTML= '<div class="linha-carrinho">' + this.m_arProdutos[key].getNome()+ ' x '+this.m_arProdutos[key].getQuant()+'<a href="javascript:carrinho.removeFromArrayByKey('+key+');" style="text-align:right;">remover</a></div>';
		
		idcarrinho.appendChild(newDiv);
	}
	//this.escreveTotal();
	this.setToCookie();
}
/*****************************************************CARRINHO******************************************/

