var request;
var object;

var loadedobjects=""


function ExportaScript(texto){
   var ini, pos_src, fim, codigo;
    var objScript = null;
    ini = texto.indexOf('<script', 0)

    while (ini!=-1){
        var objScript = document.createElement("script");
        //Procura se existe algum src a partir do inicio do script
        pos_src = texto.indexOf(' src', ini)

        ini = texto.indexOf('>', ini) + 1;

        //Verifica se é um bloco de script ou include para um script
        if (pos_src < ini && pos_src >=0){//Se encontrou um "src" dentro da tag script, então é um include de um script

            //Marca o inicio do arquivo para depois do src
            ini = pos_src + 4;
            //Procura pelo ponto do nome da extencao do arquivo e marca para depois dele
            fim = texto.indexOf
('.', ini)+4;
            //Pega o nome do arquivo
            codigo = texto.substring(ini,fim);
            //Elimina do nome do arquivo os caracteres que possam ter sido pegos por engano
            codigo = 
codigo.replace("=","").replace(" ","").replace("\"","").replace("\"","").replace("\'","").replace("\'","").replace(">","");

            // Adiciona o arquivo de script ao objeto que sera adicionado ao documento
            objScript.src = codigo;
        }else{//Se nao encontrou um "src" dentro da tag script, esta e um bloco de codigo script

            // Procura o final do script
            fim = texto.indexOf('</script>', ini);
            // Extrai apenas o script
            codigo = texto.substring(ini,fim);
            // Adiciona o bloco de script ao objeto que sera adicionado ao documento

            objScript.text = codigo;
        }

        //Adiciona o script ao documento
        document.body.appendChild(objScript);
        // Procura a proxima tag de <script
        ini = texto.indexOf
('<script', fim);

        //Limpa o objeto de script
        objScript = null;
    }
}



/* Wrapper function for constructing a request object.
 Parameters:
  reqType: The HTTP request type, such as GET or POST.

  url: The URL of the server program.
  asynch: Whether to send the request asynchronously or not. */ 
function httpRequest(url,queryString,object,reqType,asynch) {
	 //Deafault Values
	  reqType = typeof(reqType) != 'undefined' ? reqType : 'POST';

	  asynch = typeof(asynch) != 'undefined' ? asynch : true;	
	
	   //Mozilla-based browsers
	   if (window.XMLHttpRequest) { request = new XMLHttpRequest(); }
	   //Internet Explorer
	   else if (
window.ActiveXObject) {
		  request = new ActiveXObject("Msxml2.XMLHTTP");
		  if (!request) { request = new ActiveXObject("Microsoft.XMLHTTP"); }
	   }
	   //the request could still be null if neither ActiveXObject

	   //initialization succeeded
	   if (request) { 
		  this.object = object;
		  initReq(reqType,url,asynch,queryString); 
	   }
	   else { 
	   		alert("Your browser does not permit the use of all of this application's features!"); 

		}
}

/* Initialize a request object that is already constructed.
 Parameters:
   reqType: The HTTP request type, such as GET or POST.
   url: The URL of the server program.
   isAsynch: Whether to send the request asynchronously or not. */

function initReq(reqType,url,isAsynch,queryString,object) {
   try {
      /* Specify the function that will handle the HTTP response */
      request.onreadystatechange=handleResponse;
      request.open(reqType,url,isAsynch);

      /* Set the Content-Type header for a POST request */
      if (reqType.toLowerCase() == "post") {
         request.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=ISO-8859-1");

         request.send(queryString);
      } 
      else { request.send(null); }
   }
   catch(errv) { 
   		alert("The application cannot contact the server at the moment. Please try again in a few seconds.\\n Error detail: "+errv.message); 

	}
}

