
/**
 * Framework glb
 * Define Fun????es gen??ricas - fora de escopo da framework - e namespace principal da
 * framework
 *
 * @author      Globo.com
 * @author      Jorge Falc??o
 * @version     1.0
 */
 
 
/* evitar bugs com o firebug */

if ( typeof console == 'undefined ' ) {
	console = {
		debug:function(){},
		info:function(){},
		warn:function(){},
		error:function(){}
	};
}

glb = {};


glb.util = {
	
	/**
 	 * Utilizada para serializar o conte??do de um form para envio via chamada XMLHttpRequest
 	 *
 	 * @param	id do form
 	 * @return	string contendo form serializado
 	 */		
	serialize:function( frm ) {
		if ( typeof frm  == 'string' ) {
			var frm = document.getElementById(form);
		}
		var elements = frm.elements;
    	var list = [];

		//TODO: melhorar....
    	for ( var i = 0; i < elements.length; i++) {
			if ( elements[i].type == 'radio' || elements[i].type == 'checkbox' ) {
				if ( elements[i].checked ) {
					var key = encodeURIComponent(elements[i].name);
					var value = encodeURIComponent(elements[i].value);						
					list.push( key + '=' + value );
				}
			} else {
				var key = encodeURIComponent(elements[i].name);
				var value = encodeURIComponent(elements[i].value);
				list.push( key + '=' + value );
			}
    	}	
		return list.join('&');
	},

	/**
 	 * Handler para usar o console do firebug como debug.
 	 *
 	 * Firebug ?? uma extension para Firefox, e pode der encontrada em:
 	 * https://addons.mozilla.org/extensions/moreinfo.php?id=1843
 	 *
 	 * @param - variaveis para debug.
 	 */	
	debug:function() {
		if ( typeof console == 'undefined' ) {
			return;
		}
		console.debug(arguments);
	},
		
	escapeHTML: function( value ) {
    	var div = document.createElement('div');
    	var text = document.createTextNode(value);
    	div.appendChild(text);
    	return div.innerHTML;
  	},
  	
	//
	// getPageSize()
	// Returns array with page width, height and window width, height
	// Core code from - quirksmode.org
	// Edit for Firefox by pHaez
	//
	getPageSize:function(){
		var xScroll, yScroll;
	
		if (window.innerHeight && window.scrollMaxY) {	
			xScroll = document.body.scrollWidth;
			yScroll = window.innerHeight + window.scrollMaxY;
		} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
			xScroll = document.body.scrollWidth;
			yScroll = document.body.scrollHeight;
		} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
			xScroll = document.body.offsetWidth;
			yScroll = document.body.offsetHeight;
		}

		var windowWidth, windowHeight;
		if (self.innerHeight) {	// all except Explorer
			windowWidth = self.innerWidth;
			windowHeight = self.innerHeight;
		} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
			windowWidth = document.documentElement.clientWidth;
			windowHeight = document.documentElement.clientHeight;
		} else if (document.body) { // other Explorers
			windowWidth = document.body.clientWidth;
			windowHeight = document.body.clientHeight;
		}	
	
		// for small pages with total height less then height of the viewport
		if(yScroll < windowHeight){
			pageHeight = windowHeight;
		} else { 
			pageHeight = yScroll;
		}

		// for small pages with total width less then width of the viewport
		if(xScroll < windowWidth){	
			pageWidth = windowWidth;
		} else {
			pageWidth = xScroll;
		}
		arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
		return arrayPageSize;
	},
	rgb2hex:function( rgb ) {
		var reg = new RegExp("^rgb\\(([0-9]+), ([0-9]+), ([0-9]+)\\)$");
		var ret;
		if ( ret = rgb.match( reg ) ) {
			return '#' + this.dec2hex(ret[1]) + this.dec2hex(ret[2]) + this.dec2hex(ret[3]);
		} else {
			return rgb;	
		} 	
		
	},
	dec2hex:function( dec ) {
		var a = dec % 16;
		var b = (dec - a)/16;
		var hexChars = "0123456789ABCDEF";
		return hexChars.charAt(b) + hexChars.charAt(a);		
	},
	popup:function( url, name, w, h, features ) {
		var left = (screen.width - w) / 2;
		var top = (screen.height - h) / 2;
		var s = "width=" + w + ", height=" + h + ", top=" + top + ", left=" + left + "," + features;
		return window.open(url, name, s);
	}
};

