// PLEASE NOTE: This file contains two independent implementations for 
// handling pop up controls: one implementation for Safari (the "__DOM" 
// prefixed functions) and one implementation for all other browsers.  
// Any changes to one of the implementations need to be duplicated in the 
// other implementation.  

var showErrors = false;
var __popContent = "<htm" + "l><hea" + "d><sty" + "le type=\"text/css\">body { text-align:center; margin: 0px;}";
__popContent += "p { color:#888888; width:100%; height:150px; font-family:Arial,sans-serif; font-weight:bold; font-size:17px; margin-top:60px; }</style>";
//The foll 1 Line is added for WR 3867 - To avoid a new entry in tblExternal when the user clicks the back button.
__backButtonRule = "<scrip" + "t>window.history.go(1);</scrip" + "t>"

__popContent += "<hea" +  "d>"+ __backButtonRule  + "<body>";// 
var __transferMessage = "<p>Please wait, we are now transferring you";
var __transferMessage2 = ".</p>";
var __popContent1 = "<div style=\"display:none;\"><form id=\"frmTransfer\" name=\"frmTransfer\""; 
var __popContentEnd = "</form></div>";
var __popContentTimeout = "<script>setTimeout('document.forms[0].submit()',0)</script>";
__popContentEnd += "</b" + "ody></ht" + "ml>";
var agt=navigator.userAgent.toLowerCase();
var is_safari = ((agt.indexOf('safari')!=-1)&&(agt.indexOf('mac')!=-1))?true:false;
var __transferHtml;
var xmlhttp;

function loadXMLDoc(url, popUpWindow) 
{   
    xmlhttp = null;
    // code for Mozilla, etc.
    if (window.XMLHttpRequest) 
    {
        xmlhttp = new XMLHttpRequest();
    }
    // code for IE
    else if (window.ActiveXObject)
    {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    } 
    
    if (xmlhttp!=null) 
    {
      xmlhttp.onreadystatechange=state_Change;
      xmlhttp.open("GET",url,true);
      xmlhttp.send(null);
    }
    else
    {
        if(showErrors) 
        {
		    alert(e);
	    }
    }
    
    function state_Change()   
    { 
        // if xmlhttp shows "loaded"
        if (xmlhttp.readyState == 4)
        {
            // if "OK" 
            if (xmlhttp.status==200)  
            {
                var response = xmlhttp.responseText; 
                response = response.replace('<head>', '<head><base href="http://' + document.domain + msfgGetWebSiteRootPath() + '/framework/pages/"/>');
                popUpWindow.document.write(response);  
            }
            else  
            {
                if(showErrors) 
                {
				    alert(e);
			    }
            }
        }
    }
}
            


function msfgGetPopupCustomControlsPageUrl()
{
	return msfgGetWebSiteRootPath () + "/framework/pages/PopupCustomControls.html";
}

function msfgGetWebSiteRootPath()
{
    var currentUrl = document.location.href.toLowerCase();
   
       if (currentUrl.indexOf("/moneysupermarket/") != -1) 
       {				
          return "/moneysupermarket";
       }
       else if (currentUrl.indexOf("/travelsupermarket/") != -1) 
       {
          return "/travelsupermarket";
       }
       else if (currentUrl.indexOf("/webframeworktest/") != -1) 
       {
          return "/webframeworktest";
       }   
       else
       {
          return "";
       }
}

