
/** FIRST, SOME USEFUL SCRIPTS **/
//var globalpath = "http://localhost:4961/Portal";
//var globalpath = "http://gafisa.ithink.com.br";
//var globalpath = "http://localhost:1122/Portal";
var DOM = function () {}

DOM.getByID = function (id)
{
	return document.getElementById(id);
}

Array.prototype.contains = function (element)
{
    
	for (i = 0; i < this.length; i++)
	{
		if (this[i] == element)
		{
			return true;
		}
	}
	return false;
}



var CustomException = function (message)
{
  this.message = message;
  this.name = "CustomException";
}
CustomException.toString = function ()
{
	return this.name + ': "' + this.message + '"';
}


/* ADICIONAR AOS FAVORITOS DO BROWSER */

var Add2BrowserFavourites = function(){
    
    var url      = document.location.href;
    var title    = document.title;
    //alert(title);
    if (window.sidebar) window.sidebar.addPanel(title, url,"");
    else if(window.opera && window.print){
        var mbm = document.createElement('a');
        mbm.setAttribute('rel','sidebar');
        mbm.setAttribute('href',url);
        mbm.setAttribute('title',title);
        mbm.click();
    }
    else if(document.all){window.external.AddFavorite(url, title);}
    
    return false;
}



/** SCRIPT PARA ABERTURA E FECHAMENTO DE LAYERS **/

var HidePops = function() {
    $(".pop-up").hide();
}

var ShowHideElement = function(element) {
    if(element.css("display") == "none"){
        HidePops();
        element.show();
    } else {
        element.hide();
    }
    return false;
}

/** START OF COOKIES PERSISTENCE LIBRARY **/

/**
 *
 * Cookies Persitence Library - Gafisa
 *
 * This library is under the GPL licence
 * Created by Zanfranceschi - zanfranceschi@gmail.com | www.zanfranceschi.com.br
 * Updated by Sandro Salles - salles.contato@gmail.com (email/msn)
 * Last update: 2008.01.28
 *
 *  Dependency: JSON2.js library (http://www.json.org/json2.js)
 *
 **/