/**
 * C??digo das janelas do cadum
 * 
 * @author      Globo.com
 * @author      Jorge Falc??o
 * @version     1.0
 */
glb.cadun = {
	openWin:function( url ) {
		this.checkOpenStatus(this.openCenteredWindow(url, "cadun", 800, 550, "scrollbars=yes"));
	}, 
	checkOpenStatus:function(w) {
		if (w == null || w == undefined) {
			alert("Por favor, desative o seu bloqueador de popups e tente novamente");
		}
	},
	openCenteredWindow:function(url, name, w, h, features) {
		var left = (screen.width - w) / 2;
		var top = (screen.height - h) / 2;
		var s = "width=" + w + ", height=" + h + ", top=" + top + ", left=" + left + "," + features;
		return window.open(url, name, s);
	}
}



/**
 * Alias para o debug do Firebug.
 * Ex: uso $d(var1, var2, var3 ... var n );
 *
 * @param - variaveis para debug.
 * 
 */	


var $d = glb.util.debug;


glb.form = {
	checkAll:function( checkbox, checkBoxName ) {
		var f = checkbox.form;
		var els = f.elements;
		for ( var i in els ) {
			if ( els[i].type == 'checkbox' && els[i].name == checkBoxName ) {
				els[i].checked = checkbox.checked;			
			}
		}
	}
};


/**
 * Fun????es ??teis nos objetos padr??o do Javascript.
 *
 */	





/**
 * Remove espa??os em branco entre a string.
 *
 * @return String sem espa????es em branco
 * 
 */	
String.prototype.trim = function() {
	var before = new RegExp("^([\\s]+)");
	var after = new RegExp("([\\s]+)$");
	return this.replace( before, '').replace( after , '');
}

String.prototype.stripTags = function() {
	return this.replace(/<\/?[^>]+>/gi, '');
};


String.prototype.stripScripts = function() {
	return this.replace(new RegExp('(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)', 'img'), '');
}

/**
 * Esse m??todo Serve para criar fun????es que podem ser utilizadas como callback
 * para um determinado m??todo de um objeto.
 * 
 * Ex:
 * var n = {
 *		f:function() {
 *			alert('hello world');
 *		},
 *		teste:function() {
 *			setTimeout( this.f.bind(this), 1000);
 *		} 
 *	};
 *
 * @param objeto onde essa func??o vai ser executada
 * @return fun????o 
 * 
 */	
Function.prototype.bind = function(object) {
	var __method = this;
	return function() {
		return __method.apply(object, arguments);
	}
}


/**
 * Biblioteca dom da namespace glb.
 * Essa namespace cont??m v??rias fun????es de apoio para manipula????o de objetos DOM.
 * 
 * @author      Globo.com
 * @author      Jorge Falc??o
 * @version     1.0
 */

