var expDays = 100;
var exp = new Date(); 
exp.setTime(exp.getTime() + (expDays*24*60*60*1000));

var docId = 0;
var visId = 0;
var initialized = 0;


/* AJAX */
function nsXmlAll(url, ajaxSort, _xmlDoc, pFunction) {

	var httpRequest;

    if (window.XMLHttpRequest) { // Mozilla, Safari, ...
        httpRequest = new XMLHttpRequest();
        if (httpRequest.overrideMimeType) {
            httpRequest.overrideMimeType('text/xml');
        }
    } else if (window.ActiveXObject) { // IE
	    httpRequest = pickProgID(["Msxml2.XMLHTTP", "Microsoft.XMLHTTP"]);
    }

    httpRequest.onreadystatechange = function() { processXML(httpRequest, pFunction) };
    httpRequest.open('GET', siteName + url + '&ajaxFrom=0&ajaxTo=99999&ajaxSort=' + ajaxSort, true);
    httpRequest.send(null);
     
}

function processXML(http_request, pFunction) {
	var _xmlDoc;
    if (http_request.readyState == 4) {
        if (http_request.status == 200) {
        	if (document.all) {
						_xmlDoc =  pickProgID(["Msxml2.DOMDocument.5.0", "Msxml2.DOMDocument.4.0", "Msxml2.DOMDocument.3.0", "MSXML2.DOMDocument", "MSXML.DOMDocument", "Microsoft.XMLDOM"]);
        		_xmlDoc.loadXML(http_request.responseText);
        	}else {
	            _xmlDoc = http_request.responseXML;
            }
            eval(pFunction + "(_xmlDoc)" );            
        } else {
            //alert('There was a problem with the request.');
        }
    }
}

/* FIM AJAX */
function pickProgID (idList){
    // found progID flag
    var bFound = false;
    var oDoc;
    var bFound = false;
    for(var i=0; i < idList.length && !bFound; i++){
        try{
             oDoc = new ActiveXObject(idList[i]);
             bFound = true;
        }catch (objException){
            // trap; try next progID
        };
    };
    return oDoc;
}

window.location.keyValue = function ( keyName )
	{
	// Check to see if we have already retrieved the key value pairs
	// if we haven't then we need to retrieve them
	if( window.location.variablePairs == null )
		{
		if( window.location.href.indexOf('?') == -1)
			{
			return false;	
			}
		window.location.variablePairs = window.location.href.substr( window.location.href.indexOf('?') + 1).split('&');
		}
	
	// Search for the key that matches the keyName supplied
	for( var x = 0; x < window.location.variablePairs.length; x++ )
		{
		// If we find the key name then we retun the value associated with it
		if( keyName == window.location.variablePairs[x].substr( 0, window.location.variablePairs[x].indexOf('=')))
			{
			return window.location.variablePairs[x].substr( window.location.variablePairs[x].indexOf('=') + 1);
			}
		}
	
	// If we couldn't find the key in the GET parameters
	// then we return false
	return false;
	}

function init() {
  if ( window.location.keyValue('doc') != false)
  	docId = window.location.keyValue('doc');
  if (initialized == 0)
	createCboLingua();
  initialized = 1;

}

function getCurrentPage() {
  var currentPath = window.location.pathname; 
  var currentPage = currentPath.substring(currentPath.lastIndexOf('/') + 1);
  if (currentPage == "") currentPage = "index.html";
  return currentPage;
}


function getSize(_xmlDoc){

	var titulo_nodos = _xmlDoc.getElementsByTagName("item");
	
	if (titulo_nodos != undefined)
		return titulo_nodos.length;
	return 0;
}

function getValue(item, coluna, _xmlDoc){

	var titulo_nodos = _xmlDoc.getElementsByTagName("item");
	
	if (titulo_nodos.length - 1 < item)
		return;

	for(var j = 0; j < titulo_nodos[item].childNodes.length; j++){
		var itemNode = titulo_nodos[item].childNodes.item(j);
		if (itemNode.nodeType == 1 && itemNode.nodeName == coluna){
			if (document.all) {
				if(itemNode.firstChild != null)
					return itemNode.firstChild.data;
			} else {
				return itemNode.textContent;
			}
		}		
	}
	
	return '';
}


