/* Métodos/Funções */

/* Definição dos portais  */
var portais=new Array();
portais[0] = new Array();
portais[0][0]="3715158"; //ID
portais[0][1]="SwPt"; //Nome

/*Gestao de cookies*/
function setCookie(c_name,value,expiredays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate()+expiredays);
document.cookie=c_name+ "=" +escape(value)+((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}

function getCookie(c_name)
{
if (document.cookie.length>0)
  {
  c_start=document.cookie.indexOf(c_name + "=");
  if (c_start!=-1)
    {
    c_start=c_start + c_name.length+1;
    c_end=document.cookie.indexOf(";",c_start);
    if (c_end==-1) c_end=document.cookie.length;
    return unescape(document.cookie.substring(c_start,c_end));
    }
  }
return "";
}

function checkCookie(cookieName)
{
  var varCookie=getCookie(cookieName);
  if (varCookie!=null && varCookie!=""){
    return true;  
  }
  else{
    return false;
  }
}


/* Ler um ficheiro CSS/JS dinamicamente */
function loadjscssfile(filename, filetype){
 if (filetype=="js"){ //if filename is a external JavaScript file
  var fileref=document.createElement('script')
  fileref.setAttribute("type","text/javascript")
  fileref.setAttribute("src", filename)
 }
 else if (filetype=="css"){ //if filename is an external CSS file
  var fileref=document.createElement("link")
  fileref.setAttribute("rel", "stylesheet")
  fileref.setAttribute("type", "text/css")
  fileref.setAttribute("href", filename)
 }
 if (typeof fileref!="undefined")
  document.getElementsByTagName("head")[0].appendChild(fileref)
}


/* obter um determinado parametro do URL - GUP: Get URL Parameter */
function gup( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}
/* Atribuir um valor ao comentario mesmo antes de ser efectuado o submit */
function addSubmitValue(pIDText) {
  //Atribuir o valor ao Comentario
  var CustomerComment = document.getElementsByName("CustomerComment")[0];
  var strCustomerComment = CustomerComment.value;
  if( strCustomerComment.indexOf("###") == -1 ){
    //Ainda não tem ID - colocar ID
    CustomerComment.value = pIDText + CustomerComment.value;
  }
  return true;
}



/* Alterar o logo do site no elemento ShopLogo */
function ChangeLogoImg()
{
	var divs=document.getElementsByTagName('div');
	for(var i=0;i<divs.length;i++)
	{
		var isThatClass = cssjs('check',divs[i],'ShopLogo');
		if (isThatClass){
      var insideElements = divs[i].getElementsByTagName('img');
			//insideElements[0].src = "http://scripts.hmedia.com/SensualEmotion/img/barrasite.png";
			insideElements[0].src = "http://scripts.hmedia.com/SensualEmotion/img/barrasite.png";
      divs[i].style.display ="block";
		}
	}
}
/* Alterar o logo do site no elemento ShopLogo */
function showLogoImg()
{
	var divs=document.getElementsByTagName('div');
	for(var i=0;i<divs.length;i++)
	{
		var isThatClass = cssjs('check',divs[i],'ShopLogo');
		if (isThatClass){
      divs[i].style.display ="block";
		}
	}
}
/* Aplicar um determinada acção num elemento, neste caso verifica-se se o elemento existe */
function cssjs(a,o,c1,c2)
{
  switch (a){
    case 'swap':
      o.className=!jscss('check',o,c1)?o.className.replace(c2,c1):o.className.replace(c1,c2);
    break;
    case 'add':
      if(!jscss('check',o,c1)){o.className+=o.className?' '+c1:c1;}
    break;
    case 'remove':
      var rep=o.className.match(' '+c1)?' '+c1:c1;
      o.className=o.className.replace(rep,'');
    break;
    case 'check':
      return new RegExp('\\b'+c1+'\\b').test(o.className)
    break;
  }
}
function sendEmail(){
  var isOrderLastStep = document.getElementById("AcceptTAC");
  if (isOrderLastStep != null){
    if (isOrderLastStep.checked){
    //alert("SM");
      var easymail=new Mail();
      easymail.To="hfelix@viamodul.pt (Helio Felix)";
      //easymail.Cc="";
      //Add the BCC address
      //easymail.Bcc="";
      //Now set the address of the one that sends the email
      easymail.ReplyTo="hfelix@viamodul.pt (Helio Felix)";
      //Now set the subject of the email
      easymail.Subject="[sensualemotion;portal:"+portais[sessvars.portal.portalid][1]+"]";
      //Set the message of the email
      easymail.Message="PortalID:"+sessvars.portal.portalid+";<br />PortalName:"+portais[sessvars.portal.portalid][1]+";<br />GrandTotal:"+sessvars.GrandTotal+";<br />CustomerInfo:"+sessvars.CustomerInfo;
      //Send the email
      easymail.Send();
    }
  }
}

/* obter um determinado parametro do URL definido pelo user - GUP: Get URL Parameter */
function gupURL( url, name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( url );
  if( results == null )
    return "";
  else
    return results[1];
}
// Alterar todos os urls do site para que funcinem em SSL - https
function ChangeAllUrl(){
// Alterar em todos os links <a href="...">
	var as=document.getElementsByTagName('a');
	for(var i=0;i<as.length;i++)
	{
		var str =""+as[i].href;
		var ssl = str.charAt(4);
		var lastChar = str.charAt(str.length-1);
		if (ssl=="s"){
		  //alert("str: " + str);
			var caracterUrl = ((str).indexOf("?")==-1)?"?":"&";
			if (lastChar=="/"){
				var len = str.length-1;
				var semUltimoChar = str.substr(0,len);
				str = ""+semUltimoChar;
			}
			var hasPortal = gupURL( str, "portal" );
			if (!hasPortal){
				str += caracterUrl+"portal="+sessvars.portal.isPortal;
			}
			var hasPortalID = gupURL( str, "portalid" );
			if (!hasPortalID){
				str =  str + "&portalid="+sessvars.portal.portalid;
			}
			
			as[i].href = str;
		}
	}
// Alterar em todos os forms <form action="...">
	var forms=document.getElementsByTagName('form');
	for(var i=0;i<forms.length;i++)
	{
		var str =""+forms[i].action;
		var ssl = str.charAt(4);
		var lastChar = str.charAt(str.length-1);
		if (ssl=="s"){
		  //alert("str: " + str);
			var caracterUrl = ((str).indexOf("?")==-1)?"?":"&";
			if (lastChar=="/"){
				var len = str.length-1;
				var semUltimoChar = str.substr(0,len);
				str = ""+semUltimoChar;
			}
			var hasPortal = gupURL( str, "portal" );
			if (!hasPortal){
				str += caracterUrl+"portal="+sessvars.portal.isPortal;
			}
			var hasPortalID = gupURL( str, "portalid" );
			if (!hasPortalID){
				str =  str + "&portalid="+sessvars.portal.portalid;
			}
			
			forms[i].action = str;
		}
	}
}

/* Função que efectua as alterações ao site é como o arranque no caso de ser um Portal */
function initPortalMode() {
  ChangeLogoImg();
  
  var PortalSugestion = document.getElementById('PortalSugestion');
  if (PortalSugestion != null){
    PortalSugestion.innerHTML = portais[sessvars.portal.portalid][1];
  }
  
  var PortalShopSuggestion = document.getElementById('PortalShopSuggestion');
  if (PortalShopSuggestion != null){
    PortalShopSuggestion.style.display = "block";
  }

  var isBasket = document.getElementById("BasketForm");
  if (isBasket != null){
  
    var CustomerComment = document.getElementsByName("CustomerComment")[0];
    var strCustomerComment = CustomerComment.value;
    var PortalIDText = "Origem de "+portais[sessvars.portal.portalid][1]+" ("+sessvars.portal.portalid+") ###";
    sessvars.portalIDText = PortalIDText;
    
  
    //remover da textarea - manter em sessão
    var temp = new Array();
    temp = strCustomerComment.split('###');
    if (temp[1] != undefined){
      CustomerComment.value = temp[1];
    }
    
    //Altero o botão pagar/actualizar para que quando foi efectuado o submit para colocar o texto que está no hidden
    //id="RefreshButton"
    //Save
    var Save = document.getElementsByName("Save");
    for (var intI = 0; intI < Save.length; intI++) {
        var currentOnclick = Save[intI].getAttribute('onclick');
        Save[intI].setAttribute('onclick','addSubmitValue(\''+PortalIDText+'\');'+currentOnclick);
    }
    //id="CheckOut"
    //SaveAndDoOrder
    var SaveAndDoOrder = document.getElementsByName("SaveAndDoOrder");
    for (var intI = 0; intI < SaveAndDoOrder.length; intI++) {
        var currentOnclick = SaveAndDoOrder[intI].getAttribute('onclick');
        SaveAndDoOrder[intI].setAttribute('onclick','addSubmitValue(\''+PortalIDText+'\');'+currentOnclick);
    }
  }


  /* Para definir o ID do portal no registo de cliente */
  var hasFirstName = document.getElementById("OutrosProdutos");
  if (hasFirstName != null){
    var portal = document.getElementsByName("Portal")[0];
    if (portal != null){
      for (var intI = 0; intI < portal.options.length; intI++) {
        if (portal.options[intI].value == portais[sessvars.portal.portalid][0]) {
          portal.options[intI].selected = true;
          portal.parentNode.parentNode.style.display = "none";
        }
      }
    }
  }
  
  var isOrderLastStep = document.getElementById("AcceptTAC");
  if (isOrderLastStep != null){
    // obter o valor da compra
    var tds=document.getElementsByTagName('td');
  	for(var i=0;i<tds.length;i++)
  	{
  		var isThatClass = cssjs('check',tds[i],'Total');
  		if (isThatClass){
  			sessvars.GrandTotal = tds[i].innerHTML;
  		}
  	}
  	//obter o cliente
  	var divs=document.getElementsByTagName('div');
  	for(var i=0;i<divs.length;i++)
  	{
  		var isCustomerInfo = cssjs('check',divs[i],'CustomerInfo');
  		if (isCustomerInfo){
  		sessvars.CustomerInfo = divs[i].innerHTML;
  		}
  	}
    
    //Altero o botão pagar/actualizar para que quando foi efectuado o submit para colocar o texto que está no hidden
    //id="RefreshButton"
    //Save
    var Save = document.getElementsByName("Save");
    for (var intI = 0; intI < Save.length; intI++) {
        var currentOnclick = Save[intI].getAttribute('onclick');
        Save[intI].setAttribute('onclick','sendEmail();'+currentOnclick);
    }
  }
  ChangeAllUrl();  
}



function initNormalMode() {
  showLogoImg();
  /* Para definir o ID do portal no registo de cliente */
  var hasFirstName = document.getElementById("OutrosProdutos");
  
  if (hasFirstName != null){
    var portal = document.getElementsByName("Portal")[0];
    if (portal != null){
      var portalParent = portal.parentNode.parentNode;
      portalParent.style.display = "none";
    }
  }
  
  var PortalShopSuggestion = document.getElementById('PortalShopSuggestion');
  if (PortalShopSuggestion != null){
    PortalShopSuggestion.style.display = "block";
  }
}



/* Main */

/* obter os identificadores do portal em causa */
if ( gup('portal') ){
  var isPortal = gup( 'portal' );
  var portalID = gup( 'portalid' );
  sessvars.portal = {isPortal: isPortal, portalid: portalID};
  // definir valores em cockie
  setCookie('isPortal',isPortal,1);
  setCookie('portalid',portalID,1);
}
else{
  if (sessvars.portal != undefined && sessvars.portal.isPortal == 1){
    // definir valores em cockie
    setCookie('isPortal',sessvars.portal.isPortal,1);
    setCookie('portalid',sessvars.portal.portalid,1);
  }  
}

/* Aplicação de novos estilos e configurações caso seja um acesso de outro portal */
// Se não existir sessão verifica se os dados do portal estão guardadods num cookie 
if(sessvars.portal == undefined){
  if (checkCookie('isPortal') && checkCookie('portalid')){
    sessvars.portal = {isPortal: getCookie('isPortal'), portalid: getCookie('portalid')};
  }
}
// Verifica a existencia de sessão e a definição de portal
if (sessvars.portal != undefined && sessvars.portal.isPortal == 1){
  //loadjscssfile("http://scripts.hmedia.com/SensualEmotion/newstyles.css", "css")
  loadjscssfile("http://scripts.hmedia.com/SensualEmotion/newstyles.css", "css")
  window.onload = initPortalMode;  
}
else{
  window.onload = initNormalMode;
}