glb.dom = {
	
	/**
 	 * Fun????o Wrapper para document.getElementById
 	 *
 	 * @param	id do objeto ou eventualmente o proprio objeto.  
 	 * @return	Objeto ou Null se o objeto n??o existir
 	*/	
	$:function( element ) {
		if ( typeof element == 'string' ) {
			return document.getElementById( element );	
		}
		return element;
	},

	/**
	 * Remove Objeto de uma estutura DOM
	 *
	 * @param elemento ou id do elemento.
	 */	
	remove:function( element ) {
		var el = this.$( element );
		var pai = el.parentNode;
		pai.removeChild( el );
	},
	/**
	 * Altera propriedade display para 'none' tornando o objeto invis??vel.
	 *
	 * @param elemento ou id do elemento.
	 */	
	hide:function( element ) {
		try {
			this.$( element ).style.display = 'none';
		} catch( e ) {}
	},
	
	/**
	 * Altera propriedade display para '' tornando o objeto vis??vel.
	 *
	 * @param elemento ou id do elemento.
	 */			
	show:function( element ) {
		try {
			this.$( element ).style.display = '';
		} catch( e ) {}
	},

	/**
	 * Altera opacidade de um Objeto.
	 * Leve em considera????o diferen??as entre browsers.
	 * NOTA: para opacidade funcionar no IE ?? necess??ria propriedade 'width' setada.
	 *
	 * @param elemento ou id do elemento.
	 * @param Opacidade [0..1]
	 */			
	setOpacity:function( element, opacity ) {
		var element = this.$( element );

		if (opacity == 0 && element.style.visibility != "hidden" ) {
			element.style.visibility = "hidden";
		} else if (element.style.visibility != "visible") {
			element.style.visibility = "visible";
			if (window.ActiveXObject) { 
				element.style.filter = "alpha(opacity=" + opacity*100 + ")";
			}
		}
		element.style.opacity = opacity;	
	},

	/**
	 * Adiciona um className a um Objeto
	 *
	 * @param elemento ou id do elemento.
	 * @param className
	 */
	addClassName:function( element, className ) {
		$d(className);
		var element = this.$( element );
		if ( element.className.length > 0 ) {
			element.className += ' ';	
		}
		element.className += className;	
		$d(element);
	},
	/**
	 * Remove um className a um Objeto
	 *
	 * @param elemento ou id do elemento.
	 * @param className
	 */		
	remClassName:function( element, className ) {
		
		var element = this.$(element);
		var cls = element.className.split(' ');
		if ( cls.length == 0 ) return;
		var ncn = [];
		for( var i in cls ) {
			if ( cls[i] == className ) {
				continue;
			}	
			ncn.push( cls[i] );
		}
		element.className = ncn.join(' ');
	},
	/**
	 * Retorna um className a um Objeto
	 *
	 * @param elemento ou id do elemento.
	 * @param className
	 * @return boolean
	 */		
	hasClassName:function( element, className ) {
		var element = this.$(element);
		var cls = element.className.split(' ');
		if ( cls.length == 0 ) return false;
		for( var i in cls ) {
			if ( cls[i] == className ) {
				return true;
			}	
		}
		return false;
	},

	/**
	 * Retorna posi????o absoluta de um Objeto.
	 * PS: ele soma recursivamente os offsets dos seus ancestrais at?? encontrar
	 * a posi????o absoluta
	 *
	 * @param elemento ou id do elemento.
	 * @return array[ offsetLeft, offsetTop ]
	 */	
	getPosition:function( element ) {
		var element = glb.dom.$(element);
		var top = 0, left = 0;
		do {
			top += element.offsetTop  || 0;
			left += element.offsetLeft || 0;
			element = element.offsetParent;
		} while (element);
		return [left, top];
	},
	/**
	 * Faz Scroll da tela at?? a posi????o do Objeto.
	 *
	 * @param object
	 */	
	scrollTo: function( element ) {
		var element = glb.dom.$(element);
		var x = element.x ? element.x : element.offsetLeft;
		var y = element.y ? element.y : element.offsetTop;
		window.scrollTo(x, y);
	},
		
		
	addEvent:function( event, obj, listener ) {
		//console.debug(obj);
//		console.debug(obj.type + " | " + (typeof obj == 'string'));
		if ( typeof obj == 'string' )
			obj = glb.dom.$(obj);
			//console.debug(obj);
		if ( obj.addEventListener ) {
			obj.addEventListener( event, listener, false );
		} else {
			obj.attachEvent( 'on' + event, listener.bind(obj) );
		}
	},
	
	cleanWhitespace: function(element) {
    	element = glb.dom.$(element);
		for (var i = 0; i < element.childNodes.length; i++) {
			var node = element.childNodes[i];
			if (node.nodeType == 3 && !/\S/.test(node.nodeValue)) {
				glb.dom.remove(node)
			}
		}
	}


		
		
};