//******************************************************************************
// FUNCTION:	__popButton_click
//******************************************************************************
// DESC:	This generates a new window and adds html form and submits the form
//			it duplicates the existing viewstate and input elements
// PARAMS:	None
// RETURN:	None
//******************************************************************************
function __popButton_click(element, width, height, location, menubar, resizable, scrollbars, status, toolbar, newWindow, controlType, displayTrMessage, trMessage, transferMessageType, useCustomWindowFeatures, channelId) {
	
	var formName = GetParentFormName(element);
	var targetForm = document.forms[formName];
	
	// calculate screen position co-ordinates required to position popup centrally.
	var left = parseInt((screen.availWidth/2) - (width/2));
    var top = parseInt((screen.availHeight/2) - (height/2));
	
	//This var is set to true if TransferPageType = "Complex", if true, will enable 2 second delayed autosubmit.
	var __autoSubmit = (transferMessageType == 1) 

	if(is_safari) {
		__DOMpopButton_click(element, width, height, location, menubar, resizable, scrollbars, status, toolbar, newWindow, controlType, displayTrMessage, trMessage, transferMessageType, useCustomWindowFeatures, channelId);
	}
	else {

		try {
			// Set window name and properties
			var winName = GetWindowName(newWindow);

			var winString = useCustomWindowFeatures ? "width="+width+",height="+height+",left=" + left + ",top=" + top + ",screenX=" + left + ",screenY=" + top + ",location="+location+",menubar="+menubar+",resizable="+resizable+",scrollbars="+scrollbars+",status="+status+",toolbar="+toolbar : "";
			var isSecure = (document.location.href.indexOf("https:") == 0)
		
			// Make the form action an absolute URL.
			var formAction = ReplaceRemotePageUrl(targetForm.action);
			formAction = msfgResolveUrl(formAction);
			
			var popContent1 = __popContent1 +  " action='" + formAction + "' "  + "\" method=\"post\">";
			
			var winMessage = __popContent;

			// PopupButton control
			if(controlType == 0) {
				popContent1 += "<input name=\"" + element.name + "\" value=\"Button\">";
			} 

			// PopupImageButton control
			if(controlType == 1) {
				popContent1 += "<input name=\"__EVENTTARGET\" value=\"" + element.name + "\">";
				popContent1 += "<input name=\"__EVENTARGUMENT\" value=\"\">";
				//popContent1 += "<input name=\"" + element.name + ".x\" value=\"1\">";
				//popContent1 += "<input name=\"" + element.name + ".y\" value=\"1\">";
			}
			
			// Add viewstate input string
			popContent1 += GetViewStateInputString(targetForm);

			if (isSecure) {
				var winUrl = msfgGetPopupCustomControlsPageUrl();
				
				// Store tranfer page HTML in a page level variable that 
				// accessed and used by the popup window.  
				__transferHtml = winMessage + popContent1 + __popContentEnd;
				
				if (__autoSubmit)
				{
					__transferHtml += __popContentTimeout;
				}
				
				var w = window.open(winUrl, winName, winString);
			}
			else {
				// Open new window
				var w = window.open("", winName, winString);
			
				// Write HTML to window
				w.document.writeln(winMessage); 
				w.document.writeln(popContent1)
				w.document.writeln(__popContentEnd);
				
				if (__autoSubmit)
				{
					w.document.writeln(__popContentTimeout);
				}
				
				// Submit form in window 
				var x = w.document.getElementById("frmTransfer");
				
				if((x != null) && (!__autoSubmit)){
					x.submit();
				}
			}
		}
		catch(e) {
			// Show error
			if(showErrors) {
				alert(e);
			}
		}
	}		
	
	// Clear event 
	return false;
}

