//*****************************************************************************
// File:    /_generic/code/js/jsGeneric.js
// Purpose: This file has the library of generic javascript functions.
// Functions
// ----------------------------------------------------------------------------
// createPopupMsg (winParent, intMsgType, strTitle, strMessage, intWidth, 
//                 intHeight)
// IsLeapYear (intFullYear)
// String2Date (strDate)
// Date2String ()
// AddDateDays (dteDate, intDays)
// AddDateDaysS (strDate, intDays)
// GetDate (nrd)
// ChangeCountry (country)
// trim (strInput)
// CreateObjectXML(strObjectName)
//*****************************************************************************
// Author   Date       Comments
// -------- ---------- --------------------------------------------------------
// JGP/V    2002.09.26 Creation of the file.
// JGP/V    2004.07.30 Added the trim and CreateObjectXML functions.
//*****************************************************************************

/******************************************************************************
'Function: createPopupMsg()
'Purpose:  This function opens a modal dialog with a message.
'Inputs:   winParent - parent window;
'          intMsgType - type of message (0 - warning (default); 1 - error; 
'                                        2 - information);
'          strTitle - title of the message;
'          strMessage - message;
'          intWidth - width size of the modal window;
'          intHeight - height size of the modal window.
'Returns:  anything - it can be a boolean, string, object, integer, etc.
'******************************************************************************
' Author   Date       Comments
' -------- ---------- ---------------------------------------------------------
' JGP/V    2002.09.26 Creation of the function.
******************************************************************************/
function createPopupMsg (winParent, intMsgType, strTitle, strMessage, intWidth,
                         intHeight)
{
  // Declaration of the local variables.
  var objDialogParameters = new Object();
  var result;
  
  // Validation of the parameters.
  if (isNaN(intMsgType) || intMsgType < 0 || intMsgType > 2) intMsgType = 0;
  if (strTitle == '') strTitle = 'econstroi.com';
  if (strMessage == '') strMessage = '...';
  if (isNaN(intWidth) || intWidth <= 0) intWidth = 200;
  if (isNaN(intHeight) || intHeight <= 0) intHeight = 200;
  
  // Initialize the dialog parameters.
  objDialogParameters.winParent = winParent;
  objDialogParameters.msgType = intMsgType;
  objDialogParameters.title = strTitle;
  objDialogParameters.text = strMessage;
  
  // Open the modal dialog.
  result = winParent.showModalDialog("/_generic/includes/grlPopup.asp", 
            objDialogParameters, "dialogWidth: " + intWidth 
            + "px; dialogHeight: " + intHeight 
            + "px; center: Yes; help: No; status: No; scroll: No");
 
  return result;
}

function vrsn_splash(){
	window.open('https://digitalid.verisign.com/cgi-bin/Xquery.exe?Template=authCertByIssuer&form_file=../fdf/authCertByIssuer.fdf&issuerSerial=c3d67114db684fd54690259443c6100e',null,'width=800px,height=600px,top=0,left=0,resizable=yes,scrollbars=yes')
}
/******************************************************************************
'Function: IsLeapYear()
'Purpose:  This function returns true is a given year is a leap year.
'Inputs:   intFullYear - given year.
'Returns:  The result is True if the year if a lead year, false otherwise.
'******************************************************************************
' Author   Date       Comments
' -------- ---------- ---------------------------------------------------------
' JGP/V    2003.03.24 Creation of the function.
******************************************************************************/
function IsLeapYear(intFullYear){
  // Declaration of the local variables.
  var intYear;
  
  // Validation of the parameter.
  if (intFullYear == null) return false;
  if (!isFinite(intFullYear)) return false;
  
  // Format the year has an integer.
  intYear = parseInt(intFullYear);
  
  // Return the validation.
  return (intYear % 400 == 0 || (intYear % 4 == 0 && intYear % 100 != 0));
}