/* Ajax Globo Object */
glb.Ajax = function(url, options){
	this.transport = this.getTransport();
	this.postBody = options.postBody || '';
	this.method = options.method || 'post';
	this.onComplete = options.onComplete || null;
	this.onError = options.onError || null;
	this.update = glb.dom.$(options.update) || null;
	this.request(url);
}

glb.Ajax.prototype = {
	initialize: function(url, options){
		this.transport = this.getTransport();
		this.postBody = options.postBody || '';
		this.method = options.method || 'post';
		this.onComplete = options.onComplete || null;
		this.onError = options.onError || null;
		this.update = glb.dom.$(options.update) || null;
		this.request(url);
	},
	request: function(url){
		this.transport.open(this.method, url, true);
		this.transport.onreadystatechange = this.onStateChange.bind(this);
		if (this.method == 'post') {
			this.transport.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
			if (this.transport.overrideMimeType) this.transport.setRequestHeader('Connection', 'close');
		}
		this.transport.send(this.postBody);
	},
	onStateChange: function(){
	
		if (this.transport.readyState == 4 ) {
			if ( this.transport.status == 200 ) {
				
				if (this.update) {
					this.update.innerHTML = this.transport.responseText;
				}
				if (this.onComplete) {
					var ev = null;
					if ( (this.transport.getResponseHeader('Content-type') || '').match(/^text\/javascript/i) ) {
						ev = this.transport.responseText;
					} else {
						ev = this.transport.getResponseHeader("X-JSON");
					}
					var json = null;
					try {
						//Rhino
						eval('var JSON = '+ev);	
						json = JSON;
					} catch ( e ) {};
					setTimeout(function(){this.onComplete(json, this.transport);}.bind(this), 10);
				}
			} else {
				if ( this.onError ) {
					setTimeout(function(){this.onError(this.transport);}.bind(this), 10);
				}
			}
			this.transport.onreadystatechange = function(){};
		}
	},
	getTransport: function() {
		if (window.ActiveXObject) return new ActiveXObject('Microsoft.XMLHTTP');
		else if (window.XMLHttpRequest) return new XMLHttpRequest();
		else return false;
	}
};


/*
OPERAÇOES COM COOKIE
*/

/* Operações com Cookies*/

function getexpirydate(nodays){
 var UTCstring;
 Today = new Date();
 nomilli=Date.parse(Today);
 Today.setTime(nomilli+nodays*24*60*60*1000);
 UTCstring = Today.toUTCString();
return UTCstring;
}

function getcookie(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 unescape(c.substring(nameEQ.length,c.length));
	}
	return null;
}

function setcookie(name,value,duration, domain){
 cookiestring=name+"="+escape(value)+";EXPIRES="+getexpirydate(duration)+";domain="+domain+";path=/";
 document.cookie=cookiestring;
 if(!getcookie(name)){
 return false;
 }
 else{
 return true;
}
}

function messageByCookie(cookiename,msg){
var	cookieValue = getcookie(cookiename);
if(cookieValue=='OK'){
	showAlert(msg);
	cookieValue=setcookie(cookiename,'DEL',-1);
}
}

function showMessageByCookie(cookiename)
{
	var tipoMensagem;
	var mensagem;
	var	cookieValue = getcookie(cookiename);
	
	if (cookieValue)
	{
	    var pos = cookieValue.indexOf("$#$");
    	if (pos != 0) {
    		tipoMensagem = cookieValue.substring(0, pos);
    		mensagem = cookieValue.substring(pos + 3, cookieValue.length);
    	} else {
    		mensagem = cookieValue;
    	}
		showAlert(mensagem);
		// cookieValue=setcookie(cookiename,'DEL',-1);
	}
}