//******************************************************************************
// FUNCTION:	__popSubmit
//******************************************************************************
// DESC:	This generates a new window and adds html form and submits the form
//			it duplicates the existing viewstate and sets the correct event target
//			and argument
// PARAMS:	None
// RETURN:	None
//******************************************************************************
function __popSubmit(name, width, height, location, menubar, resizable, scrollbars, status, toolbar, newWindow, controlType, displayTrMessage, trMessage, transferMessageType, useCustomWindowFeatures, channelId, url) {

	var id = GetId(name);
	var element = document.getElementById(id);
	var formName = GetParentFormName(element);
	var targetForm = document.forms[formName]; 
	
	//This var is set to true if TransferPageType = "Complex", if true, will enable 2 second delayed autosubmit.
	var __autoSubmit = (transferMessageType == 1) 
	
	if(is_safari) { 
		__DOMpopSubmit(name, width, height, location, menubar, resizable, scrollbars, status, toolbar, newWindow, controlType, displayTrMessage, trMessage, transferMessageType, useCustomWindowFeatures, channelId, url)
	}
	else {

		try {
			// Set window names and properties
			var winName = GetWindowName(newWindow);
			var winString = useCustomWindowFeatures ? "width="+width+",height="+height+",location="+location+",menubar="+menubar+",resizable="+resizable+",scrollbars="+scrollbars+",status="+status+",toolbar="+toolbar : "";		
			var isSecure = (document.location.href.indexOf("https:") == 0)
			
			// Link button control type 
			if(controlType == 2)
			{
				// Make the form action an absolute URL.
				var formAction = ReplaceRemotePageUrl(targetForm.action);
				formAction = msfgResolveUrl(formAction);
				
				var popContent1 = __popContent1 +  " action='" + formAction + "' method=\"post\">";
				var winMessage = __popContent;
				
				// Add viewstate input string
				popContent1 += GetViewStateInputString(targetForm);

				// Need to set target and argument as input on new form
				popContent1 += "<input name=\"__EVENTTARGET\" value=\"" + name + "\">";
				popContent1 += "<input name=\"__EVENTARGUMENT\" value=\"\">";
								
				// If the current page is secure.
				if (isSecure)
				{
					var winUrl = msfgGetPopupCustomControlsPageUrl();
					
					// Store tranfer page HTML in a page level variable that 
					// accessed and used by the popup window.  
					__transferHtml = winMessage + popContent1 + __popContentEnd;
					
					if (__autoSubmit)
					{
						__transferHtml += __popContentTimeout;
					}
					
					var w = window.open(winUrl, winName, winString);
				}
				else 
				{
					var w = window.open("",winName, winString); 
					 
					// Write html in new window			
					w.document.writeln(winMessage);
					w.document.writeln(popContent1)
					w.document.writeln(__popContentEnd);
					
					if (__autoSubmit)
					{
						w.document.writeln(__popContentTimeout);
					}

					// Get reference to new form and submit it
					var x = w.document.getElementById("frmTransfer");
					
					if ((x != null) && (!__autoSubmit))
					{
						x.submit();
					}
				} 
			}
			else if(controlType == 3) {	
				// Normal hyperlink, just open url in new window
				window.open(url,winName, winString);
			}
		}
		catch(e) {			 	
			// Show error
			if(showErrors) {
				alert(e);
			}
		}
	}
}

