/* 
Author: Aaron Murray
email : a a r o n m u r r a y @ m s n . c o m 
*/

/* 
Functions in this file will most likely occur in groups of 3.
The first will be an alias function so the client can call the  SubmitAjaxRequest() easily.
	It will basically do 3 things: 
		1. Identify the server side function that will handle this request
		2. Pass any parameters to this server side function through URL args
		3. Register the name of the js function that will handle the response from the server

The second function will be the EventHandler.
Essentially it is a shell that calls a more detailed function, and passes it any parameters necessary.
It will also handle the processing if the request should fail from the server.

The third function will actually do the processing specified in the EventHandler (function 2).

There may be more functions, but this 3 step layout is the most common. 
Any additional functions will probably be extensions to step 3, which may have complex processing.
The first two should be fairly similar most of the time.
		
*/



/*	*	* CHANGE PICTURE	*	*	*	*	*	*	*	*	*	*	*	*	*/

//handle the changing of the picture dropdown
function ChangePicture(pId, pPicture) {
	SubmitAjaxRequest("changepicture", "&imgid=" + encodeURIComponent(pId) + "&clientimageid=" + encodeURIComponent(pPicture), HandleImageListResponse);
}

//change the image based on the selected ID
function SetImage(pXmlResponseDocument)
{
	try {
		var xmlNodes = pXmlResponseDocument.getElementsByTagName('url');	//get the data in the <url></url> tags
		var xmlIdNodes = pXmlResponseDocument.getElementsByTagName('clientimageid');
		var clientImageId = getInnerText(xmlIdNodes[0]);	//get the data from the first <clientImageId></clientImageId> tag node
		var url = getInnerText(xmlNodes[0]);	//get the data from the first <url></url> tag node
		if (url == "" || url == null) {
			hide(clientImageId);
		} else {
			getObjectByID(clientImageId).src = url;
			show(clientImageId);
		}
	} catch(e) {
		var r = '';
		for (var p in e)
			r += p + ': ' + e[p] + '\n';
		alert("Oops: " + r);
		show(clientImageId);
		getObjectByID(clientImageId).alt = r;
		getObjectByID(clientImageId).src = "/images/site/unavailable.gif";
	}
}

//Called when response comes back from server
function HandleImageListResponse()
{
	// To make sure receiving response data from server is completed
	if(XmlHttp.readyState == 4)
	{
		// To make sure valid response is received from the server, 200 means response received is OK
		if(XmlHttp.status == 200) {
			SetImage(XmlHttp.responseXML.documentElement);
		} else {
			//hide("imgPicture");
			//alert("There was a problem retrieving data from the server." );
		}
	}
}




/*	*	* GET DEBUG INFO	*	*	*	*	*	*	*	*	*	*	*	*	*/

//handle the changing of the picture dropdown
function RequestDebugLog(pDivId, pShowCheckpoints, pShowTraces, pShowWarnings, pShowErrors) {
	SubmitAjaxRequest("GetDebugInfo", "&id=" + encodeURIComponent(pDivId) + "&showcheckpoints=" + encodeURIComponent(pShowCheckpoints) + "&showtraces=" + encodeURIComponent(pShowTraces) + "&showwarnings=" + encodeURIComponent(pShowWarnings) + "&showerrors=" + encodeURIComponent(pShowErrors), HandleRequestDebugLogResponse);
}

