$(document).ready(function(){
 bodyPositioning();
 posicionarConteudo();
});

function nothing(){
 
}

function bodyPositioning(){
 c = $('#content');
 d = $(document);
 
 if(c.height() < c.height(d.height() - 344))
  c.height(d.height() - 344);
 
 $('#pic-overlay').height($('body').height()).width($('body').width()).offset({top:0,left:0});
}

function posicionarConteudo(){
 var height   = getHeight();
 var width    = getWidth();  
 var browser  = LerCookie('ckbrowser'); 
 
 if(document.getElementById("div_infoloader"))
  document.getElementById("div_infoloader").style.left   = ((width - document.getElementById("div_infoloader").style.width.replace(/px/g,""))  / 2)+"px";
  
 $('#pic-overlay').height($('body').height()).width($('body').width()).offset({top:0,left:0});
}

function ntfPosition(){
 height = getHeight();
 width  = getWidth();
 margin = 30;
 
 //TOP
 $('.ntf') .css({ top:(height - 105)+'px' });
 $('.ntfr').css({ top:(height - 33)+'px' });
 
 //LEFT
 $('.ntf').each(function(){
  id = $(this).attr('id');
  
  if($(this).prev().attr('id')!=undefined){
   pleft  = $(this).prev().offset().left;
   pwidth = $(this).prev().width();
  }
  else{
   pleft  = 0;
   pwidth = 0
  }
  
  $(this).css({ left:(pleft + pwidth + margin)+'px' });
  $('#'+id+'reflex').css({ left:(pleft + pwidth + margin)+'px' });
 });
}

function login(){
 ajaxPost("form","verifier","includes/login.php","Verificando...");
}

function onlyNumbers(campo) {
 var digits="0123456789";
 var campo_temp;
 for (var i=0;i<campo.value.length;i++){
  campo_temp=campo.value.substring(i,i+1)    
  if (digits.indexOf(campo_temp)==-1){
   campo.value = campo.value.substring(0,i);
   break;
  }
 }
}

function criaXMLHttp() {
	if (typeof XMLHttpRequest != "undefined")
		return new XMLHttpRequest();
	else 
	 if (window.ActiveXObject) {
			var versoes = ["MSXML2.XMLHttp.5.0", "MSXML2.XMLHttp.4.0", "MSXML2.XMLHttp.3.0", "MSXML2.XMLHttp", "Microsoft.XMLHttp"];
		}

		for (var i = 0; i < versoes.length; i++) {
			try
			{
				return new ActiveXObject(versoes[i]);
			}	catch (e) {
			}
		}
		throw new Error();
}

function resizeOverlay(target,ready){
 //alert(target);
 
 /*if(ready==4 || ready==undefined)
  return false;*/
 
 if(document.getElementById(target)){
  t = $('#'+target).offset().top;
  w = $('#'+target).width();
  h = $('#'+target).height();
  
  $('#content-overlay').width(w).height(h).css({top:t});
  
  //$('#content-overlay img').css('margin',(Math.round(h / 2) - Math.round($('#content-overlay img').height() / 2))+'px 0 0 '+(Math.round(w / 2) - Math.round($('#content-overlay img').width() / 2))+'px');
  $('#content-overlay img').css('margin','50px 0 0 '+(Math.round(w / 2) - Math.round($('#content-overlay img').width() / 2))+'px');
  
  if(document.getElementById('content-overlay')){
   setTimeout(function(){
    resizeOverlay(target);
   },100);
  }
 }
 else
  return false;
}

function detachOverlay(){
 setTimeout(function(){
 	if(document.getElementById('content-overlay'))
 	 $('#content-overlay').fadeTo('slow',0.001,function(){ $('#content-overlay').detach(); });
	},500);
}

