//holds an instance of XMLHttpRequest
var xmlhttp=createXmlHttpRequestObject();
var globalRequestId="none";
//creates an XMLHttpRequest instance
function createXmlHttpRequestObject()
	{
		//will store the reference to the XMLHttpRequest object
		var xmlhttp=null;
		//this should work for all browsers except IE6 and older
		try
		{
			//try to create XMLHttpRequest object
			xmlhttp=new XMLHttpRequest();
		}	
		catch(e)
		{
			//assume IE6 or older
			var XmlHttpVersions=new Array(  "MSXML2.XMLHTTP.6.0",
											"MSXML2.XMLHTTP.5.0",
											"MSXML2.XMLHTTP.4.0",
											"MSXML2.XMLHTTP.3.0",
											"MSXML2.XMLHTTP",
											"Microsoft.XMLHTTP");
			//try every prog id until one works
			for (var i=0;i<XmlHttpVersions.length && !xmlhttp;i++)
			{
				try
				{
					//try to create XMLHttpRequest object
					xmlhttp=new ActiveXObject(XmlHttpVersions[i]);
					//alert("Old IE - "+XmlHttpVersions[i]);
				}	
				catch(e)
				{
				}
			}
		}
		//return the created object or display an error message
		if (!xmlhttp)
		{
			alert("Error creating the XmlHttpRequest object");
		}
		else
		{
			return xmlhttp;
		}
	}
	
//function called when the state of the HTTP request changes
function handleRequestStateChange()
{
	//when readyState is 4, we are ready to read the server response
	if (xmlhttp.readyState==4)
	{
					
		//continue only if HTTP status is "Ok"
		if ((xmlhttp.status==200)||(xmlhttp.status==0))
		{
			try
			{
				//do something with the server response
				handleServerResponse();
			}
			catch(e)
			{
				//display error message
				alert("Error reading the response: "+e.toString());
			}
		}
		else
		{
			//display a status message
			alert("There was a problem receiving the date:\n"+xmlhttp.statusText+"; ready state : "+xmlhttp.readyState);
		}
	}
}
	
//handles the response received from the server	
function handleServerResponse()
{
	//retrieve the server's response packaged as an XML DOM Object
	//alert(xmlhttp.responseXML);
	var xmlResponse=xmlhttp.responseXML;
	//cathing potential errors with IE and Opera
	if (!xmlResponse || !xmlResponse.documentElement)
		throw("Invalid XML structure: \n"+xmlhttp.responseText);
	//cathing potential errors with FireFox
	var rootNodeName=xmlResponse.documentElement.nodeName;
	if (rootNodeName=="parseerror")
		throw("Invalid XML structure:\n"+xmlhttp.responseText);
	
	//getting the root element (the document element)
	xmlRoot=xmlResponse.documentElement;
	//testing that we received the XML document we expected
	
	if (rootNodeName!="response" )	
		throw("Invalid XML structure:\n"+xmlhttp.responseText);
		
    if (globalRequestId=="askForJudete")
    {
        globalRequestId="none";
        readLocalitati(xmlRoot);	
    }
    else
    {
        if (globalRequestId=="commentAdd")
            {
                globalRequestId="none";
                readAddCommentResponse(xmlRoot);
            }
        else
            {
                if (globalRequestId=="createDescription")
                {
                    globalRequestId="none";
                    readCreateDescriptionResponse(xmlRoot);
                }
                else
                {
                    if (globalRequestId=="editDescription")
                    {
                        globalRequestId="none";
                        readEditDescriptionResponse(xmlRoot);
                    }
                    else
                    {
                        if (globalRequestId=="contact")
                        {
                            globalRequestId="none";
                            readContactResponse(xmlRoot);
                        }
                    }
                }
            }
     }
}

	

function pageReload()
{
    location.reload(true);
    }
    