/* TEXTO */
function exibirTexto(docValue, page){
	
	if (page != undefined && page != getCurrentPage()) {
		document.location = page + "?doc=" + docValue;
	} else {
		var xmlDocTexto;
 		nsXmlAll('exibeTextoAjax.do?ASS_ID=' + assinanteID + '&DOC_ID=' + docValue + '&LIN_ID=' + linId + '&VIS_ID=' + visId,'DOC_ID', xmlDocTexto,"exibirTextoDone");
	}
}
function exibirTextoDone(xmlDocTexto) {
	
	document.getElementById("docRelacionadoSecao").style.display = 'none';
	document.getElementById("ajaxDocRelacionado").style.display = 'none';
	document.getElementById("arqRelacionadoSecao").style.display = 'none';
	document.getElementById("ajaxArqRelacionado").style.display = 'none';


 	document.getElementById("ajaxTitulo").innerHTML = '';
 	document.getElementById("ajaxTexto").innerHTML = '';

 	if (getValue(0,'DOC_ID',xmlDocTexto) != undefined) {
		
		var texto = new String(getValue(0,'LDC_TEXTO',xmlDocTexto));
		texto = texto.replace(/&quot;\.\./gi,"\"portal");
		texto = texto.replace(/&quot;/gi,"\"");
		texto = texto.replace(/mostraImagemGenerica/gi,"portal/mostraImagemGenerica");


	 	document.getElementById("ajaxTitulo").innerHTML = getValue(0,'LDC_TITULO',xmlDocTexto);
	 	document.getElementById("ajaxTexto").innerHTML = texto;


 	
 		docId = getValue(0,'DOC_ID',xmlDocTexto);	 	   

	  if (getValue(0,'DOC_LOGO_EXISTS',xmlDocTexto) != "-1") {
		  document.getElementById("ajaxImagem").style.display = 'block';
	    if (document.all) {
		  	  document.getElementById("ajaxImagem").style.filter = "progid:DXImageTransform.Microsoft.Fade(duration=0.3)";
		  	  document.getElementById("ajaxImagem").filters[0].Apply();
			  document.getElementById("ajaxImagem").src = siteName + "mostraImagem.do?DOC_ID=" + docId;
		  	  document.getElementById("ajaxImagem").filters[0].Play();
		  }	 else {
		 	  document.getElementById("ajaxImagem").src = siteName + "mostraImagem.do?DOC_ID=" + docId;
		  }
		}	else {
	  	 	document.getElementById("ajaxImagem").src = "portal/images/spacer.gif";
			document.getElementById("ajaxImagem").style.display = 'none';
		}
		 	
	 	exibirArquivoRelacionado(docId);
		exibirTextoRelacionado(docId);

	} else {
	 	document.getElementById("ajaxImagem").src = "portal/images/spacer.gif";
	}
	
	visId = 4;
	

}
/* FIM TEXTO */


/* TEXTO REL */
function exibirTextoRelacionado(docValue) {
	var xmlDocRelacionado;
	nsXmlAll('findDocumentoRelacionadoAjax.do?ASS_ID=' + assinanteID + '&DOC_ID=' + docValue + '&LIN_ID=' + linId,'DOC_ID', xmlDocRelacionado, "exibirTextoRelacionadoDone");
}

function exibirTextoRelacionadoDone(xmlDocRelacionado) {


	 	var docRel = '<ul>';
		for (i = 0; i < getSize(xmlDocRelacionado); i++) {

			docRel += '<li><a class="luxCssDocRelacionado" style="text-decoration:none;" href="javascript:exibirTexto(' + getValue(i,'DOC_ID_REL',xmlDocRelacionado) + ')">';
			docRel += getValue(i,'LDC_TITULO',xmlDocRelacionado);
			docRel += '</a></li>';
		}
		docRel += '</ul>';
		
		if(getSize(xmlDocRelacionado) > 0) {
  		  document.getElementById("docRelacionadoSecao").style.display = 'block';
			document.getElementById("ajaxDocRelacionado").style.display = 'block';
			document.getElementById("ajaxDocRelacionado").innerHTML = docRel;
		}

}
/* FIM TEXTO REL */


