/**
 * @author Regis Maioli
 * My Event Plugin - functions based on Prototype.js
 * (Prototype JavaScript framework, version 1.4.0 (c) 2005 Sam Stephenson <sam@conio.net>)
 * requires - jquery 1.2.3 framework
 */ 
jQuery.fn.mousePos = function() {
	var x = 0, y = 0, event = this[0], d = document;
	x = event.pageX || (event.clientX + (d.documentElement.scrollLeft || d.body.scrollLeft));
	y = event.pageY || (event.clientY + (d.documentElement.scrollTop || d.body.scrollTop));
	return {x:x, y:y};
};
jQuery.fn.mouseX = function() {
	return this.mousePos().x;
};
jQuery.fn.mouseY = function() {
	return this.mousePos().y;
};
jQuery.fn.stopPropagation = function() {
	var event = this[0];
	if (event.preventDefault) {
		event.preventDefault();
		event.stopPropagation();
	}
	else {
		event.returnValue = false;
		event.cancelBubble = true;
	}
};


String.prototype.lTrim = function(){ return this.replace(/^\s*/,""); };
String.prototype.rTrim = function(){ return this.replace(/\s*$/,""); };
String.prototype.trim = function(){ return this.rTrim().lTrim(); };
String.prototype.isEmpty = function(){ return (this.trim()=='') };
String.prototype.isDefined = function() { return eval("typeof "+this+" != 'undefined'");	}
String.prototype.eval = function() { return eval(this); }
function maxDay(y,m) {return ((m!=2)&&(m<13))?((m<8)?((m%2==1)?31:30):((m%2==1)?30:31)):(m<13)?(((y%4==0)&&((!(y%100==0))||(y%400==0)))?29:28):false;}
String.prototype.isDate = function() { 
	if(this.isEmpty() ||(!this.match(/\d{1,2}\/\d{1,2}\/\d{4}/))) return false;
	dt=this.split("/");
	return ((dt.length!=3)||(dt[0]<=0)|| (dt[1]<=0)|| (dt[2]<1900) || (dt[1]>13)||(dt[0]>maxDay(dt[2],dt[1])))?false:true;
}
String.prototype.isEmail = function(email){	return (this.isEmpty()) ? false : this.match(/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)+$/);}
Array.prototype.indexOf=function(v) { for (var i = 0; i < this.length; i++) if (this[i] == v) return i; return -1; }
Array.prototype.insert=function(pos,v) { this.splice(pos,0,v) };
Array.prototype.remove=function(v) { this.removeAt(this.indexOf(v)); };
Array.prototype.removeAt=function(ix) { if(ix>-1) this.splice(ix,1) };
Array.prototype.add=Array.prototype.queue=function(T){this.push(T);};
Array.prototype.exists=function(v) { return this.indexOf(v)>-1 };
Array.prototype.removeAt=function(Y){return this.splice(Y,1);};