//called after the page has finished loading
function kajAskFormSelect($type)
	{
		//only continue if xmlhttp isn't void
		if (xmlhttp)
		{
			//don't try to make server requests if the XMLHttpRequestObject is busy
			if (!((xmlhttp.readyState==0) || (xmlhttp.readyState==4)))
			{
				alert("Can't connect to server, please try again later ("+xmlhttp.readyState+").");
			}
			else
			{
				//try to connect to the server
				try
				{
					var selectedId=document.getElementById("idJudet").value;
					var params="idJudet="+selectedId;
								
					//initiate the asynchronous HTTP request
					xmlhttp.onreadystatechange=handleRequestStateChange;
                    globalRequestId="askForJudete";
					xmlhttp.open("GET", "./libs/ajax/askForJudete.php?"+params, true);
					xmlhttp.send(null);
				}
				catch(e)
				{
					alert("Cant't connect to the server: \n"+e.toString());
				}
			}
		}
		else
		{
			alert("No connection");
		}
	}

function readLocalitati(xmlRoot)
{
	
	if (!xmlRoot.firstChild)
	{ 
		document.forms['addObjectiveForm'].idLocalitate.options.length = 0;
		document.forms['addObjectiveForm'].idLocalitate.options[0] = new Option('judetul ales nu contine nici o localitate','none');
		var bSubmit=document.getElementById("submitAddObjective");
		bSubmit.disabled=true;
	}
	else
	{
		//the value we need to display 
		idArray = xmlRoot.getElementsByTagName("id");
		nameArray = xmlRoot.getElementsByTagName("nume");
		
		document.forms['addObjectiveForm'].idLocalitate.options.length = 0;
		for (var i=0; i<idArray.length; i++)
		{
			document.forms['addObjectiveForm'].idLocalitate.options[i] = new Option(nameArray.item(i).firstChild.data,idArray.item(i).firstChild.data);
		}
		
		var bSubmit=document.getElementById("submitAddObjective");
		bSubmit.disabled=false;
	}
	
}
function kajAddComment(targetId,userId)
{
    tinyMCE.triggerSave(true,true);
    if (tinymce)
    {
        var commentNew=tinyMCE.get('commentNew').getContent();
        //alert(tText);
        //only continue if xmlhttp isn't void
        if (commentNew!="")
        {
            if (xmlhttp)
            {
                //don't try to make server requests if the XMLHttpRequestObject is busy
                if (!((xmlhttp.readyState==0) || (xmlhttp.readyState==4)))
                {
                    alert("Can't connect to server, please try again later ("+xmlhttp.readyState+").");
                }
                else
                {
                    //try to connect to the server
                    try
                    {
                        commentNew=stripText(commentNew);
                        var params="commentNew="+commentNew+"&targetId="+targetId+"&userId="+userId;
                        //initiate the asynchronous HTTP request
                        globalRequestId="commentAdd";
                        xmlhttp.open("POST", "./libs/ajax/commentAdd.php", true);
                        xmlhttp.onreadystatechange=handleRequestStateChange;
                        //fara astea -setRequestHeader-  nu merge sa faci POST... doar GET
                        xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                        xmlhttp.setRequestHeader("Content-length", params.length);
                        xmlhttp.setRequestHeader("Connection", "close");
                        xmlhttp.send(params);
                    }
                    catch(e)
                    {
                        alert("Cant't connect to the server: \n"+e.toString());
                    }
                }
            }
            else
            {
                    writeTextNode("screenError","Eroare! Nu exista conexiune cu serverul");
                    showElem("screenError");
            }
        }
        else
        {
                writeTextNode("screenError","Eroare! Trebuie introdus textul comentariului");
                showElem("screenError");
            }
    }
    else
    {
            writeTextNode("screenError","Eroare! Nu am gasit obiectul text");
            showElem("screenError");
    }
    
    return false;
}
function readAddCommentResponse(xmlRoot)
{
	if (!xmlRoot.firstChild)
	{ 
		alert("raspuns vid");
	}
	else
	{
		//the value we need to display 
		response = xmlRoot.getElementsByTagName("addResponse");
        var responseText=response[0].firstChild.nodeValue;
		//alert("ok: "+response[0].firstChild.nodeValue);
        
        writeTextNode("screenError",responseText);
        showElem("screenError");
        pageReload();
	}
	
}
function kajCreateDescription(targetId,userId)
{
    var newCat=document.getElementById("listCategorii");
    var newCatId=newCat.value;
    
    if (newCatId!=0)
    {
        tinyMCE.triggerSave(true,true);
        if (tinymce)
        {
            var descriptionNew=tinyMCE.get('descriptionNew').getContent();
            //alert(tText);
            //only continue if xmlhttp isn't void
            if (descriptionNew!="")
            {
                if (xmlhttp)
                {
                    //don't try to make server requests if the XMLHttpRequestObject is busy
                    if (!((xmlhttp.readyState==0) || (xmlhttp.readyState==4)))
                    {
                        alert("Can't connect to server, please try again later ("+xmlhttp.readyState+").");
                    }
                    else
                    {
                        //try to connect to the server
                        try
                        {
                            descriptionNew=stripText(descriptionNew);
                            var params="descriptionNew="+descriptionNew+"&targetId="+targetId+"&userId="+userId+"&newCatId="+newCatId;
                            //initiate the asynchronous HTTP request
                            globalRequestId="createDescription";
                            xmlhttp.open("POST", "./libs/ajax/createDescription.php", true);
                            xmlhttp.onreadystatechange=handleRequestStateChange;
                            //fara astea -setRequestHeader-  nu merge sa faci POST... doar GET
                            xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                            xmlhttp.setRequestHeader("Content-length", params.length);
                            xmlhttp.setRequestHeader("Connection", "close");
                            xmlhttp.send(params);
                        }
                        catch(e)
                        {
                            alert("Eroare! Nu exista conexiune cu serverul: \n"+e.toString());
                        }
                    }
                }
                else
                {
                    writeTextNode("screenError","Eroare! Nu exista conexiune cu serverul");
                    showElem("screenError");
                }
            }
            else
            {
                writeTextNode("screenError","Eroare! Trebuie introdus textul descrierii");
                showElem("screenError");
                }
        }
        else
        {
            writeTextNode("screenError","Eroare! Nu am gasit obiectul text");
            showElem("screenError");
        }
    }
    else
    {
        writeTextNode("screenError","Eroare! Trebuie ales un nume pentru noua categorie");
        showElem("screenError");
        }
    
    showElem("screenError");
    return false;
}
function readCreateDescriptionResponse(xmlRoot)
{
	if (!xmlRoot.firstChild)
	{ 
		alert("raspuns vid");
	}
	else
	{
		//the value we need to display 
		response = xmlRoot.getElementsByTagName("createResponse");
        var responseText=response[0].firstChild.nodeValue;
		//alert("ok: "+response[0].firstChild.nodeValue);
        
        writeTextNode("screenError",responseText);
        showElem("screenError");
        pageReload();
	}
	
}


