var code = 1;
var userid		= null;
var useridint	= null;
var r_aux = null;
var userName_aux = null;

function enviaLogin(){
	document.getElementById("frmLogin").submit();
}

function les_teves_dades() {
  document.getElementById("myform").submit();
}
						
// Obté resultat de la petició remota
// ==0 : OK, !=0 : KO
function getResultCode(result) {
	return result ? result.documentElement.getElementsByTagName("code")[0].firstChild.data : -1;
}

// obté un valor del xml resposta
function retrieveValueFromXml(result, fieldName, defaultValue) {
	return result!=null && result.documentElement.getElementsByTagName(fieldName)[0]!=null ? 
		result.documentElement.getElementsByTagName(fieldName)[0].firstChild.data : defaultValue;
}

// Obté resultat de la petició remota
// pos0 : estat (==0:OK, !=0:KO); pos1 : camp 'data'; pos2 : user name (nick); pos3 : user idint


function getResultAdvanced(result) {
	var xml_result	= new Array();
	if (result!=null) {
		xml_result[0]	= retrieveValueFromXml(result, "code", -1);
		xml_result[1]	= retrieveValueFromXml(result, "data", null);
		xml_result[2]	= retrieveValueFromXml(result, "USERID", null);
		xml_result[3]	= retrieveValueFromXml(result, "USERIDINT", null);
		code			= xml_result[0];
		userid			= xml_result[2];
		useridint		= xml_result[3];
	} else {
		xml_result[0]	= code;
		xml_result[1]	= null;
		xml_result[2]	= userid;
		xml_result[3]	= useridint;
	}
	return xml_result;
}
		
		
function genericFunctionLogin3cat24(id, result){
	var arr = getResultAdvanced(result);
	var code = 1;
	var userid = "";
	var doclocation = ""+document.location;
	var iBaseProtocol = doclocation.indexOf("//");
	var iBaseUrl = doclocation.indexOf("/",iBaseProtocol+2);
	var baseurl = doclocation.substring(0,iBaseUrl);
	var basesecurl = "https://secure.ccrtvi.com";
	
	var v_url = escape(document.location);	
	v_url.replace("&","&amp;");
	
	if ( arr[0]==0 ) {	
	 	var divToShow =	'<ul>';
		divToShow +=			'	<li class="dadesUser"><a href="javascript:les_teves_dades()" title="Les teves dades">Les teves dades</a></li>';
		divToShow +=			'	<li class="">Hola <strong>'+arr[2]+'</strong>, ja ets dins</li>';
		divToShow +=			'	<li class=""><a href="https://secure.ccrtvi.com/su/Register?hiPersist=true&amp;hiTarget=http://www.324.cat/pnoticies/g.jsp?url=' + escape(document.location) + '&amp;hiAction=0" title="Surt">Surt</a></li>';
		divToShow +=			'	<li class="elmeu3cat24"><a href="/elmeu324/" title="El meu 324 - L\'espai de participació">Elmeu324</a></li>';
		divToShow +=			'</ul>';
		divToShow +=			'<form name="myform" id="myform" action="http://www.324.cat/su/Register" method="post">';
		divToShow +=			'<input name="hiAction" type="hidden" value="33"/>';
		divToShow +=			'<input name="hiServiceId" type="hidden" value="CITN_REG"/>';
		divToShow +=			'<input name="hiRegServiceId" type="hidden" value="CITN_REG"/>';
		divToShow +=			'<input name="hiTarget" type="hidden" value="not_P01.jsp"/>';
		divToShow +=			'<input name="hiErrTarget" type="hidden" value="error.jsp"/>';
		divToShow +=			'<input name="hiPortal" type="hidden" value="not"/>';
		divToShow +=			'</form>';


	 	var divTarget = document.getElementById('logged');
		divTarget.innerHTML = divToShow;
	}
	
} 