var Select = {
	hasSelectFeatures:true
	,addItem:function(value,text){
		if(!value) return;
		text = (text || value);
		var newOption = document.createElement("OPTION");
		newOption.value=value;
		newOption.text=text;
		try {this.add(newOption);}catch(e){this.add(newOption,null);}
	},
	removeItem:function(ix){
		if (typeof ix == 'string') ix = this.indexOf(ix);
		if(this[ix]) this.remove(ix);
	},
	removeSelected:function(){
		if(this.multiple) while(this.selectedIndex>-1){
			this.remove(this.selectedIndex);
		} else this.remove(this.selectedIndex);
	},
	move:function(to){
		to = $(to)[0];
		if(this.multiple) while(this.selectedIndex>-1){
			to.appendChild(this[this.selectedIndex]);
		} else to.appendChild(this[this.selectedIndex]);
	},
	moveAll:function(to){
		to = $(to)[0];
		while(this.length) to.appendChild(this[this.length-1]);
	},
	moveUp:function() {
		var ix = this.selectedIndex;
		if (ix<0) return;
		if (ix) this.insertBefore(this[ix],this[ix-1]);
	},
	moveDown:function() {
		var ix = this.selectedIndex+1;
		if (ix==0) return;
		if (ix<this.length) this.insertBefore(this[ix],this[ix-1]);
	},
	moveToFirst:function() {
		var ix = this.selectedIndex;
		if (ix<0) return;
		else this.insertBefore(this[ix],this[0]);
	},
	moveToLast:function(){
		var ix = this.selectedIndex;
		if (ix<0) return;
		else this.appendChild(this[ix]);
	},
	setSelected:function(v) {
		var i = this.indexOf(v);
		if(i>-1) this[i].selected=true;
		return (i>-1);
	},
	selectAll:function() {
		if(this.length==0) return false;
		else for (var i=0; i<this.length;i++) this[i].selected=true;
		return true;
	},
	indexOf:function(text){
		for(var i=0;i<this.length;i++) if (this[i].text==text) return i;
		return -1;
	},
	clear:function(o){ 
		try { this.length=0; } catch(e) {}; 
	},
	order:function(){ 
		var arr = new Array();
		for(var i=0;i<this.length;i++) {
			arr[i] = new Array();
			var tmp_text = this[i].text;
			arr[i][0] = tmp_text.toLowerCase();
			arr[i][1] = {value:this[i].value,text:this[i].text,selected:this[i].selected};
		}
		arr.sort();
		for(var i=0;i<this.length;i++) {
			var option = arr[i][1];
			this[i].text = option.text;
			this[i].value = option.value;
			this[i].selected = option.selected;
		}
	}
	,getAll:function(){
		var values = new Array();
		for(var i=0;i<this.length;i++) values.push(this[i].value);
		return values;
	}
	,set:function(element){
		if (!element.hasSelectFeatures) {
			jQuery.extend(element,this);
		}
	}
}



var IframeRequest = function(form, options){

	this.form = form;
	this.defaultFunction=function(o){ return true; }
	this.name = 'IframeRequester_'+ String(Math.random()).substring(2,5);
	window[this.name] = this;
	this.send_timeout = null;
	this.clear_msg_timeout = null;
	this.div_iframe = null;
	this.submited = false;
	this.options = options || {};
	this.onSubmit = this.options.onSubmit || this.defaultFunction;
	this.onSuccess = this.options.onSuccess || this.defaultFunction;
	this.onError = this.options.onError || this.defaultFunction;
	this.send_msg = this.options.send_msg || 'Aguarde...';
	this.div_msg = this.options.div_msg || null;
	
	$(this.form).submit(function(){ return this.IframeRequester.send(); });
	
	this.form.target = this.name + '_iframe';
	this.form.IframeRequester = this;
	this.form._submit = function(){
		var a = document.createElement("INPUT");
		a.type="image";
		a = this.appendChild(a);
		$(a).hide()[0].click();
		$(a).remove();
	};
	
	this.send = function(){
		try {
			if(this.submited) return false;
			if (this.onSubmit(this.form) == false) { return false; } 
			else {
				clearTimeout(this.clear_msg_timeout);
				
				if(this.div_msg) $(this.div_msg).html(this.send_msg);
				
				this.div_iframe = (!this.div_iframe) ? document.body.appendChild(document.createElement("DIV")) : this.div_iframe;
				var d = $(this.div_iframe);
				
				d.hide().html('<iframe name="' + this.name + '_iframe" src="javascript=false" frameborder="0" width="100" height="100" style="display=inline"></iframe>');
	
				this.submited = true;
				this.send_timeout = setTimeout(this.name + ".releaseSubmit(1);", 30000);
			}
		} catch(e){
			return false;
		}
	};
	this.releaseSubmit = function(clearMsg){
		this.submited = false;
		clearTimeout(this.send_timeout);
		if(clearMsg && this.div_msg) $(this.div_msg).empty();
		this.clearIframe();
	};
	this.error = function(error){
		this.releaseSubmit(1);
		this.onError(this.form, error);
	}
	this.success = function(msg){
		this.releaseSubmit();
		if (msg && this.div_msg) {
			var o = $(this.div_msg);
			o.html(msg);
			this.clear_msg_timeout = setTimeout(function(){
				o.empty();
			}, 5000);
		}
		this.onSuccess(this.form, msg);
	};
	
	this.clearIframe = function(){
		var o = $(this.div_iframe);
		//setTimeout(function(){ o.empty(); }, 100);
	};
}; 