/* ARQ REL */
function exibirArquivoRelacionado(docValue) {
	var xmlArqRelacionado;
	nsXmlAll('findArquivoRelacionadoAjax.do?ASS_ID=' + assinanteID + '&DOC_ID=' + docValue,'ARQ_ORDEM', xmlArqRelacionado, "exibirArquivoRelacionadoDone");
}

function exibirArquivoRelacionadoDone(xmlArqRelacionado) {


	 	var docRel = '<ul>';
		for (i = 0; i < getSize(xmlArqRelacionado); i++) {

			docRel += '<li><a class="luxCssDocRelacionado" style="text-decoration:none;" href="javascript:download(' + getValue(i,'ARQ_ID',xmlArqRelacionado) + ')">';
			docRel += getValue(i,'ARQ_DESCRICAO',xmlArqRelacionado);
			docRel += '</a></li>';
		}
		docRel += '</ul>';
		if(getSize(xmlArqRelacionado) > 0) {
		  document.getElementById("arqRelacionadoSecao").style.display = 'block';
			document.getElementById("ajaxArqRelacionado").style.display = 'block';
			document.getElementById("ajaxArqRelacionado").innerHTML = docRel;
		}

}
function download(arqId) {
	document.location = siteName + 'arquivoDownload.do?ARQ_ID=' + arqId;
}


/* FIM ARQ REL */



/* MENU */
function createMenus(){

	if (BackgroundImage == undefined)
		return;

	var xmlDocMenu;
 	nsXmlAll('createMenuAjax.do?ASS_ID=' + assinanteID + '&LIN_ID=' + linId,'LIN_ID',xmlDocMenu,"createMenusDone");
}

function createMenusDone(xmlDocMenu) {
  var numFirstMenu = 0;
  var menuCode = '';
  var i = 0;
  for (i = 0; i < getSize(xmlDocMenu); i++){
       if ( getValue(i,'MEN_SUPER_ID',xmlDocMenu) == '' ){
          numFirstMenu++;
       }
  }
  NoOffFirstLineMenus = numFirstMenu;
  
  
  if (FirstLineHorizontal == 1) {
  	MenuWidth = CellMenuWidth * numFirstMenu;
	MenuHeight = CellMenuHeight;
  } else {
	MenuWidth = CellMenuWidth;
  	MenuHeight = CellMenuHeight * numFirstMenu;
  }
 
 
		
	if (Loadd && document.getElementById("divMenu") != null) {
 		document.body.removeChild(document.getElementById("divMenu"));
  	}

  if(getSize(xmlDocMenu) > 0) {
 
        RcrsLvl=0;
        FrstCreat=1;
        Loadd=0;
        Creatd=0;
        AcrssFrms=1;
	
  	eval( writeMenuJavascript('',CellMenuWidth,CellMenuHeight,'',xmlDocMenu) );
  	Go();

  }
  
}

/* FIM MENU */



function writeMenuJavascript(index, width, height, parentId, xmlDocMenu) {


	var menuCode = '';
	var menuCount = 1;
  var q = 1;
  var t = 0;
  
	for (q = 0; q < getSize(xmlDocMenu); q++){
	
		if (getValue(q,'MEN_SUPER_ID',xmlDocMenu) == parentId) {

			var numOfChildren = 0;
			for (t = 0; t < getSize(xmlDocMenu); t++){
				if (getValue(t,'MEN_SUPER_ID',xmlDocMenu) == getValue(q,'MEN_ID',xmlDocMenu)) {
					numOfChildren++;
				}
			}


			// Writes the menu code line: parent menu followed by its children 
			menuCode += 'Menu';
			menuCode += index + (menuCount++);
			menuCode += '=new Array("';
			menuCode += getValue(q,'LIN_MEN_TEXTO',xmlDocMenu);
			menuCode += '","javascript:exibirTexto(';
			menuCode += getValue(q,'DOC_ID',xmlDocMenu);
			menuCode += ',\'';
			menuCode += getValue(q,'MEN_PAGINA',xmlDocMenu);
			menuCode += '\')","",';
			menuCode += numOfChildren;
			
			
			
			if (index == '') {
		        menuCode += ',';
		        menuCode += height;
		        menuCode += ',';   
				menuCode += width;
			}else {
				menuCode += ',';
	          	menuCode += height;
	          	menuCode += ',';	
				menuCode += 120;
			}
			
			menuCode += ');\n';


			// Recursive call if there are children
			if (numOfChildren > 0) {
				menuCode += writeMenuJavascript(index + (menuCount-1) + "_", width, height, getValue(q,'MEN_ID',xmlDocMenu), xmlDocMenu);
			}
			
		}
	}
	

	return menuCode;
}

