// For creating the xmlhttprequest object.
function getXMLHTTPRequest() {
	try {

	req = new XMLHttpRequest();

	} catch(err1) {

	  try {

	  req = new ActiveXObject("Msxml2.XMLHTTP");

	  } catch (err2) {

		try {

		req = new ActiveXObject("Microsoft.XMLHTTP");

		} catch (err3) {

		  req = false;
		  //Call php normaly

		}
	  }
	}

	return req;
}

//Manage the the folders.
function manageFolders(status, folder) {

	httpreq=getXMLHTTPRequest();

	var url = './scripts/folders.php';

	url = url+"?folder="+folder+"&status="+status;

	//
	httpreq.open("GET", url, true);


	//Call the function when the server call back.
	httpreq.onreadystatechange = function(){

		if (httpreq.readyState == 4) {

			if(httpreq.status == 200) {

			   var content = httpreq.responseText;

			   document.getElementById(folder).innerHTML = content;
			   //alert(content);

			   /* Track this ajax call with Google Analytics */
			   pageTracker._trackPageview("/folder/"+folder+"-"+status);
			}

		} else {

			document.getElementById(folder).innerHTML = '<table width="100%" border="0" cellspacing="0" cellpadding="0" class="lefttd">' +
					'<tr>' +
						'<td colspan="2"><img src="images/folders/expand.gif" width="169" height="11" title="Haz click aqu&iacute; para expandir la carpeta" onclick="manageFolders(expand, '+ folder + ')" /></td>'+
					'</tr>'+
				'</table>';

		}


	}//End online function.

		//Send the request.
		httpreq.send(null);

}//End function

//Manage the comunication with the server for getting the sections.
function manageSections(url, id, order, action) {
	
	//url=encodeURI(url);
	
	//alert(url);
	if(order){

		var msg = '';

	} else {

		var msg = '<p><center><strong><br /><br /><br /><br /><br /><br /><br /><br />Cargando...</strong></center></p>';
	}
	httpreq=getXMLHTTPRequest();

	httpreq.open("GET", url, true);
	//alert(url);
	//Call the function foldersResponse when the server call back.
	httpreq.onreadystatechange = function(){
		
		if (httpreq.readyState == 4) {

			if(httpreq.status == 200) {

			   var section = httpreq.responseText;
				//alert(section);

			   document.getElementById(id).innerHTML = section;
			   window.status="Realizado";

				//Execute the action.
				if(action != null) eval(action);

				/* Track this ajax call with Google Analytics */
				pageTracker._trackPageview("/"+url);

			}

		} else {
			
		  	window.status="Realizando...";
			document.getElementById(id).innerHTML = msg;

		}

	}//End online function.

	//Send the request.
	httpreq.send(null);

}

/* Generate url from all inputs in a form */
function generateUrl(form){
	var elem;
	//var fields = form.elements.length;
	var fields=form.length;
	var url = "";

	for(var i=0; i < fields; i++){
		elem = form.elements[i];

		/*
			if
				input is disabled or
				input hasn't have a name attribute or
				input is of type 'button'
				radio or checkbox isn't checked
			then
				don't append it to the url

		*/

		if(elem.disabled || elem.name == "" || elem.type == "button" || (elem.type == 'radio' || elem.type == "checkbox") && !elem.checked){
			continue;
		}

		if(i==0) url += "?";
		if(i>0) url += "&";

		//url += encodeURI(elem.name) + '=' + encodeURIComponent(elem.value);
		url += elem.name + '=' + elem.value;

		//if(i < fields-1) url += "&";
	}

	return url;
}

//For making the url with the form fields.
function regFormVars(url, formName, id){

	var form = document.forms[formName];

	url += generateUrl(form);
	//console.log(url.replace(/&/g, "&\n"));

	//alert(url);

	httpreq = getXMLHTTPRequest();

	httpreq.open("GET", url, true);

	httpreq.onreadystatechange = function(){

		if (httpreq.readyState == 4) {

			if(httpreq.status == 200) {

			   var section = httpreq.responseText;

			   if(id!=undefined){

			   		document.getElementById(id).innerHTML=section;

			   }

			}
		}

	}

	//Send the request.
	httpreq.send(null);
}

//For showing the link form.
function showLink(form, ename, url, id){

	if(form.elements[ename].value != ''){

		url += '?show=true';
		//alert(url);
	}

	manageSections(url, id, true);

}


/* Checks if required fields are filled or not */
function checkForm(url, formName, regUrl){
	
	var counter=0;
	var form = document.forms[formName];
	
	var vars=generateUrl(form);
	//console.log(vars.replace(/&/g, "&\n"));
	
	url += vars + "&form=" + formName + "&checkErrors=1";

	httpreq=getXMLHTTPRequest();

	httpreq.open("GET", url, true);

	httpreq.onreadystatechange = function(){

		if (httpreq.readyState == 4) {

			if(httpreq.status == 200) {

				var response = httpreq.responseText;
				
				//Call function to make the associative array.
				var formVars = splitIntoArray(response,";");

				//For getting the labels and errors.
				for(prop in formVars){
					var inputName = prop;
					var errorMsg = formVars[prop];
					var label = document.getElementById(inputName + "Label");

					if(label != null){
						if(errorMsg == ""){
							label.removeAttribute("class");
							label.removeAttribute("title");
						}
						else{
							label.className = "unfilled";
							label.title = errorMsg;
							counter++;
						}
					}

				}
				/* if all required fields were given */
				if(counter==0){
					regUrl=regUrl+vars;
					//Send the vars to reg
					manageSections(regUrl, 'central_content');
					//document.location.href = "#top";
					//refreshPage('index.php',7000);
					
				}
				/* if some required fields were NOT given */
				else{
					/* go to the top of the form */
					document.location.href = "#formTop";
					
					/* display an error message */
					alert("Por favor, rellene los campos requeridos (marcados en rojo).");
				}

			}

		}

	}

	//Send the request.
	httpreq.send(null);
}

/* Checks if required fields are filled or not */
function getSession(){

	url = "/scripts/database/solic_preins_vars.php?getSession=1";

	httpreq=getXMLHTTPRequest();

	httpreq.open("GET", url, true);

	httpreq.onreadystatechange = function(){

		if (httpreq.readyState == 4) {

			if(httpreq.status == 200) {

				console.log(httpreq.responseText.replace(/<[^>]+>/g, ""));
				

			}

		}

	}

	//Send the request.
	httpreq.send(null);
}
