// JavaScript Document
// JavaScript com acessorios para os sitema
// Funções communs para criação de elementos html mais completos

//A partir de retorno de JSON esta função monta os itens do select
/*
Parametros de entreda = Object;
@url = arquivo JSON "/json/return.lista.php" - String
@defaultValue = valos padrão do select - String
@fildValue = indice do JSON que será considerad o value o <option> - String
@fieldName = indice do JSON que será o Conteudo do <option> - String
@data = valores para o GET do PHP  - Object "{id:'X'}"
@attr = Attributos para o <option> - Object
*/
jQuery.fn.montaSELECT = function(P){
	var SELECT_local = this;
	
	P = jQuery.extend({
		url: false,
		defaultValue: 'null',
		fieldValue: "id",
		fieldName: "nome",
		data: {},
		attr: {},
		success: function(){ return false; }
	}, P);
	
	if(P.url){
		jQuery.ajax({
			url: P.url,
			data: P.data,
			dataType: "json",
			beforeSend: function(){
				jQuery("option[value!='null']",SELECT_local).remove();
				SELECT_local.css({background:"#CCC",color:"#666",fontStyle:"italic"});
				jQuery("<option/>").html("aguarde...").val("").appendTo(SELECT_local);	
			},
			success: function(json){
				jQuery("option[value!='null']",SELECT_local).remove();
				if(json.dados){
					jQuery.each(json.dados, function(i, valor){
									jQuery("<option/>").html(valor[P.fieldName]).attr(P.attr).attr({value:valor[P.fieldValue]}).appendTo( SELECT_local );
								});
					SELECT_local.val(P.defaultValue);
				}
				SELECT_local.css({background:"",color:"",fontStyle:""});
				P.success(SELECT_local, json);
			}
		});
	}else if(P.list){
		jQuery("option[value!='null']",SELECT_local).remove();
		if(typeof(P.list) == 'number'){
			for(var i=1; i<=P.list; i++)
				jQuery("<option/>").html(i).attr(P.attr).attr({value:i}).appendTo( SELECT_local );
		}else{
			jQuery.each(P.list, function(i, valor){
				jQuery("<option/>").html(valor).attr(P.attr).attr({value:valor}).appendTo( SELECT_local );
			});
		}
		setTimeout(function(){ SELECT_local.val(P.defaultValue); }, 50);
	}
	return this;
};

/*
	
*/
jQuery.fn.selecionarTodos = function(){
	var tabela = this;
	jQuery(".ck-todos",this).click(function(){
		jQuery("input:checkbox:visible", tabela).attr("checked",jQuery(this).attr("checked"));
	});
	jQuery("input:checkbox", this).click(function(){
		if( jQuery(".ck-todos",tabela).attr("checked") ){
			jQuery(".ck-todos",tabela).attr("checked",jQuery(this).attr("checked"));
		}
	});
	return this;
};


/*
Utilize para monta um campo de data a partir de um input qualquer
*/
jQuery.fn.montaData = function(){
	//<input type="button" class="botaoCalendar" onclick="" value="&nbsp;"/>
	this.each(function(){
		if(!jQuery(this).attr("datado") && jQuery(this).attr('id') ){
			var idData = jQuery(this).attr('id');
			var data = jQuery("<input type='button'/>").addClass("botaoCalendar").val("  ").click(function(){
				displayCalendar(document.getElementById(idData),'dd/mm/yyyy',this);
			});
			jQuery(this).before(data);
			jQuery(this).width( jQuery(this).width()-data.width()-13 ).attr({readonly:"readonly", datado:"datado"});
		}
	});
	return this;
};

/*
	monta um botao
*/
jQuery.fn.montaBotao = function(P){
	P = jQuery.extend({
		prefix: "botao"
	}, P);
	if(P.prefix != ""){
		P.prefix = P.prefix+"-";
	}
	this.each( function(){
		if( jQuery(".b_conteudo",this).length == 0 ){
			var cont = jQuery("<div/>").addClass("b_conteudo");
			var center = jQuery("<div/>").addClass("b_center");
			jQuery(this).wrapInner(cont).wrapInner(center);
			
			jQuery("<div/>").addClass("b_left").prependTo(this);
			jQuery("<div/>").addClass("b_right").appendTo(this);
			
			jQuery(this).hover(
				function(){ jQuery(this).addClass(P.prefix+"over"); },
				function(){ jQuery(this).removeClass(P.prefix+"over"); }
			).click( function(){ jQuery(this).removeClass(P.prefix+"over"); });
		}
	});
	return this;
};

jQuery.fn.centralizaBotao = function(){
	jQuery(this).each( function(){
			// necessario para ie inserir um clear apos todos os botoes
			// faz isso automaticamente
			jQuery(this).width("");
			if(!jQuery(".clear",this).length){
				jQuery("<div/>").addClass("clear").appendTo(this);
			}
			//jQuery(this).css({paddingLeft:'0'});
			var botoes = jQuery("a",this);
			var largura_botoes = 0;
			var largura_total = jQuery(this).width(); // largura da div centraliza botao
			botoes.each(function(i){
				largura_botoes += jQuery(this).width();
				if(i==0)
					jQuery(this).css("marginLeft",0); // remove a margem direita do ultimo botao
				largura_botoes += parseInt(jQuery(this).css("marginLeft")); // adiciona na contagem o valor da margem direita
			});
			//jQuery(this).css({paddingLeft: (largura_total-largura_botoes)/2 });
			jQuery(this).width(largura_botoes).css({marginLeft:"auto",marginRight:"auto"});
	});
	return this;
};

jQuery.fn.extend({
	check: function() {
		return this.each(function() { this.checked = true; });
	},
	uncheck: function() {
		return this.each(function() { this.checked = false; });
	}
});

