var intervalo1;
var intervalo2;
var mydate = new Date();
var pagina_atual;
data_utc = Date.UTC(mydate.getYear(), mydate.getMonth(), mydate.getDate(), mydate.getHours(), mydate.getMinutes(), mydate.getSeconds(), mydate.getMilliseconds());

// JavaScript Document
Number.prototype.formatMoney = function(c, d, t){
	var n = this, c = isNaN(c = Math.abs(c)) ? 2 : c, d = d == undefined ? "," : d, t = t == undefined ? "." : t, s = n < 0 ? "-" : "", i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
	return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
}

String.prototype.fullReplace = function(value, replacement){
    var Val = new String(this);
    i = 0;
    while(Val.search(value) >= 0)
	{
	    Val = Val.replace(value, replacement);
	    if(i >= 50)
	        break;
        i++;
	}
    return Val;
}

// Alert usando o plugin blockUI
function jAlert(mensagem){
	$.unblockUI;
	html = "<h1>Aviso!</h1>";	
	html = html + "<p>"+ mensagem +"</p>";
	html = html + "<p id='okAlert'>OK</p>";
	$.blockUI({ message: html, css:{ background: '#ffff99 url(http://www.e-value.com.br/_valuegaia/img/alert.jpg) no-repeat 10px center', 'padding-left':'35px',cursor: "auto"} });
	$("#okAlert").click(function(){$.unblockUI();});	
}
function jLoading(){
	$.unblockUI
	html = "<h1>Carregando</h1><p>Por favor, aguarde.</p>";	
	$.blockUI({ message: html, css:{ background: '#c0ffff url(http://www.e-value.com.br/_valuegaia/img/load.gif) no-repeat 10px center', 'padding-left':'35px',cursor: "auto", color: "#4a8389","font-size": "12px"} });
}
function jError(mensagem){
	$.unblockUI
	html = "<h1>Erro</h1><p>"+ mensagem +"</p>";	
	html = html + "<p id='okAlert'><a href='#'>OK</a></p>";
	$.blockUI({ message: html, css:{ background: '#F66 url(http://www.e-value.com.br/_valuegaia/admin/img/error.jpg) no-repeat 10px center', 'padding-left':'35px',cursor: "auto", color: "#600","font-size": "12px"} });
	$("#okAlert").click(function(){$.unblockUI(); return(false); });
}
function jOk(){
	var myArg = arguments;
	$.unblockUI;
	html = "<h1>Sucesso</h1><p>"+ arguments[0] +"</p>";	
	html = html + "<p id='okAlert' class='okAlert'><a href='#'>OK</a></p>";
	$.blockUI({ message: html, css:{ background: '#99ff99 url(http://www.e-value.com.br/_valuegaia/admin/img/ok.gif) no-repeat 10px center', 'padding-left':'35px',cursor: "auto", color: "#4a8389","font-size": "12px"} });
	$("#okAlert").click(function(){
		$.unblockUI();
		if(myArg[1]){
			newWindow(myArg[1],"");
		}
		return(false);
	});
}
function jConfirmDelete(mensagem, obj){
	$.unblockUI
	html = "<h1>Aten&ccedil;&atilde;o</h1><p>"+ mensagem +"</p>";	
	html = html + "<p><a href='#' id='okAlert'>Sim</a> <a href='#' id='noAlert'>N&atilde;o</a></p>";
	$.blockUI({ message: html, css:{ background: '#fc6 url(http://www.e-value.com.br/_valuegaia/admin/img/confirm.gif) no-repeat 10px center', 'padding-left':'35px',cursor: "auto", color: "#C30","font-size": "12px"} });
	$("#okAlert").click(function(){
		$.unblockUI();
		var caminho = new Array(); 
		caminho = obj.attr("href").split("?");
		pastas = caminho[0].replace("-acao","");
		//alert(pastas);		
		$.ajax({
			type: "GET",
			beforeSend: function(){
				jLoading();
			},
			error : function(){
				$.blockUI({message: "erro", css:{ cursor: "auto"}});
			},
			url: caminho[0],
			data: caminho[1],
			success: function(msg){
				$.unblockUI();
				obj.parent().parent().remove();
			}
		});
	});
	$("#noAlert").click(function(){$.unblockUI();return false;});
	return false;	
}
function jConfirm(mensagem, link, param){
	$.unblockUI;
	html = "<h1>Mensagem de confirma&ccedil;&atilde;o</h1>";	
	html = html + "<p>"+ mensagem +"</p>";
	html = html + "<p><a href='" + link + "' id='okConfirm'>Sim</a> <a href='#' id='noAlert'>N&atilde;o</a></p>";
	$.blockUI({ message: html, css:{ background: '#ffff99 url(http://www.e-value.com.br/_valuegaia/img/alert.jpg) no-repeat 10px center', 'padding-left':'35px',cursor: "auto"} });
	$("#okConfirm").click(function(){
		$.unblockUI();
		newWindow(link,param)
		return(false);
	});
	$("#noAlert").click(function(){$.unblockUI();return false;});
	return false;
}
/*function newWindow(page, param){
	var mydate = new Date();
	data_utc = Date.UTC(mydate.getYear(), mydate.getMonth(), mydate.getDate(), mydate.getHours(), mydate.getMinutes(), mydate.getSeconds(), mydate.getMilliseconds());	
	$.ajax({
		type: "GET",
		beforeSend: function(){
			jLoading();
		},
		error : function(){
			$.blockUI({message: "erro", css:{ cursor: "auto"}});
		},
		url: page,
		data: param + "&MS=" + (data_utc * -1),
		success: function(msg){
			$.unblockUI();
			$.historyLoad(page);
			$("#content").html(msg);
			setLinkinSamePage();
		}
	});

	
}*/
function setLinkinSamePage(){
		$("#content a").click(function(){
			
			if($(this).attr("class") == "lkExcluir"){
				jConfirmDelete("Deseja realmente excluir esse registro?",$(this));
			}else if($(this).attr("target") == "_blank"){
				return(true);
			}else if($(this).attr("class") == "window"){
				$(this).Window();
				//return(false);
			}else if($(this).attr("class").indexOf("colorbox") > -1){
				//return(false);
			}else if($(this).attr("rel") == "noaction"){
			    //return(false);
			}else{
				actualValue = $(this).attr("href");
				pos = actualValue.indexOf("#");
				carc = actualValue.substr(pos,1);
				if(carc != "#"){
					actualValue = actualValue.split("?");
					file = actualValue[0];
					parametrow = actualValue[1];
					newWindow(file, parametrow);
				}
			}
			$(".FotoSlide").slideshow();
			
			return false;
		});
		if ($.browser.msie){
			$("input[type=text], input[type=password],select, textarea").addClass("fields");
			$("input[type=text], input[type=password],select, textarea").focus(function(){
				$(this).addClass("fieldsFocus");
			});
			$("input[type=text], input[type=password],select, textarea").blur(function(){
				$(this).removeClass("fieldsFocus");																   
				$(this).addClass("fields");																   
			});
		}
		$("input:disabled").addClass("disabled");
		$("#Reset").click(function(){
			way = $("#form1").attr("action").replace("-acao","");
			newWindow(way,"");
		});
		
	$("input,textarea").keypress(function(e){
		if(capsLockCheck(e)){
			jAlert("Por favor, desabilite a tecla <strong>CAPS LOCK</strong> do seu teclado")
			return(false);	
		}
		if(e.which == 39){
			return(false);	
		}
	});		
}
function atualizaData(dataParam){

	data = dataParam.split("/");
	//var mesArr = Array("jan", "fev","mar","abr","mai","jun","jul","ago","set","out","nov","dez");
	var semana = data[0]	
	var ano = data[1];	
	var mes = data[2];
	var dia = data[3];
	var hora = data[4];
	var minuto = data[5];
	var segundos = data[6];
	
	var formatSem = semana.substr(-3,1);
	formatSem = formatSem.toUpperCase() + semana.substr(1,2); 
	strData = formatSem + ", " + dia + "/" + mes + "/" + ano + " - " + hora + ":" + showFilled(minuto) + ":" + showFilled(segundos);
	$("#relogio").html(strData);
	
	segundos = parseInt(segundos);
	minuto = parseInt(minuto);
	//hora = parseInt(hora);
	if(segundos < 59)	segundos = parseInt(segundos) + 1;
	else{
		segundos = 0;
		if(minuto < 59)	minuto = parseInt(minuto) + 1;
		else{
			minuto = 0;
			hora = parseInt(hora) + 1;
		}		
	}
	str = semana + "/" + ano + "/" + mes + "/" + dia + "/" + hora + "/" + minuto + "/" + segundos;
	intervalo2 = setTimeout("atualizaData('" + str + "')",1000);	
}
function showFilled(Value) {
	Value = parseInt(Value);
	return (Value > 9) ? "" + Value : "0" + Value;
}
function getData(){
	clearInterval(intervalo2);
	clearInterval(intervalo1);
	$.ajax({
		   url: "relogio.aspx",
		   data: "MS=" + data_utc,
		   success: function(hour){
			   atualizaData(hour);
		   }
	});
	intervalo1 = setInterval("getData()",100000);
}
function hideFieldSets(){
	for(i = 0; i < arguments.length;i++){
		$("fieldset > legend:eq("+arguments[i]+")").parent().find(" > div").hide();	
		$("fieldset > legend:eq("+arguments[i]+")").parent().toggleClass("legendoff");
		$("fieldset > legend:eq("+arguments[i]+")").click(function(){
			$(this).parent().toggleClass("legendoff");
			if($(this).parent().attr("class") != "legendoff"){
				$(this).parent().find(" > div").show();
			}else{
				$(this).parent().find(" > div").hide();
			}	
			
		});

	}
}
function cadastraNovo(){
	$("a[@title='Cadastrar_novo']").each(function(){
		rel = $(this).attr("rel").split(",");
		novos = new Array();
		antigo = $("#" + rel[rel.length - 1]);
	
		for(i = 0; i < rel.length - 1;i++){
			novos.push($("#" + rel[i]));
			$("#" + rel[i]).parent().hide();
		}
		$(this).click(function(){
			rel = $(this).attr("rel").split(",");
			novos = new Array();
			antigo = $("#" + rel[rel.length - 1]);
		
			for(i = 0; i < rel.length - 1;i++){
				novos.push($("#" + rel[i]));
				$("#" + rel[i]).parent().hide();
			}							   
			if($(this).attr("class") == "changeField"){
				antigo.attr("disabled","disabled");
				antigo.val("");
				for(i = 0; i < (rel.length - 1);i++){
					novos[i].parent().fadeIn();
				}
				$(this).find("img").attr("src","img/bg-subtrair.jpg")
			}else{
				antigo.removeAttr("disabled");
				for(i = 0; i < (rel.length - 1);i++){
					novos[i].val("");			
					novos[i].parent().hide();
					$(this).find("img").attr("src","img/bg-adicionar.jpg")
				}
				
			}
			$(this).toggleClass("changeFieldOFF");
			return false;
		});
	});
}