//******************************************************************************
// FUNCTION:	__DOMpopButton_click
//******************************************************************************
// DESC:	This generates a new window and adds elements to a form through the
//			DOM and submits the form
// PARAMS:	None
// RETURN:	None
//******************************************************************************
function __DOMpopButton_click(element, width, height, location, menubar, resizable, scrollbars, status, toolbar, newWindow, controlType, displayTrMessage, trMessage, transferMessageType, useCustomWindowFeatures, channelId)
{
	//alert("__DOMpopButton_click");  

	var formName = GetParentFormName(element); 
	var targetForm = document.forms[formName];

	try
	{
		// Create the transfer page content.
		__popContent = "<htm" + "l><hea" + "d><sty" + "le type=\"text/css\">body { text-align:center; }";
		__popContent += "p { color:#888888; width:100%; height:150px; font-family:Arial,sans-serif; font-weight:bold; font-size:17px; margin-top:60px; }</style>";
		__popContent += "</hea" + "d><p>Please wait, we are now transferring you";
		__popContentEnd = ".</p></b" + "ody></ht" + "ml>";

		// Set window name and properties
		var winName = GetWindowName(newWindow);
		var winString = useCustomWindowFeatures ? "width="+width+",height="+height+",location="+location+",menubar="+menubar+",resizable="+resizable+",scrollbars="+scrollbars+",status="+status+",toolbar="+toolbar : "";

		// Declare variables for creating hidden inputs.
		var button;
		var __EVENTTARGET = document.getElementsByName("__EVENTTARGET")[0];
		var __EVENTARGUMENT = document.getElementsByName("__EVENTARGUMENT")[0];
		var blnAddedEventInputs = false;

		// PopupButton control.
		if (controlType == 0)
		{
			button = document.createElement("INPUT");
			button.setAttribute("type", "hidden");
			button.setAttribute("name", element.name);
			button.setAttribute("value", "Button");
			
			targetForm.appendChild(button);
		}

		// PopupImageButton control. 
		if (controlType == 1)
		{
			// Check is the __EVENTTARGET field already exists.
			if (__EVENTTARGET == null)
			{
				// Create the hidden fields
				__EVENTTARGET = document.createElement("INPUT");
				__EVENTTARGET.setAttribute("name", "__EVENTTARGET");
				__EVENTTARGET.setAttribute("value", element.name);
				__EVENTARGUMENT = document.createElement("INPUT");
				__EVENTARGUMENT.setAttribute("name", "__EVENTARGUMENT");
				__EVENTARGUMENT.setAttribute("value", "");

				// Determine where the hidden fields should be added.
				targetForm.appendChild(__EVENTTARGET);
				targetForm.appendChild(__EVENTARGUMENT);
				
				// Flag the hidden inputs for removal at the end.
				blnAddedEventInputs = true;
			}

			// Set the value to the name of the button that was clicked.
			__EVENTTARGET.value = element.name;
		}

		// Open window.
		var w = window.open("", winName, winString);

		// Submit the page into the popup window, then reset the page to the way it was before.

		targetForm.__EVENTTARGET.value = element.name.split("$").join(":");
		
		var originalFormAction = targetForm.action;
		var formAction = ReplaceRemotePageUrl(originalFormAction);
		
		targetForm.action = formAction;		
		targetForm.target = winName;

        targetForm.submit();
		targetForm.action = originalFormAction;		
		targetForm.target = "_self";

		// Check whether to remove any hidden inputs that were added.

		if(button != null)
		{
			button.parentNode.removeChild(button);
		}
		
		if (blnAddedEventInputs)
		{
			__EVENTTARGET.parentNode.removeChild(__EVENTTARGET);
			__EVENTARGUMENT.parentNode.removeChild(__EVENTARGUMENT);
		}
		
	} catch(e) {
		// Show error.
		if(showErrors)
		{
			alert(e);
		}
	}
}


//******************************************************************************
// FUNCTION:	__DOMpopSubmit 
//******************************************************************************
// DESC:	This generates a new window and adds elements to a form through the
//			DOM and submits the form 
// PARAMS:	None
// RETURN:	None
//******************************************************************************
function __DOMpopSubmit(name, width, height, location, menubar, resizable, scrollbars, status, toolbar, newWindow, controlType, displayTrMessage, trMessage, transferMessageType, useCustomWindowFeatures, channelId, url) {
	
	//alert("__DOMpopSubmit");
	
	var id = GetId(name); 
	var element = document.getElementById(id);
	var formName = GetParentFormName(element);
	var targetForm = document.forms[formName];
	
	try {
		__popContent = "<htm" + "l><hea" + "d><sty" + "le type=\"text/css\">body { text-align:center; }";
		__popContent += "p { color:#888888; width:100%; height:150px; font-family:Arial,sans-serif; font-weight:bold; font-size:17px; margin-top:60px; }</style>";
		__popContent += "</hea" + "d><p>Please wait, we are now transferring you";
		__popContentEnd = ".</p></b" + "ody></ht" + "ml>";

		// Set window name and properties
		var winName = GetWindowName(newWindow);
		var winString = useCustomWindowFeatures ? "width="+width+",height="+height+",location="+location+",menubar="+menubar+",resizable="+resizable+",scrollbars="+scrollbars+",status="+status+",toolbar="+toolbar : "";
		
		// PopupLinkButton control 
		if(controlType == 2) { 

			var w = window.open("",winName, winString);  	    
		    
	   		var originalFormAction = targetForm.action;
    		var formAction = ReplaceRemotePageUrl(originalFormAction);

    		targetForm.action = formAction;		
   			targetForm.target = winName;
			targetForm.__EVENTTARGET.value = name.split("$").join(":");
			targetForm.submit();
    		targetForm.action = originalFormAction;		
			targetForm.target = "_self";
			
		}
		else if(controlType == 3) {	
			// PopupHyperLink control
			window.open(url,winName, winString);
		}
	}
	catch(e) {	
		// Show error
		if(showErrors) {	
			alert(e);
		}
	}
}

