/*
*Initialisation of XMLHttpREquest object
*/
function initAjax(){
    var xhr = null; 
	 
	if(window.XMLHttpRequest) // Firefox 
	   xhr = new XMLHttpRequest(); 
	else if(window.ActiveXObject) // Internet Explorer 
	   xhr = new ActiveXObject("Microsoft.XMLHTTP"); 
	else { // XMLHttpRequest non support? par le navigateur 
	   alert("Votre navigateur ne supporte pas les objets XMLHTTPRequest..."); 
	   xhr = null;
       return xhr; 
	} 
    return xhr;
}
/*
a GEt function
@country for this country name
-> Geodata from geo sections
*/
function getGeoPos (country,form){    
    var xhr_object = initAjax();
	xhr_object.open("GET", cpath+"scripts/DB/getGeoPos.php?country="+country+"&form="+form, true);  
	
	xhr_object.onreadystatechange = function() { 
        if(xhr_object.readyState == 4) 
            eval(xhr_object.responseText); 
    } 
  
	xhr_object.send(null); 
}


/*
* Check if Exist xtratype opal_xtra's for the parent id of type
-> [paths]
ex: ajaxGetXtras('lodgings',22,'photo','$contextPath/users/oceatoon/gfx/lodgings/toto.jppg');
*/
function ajaxGetXtras(type,id,xtratype,file){
    var xhr_object = initAjax();
    
    xhr_object.open("GET", cpath+"scripts/DB/getXtras.php?type="+type+"&id="+id+"&xtratype="+xtratype, true);  
    
	xhr_object.onreadystatechange = function() { 
        if(xhr_object.readyState == 4){
            xtraT = eval(xhr_object.responseText);
            if(xtraT[xtraT.length-1] == null)
            	xtraT.pop();
            if(xtraT.length>0){
            	xtraT.push(file);
            	document.getElementById("nextphoto").style.visibility = "visible";
            	document.getElementById("prevphoto").style.visibility = "visible";
            }
         } 
    } 
	xhr_object.send(null);
}

/*
* Retrives and builds the HTML to be shown for this element @id of @type 
->string of html code
*/
function ajaxGetHtml(type , id, user, file){
	var xhr_object = initAjax();
	
    xhr_object.open("GET", cpath+"scripts/DB/getHTML.php?type="+type+"&id="+id+"&user="+user+"&file="+file, false);  
	xhr_object.send(null);
    if(xhr_object.readyState == 4) 
        return xhr_object.responseText;
}
function ajaxGetHtmlTabList(type , time, user,page){
	var xhr_object = initAjax();
	
    xhr_object.open("GET", cpath+"scripts/DB/getHTMLTabList.php?type="+type+"&time="+time+"&page="+page+"&user="+user+"&lstart="+lstart, false);  
	xhr_object.send(null);
    if(xhr_object.readyState == 4) 
        return xhr_object.responseText;
}

/*
* Ajax REtreives data from Raj's zee source webservice 
*/
function getSuggest (country,city){    
    var xhr_object = initAjax();
	xhr_object.open("GET", cpath+"scripts/WS/GeocodeWSDL.php?country="+country+"&city=^"+city, true);  
	
	xhr_object.onreadystatechange = function() { 
        if(xhr_object.readyState == 4){ 
            document.getElementById('suggest').innerHTML = xhr_object.responseText;
        }  
    }  	
	xhr_object.send(null); 
}

/*
* Generic Ajax suggest system
* type  = the file name to get like "theme"
* word = the word being typed
* opt = the table to search, must be an opal theme
* opt2 = the dbprefix 
* opt3 = the FIELD to retrieve if null = NAME
* opt4 = the action to apply on the returned link
* opt5 = destination innerHTML
*/
function getXSuggest (type,word,opt,opt2,opt3,opt4,opt5){
	optvar = (opt!=null) ? "&opt="+opt : "";
	opt2var = (opt2!=null) ? "&opt2="+opt2 : "";	 
	opt3var = (opt3!=null) ? "&opt3="+opt3 : ""; 
	opt4var = (opt4!=null) ? "&opt4="+opt4 : ""; 
    var xhr_object = initAjax();
	xhr_object.open("GET", cpath+"scripts/DB/"+type+"Suggest.php?word="+word+optvar+opt2var+opt3var+opt4var, true);  
	xhr_object.onreadystatechange = function() { 
        if(xhr_object.readyState == 4){ 
        	//alert(xhr_object.responseText);
        	if(opt5!=null && opt5!="")
            	document.getElementById(opt5).innerHTML = xhr_object.responseText;
            else
            	document.getElementById(type+'suggest').innerHTML = xhr_object.responseText;
        }  
    } 
	xhr_object.send(null); 
}