//change the image based on the selected ID
function ShowDebugLog(pXmlResponseDocument)
{
    //singles
	var xmlNodesDivId           = pXmlResponseDocument.getElementsByTagName('Id');
    var divId                   = getInnerText(xmlNodesDivId[0]);

    //multiples
	var xmlNodesMessageTypes    = pXmlResponseDocument.getElementsByTagName('MessageType');	//get the data in the <></> tags
	var xmlNodesMessages        = pXmlResponseDocument.getElementsByTagName('Message');
	var xmlNodesTimes           = pXmlResponseDocument.getElementsByTagName('Time');
	var xmlNodesFileNames       = pXmlResponseDocument.getElementsByTagName('FileName');
	var xmlNodesMethodNames     = pXmlResponseDocument.getElementsByTagName('MethodName');
	var xmlNodesLineNumbers     = pXmlResponseDocument.getElementsByTagName('LineNumber');
	var xmlNodesSessionIds      = pXmlResponseDocument.getElementsByTagName('SessionId');

    var lMessageType, lMessage, lTime, lFileName, lMethodName, lLineNumber, lSessionId;
    if (xmlNodesMessageTypes != null && xmlNodesMessageTypes.length > 0 ) {
        var html = "<table class=debugTable width=\"100%\">";
        html += "<tr><th>Type</th><th>Message</th><th>Method Name</th><th>Time</th></tr><tr></tr>";
        
        for (var i=0; i<xmlNodesMessageTypes.length; i++) {
            //for each debug entry
            lMessageType    = getInnerText(xmlNodesMessageTypes[i]);
            lMessage        = getInnerText(xmlNodesMessages[i]);
            lTime           = getInnerText(xmlNodesTimes[i]);
            lFileName       = getInnerText(xmlNodesFileNames[i]);
            lMethodName     = getInnerText(xmlNodesMethodNames[i]);
            lLineNumber     = getInnerText(xmlNodesLineNumbers[i]);
            lSessionId      = getInnerText(xmlNodesSessionIds[i]);

			var cssclass = "debug"+lMessageType;
			if ((i % 2) == 0) {
				cssclass += "Alt";
			}
        
            html += "<tr class='"+cssclass+"'><td valign=top>"+lMessageType+"</td><td>"+lMessage+"</td><td>"+lMethodName+" : "+lLineNumber+"</td><td>"+lTime+"</td></tr>";
            if (lFileName != "") {
				html += "<tr class='"+cssclass+"'><td colspan=6><b>File: </b>"+lFileName+"</td></tr>";
            }
        }

        html += "</table>";
    } else {
        html = "No records found";
    }

    //alert("Debug Records found: " + xmlNodesMessageTypes.length + "\n\nReturned XML from the server:\n" + pXmlResponseDocument.xml + "\n\nClient generated HTML:\n" + html);
    
    clearFieldValue(getObjectByID(divId));
    var theDiv = getObjectByID(divId);
    theDiv.innerHTML = html;
    
}

//Called when response comes back from server
function HandleRequestDebugLogResponse()
{
	// To make sure receiving response data from server is completed
	if(XmlHttp.readyState == 4)
	{
		// To make sure valid response is received from the server, 200 means response received is OK
		if(XmlHttp.status == 200) {
		    if (XmlHttp.responseXML.documentElement != null) {
                ShowDebugLog(XmlHttp.responseXML.documentElement);
            } else {
			    window.status = "Request finished, but it did not return any data.";
            }
		} else if (XmlHttp.status == 401) {
			    window.status = "Access to remove site was denied";
		} else if (XmlHttp.status == 404) {
			    window.status = "Url not found";
		} else if (XmlHttp.status == 500) {
			    window.status = "Internal Server Error on remote site. Status 500";
		} else {
			window.status = "There was a problem retrieving data from the server.";
		}
	}
}





/*	*	* CHANGE COUNTRY	*	*	*	*	*	*	*	*	*	*	*	*	*/

//handle the changing of the country dropdown
function CountryListOnChange() 
{
	var countryList = getObjectByID("countryList");
	var selectedCountry = countryList.options[countryList.selectedIndex].value;	//Getting the selected country from country combo box.
	var urlParams = "&SelectedCountry=" + encodeURIComponent(selectedCountry);

	SubmitAjaxRequest("CHANGECOUNTRY", urlParams, HandleStateListResponse);
}



//Called when response comes back from server
function HandleStateListResponse()
{
	// To make sure receiving response data from server is completed
	if(XmlHttp.readyState == 4)
	{
		// To make sure valid response is received from the server, 200 means response received is OK
		if(XmlHttp.status == 200) {		
			ClearDropDownList("stateList");	
			SetStateListItems("stateList", XmlHttp.responseXML.documentElement);
		} else {
			alert("There was a problem retrieving data from the server." );
		}
	}
}

//adds the states of currently selected country
function SetStateListItems(listName, countryNode)
{
	var stateNodes = countryNode.getElementsByTagName('state');	//the <state> objects in the XML
	var textValue; 
	var optionItem;
	var theList = getObjectByID(listName);
	//Add new states list to the state combo box.
	for (var count = 0; count < stateNodes.length; count++)
	{
   		textValue = getInnerText(stateNodes[count]);
		optionItem = new Option( textValue, textValue,  false, false);
		theList.options[theList.length] = optionItem;
	}
}