/******************************************************************************
'Function: String2Date()
'Purpose:  This function transforms a string to a date.
'Inputs:   strDate - the given date in one of the following formats: 
'             dd/mm/yyyy or yyyy/mm/dd.  Accepts '/', '-' and '.' and the 
'             separator.  Accepts days and months with only one digit.
'Returns:  The result date.
'******************************************************************************
' Author   Date       Comments
' -------- ---------- ---------------------------------------------------------
' JGP/V    2003.03.24 Creation of the function.
******************************************************************************/
function String2Date(strDate)
{
  // Declaration of the local variables.
  var intDay, intMonth, intFullYear;
  var arexFormats = new Array(/^(\d{1,2})[\/\-\.](\d{1,2})[\/\-\.](\d{4})$/,
                              /^(\d{4})[\/\-\.](\d{1,2})[\/\-\.](\d{1,2})$/);
  var aintMonthType = new Array(1,2,1,0,1,0,1,1,0,1,0,1);
  
  // Validation of the parameter.
  if (strDate == null) return false;
  
  // Search for the format of the date.
  for (i = 0; i < arexFormats.length; i++)
  {
    if (arexFormats[i].test(strDate))
    {
      // If the format is dd/mm/yyyy, ...
      if (i == 0)
      {
        intDay = parseInt(RegExp.$1, 10);
        intMonth = parseInt(RegExp.$2, 10);
        intFullYear = parseInt(RegExp.$3, 10);
      }
      // Else the format is yyyy/mm/dd ...
      else
      {
        intDay = parseInt(RegExp.$3, 10);
        intMonth = parseInt(RegExp.$2, 10);
        intFullYear = parseInt(RegExp.$1, 10);
      }
      
      // If the day is less than 1, then is 1.
      if (intDay < 1) intDay = 1;
      
      // If the month is not between 1 and 12, return false.
      if (intMonth < 1 || intMonth > 12) return false;

      // Validate the type of month.
      switch (aintMonthType[intMonth - 1])
      {
        // If month has only 30 days...
        case 0:
          // If the day is greater that 30, then is 30.
          if (intDay > 30) intDay = 30;
          break;
        // If month has only 31 days...
        case 1:
          // If the day is greater that 31, then is 31.
          if (intDay > 31) intDay = 31;
          break;
        // If month has only 28/29 days...
        case 2:
          // If is a leap year, ...
          if (IsLeapYear(intFullYear))
          {
            // If the day is greater that 29, then is 29.
            if (intDay > 29) intDay = 29;
          }
          else
          {
            // If the day is greater that 28, then is 28.
            if (intDay > 28) intDay = 28;
          }
          break;
      }
      
      // Return the date.
      return new Date(intFullYear, intMonth - 1, intDay);
    }
  }
  return false;
}

/******************************************************************************
'Function: Date2String()
'Purpose:  This function transforms a date to a string.
'Inputs:   dteDate - given date (optional).  If not given returns today's date.
'          strSeparator - char used to separate the date items (optional). 
'                         If not given uses '/'. 
'Returns:  The result date in the dd/mm/yyyy format.
'******************************************************************************
' Author   Date       Comments
' -------- ---------- ---------------------------------------------------------
' JGP/V    2003.03.24 Creation of the function.
******************************************************************************/
function Date2String()
{
  // Declaration  of the local variables.
  var rex = /^[\/\-\.]$/;
  var result;

  // If no parameter was given uses today's date and '/'.
  if (arguments.length == 0) return Date2String(new Date(), '/');
  
  // If only one parameter was given, ...
  if (arguments.length == 1)
  {
    // If the parameters is the separator, use it with today's date.
    if (arguments[0].length == 1)
    {
      return Date2String(new Date(), arguments[0]);
    }
    // Else, use the parameter has the date with the default separator.
    else
    {
      return Date2String(arguments[0], '/');
    }
  }
  
  // Validation of the parameters.
  if (arguments[0] == null || arguments[1] == null) return false;
  
  // Validation of the separator char.
  if (!rex.test(arguments[1])) return false;
  
  try
  {
    // Add the day.
    if (arguments[0].getDate() < 10) 
    {
      result = '0' + arguments[0].getDate();
    }
    else
    {
      result = '' + arguments[0].getDate();
    }
    
    result += arguments[1];
    
    // Add the month.
    if (arguments[0].getMonth() < 9) 
    {
      result += '0' + (arguments[0].getMonth() + 1);
    }
    else
    {
      result += '' + (arguments[0].getMonth() + 1);
    }
    
    // Add the full year.
    result += arguments[1] + arguments[0].getFullYear();
    
    // Return the result.
    return result;
  }
  catch(e)
  {
    // In case of any errors, return false.
    return false;
  }
}

/******************************************************************************
'Function: AddDateDays()
'Purpose:  This function adds a given number of days to a given date.
'Inputs:   dteDate - given date
'          intDays - given number of days to be added
'Returns:  The result date.
'******************************************************************************
' Author   Date       Comments
' -------- ---------- ---------------------------------------------------------
' JGP/V    2003.03.24 Creation of the function.
******************************************************************************/
function AddDateDays(dteDate, intDays){
  var dteResult;

  if (dteDate == null || intDays == null) return false;
  
  try
  {
    dteResult = new Date();
    dteResult.setTime(dteDate.getTime() + (intDays*24*60*60*1000));
    
    return dteResult;
  }
  catch(e)
  {
    return false;
  }
}