function ajaxGet(target,link,msg){
	var url        = link;
 var overlay    = false; 	
 var divContent = eval("document.getElementById('"+target+"')");
 
 divInfo = document.getElementById("div_infoloader");
 tdInfo  = document.getElementById("td_infoloader");
 
 var XMLHttp = criaXMLHttp();
 XMLHttp.open("get", url, true);
 
 if(msg!="" && msg!=undefined && msg!='undefined'){
  tdInfo.innerHTML      = msg;
  divInfo.style.display = "block";
 }
 
 //------------------------------------
 //CRIA UM OVERLAY SOBRE O OBJETO 
 //ONDE SERÁ CARREGADA A PÁGINA CHAMADA
 //------------------------------------
 if(!document.getElementById('content-overlay')){
  overlay = true;
  //alert(document.getElementById('content-overlay'));
  
  if(document.getElementById(target).style.display!='none'){
   $('#content').prepend('<div id="content-overlay" style="position:absolute; background-color:#FFF; z-index:99;"><img src="../images/loading_wheel.gif" style="display:none;" onload="this.style.display=\'block\'" /></div>');
   //$('#content-overlay').css('opacity','0.001');
   //alert(link);
   t = $('#'+target).offset().top;
   w = $('#'+target).width();
   h = $('#'+target).height();
   //alert(document.getElementById('content-overlay'));
   $('#content-overlay').width(w).height(h).css({top:t});
   resizeOverlay(target);
   //alert(document.getElementById('content-overlay'));
   //$('#content-overlay img').css('margin',(Math.round(h / 2) - Math.round($('#content-overlay img').height() / 2))+'px 0 0 '+(Math.round(w / 2) - Math.round($('#content-overlay img').width() / 2))+'px');
   //$('#content-overlay img').css('margin',(Math.round(h / 2) - Math.round($('#content-overlay img').height() / 2))+'px 0 0 '+(Math.round(w / 2) - Math.round($('#content-overlay img').width() / 2))+'px');
   //$('#content-overlay').fadeTo('slow',0.5);
  }
 }
 //------------------------------------

 XMLHttp.onreadystatechange = function () {
  //resizeOverlay(target,XMLHttp.readyState);
  
	if(XMLHttp.readyState == 4)
		if(XMLHttp.status == 200){
			exibeResult(target,XMLHttp.responseText);			
			setTimeout("divInfo.style.display='none'",1000);
			return true;
		} 
 	else 	{
 		tdInfo.innerHTML = "Não foi possível encontrar \""+link+"\".";
 		exibeResult(target,'none');
 		return false;
 	}
 	
 	/*setTimeout(function(){
  	if(document.getElementById('content-overlay') && overlay==true)
  	 $('#content-overlay').fadeTo('slow',0.001,function(){ $('#content-overlay').detach(); });
 	},1000);*/
 	
 };

 XMLHttp.setRequestHeader("Content-Type","text/html; charset=ISO-8859-1");  
 XMLHttp.send(null); 
}

function carregando(tipo) {
 switch(tipo){
  case "wheel1":
   var msg = "<img src='imagens/loading_wheel1.gif' width='12' height='12'>&nbsp;Carregando...";
  break; 
 }
 
 return msg;
}


function ajaxPost(form,div,pagina,msg){
	var sBody   = criaReqStr(document[form]);
	
 divInfo = document.getElementById("div_infoloader");
 tdInfo  = document.getElementById("td_infoloader");

	var oXMLHttp = criaXMLHttp();
	// 1o arg: usa o método post
	// 2o arg: envia a requisição post a página do formulário
	// 3o arg: usa o modo assincrono
	oXMLHttp.open("post", pagina, true);
	// importante.. a maioria das linguagens server-side verifica 
	// essa codificação para o parsing da informação
	oXMLHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
 
 if(msg!="")
  divInfo.style.display = "block";

	oXMLHttp.onreadystatechange = function (){
		// readyState == 4 quer dizer Completo e sem erros
		if(oXMLHttp.readyState == 4){
			exibeResult(div,oXMLHttp.responseText); // PASSO O NOME DA DIV, E A RESPOSTA DO PROCESSAMENTO DA PÁGINA
			setTimeout("divInfo.style.display='none'",200);
			//tdInfo.innerHTML = oXMLHttp.responseText;
		}
		else if(oXMLHttp.readyState == 2 || oXMLHttp.readyState == 1 || oXMLHttp.readyState == 0){
		 //exibeResult(div,carregando(loading));
		 if(msg!="")
		  tdInfo.innerHTML = msg;
		}
		else if(oXMLHttp.readyState == 5){
			//exibeResult(div,"Ocorreu um erro: " + oXMLHttp.statusText);
			//exibeResult(div,oXMLHttp.readyState);
			tdInfo.innerHTML = "Ocorreu um erro: " + oXMLHttp.statusText;
			tdInfo.innerHTML = oXMLHttp.readyState;
		}
	};
	// depois de ser setado todos os parametros
	// é enviado os valores usando o método post
	oXMLHttp.send(sBody);	
}

function criaReqStr(oForm){
	var aPostStr = new Array();

	for(var i = 0; i < oForm.elements.length; i++){
		var sValor = encodeURIComponent(oForm.elements[i].name);
		sValor += "=";
		sValor += encodeURIComponent(oForm.elements[i].value);
		aPostStr.push(sValor);
	}
	// retorna uma string no padrão "post request":
	// nome1=valor1&nome2=valor2&...&nomeN=valorN
	return aPostStr.join("&");
}  

