/* AJAX related */

var __DEBUG=false;

function $(elm) {
	return document.getElementById(elm);
}



function stopDefault(e) {
	if(e && e.preventDefault) 
		e.preventDefault();
	else
        window.event.returnValue = false;
	return false;
}

function getXhr(){
     var xhr = null; 
	 if(window.XMLHttpRequest) {
	      xhr = new XMLHttpRequest(); 
	  }
	  else if(window.ActiveXObject) { 
		try {
			xhr = new ActiveXObject("Msxml2.XMLHTTP");
		} 
		catch (e) {
			xhr = new ActiveXObject("Microsoft.XMLHTTP");
		}
	}
	else {  
		alert("XMLHTTPRequest not supported..."); 
		xhr = false; 
	} 
	return xhr;
}
//get the response from the server and display errors, 
//success or redirect to a new page
function handleResponse (errorList,formSending,targetDiv) {
			//erase the loading view if any
			if($('loading')) {
				hide($('loading'));
			}
			//check the response from the server
			//if start with Errors::, assume error
			//debugConsole('Server Response',errorList);
			var displayed=getElementsByClassName(document, "div", "error");

			for (var count=0; count<displayed.length; count++) {
				//debugConsole('process','hidding displayed errors not in the response');
				var str=displayed[count].id;
					if(!str.match(errorList)) {
						hide($(displayed[count].id));
					}
			}
			if(errorList.indexOf("Errors::",0)>=0) {
				//debugConsole('process','Errors:: found, displaying errors');
				var displayed=getElementsByClassName(document, "div", "error");
				//split the error list and display the errors
				list = errorList.split('Errors::');
				list = list[1].split(',');
				for (var count=0; count<list.length; count++) {			
					show($('error_'+list[count]));
				}	
				return false;
			}

			//if there is no error and no redirect link, we hide the displayed errors if any
			if(!formSending) {
				//if there is no target div, assign successful
				//debugConsole('redirect','false');
				handleSuccess(targetDiv,errorList);
				return;
			}
			//if there's no error and a redirect link,redirect
			else {
				//debugConsole('redirect','true');
				window.location=formSending;
				return;
			}
}
function handleRequest (xhr,formSending,targetDiv) {
	xhr.onreadystatechange = function(){

		if($('loading')){ show($('loading')); }	
				//debugConsole('Server status ',xhr.status);
				//debugConsole('Server readyState ',xhr.readyState);
		if(xhr.readyState == 4 && xhr.status == 200){
			handleResponse(xhr.responseText,formSending,targetDiv);	
		}
	}
}

//create the request string for the server for one form
function serialize(currentForm) {
	var requestString= '';
 	var inputs = currentForm.getElementsByTagName("input");
	for (var inputNumber = 0; inputNumber < inputs.length; inputNumber++) {
		if (inputs[inputNumber].type == "text" || inputs[inputNumber].type == "hidden" ||
			inputs[inputNumber].type == "password") {
			requestString += _encodeURIComponent(inputs[inputNumber].name) + "=" + _encodeURIComponent(inputs[inputNumber].value) + "&";
		}
		if (inputs[inputNumber].type == "radio" || inputs[inputNumber].type == "checkbox") {
			if(inputs[inputNumber].checked) {
				requestString += _encodeURIComponent(inputs[inputNumber].name) + "=" + _encodeURIComponent(inputs[inputNumber].value) + "&";
			}
		}		
	}
	//collect all selects
 	var selects = currentForm.getElementsByTagName("select");
	for (var selectNumber = 0; selectNumber < selects.length; selectNumber++) {
		requestString += _encodeURIComponent(selects[selectNumber].name) + "=" + _encodeURIComponent(selects[selectNumber].value) + "&";
	}
	//collect all textareas
 	var textareas = currentForm.getElementsByTagName("textarea");
	for (var textareaNumber = 0; textareaNumber < textareas.length; textareaNumber++) {
		requestString += _encodeURIComponent(textareas[textareaNumber].name) + "=" + _encodeURIComponent(textareas[textareaNumber].value) + "&";
	}
	requestStr=requestString+"ajax=true";
	return requestStr;
}

function AJSubmit(cDiv,formSending,targetDiv,onBeforeSend) {
	var result=true;

	eleForm = $(cDiv).getElementsByTagName("form");

	if(typeof(onBeforeSend)=='function') {
		result=onBeforeSend(eleForm[0]);
		//debugConsole('Javascript callback function result : ',result);
	}
	if(!result) { 
		//debugConsole('Javascript callback function result : ',result);
		return false; 
	}

	//inner function to use closure
	var sendRequest= function () {
		var xhr = getXhr();
		xhr.open("POST",eleForm[0].action,true);
		xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		xhr.send(serialize(eleForm[0]));
		handleRequest(xhr,formSending,targetDiv);
	}

 	if(onBeforeSend){ 
		setTimeout(sendRequest,800);
	} else {
		sendRequest();
	}
	sendRequest=null;
}

