// Add jquery:
document.write("<scr" + "ipt src='/scripts/jquery-1.7.1.min.js'></scr" + "ipt>");
document.write("<scr" + "ipt src='/scripts/jquery.subwayPlugins.js'></scr" + "ipt>");

// Waits until facebook script loaded:
function fbEnsureInit(callback) {
	if (!window.fbApiInitialized) {
		setTimeout(function() { fbEnsureInit(callback); }, 50);
	} else {
		if (callback) { callback(); }
	}
}
var SubFB = {
	streamPublish: function(URL, Rel, Message, ActionLinks){
		FB.ui({ 
			method: 'stream.publish'
			, message: Message
			, action_links: ActionLinks//[{ text:'Subway', href:URL }] 
		});
		//			, display: 'dialog'
	}
	, metrics: function(URL) {
		$.post('/Facebook/local/like_click.asp', { url:URL });
	}
}


function WindowOpenCentre(URL, width, height, resizable, scrollable, status)
{
	// Show edit form:
	var left   = (screen.width  - width)/2;
	var top    = (screen.height - height)/2;
	var params = 'width='+width+', height='+height;
	params += ', top='+top+', left='+left;
	params += ', directories=no';
	params += ', location=no';
	params += ', menubar=no';
	params += ', resizable=' + resizable;
	params += ', scrollbars=' + scrollable;
	params += ', status=' + status;
	params += ', toolbar=no';
	newwin=window.open(URL, 'Popup', params, true);
	if (window.focus)
		newwin.focus()
	else
		alert("It appears you have a popup blocker installed.  Please add us to your popup blocker.");
	return newwin;
}

// JavaScript Document
var Catering = {
	
	ValidateLogin: function(sender, form) 
	{
		if (!FormsHelper.ValidateTextField("txtLogUName", "You must enter an email address."))
			return false;
		if (!FormsHelper.ValidateTextField("txtLogPwd", "You must enter your password."))
			return false;
		return true;
	}
}

