﻿// JScript File
// Permite preencher inputs do form e de seguida fazer o submit
function submitForm(eElemsID,eElemsValue,frmID,action,reset)
{  
	var _frmElem = document.getElementById(frmID);
	if (_frmElem) {
				
		if (reset) {
			resetDefaultValues(_frmElem);
		}
		
	    if (eElemsID != null)
	    {
	        for (var i = 0; i < eElemsID.length; i++) {				
				var _eElem = document.getElementById(eElemsID[i]);
				if (_eElem) {		
					if (_eElem.type == 'select-one') {
						_eElem.value = eElemsValue[i];
						if (_eElem.value == ''){
							opt = "new Option" + "('"+ _eElem.options[0].text + "','" + eElemsValue[i] +"')";
						    _eElem.options[0] = eval(opt);
							_eElem.selectedIndex = 0;
							//alert(_eElem.options[0].value);
						}
					}
					else {
						_eElem.value = eElemsValue[i];
						//alert(_eElem.name + " . " + _eElem.value);
					}
				}
	        }
	    }
            
        if (action != "" && action != undefined)
        {
            _frmElem.action = action;
        }
        _frmElem.submit();        
    }
}
// reset inputs do form de pesquisa de artigos
function resetDefaultValues(frm) {
    for (var i=0, j=frm.elements.length; i<j; i++) {
        myType = frm.elements[i].type;
		switch (myType){
			case 'text':
				frm.elements[i].value = '';
				break;
			case 'select-one':
				myId = frm.elements[i].id;
				switch (myId){
					case 'fCODAGRUP':
					case 'fCODCLA':
					case 'fCODFAM':
						frm.elements[i].selectedIndex = 0;
						break;		
					default:
						// do nothing
						break;
				}
			default:
				// do nothing
				break;
		}
    }
}
// retorna os artigos seleccionados
var strArtigosSemDisponibilidade = "";
function getArtigosSeleccionados(elemName, artsDisp)
{
    // buscar os artigos seleccionados
    var numArts = document.getElementsByName(elemName) ;
    var sep = ""; var sep1 = "";
    var strAux = "";var refart = "";
    for (var i = 0; i < numArts.length; i++)
    {
        if (numArts[i].checked)
        {
            if (artsDisp)
            {
                var disp = numArts[i].getAttribute("disponivel");
                
                if (disp == 'true'){
                    refart += sep1 + numArts[i].getAttribute("refart");
                    sep1 = ",";
                }  
                else
                {
                    strAux += sep + numArts[i].value;
                    sep = ",";
                }          
            }    
            else
            {
                strAux += sep + numArts[i].value;
                sep = ",";
            }            
        } 
    }    
    
    strArtigosSemDisponibilidade = refart;
    return (strAux);
}
// actualiza o carrinho de compras
function actualizarCarrinho()
{
	updateChanges('../artigos/carrinho_totais_xmlhttp.asp',loadCarrinho,null,null,null);	              

}
// actualiza os dados vindos por content nos divs do carrinho;
function loadCarrinho(content)
{
	var _divNumArts = document.getElementById("divCestoNumArts");
	var _divTotal = document.getElementById("divCestoTotal");
	var _userArtCesto = document.getElementById("userTemArtigosCesto");
	if (content != "")
	{
		content = SPW_HTMLDecode(content);
		arrC = content.split("|");		
		if (arrC[0] == 1) 
		{
			if (_divNumArts) 
				_divNumArts.innerHTML = arrC[1];
			if (_divTotal) 
				_divTotal.innerHTML = arrC[2];
			if (_userArtCesto) 
				_userArtCesto.value = (arrC[1] > 0);						
		}
	}	
}
// adiciona o artigo ao carrinho
// utilizada na listagem, ficha de produtos, adiciona um de cada vez
function adicionarArtigoCarrinho(NUMART,CODART,QtdElemID)
{
	var qtd = document.getElementById(QtdElemID);
	var params = "NUMART="+ NUMART + "&CODART="+ CODART + "&Qtd="+ qtd.value;
	
	if (!SPW_JS_ValidaIntObg1(null,qtd,18,'Qtd'))
	    return false;
	
	updateChanges('../artigos/artigocesto_adi_xmlhttp.asp',showResult,null,null,params);
	qtd.value = 0;
	qtd.select();
}

// mostra a mensagem resultante da operação efectuada
function showResult(content)
{
	showMessage(content);
	
	actualizarCarrinho();	
}
// mostra a mensagem resultante da operação efectuada
function showResultLista(content)
{
	showMessage(content);
}
// mostra a mensagem
var timeout;
function showMessage(msg,timer){
	if (msg != "") {
		var _divMsg = document.getElementById("divMsgInfo");
		if (_divMsg)
		{
		    if (timer == undefined) timer = 4000;
		    		    
			try {
				showDivMessagesInfo(msg);
				if (timer > 0)
				{
				    timeout = setTimeout(function(){
					    hideDivMessagesInfo();
				    }, timer);
				}
			} 
			catch(ex) {
				alert(SPW_HTMLDecode(msg));
			}
		}
		else{
			alert(SPW_HTMLDecode(msg));		
		}
	}
}

