// --------------------------------------------------------
//  FUNÇÕES-BASE DE SCRIPT DO LADO DO CLIENTE (JavaScript)
// --------------------------------------------------------
//  f1) Carregar Página
//  f2) Definir o foco de um controle no form
//  f3) Abrir nova janela 
//  f4) Validar Data
//  f5) Limpar todos os controles de um form html
//  f6) Impressão de documentos html
//  f7) Analisador de informações de parâmetros da url
//  f8) Redimensionar e Centralizar a Janela 
//  f9) Maximizar a Janela 
// --------------------------------------------------------

//f1) Carregar Página
function loadPage(frameTarget, pageName) {
  parent(frameTarget).location.href=pageName;
}

//f2) Definir o foco de um controle no form
function setfocus (form, NumCtr) {
  form(NumCtr).focus();
  return;
}

//f3) Abrir nova janela 
function WinOpen (pageName, targetName, toolbar, directories, menubar, resizable, left, top, width, height) {

	// Passe left=0 e top=0 para centrar a janela na tela
	if ((left == 0) && (top == 0)) {
		left = (window.screen.width - width) /2 ; 
		top = (window.screen.height - height) /2 ;
	}

	if (targetName="") targetName = "DisplayWindow";

	msg=open(pageName, targetName,
	         "toolbar=" + toolbar + ",directories=" + directories + ",menubar=" + menubar + 
             ",resizable=" + resizable + ",left=" + left + ",top=" + top + ",width=" + width +
             ",height=" + height + ",true");
}

//f3.1
function windowOpen (pageName, windowName, width, height) {
	var pLeft = (window.screen.availWidth - width) /2 ; 
	var pTop = (window.screen.availHeight - height) /2 ;
	
	pFeatures = 'width=' + width + 'px,'; 
	pFeatures += 'height=' + height + 'px,'; 
	pFeatures += 'top=' + pTop + 'px,'; 
	pFeatures += 'left=' + pLeft + 'px,';
	pFeatures += 'toolbar=no,'; 
	pFeatures += 'directories=no,'; 
	pFeatures += 'menubar=no,'; 
	pFeatures += 'resizable=no,'; 
	pFeatures += 'scrollbars=yes,';
	pFeatures += 'status=yes'; 
	
	myRef = window.open(pageName, windowName, pFeatures);
	myRef.focus();
}


//f4) Validar Data
function check_date (field) {
var checkstr = "0123456789";
var DateField = field;
var Datevalue = "";
var DateTemp = "";
var seperator = "/";
var day;
var month;
var year;
var leap = 0;
var err = 0;
var i;
  
  err = 0;
  DateValue = DateField.value;
  
  // retira espaços à esquerda.
  while ('' + DateValue.charAt(0) == ' ') 
    DateValue = DateValue.substring (1, DateValue.length);  
  
  // retira espaços à direita.
  while ('' + DateValue.charAt(DateValue.length-1) ==' ') 
    DateValue = DateValue.substring(0, DateValue.length-1);
  
  // verifica se o campo tem algum caractere
  if (DateValue.length == 0) {
    DateField.value = ''; 
    return err; 
  }

  // Apaga todos os caracteres, exceto 0..9 
  for (i = 0; i < DateValue.length; i++) {
    if (checkstr.indexOf(DateValue.substr(i,1)) >= 0) {
      DateTemp = DateTemp + DateValue.substr(i,1);
    }
  }
  DateValue = DateTemp;

  // Sempre modifica a data para 8 dígitos - string
  // Se o ano foi entrado com 2-dígitos / assume sempre 20xx 
  if (DateValue.length == 6) {
    DateValue = DateValue.substr(0,4) + '20' + DateValue.substr(4,2);
  }
  if (DateValue.length != 8) {
    err = 19;
  }

  // ano está errado se ano = 0000 
  year = DateValue.substr(4,4);
  if (year == 0) {
    err = 20;
  }

  // Validação do mês 
  month = DateValue.substr(2,2);
  if ((month < 1) || (month > 12)) {
    err = 21;
  }

  // Validação do dia 
  day = DateValue.substr(0,2);
  if (day < 1) {
    err = 22;
  }
  
  // Validação ano-bisexto/ fevereiro/ dia 
  if ((year % 4 == 0) || (year % 100 == 0) || (year % 400 == 0)) {
    leap = 1;
  }
  if ((month == 2) && (leap == 1) && (day > 29)) {
    err = 23;
  }
  if ((month == 2) && (leap != 1) && (day > 28)) {
    err = 24;
  }
  
  // Validação dos outros meses 
  if ((day > 31) && ((month == "01") || (month == "03") || (month == "05") || (month == "07") || (month == "08") || (month == "10") || (month == "12"))) {
    err = 25;
  }
  if ((day > 30) && ((month == "04") || (month == "06") || (month == "09") || (month == "11"))) {
    err = 26;
  }

  // se 00 é entrado, apaga a entrada 
  if ((day == 0) && (month == 0) && (year == 00)) {
    err = 27; day = ""; month = ""; year = ""; seperator = "";
  }
  
  // se nenhum erro, então escreve a data completa na caixa de texto (ou seja 13/12/2001)
  if (err == 0) {
    DateField.value = day + seperator + month + seperator + year;
  }
  
  // Mensagem de Erro se err != 0 
  else {
    alert("Data incorreta!");
    DateField.select();
    DateField.focus();
  }

  // Devolve o número do erro.
  return err;
}