/******************************************************************************
'Function: AddDateDaysS()
'Purpose:  This function adds a given number of days to a given date.
'Inputs:   strDate - given date in the dd/mm/yyyy format
'          intDays - given number of days to be added
'Returns:  The result date in the dd/mm/yyyy format.
'******************************************************************************
' Author   Date       Comments
' -------- ---------- ---------------------------------------------------------
' JGP/V    2003.03.20 Creation of the function.
******************************************************************************/
function AddDateDaysS(strDate, intDays){
  var dteDate;
  
  if (strDate == null || intDays == null) return false;
  
  dteDate = String2Date(strDate);
  if (dteDate != false)
  {
    dteDate = AddDateDays(dteDate, intDays);
  }
  
  return Date2String(dteDate);
}
/******************************************************************************
'Function: DateAdd()
'Purpose:  This function adds 365 days to today's date.
'******************************************************************************
' Author   Date       Comments
' -------- ---------- ---------------------------------------------------------
' Nuno Fonseca    2003.03.06 Creation of the function.
******************************************************************************/

function GetDate(nrd){
var DateAdd ;
DateAdd = nrd;
var now = new Date();
var newDate = new Date();
var dtDif = newDate.getTime() + (DateAdd*24*60*60*1000);
newDate.setTime(dtDif);
future = newDate.toLocaleDateString();
day = newDate.getDate();
if (day < 10){
day = '0' + day}
month = newDate.getMonth() + 1;
if (month < 10){
month = '0' + month}
year = newDate.getFullYear();
futuref = (day + '/' + month + '/' + year)
}

/******************************************************************************
'Function: ChangeCountry()
'Purpose:  This function changes the server in the URL.
'Inputs:   none
'Returns:  nothing
'******************************************************************************
' Author   Date       Comments
' -------- ---------- ---------------------------------------------------------
' JGP/V    2004.03.04 Creation of the function.
' JGP/V    2004.07.28 Changed to accept "es.*".
******************************************************************************/
function ChangeCountry(country){
	// JB - 2010.03.29 - Melhorias AdP / Melhorias Multibrowser F4
    var objXMLHTTP = W3CNewObject('xmlhttp');
    
	objXMLHTTP.open('POST','/_generic/code/js/ChangeCountryXMLHTTP.asp', false);
	objXMLHTTP.send('<root><country>' + country + '</country></root>');

    delete(objXMLHTTP); 
	
	//FG 2010-04-06 BEGIN ADP Improvements
	if(BrowserDetect.browser == "Safari" && (document.URL.match(/Ver_Requisicao.asp/i) || document.URL.match(/Ver_Formulario.asp/i) || document.URL.match(/Criar_Proposta.asp/i)))
	{
		//Create form
		newform=document.createElement("form");
		newform.setAttribute('action', window.location);		
		newform.setAttribute('method','POST');
		
		//Get Parameters to Post
		var i = 0;
		for (i = 0; i < objFormKeys.length; i++)
		{
			var parm1 = document.createElement("input");
			parm1.setAttribute("id", objFormKeys[i]);
			parm1.setAttribute("name", objFormKeys[i]);
			parm1.setAttribute("type", "hidden");
			parm1.setAttribute("value", objFormValues[i]);

			newform.appendChild(parm1);
		}	
		
		//Submit Values
		newform.submit();
	}
	else 
	{
		window.location.reload();
	}	
	//FG 2010-04-06 END ADP Improvements
}

/******************************************************************************
'Function: trim()
'Purpose:  This function trims a string.
'Inputs:   strInput - input string;
'Returns:  string without spaces in the begin and the end.
'******************************************************************************
' Author   Date       Comments
' -------- ---------- ---------------------------------------------------------
' JGP/V    2004.07.22 Creation of the function.
******************************************************************************/
function trim(strInput){
	var strResult;
	var objRegex = new RegExp('(^\\s+)|(\\s+$)');
	strResult = strInput.replace(objRegex, '');
	return (strResult);
}