function dateDif(strData, nDias){
	//var dif = Date.UTC(data1.getYear(),data1.getMonth(),data1.getDate(),0,0,0) - dia;
	//return Math.abs((dif / 1000 / 60 / 60 / 24));
	strDs = strData.split("/");
	var dataAtual = new Date(strDs[2],(strDs[1] - 1),strDs[0]);
	//alert(dataAtual.getDay());
    var segDia = 86400000; //24 * 60 * 60 * 1000
    var a = dataAtual.getTime();
    var b = a + ((nDias - 1) * segDia);
    var c = new Date(b);
    return(showFilled(c.getDate()) + "/" + showFilled(c.getMonth() + 1) + "/" + showFilled(c.getFullYear()));
}
//alert(diferencaDias(data_ini, data_utc)));




// HISTORY


function newWindow(page, param){
	//fecha qualquer colorbox que estiver aberto
	//código
	var mydate = new Date();
	data_utc = Date.UTC(mydate.getYear(), mydate.getMonth(), mydate.getDate(), mydate.getHours(), mydate.getMinutes(), mydate.getSeconds(), mydate.getMilliseconds());		
	if(data_utc < 0){
		data_utc = data_utc	* (-1);
	}
	if(param) param = param + "?";
	else param = "";

	//if(pagina_atual.indexOf("imovel-novo") > 0 || pagina_atual.indexOf("imovel-alterar") > 0){
	//    if(confirm("Deseja realmente encerrar o cadastro sem salvar?")){
	//        if(validateBrowser()) $.historyLoad(page + "?MS=" + data_utc + "&" + param);
	//        else pageload(page + "?MS=" + data_utc + "&" + param);
	//    }else return(false);
	//}else{
	//page + (page.search("?") ? "" : "?" ) +
        if(validateBrowser()) $.historyLoad(page + "?MS=" + data_utc + "&" + param);
        else pageload(page + "?MS=" + data_utc + "&" + param);	
	//}
	
	
}