//f5) Limpar todos os controles de um form html
function LimpaForm(FormName) {

  for (i=0; i < FormName.length; i++) {
    var tempobj = FormName.elements[i]
    
    // limpa as caixas de texto. 
    if (tempobj.type == "text") 
      tempobj.value = "";
      
    if (tempobj.type.toString().charAt(0)=="s") {

      //limpa as listbox.
      if (tempobj.size > 1) {
        var len = tempobj.options.length; 
        for(var j = (len-1); j >= 0; j--) 
          tempobj.options[j] = null;
      } 
      // seta a combobox no 1º elemento.
      else 
        tempobj.selectedIndex = 0;
    }
  }
}

//f6) Impressão de documentos html
var da = (document.all) ? 1 : 0;
var pr = (window.print) ? 1 : 0;
var mac = (navigator.userAgent.indexOf("Mac") != -1); 

function printPage()
{
  if (pr)              // NS4, IE5
    window.print()
  else if (da && !mac) // IE4 (Windows)
    vbPrintPage()
  else                 // other browsers
    alert("Desculpe seu browser não suporta esta função. Por favor utilize a barra de trabalho para imprimir a página.");
  return false;
}

if (da && !pr && !mac) with (document) {
  writeln('<OBJECT ID="WB" WIDTH="0" HEIGHT="0" CLASSID="clsid:8856F961-340A-11D0-A96B-00C04FD705A2"></OBJECT>');
  writeln('<' + 'SCRIPT LANGUAGE="VBScript">');
  writeln('Sub window_onunload');
  writeln('  On Error Resume Next');
  writeln('  Set WB = nothing');
  writeln('End Sub');
  writeln('Sub vbPrintPage');
  writeln('  OLECMDID_PRINT = 6');
  writeln('  OLECMDEXECOPT_DONTPROMPTUSER = 2');
  writeln('  OLECMDEXECOPT_PROMPTUSER = 1');
  writeln('  On Error Resume Next');
  writeln('  WB.ExecWB OLECMDID_PRINT, OLECMDEXECOPT_DONTPROMPTUSER');
  writeln('End Sub');
  writeln('<' + '/SCRIPT>');
}

//f7) Analisador de informações de parâmetros da url 
function QueryString(key) 
{ 
	var value = null; 
	for (var i=0;i<QueryString.keys.length;i++) 
	{ 
		if (QueryString.keys[i]==key) 
		{ 
			value = QueryString.values[i]; 
			break; 
		} 
	} 
	return value; 
} 

QueryString.keys = new Array(); 
QueryString.values = new Array(); 

function QueryString_Parse() 
{ 
	var query = window.location.search.substring(1); 
	var pairs = query.split("&"); 

	for (var i=0;i<pairs.length;i++) 
	{ 
		var pos = pairs[i].indexOf('='); 
		if (pos >= 0) 
		{ 
			var argname = pairs[i].substring(0,pos); 
			var value = pairs[i].substring(pos+1); 
			QueryString.keys[QueryString.keys.length] = argname; 
			QueryString.values[QueryString.values.length] = value; 
		} 
	} 
} 
QueryString_Parse(); 

//f8) Redimensionar e Centralizar a Janela 
function resizeCenterWin (w, h) {

	x = (window.screen.width - w) / 2 ; 
	y = (window.screen.height - h) / 2 ;
	window.resizeTo(w, h);
	window.moveTo(x, y);
}

//f9) Maximizar Janela
function winMaximize() {
	window.moveTo(0,0);
	window.resizeTo(screen.availWidth, screen.availHeight); 
}

//f10) Abertura janela modal
function WinModalOpen(pURL, pArgIn, pWidth, pHeight){

	var pLeft = (window.screen.availWidth - pWidth) /2 ; 
	var pTop = (window.screen.availHeight - pHeight) /2 ;
	
	pFeatures = 'dialogWidth:' + pWidth + 'px;'; 
	pFeatures += 'dialogHeight:' + pHeight + 'px;';
	pFeatures += 'dialogLeft:' + pLeft + 'px;';
	pFeatures += 'dialogTop:' + pTop + 'px;'; 
	pFeatures += 'help:no;'; 
	pFeatures += 'status:no;'; 
	 
	window.showModalDialog(pURL, pArgIn, pFeatures); 
}

//f11) Aberura janela modaless
function WinModalessOpen(pURL, pWidth, pHeight){

	var pLeft = (window.screen.availWidth - pWidth) /2 ; 
	var pTop = (window.screen.availHeight - pHeight) /2 ;
	
	pFeatures = 'dialogWidth:' + pWidth + 'px;'; 
	pFeatures += 'dialogHeight:' + pHeight + 'px;';
	pFeatures += 'dialogLeft:' + pLeft + 'px;';
	pFeatures += 'dialogTop:' + pTop + 'px;'; 
	pFeatures += 'help:no;'; 
	pFeatures += 'status:no;'; 
	
	window.showModelessDialog(pURL, '', pFeatures); 
}