function exibeResult(div,sTxt){
 if(div!=null){
 	var divStatus = document.getElementById(div);
 	divStatus.innerHTML = sTxt;
	}
}

function LerCookie(strCookie){
 var strNomeIgual = strCookie + "=";
 var arrCookies = document.cookie.split(';');

 for(var i = 0; i < arrCookies.length; i++){
  var strValorCookie = arrCookies[i];
  
  while(strValorCookie.charAt(0) == ' '){
   strValorCookie = strValorCookie.substring(1, strValorCookie.length);
  }
  if(strValorCookie.indexOf(strNomeIgual) == 0){
   return strValorCookie.substring(strNomeIgual.length, strValorCookie.length);
  }
 }
 return null;
}

function GerarCookie(strCookie, strValor, lngDias){
 var dtmData = new Date();

 if(lngDias){
  dtmData.setTime(dtmData.getTime() + (lngDias * 24 * 60 * 60 * 1000));
  var strExpires = "; expires=" + dtmData.toGMTString();
 }
 else{
  var strExpires = "";
 }
 document.cookie = strCookie + "=" + strValor + strExpires + "; path=/";
}

function ExcluirCookie(strCookie){
 GerarCookie(strCookie, '', -1);
}

function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}

function strrchr(haystack, needle) {
 var pos = 0;

 if (typeof needle !== 'string') {
  needle = String.fromCharCode(parseInt(needle, 10));
 }
 needle = needle.charAt(0);
 pos = haystack.lastIndexOf(needle);

 if (pos === -1) {
  return false;
 }

 return haystack.substr(pos);
}

function moveSidebars(id){
 div  = $('#'+id);
 divr = $('#'+id+'reflex');
 
 if(div.attr('position')=='L'){
  if(div.attr('status')=='O'){
   div .animate({marginLeft:(-div.width() + 9)+'px'},'slow');
   divr.animate({marginLeft:(-div.width() + 9)+'px'},'slow');
   div .attr('status','C')
   $('#imgsbl').attr('src','images/icons/sb_arrowl.png');
  }
  else if(div.attr('status')=='C'){
   div .animate({marginLeft:'0px'},'slow');
   divr.animate({marginLeft:'0px'},'slow');
   div .attr('status','O')
   $('#imgsbl').attr('src','images/icons/sb_arrowl2.png');
  }
 }
 else if(div.attr('position')=='R'){
  if(div.attr('status')=='O'){
   div .animate({marginLeft:(getWidth() - 11)+'px'},'slow');
   divr.animate({marginLeft:(getWidth() - 11)+'px'},'slow');
   div .attr('status','C')
   $('#imgsbr').attr('src','images/icons/sb_arrowr.png');
  }
  else if(div.attr('status')=='C'){
   div .animate({marginLeft:(getWidth() - div.width())+'px'},'slow');
   divr.animate({marginLeft:(getWidth() - div.width())+'px'},'slow');
   div .attr('status','O')
   $('#imgsbr').attr('src','images/icons/sb_arrowr2.png');
  }
 }
}