/**
 *
 * Core configuration class
 * Stores, saves, and retrieves specific preferences adn user navigation.
 * Cookie based storage.
 *
**/
var Configuration = function ()
{
	
	// workaround
	var _this = this;
	
	// cookie name prefix
	this.cookiePrefix = "GafisaConfigObject";
	//this.path = globalpath;
	
	// data to be saved
	this.data =
	{
		path 	: "",
		name    :   "",
		email   :   "",
		area    :   "",
		stateID :   "",
		stateName :   "",
		stateUF :   "",
		cityID  :   "",
		cityName  :   "",
		category:   "",
		visitedPages :  "",
		favourites  :   "",
		currentAttributeID : "",
		saved : false ,
		ingles : "0"
	};
	
	// workaround
	// Always leave this blank and the same structure as the "data" property.
	// This is used in case the "load" method throws an exception (fails).
	this.protoData =
	{
		path 	: "",
		name    :   "",
		email   :   "",
		area    :   "",
		stateID :   "",
		stateName :   "",
		stateUF :   "",
		cityID  :   "",
		cityName  :   "",
		category:   "",
		visitedPages :  "",
		favourites  :   "",
		currentAttributeID : "",
		saved : false,
		ingles : "0"		
	};
	
	// visited pages array (navigation history)
	this.visitedPages = new Array();
	
	// favourites array
	this.favourites = new Array();
	
	// max. length for "visitedPages" property
	this.visitedPagesLimit = 15;
	
	// max. length for "favourites" property
	this.favouritesLimit = 15;
	
	// default array separator character (used in "favourites" and "visitedPages" properties)
	this.arraySep = "|";
	
	
	/**
	 * Adds document.location.href to the "visitedPages" array property.
	 * No duplicates allowed - they're ignored.
	 *
	 * @returns boolean 
	 *
	 */
	this.pageAdd = function ()
	{
		var last = (( document.location.href.indexOf("?") < 0 ) ? document.location.href.length + 1 :  document.location.href.indexOf("?"));

    var stateIdUrl = getQueryVariable('stateid');
    var cityIdUrl = getQueryVariable('cityid');
		
		if(cityIdUrl > 0)
		{
		  //PersistCookieStateInfo2(stateIdUrl, );
		  //PersistCookieCityInfo2();
		  
			url = document.title + ' - ' + gafisaConfig.data.cityName + _this.arraySep + escape(document.location.href/*.substring(0,last)*/).toLowerCase();
		//alert(url);	
		}	
		else
			url = document.title + _this.arraySep + escape(document.location.href/*.substring(0,last)*/).toLowerCase();
			
		//url = document.title + _this.arraySep + escape(document.location.href/*.substring(0,last)*/).toLowerCase();
		//alert('urlexistente' + url);
		if (!_this.visitedPages.contains(url))
		{
			//alert("nao tem caraleo " + url + " ");
			_this.visitedPages.unshift(url);

			if (_this.visitedPages.length > _this.visitedPagesLimit)
			{
				_this.visitedPages.pop();
			}
			return true;
		}
		return false;
	}	
	
	
	/**
	 * Adds document.location.href to the "favourites" array property.
	 * No duplicates allowed - they're ignored.
	 *
	 * @returns boolean 
	 *
	 */
	this.favAdd = function ()
	{

		url = document.title + _this.arraySep + escape(document.location.href);

		if (!_this.favourites.contains(url))
		{
			_this.favourites.unshift(url);
			
			if (_this.favourites.length > _this.favouritesLimit)
			{
				_this.favourites.pop();
			}
			
			return true;
		}
		return false;
	}
	
	
	this._favAdd = function(nome, entID, isEnt, urlAmigavel)
	{
		
		var reg = $.trim(nome) + _this.arraySep + $.trim(entID)  ;
		
		if(isEnt) {		
		    reg += (_this.arraySep + isEnt);
		}
		if (urlAmigavel)
		{
			reg += (_this.arraySep + urlAmigavel)
		}	
		//alert ('reg = ' + reg);
		if (!_this.favourites.contains(reg)) {
			_this.favourites.unshift(reg);
			
			if (_this.favourites.length > _this.favouritesLimit) {
				_this.favourites.pop();
			}
			
			return true;
		}
		return false;		
	}
	
	
	
	this.removeFav = function(nome, _url, isEnt, urlAmigavel)
	{
		
		
		
		var url = $.trim(nome) + _this.arraySep + $.trim(_url);	
		//alert ('removeFav url - ' + url);
		if(isEnt) {
		    url += _this.arraySep + isEnt;
		}
		if (urlAmigavel)
		{
			url += _this.arraySep + urlAmigavel;
		}
		
		
		if (_this.favourites.contains(url)) {
			for(var i = 0; i < _this.favourites.length; i++) {	
				//alert($.trim(_this.favourites[i]));
				if($.trim(_this.favourites[i]) == $.trim(url)) {				
						_this.favourites.splice(i, 1);							
						return true;
					break;
				}
			}
			
			
		}
		return false;				
	}	
	
	
	/**
	 * Saves the "data" property to a cookie
	 *
	 */
	this.save = function ()
	{        	
		// expire
		//alert('saving');
		var days = 60;
		var date = new Date();
		date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
		// .expire	    
		_this.data.visitedPages = (_this.visitedPages.length > 0)?_this.visitedPages.join():"";
		_this.data.favourites = (_this.favourites.length > 0)?_this.favourites.join():"";
		//_this.data.ingles=document.getElementById("ingles").value;
		_this.data.saved = 1;        		
		document.cookie = _this.cookiePrefix + "=" + JSON.stringify(_this.data) + "; expires=" + date.toGMTString() + "; path=/";		
		
	}
	
	this.decode = function  (str) {

	  var dest = "";

	  var len = str.length;

	  var index = 0;

	  var code = null;

	  var i = 0;

	  while (i < len) {

	    i = str.indexOf ("%", i);

	    if (i == -1)

	      break;

	    if (index < i)

	      dest += str.substring(index, i);

	    code = str.substring (i+1,i+3);

	    i += 3;

	    index = i;

	    if (code == "20") dest += " ";

	    else if (code == "25") dest += "%";

	    else if (code == "2C") dest += ",";

	    else if (code == "3B") dest += ";";

	    else if (code == "08") dest += "\b";

	    else if (code == "09") dest += "\t";

	    else if (code == "0A") dest += "\n";

	    else if (code == "0C") dest += "\f";

	    else if (code == "0D") dest += "\r";

	    else {

	      i -= 2;

	      index -= 3;

	    }

	  }

	  if (index < len)

	    dest += str.substring(index, len);

	  return dest;

	} 	
	
	this.getCookieVal = function  (offset) {	
	  var endstr = document.cookie.indexOf (";", offset);
	  if (endstr == -1)
	    endstr = document.cookie.length;

	  return this.decode(document.cookie.substring(offset, endstr));

	} 	
	
	this.GetCookie = function (name) {

	  var arg = name + "=";
	  var alen = arg.length;
	  var clen = document.cookie.length;
	  var i = 0;

	  while (i < clen) {

	    var j = i + alen;
	    if (document.cookie.substring(i, j) == arg)
	      return this.getCookieVal (j);
	    i = document.cookie.indexOf(" ", i) + 1;

	    if (i == 0) break;

	  }

	  return null;
	}
  	


	/**
	 * Loads data saved in a cookie and parses (JSON format) it to the "data" property
	 *
	 * @returns boolean 
	 *
	 */
	this.load = function ()
	{
		try {				
			// alert(this.cookiePrefix);
			// alert(this.GetCookie(this.cookiePrefix));	
			//alert(document.cookie.replace($.trim(_this.cookiePrefix) + "=", ""));		
			//alert(_this.cookiePrefix);
			// var ck = document.cookie.replace(_this.cookiePrefix + "=", "");
			//alert(ck.substring(0, ck.indexOf(";")));			
			var ck = this.GetCookie(this.cookiePrefix);		
			//alert(ck);
			if(ck) {
			 _this.data = JSON.parse(this.GetCookie(this.cookiePrefix));			 
			}
	
		} catch(e) {
		alert(e.message);
		_this.data = _this.protoData;	
			/*try {
			alert(_this.cookiePrefix);
			alert(document.cookie.replace(_this.cookiePrefix + "=", ""));
			if(document.cookie.replace(_this.cookiePrefix + "=", "")) {
				_this.data = JSON.parse(document.cookie.replace(_this.cookiePrefix + "=", ""));			
				
			} else {
				_this.data = _this.protoData;
				
			}			
			}catch(e){alert(e.message);}*/
		}
	
	_this.visitedPages = (_this.data.visitedPages != "")?_this.data.visitedPages.split(","):new Array();
	_this.favourites = (_this.data.favourites != "")? _this.data.favourites.split(",") : new Array();					
	
	return true;		
		
	}

	/**
	 * Blanks and expires the cookie that stores this class data
	 *
	 */
	this.erase = function ()
	{
		document.cookie = _this.cookiePrefix + "=; expires=-86400000; path=/";
	}
}