// mostra o div que mostra as informações
function showDivMessagesInfo(msg)
{
	var _divMsg = document.getElementById("divMsgInfo");
	var _divAll = document.getElementById("divAll");	
	if (_divAll) 
	{
		_divAll.style.display = "block";
		_divAll.style.width = SPW_GetDocumentWidth();	
		_divAll.style.height = SPW_GetDocumentHeight();
		
		//alert(SPW_GetDocumentWidth() + ".." + SPW_GetDocumentHeight());		
	}
	if (_divMsg) 
	{
		centerDiv(_divMsg);
		_divMsg.className = "divShow divInfo";
		_span = document.getElementById("spanMsg");						
		if (_span) _span.innerHTML = msg;			
	}	
}
// centra o div no meio da janela
function centerDiv(div)
{ 
    var _left = (document.body.clientWidth - 200) / 2;
    div.style.left  = _left + document.body.scrollLeft;
    var _top = (document.body.clientHeight - 150) / 2;
    div.style.top  = _top + document.body.scrollTop;
	
}
// esconde o div que mostra as informações
function hideDivMessagesInfo()
{	
	// parar o settimeout
	clearTimeout(timeout);

	var _divMsg = document.getElementById("divMsgInfo");
	var _divAll = document.getElementById("divAll");
	if (_divAll) 
	{
		_divAll.style.display = "none";
	}
	if (_divMsg) 
	{
		_divMsg.className = "divHide";	
		_span = document.getElementById("spanMsg");						
		if (_span) _span.innerHTML = "";			
	}	
}

var divScrollTop = 0;
function saveScrollTop(divID)
{
	var _div = document.getElementById(divID);
	if(_div) divScrollTop = _div.scrollTop;
}
function setDivScrollTop(divID)
{
	var _div = document.getElementById(divID);
	if (_div) {
		var _posTop = document.getElementById("posScrollTop");
		if (_posTop) {
			divScrollTop = _posTop.value;
			_posTop.value = 0;
		}
		_div.scrollTop = divScrollTop;
	}	
}

// de acordo com o Agrupamento seleccionado carrega a combo de classes associadas
function loadClasses(eElem,urlPage)
{
    var url = urlPage +'/artigos/classe_lista_xmlhttp.asp?fCODAGRUP='+eElem.value;
    updateChanges(url,loadClassesToSelect);    
}
// carrega os options no select das classes
function loadClassesToSelect(content)
{
    loadToSelect(content,"fCODCLA");	
}

// de acordo com a Classe seleccionada carrega a combo de marcas que têm artigos dessa classe
function loadMarcas(eElem,urlPage)
{
    var url = urlPage +'/artigos/marca_lista_xmlhttp.asp?fCODCLA='+eElem.value ;
    updateChanges(url,loadMarcasToSelect);
}
// de acordo com o Agrupamento seleccionada carrega a combo de marcas que têm artigos desse agrupamento
function loadMarcasAgrup(eElem,urlPage)
{
    var url = urlPage +'/artigos/marca_lista_xmlhttp.asp?fCODAGRUP='+eElem.value ;
    updateChanges(url,loadMarcasToSelect);
}

//carrega os dados para o local de entrega
function loadLocalEntrega(eElem)
{
	updateChanges('../artigos/localentrega_xmlhttp.asp?fCODCLENT=' + eElem.value, loadLocalEntregaCampos);
}
// carrega os inputs com os valores do local de entrega
function loadLocalEntregaCampos(content)
{
	if (content != "") {
		
		content = SPW_HTMLDecode(content);
		var arrLoc = content.split("[|]");
		
		var _morada = document.getElementById("ExpMorada");	
		var _codpostal = document.getElementById("ExpCodPostal");	
		var _sublocal = document.getElementById("ExpSubLocal");
		var _local = document.getElementById("ExpLocalidade");
		
		if (_morada){
			_morada.value = arrLoc[0];}
		if (_codpostal){
			_codpostal.value = arrLoc[1];}		
		if (_sublocal){
			_sublocal.value = arrLoc[2];}
		if (_local){
			_local.value = arrLoc[3];}		
	}
}

// carrega os options no select das marcas
function loadMarcasToSelect(content)
{
    loadToSelect(content,"fCODFAM");
}

// carrega os dados do XMLHttpRequest para o Select indicado
function loadToSelect(content,eElemID)
{
    var inpDestino = document.getElementById(eElemID);      
    if (inpDestino)
    {
        if (inpDestino.type == 'select-one')
        {
            aux = SPW_HTMLDecode(content);	                
	        if (aux != "" && aux != 0)
	        {	
		        inpDestino.options.length = 1;		    
		        mArray = aux.toString().split("[|]");				
		        for (j = 1; j <= mArray.length; j++)
		        {		
			        mArrayId = mArray[j-1].toString().split("|");		
			        opt = "new Option" + "('"+ mArrayId[1] + "','" + mArrayId[0] +"')";
			        inpDestino.options[j] = eval(opt);
    			    
			        mArrayId = "";
		        }
	        }
	        else{
		        inpDestino.options.length = 1;
		    }
		}
    }    
}