/******************************************************************************
'Function: CreateObjectXML()
'Purpose:  This function returns a xmlHTTP object or a xml object.
'Inputs:   strObjectName - type of object (xml or xmlhttp).
'Returns:  Returns a xmlHTTP object or a xml object.
'******************************************************************************
' Author   Date       Comments
' -------- ---------- ---------------------------------------------------------
' JGP/V    2004.07.30 Creation of the function.
******************************************************************************/
function CreateObjectXML(strObjectName)
{
	var obj;
	switch (strObjectName)
	{
	  case 'xmlhttp':
	    try{ obj = new ActiveXObject('MSXML2.XMLHTTP'); }
		  catch(e){ try { obj = new ActiveXObject('MSXML.XMLHTTP'); }
			          catch(e) { obj = new ActiveXObject('Microsoft.XMLHTTP'); } }
			break;
	  case 'xml':
	    try { obj = new ActiveXObject('MSXML2.DomDocument'); }
	    catch(e) { try { obj = new ActiveXObject('MSXML.DomDocument'); }
				         catch(e) { obj = new ActiveXObject('Microsoft.DomDocument');}}
			obj.async = false;
			break;
	  default:
	    obj = null;
	}
	return obj;
}

/******************************************************************************
'Function: AddXMLAttribute()
'Purpose:  This function adds or updates an attribute from a node.
'Inputs:   xmlNode - XML node object
'          strAttrName - name of the attribute to be added or updated
'          strAttrValue - value to be set in the attribute
'Returns:  True - OK, False - Error
'******************************************************************************
' Author   Date       Comments
' -------- ---------- ---------------------------------------------------------
' JGP/V    2004.07.22 Creation of the function.
******************************************************************************/
function AddXMLAttribute(xmlNode, strAttrName, strAttrValue)
{
  var xmlDoc, alstAttributes, attr, newAttr;
  
  try
  {
    xmlDoc = xmlNode.ownerDocument;
    alstAttributes = xmlNode.attributes;
    attr = alstAttributes.getNamedItem(strAttrName);
    if (attr == null)
    {
      newAttr = xmlDoc.createAttribute(strAttrName);
      newAttr.value = strAttrValue;
      alstAttributes.setNamedItem(newAttr);
    }
    else
    {
      attr.value = strAttrValue;
    }
    return true;
  }
  catch (e)
  {
    return false;
  }
}

/******************************************************************************
'Function: AddXMLChild()
'Purpose:  This function adds a child to a specific node.
'Inputs:   xmlNode - XML node object
'          strChildName - name of the child to be added
'Returns:  New Element - OK, null - Error
'******************************************************************************
' Author   Date       Comments
' -------- ---------- ---------------------------------------------------------
' JGP/V    2004.07.22 Creation of the function.
******************************************************************************/
function AddXMLChild(xmlNode, strChildName){
  var xmlDoc, newElm;
  
  try{
    xmlDoc = xmlNode.ownerDocument;
    newElm = xmlDoc.createElement(strChildName);
    xmlNode.appendChild(newElm);
    return newElm;
  }catch (e){
    return null;
  }
}