/** END OF COOKIES PERSISTENCE LIBRARY **/



/* START OF DHTML COMBO METHODS */


/**
 *
 * Found somewhere, don't remember where (if u did, please mail me)
 *
 * Updated by Sandro Salles - salles.contato@gmail.com (email/msn)
 * Last update: 2008.01.28
 *
 *  Dependency: jQuery (www.jquery.com);
 *
 **/
 
var setElementValue = function (option, comboID, index)
{
    var dhtml = $(option).parent().parent();
    var combo = DOM.getByID(comboID);
    combo.selectedIndex = index;
    dhtml.find(".selected-option:first").html(combo.options[combo.options.selectedIndex].text);
}


// Esta variável serve para evitar q haja sobreposição errada dos diversos layers de dhtmlcombo na página
var dhtmlCombozIndex = 1;

var dhtmlcombo = function (objCombo){

	var combo           =   objCombo;
	var comboWidth      =   Number($(combo).css("width").replace("px",""));
	var comboParent     =   $(combo).parent();
	
	
	
	// dá um bypass na string colocada pelo .NET, pega só o id original do select
    var comboCleanedID         =   combo.id.substring(combo.id.indexOf("ddl")); 
    
	var dhtml   = '<div id="dhtml-'+comboCleanedID+'" class="dhtml-combo-div">';
	dhtml           += '<span class="selected-option">'+combo.options[combo.options.selectedIndex].text+'</span>';
	dhtml           += '<div class="options-list">';
	
	// só escreve as opções se houver mais de uma ou se a unica que houver for válida (value != #)
	if(combo.options.length > 1 || (combo.options.length == 1 && combo.options[0].value!= "#"))
	{
	    for (var i=0; i<combo.options.length; i++)
	    {
	        var value   = combo.options[i].value;
	        var text    = combo.options[i].text;
	        
		    dhtml           += '<a href="#" onclick="setElementValue(this,\''+ combo.id +'\',\''+i+'\'); return false;" class="dhtml-option">';
		    dhtml               +=text;
		    dhtml           += '</a>';
	    }
	}
	
	dhtml           += '</div>';
	dhtml      += '</div>';
    
    comboParent.append(dhtml);
    
	$(combo).hide();
	
	var dhtmlCombo      =   comboParent.find('.dhtml-combo-div:first');
	var dhtmlSelected   =   dhtmlCombo.find('.selected-option:first'); 
	var dhtmlOptions    =   dhtmlCombo.find('.options-list:first');

    dhtmlCombo.width(comboWidth);
    dhtmlCombo.css("z-index",Number(dhtmlCombo.css("z-index"))-dhtmlCombozIndex);
        
    (dhtmlSelected.width() <= comboWidth)?dhtmlOptions.width(comboWidth+8):dhtmlOptions.width(dhtmlOptions.width());

	if(dhtmlOptions.height() > 168) {
	    dhtmlOptions.height(168);
	}
	
	if(combo.options.length > 1 || (combo.options.length == 1 && combo.options[0].value!= "#"))
	{
	    dhtmlCombo.click(function(){
            $(this).find('.options-list:first').show();
	    });
    	
	    dhtmlCombo.mouseover(function(){
            $(this).find('.options-list:first').show();
	    });
    	
	    dhtmlCombo.mouseout(function(){
            $(this).find('.options-list:first').hide();
	    });
	} else {
	    dhtmlSelected.css("color","#999");
	    dhtmlSelected.css("font-style","italic");
	}
    
    dhtmlCombozIndex++;
    
    return 	dhtmlCombo;
}