function kajEditDescription(targetId,userId,desId,chosen)
{
    hideElem("screenError");
    tinyMCE.triggerSave(true,true);
    if (tinymce)
    {
        var descriptionNew=tinyMCE.get('descriptionOld'+chosen).getContent();
        //alert(tText);
        //only continue if xmlhttp isn't void
        if (descriptionNew!="")
        {
            if (xmlhttp)
            {
                //don't try to make server requests if the XMLHttpRequestObject is busy
                if (!((xmlhttp.readyState==0) || (xmlhttp.readyState==4)))
                {
                    alert("Can't connect to server, please try again later ("+xmlhttp.readyState+").");
                }
                else
                {
                    //try to connect to the server
                    try
                    {
                        descriptionNew=stripText(descriptionNew);
                        var params="descriptionNew="+descriptionNew+"&targetId="+targetId+"&userId="+userId+"&desId="+desId;
                        //initiate the asynchronous HTTP request
                        globalRequestId="editDescription";
                        xmlhttp.open("POST", "./libs/ajax/editDescription.php", true);
                        xmlhttp.onreadystatechange=handleRequestStateChange;
                        //fara astea -setRequestHeader-  nu merge sa faci POST... doar GET
                        xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                        xmlhttp.setRequestHeader("Content-length", params.length);
                        xmlhttp.setRequestHeader("Connection", "close");
                        xmlhttp.send(params);
                    }
                    catch(e)
                    {
                        alert("Eroare! Datele nu au fost transmise corect: \n"+e.toString());
                    }
                }
            }
            else
            {
                writeTextNode("screenError","Eroare! Nu exista conexiune cu serverul");
                showElem("screenError");
            }
        }
        else
        {
            writeTextNode("screenError","Eroare! Trebuie introdus textul descrierii");
            showElem("screenError");
            }
    }
    else
    {
        writeTextNode("screenError","Eroare! Nu am gasit obiectul text");
        showElem("screenError");
    }
    
    showElem("screenError");
    return false;
}
function readEditDescriptionResponse(xmlRoot)
{
	if (!xmlRoot.firstChild)
	{ 
		alert("raspuns vid");
	}
	else
	{
		//the value we need to display 
		response = xmlRoot.getElementsByTagName("editResponse");
        var responseText=response[0].firstChild.nodeValue;
		//alert("ok: "+response[0].firstChild.nodeValue);
        
        writeTextNode("screenError",responseText);
        showElem("screenError");
        //pageReload();
	}
	
}
function kajContact(userId)
{
    hideElem("screenError");
    var nume=document.getElementById('contactNume');
    if (nume)
        {
        var email=document.getElementById('contactEmail');
            if (email)
            {
                tinyMCE.triggerSave(true,true);
                if (tinymce)
                {
                    var message=tinyMCE.get('contactMessage').getContent();
                    //only continue if xmlhttp isn't void
                    if (message!="")
                    {
                        if (xmlhttp)
                        {
                            //don't try to make server requests if the XMLHttpRequestObject is busy
                            if (!((xmlhttp.readyState==0) || (xmlhttp.readyState==4)))
                            {
                                alert("Can't connect to server, please try again later ("+xmlhttp.readyState+").");
                            }
                            else
                            {
                                //try to connect to the server
                                try
                                {
                                    mesaj=stripText(mesaj);
                                    var params="mesaj="+mesaj+"&nume="+nume+"&email="+email+"&user="+userId;
                                    //initiate the asynchronous HTTP request
                                    globalRequestId="contact";
                                    xmlhttp.open("POST", "./libs/ajax/contact.php", true);
                                    xmlhttp.onreadystatechange=handleRequestStateChange;
                                    //fara astea -setRequestHeader-  nu merge sa faci POST... doar GET
                                    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                                    xmlhttp.setRequestHeader("Content-length", params.length);
                                    xmlhttp.setRequestHeader("Connection", "close");
                                    xmlhttp.send(params);
                                }
                                catch(e)
                                {
                                    alert("Eroare! Datele nu au fost transmise corect: \n"+e.toString());
                                }
                            }
                        }
                        else
                        {
                            writeTextNode("screenError","Eroare! Nu exista conexiune cu serverul");
                            showElem("screenError");
                        }
                    }
                    else
                    {
                        writeTextNode("screenError","Eroare! Trebuie introdus textul mesajului");
                        showElem("screenError");
                    }
                }
                else
                {
                    writeTextNode("screenError","Eroare! Nu am gasit obiectul text");
                    showElem("screenError");
                }
            }
            else
            {
                writeTextNode("screenError","Eroare! Trebuie sa specificati o adresa de email.");
                showElem("screenError");
            }
    }
    else
    {
        writeTextNode("screenError","Eroare! Trebuie sa specificati un nume.");
        showElem("screenError");
    }
        
    showElem("screenError");
    return false;
}
function readContactResponse(xmlRoot)
{
	if (!xmlRoot.firstChild)
	{ 
		alert("raspuns vid");
	}
	else
	{
		//the value we need to display 
		response = xmlRoot.getElementsByTagName("editResponse");
        var responseText=response[0].firstChild.nodeValue;
		//alert("ok: "+response[0].firstChild.nodeValue);
        
        writeTextNode("screenError",responseText);
        showElem("screenError");
        //pageReload();
	}
	
}
function writeTextNode(id,text)
{
    var elem = document.getElementById(id);
        if (elem)
        {
            if (elem.firstChild) 
            {
                elem.removeChild(elem.firstChild);
            }
            var newTextNode=document.createTextNode(text);
            elem.appendChild(newTextNode);
        }
    }
function showElem(id)
{
    var elem = document.getElementById(id);
        if (elem)
        {
            elem.style.display="block";
        }
    }
function hideElem(id)
{
    var elem = document.getElementById(id);
        if (elem)
        {
            elem.style.display="none";
        }
    }
function stripText(text)
{
    //checks the text for a string, and removes it 
    
    //remove spaces &nbsp and <p>&nbsp</p>    alert(text);
    //text=text.replace(/<p>&nbsp</p>/," ");
    text=text.replace(/&nbsp;/g,"");
    //alert(text);
    return text;
    }