//event handler for XMLHttpRequest
function handleResponse() {
   if (request.readyState == 1) {
      //document.getElementById(object).innerHTML = "<div align='center'></div><strong>Loading...</strong></div>"; 

//      document.getElementById("fullBody").style.display = "block";
   }
   if(request.readyState == 4) {
      if(request.status == 200) { 
	  
		var resposta=request.responseText;

		resposta=resposta.replace(/\+/g," ");
		resposta=unescape(resposta);
//  		document.getElementById(object).innerHTML = request.responseText; 
  		document.getElementById(object).innerHTML = resposta; 

		ExportaScript(resposta);
	  

//			handleFocus();
	  }
      else { 
	  	alert("A problem occurred with communicating between the XMLHttpRequest object and the server program."); 
	}

//     document.getElementById("fullBody").style.display =  "none";
   }
}




// Gestão de Paginas (Conteudo do site)-----------------------------------------------------------------------------
// Ajax - Wizzywigg ------------------------------------------------------------------------------------------------
var requestWW;
var objectTituloPagina;
var objectResumoPagina;
var objectConteudo;
var objectMenu;
var objectLingua;
var objectIdWebsite;

var objectIdPagina;
var objectComment;
var objectPublica;

/* Wrapper function for constructing a request object.
 Parameters:
  reqType: The HTTP request type, such as GET or POST.
  url: The URL of the server program.
  asynch: Whether to send the request asynchronously or not. */ 
function httpRequestWW(url,queryString,objectTituloPagina,objectResumoPagina,objectConteudo,objectMenu,objectLingua,objectIdWebsite,objectIdPagina,objectComment,objectPublica,reqType,asynch) {
	 //Deafault Values
	  reqType = typeof(reqType) != 'undefined' ? reqType : 'POST';
	  asynch = typeof(asynch) != 'undefined' ? asynch : true;	
	
	   //Mozilla-based browsers
	   if (window.XMLHttpRequest) { requestWW = new XMLHttpRequest(); }
	   //Internet Explorer
	   else if (window.ActiveXObject) {
		  requestWW = new ActiveXObject("Msxml2.XMLHTTP");
		  if (!requestWW) { requestWW = new ActiveXObject("Microsoft.XMLHTTP"); }
	   }
	   
	   //the request could still be null if neither ActiveXObject
	   //initialization succeeded
	   if (requestWW) { 
		  this.objectTituloPagina = objectTituloPagina;
		  this.objectResumoPagina = objectResumoPagina;
		  this.objectConteudo 	  = objectConteudo;
		  this.objectMenu 	  	  = objectMenu; 
	  	  this.objectLingua		  = objectLingua;
		  this.objectIdWebsite    = objectIdWebsite;
		  
		  this.objectIdPagina     = objectIdPagina;
		  this.objectComment      = objectComment;
		  this.objectPublica      = objectPublica;
		  
		  //Set Wizzywigg
		  if( document.getElementById('conteudo').style.display == "block"  )
		  			showDesign();
		  
		  initReqWW(reqType,url,asynch,queryString); 
	   }
	   else { alert("Your browser does not permit the use of all of this application's features!"); }
}

/* Initialize a request object that is already constructed.
 Parameters:
   reqType: The HTTP request type, such as GET or POST.
   url: The URL of the server program.
   isAsynch: Whether to send the request asynchronously or not. */
function initReqWW(reqType,url,isAsynch,queryString,object) {
   try {
      /* Specify the function that will handle the HTTP response */
      requestWW.onreadystatechange=handleResponseWW;
      requestWW.open(reqType,url,isAsynch);
      /* Set the Content-Type header for a POST request */
      if (reqType.toLowerCase() == "post") {
         requestWW.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
         requestWW.send(queryString);
		 lockPageSaving();
      } 
      else { requestWW.send(null); }
   }
   catch (errv) { 
   	alert("The application cannot contact the server at the moment. Please try again in a few seconds.\\n Error detail: "+errv.message);
   }
}

