// MUDA ESTADO DA JANELA
function Mudaestado(campo){	
	if ($('#'+campo).css("display") == "none")
	{
		$('#'+campo).fadeIn("normal");
		//var box = new Array(0, 45, 3000, 3000);
		//$('#'+campo).Draggable({snapDistance:0, opacity: 0.9,handle: ".jan_handle", frameClass: "jan_ghost", zIndex: 	801, containment: box});

		parafrente(campo);
	}
	else
	{
		$('#'+campo).fadeOut("normal");
	}	
}

// CHAMA O ARQUIVO Q GERA O PDF COM A LISTAGEM PRA IMPRIMIR
function imprimir_lista(campo,arquivo){	

	var html = $.ajax({
						url: arquivo,
						success: function(msg)
						{
							MsgN('#'+campo,'Relatório criado comsucesso!','I',function(){ abre_janela(msg); } );
						},
						error: function(msg)
						{
							MsgN('#'+campo,msg,'E','');
						}
					  });
	
}

//ABRE JANELA POPUP PARA A EXIBIÇÃO DOS RELATORIOS
function abre_janela(arquivo)
{
	window.open(arquivo,"SAMEX","toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,left=20,top=20,width=700,height=500");
}

// ALTERA DE MINIMIZADO PARA MAXIMIZADO E VICE-VERSA
function MudaMax(img,campo){	
	if ($(img).attr("src") == "img/ic_minimizar.gif")
	{
		$(img).attr("src","img/ic_maximizar.gif");
		$('#'+campo).children(".jan_conteudo").css("display","none");
	}
	else
	{
		$(img).attr("src","img/ic_minimizar.gif");
		$('#'+campo).children(".jan_conteudo").css("display","");
	}
}


// COLOCA A JANELA PRA FRENTE
function parafrente(campo)
{ 
	var maximo = 0;
	$("div.jan_root").each( function(i){
									if ($(this).css("z-index") > maximo ){
											maximo = parseInt($(this).css("z-index"));
										}					
								  }
						)
	if (maximo > 700)
	{
		$("div.jan_root").each( function(i){
										if ($(this).css("z-index") > 300)
										{
											maximo = $(this).css("z-index",300);
										}
							  });
	}
	
	if ($('#'+campo).css("z-index") <= maximo)
	{
		$('#'+campo).css("z-index",maximo+1);
	}		
}
	

// FUNÇÃO PRINCIPAL DAS JANELAS
// CRIA A JANELA E COLOCA AS FUNÇÕES NESCESSÁRIAS
function Janela(campo,titulo,url,form,largura){	
	if ($("*").index( $('#'+campo)[0] ) != -1)
	{
		if ($('#'+campo).css("display") == "none")
		{
			Mudaestado(campo);
		}
	}
	else
	{
		$('#jn_base').clone().prependTo("#principal").attr("id", campo);
		if (largura != '' &&  largura != null)
		{
			$('#'+campo).css("width",largura);
		}
		janPos(campo);
		
		Mudaestado(campo);	
	
		// FECHAR MINIMIZAR E PARAFRENTE
		$('#'+campo).children(".jan_handle").children(".jan_system").children(".jan_fechar").mousedown( function(){	removerJN(campo); }	);
		$('#'+campo).children(".jan_handle").children(".jan_system").children(".jan_max").mousedown( function(){ MudaMax(this,campo); }	);
		$('#'+campo).mousedown( function(){ parafrente(this); } );

	}
	
	// MANDA PARA FRENTE
	$('#'+campo).click( function(){ parafrente(campo); } );

	if (titulo != '')
	{
	//COLOCA O TITULO
		$('#'+campo).children(".jan_handle").children(".jan_titulo").text(titulo);
	}
 	// VERIFICA SE FOI PASSAADO UM FORM
	if (form == '' ||  form == null)
	{
		// CHAMA AJAX
		$('#'+campo).children(".jan_conteudo").load(url,'',function(r){ AjaxCallback(r); } );	
	}
	else
	{
		// RECUPERA VALORES DO FORMA E CHAMA AJAX
		var get = dadosform(form);
		$('#'+campo).children(".jan_conteudo").load(url+get,'',function(r){ AjaxCallback(r); } );
	}
	
	$('#'+campo).children(".jan_handle").attr('id', campo+'_hd');

	//DRAG
	$('#'+campo).children(".jan_handle").mousedown(function(){ inidrag(''+campo+'',campo+'_hd'); });
	$('#'+campo).children(".jan_handle").mouseup(function(){ isHot=false; });

	// COLOCA O CARREGANDO NA JANELA PRINCIPAL
	carregando($('#'+campo).children(".jan_conteudo"));
	
	parafrente(campo);
}

// AJUSTA POSIÇÃO DA JANELA
function janPos(campo)
{
	var px = new Array();
	var py = new Array();
	var t = 0;
	var l = 0;
	var j;
	var verifica;
	var x,y;
	// RECEBE AS POSIÇÕES DAS JANELAS
	$(".jan_root").each(function(i){
							px[i] = parseInt($(this).css("left"));
							py[i] = parseInt($(this).css("top"));
						});
	for(t = 15; t < 200; t = t +15)
	{
		l = l +20;
		verifica = true;
		for (j = 0; j < px.length-1; j++) {
			if (l == px[j] || t == py[j] )
			{
				verifica = false;
			}
		}
	
		if (verifica == true)
		{
			$('#'+campo).css("left",l);
			$('#'+campo).css("top",t);
			return true;
		}
	}
	return false;
}