function pageload(hash){
	// hash doesn't contain the first # character.^
	var vHash = new Array();
	if(hash) {
		vHash = hash.split("?");
	}else{
		vHash[0] = "inicio.aspx";
		vHash[1] = "inicio.aspx";
	}
	pagina_atual = vHash[0];

	$.ajax({
		type: "GET",
		beforeSend: function(){
			jLoading();
		},
		error : function(){
			jConfirm("Sua conex&atilde;o com a internet est&aacute; inst&aacute;vel. <br />Tentar acessar novamente?",vHash[0],vHash[1]);
		},
		cache: false,
		url: vHash[0],
		data: vHash[1],
		success: function(msg){
			if(msg.indexOf("txLogin") < 0){
			    if(msg.indexOf("@[Alerta]:") >= 0){
			        jAlert(msg.substr(msg.indexOf("@[Alerta]:") + 10,msg.length));
			        return(false);
                }else{
				    $.unblockUI();
				    $("#content").html(msg);
				    //alert(msg);
				    setLinkinSamePage();	
				}
			}else{
				location.href="../login.aspx?idImobiliaria=" + $("#hdidImobiliaria").val();
			}
		}
	});
}

function validateBrowser(){
	if($.browser.msie){	
		if(parseInt($.browser.version) >= 7){
			return(true);
		}
	}else{
		return(true);
	}
	return(false);

}