//f12 Leitura Cookie
function get_cookie(Name) {
	var search = Name + "="
	var returnvalue = "";
	if (document.cookie.length > 0) {
		offset = document.cookie.indexOf(search)
		// if cookie exists
		if (offset != -1) { 
			offset += search.length
			// set index of beginning of value
			end = document.cookie.indexOf(";", offset);
			// set index of end of cookie value
			if (end == -1) end = document.cookie.length;
			returnvalue=unescape(document.cookie.substring(offset, end))
		}
	}
	return returnvalue;
} 


//f15) Abrir janela popup para exibir informações para o usuário
function WinPopup(pInnerHtml, pLeft, pTop, pWidth, pHeigh)
{
	var oPopup = window.createPopup();
    var oPopBody = oPopup.document.body;
    oPopBody.style.backgroundColor = "lightyellow";
    oPopBody.style.border = "solid black 1px";
    oPopBody.innerHTML = pInnerHtml;
    oPopup.show(pLeft, pTop, pWidth, pHeigh, document.body);
}

//------------------------------------------------------------------------------------
// As funções seguintes chamam uma janela com ítens a serem incluídos e/ou excluídos 
// em um listbox, sendo que a 1ª parte é responsável por chamar a janela e a 2ª parte
// realiza as operações de inserçao e exclusão na mesma.
//------------------------------------------------------------------------------------

//                             1ª P A R T E


// Abre a janela.

function small_window (myurl) {

  myurl = 'http://' + IP_servidor + ':' + Porta + '/' + myurl;

  var newWindow;
  var props = 'scrollBars=no,resizable=yes,toolbar=no,menubar=no,location=no,' +
              'directories=no,width=460,height=360';
  newWindow = window.open(myurl, "Add_from_Src_to_Dest", props);
}


// Adiciona a lista de itens selecionados à janela (obs: é chamado da janela filha!)  

function addToParentList(sourceList) {
  destinationList = window.document.forms[0].parentList;
  for(var count = destinationList.options.length - 1; count >= 0; count--) {
    destinationList.options[count] = null;
  }
  for(var i = 0; i < sourceList.options.length; i++) {
    if (sourceList.options[i] != null)
    destinationList.options[i] = new Option(sourceList.options[i].text, sourceList.options[i].value);
  }
}


// Marca todos os itens selecionados para o botão submit. 

function selectList(sourceList) {
  sourceList = window.document.forms[0].parentList;
  for(var i = 0; i < sourceList.options.length; i++) {
    if (sourceList.options[i] != null)
    sourceList.options[i].selected = true;
  }
  return true;
}


// Deleta os itens selecionados da lista.

function deleteSelectedItemsFromList(sourceList) {
  var maxCnt = sourceList.options.length;
  for(var i = maxCnt - 1; i >= 0; i--) {
    if ((sourceList.options[i] != null) && (sourceList.options[i].selected == true)) {
      sourceList.options[i] = null;
    }
  }
}


//                             2ª P A R T E


// Adiciona os itens selecionados na janela de origem (chamando um método desta!)

function addSelectedItemsToParent() {
  self.opener.addToParentList(window.document.forms[0].destList);
  window.close();
}


// Preenche a lista com os itens já selecionados.

function fillInitialDestList() {
  var destList = window.document.forms[0].destList; 
  var srcList = self.opener.window.document.forms[0].parentList;

  for (var count = destList.options.length - 1; count >= 0; count--) {
    destList.options[count] = null;
  }
  for(var i = 0; i < srcList.options.length; i++) { 
    if (srcList.options[i] != null)
      destList.options[i] = new Option(srcList.options[i].text, srcList.options[i].value);
  }
}


// Adiciona os itens selecionados da lista de origem para a de destino.

function addSrcToDestList() {
  destList = window.document.forms[0].destList;
  srcList = window.document.forms[0].srcList; 
  var len = destList.length;

  for(var i = 0; i < srcList.length; i++) {
    if ((srcList.options[i] != null) && (srcList.options[i].selected)) {

      // Verifica se o valor já está ou não na lista. 
      var found = false;
      for(var count = 0; count < len; count++) {
        if (destList.options[count] != null) {
          if (srcList.options[i].text == destList.options[count].text) {
            found = true;
            break;
          }
        }
      }
      
      if (found != true) {
        destList.options[len] = new Option(srcList.options[i].text, srcList.options[i].value); 
        len++;
      }
    }
  }
}


// Deleta a lista de destino.

function deleteFromDestList() {
  var destList  = window.document.forms[0].destList;
  var len = destList.options.length;

  for(var i = (len-1); i >= 0; i--) {
    if ((destList.options[i] != null) && (destList.options[i].selected == true)) {
      destList.options[i] = null;
    }
  }
}











