// 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;
	}
	
	, 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});
	}
}

function $get(CtrlID)
{
	var oCtrl = document.getElementById(CtrlID);
	if (oCtrl)
		return oCtrl;
}

var Overlay = {
	_olay: null
	, _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;
	}
}