/* COMBO LINGUA */
var _xmlComboLingua;
function createCboLingua() {
	var _xmlLingua;
 	nsXmlAll('createLinguaAjax.do?ASS_ID=' + assinanteID,'LIN_DESCRICAO',_xmlLingua,"createCboLinguaDone");
} 

function createCboLinguaDone(_xmlDoc) {
	_xmlComboLingua = _xmlDoc;
 	//comboXML('cboLingua','LIN_ID',new Array('LIN_DESCRICAO'),linId,'', _xmlDoc);
 	
	var linHtml = "";
	var linIndex = 0;

	for (var i = 0; i < getSize(_xmlDoc); i++) { 
		linHtml += "<img style=\"cursor:hand\" src=\"" + siteName + "mostraImagemLingua.do?LIN_ID=" + getValue(i,"LIN_ID",_xmlDoc) + "\" border=\"0\" ";
		linHtml += "onclick=\"sincLinguaImagem(" + i + ")\" ";
		linHtml += "alt=\"" + getValue(i,"LIN_DESCRICAO",_xmlDoc) + "\">&nbsp;";
		
		
		if (getValue(i,"LIN_ID",_xmlDoc) == linId)
			linIndex = i;
		
	} 	
	
	document.getElementById('ajaxLingua').innerHTML = linHtml;
	
	sincLinguaImagem(linIndex);
	
} 

function sincLinguaImagem(linIndex) {
	linId = getValue(linIndex, "LIN_ID", _xmlComboLingua);

	document.getElementById("docRelacionadoSecao").style.display = 'none';
	document.getElementById("ajaxDocRelacionado").style.display = 'none';
	document.getElementById("arqRelacionadoSecao").style.display = 'none';
	document.getElementById("ajaxArqRelacionado").style.display = 'none';

	document.getElementById('ajaxDocRelacionadoTitulo').innerHTML = getValue(linIndex, "LIN_DOCUMENTO", _xmlComboLingua);
	document.getElementById('ajaxArqRelacionadoTitulo').innerHTML = getValue(linIndex, "LIN_ARQUIVO", _xmlComboLingua);

	
	exibirTexto(docId, getCurrentPage());
	createMenus();
}

function sincLingua() {
	linId = getValue(document.getElementById('cboLingua').value, "LIN_ID", _xmlComboLingua);
	document.getElementById('ajaxDocRelacionadoTitulo').innerHTML = getValue(document.getElementById('cboLingua').value, "LIN_DOCUMENTO", _xmlComboLingua);
	document.getElementById('ajaxArqRelacionadoTitulo').innerHTML = getValue(document.getElementById('cboLingua').value, "LIN_ARQUIVO", _xmlComboLingua);
	createMenus();


	exibirTexto(docId, getCurrentPage());
}


function comboXML(name,coluna,valueArray,selectedValue,first, _xmlDoc){


	var titulo_nodos = _xmlDoc.getElementsByTagName("item");

	var objCombo = document.getElementById(name);
	
	for (var k = objCombo.options.length - 1; k >= 0; k--)
		objCombo.options[k] = null;


	for (var i = 0; i < titulo_nodos.length; i++) { 
		if (titulo_nodos[i].hasChildNodes) {    
			var valorOption = i;
			var descOption = "";

			/*		
			for (var j = 0; j < titulo_nodos[i].childNodes.length; j++) { 
				var itemNode = titulo_nodos[i].childNodes.item(j);
				if (itemNode.nodeType == 1 && itemNode.nodeName == coluna) {
					valorOption = itemNode.firstChild.data;
				}
			}
			*/
			
			for (var k = 0; k < valueArray.length; k++) {
				var achou = false;
				for (var j = 0; j < titulo_nodos[i].childNodes.length; j++) { 
					var itemNode = titulo_nodos[i].childNodes.item(j);
					if (itemNode.nodeType == 1 && itemNode.nodeName == valueArray[k]) {
						descOption += itemNode.firstChild.data;
						achou = true;
					}
				}
				if (!achou)
					descOption += valueArray[k];
			}


			opt = document.createElement("OPTION");
			opt.text = descOption;
			opt.value = valorOption;
			objCombo.options.add(opt);
		}
	}
	
	
	for (var i = 0; i < objCombo.options.length; i++) {
		if (objCombo.options[i].value == selectedValue) {
			objCombo.options[i].selected = true;
			break;
		}
	}
	
}