function genericFunctionLogin3cat24CGU(id, result){
	var arr = getResultAdvanced(result);
	var code = 1;
	var userid = "";
	var doclocation = ""+document.location;
	var iBaseProtocol = doclocation.indexOf("//");
	var iBaseUrl = doclocation.indexOf("/",iBaseProtocol+2);
	var baseurl = doclocation.substring(0,iBaseUrl);
	var basesecurl = "https://secure.ccrtvi.com";
	
	var v_url = escape(document.location);	
	v_url.replace("&","&amp;");
	
	if ( arr[0]==0 ) {	
 		if(enviaOk==""){
  		if (document.location == "http://www.324.cat/envia") {
  			window.location.href = "http://www.324.cat/pnoticies/1024ParticipacioUpload.jsp?seccio=upload&username="+arr[2];
  		}
  		else {
  			window.location.href = "http://www.324.cat/pnoticies/1024ParticipacioUploadKioskJove.jsp?seccio=upload&username="+arr[2];
  		}
  	}
  	  
  	var urllogout = "http://www.324.cat/envia";  	
  	if (document.location.href.match("1024ParticipacioUploadKioskJove.jsp")) {  	
  		urllogout = "http://www.324.cat/enviakioskjove";
		} 	
				
	 	var divToShow =	'<ul>';
		divToShow +=			'	<li class="dadesUser"><a href="javascript:les_teves_dades()" title="Les teves dades">Les teves dades</a></li>';
		divToShow +=			'	<li class="">Hola <strong>'+arr[2]+'</strong>, ja ets dins</li>';
		divToShow +=			'	<li class=""><a href="https://secure.ccrtvi.com/su/Register?hiPersist=true&amp;hiTarget=http://www.324.cat/pnoticies/g.jsp?url=' + urllogout + '&amp;hiAction=0" title="Surt">Surt</a></li>';
		divToShow +=			'	<li class="elmeu3cat24"><a href="/elmeu324/" title="El meu 324 - L\'espai de participació">Elmeu324</a></li>';
		divToShow +=			'</ul>';
		divToShow +=			'<form name="myform" id="myform" action="http://www.324.cat/su/Register" method="post">';
		divToShow +=			'<input name="hiAction" type="hidden" value="33"/>';
		divToShow +=			'<input name="hiServiceId" type="hidden" value="CITN_REG"/>';
		divToShow +=			'<input name="hiRegServiceId" type="hidden" value="CITN_REG"/>';
		divToShow +=			'<input name="hiTarget" type="hidden" value="not_P01.jsp"/>';
		divToShow +=			'<input name="hiErrTarget" type="hidden" value="error.jsp"/>';
		divToShow +=			'<input name="hiPortal" type="hidden" value="not"/>';
		divToShow +=			'</form>';


	 	var divTarget = document.getElementById('logged');
		divTarget.innerHTML = divToShow;
	}
	
} 