function AJSubmit2(eleForm,targetDiv,onBeforeSend) {

	var result=true;

	if(typeof(onBeforeSend)=='function') {
		result=onBeforeSend(eleForm[0]);
		//debugConsole('Javascript callback function result : ',result);
	}
	if(!result) { 
		//debugConsole('Javascript callback function result : ',result);
		return false; 
	}

	//inner function to use closure
	var sendRequest= function () {
		var xhr = getXhr();
		xhr.open("POST",eleForm.action,true);
		xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		xhr.send(serialize(eleForm));
		handleRequest(xhr,'',targetDiv);
	}

 	if(onBeforeSend){ 
		setTimeout(sendRequest,800);
	} else {
		sendRequest();
	}
	sendRequest=null;
}


/*queryPath : string, the page to call 
  success : object, the name of divs and effects to use to insert data
  params : object, parameters and value to be sent to the page to call (POST only)
*/

function remote_function2(queryPath,oCallback,params) {

		var xhr = getXhr();

		var abort = function() {
			if(xhr) xhr.abort();
			clearTimeout(timer);
			try {oCallback.onTimeOut();}catch(e) {};
		}

		var timer=setTimeout(abort,2000);

		try { oCallback.onStart(); } catch(e) { }

		xhr.onreadystatechange = function(){

			try { oCallback.onStateChange(xhr.readyState,xhr.status); } catch(e) {}

			if(xhr.readyState == 4){

			   if(xhr.status == 200){

					var response=xhr.responseText;
					xhr=null;
			        clearTimeout(timer);

					if(response.indexOf('Errors::',0)==-1) {
						 try { oCallback.onSuccess(response); } catch(e) { }
					}
					else {
						response2=response.split('Errors::');
						for(k=1; k<response2.length; k++) show($('error_'+response2[k]));
						 try { oCallback.onSuccess(response); } catch(e) { }
					}
                }
				else {
					xhr=null;
				 	try { oCallback.onError(xhr.status); } catch(e) {}
				}
			}	
		}
		var Str=[];

		sendValue=new Array();
		if(params) { 
				method='POST'; 
				for (var param in params) {
					sendValue.push(_encodeURIComponent(param)+"="+_encodeURIComponent(params[param]));
				}
				sendValue.push('ajax=true');
				sendValue=sendValue.join('&');
		} 
		else { 
			method='GET';
			if(Str.length>0)
				queryPath=queryPath+'&'+Str+'&ajax=true';
			else 
				queryPath=queryPath+'&ajax=true';
			sendValue=null;
		}


	   //debugConsole('remote query',queryPath);

		xhr.open(method,queryPath,true);
		if(method=='POST') { 
			xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		}
		xhr.send(sendValue);

}

function remote_function (queryPath,success,params,arrayOfIds) {
		var loader=false;
		var id='loading';

		var xhr = getXhr();


		var abort = function() {

			if(xhr) xhr.abort();
			clearTimeout(timer);
		}

		var timer=setTimeout(abort,2000);

		try { onStart(); } catch(e) { }

		xhr.onreadystatechange = function(){

			try { onStateChange(); } catch(e) {}
			if(!loader && $(id)) {
				show($(id));
				loader=true;
			}
			if(xhr.readyState == 4){

			   if(xhr.status == 200){

					if(loader) { hide($(id));}
					var response=xhr.responseText;
					xhr=null;
			        clearTimeout(timer);

					//debugConsole ('remoteFunctionCall',response);

					if(response.indexOf('Errors::',0)==-1) {
						handleSuccess(success,response);
					}
					else {
						response=response.split('Errors::');
						for(k=1; k<response.length; k++) {
							show($('error_'+response[k]));
						}
					}
                }
				else {
					xhr=null;
				 	try { onError(xhr.status); } catch(e) {}
				}
			}	
		}
		var Str=new Array();
		if(arrayOfIds) {
			for (var j=0; j < arrayOfIds.length; j++) {
				Str.push(arrayOfIds[j].name+'='+arrayOfIds[j].value);					
			}
			Str=Str.join('&');
		}

		sendValue=new Array();
		if(params) { 
			method='POST'; 
			for (var param in params) {
				sendValue.push(_encodeURIComponent(param)+"="+_encodeURIComponent(params[param]));
			}
			sendValue.push('ajax=true');
			sendValue=sendValue.join('&');
			sendValue+=Str;
		} 
		else { 
			method='GET';
			if(Str.length>0)
				queryPath=queryPath+'&'+Str+'&ajax=true';
			else 
				queryPath=queryPath+'&ajax=true';
			sendValue='null';
		}
	   //debugConsole('remote query',queryPath);
		xhr.open(method,queryPath,true);
		if(method=='POST') { 
			xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		}
		xhr.send(sendValue);
}