// REMOVE JANELA
function removerJN(jn){	
	$('#'+jn).remove();
}


// MSG /////////////////////// INICIO
// CRIA JANELA DE MSG, BASEDA NO MODELO #MSG
function MsgN(local,texto,tipo,fn){	

	Nmsg = Nmsg + 1;
	
	var nomejn = 'xmsg'+Nmsg+'ss';

	$('#msg').clone().prependTo(''+local+'').attr("id", ''+nomejn+'');
	
	if (tipo == 'E')
	{
		$('#'+nomejn).children('.msg_icone').css("background-image","url(img/ic_jan_erro.png)");
	}
	else
	{
		$('#'+nomejn).children('.msg_icone').css("background-image","url(img/ic_jan_msg.png)");
	}

	$('#'+nomejn).children('.msg_conteudo').html(texto);
	

	$('#'+nomejn).children('.msg_ok').click( function(){ removerJN(''+nomejn+''); } );

	if (fn)
	{
		$('div#'+nomejn).children('.msg_ok').click(fn);
	}
	
	$('div#'+nomejn).fadeIn("fast");
	
	$('#'+nomejn).children('.msg_ok').hover( 
											  function(){ $(this).css("opacity",0.6); },
											  function(){ $(this).css("opacity",1); }
											  ); 
}

// REMOVE JANELA MSG
function removerMsg(jn){	
	$('#'+jn).remove();
}
// MSG /////////////////////// FIM

// LOCALIZAR /////////////////////// INÍCIO
// CRIA E ABRE JANELA LOCALIZAR
function lc_abrir(local,url){	

	Nmsg = Nmsg + 1;
	
	var nomelc = 'loca'+Nmsg+''; // ID DA JANELA
	
	var jncon = nomelc+'cont'; // ID DO CONTEUDO
	
	$('#jn_localizar').clone().prependTo(''+local+'').attr("id", ''+nomelc+'');

	$('#'+nomelc).children(".lc_conteudo").attr("id", ''+jncon+'');
	
	$('#'+nomelc).children(".lc_conteudo").load(url+'&jnid='+nomelc+'&jncon='+jncon,'',function(r){ AjaxCallback(r); } );
	
	$('#'+nomelc).children(".lc_fechar").click( function(){ removerJN(''+nomelc+''); } );
	
	$('#'+nomelc).fadeIn("fast");

//	$('#'+nomelc).Draggable({snapDistance:5, opacity: 0.9, zIndex: 	801});
	
	parafrente(nomelc);
	
}
// FUNÇÃO USANBDO QUANDOS E CLICA EM UM REGITRO DENTRO DE UMA JANELA LOCALIZAR
function lc_escolhe(id,lcid,desc,lcdesc,lc_jan){	

	$('#'+lcid).val(''+id+'');
	$('#'+lcdesc).text(''+desc+'');
	
	$('#'+lc_jan).remove();
}
// LOCALIZAR /////////////////////// FIM

// DRAG /////////////////////// INÍCIO

var mroot,mhandle;
isIE=document.all;
isNN=!document.all&&document.getElementById;
isN4=document.layers;
isHot=false;

function ddInit(e){
  topDog=isIE ? "BODY" : "HTML";
  whichDog= document.getElementById(mroot);  
  hotDog=isIE ? event.srcElement : e.target;  
  while (hotDog.id!=mhandle&&hotDog.tagName!=topDog){
    hotDog=isIE ? hotDog.parentElement : hotDog.parentNode;
  }  
  if (hotDog.id==mhandle){
    offsetx=isIE ? event.clientX : e.clientX;
    offsety=isIE ? event.clientY : e.clientY;
    nowX=parseInt(whichDog.style.left);
    nowY=parseInt(whichDog.style.top);
    ddEnabled=true;
    document.onmousemove=dd;
  }
}

function dd(e){
  if (!ddEnabled) return;
//  var pleft = parseInt($("#principal").css("top"));
  var vleft = isIE ? nowX+event.clientX-offsetx : nowX+e.clientX-offsetx; 
  var vtop  = isIE ? nowY+event.clientY-offsety : nowY+e.clientY-offsety;

  if (parseInt(vleft) > 0)
  	whichDog.style.left=vleft;//isIE ? nowX+event.clientX-offsetx : nowX+e.clientX-offsetx; 
  if (parseInt(vtop) > 0)
	whichDog.style.top=vtop;//isIE ? nowY+event.clientY-offsety : nowY+e.clientY-offsety;
  
  
  return false;  
}


document.onmouseup=Function("ddEnabled=false");

function inidrag(root,handle)
{
	mroot=root;
	mhandle=handle;
	isHot=true;
	document.onmousedown=ddInit;
}
// DRAG /////////////////////// FIM