/* para o header */
var AddFav = function(){
	var url = window.location;
	var title = window.document.title;
	if (window.sidebar) window.sidebar.addPanel(title, url, "");
	else if (window.external) window.external.AddFavorite(url, title);
}

var HeresMitta = {
	 session_created:false
	,favoritos:new Array()
	,showError: function(div, msg){
		var divMsg = $('#div'+div+'Msg').html('<div class="error_msg">'+msg+'</div>').show(500);
		var divOK = $('#div'+div+'OK').addClass('nok').removeClass('ok').show(200);
	}
	,showOK: function(div, showIco){
		var divMsg = $('#div'+div+'Msg').hide(500);
		var divOK = $('#div'+div+'OK')[(showIco)?'addClass':'removeClass']('ok').removeClass('nok').show(200);
	}
	,setFavorito:function(objID){
		if(this.favoritos.indexOf(objID)<0) this.favoritos.push(objID);
		$('#div_fav_'+objID).removeClass("fav_off").addClass("fav_on");
	}
	,unsetFavorito:function(objID){
		this.favoritos.remove(objID);
		$('#div_fav_'+objID).removeClass("fav_on").addClass("fav_off");
	}
	,addFavoritos:function(objID){
		$.post("/favorito.php", {obj_id: objID},
			function(data){
				if(data.error){
					HeresMitta.showError("Fav_"+objID,data.error);
					setTimeout(function(){HeresMitta.showOK("Fav_"+objID) },5000);
				}
				else if(data.favorito)
					HeresMitta.setFavorito(data.objeto_id);
				else 
					HeresMitta.unsetFavorito(data.objeto_id);									
			}
		,"json");
	}
}
	
var Animacao = {
	Estrelas:{
		iniciar:function(e){
			if(!this.liberado||this.votando) return;
			$('#'+this.id+' div.hint_estrelas').hide();
			$('#'+this.id+' div.vota_estrelas').html('').show();
		}
		,parar:function(e){
			if(!this.liberado||this.votando) return;
			$('#'+this.id+' div.vota_estrelas').hide();
			$('#'+this.id+' div.hint_estrelas').show();
		}
		,calcular:function(e){
			if(!this.liberado||this.votando) return;
			var of = $(this).offset(this)
			, 	x = $(e).mouseX() - of.left
			, 	value = parseInt((x/26)+1)
			, 	width;
			value = (value>5)?5:value;
			width = (value*26) + 'px';
			$('#'+this.id+' div.vota_estrelas').css("width", width);
			this.myhint = value;
		}
		,atualiza:function(o, value){
			value = (value>5)?5:value;
			width = (value*26) + 'px';
			$(o+' div.vota_estrelas').html('<div>OK!</div>').hide();
			$(o+' div.hint_estrelas').css("width", width).show();
			$(o)[0].liberado = false;
		}
		,enviaVoto:function(e) { 
			if(!this.liberado||this.votando) return;
			this.votando = true;
			var ObjID = this.id.split('_')[1];
			var Nota =  this.myhint;
			$('#'+this.id+' div.vota_estrelas').html('<div>Votando...</div>');
			$.post("/votar.php", {nota: Nota, obj_id: ObjID},
			  function(data){
			  	var o = '#estrelas_'+data.obj_id;
					$(o)[0].votando = false;
				if(!data.votoOK) {
					$(o+' div.vota_estrelas').html('').hide();
					HeresMitta.showError("Fav_"+ObjID, data.errorMsg);
					setTimeout(function(){HeresMitta.showOK("Fav_"+ObjID) },5000);
				} else {
					Animacao.Estrelas.atualiza(o, data.nota);
				}
			  },"json");
		}
		,set:function(o){
			$(o).hover(this.iniciar, this.parar)
				.mousemove(this.calcular)
				.click(this.enviaVoto);
			$(o)[0].liberado = true;
		}
	}
} 
