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 e um bloco de script ou include para um script
        if (pos_src < ini && pos_src >=0){//Se encontrou um "src" dentro da tag script, entao e 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) {
	 //Default 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=utf-8");

         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) {
	  lockPage2();
   }
   if(request.readyState == 4) {
      if(request.status == 200) {
		var resposta=request.responseText;
		resposta=resposta.replace(/\+/g," ");
		resposta=unescape(resposta);
  		document.getElementById(object).innerHTML = resposta; 
		 unlockPage2();		
		ExportaScript(resposta);
	  }
      else { 
	  	alert("A problem occurred with communicating between the XMLHttpRequest object and the server program."); 
	}
   }
}





// Ajax - Global Functions Beta Experiments ---------------------------------------------------------------------------------------

//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
			}
		}
}

//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;
};




/*
getTagContent - Unused
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;
}

//------------------------------------------------------------------------------------------------------------------------------