// encarregasse de chamar o ajax para buscar os dados e chamar as funções para fazer os loads dos dados
function updateChanges(url,functionToRun, divContent,carregarLabel,dataForm ){
    setTimeout(
          function() {
              if (divContent)
              {
                if( document.getElementById(divContent).innerHTML == '' )
                  document.getElementById(divContent).innerHTML = '<span>'+ carregarLabel +'</span>';
              }
          } , 1500);
    
    ajaxPost(url, functionToRun,dataForm );
}

//para as listagens
function toggleNext( oImg, c )
{
    var oEl;
		
	if (c != undefined) {
        oEl = document.getElementById("div"+c);
	}else{
		var i = 0;
		oEl = oImg;
	
		for ( i = oImg.sourceIndex; oEl && document.all[i].tagName != "SPAN" && document.all[i].tagName != "DIV"; i++ )
		{
			oEl = document.all[i+1];		
		}
	}

    if( !oEl || oEl.tagName != "DIV" ) return;

    if( -1 != oImg.src.indexOf( "menos" ) )
    {
        oImg.src = "../images/ic_mais.gif";
        oEl.style.display = "none";
    }
    else
    {
        oImg.src = "../images/ic_menos.gif";
        oEl.style.display = "block";
    }
}
// faz o check/uncheck a um campo do tipo checbox
function checkCampo(elemID)
{
	var _elem = document.getElementById(elemID);	
	if (_elem)
	{
	    if (_elem.type == 'checkbox' || _elem.type == 'radio'){
		    _elem.checked = !_elem.checked;		
		    if (_elem.onclick)
		        _elem.onclick();
	    }
	}	
}

// coloca o valor no campo
function setValueCampo(elemID, valor, call)
{
    var _elem = document.getElementById(elemID);	
	if (_elem)
	{
        switch(_elem.type)
        {
            case "select-one":
                _elem.selectedIndex = valor;    
                        
                break;    
            case "text":
                _elem.value = valor;
                break;
            case "hidden":
                _elem.value = valor;
                break;
            default:
                // do nothing
                alert("Tipo de campo inválido.");
                break;
        }     
    }	
}

// confirma caso o cesto tenha artigos o logout
function callLogout(urlLogout,msg,urlPage)
{   
    var temArt = document.getElementById("userTemArtigosCesto");    
    
    if (temArt.value == 'true'){
        confirmLogout(urlLogout,msg,urlPage);
    }    
    else{
        window.location.href = urlLogout;
    }
}

//Funcao de confirmação de logout
function confirmLogout(urlTo,msg,urlPage){    
	var url = urlPage +"/dialogos/showmsglogout.asp?urlTo="+ escape(urlTo) +"&msg="+msg;
	
	var iW=350; var iH=150; var R='no'; var S='no';
	var SC='no'; var T='no'; var TB='no'; 
	var TOP='250'; var LEFT='200';
	var sF="";
	
	sF+=iW?'width='+iW+',':'';
	sF+=iH?'height='+iH+',':'';
	sF+=R?'resizable='+R+',':'';
	sF+=S?'status='+S+',':'';
	sF+=SC?'scrollbars='+SC+',':'';
	sF+=T?'titlebar='+T+',':'';
	sF+=TB?'toolbar='+TB+',':'';
	sF+=TB?'menubar='+TB+',':'';
	sF+=TOP?'top='+TOP+',':'';
	sF+=LEFT?'left='+LEFT+',':'';
	
	window.open(url,'ConfirmLogout',sF).focus();
}

// funções de AJAX
function ajaxPost(url, callback, dataForm){
function ajaxBindCallback(){
      if (ajaxRequest.readyState == 4) {
          if (ajaxRequest.status == 200) {
            if (callback){                
                callback(ajaxRequest.responseText);                
            } else {
                alert('no callback defined');
            }
          } else {
             _showAjaxError(ajaxRequest);
             callback('');
          }
          delete ajaxRequest;
      }
    }

    var ajaxRequest = null;

      try {
        ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
      } catch(e) {
       try {
            ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
       } catch(ex) {
        try {
            ajaxRequest = new XMLHttpRequest();
        } catch(exc) {
            alert("Impossivel de efectuar carregamento via Ajax.");
            ajaxRequest = null;
        }
       }
      }

      if( ajaxRequest ){
        ajaxRequest.onreadystatechange = ajaxBindCallback;
        ajaxRequest.open("POST", url, true);
		ajaxRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		if (dataForm == null){
		    ajaxRequest.send('');
		}
        else{
            ajaxRequest.send(dataForm);
        }        
      }
}
function _showAjaxError(ajaxRequest){
    try{
        alert('Error['+ajaxRequest.status+']: '+ ajaxRequest.statusText);          
    }catch(e){
        alert('Error['+ajaxRequest.status+']: '+ ajaxRequest.statusText + '\n\n'+ e.message);
    }
}
//------------------------------------------------------------------------------------