//event handler for XMLHttpRequest
function handleResponseWW() {
   if (requestWW.readyState == 1) {
      //document.getElementById(object).innerHTML = "<div align='center'></div><strong>Loading...</strong></div>"; 
      document.getElementById("fullBodySaving").style.display = "block";
   }
   if(requestWW.readyState == 4) {
      if(requestWW.status == 200) { 

		 	//Parsing XML
				xml = requestWW.responseText;

				var titulo     = getTagContent(xml,'whzzwgTituloPagina');
				var resumo     = getTagContent(xml,'whzzwgResumoPagina');
				var conteudo   = getTagContent(xml,'whzzwgConteudo');
				var menuId     = getTagContent(xml,'whzzwgId_menu');
				var id_Lg      = getTagContent(xml,'whzzwgId_lingua');
				var id_pagina  = getTagContent(xml,'whzzwgId_pagina');
				var id_website = getTagContent(xml,'whzzwgId_website');
				var publica    = getTagContent(xml,'whzzwgPublic');
				var comment    = getTagContent(xml,'whzzwgComment');
				
				//writting info into fields
				document.getElementById(objectIdWebsite).value = id_website; 
	  			document.getElementById(objectTituloPagina).value = titulo; 
				document.getElementById(objectResumoPagina).value = resumo; 
				
		//		document.getElementById(objectIdPagina).value = id_pagina; 
				document.getElementById(objectComment).value = comment; 
				document.getElementById(objectPublica).value = publica; 
				
				//seleccionar comentario e publica
				if(comment == "1") 
					document.form1.comment.checked = true;
				if(publica == "1") 
					document.form1.publica.checked = true;	
					
				//Selecting menu
					//check if menuId exists in <Select box	
					ofounded= false;	
					for(i=0 ; i< document.getElementById('id_menu').length; i++ ){
						if(menuId == document.getElementById('id_menu').options[i].value){
							id_menu_index = i;
							ofounded = true;
						}
					}
					if(ofounded){
						document.form1.id_menu.selectedIndex =  id_menu_index;
					}else
						document.form1.id_menu.selectedIndex =  0;
					
				//Selecting Lingua
					//check if menuId exists in <Select box	
					ofounded= false;	
					for(i=0 ; i< document.getElementById('id_lingua').length; i++ ){
						if(id_Lg == document.getElementById('id_lingua').options[i].value){
							id_lingua_index = i;
							ofounded = true;
						}	
					}
					if(ofounded)
						document.form1.id_lingua.selectedIndex =  id_lingua_index;
					else
						document.form1.id_lingua.selectedIndex =  0;
					

				c('conteudo'); //Focus Whizzywig Textarea
				oW.document.body.innerHTML = conteudo;	//Writting content
				makeSo("html");
				showDesign();
								
				//Handle Id_Pagina & Lingua info
				if(id_pagina == '' ){
					document.getElementById('id_lingua').disabled = true;
				}else{
					document.getElementById('id_lingua').disabled = false;
					document.getElementById('id_pagina').value = id_pagina;
				}		
					
				handleFocus();
				setTimeout("loadobjs('../include/tmp/whizzyDoc.css')",5);
	 }
      else { 
	  		alert("A problem occurred with communicating between the XMLHttpRequest object and the server program."); 
	};
      document.getElementById("fullBody").style.display =  "none";
	  document.getElementById("fullBodySaving").style.display = "none";
	  unlockPageSaving();
   }
   

}
//------------------------------------------------------------------------------------------------------------------------------


// Gestão de Newsletter --------------------------------------------------------------------------------------------
// Ajax - Wizzywigg ------------------------------------------------------------------------------------------------
var requestNL;
var objectAssuntoNL;
var objectConteudoNL;

/* Wrapper function for constructing a request object.
 Parameters:
  reqType: The HTTP request type, such as GET or POST.
  url: The URL of the server program.
  asynch: Whether to send the request asynchronously or not. */ 
function httpRequestNL(url,queryString,objectAssunto,objectConteudo,reqType,asynch) {
	 //Deafault Values
	  reqType = typeof(reqType) != 'undefined' ? reqType : 'POST';
	  asynch = typeof(asynch) != 'undefined' ? asynch : true;	
	
	   //Mozilla-based browsers
	   if (window.XMLHttpRequest) { requestNL = new XMLHttpRequest(); }
	   //Internet Explorer
	   else if (window.ActiveXObject) {
		  requestNL = new ActiveXObject("Msxml2.XMLHTTP");
		  if (!requestNL) { requestNL = new ActiveXObject("Microsoft.XMLHTTP"); }
	   }
	   //the request could still be null if neither ActiveXObject
	   //initialization succeeded
	   if (requestNL) { 
		  this.objectAssuntoNL  = objectAssunto;
		  this.objectConteudoNL = objectConteudo;
		  
		  initReqNL(reqType,url,asynch,queryString); 
	   }
	   else { alert("Your browser does not permit the use of all of this application's features!"); }
}