/******************************************************************************
'Function: DelXMLChild()
'Purpose:  This function removes a child node from a specific node.
'Inputs:   xmlNode - XML node object where the child is
'          xmlChild - XML node object to be removed
'Returns:  True - OK, False - Error
'******************************************************************************
' Author   Date       Comments
' -------- ---------- ---------------------------------------------------------
' JGP/V    2004.07.22 Creation of the function.
******************************************************************************/
function DelXMLChild(xmlNode, xmlChild){
	try{xmlNode.removeChild(xmlChild);return true;}
	catch (e){return false;}
}

    function msieversion(){
		var ua = window.navigator.userAgent
        var msie = ua.indexOf ( "MSIE " )      
        if (msie > 0){return parseFloat (ua.substring (msie + 5, ua.indexOf (".", msie ) + 2));}else{return 0;}
      }
	
	function verifyversion(){      
		if ( msieversion() < 6 ){
			var intResult = createPopupMsg(this, 2, "Versão do Browser desactualizada", "O econstroi.com está optimizado para Internet Explorer 6.0 ou superior.<BR>O programa que tem instalado é mais antigo e poderá não executar todas as funcionalidades.<BR>Por favor actualize a sua versão clicando em <A onclick='returnValue=1;window.close();' href='#' style='color: #FFCC00'>português</A> ou <A onclick='returnValue=2;window.close();' href='#'  style='color: #FFCC00'>inglês</A>.", 700, 195);
			if (intResult == 1){window.location='_generic/media/ie6setupPT.exe';}
			if (intResult == 2){window.location='_generic/media/ie6setupOR.exe';}
        }
      }
	
      function securesite(){
		if (getCookie("ecseguro") == null || getCookie("ecseguro") == "null"){
			switch(getLang()){
			case '2': 
				var intResult = createPopupMsg(this, 2, "Alerta de Seguridad", 
				"<SPAN class='SmallLetterDGray'>" +
				"Está a punto de entrar en un <A id='test' href='#' " +
				"onclick='returnValue=2;window.close();'>sitio " +
				"seguro</a>.<BR><BR>" +
				"Toda la información que introduzca no podrá ser " +
				"vista por nadie más en Internet.<BR><BR>" +
				"<INPUT type='checkbox' name='chkSecure' value='1' " +
				"onchange='returnValue=this.value;'>" +
				"En el futuro, no quiero volver a ver este aviso." +
				"</SPAN>", 350, 195);
				break;
			case '3':
				var intResult = createPopupMsg(this, 2, "Security Alert", 
				"<SPAN class='SmallLetterDGray'>" +
				"You are entering a secure web " +
				"site.<BR><BR>" +
				"Any given information will not be seen by others.<BR><BR>" +
				"<INPUT type='checkbox' name='chkSecure' value='1' " +
				"onchange='returnValue=this.value;'>" +
				"In the future, I do not want this alert to be shown." +
				"</SPAN>", 350, 195);
				break;
			default: 
				var intResult = createPopupMsg(this, 2, "Alerta de Segurança", 
				"<SPAN class='SmallLetterDGray'>" +
				"Está prestes a entrar num <A id='test' href='#' " +
				"onclick='returnValue=2;window.close();'>sítio " +
				"seguro</a>.<BR><BR>" +
				"Qualquer informação que disponibilize não poderá ser " +
				"vista por mais ninguém na Internet.<BR><BR>" +
				"<INPUT type='checkbox' name='chkSecure' value='1' " +
				"onchange='returnValue=this.value;'>" +
				"Futuramente, não quero ver de novo este aviso" +
				"</SPAN>", 350, 195);
				break;
			}

			if (intResult == 1){
				setCookie("ecseguro", "true");
			}else if (intResult == 2){
				var result = window.showModalDialog("/info/seguranca/infoSeguranca.asp", null,"dialogWidth: 700px; dialogHeight: 510px; center: Yes; help: No; status: No; scroll: Yes; resizable: Yes");
		            
				if (result == 1){
				result = window.showModalDialog("/info/seguranca/infoEstatutos.asp", null,"dialogWidth: 400px; dialogHeight: 360px; center: Yes; help: No; status: No; scroll: No;");
				}
			}
		}
      }
      
      
      
            /*Funcao para alerta da nova imagem do econstroi */
      /* PL 20071009 */
      function fnNewHomepageAlert(){

        if (getCookie("ecnewhomepage") == null || getCookie("ecnewhomepage") == "null"){
				 var intResult = createPopupMsg(this, 2, "Hoje foi lançado o novo site econstroi.", 
				"<SPAN class='LetterMedDGray'>" +
				"<B>O novo econstroi visa facilitar o acesso à informação por parte de todos os utilizadores.<BR>"+
				"Para o efeito, entre outras, foram introduzidas algumas mudanças no menu principal, que incorpora agora informação sobre os mercados e soluções disponíveis nas plataformas Vortal.<BR>"+
				"A navegação é agora mais clara, funcional e simples, facilitando e agilizando o acesso à informação.<BR><BR>"+
				"Esta melhoria terá um reduzido impacto na utilização do mercado electrónico, mantendo-se a área de trabalho inalterada.</B>"+
				"</SPAN>", 480, 255);	
				
			setCookie("ecnewhomepage", "true");
							
        }
        
        
      }
      
      
      /*	BF 20090108	*/
      function fnGerirCertificadosError(){
	//	fnMostraIndisponibilidade('Esta funcionalidade só está disponível a utilizadores que fizeram login com autenticação por certificado digital.',null,'Continuar',null,null, 100);
		alert('Esta funcionalidade só está disponível a utilizadores que fizeram login com autenticação por certificado digital.');
      }
      
      //função que perrmite gerir os certificados digitais
      function fnGerirCertificados()
      {

			window.open('/Portal.WebUI/Generic/ManageDigitalCertificates.aspx',null,'toolbar=no menubar=no location=no directories=no resizable=no width=900px height=520px left=20px top=20px scrollbars=no');
	
      }

      function onloadmain(){verifyversion();securesite();}