/* FLASH MANIPULATION CLASS */

/****************************************************************************
* Flash Tag Write Object v1.2b - by Lucas Fererira - www.lucasferreira.com	
* Info and Usage: www.lucasferreira.com/flashtag						
* bugs/reports: contato@lucasferreira.com							
****************************************************************************/

if(Browser == undefined){
	var Browser = {
		isIE: function(){ return (window.ActiveXObject && document.all && navigator.userAgent.toLowerCase().indexOf("msie") > -1  && navigator.userAgent.toLowerCase().indexOf("opera") == -1) ? true : false; }
	}
}

var Flash = function(movie, id, width, height, initParams){

	this.html = "";
	this.attributes = this.params = this.variables = null;
	
	this.variables = new Array();
	this.attributes = {
		"classid": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",
		"codebase": "http://fpdownload.macromedia.com/get/flashplayer/current/swflash.cab#version=8,0,22,0",
		"type": "application/x-shockwave-flash"
	}
	this.params = { "pluginurl": "http://www.macromedia.com/go/getflashplayer_br" };
	
	if(movie) {
		this.addAttribute("data", movie);
		this.addParameter("movie", movie);
	}
	
	if(id && id != null) this.addAttribute("id", id);
	if(width) this.addAttribute("width", width);
	if(height) this.addAttribute("height", height);
	
	if(initParams != undefined){
		for(var i in initParams){
			this.addParameter(i.toString(), initParams[i]);
		}
	}
	
}
Flash.version = "1.2b";
Flash.getObjectByExceptions = function(obj, excep){
	var tempObj = {};
	for(var i in obj){
		var inclui = true;
		for(var j=0; j<excep.length; j++)
			if(excep[j] == i.toString()) { inclui = false; break; };
		if(inclui) tempObj[i] = obj[i];
	}
	return tempObj;
}
Flash.prototype.addAttribute = function(prop, val){ this.attributes[prop] = val; }
Flash.prototype.addParameter = function(prop, val){ this.params[prop] = val; }
Flash.prototype.addVariable = function(prop, val){ this.variables.push([prop, val]); }
Flash.prototype.getFlashVars = function(){
	var tempString = new Array();
	
	for(var i=0; i<this.variables.length; i++)
		tempString.push(this.variables[i].join("="));
		
	return tempString.join("&");
}

Flash.prototype.toString = function(){
	
	this.params.flashVars = this.getFlashVars();
	if(Browser.isIE()){
		//IE
		this.html = "<ob" + "ject";
		var attr = Flash.getObjectByExceptions(this.attributes, ["type", "data"]);
		for(var i in attr) if(i.toString() != "extend") this.html += " " + i.toString() + " = \"" + attr[i] + "\"";
		this.html += "> ";
		var params = Flash.getObjectByExceptions(this.params, ["pluginurl", "extend"]);
		for(var i in params) if(i.toString() != "extend") this.html += "<param name=\"" + i.toString() + "\" value=\"" + params[i] + "\" /> ";
		this.html += " </obj" + "ect>";
	} else {
		//non-IE
		this.html = "<!--[if !IE]> <--> <obj" + "ect";
		var attr = Flash.getObjectByExceptions(this.attributes, ["classid", "codebase"]);
		for(var i in attr) if(i.toString() != "extend") this.html += " " + i.toString() + " = \"" + attr[i] + "\"";
		this.html += "> ";
		var params = Flash.getObjectByExceptions(this.params, ["extend"]);
		for(var i in params) if(i.toString() != "extend") this.html += "<param name=\"" + i.toString() + "\" value=\"" + params[i] + "\" /> ";
		this.html += " </obj" + "ect> <!--> <![endif]-->";
	}

	return this.html;
	
}

Flash.prototype.write = Flash.prototype.outIn = Flash.prototype.writeIn = function(w){
	if(typeof w == "string" && DOM.getByID) var w = DOM.getByID(w);
	if( w != undefined && w ) w.innerHTML = this.toString();
	else document.write( this.toString() );
}