/*
* Takes an object as argument , builds the list of parmeters dynamically  
*/
function getXSuggestDyn (optObj){
	optvar = Obj2FunctionArg(optObj);
    var xhr_object = initAjax();
	xhr_object.open("GET", cpath+"scripts/DB/Suggest.php?"+optvar , true);  
	xhr_object.onreadystatechange = function() { 
        if(xhr_object.readyState == 4){ 
        	//alert(xhr_object.responseText);
        	if(optObj["target"]!=null && optObj["target"]!="")
            	document.getElementById(optObj["target"]).innerHTML = xhr_object.responseText;
        }  
    } 
	xhr_object.send(null); 
}

/*
*  Ajax Calls for retreiving the code for a GMap index Page(opal 2 my own GMap)
*/
function ajaxGetHtmlGMap(gkey , user, lon, lat,zoom){
	var xhr_object = initAjax();
    xhr_object.open("GET", cpath+"scripts/DB/getMyOwnGMap.php?gkey="+gkey+"&user="+user+"&lon="+lon+"&lat="+lat+"&zoom="+zoom, false);  
	xhr_object.send(null);
    if(xhr_object.readyState == 4)
        document.form.GMapHTML.value = xhr_object.responseText;
}

//Check in DB if user exist 
//return alert(wont work) if not
function AjaxCheckUserExist(user){
	var xhr_object = initAjax();
    xhr_object.open("GET", cpath+"scripts/DB/userExist.php?user="+user, false);  
	xhr_object.send(null);
    if(xhr_object.readyState == 4)
        eval(xhr_object.responseText);
}

//Captcha Validation 
//return true or alert+false
function Capcheck(val){
	var xhr_object = initAjax();
    xhr_object.open("GET", cpath+"scripts/DB/Capcheck.php?val="+val, false);  
	xhr_object.send(null);
	res=false;
    if(xhr_object.readyState == 4){
        eval(xhr_object.responseText);
        return res;
     }
        
}
//connected users fills a JS array 
function Connected()
	{
		var xhr_object = initAjax();
	    xhr_object.open("GET", cpath+"scripts/DB/online.php", false);
	    xhr_object.send(null);
	    var oldT = [];
	    if (xhr_object.readyState == 4) {
	    	oldT = connectedT;
	        connectedT = eval(xhr_object.responseText);
	    }
	    //swaps icons according to connection status
		if(oldT.length != 0 && oldT.length > connectedT.length){//nelle deconnection
			//alert("nelle deconnexion"+oldT+"///"+connectedT);
			for(var ix = 0 ; ix < oldT.length ; ix++){
				if(!in_T(connectedT,oldT[ix])){
					if(opal.userT[oldT[ix]])
						opal.userT[oldT[ix]].marker.setIcon(userIcon);}}}
		else if( oldT.length != 0 && oldT.length < connectedT.length){//nelle connection
			//alert("nelle connexion "+oldT+"///"+connectedT);
			for(var ix = 0 ; ix < connectedT.length ; ix++){
				if(connectedT[ix]!="" && !in_T(oldT,connectedT[ix])){
					if(opal.userT[connectedT[ix]])
						opal.userT[connectedT[ix]].marker.setIcon(loguserIcon);}}}

	    if(logged != 'false')
	    {
	    	xhr_object = initAjax();
	    	xhr_object.open("GET", cpath+"scripts/DB/chat.php", false);
		    xhr_object.send(null);
		    var fromT = [];
		    var msgT = [];
		    if (xhr_object.readyState == 4) {
	        	eval(xhr_object.responseText);
	        	for(var ix = 0 ; ix < msgT.length ; ix++)
	        	{
	        		var qmsg = prompt('Member: '+fromT[ix]+' says : '+msgT[ix],'answer');
	        		if(qmsg)
	        			saveChat(fromT[ix],qmsg);
	        	}
		    }
		}
	    setTimeout("Connected()",10000);
	}

