/**
 * Ajax.js
 *
 * Collection of Scripts to allow in page communication from browser to (struts) server
 * ie can reload part instead of full page
 *
 * How to use
 * ==========
 * 1) Call retrieveURL from the relevant event on the HTML page (e.g. onclick)
 * 2) Pass the url to contact (e.g. Struts Action) and the name of the HTML form to post
 * 3) When the server responds ...
 *		 - the script loops through the response , looking for <span id="name">newContent</span>
 * 		 - each <span> tag in the *existing* document will be replaced with newContent
 *
 * NOTE: <span id="name"> is case sensitive. Name *must* follow the first quote mark and end in a quote
 *		 Everything after the first '>' mark until </span> is considered content.
 *		 Empty Sections should be in the format <span id="name"></span>
 */

//global variables
  	var req;
  	var response;
  	var queryCampaignID;
//	var SERVER_URL = 'http://yarra:8080/mjhorne/emailer';
	var SERVER_URL = 'http://www.ayudamail.com.au/emailer-1.4.12';
//TODO

  /**
   * Get the contents of the URL via an Ajax call
   * url - to get content from (e.g. /struts-ajax/sampleajax.do?ask=COMMAND_NAME_1) 
   * nodeToOverWrite - when callback is made
   * nameOfFormToPost - which form values will be posted up to the server as part 
   *					of the request (can be null)
   */

  function retrieveURL(url,nameOfFormToPost) {
    
		//get the (form based) params to push up as part of the get request
		url=url;
		//+getFormAsString(nameOfFormToPost);
		
		//Do the Ajax call
		if (window.XMLHttpRequest) { 
		
			// Non-IE browsers
			req = new XMLHttpRequest();
			//req.onreadystatechange = processStateChange;
		
			req.onreadystatechange = function() {

				if (req.readyState == 4) { // Complete

					if (req.status == 200) { // OK response

						response = req.responseText;
					}
				}
			}

			try {
				req.open("GET", url, true); //was get
			} catch (e) {
				alert("Problem Communicating with Server\n"+e);
			}

			req.send(null);

		} else if (window.ActiveXObject) { // IE

			req = new ActiveXObject("Microsoft.XMLHTTP");

			if (req) {
				req.onreadystatechange = processStateChange;
				req.open("GET", url, true);
				req.send();
			}

		}

		return null;

	}


	function processStateChange() {
		if (req.readyState == 4) { // Complete
			if (req.status == 200) { // OK response
				response = req.responseText;
			}
		}
	} 
	
	function initialiseQueryCampaignWithCampaignType(shortInterval, longInterval, id, 
		sending, campaignType) 
	{

		interval = 5;
		
		queryCampaignID = id;
		
		makeRequestWithCampaignType(sending, campaignType);

		setInterval("makeRequestWithCampaignType('" + sending + "', '" 
													+ campaignType + "')", interval*1000);
	}

	 function initialiseQueryCampaign(shortInterval, longInterval, id) {

		interval = 5;
		
		queryCampaignID = id;
		
		makeRequest();

		setInterval("makeRequest()", interval*1000);
		
	}
		
	function initialiseQueryCampaignList() {

		interval = 5;

		queryCampaignID = null;
		
		makeRequest();

		setInterval("makeRequest()", interval*1000);

	}

	// Loops infinitely, trying to make requests
	function makeRequest() {

		if(queryCampaignID == null) {

			retrieveURL(SERVER_URL + '/do/Query?method=queryList', null);

			var campaignStatuses = findElements("campaignStatus", response);

			if(campaignStatuses) {
				for(i = 0; i < campaignStatuses.length; i++) {
//				alert("campaignStatus_" + campaignStatuses[i].id);
				//alert(document.getElementById("campaignStatus_" + campaignStatuses[i].id));
//
//
//

					document.getElementById("campaignStatus_" + campaignStatuses[i].id).innerHTML = campaignStatuses[i].value;
				}
			} 

		} else {
			retrieveURL(SERVER_URL + '/do/Query?method=query&id=' + queryCampaignID, null);

			if(response) {
				var campaignStatuses = findElements("campaignStatus", response);
				
				if(campaignStatuses) {
					for(i = 0; i < campaignStatuses.length; i++) {
						document.getElementById("campaignStatus").innerHTML = campaignStatuses[i].value;
					}
				} else {
					document.getElementById("campaignStatus").innerHTML = "Determining campaign status, please wait..."; 
				} 
			} else {
				document.getElementById("campaignStatus").innerHTML = "Determining campaign status, please wait...";
			}
			
			var sendingActions = findElements("sendingActions", response);

			if(sendingActions) {
				for(i = 0; i < sendingActions.length; i++) {
					document.getElementById("sendingActions").innerHTML = sendingActions[i].value;
				}
			}
		}
	}


	//make a request and replace only the html that needs replacing	
	function makeRequestWithCampaignType(sending, campaignType) {

		if(queryCampaignID != null) 
		{
			retrieveURL(SERVER_URL + '/do/Query?method=query&id=' + queryCampaignID, null);
			
			if(response)
			{
				//get the new campaignType from the ajax status request
				var campaignTypeXML = findElements("campaignType", response);
				if(campaignTypeXML)
				{
					//campaignType = campaignTypeXML[0].value;
				}

				//get the new sending status from the ajax request
				var sendingStatXML = findElements("sendingStat", response);
				if(sendingStatXML)
				{
					sending = sendingStatXML[0].value;
				}
			}

			if(response) 
			{
				var campaignStatuses = findElements("campaignStatus", response);
			
				if(campaignStatuses) {
					for(i = 0; i < campaignStatuses.length; i++) 
					{
						if(campaignType == "live")
						{
							jQuery('#testCampaignStatus').html("Idle");
							document.getElementById("campaignStatus").innerHTML = campaignStatuses[i].value;
						}
						else
						{
							if(sending == "true")
							{
								document.getElementById("testCampaignStatus").innerHTML = campaignStatuses[i].value;
							}
							else
							{
								document.getElementById("campaignStatus").innerHTML = campaignStatuses[i].value;
								document.getElementById("testCampaignStatus").innerHTML = campaignStatuses[i].value;
							}
						}
					}
				} 
				else 
				{
					if(campaignType == "live")
					{
						jQuery('#testCampaignStatus').html("Idle");
						document.getElementById("campaignStatus").innerHTML = "Determining campaign status, please wait..."; 
					}
					else
					{
						document.getElementById("testCampaignStatus").innerHTML = "Determining campaign status, please wait..."; 
					}
				} 
			} 
			else 
			{
				if(campaignType == "live")
				{
					jQuery('#testCampaignStatus').html("Idle");
					document.getElementById("campaignStatus").innerHTML = "Determining campaign status, please wait...";
				}
				else
				{
					document.getElementById("testCampaignStatus").innerHTML = "Determining campaign status, please wait...";
				}
			}
			
			var sendingActions = findElements("sendingActions", response);
			
			if(sendingActions && campaignType == "live") 
			{
				jQuery('#testCampaignStatus').html("Idle");

				var fullHtml = '';
				for(i = 0; i < sendingActions.length; i++) 
				{
					fullHtml = sendingActions[i].value;
					if(sending == "false")
					{
						liveRecipients = jQuery(fullHtml).find("#liveRecipients").text();
						unsentLiveRecipients = jQuery(fullHtml).find("#unsentLiveRecipients").text();
						sentSoFar = parseInt(liveRecipients) - parseInt(unsentLiveRecipients);

						jQuery("#liveRecipients").html(liveRecipients);
						jQuery("#unsentLiveRecipients").html(unsentLiveRecipients);
						jQuery("#sentSoFar").html(sentSoFar);
						
						//remove the buttons that were added during sending
						jQuery(".sendingAction").remove();
					}
					else
					{
						//set the appropriate button for the current campaign status
						jQuery(fullHtml).find(".sendingAction").each(function(index) {
							newLink = '<a href="' 
								+ $(this).attr('href') + '" class="' + $(this).attr('class') + '"';
							
							//add confirm dialogs based on what the link is
							if($(this).attr('class').search('sendAbortBtn') > 0)
							{
								newLink += ' onclick="return confirm(\'Are you sure you want to abort the send?\');"';
							}
							else if($(this).attr('class').search('sendNowBtn') > 0)
							{
								newLink += ' onclick="return confirm(\'Are you sure you want to send the campaign now?\');"';
							}
							newLink += '></a>';

							jQuery("#button_" + index).html(newLink);
						});
					}
				}
			}
			else if(sendingActions)
			{
				//update the test details accordingly
				var fullHtml = '';
				for(i = 0; i < sendingActions.length; i++) 
				{
					fullHtml = sendingActions[i].value;
					if(sending == "false")
					{
						jQuery('#testCampaignStatus').html("Idle");

						//take care of the live details
						liveRecipients = jQuery(fullHtml).find("#liveRecipients").text();
						unsentLiveRecipients = jQuery(fullHtml).find("#unsentLiveRecipients").text();
						sentSoFar = parseInt(liveRecipients) - parseInt(unsentLiveRecipients);

						//set each required element
						jQuery("#liveRecipients").html(liveRecipients);
						jQuery("#unsentLiveRecipients").html(unsentLiveRecipients);
						jQuery("#sentSoFar").html(sentSoFar);

						//remove the buttons that were added during sending
						jQuery(".sendingAction").remove();
					}
					else
					{
						//set the buttons for the current campaign status
						jQuery(fullHtml).find(".sendingAction").each(function(index) {
							newLink = '<a href="' + $(this).attr('href') + '" class="' 
								+ $(this).attr('class') + '"';
							
							//add confirm dialogs based on what the link is
							if($(this).attr('class').search('sendAbortBtn') > 0)
							{
								newLink += ' onclick="return confirm(\'Are you sure you want to abort the send?\');"';
							}
							else if($(this).attr('class').search('sendNowBtn') > 0)
							{
								newLink += ' onclick="return confirm(\'Are you sure you want to send the campaign now?\');"';
							}
							newLink += '></a>';

							jQuery("#test_button_" + index).html(newLink);
						});
					}
				}
			}
		}
	}



	function findElements(elementName, textToSplit) {

		if(textToSplit) {
			var returnElements = new Array();

			var elements=textToSplit.split("</" + elementName + ">");

			var j = 0;
			var i = 0;

			for (i = elements.length - 1; i >= 0; --i){

				startPos = elements[i].indexOf("<" + elementName);		

				startIDPos = elements[i].indexOf("id=\"", startPos);		
				
				endPos = elements[i].indexOf(">", startPos);
				if(startPos >= 0) {

					id = null;
					value = null;

					value = elements[i].substring(endPos + 1);

					if((startIDPos < endPos) && (startIDPos > startPos)) {
						id = elements[i].substring(startIDPos + 4, endPos - 1);
					}

					if(value != null) {
						ele = new Object();
						ele.id = id;
						ele.value = value;
						returnElements[j++] = ele;
					}
				}
			}
			return returnElements;

		} else {

			return null;
		}
	}