/* Initialize a request object that is already constructed.
 Parameters:
   reqType: The HTTP request type, such as GET or POST.
   url: The URL of the server program.
   isAsynch: Whether to send the request asynchronously or not. */
function initReqNL(reqType,url,isAsynch,queryString,object) {
   try {
      /* Specify the function that will handle the HTTP response */
      requestNL.onreadystatechange=handleResponseNL;
      requestNL.open(reqType,url,isAsynch);
      /* Set the Content-Type header for a POST request */
      if (reqType.toLowerCase() == "post") {
         requestNL.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
         requestNL.send(queryString);
		 lockPageSaving();
      } 
      else { requestNL.send(null); }
   }
   catch (errv) { 
   	alert("The application cannot contact the server at the moment. Please try again in a few seconds.\\n Error detail: "+errv.message);
   }
}

//event handler for XMLHttpRequest
function handleResponseNL() {
   if (requestNL.readyState == 1) {
      //document.getElementById(object).innerHTML = "<div align='center'></div><strong>Loading...</strong></div>"; 
      document.getElementById("fullBodySaving").style.display = "block";
   }
   if(requestNL.readyState == 4) {
      if(requestNL.status == 200) { 

		 	//Parsing XML
				xml = requestNL.responseText;

				var assunto  = getTagContent(xml,'whzzwgAssunto');
				var conteudo= getTagContent(xml,'whzzwgConteudo');
				var id_newsletter = getTagContent(xml,'whzzwgId_newsletter');
				var ficheiros_anexados = getTagContent(xml,'whzzwgFicheiros');
								
				//writting info into fields
	  			document.getElementById(objectAssuntoNL).value = assunto; 

				//Adding files
				document.getElementById('ficheiros_anexados').innerHTML = ficheiros_anexados;

				c('conteudo'); //Focus Whizzywig Textarea
				oW.document.body.innerHTML = conteudo;	//Writting content
				makeSo("html");
				showDesign();
								
				//Handle Id_Pagina & Lingua info
				if(id_newsletter != '' ){
					document.getElementById('id_newsletter').value = id_newsletter;
				}		
					
				handleFocus();
	 }
      else { 
	  		alert("A problem occurred with communicating between the XMLHttpRequest object and the server program."); 
	};
      document.getElementById("fullBody").style.display =  "none";
	  document.getElementById("fullBodySaving").style.display = "none";
	  unlockPageSaving();
   }
   

}
//------------------------------------------------------------------------------------------------------------------------------




// Ajax - Global Functions ------------------------------------------------------------------------------------------------

/*
getTagContent 
This function is Simple XML parser that gets data from XML tags. 
The purpose of this functions was to get data content from webforms that use ajax
*/
function getTagContent(xmlStr, tag) {
	var offset = 0;
	do {
		offset = xmlStr.indexOf( "<" + tag + ">", offset);
		if(offset != -1){
			n1 = offset;
		}				
	} while (offset++ != -1)

	offset = 0;
	do {
		offset = xmlStr.indexOf( "</" + tag + ">", offset);
		if(offset != -1){
			n2 = offset;
		}					
	} while (offset++ != -1)			
	
	content = xmlStr.substr(n1+2+tag.length, n2-n1-2-tag.length); 
	return content;
}


//This function handles the focus for Adding or editting records
function handleFocus(){
	if(document.getElementById('nomeUtilizador')){
		document.getElementById('nomeUtilizador').select();
		
		///if(document.getElementById('nomeUtilizador').visibility == 'visible'  )
		//	document.getElementById('nomeUtilizador').focus();
		
	}else if(document.getElementById('tituloPagina'))
		document.getElementById('tituloPagina').select();		
	else if(document.getElementById('nomeLingua'))
		document.getElementById('nomeLingua').select();		
	else if(document.getElementById('titulo'))
		document.getElementById('titulo').select();	
	else if(document.getElementById('nomeMenu'))
		document.getElementById('nomeMenu').select();
	else if(document.getElementById('assunto'))
		document.getElementById('assunto').select();		
	else if(document.getElementById('email'))
		document.getElementById('email').select();
	
}