//******************************************************************************
// FUNCTION:	GetWindowName
//******************************************************************************
// DESC:	Generates a unique window names based on the current UTC date
// PARAMS:	None
// RETURN:	string
//******************************************************************************
function GetWindowName(isNewWindow) 
{
	var uniqueName = "_transfer";
	
	if(isNewWindow)
	{
		// Name format e.g. Fri_Oct_28_13_18_53_UTC_0100_2005
		uniqueName = new Date().toString().replace(/\s/g,"_");
		uniqueName = uniqueName.replace(/:/g,"_");
		uniqueName = uniqueName.replace(/\+/g,"_");
	}

	return uniqueName;
}

//******************************************************************************
// FUNCTION:	ReplaceRemotePageUrl
//******************************************************************************
// DESC:	Replaces the async parameter of the remotePage querystring with a blank
// PARAMS:	none
// RETURN:	string
//******************************************************************************
function ReplaceRemotePageUrl (remotePage)
{
	// Fixes an issue to submit deeplink forms from the results page
	// by removing async from the querystring.
	var rexp = /[?&]async=true/gi;
	var replaceRemotePage = remotePage;
	
	if (replaceRemotePage == null || replaceRemotePage == '')
	{
	    replaceRemotePage = document.URL;
	}
	
	replaceRemotePage = replaceRemotePage.replace(rexp,'');
	// Return
	return replaceRemotePage;
	
}

//******************************************************************************
// FUNCTION:	GetParentFormName
//******************************************************************************
// DESC:	Returns the name of the form to which the element belongs.
// PARAMS:	element - The child element of the form.
// RETURN:	formName - The form's name (blank if no form can be found).
//******************************************************************************
function GetParentFormName(element)
{
	var node = element;
		
	while (node != null)
	{
		if (node.nodeName != 'undefined')
		{
			if (node.nodeName.toUpperCase() == 'FORM')
			{
				return node.name; 
			}
		}
		
		node = node.parentNode; 
	}
	
	return '';
}

//******************************************************************************
// FUNCTION:	GetViewStateInputString
//******************************************************************************
// DESC:	Generates the viewstate input string from current document
// PARAMS:	form object
// RETURN:	string
//******************************************************************************
function GetViewStateInputString(targetForm)
{
	var strInput = '';
	len = targetForm.elements.length;
	
	for(i=0 ; i<len ; i++)
	{
		//alert("In form " + formCount + " element " + i + " " + document.forms[formCount].elements[i].getAttribute("name"));
		if(targetForm.elements[i].getAttribute("name") == "__VIEWSTATE")
		{
			strInput= "<input name=\"__VIEWSTATE\" value=\"" + targetForm.elements[i].value + "\">";
			break;
		}
	}
		
	return strInput;
}

//******************************************************************************
// FUNCTION:	GetId
//******************************************************************************
// DESC:	Generates an id based on
// PARAMS:	string
// RETURN:	string
//******************************************************************************
function GetId(str)
{
	return (str.replace(/:/g,'_')).replace(/\$/g,'_');
}