/* Javascript forms helper */
var FormsHelper = {
	IsValid: false
	, LoadedHTMLScripts: false
	, _LiveSubmitCallback: null
	
	// Validates a text field, shows message if empty.
	, ValidateTextField : function(CtrlID, ValMessage)
	{
		var oCtrl = document.getElementById(CtrlID);
		if (oCtrl)
			if (oCtrl.value == '')
			{
				alert(ValMessage);
				oCtrl.focus();
				return false;
			}
		return true;
	}
	, ValidateCheckbox : function(CtrlID, ValMessage)
	{
		if (!$('#' + CtrlID).is(":checked"))
		{
			alert(ValMessage)
			$('#' + CtrlID).focus();
			return false;
		}
		return true;
	}
	
	, SubmitFormAction : function(FormID, Action, ActionValue)
	{
		if (!$get(FormID).hdAction){
			var e = document.createElement("input");
			e.setAttribute("type","hidden");
			e.setAttribute("id","hdAction");
			e.setAttribute("name","hdAction");
			$get(FormID).appendChild(e);
		}
		if (!$get(FormID).hdActionValue){
			var e = document.createElement("input");
			e.setAttribute("type","hidden");
			e.setAttribute("id","hdActionValue");
			e.setAttribute("name","hdActionValue");
			$get(FormID).appendChild(e);
		}

		$get(FormID).hdAction.value = Action;
		$get(FormID).hdActionValue.value = ActionValue;
		$get(FormID).submit();		  
	}
	
	, ValidateEmail : function(emailStr) {
		
		// checks if the e-mail address is valid
		var emailPat = /^(\".*\"|[A-Za-z0-9\_][A-Za-z0-9\.\-\_]*)@(\[\d{1,3}(\.\d{1,3}){3}]|([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,3})$/; //"
		var matchArray = emailStr.match(emailPat);
		if (matchArray == null) {
			//field.select();
			//field.focus();
			alert("Please enter a valid Email address.\n(check the '@' and '.' characters)");
			return false;
		}
		
		// make sure the IP address domain is valid
		var IPArray = matchArray[2].match(/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/);
		if (IPArray != null) {
			for (var i=1; i<=4 ;i++) 
			{
				if (IPArray[i]>255) 
				{
					//field.select();
					//field.focus();
					alert("Please enter a valid destination IP address.")
					return false;
				}
			}
		}
		return true;
	}
	
	, SetSubmit: function(Bool) {
		FormsHelper.IsValid = Bool;
		return Bool
	}
	
	
	// Hidden form submitting:
	, RegisterLiveSubmit: function(FormID, SubmitCallback)
	{
		var oFrame = $get('fmSubmitter');
		if (!oFrame || oFrame == undefined)
		{
			oFrame = document.createElement("iframe");
			oFrame.setAttribute("id","fmSubmitter");
			oFrame.setAttribute("name","fmSubmitter");
			oFrame.setAttribute("height","1");
			oFrame.style.visibility = "hidden";
			oFrame.style.height = "1";
			document.body.appendChild(oFrame);
		}
		
		this._LiveSubmitCallback = SubmitCallback;
		
		// Mozilla, Opera and webkit nightlies currently support this event
		if ( document.addEventListener ) {//alert('moz');
			oFrame.removeEventListener("load", FormsHelper._DoLiveSubmitCallback, false);
			oFrame.addEventListener("load", FormsHelper._DoLiveSubmitCallback, false);
	
		// If IE event model is used
		} else if ( document.attachEvent ) {//alert('ie');
			oFrame.detachEvent("onload", FormsHelper._DoLiveSubmitCallbackIE);
			oFrame.attachEvent("onload", FormsHelper._DoLiveSubmitCallbackIE);
			
		}
		$get(FormID).target = oFrame.id;
	}
	, _DoLiveSubmitCallback: function(){ 
		if (FormsHelper.IsValid)
		{
			var sRtn = $get("fmSubmitter").contentDocument.body.innerHTML;
			sRtn = sRtn.replace(/^\s+|\s+$/g,"");
			FormsHelper._LiveSubmitCallback(sRtn); 
			//SubmitCallback($get("fmSubmitter").contentDocument.body.innerHTML); 
		}
	}
	, _DoLiveSubmitCallbackIE: function(){ 
		if (FormsHelper.IsValid)
		{
			var sRtn = $get("fmSubmitter").contentWindow.document.body.innerHTML;
			sRtn = sRtn.replace(/^\s+|\s+$/g,"");
			FormsHelper._LiveSubmitCallback(sRtn);
			//SubmitCallback($get("fmSubmitter").contentWindow.document.body.innerHTML);
		}
	}
	
	
	// Helper Methods
	, ReloadPage: function() {
		document.location.href = document.location.href;
	}
	
	// ov = true / false show screen overlay
	// p = parent (usually this?)
	, OpenWindow: function(url,wd,hg,ov,p,opt)
	{
		// Has scripts??
		/*if (!FormsHelper.LoadedHTMLScripts)
		{
			document.write("<scr" + "ipt src='/RipeCMS/HTMLEditor/scripts/innovaeditor.js'></scr" + "ipt>");
			FormsHelper.LoadedHTMLScripts = true;
		}*/
		var id = "ID"+(new Date()).getTime();
		var f = new ISWindow(id);
		f.iconPath = "/RipeCMS/HTMLEditor/scripts/icons/";
		f.show({width:wd+"px", height:hg+"px",overlay:ov,center:true, url:url, openerWin:p, options:opt});
	}
	
	, doLogin: function(RedirTo){	
		if (!FormsHelper._ValidateLoginForm())
			return;
		
		var sData = $('#formLogin').serialize();
		$.post("/EatFreshClub/_inc/functionsAJAX.asp", sData+"&actn=login", function(data){
			if (data.error)
			{
				alert(data.error);
				$('#btnLogin').val("Login");
				$('#btnLogin').attr("disabled", "");
				return;
			}
			// Login:
			window.top.location = RedirTo;//"http://www.facebook.com/SubwayAustralia?sk=app_158188097536417";
			//window.location.href = "tab_EFCWelcome.asp";
		}, "json");
		$('#btnLogin').val("please wait...");
		$('#btnLogin').attr("disabled", "disabled");
	}
	, _ValidateLoginForm: function()
	{
		_bFormValid = false;
		
		if (!FormsHelper.ValidateTextField("txtLogUName", "You must supply your login email address."))
			return false;
		if (!FormsHelper.ValidateTextField("txtLogPwd", "You must supply a password."))
			return false;
			
		// Validate email:
		var oTxt = $get("txtLogUName");
		if (!FormsHelper.ValidateEmail(oTxt.value))
		{
			oTxt.focus();
			return false;
		}
		
		return true;
	}

}

// left padding s with c to a total of n chars
function pad_left(s, c, n) {
    if (! s || ! c || s.length >= n) {
        return s;
    }

    var max = (n - s.length)/c.length;
    for (var i = 0; i < max; i++) {
        s = c + s;
    }

    return s;
}

// right padding s with c to a total of n chars
function pad_right(s, c, n) {
    if (! s || ! c || s.length >= n) {
        return s;
    }

    var max = (n - s.length)/c.length;
    for (var i = 0; i < max; i++) {
        s += c;
    }

    return s;
}

function $get(CtrlID)
{
	var oCtrl = document.getElementById(CtrlID);
	if (oCtrl)
		return oCtrl;
}
function validateEmail(Ctrl)
{
	return FormsHelper.ValidateEmail($(Ctrl).val());
}

var Overlay = {
	_olay: null
	, _oContent: null
	
	, ShowForgotPwdUI : function(SrcEmailFieldID, SrcPwdFieldID, CheckPwdPage, Flavour)
	{
		var sPwdPage = '/_inc/tools/forgotPwd.asp';
		if (CheckPwdPage != null && CheckPwdPage != '')
			sPwdPage = CheckPwdPage;
		if (Overlay._oContent != null)
			return;
		
		var oInput = $('<div id="dvForgotPwd" style="display:block;width:400px;position:absolute;top:0px;background:#fff;padding:10px;border:4px solid orange;">'
            + '<div>'
            + '    <p class="textHeading">Password Retrieval</p>'
            + '    <p class="textStandard">Use the following for to retrieve your password.  Please enter your account email address:</p>'
            + '    <p>'
            + '        <input type="text" id="txtFPUName" name="txtFPUName" value="" style="width:300px;" />'
            + '    </p>'
            + '    <p>'
            + '        <input type="button" id="btnFPSend" value="Send my Password" />'
            + '        <input type="button" id="btnFPCancel" value="Cancel" />'
            + '    </p>'
            + '    <div id="dvFPMessage" class="textStandard"></div>'
            + '</div>'
        	+ '</div>');
		Overlay._oContent = oInput;
		$('body').append(oInput);
		oInput.center();

		oInput.find('input[id=txtFPUName]').val($('#' + SrcEmailFieldID).val());
		oInput.find('input[id=btnFPSend]').click(function(){
			$.ajax({
				url: sPwdPage
				, type: 'POST'
				, data: { action:'forgotPwd', pwd:oInput.find('input[id=txtFPUName]').val(), flv:Flavour }
				, success: function(data, textStatus, XMLHttpRequest){
					var oMsg = oInput.find('div[id=dvFPMessage]');
					if (data == "1")
					{
						oMsg.html("Your password has been sent to your registered email address.<br><input type='button' id='btnFPOk' value='Continue' />");
						oInput.find('input[id=btnFPOk]').click(function(){ 
							$('#' + SrcEmailFieldID).val(oInput.find('input[id=txtFPUName]').val());
							oInput.remove(); 
							Overlay._oContent=null; 
							$('#' + SrcPwdFieldID).focus();
						});
						oInput.center();
					}
					else
						oMsg.html(data);
				}
			});
		});
		oInput.find('input[id=btnFPCancel]').click(function(){ oInput.remove(); Overlay._oContent=null; });
	}
	
	, Show : function()
	{
		//this._RenderBox();
		//this._oContent.innerHTML = "<h2>Loading</h2>";
		//Overlay.ShowLoading();
		this._olay.style.display = 'block';
	}
	, Hide : function()
	{
		if (this._olay)
			this._olay.style.display = 'none';
	}
	
	, ShowLoading: function(loadingContainer)
	{
		this._RenderBox();
		
		if (this._oContent.innerHTML == "")
			this._oContent.innerHTML = "<span class='textSubHeading'>Loading, please wait...</span>";
		else
			loadingContainer.innerHTML = "<span class='textSubHeading'>Loading, please wait...</span>";
	}
	
	, ShowContent: function(Content)
	{
		this._RenderBox();
		
		
		if (typeof(Content) == 'string')
			this._oContent.innerHTML = Content;
		else if (typeof(Content) == 'object')
		{
			//this._oContent.innerHTML = "";
			this._oContent.appendChild(Content.parentNode.removeChild(Content));
			//this._oContent.appendChild(Content.childNodes[0]);
		}
		this.Show();
	}

	
//var q = document.getElementById('img1');
//o.appendChild(q.parentNode.removeChild(q));


	// Internal methods
	, _RenderBox: function()
	{
		if (Overlay._olay == null)
		{
			// Add:
			//var oOlayOut = Overlay._olay;
			
			// Simple window:
			var o = document.createElement("div");
			o.setAttribute("id","dvOlayOuter");
			//o.setAttribute("class","white_content");
			o.setAttribute("style","display:none;position: absolute;top:35%; left:35%; width:30%; padding:16px; border:4px solid orange; background-color: white; z-index:1002;");
			document.body.appendChild(o);
			
			Overlay._olay = o;
			Overlay._oContent = o;
			
			// Drop shadow boxes method::
			/*var oOlayOut = document.createElement("div");
			oOlayOut.setAttribute("id","dvOlayOuter");
			oOlayOut.setAttribute("class","blur");
			oOlayOut.setAttribute("style","display:none;");
			document.body.appendChild(oOlayOut);
			
			var m = document.createElement("div");
			m.setAttribute("class","shadow");
			oOlayOut.appendChild(m);
			
			var c = document.createElement("div");
			c.setAttribute("class","content");
			m.appendChild(c);
			
			
			Overlay._olay = oOlayOut;
			Overlay._oContent = c;*/
			
			//Overlay._olay.style.display = "block";
			
			//Overlay._oContent.innerHTML = "Hello";
			
			
//			if (!$get(FormID).hdAction){
//			var e = document.createElement("input");
//			e.setAttribute("type","hidden");
//			e.setAttribute("id","hdAction");
//			e.setAttribute("name","hdAction");
//			$get(FormID).appendChild(e);
//		}
		}
	}
	
	// Different method styles:
	/*.black_overlay{
		display: none;
		position: absolute;
		top: 0%;
		left: 0%;
		width: 100%;
		height: 100%;
		background-color: black;
		z-index:1001;
		-moz-opacity: 0.8;
		opacity:.80;
		filter: alpha(opacity=80);
	}
	.white_content {
		display: none;
		position: absolute;
		-top: 25%;
		-left: 25%;
		-width: 50%;
		-height: 50%;
		top: 35%;
		left: 35%;
		width: 30%;
		padding: 16px;
		border: 4px solid orange;
		background-color: white;
		z-index:1002;
		overflow: auto;
	}
	
	.blur{
		background-color: #ccc;
		color: inherit;
		margin-left: 4px;
		margin-top: 4px;
		
		position: absolute;
		top: 35%;
		left: 35%;
		width: 30%;
		-height: 50%;
		-padding: 5px;
	}
	
	.shadow,
	.content{
		position: relative;
		bottom: 2px;
		right: 2px;
	}
	
	.shadow{
		background-color: #666;
		color: inherit;
	}
	
	.content{
		background-color: #fff;
		color: #000;
		border: 1px solid #000;
		padding: .5em 2ex;
	}*/
}

/* Ataye AJAX now common */
var ATAYE_RESPONSE_OK = 200;		// Successful response.
var AtayeAJAX_2 = function()
{
	this._workingProcessor = null;
	this._ProcessorList = Array("Msxml2.XMLHTTP.6.0", "Msxml2.XMLHTTP.5.0", "Msxml2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP");
	this._hasError = false;
	this.RequestURL = null;
	this.ErrorText = null;
    this.Silent = false;
	this.Debugging = false;
	
	this.Get = function(params, callbackFunction)
	{
		this.Debug("SEND: " + params);
		this.OnComplete = callbackFunction;
		this.GetURL(params);
	}
	
	this.GetURL = function(params)
	{
		if (!this._workingProcessor)
			if (!this._getProcessor())
			{
            	_hasError = true;
                ErrorText = "Error getting processor";
				return false;
			}
		
		// Start:
		try
		{
			// If no url set, use url of current page:
			if (!this.RequestURL)
			{
				this.RequestURL = document.location.href;
				this.RequestURL = this.RequestURL.split('#')[0];
			}
            else if (this.RequestURL.charAt(0) == '/')
            {
            	this.RequestURL = document.location.protocol + '//' + document.location.host + this.RequestURL;
            }
			
			// Send request:
			this._workingProcessor.open("POST", this.RequestURL, true);
			this._workingProcessor.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
			this._workingProcessor.onreadystatechange = this._onResponse.bind(this, this._workingProcessor);
			this._workingProcessor.send(params);
			
			return true;
		} 
		catch(e)
		{
        	this._hasError = true;
            this.ErrorText = e.description;
			if (!this.Silent)
            	alert("There was an error with the request: " + e.description);
            this.OnError(e);
		}
	}
	
	Function.prototype.bind = function(object) 
	{      
		var method = this;
		arguments.slice = Array.prototype.slice;
		var oldArguments = arguments.slice(1);
		return function() { 
			return method.apply(object, oldArguments); 
		};
	}
	
	this._onResponse = function(AjaxObj)
	{
		if (AjaxObj == undefined)
			return;
			
			//alert(AjaxObj);
		var Status = {
			'State' : AjaxObj.readyState
			, 'Status' : (AjaxObj.readyState == 4)? AjaxObj.status : null
		}
		this.OnStatusChange(Status);
		
		if (Status.State == 4)
		{
			this.OnComplete(Status, this._workingProcessor.responseText);
		}
	}

	
	
	// Public method, handle response:
	this.OnStatusChange = function(Status)
	{
		//alert("Status: " + Status.State);
	}
	
	this.OnComplete = function(Status, Response)
	{
		//alert("State: " + Status.Status + ", Response: " + Response);
	}
    
    this.OnError = function(Err)
    {
    
    }
	

	// Private method. Get a processor:
	this._getProcessor = function()
	{
		var objException = null;
		var oProc = null;
		var arProcessorList = new Array("Msxml2.XMLHTTP.6.0", "Msxml2.XMLHTTP.5.0", "Msxml2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP");
        
		// Browser:
		if ( document.all && document.getElementById && !window.opera ) {
            AtayeAJAX.IE = true;
        }
        if ( !document.all && document.getElementById && !window.opera ) {
            AtayeAJAX.FF = true;
        }
        if ( document.all && document.getElementById && window.opera ) {
            AtayeAJAX.OP = true;
        }
		
		// Get processor:
		try
		{
			oProc = new XMLHttpRequest();
		} 
		catch (e)
		{
			for(var i=0; i < arProcessorList.length && !oProc; i++)
			{
				try
				{
					oProc = new ActiveXObject(arProcessorList[i]);
				}catch (objException){}
			}
		}
		
		if (!oProc) 
		{
			_hasError = true;
			alert("Could not retreive a valid progID of Class: " + arProcessorList[arProcessorList.length-1]+". (original exception: "+e+")");
			return false;
		}
		else
		{
			this._workingProcessor = oProc;
			this._workingProcessor.onreadystatechange = AtayeAJAX._onResponse;
		}
		return true;
	}
	
	// Public support method.  Returns the value of the given control:
	this.GetFormFieldValue = function(CtrlID)
	{
		var oCtrl = document.getElementById(CtrlID);
		if (oCtrl)
		{
			//return oCtrl.type;
			//return oCtrl.value;
			switch(oCtrl.type.toLowerCase())
			{
				case "checkbox":
					return oCtrl.checked;
					
				default:
					return oCtrl.value;
			}
			// Get type and then get value:
			
		}
	}
	
	this.Debug = function(Message)
	{
		if (!this.Debugging)
			return;
		
		var oOutput = $get('dvAJAXDebugOutput');
		if (oOutput == undefined)
		{
			oOutput = document.createElement("div");
			oOutput.setAttribute("id","dvAJAXDebugOutput");
			oOutput.setAttribute("style","height:100px;background:#fff;overflow:auto;");
			document.body.appendChild(oOutput);
			oOutput.innerHTML = "<span style='font-size:12pt;font-weight:bold;'>Ataye AJAX Debug window.</span><br/>";
		}
		
		oOutput.innerHTML = Message + "<br/>" + oOutput.innerHTML;
	}
}