function URLEncode(plaintext )
{
	// The Javascript escape and unescape functions do not correspond
	// with what browsers actually do...
	var SAFECHARS = "0123456789" +					// Numeric
					"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
					"abcdefghijklmnopqrstuvwxyz" +
					"-_.!~*'()";					// RFC2396 Mark characters
	var HEX = "0123456789ABCDEF";

	var encoded = "";
	for (var i = 0; i < plaintext.length; i++ ) {
		var ch = plaintext.charAt(i);
	    if (ch == " ") {
		    encoded += "+";				// x-www-urlencoded, rather than %20
		} else if (SAFECHARS.indexOf(ch) != -1) {
		    encoded += ch;
		} else {
		    var charCode = ch.charCodeAt(0);
			if (charCode > 255) {
			    alert( "Unicode Character '" 
                        + ch 
                        + "' cannot be encoded using standard URL encoding.\n" +
				          "(URL encoding only supports 8-bit characters.)\n" +
						  "A space (+) will be substituted." );
				encoded += "+";
			} else {
				encoded += "%";
				encoded += HEX.charAt((charCode >> 4) & 0xF);
				encoded += HEX.charAt(charCode & 0xF);
			}
		}
	} // for

	return encoded;
};

function URLDecode( encoded)
{
   // Replace + with ' '
   // Replace %xx with equivalent character
   // Put [ERROR] in output if %xx is invalid.
   var HEXCHARS = "0123456789ABCDEFabcdef"; 

   var plaintext = "";
   var i = 0;
   while (i < encoded.length) {
       var ch = encoded.charAt(i);
	   if (ch == "+") {
	       plaintext += " ";
		   i++;
	   } else if (ch == "%") {
			if (i < (encoded.length-2) 
					&& HEXCHARS.indexOf(encoded.charAt(i+1)) != -1 
					&& HEXCHARS.indexOf(encoded.charAt(i+2)) != -1 ) {
				plaintext += unescape( encoded.substr(i,3) );
				i += 3;
			} else {
				alert( 'Bad escape combination near ...' + encoded.substr(i) );
				plaintext += "%[ERROR]";
				i++;
			}
		} else {
		   plaintext += ch;
		   i++;
		}
	} // while

   return plaintext;
};

//IMPORTANT
//This function is on Beta testing - is not in USE
/*
Note that function loadobjs() can invoke any number of CSS and external JavaScript files that you need. For example
	loadobjs('external.css') //load one CSS file
	loadobjs('external.css', 'external2.css', 'feature.js') //load 2 CSS files & 1 JS file
	loadobjs('feature.js', 'feature2.js', 'feature3.js') //load 3 JS files 
 * 
 */
function loadobjs(){
		if (!document.getElementById)
			return
			for (i=0; i<arguments.length; i++){
				var file=arguments[i]
				var fileref=""
				if (loadedobjects.indexOf(file)==-1){ //Check to see if this object has not already been added to page before proceeding
					if (file.indexOf(".js")!=-1){ //If object is a js file
						fileref=document.createElement('script')
						fileref.setAttribute("type","text/javascript");
						fileref.setAttribute("src", file);
						}
					else if (file.indexOf(".css")!=-1){ //If object is a css file
						fileref=document.createElement("link")
						fileref.setAttribute("rel", "stylesheet");
						fileref.setAttribute("type", "text/css");
						fileref.setAttribute("href", file);
				}
			}
			if (fileref!=""){
				//document.getElementsByTagName("head").item(0).appendChild(fileref); //loadobjs original
				//document.getElementById("whizzywighead").item(0).appendChild(fileref); //hack for whyzzy	
				
				//document.getElementById('main_content').item(0).appendChild(fileref);
							
				loadedobjects+=file+" " //Remember this object as being already added to page
			}
		}
}
//------------------------------------------------------------------------------------------------------------------------------