/* FIM COMBO */


function BeforeStart(){
	return;
}
function AfterBuild(){
	return;
}
function BeforeFirstOpen(){
	return;
}
function AfterCloseAll(){
	return;
}


function getCookieVal (offset) {  
	var endstr = document.cookie.indexOf (";", offset);  
	if (endstr == -1) { endstr = document.cookie.length; }
	return unescape(document.cookie.substring(offset, endstr));
}



function GetCookie (name) {  
	var arg = name + "=";  
	var alen = arg.length;  
	var clen = document.cookie.length;  
	var i = 0;  
	while (i < clen) {    
		var j = i + alen;    
		if (document.cookie.substring(i, j) == arg) return getCookieVal (j);    
		i = document.cookie.indexOf(" ", i) + 1;    
		if (i == 0) break;   
	}  
	return null;
}



function SetCookie (name, value) {  
	document.cookie = name + "=" + escape (value) + "; expires=" + exp.toGMTString();
}


function cookie(){
	
	var today = new Date();
	var codigo = today.getYear() + "-"  + today.getMonth() + "-" + today.getDate();
	var codigoAnt = GetCookie('Luxfacta');
	
	
	if(codigoAnt == null){
		visId = 1;
	}
	else
		if(codigo == codigoAnt){
			visId = 2;
		}
	else
		if(codigo != codigoAnt){
			visId = 3;
		}	
	
	SetCookie('Luxfacta',codigo);

}		

cookie();

// :: Ajax Combo ::

function AjaxCombo (url, sort, valueProperty, textProperty, firstItem, comboObject, selectedValue) {
	this.create = create;

	function create() {
 		getAjax(url , sort, this);
	}
	
	function ajaxReady(_xmlCombo) {
	
		var xmlItens = _xmlCombo.getElementsByTagName("item");
	
		for (k = comboObject.options.length - 1; k >= 0; k--)
			comboObject.options[k] = null;
	
		var opt = document.createElement("OPTION");
		opt.text = firstItem;
		opt.value = "0";
		comboObject.options.add(opt);
		
		
		for (i = 0; i < xmlItens.length; i++) { 
			if (xmlItens[i].hasChildNodes) {    
				var valorOption = "";
				var descOption = "";
			
				for (j = 0; j < xmlItens[i].childNodes.length; j++) { 
					var itemNode = xmlItens[i].childNodes.item(j);
					if (itemNode.nodeType == 1 && itemNode.nodeName == valueProperty) {
						valorOption = itemNode.firstChild.data;
					}
				}
				for (k = 0; k < textProperty.length; k++) {
					var achou = false;
					for (j = 0; j < xmlItens[i].childNodes.length; j++) { 
						var itemNode = xmlItens[i].childNodes.item(j);
						if (itemNode.nodeType == 1 && itemNode.nodeName == textProperty[k]) {
							descOption += itemNode.firstChild.data;
							achou = true;
						}
					}
					if (!achou)
						descOption += text[k];
					
				}
	
				opt = document.createElement("OPTION");
				opt.text = descOption;
				opt.value = valorOption;
				comboObject.options.add(opt);
			}
		}
		
		
		for (i = 0; i < comboObject.options.length; i++) {
			if (comboObject.options[i].value == selectedValue) {
				comboObject.options[i].selected = true;
				break;
			}
		}
	}
	function getAjax(url, ajaxSort, object) {
		
		var _xmlDoc;
		var httpRequest;
	
	    if (window.XMLHttpRequest) { // Mozilla, Safari, ...
	        httpRequest = new XMLHttpRequest();
	        if (httpRequest.overrideMimeType) {
	            httpRequest.overrideMimeType('text/xml');
	        }
	    } else if (window.ActiveXObject) { // IE
		    httpRequest = pickProgID(["Msxml2.XMLHTTP", "Microsoft.XMLHTTP"]);
	    }
	
	    httpRequest.onreadystatechange = function() { processAjax(httpRequest, object) };
	    httpRequest.open('GET', siteName + url + '&ajaxFrom=0&ajaxTo=99999&ajaxSort=' + ajaxSort, true);
	    httpRequest.send(null);
	     
	}
	
	function processAjax(http_request, object) {
		var _xmlDoc;
	    if (http_request.readyState == 4) {
	        if (http_request.status == 200) {
	        	if (document.all) {
							_xmlDoc =  pickProgID(["Msxml2.DOMDocument.5.0", "Msxml2.DOMDocument.4.0", "Msxml2.DOMDocument.3.0", "MSXML2.DOMDocument", "MSXML.DOMDocument", "Microsoft.XMLDOM"]);
	        		_xmlDoc.loadXML(http_request.responseText);
	        	}else {
		        	var dparser = new DOMParser();
		            _xmlDoc = dparser.parseFromString(http_request.responseText, "text/xml");
	            }
	            ajaxReady(_xmlDoc);            
	        } else {
	        }
	    }
	}

} 


