/**
* Cookie Cart
*
*
* @package     Cookie Cart
* @author      Elainne Barros (lanlanb) <http://cookiecart.blogspot.com/>
* @version     1.0
* @copyright   Copyright (C)2008 Elainne Barros . Licença Creative Atribuição-Compartilhamento pela mesma Licença 3.0 Unported Commons
* @example     index.php
**/

/************************************************************************************************************************ Configuração
***********************************************************************************************************************/
var campos = new Array("id_imovel","cod_imovel"); // o primeiro campo deve ficar em branco.
var destinatario = "email@cookiecart.com"; // e-mail para o qual devem ir os pedidos

/*
*	Funções de cookies (créditos: http://scripts.franciscocharrua.com/javascript_cookies.php)
*/
function setCookie(name, value)
         {
         //If name is the empty string, it places a ; at the beginning
         //of document.cookie, causing clearCookies() to malfunction.
         if(name != '')
            document.cookie = name + '=' + value;
         }

function getCookie(name)
         {
         //Without this, it will return the first value 
         //in document.cookie when name is the empty string.
         if(name == '')
            return('');
         
         name_index = document.cookie.indexOf(name + '=');
         
         if(name_index == -1)
            return('');
         
         cookie_value =  document.cookie.substr(name_index + name.length + 1, 
                                                document.cookie.length);
         
         //All cookie name-value pairs end with a semi-colon, except the last one.
         end_of_cookie = cookie_value.indexOf(';');
         if(end_of_cookie != -1)
            cookie_value = cookie_value.substr(0, end_of_cookie);

         //Restores all the blank spaces.
         space = cookie_value.indexOf('+');
         while(space != -1)
              { 
              cookie_value = cookie_value.substr(0, space) + ' ' + 
              cookie_value.substr(space + 1, cookie_value.length);
							 
              space = cookie_value.indexOf('+');
              }

         return(cookie_value);
         }
        
function clearCookies()
         {
         Cookies = document.cookie;
         Cookie = Cookies;
         expires = new Date();
         expires.setYear(expires.getYear() - 1);

         while(Cookie.length > 0)
              {
              //All cookie name-value pairs end with a semi-colon, except the last one.
              Cookie = Cookies.substr(0, Cookies.indexOf(';'));
              Cookies = Cookies.substr(Cookies.indexOf(';') + 1, Cookies.length);

              if(Cookie != '')
                 document.cookie = Cookie + '; expires=' + expires;
              else
                 document.cookie = Cookies + '; expires=' + expires;			  			  	  
              }		 		 
         }

/*
*	Funções do carrinho
*/
function in_array(needle, haystack, strict) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: in_array('van', ['Kevin', 'van', 'Zonneveld']);
    // *     returns 1: true
 
    var found = false, key, strict = !!strict;
 
    for (key in haystack) {
        if ((strict && haystack[key] === needle) || (!strict && haystack[key] == needle)) {
            found = true;
            break;
        }
    }
 
    return found;
}
/* Ajusta moeda (créditos: http://www.web-source.net/web_development/currency_formatting.htm) */
function moeda(amount)
{
	var i = parseFloat(amount);
	if(isNaN(i)) { i = 0.00; }
	var minus = '';
	if(i < 0) { minus = '-'; }
	i = Math.abs(i);
	i = parseInt((i + .005) * 100);
	i = i / 100;
	s = new String(i);
	if(s.indexOf('.') < 0) { s += '.00'; }
	if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
	s = minus + s;
	s = s.replace(".", ",");
	return s;
}

/* Envia email com o conteúdo do carrinho */
function emailCar(conteudo) {

  var subject = "?subject=" + "Pedido";
  var body = "body="+ conteudo;
  if(subject && body) body = "&"+body; else if(body)body="?"+body;
  if(destinatario)
   document.location="mailto:"+destinatario+subject+body;
  return destinatario?true:false;
}

/* Envia form em popup onsubmit="return createTarget(this.target)" target="formtarget" */
function createTarget(t){
window.open("", t, "width=600,height=550");
return true;
}

/* Limpa carrinho de compras */
function limpaCarrinho(name)
         {                  
         expires = new Date();
         expires.setYear(expires.getYear() - 1);

         document.cookie = name + '=null' + '; expires=' + expires; 		 
         }

/* Retira produto do carrinho */
function retiraProd(item) {
	var carrinho_cookie = getCookie('carrinho');
	var carrinho_novo = carrinho_cookie.replace("|" + item, "")
	setCookie('carrinho',carrinho_novo);
 }

function array_unique(ar){
  var sorter = {};
  for(var i=0,j=ar.length;i<j;i++){
    sorter[ar[i]] = ar[i];
  }
  ar = [];
  for(var i in sorter){
    ar.push(i);
  }
  return ar;
}

/* Adiciona produto ao carrinho */
function adicionaProd(Form){
var cForm = document.forms[Form]
var formArray = new Array();
var chkArray = new Array();
var selArray = new Array();

 for(i=0; i<cForm.elements.length; i++){
  
  var campo = cForm.elements[i].name;
  
	switch(cForm.elements[i].type)
	{
	// Indefinido ou Submit
		case 'undefined': case 'submit': break;
	// Select one
		//case 'select-one':
		//	formArray[i] = cForm.elements[i].selectedIndex.value;
		// break;
	// Select-Multiple
		case 'select-multiple':
		for (var x = 0; x < cForm.elements[i].options.length; x++)
		if (cForm.elements[i].options[x].selected)
		selArray.push(cForm.elements[i].options[x].value);
		var selposition = i;
			 break;
	// Radio
		case 'radio':
				if(cForm.elements[i].checked == true)
				formArray.push(cForm.elements[i].value);
			 break;
	// Checkbox
		case 'checkbox':	
				if(cForm.elements[i].checked == true)
					chkArray.push(cForm.elements[i].value);
					var chkposition = i;
			 break;
	// Padrão
		default: formArray.push(cForm.elements[i].value); break;
	}

   } // for
   
   if (chkArray != 0) {
    chkArray = chkArray.join("**")
	formArray.splice ( chkposition, 0, chkArray );
	}
   if (selArray != 0) {
    selArray = selArray.join("**")
	formArray.splice ( selposition, 0, selArray );
	}   
   
	var carrinho_cookie = getCookie('carrinho');
	novoItem = "|" + formArray;
	setCookie('carrinho',carrinho_cookie + novoItem);
	alert("Imóvel adicionado na sua lista 'Meus Imóveis'");
	
} // function

/* Exibe carrinho */
function verCarrinho() {
var carrinho_cookie = getCookie('carrinho');
if (carrinho_cookie != "") {
 return carrinho_cookie.split("|");
 } else {
	return ""
}

}