function handleSuccess(success,response) {
	if(!success) return;
	firstArray:for (var i=0; i < success.length; i++) {
		firstObject:for (var id in success[i]) {
			secondArray:for (var j=0; j < success[i][id].length; j++) {
				var k=success[i][id][j];
				if(k=='response') {
						//var nodes=make(response);	
						//for(var l=0;l<nodes.length;l++) $(id).appendChild(nodes[l]); 
							$(id).innerHTML=response;
						continue;
				} 
				if(k=='value') {
						$(id).value = success[i][id][j+1];
						continue firstObject;
				} 
				if(k=='insert') {
						$(success[i][id][j+1]).value = $(id).value;
						continue firstObject;
				} 
				if(k=='show') {
						show($(id)); continue;
				}
				if(k=='hide') {
						hide($(id)); continue;
				}
				if(k.indexOf('function',0)>=0) {
						var func=k.split(':');
						var func2 = eval(func);
						var func3=eval(func2[1]);
						func3();
						continue;
				} 
				if($(id)) {
					eval("new Effect."+k+"($(id))");
				}
			}
		}
	}
				 	try { onSuccess(); } catch(e) {}
	return;
}

//ASYNCHRONE UPLOAD BAR--------
var uploadState=0;
function AJUpload(el,arrayOfIds,callback) {
		if(uploadState==1) {
			return alert('uploading...');
		}
		el.target='upload_frame';
		el.submit();
		$('upload_frame').style.width='0px';
		getActualSize(arrayOfIds,callback);
}
count=0;
function getActualSize (arrayOfIds,callback) {
		uploadState=1;
		x = getXhr();
		x.onreadystatechange = function(){
			if(x.readyState == 4 && x.status == 200){
				++count;
				var oJSON=eval("("+x.responseText+")");

					//debugConsole('AJUpload',x.responseText);

				if(oJSON.percent=='0%') {
					var bar=$('progress_bar');
					var bar2=$('progress_state');
					new Effect.Appear(bar);
					new Effect.Appear(bar2);				
				}
				if(oJSON.percent!='100%' || oJSON.fullsize!='downloaded') {
					$('progress_state').innerHTML=oJSON.filesize +'/'+ oJSON.fullsize +' downloaded '+ oJSON.percent;
					$('progress').style.width=oJSON.percent;
					getActualSize(arrayOfIds,callback);
				} 
				else if(oJSON.fullsize=='downloaded' || oJSON.percent!='100%') {
					uploadState=0;
					new Effect.Fade($('progress_bar'));
					$('progress_state').innerHTML='upload successfull';
					$('progress').style.width='0px';
					new Effect.Fade($('progress_state'));
					uploadCallback(oJSON);
					var func = eval(callback);
					func();
					func='';
					oJSON='';
				}
			}
		}
		var Str=new Array();
		for (var j=0; j < arrayOfIds.length; j++) {
			Str.push(arrayOfIds[j].name+'='+arrayOfIds[j].value);					
		}
		Str=Str.join('&');
		var r=Math.floor(Math.random()*101);
		x.open('GET','/cgi-bin/progress_bar.cgi?'+Str+'&rand='+r,true);
		x.send(null);
}



//-----------------------------


//EFFECTS
function show(elm) {
	elm.style.display="block";
}
function hide(elm) {
	elm.style.display="none";
}




//FLASH
function getInfoFromFlash(params) {

	var oJSON=eval('('+params+')');
	var func=eval(oJSON.action);
	//debugConsole('Action',oJSON.action);
	if(typeof func =="function") {
		func(oJSON);
	}
}
function getFlashMovie(movieName) {
  return (window[movieName+'2']) ? window[movieName+'2'] : document[movieName];
}
function sendInfoToFlash(evtName,params) {
    getFlashMovie('map').sendTextToFlash(evtName,params);
} 

//-------//

////debugGER
function debugConsole (title,elem) {
		if(__DEBUG) {
		warningDiv = document.createElement("div");
		warningDiv.style.backgroundColor="white";
		warningDiv.style.color="red";
		warningDiv.style.top="0px";
		warning = document.createTextNode(title+':'+elem);
		warningDiv.appendChild(warning);
		document.lastChild.appendChild(warningDiv);
		}
}