function buttonExecuting(button,type){
 btn = document.getElementById(button);
 
 if(type==1){
  document.cookie = "ck"+button+"_onmouseover="+btn.getAttribute("onmouseover").replace(/;/g,'<#>')+"; path=/;";
  document.cookie = "ck"+button+"_onmousedown="+btn.getAttribute("onmousedown").replace(/;/g,'<#>')+"; path=/;";
  document.cookie = "ck"+button+"_onmouseout=" +btn.getAttribute("onmouseout") .replace(/;/g,'<#>')+"; path=/;";
  document.cookie = "ck"+button+"_onclick="    +btn.getAttribute("onclick")    .replace(/;/g,'<#>')+"; path=/;";
  document.cookie = "ck"+button+"_class="      +btn.getAttribute("firstclass") .replace(/;/g,'<#>')+"; path=/;";
  
  btn.setAttribute("onmouseover","");
  btn.setAttribute("onmousedown","");
  btn.setAttribute("onmouseout" ,"");
  btn.setAttribute("onclick"    ,"");  
  
  btn.style.cursor = "default";
  
  switch(button){
   case "btn_salvar": txt = "Salvando"; break;
   default          : txt = "Aguarde";
  }
    
  btn.innerHTML = "<img src='imagens/loading_wheel2.gif' height='11' width='11' />&nbsp;"+txt;
 }
 else if(type==2){
  btn.innerHTML = btn.getAttribute("label");
  
  btn.setAttribute("onmouseover",LerCookie("ck"+button+"_onmouseover").replace(/<#>/g,';'));
  btn.setAttribute("onmousedown",LerCookie("ck"+button+"_onmousedown").replace(/<#>/g,';'));
  btn.setAttribute("onmouseout" ,LerCookie("ck"+button+"_onmouseout") .replace(/<#>/g,';'));
  btn.setAttribute("onclick"    ,LerCookie("ck"+button+"_onclick")    .replace(/<#>/g,';'));
  btn.className = LerCookie("ck"+button+"_class");
  
  btn.style.cursor = "pointer";
  
  ExcluirCookie("ck"+button+"_onmouseover");
  ExcluirCookie("ck"+button+"_onmousedown");
  ExcluirCookie("ck"+button+"_onmouseout");
  ExcluirCookie("ck"+button+"_onclick");
  ExcluirCookie("ck"+button+"_class");
 }
}

function buttonOnclick(id,func,arrValues){
 str = func+"(";
 
 for(i=0;i<arrValues.length;i++){
  if(i==0)
   str += "'"+arrValues+"'";
  else
   str += ",'"+arrValues+"'";
 }
 
 str += ")";
 str = "document.getElementById('"+id+"').setAttribute('onclick',\""+str+"\")";
 alert(str);
 eval(str);
}

function getWidth(){
 // Thiago Marotta Couto
 // thiago@isbyte.com
 // http://isbyte.com/
 // December, 06 - 2008
 return window.innerWidth        ? window.innerWidth                    : /* For non-IE */
        document.documentElement ? document.documentElement.clientWidth : /* IE 6+ (Standards Compilant Mode) */
        document.body            ? document.body.clientWidth            : /* IE 4 Compatible */
        window.screen.width;                                              /* Others (It is not browser window size, but screen size) */
}

function getHeight(){
 // Thiago Marotta Co
 // thiago@isbyte.com
 // http://isbyte.com/
 // December, 06 - 2008
 return window.innerHeight       ? window.innerHeight                    : /* For non-IE */
        document.documentElement ? document.documentElement.clientHeight : /* IE 6+ (Standards Compilant Mode) */
        document.body            ? document.body.clientHeight            : /* IE 4 Compatible */
        window.screen.height;                                              /* Others (It is not browser window size, but screen size) */
}

function mysqlError(host){
 if(host=='localhost'){
  content  = "<b>QUERY :</b> "+$('#mysql-query').val().replace(/<APOSTROFO>/g,"'")+"<br /><br />";
  content += "<b>ERROR :</b> "+$('#mysql-error').val().replace(/<APOSTROFO>/g,"'");
 }
 else
  content  = $('#mysql-error').val().replace(/<APOSTROFO>/g,"'");
 
 setTimeout(function(){
  dialog('Erro ao salvar os dados',content,'alert');
 },500);
}

function updateTips(text,type,icon){
 var tips = $(".validateTips")
 
 if(type=="" && type==null && type=="undefined"){
  type = "highlight";
 }
  
 if(icon!="" && icon!=null && icon!="undefined")
  ico = "<span class='ui-icon ui-icon-"+icon+"' style='float:left'></span>&nbsp;";
 else
  ico = "";
  
 tips.html(ico+text);  
	tips.addClass('ui-state-'+type);
	setTimeout(function() {
		tips.removeClass('ui-state-'+type, 1500);
	}, 500);
}

function dialog(title,msg,icon,o){
 var content = "";
 
 if(icon!="" && icon!="undefined" && icon!=null)
  ico = "<span class='ui-icon ui-icon-"+icon+"' style='float:left; margin:0 7px 0 0;'></span>";
 else
  ico = "";
 
 content += "<div id='dialog-message' title=\""+ico+title+"\">";
 content += "	<p>";  
 content += msg;
 content += "	</p>";
 content += "</div>";
 
 $("#dialog-message").dialog("destroy");
 $("body").prepend(content); 
 
	$("#dialog-message").dialog({
	 width: 450,
		modal: true,
		buttons: {
			Ok: function() {
				$(this).dialog('close');
				$(this).dialog('destroy');
				$("#dialog-message").detach();
				o.focus();
			}
		}
	});
}

function checkLength(o,label,min,max,type){
	if((max!=null && o.val().length > max ) || o.val().length < min){
		o.addClass('ui-state-error');
		
		if(max==null)
		 msg = "O campo '"+label+"' deve ter no mínimo "+min+" caracteres."
		else
		 msg = "O campo '"+label+"' deve ter entre "+min+" e "+max+" caracteres."
		
  /* 		
		if(type=="tip")
		 updateTips("Erro de validação",msg,"error");
		else
		 dialog("Erro de validação",msg,"alert",o);
		*/
		alert(msg);
  o.focus(); 
		return false;
	}
 else{
		return true;
	}
}

function checkCombobox(o,label,not,alert){
 //$('#div_conteudo').prepend(o.val()+" - "+not);
 
 if(o.val()==not){
		o.addClass('ui-state-error');
		
		msg = "Selecione uma opção para o campo '"+label+"'.";
		/*
		if(dialog=="tip")
		 updateTips("Erro de validação",msg,"error");
		else
		 dialog("Erro de validação",msg,"alert",o);
		*/
  
  alert(msg);
  o.focus(); 
		return false;
	}
 else{
		return true;
	}
}

function checkRegexp(o,regexp,msg,type){
	if(!(regexp.test(o.val()))){
		o.addClass('ui-state-error');
		
		/*
		if(type=="tip")
		 updateTips("Erro de validação",msg,"error");
		else
		 dialog("Erro de validação",msg,"alert");
		*/
		
		alert(msg);
  o.focus(); 
		return false;
	}
 else{
		return true;
	}
}

function testPassword(field){
 field.value = field.value.replace(/[!,@,#,$,%,^,&,*,?,_,~,´,`, ,;,\,,\/,\\,\[,\],\{,\},+,§,¬,&,¨,¢,£,¹,²,³,\(,\),º,ª,|,<,>,:,\',\"]/g,'');
}

function lockFields(){
 input    = document.getElementsByTagName('input');
 textarea = document.getElementsByTagName('textarea');
 select   = document.getElementsByTagName('select');
 button   = document.getElementsByTagName('button');
	trs      = document.getElementsByTagName('tr');
	imgs     = document.getElementsByTagName('img');
	
	//INPUTS
 for(i=0;i<input.length;i++){
 	var cpo  = input[i]; 
  
		//cpo.value = "";
	 cpo.selected = "false";
	 cpo.checked  = "false";
		 
		cpo.disabled = "true";  
 }
 
 //TEXTAREA
 for(i=0;i<textarea.length;i++){
 	textarea[i].disabled='true';
  //textarea[i].value='';
 }
 
 //SELECT
 for(i=0;i<select.length;i++){
 	//select[i].options[0].selected = true;
  select[i].disabled='true';
 }
 
 //BUTTONS
 var i=0;
 for(i=0;i<button.length;i++){
  button[i].disabled='true';
 }
 
 //TD'S
	/*for (var i=0; i<trs.length; i++){
  var tr      = trs[i];
  var onclick = tr.getAttribute('onclick');
  tr.onclick  = "";
  
  var style   = tr.getAttribute('style');
  tr.style.cursor = "default";
	}*/
	
	//IMAGENS
	for (var i=0; i<imgs.length; i++){		
  var img = imgs[i];
  var src = img.getAttribute('src');
  var vlr = img.src.split("/");
  
  //alert(src);
  
  for(k=0;k<vlr.length;k++){
	  if(vlr[k]=="-.gif" || vlr[k]=="+.gif" || vlr[k]=="go.gif" || vlr[k]=="up.gif" || vlr[k]=="xis.gif" || vlr[k]=="btn_tmkt_consultapreco.gif"){
	  	//alert(vlr[k]);	  	
	  	
		  var onclick = img.getAttribute('onclick');
		  img.onclick = "";
		  
		  var style = img.getAttribute('style');
		  img.style.cursor = "default";
	  }
  }
	}
}

function showWorksByStatus(){
 sts = $('#status').val(); 
 
 if(sts!=''){
  $('#sortable3 li, #sortable4 li').each(function(){
   if($(this).attr('status')==sts)
    $(this).show();
   else
    $(this).hide();
  });
 }
 else{
  $('#sortable3 li, #sortable4 li').show();
 }
}

function updateUnreadInfo(refer,val){
 if(!document.getElementById('div-'+refer+'-qtd'))
  return false;

 v = parseFloat($('#div-'+refer+'-qtd').text());

 if(val<0)
  v = val + v;
 else
  v = val;

 if(v==0)
  $('#div-'+refer+'-qtd').detach();
 else
  $('#div-'+refer+'-qtd').text(v);
}

function btnSPV(refer){
 dsp   = $('#'+refer+'-list').css('display');
 //icons = Array('ui-icon-circle-triangle-n','ui-icon-circle-triangle-s');
 icons = Array('ui-icon-triangle-2-n-s','ui-icon-triangle-2-n-s');
 
 if(dsp=='none')
  icon = icons[1];
 else
  icon = icons[0]; 
 
 $('#'+refer+'-content').prepend('<div id="btn-spv" class="ui-state-default ui-corner-all btn-spv" onclick="slidePanelV(\''+refer+'\');"><span id="span-spv" class="ui-icon '+icon+'"></span></div>');
 $('#btn-spv').css({'margin':'-10px 0 0 '+Math.round(($('#section-content').width() / 2) - 8)+'px'});  
}

function slidePanelV(refer){
 dsp   = $('#'+refer+'-list').css('display');
 //icons = Array('ui-icon-circle-triangle-n','ui-icon-circle-triangle-s');
 icons = Array('ui-icon-triangle-2-n-s','ui-icon-triangle-2-n-s');
 
 if(dsp=='none'){
  icon = icons[1];
  h1   = $('#'+refer+'-content').height() - $('#'+refer+'-list').height();
  h2   = $('#'+refer+'-message').height() - $('#'+refer+'-list').height();
  
  $('#'+refer+'-list')   .slideDown('fast');  
  $('#'+refer+'-list')   .css({'overflow-x':'hidden','overflow-y':'auto'});
  $('#'+refer+'-content').css({'border-top':'solid 1px #BBB'});
  $('#'+refer+'-content').animate({ height: h1+'px'},'fast', function(){
   $('#span-spv').removeClass(icons[1]).addClass(icons[0]);
  });  
 }
 else{
  icon = icons[0];
  h1   = $('#'+refer+'-content').height() + $('#'+refer+'-list').height();
  h2   = $('#'+refer+'-message').height() + $('#'+refer+'-list').height();
  
  $('#'+refer+'-list')   .slideUp('fast');  
  $('#'+refer+'-content').animate({ height: h1+'px'},'fast', function(){
   $('#span-spv').removeClass(icons[0]).addClass(icons[1]);
   $('#'+refer+'-content').css({'border-top':'none'});
  });  
 }
 
 $('#'+refer+'-message').animate({ height: h2+'px'},'fast',function(){
  $('#'+refer+'-message').css({'overflow-x':'hidden','overflow-y':'auto'});
 }); 
}

function checkList(refer){
 if(document.getElementById(refer+'-checkall').checked==true){
  $('.'+refer+'-checkbox').each(function(){
   id = $(this).attr('id');
   document.getElementById(id).checked = true;
  });
 }
 else{
  $('.'+refer+'-checkbox').each(function(){
   id = $(this).attr('id');
   document.getElementById(id).checked = false;
  });
 }
}

function addTrInvst(id,id_invst,name_invst,info_permission){
 tdattr = " align='left' valign='middle' style='padding:2px 5px 2px 5px; border-bottom:solid 1px #E8E9EA;' ";
 
 tr  = "\n<tr id='tr-pwk-"+id_invst+"' onmouseover=\"this.style.backgroundColor='#FBFBFB'\" onmouseout=\"this.style.backgroundColor='#FFF'\" style='background-color:#FFF; cursor:default;'>";
 tr += "\n <td "+tdattr+"><input type='checkbox' id='invst-"+id_invst+"' value='"+id_invst+"' class='invst-checkbox' /></td>";
 tr += "\n <td "+tdattr+">"+name_invst+"</td>";
 tr += "\n <td "+tdattr+">"+info_permission+"</td>";
 tr += "\n <td "+tdattr+">";
 tr += "    <div class='ui-state-default ui-corner-all' onclick=\"ajaxGet('update','../includes/dbmanager.php?action=D&refer=permissionswrk&id="+id+"&selecteds="+id_invst+"','Removendo permissão...')\" style='width:16px; float:left;' alt='Remover' title='Remover'>";
 tr += "     <span class='ui-icon ui-icon-minus' style='cursor:pointer;'></span>";
 tr += "    </div>";
 tr += "\n </td>"
 tr += "\n</tr>";
 
 $('#tbody-pwk').append(tr);
}

function addTrSales(id){
 tdattr = " valign='middle' style='padding:2px 5px 2px 5px; border-bottom:solid 1px #E8E9EA;' ";
 
 if(document.form.box.value=='1')
  box = 'Sim';
 else
  box = 'Não';
 
 tr  = "\n<tr id='tr-sls-"+id+"' onmouseover=\"this.style.backgroundColor='#FBFBFB'\" onmouseout=\"this.style.backgroundColor='#FFF'\" style='background-color:#FFF; cursor:default;'>";
 tr += "\n <td align='left'  "+tdattr+"><input type='checkbox' id='sls-"+id+"' value='"+id+"' class='sls-checkbox' /></td>";
 tr += "\n <td align='left'  "+tdattr+">"+document.form.unit.value+"</td>";
 tr += "\n <td align='right' "+tdattr+">"+document.form.ps.value+"</td>";
 tr += "\n <td align='left'  "+tdattr+">"+document.form.area.value+"</td>";
 tr += "\n <td align='left'  "+tdattr+">"+box+"</td>";
 tr += "\n <td align='right' "+tdattr+">R$ "+document.form.value.value+"</td>";
 tr += "\n <td align='left'  "+tdattr+">";
 tr += "    <div class='ui-state-default ui-corner-all' onclick=\"ajaxGet('update','../includes/dbmanager.php?action=D&refer=sales&selecteds="+id+"','Removendo registro...')\" style='width:16px; float:left;' alt='Remover' title='Remover'>";
 tr += "     <span class='ui-icon ui-icon-minus' style='cursor:pointer;'></span>";
 tr += "    </div>";
 tr += "\n </td>"
 tr += "\n</tr>";
 
 $('#tbody-sls').append(tr);
 
 document.form.unit .value = '';
 document.form.ps   .value = '';
 document.form.area .value = ''; 
 document.form.value.value = '';
 
 document.form.box.options[0].selected = true;
}

function removeSelectedInvst(id){
 invst = '';
 
 $('.invst-checkbox').each(function(){
  idd = $(this).attr('id');
  
  if(document.getElementById(idd).checked==true)
   invst += ','+$(this).val();
 });
 
 if(invst=='')
  return false;
 else{
  ajaxGet('update','../includes/dbmanager.php?action=D&refer=permissionswrk&id='+id+'&invst='+invst.substr(1),'Removendo permissão...');
 }
}

function removeSelectedList(id,refer){
 selecteds = '';
 
 $('.'+refer+'-checkbox').each(function(){
  idd = $(this).attr('id');
  
  if(document.getElementById(idd).checked==true)
   selecteds += ','+$(this).val();
 });
 
 if(selecteds=='')
  return false;
 else{
  if(refer=='invst'){
   reference = 'permissionswrk';
   param     = '&selecteds='+selecteds.substr(1);
   message   = 'Removendo permissão...';
  }
  else if(refer=='sls'){
   reference = 'sales';
   param     = '&selecteds='+selecteds.substr(1);
   message   = 'Removendo registros...';
  }
  else if(refer=='cnd'){
   reference = 'condominium';
   param     = '&selecteds='+selecteds.substr(1);
   message   = 'Removendo registros...';
  } 
  
  ajaxGet('update','../includes/dbmanager.php?action=D&refer='+reference+'&id='+id+param,message);
 }
}

function showCondominiumContact(id){
 tr = $('#tr-cnd-'+id+'-content');
 td = $('#td-cnd-'+id+'-content');
 
 if(tr.css('display')=='none'){
  tr.css('display','table-row');
  
  ajaxGet('td-cnd-'+id+'-content','condominium.php?type=form&fkni_key_wrk='+document.form.pkni_key_wrk.value+'&pkni_key_cnd='+id,'Carregando...');
 }
 else{
  tr.css('display','none');
 } 
}

function mainAnimation(works,oworks){
 if($('#dtq-loading').css('display')!='none')
  $('#dtq-loading').fadeOut('fast');
 
 if(oworks==undefined)
  oworks = works;
 
 if(works.length==0 || works=='')
  works = oworks;
 
 $('#dtq-full').css({'display':'none'});
 
 $('#dtq-full').attr('src','images/destaque/'+works[0][0]+'_full.jpg')
 $('#dtq-full').click(function(){
   window.location = works[0][1];
  });
 
 imt = 324 - $('#dtq-full').height();
 
 if(works[0][2].length>25){
  tmt   = '190px';
  tbgmt = '195px';
  th    = 130;
  tbgh  = 125;
 }
 else{
  tmt   = '250px';
  tbgmt = '255px';
  th    = 70;
  tbgh  = 65;
 }
 
 $('#div-title')   .height(th)  .css({marginTop:tmt});
 $('#div-title-bg').height(tbgh).css({marginTop:tbgmt});
 
 $('#dtq-full').css({'margin-top':imt});
 $('#title')   .html(works[0][2]).css({'margin-left':'800px'});
 $('#title-bg').html(works[0][2]).css({'margin-left':'662px',opacity:0.4});
 
 $('#dtq-full').fadeIn('slow');
 $('#title')   .fadeIn('slow');
 $('#title-bg').fadeIn('slow',function(){
  
  $('#dtq-full').css({'margin-top':imt});
  
  $('#dtq-link').click(function(){
   window.location = works[0][1];
  });
  
  $('#dtq-full').animate({
   marginTop:'0px'
  },20000);
   
  //INICIA O title-donato
  $('#title').animate({
   marginLeft:'20px'
  },12000);
  
  //INICIA O title-donato-bg
  $('#title-bg').animate({
   marginLeft:'50px'
  },12000);
  
  newworks = new Array();
  
  if(works.length==1){
   newworks = '';
  }
  else{
   for(i=1;i<works.length;i++)
    newworks[i-1] = works[i];
  }
  
  setTimeout(function(){
   $('#dtq-full').fadeOut('slow');
   $('#title')   .fadeOut('slow');
   $('#title-bg').fadeOut('slow',function(){
    mainAnimation(newworks,oworks);
   }); 
  },20000)
 
 });
}


$(document).ready(function(){
 works = new Array(Array('donato','obras.php?id=6','Centro Empresarial<br />Donato Werneck'),Array('splendore','obras.php?id=7','Residencial Splendore'));
 
 for(i=0;i<works.length;i++){  
  $('#dtq-content').prepend("<img src='images/destaque/"+works[i][0]+"_full.jpg' style='display:none' />");
 }
 
 setTimeout(function(){
  mainAnimation(works);
 },2000);
});



function carousel(imgs,sizes){
  div  = '';
  div += '<div id="carousel-div" class="carousel-div">';
  div += '<table border="0" cellspacing="0" cellpadding="0" width="'+(951 * imgs.length)+'"><tr>';
  
  for(i=0;i<imgs.length;i++){
   r = i+1;
   
   div += '<td align="center" valign="bottom" class="carousel-td">';
   div += '<div class="ui-corner-all" style="border:solid 1px #999; width:'+(sizes[i])+'px; padding:10px; background:#FFF;">';
   div += '<img id="carousel-img-'+r+'" src="images/certificacoes/'+imgs[i]+'.jpg" class="carousel-img" style="border:solid 1px #CCC" />';
   div += '</div>';   
   div += '</td>';
  }
  
  div += '</tr>';
  div += '<tr>';
  
  for(i=0;i<imgs.length;i++){
   r = i+1;
   
   div += '<td align="center" valign="top" class="carousel-td">';
   div += '<div class="ui-corner-top" style="height:15px; width:'+(sizes[i]+20)+'px; background-color:#FFF; border:solid 1px #999;"></div>';
   div += '</td>';
  }
  
  div += '</tr></table>';
  div += '</div>';
  
  div += '<div style="height:17px; top:690px; width:950px; position:absolute; background-image:url(images/template/ntf_overlayreflex.png);"></div>';
  
  $('#carousel-content').prepend(div);  
  $('#content').prepend('<div id="carousel-div-back" style="display:none;"><img onclick="carouselNavigation(\'back\')" src="images/certificacoes/back.png" style="cursor:pointer" /></div>');
  $('#content').prepend('<div id="carousel-div-next"><img onclick="carouselNavigation(\'next\')" src="images/certificacoes/next.png" style="cursor:pointer" /></div>');
  
  $('#carousel-div-1').css({'display':'block','margin-left':'225px'});
  
  $('#carousel-content').attr({'sel':'0','total':imgs.length});
  
  $('code').html('total: '+imgs.length+'<br />sel: '+0+'<br />r: <br />margin: '+0);
 }
 
function carouselNavigation(dir){
 total = parseFloat($('#carousel-content').attr('total'));
 sel   = parseFloat($('#carousel-content').attr('sel'));
 
 if(dir=='next'){
  r = sel + 1;
  c = -1;
 }
 else{
  r = sel - 1;
  c = 1;
 }
 
 margin = 951 * r * -1;
 
 $('#carousel-div').animate({
  'margin-left':margin+'px'
 },1000);
  
 $('#carousel-content').attr('sel',r);
   
 if(r>=1 && r<(total-1)){
  $('#carousel-div-back').show('fast');
  $('#carousel-div-next').show('fast');
 }
 else if(r==0){
  $('#carousel-div-back').hide('fast');
  $('#carousel-div-next').show('fast');
 }
 else if(r==(total-1)){
  $('#carousel-div-back').show('fast');
  $('#carousel-div-next').hide('fast');
 }
 
 $('code').html('total: '+total+'<br />sel: '+sel+'<br />r: '+r+'<br />margin: '+margin);
}