/* Noves funcions per optimitzar el proces de LOGIN */

  function getCookie(name) {
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf(";" + prefix);
    if (begin == -1) {
     begin = dc.indexOf("; " + prefix);
     if (begin == -1) {
      begin = dc.indexOf(prefix);
      if (begin != 0) return null;
     } else begin += 2;
    } else {
     begin += 1;
    }
    var end = dc.indexOf(";", begin);
    if (end == -1) {
     end = dc.length;
    }
    return unescape(dc.substring(begin + prefix.length, end));
  }
  
  function getXmlSerialized(xmlstring) { 
   if (document.implementation.createDocument && typeof DOMParser!='undefined') {
     return new DOMParser().parseFromString(xmlstring, "text/xml");
   } else if (typeof XMLSerializer!='undefined') {
     return new XMLSerializer().serializeToString(xmlstring);
   } else if (xmlstring.xml) {
     return xmlstring.xml;
   } else if (window.ActiveXObject) {
        var dom = new ActiveXObject("Microsoft.XMLDOM");
        dom.async="false"; 
        dom.loadXML(xmlstring);
        return dom;
    } else return null;
  }  
  
  function getDateGMT(l) {
   var d = new Date();
   d.setTime(l);
   return d.toGMTString();
  }
     
  function CheckValidCookieUser(dbg) {
   var r = getCookie("__USERDATA__"); 
   var r2 = getCookie("__USERDATA__TIMECHECK__");
   var now = new Date().getTime();
   var r2fix = ((r2==null || r2=='' || r2=='null')?0:(r2*1));
   var diff = (r2fix-now);
   var ret = (
    r!=null && r!='' && r!='null' && r.indexOf("<code>0</code>")>-1 //check that userdata found and valid
    && (r2==null || r2=='' || r2=='null' || (diff>0)) // check cookie time period valid or null
   );   
   if (dbg) {
    ret= ret + " ... "
    + " diff[" + diff
    + "] UDT[" + r2fix //+ " " + getDateGMT(r2fix)
    + "] now[" + now //+ " " + getDateGMT(now)
    + "] UD[" + r + "] "
    ;
   }
   return ret;
  }   
    
  var expireCheckCookieTime = 300*1000;  //expires in 5 minutes (milliseconds)            
  var urlgatewaybase = "http://www.324.cat/pnoticies/g.jsp";
  
  
  function checkUser() {
    if (!CheckValidCookieUser()) {
      var r = getCookie("_FOREIGN_SESSION_ID"); 
      if (r!=null && r!='' && r!='null'  || !(document.cookie)) {  
          loadXMLDoc(urlgatewaybase+"?a=1&t="+r+new Date().getTime(),false,"Login3cat24");
          var futdate = new Date();  //Get the current time and date
          var expdate = futdate.getTime();  //Get the milliseconds since Jan 1, 1970
          expdate += expireCheckCookieTime;  //expires in 5 minutes (milliseconds)       
          var newCookie="__USERDATA__TIMECHECK__=" + expdate +"; path=/;"; //Set the new cookie values up
          window.document.cookie=newCookie; //Write the cookie    
      } else {
       genericFunctionLogin3cat24(null, null);
      }
    } else {
      genericFunctionLogin3cat24(null, getXmlSerialized(getCookie("__USERDATA__")));
    } 
  }
  
  function checkUser2() {
    if (!CheckValidCookieUser()) {
      var r = getCookie("_FOREIGN_SESSION_ID"); 
      if (r!=null && r!='' && r!='null'  || !(document.cookie)) {  
          loadXMLDoc(urlgatewaybase+"?a=1&t="+r+new Date().getTime(),false,"CheckUserName");
          var futdate = new Date();  //Get the current time and date
          var expdate = futdate.getTime();  //Get the milliseconds since Jan 1, 1970
          expdate += expireCheckCookieTime;  //expires in 5 minutes (milliseconds)       
          var newCookie="__USERDATA__TIMECHECK__=" + expdate +"; path=/;"; //Set the new cookie values up
          window.document.cookie=newCookie; //Write the cookie    
      } else {
       genericFunctionCheckUserName(null, null);
      }
    } else {
      genericFunctionCheckUserName(null, getXmlSerialized(getCookie("__USERDATA__")));
    } 
  }

  function checkUserEnviaCGU(username) {
 		enviaOk = username;
    if (!CheckValidCookieUser()) {
      var r = getCookie("_FOREIGN_SESSION_ID"); 
      if (r!=null && r!='' && r!='null'  || !(document.cookie)) {  
          loadXMLDoc(urlgatewaybase+"?a=1&t="+r+new Date().getTime(),false,"Login3cat24CGU");
          var futdate = new Date();  //Get the current time and date
          var expdate = futdate.getTime();  //Get the milliseconds since Jan 1, 1970
          expdate += expireCheckCookieTime;  //expires in 5 minutes (milliseconds)       
          var newCookie="__USERDATA__TIMECHECK__=" + expdate +"; path=/;"; //Set the new cookie values up
          window.document.cookie=newCookie; //Write the cookie    
      } else {
       genericFunctionLogin3cat24CGU(null, null);
      }
    } else {
      genericFunctionLogin3cat24CGU(null, getXmlSerialized(getCookie("__USERDATA__")));
    }  		
  }
 