//save a message to chat db
//alert(msg delivered) or msg undelivered
function saveChat(to,msg){
	var xhr_object = initAjax();
    xhr_object.open("GET", cpath+"scripts/DB/chatInsert.php?to="+to+"&msg="+msg, false);
    xhr_object.send(null);
    if (xhr_object.readyState == 4) {
        eval(xhr_object.responseText);
    }
}

//saves a pinpointed location to DB
//alert(position saved) or not
function savePinPos(type,xtype,id,lng,lat){
	var xhr_object = initAjax();
	//alert("xtype="+xtype+"&id="+id+"&lng="+lng+"&lat="+lat);
    xhr_object.open("GET", cpath+"scripts/DB/save"+type+".php?xtype="+xtype+"&id="+id+"&lng="+lng+"&lat="+lat, false);
    xhr_object.send(null);
    if (xhr_object.readyState == 4) {
        eval(xhr_object.responseText);
    }
}

//check if this point could be inside a custom map
//if yes prompt do you want to add to custom map
/*function checkIfInCustomMap(type,id,lng,lat){
	var xhr_object = initAjax();
    xhr_object.open("GET", cpath+"scripts/DB/checkIfInCustomMap.php?lng="+lng+"&lat="+lat, false);
    xhr_object.send(null);
    if (xhr_object.readyState == 4) {
       var insert2CustomMap = eval(xhr_object.responseText);
       if(insert2CustomMap){
       		savePinPos("CustomReferentialInsert","lifepoints",id,lng,lat)
       }
    }
}*/

/*
SAve the current form to DB
returns and shows the uploaded img
*/
function saveUploadAddFile(type, form){    
    var xhr_object = initAjax();
	xhr_object.open("POST", cpath+"scripts/user/addtest.php", true);
	var data = "";  
	for(var ct =0 ; ct < form.elements.length ; ct++){
	    data = data+form.elements[ct].name+"="+form.elements[ct].value
	    if(ct < form.elements.length-1)
	        data = data+"&";
	}
	alert(data)
	xhr_object.setRequestHeader("Content-type", "multipart/form-data");
	xhr_object.send(data); 
	
	xhr_object.onreadystatechange = function() { 
        if(xhr_object.readyState == 4) 
            alert(xhr_object.responseText); 
    } 
}

//Add a new row into opal_customreferential DB 
function AjaxAddCustRef(user,type,id,mapid,lat,lng){
	//alert("user="+user+"&mapid="+mapid+"&type="+type+"&id="+id+"&lat="+lat+"&lng="+lng);
	var xhr_object = initAjax();
    xhr_object.open("GET", cpath+"scripts/DB/addCustRef.php?user="+user+"&mapid="+mapid+"&type="+type+"&id="+id+"&lat="+lat+"&lng="+lng, false);  
	xhr_object.send(null);
	if(xhr_object.readyState == 4){
		//alert(xhr_object.responseText);
        var r = eval(xhr_object.responseText);
    	}
    if(r)alert("your point is activated on the current custom map "+mapid);
    else alert("Please try again a problem occured while adding the point.");
}
//Remove a row from opal_customreferential DB 
function AjaxDelCustRef(id,type,name){
	var del = confirm("deleting : "+name);
	alert("id="+id+"&type="+type);
	if(del){
		var xhr_object = initAjax();
	    xhr_object.open("GET", cpath+"scripts/DB/deleteCustRef.php?id="+id+"&type="+type, false);  
		xhr_object.send(null);
	} 
}

//retreives all info for a custom map to open autonomously
//@mapid = id of the map to open
function AjaxSetUpCustomMap (mapid) {
	//alert("mapid="+mapid);
	var xhr_object = initAjax();
    xhr_object.open("GET", cpath+"scripts/DB/getCustomMapInfo.php?mapid="+mapid, false);  
	xhr_object.send(null);
	if(xhr_object.readyState == 4)
		eval(xhr_object.responseText);
}
//add a row into opal_assocs 
//type = type of the association
//id,idtype are the father point specs 
//iid and iidtype are the child point specs
function Ajax_SetAssocType2Type(type,id,idtype,iid,iidtype){
		var xhr_object = initAjax();
	    xhr_object.open("GET", cpath+"scripts/DB/InsertAssocType2Type.php?type="+type+"&id="+id+"&idtype="+idtype+"&iid="+iid+"&iidtype="+iidtype, false);  
		xhr_object.send(null);
		if(xhr_object.readyState == 4)
        var r = eval(xhr_object.responseText);
    	
	    if(r)alert("associated to "+type);
	    else alert("Please try again a problem occured during association.");
}