function endereco_ajax() {
document.getElementById("pontos_venda").innerHTML = "";


	obj = document.getElementById('END_ESTADO');
	obj2 =  document.getElementById('END_CIDADE');
	if (obj.selectedIndex > 0){
		estado = obj.options.item(obj.selectedIndex).value;
		
		var comb = new AjaxCombo('../portal/findEnderecoCidadeAjax.do?END_ESTADO=' + estado,'END_CIDADE', 'END_CIDADE', new Array('END_CIDADE'), '-- Selecione --', obj2, '0');
		comb.create();
		return false;
	}
}

function cidade_ajax(){
document.getElementById("pontos_venda").innerHTML = "";

	obj = document.getElementById('END_ESTADO');
	obj2 =  document.getElementById('END_CIDADE');
	obj3 = document.getElementById('END_DIVISAO');

	
	if (obj.selectedIndex > 0 && obj2.selectedIndex > 0){
		estado = obj.options.item(obj.selectedIndex).value;
		cidade = obj2.options.item(obj2.selectedIndex).value;
			
		var comb = new AjaxCombo('../portal/findEnderecoDivisaoAjax.do?END_ESTADO=' + estado + "&END_CIDADE=" + cidade  ,'END_DIVISAO', 'END_DIVISAO', new Array('END_DIVISAO'), '-- Selecione --', obj3, '0');
		comb.create();
		return false;

	}	
	
}


function divisao_ajax(){
document.getElementById("pontos_venda").innerHTML = "";
	
	estado = document.getElementById('END_ESTADO').value;
	cidade =  document.getElementById('END_CIDADE').value;
	divisao =  document.getElementById('END_DIVISAO').value;
	
	var xmlEndereco;
	nsXmlAll('../portal/findEnderecoAjax.do?END_ESTADO=' + estado + '&END_CIDADE='+ cidade + '&END_DIVISAO=' + divisao ,'END_NOME', xmlEndereco, "exibirEndereco");
	
}

function exibirDivisao(xmlEndereco) {
 	var html = "";
 	for (i = 0; i < getSize(xmlEndereco); i++) {
 		html += "<b>"+getValue(i,'END_NOME',xmlEndereco)+"</b><br>"+getValue(i,'END_DESCRICAO',xmlEndereco)+"<br><br>";
 	}
	if(getSize(xmlEndereco) > 0)
		document.getElementById("pontos_venda").innerHTML = html;
}


function exibirEndereco(xmlEndereco) {
 	var html = "";
 	for (i = 0; i < getSize(xmlEndereco); i++) {
 		html += "<b>"+getValue(i,'END_NOME',xmlEndereco)+"</b><br>"+getValue(i,'END_DESCRICAO',xmlEndereco)+"<br><br>";
 	}
	if(getSize(xmlEndereco) > 0)
		document.getElementById("pontos_venda").innerHTML = html;
}