// VALIDA SE O CAPS LOCK ESTÁ ATIVADO
function capsLockCheck(ev) {
	var e = ev || window.event;
	codigo_tecla = e.keyCode?e.keyCode:e.which;
	tecla_shift = e.shiftKey?e.shiftKey:((codigo_tecla == 16)?true:false);
	if(((codigo_tecla >= 65 && codigo_tecla <= 90) && !tecla_shift) || ((codigo_tecla >= 97 && codigo_tecla <= 122) && tecla_shift)) {
		return(true);
	}
	else {
		
		return(false);
	}
}

function aspasSimples(){
	var e = ev || window.event;
	codigo_tecla = e.keyCode?e.keyCode:e.which;
	tecla_shift = e.shiftKey?e.shiftKey:((codigo_tecla == 16)? true : false);
}

function serializeAll(val){
    text = "";
    tempChar = "";
    
    $(val + ' *').each(function(){
        if($(this).attr('name') != undefined){
        text += tempChar + $(this).attr('name') + '=' + $(this).val();
        tempChar = "&";
        }
    });
        
    return text;
}

function trim (str) {
	str = str.replace(/^\s+/, '');
	for (var i = str.length - 1; i >= 0; i--) {
		if (/\S/.test(str.charAt(i))) {
			str = str.substring(0, i + 1);
			break;
		}
	}
	return str;
}