//Get ul - li  list of all association
//id and idtype being the father point of the assocs
//type is the type of the association
function AjaxGetListAssocs(id,idtype,type){
	var xhr_object = initAjax();
    xhr_object.open("GET", cpath+"scripts/DB/getListAssocs.php?id="+id+"&idtype="+idtype+"&type="+type, false);
	xhr_object.send(null);
	if(xhr_object.readyState == 4){
	    if(xhr_object.responseText!="")    
			eval(xhr_object.responseText);
	}
}

//get common theme elemetns such as location
function AjaxGetFromAllThemes(type,word,injectdivname){
	var xhr_object = initAjax();
    xhr_object.open("GET", cpath+"scripts/DB/getListFromAllThemes.php?type="+type+"&word="+word, false);
	xhr_object.send(null);
	if(xhr_object.readyState == 4){
	    if(xhr_object.responseText!="")    
			document.getElementById(injectdivname).innerHTML = xhr_object.responseText;
	}
}

//uses the generic add$theme.php structure of a theme to inject or update data
//@theme defines the theme destination 
//@fields : is an object containing key: values relative to the theme DB table
//@action : is an object representing a function to be dynamically build by Obj2FunctionArg {fct:\"AssocWorker\",str_arg1:\"team\" , arg2:\"context.type\" , arg3:\"context.id\"}
//@elseaction : is an object representing a function to be dynamically build by Obj2FunctionArg {fct:\"AssocWorker\",str_arg1:\"team\" , arg2:\"context.type\" , arg3:\"context.id\"}
//@type : null or import
function Ajax_addTheme(theme,fields,action,elseaction,type){
	var xhr_object = initAjax();
	xhr_object.open("POST", cpath+"scripts/user/add"+theme+".php", true);
	var data = "";  
	var ct = 0;
	for(var field in fields){
		ct++;
	    data = data+field+"="+fields[field];
	        data = data+"&";
	}
	xhr_object.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xhr_object.send(data); 
	var r =false;
	xhr_object.onreadystatechange = function() { 
        if(xhr_object.readyState == 4) {
        	if (xhr_object.status == 200) {
	            eval(xhr_object.responseText);
	            
			    if(context.result){
			    	//if(type==null)
			    		alert(theme+" entry created, please carry on.");
			    	if(action!=null)
			    		buildFunctionEval(action , context);
			    	//return context;
			    }
			    else {
			    	alert("Please try again a problem occured while creating "+theme+".");
			    	if(elseaction != null)
			    		buildFunctionEval(elseaction , context);
			    	return null;
			    }
			} else {
				alert(xhr_object.responseText);
				buildFunctionEval(elseaction , context);
				return null;
			}
        }
    }
}

//this funciton builds a function and executes it 
//obj : {fct:... , arg:... , str_arg:'...'}
function buildFunctionEval(funct_obj,context)
	{
		/*for (var prop in funct_obj)
		{
	      alert( prop + " is " + funct_obj[prop]);
	   	}*/
		var ct = 0;
		arg = "";
		for(var a in funct_obj){
		    if(a!="fct")
		    	if(a.indexOf("str")>=0)
		    		arg = (arg!="") ? arg+", '"+funct_obj[a]+"'" : "'"+funct_obj[a]+"'";
		    	else 
		    		arg = (arg!="") ? arg+", "+funct_obj[a] : funct_obj[a];
		}
		//the context is allways added to the function's argument list
		/*for(var a in context){
	    	if(a.indexOf("str")>=0)
	    		arg = (arg!="") ? arg+", '"+context[a]+"'" : "'"+context[a]+"'";
	    	else 
	    		arg = (arg!="") ? arg+", "+context[a] : context[a];
		}*/
		funct_obj_call = funct_obj.fct+"("+arg+",context);";
		//alert(funct_obj_call);
		eval(funct_obj_call);
	}
	
function Obj2FunctionArg(obj)
	{
		arg = "";
		for(var a in obj){ 
	    	arg = ( arg != "" ) ? arg+"&"+a+"="+obj[a] : a+"="+obj[a];
		}
		return arg;
	}