var xmlImdiomaCarregado = false;
jQuery.textoIdioma = function(cod, before){
	if(xmlImdiomaCarregado){
		var msg = jQuery("msg#"+cod, xmlImdiomaCarregado);
		before(msg);
	}else{
		jQuery.ajax({
			url: "js/mensagens.xml",
			dataType: 'xml',
			success: function(data){
				xmlImdiomaCarregado = data;
				var msg = jQuery("msg#"+cod, data);
				before(msg);
			}
		});
	}
};

function tamanhoTela() {
	var w = new Array();
	if (self.innerHeight) { // all except Explorer
		w[0] = self.innerWidth;
		w[1] = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		w[0] = document.documentElement.clientWidth;
		w[1] = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		w[0] = document.body.clientWidth;
		w[1] = document.body.clientHeight;
	}
	return w;
}

// url_encode version 1.0 
function url_encode(str) {
	var hex_chars = "0123456789ABCDEF";
	var noEncode = /^([a-zA-Z0-9\_\-\.])jQuery/;
	var n, strCode, hex1, hex2, strEncode = "";
	for (n = 0; n < str.length; n++) {
		if (noEncode.test(str.charAt(n))) {
			strEncode += str.charAt(n);
		}
		else {
			strCode = str.charCodeAt(n);
			hex1 = hex_chars.charAt(Math.floor(strCode / 16));
			hex2 = hex_chars.charAt(strCode % 16);
			strEncode += "%" + (hex1 + hex2);
		}
	}
	return strEncode;
}

// url_decode version 1.0 
function url_decode(str) {
	var n, strCode, strDecode = "";
	for (n = 0; n < str.length; n++) {
		if (str.charAt(n) == "%") {
			strCode = str.charAt(n + 1) + str.charAt(n + 2);
			strDecode += String.fromCharCode(parseInt(strCode, 16));
			n += 2;
		}
		else {
			strDecode += str.charAt(n);
		}
	}
	return strDecode;
}

var janela;
function abrirjanelaFull(X,Y,R) {
	TT = tamanhoTela();
	R = R ? R : 0; janela = window.open(X,Y,'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable='+R+',width='+TT[0]+',height='+TT[1]+',left=0,top=0');
	return janela;
}

Array.prototype.in_array = function (obj) {
	var len = this.length;
	for (var x=0; x<=len; x++) {
		if (this[x] == obj) { return true; }
	}
	return false;
}

jQuery.fn.addDisabled = function(){
	jQuery(this).addClass("disabled");
	jQuery("input,select",this).attr("disabled","disabled").addClass("disabled");
}
jQuery.fn.removeDisabled = function(){
	jQuery(this).removeClass("disabled");
	jQuery("input,select",this).removeAttr("disabled").removeClass("disabled");
}
jQuery.fn.toggleDisabled = function(){
	if(jQuery(this).hasClass("disabled")){
		jQuery(this).addDisabled();
	}else{
		jQuery(this).removeDisabled();
	}
}

function roundNumber(num, dec) {
	var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
	result = String(result);
	decimals = result.substr(result.lastIndexOf('.')+1);
	if(result.lastIndexOf('.') == -1){
		decimals = '';
		result += '.';
	}
	if(decimals.length < dec){
		for(i=0;i<dec-decimals.length;i++){
			result += '0';
		}
	}
	return result;
}

/*
 * Allows only valid characters to be entered into input boxes.
 * Note: does not validate that the final text is a valid number
 * (that could be done by another script, or server-side)
 *
 * @name     numeric
 * @param    decimal      Decimal separator (e.g. '.' or ',' - default is '.')
 * @param    callback     A function that runs if the number is not valid (fires onblur)
 * @author   Sam Collett (http://www.texotela.co.uk)
 * @example  $(".numeric").numeric();
 * @example  $(".numeric").numeric(",");
 * @example  $(".numeric").numeric(null, callback);
 *
 */
eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('r.E.W=7(c,d){c=c||".";d=q d=="7"?d:7(){};6.K(7(e){g a=e.i?e.i:e.h?e.h:0;2(a==k&&6.N.J()=="G"){5 3}f 2(a==k){5 j}g b=j;2((e.4&&a==y)||(e.4&&a==v))5 3;2((e.4&&a==t)||(e.4&&a==u))5 3;2((e.4&&a==V)||(e.4&&a==S))5 3;2((e.4&&a==R)||(e.4&&a==Q))5 3;2((e.4&&a==P)||(e.4&&a==O)||(e.L&&a==p))5 3;2(a<I||a>H){2(a==p&&6.l.F==0)5 3;2(a==c.n(0)&&6.l.o(c)!=-1){b=j}2(a!=8&&a!=9&&a!=k&&a!=D&&a!=C&&a!=M&&a!=B&&a!=A){b=j}f{2(q e.i!="z"){2(e.h==e.m&&e.m!=0){b=3}f 2(e.h!=0&&e.i==0&&e.m==0){b=3}}}2(a==c.n(0)&&6.l.o(c)==-1){b=3}}f{b=3}5 b}).x(7(){g a=r(6).w();2(a!=""){g b=T U("^\\\\d+$|\\\\d*"+c+"\\\\d+");2(!b.s(a)){d.X(6)}}});5 6}',60,60,'||if|true|ctrlKey|return|this|function||||||||else|var|keyCode|charCode|false|13|value|which|charCodeAt|indexOf|45|typeof|jQuery|exec|120|88|65|val|blur|97|undefined|46|39|36|35|fn|length|input|57|48|toLowerCase|keypress|shiftKey|37|nodeName|86|118|90|122|67|new|RegExp|99|numeric|apply'.split('|'),0,{}))
