/*
takeaway_global.js  v. 1.0

Copyright (c) 2007 Technotion Limited. All rights reserved.
Last modified: 19/June/2007

*/


var Event = {
	add: function(obj,type,fn) {
		if (obj.attachEvent) {
			obj['e'+type+fn] = fn;
			obj[type+fn] = function() { obj['e'+type+fn](window.event); }
			obj.attachEvent('on'+type,obj[type+fn]);
		} else
		obj.addEventListener(type,fn,false);
	},
	remove: function(obj,type,fn) {
		if (obj.detachEvent) {
			obj.detachEvent('on'+type,obj[type+fn]);
			obj[type+fn] = null;
		} else
		obj.removeEventListener(type,fn,false);
	}
}



var is_regexp = (window.RegExp) ? true : false;

var dom_type = '';

if (document.getElementById)
{
	dom_type = "std";
}
else if (document.all)
{
	dom_type = "ie4";
}
else if (document.layers)
{
	dom_type = "ns4";
}


// make an array to store cached locations of objects called by fetch_object
var ta_objects = new Array();





// *** GLOBAL FUNCTIONS ***

// function to emulate document.getElementById
function fetch_object(idname, forcefetch) {
	if (forcefetch || typeof(ta_objects[idname]) == "undefined")
	{
		switch (dom_type)
		{
			case "std":
			{
				ta_objects[idname] = document.getElementById(idname);
			}
			break;

			case "ie4":
			{
				ta_objects[idname] = document.all[idname];
			}
			break;

			case "ns4":
			{
				ta_objects[idname] = document.layers[idname];
			}
			break;
		}
	}
	return ta_objects[idname];
}


// function to set a cookie
function set_cookie(name, value, expires) {
	if (!expires) {
		expires = new Date();
	}
	document.cookie = name + "=" + escape(value) + "; expires=" + expires.toGMTString() +  "; path=/";
}

// function to retrieve a cookie
function fetch_cookie(name)
{
	cookie_name = name + "=";
	cookie_length = document.cookie.length;
	cookie_begin = 0;
	while (cookie_begin < cookie_length)
	{
		value_begin = cookie_begin + cookie_name.length;
		if (document.cookie.substring(cookie_begin, value_begin) == cookie_name)
		{
			var value_end = document.cookie.indexOf (";", value_begin);
			if (value_end == -1)
			{
				value_end = cookie_length;
			}
			return unescape(document.cookie.substring(value_begin, value_end));
		}
		cookie_begin = document.cookie.indexOf(" ", cookie_begin) + 1;
		if (cookie_begin == 0) {
			break;
		}
	}
	return null;
}

// function to delete a cookie
function delete_cookie(name) {
	var expireNow = new Date();
	document.cookie = name + "=" + "; expires=Thu, 01-Jan-70 00:00:01 GMT" +  "; path=/";
}








// *** CONSTANTS ***

var TAKEAWAY_STATUS_CLOSED=0;
var TAKEAWAY_STATUS_OPEN=1;
var TAKEAWAY_STATUS_OPENING=2;
var TAKEAWAY_STATUS_CLOSING=3;

var CALC_TA_STATUS_LIST_MODE=1;
var CALC_TA_STATUS_MENU_MODE=2;

var TEXTAREA_COMMENTS_MAX_CHARS=80;

var weekdaysArr = new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");
var monthArr = new Array("January","February","March","April","May","June","July","August","September","October","November","December");

var tab_index_count = 0;
var order_deadline_timestamp = false;









function padTime(i) {
	if (i<10) {i="0" + i} return i;
}

function getHour(i) {
	if (i==0) {
		return 12;
	} else if (i>12) {
		return (i-12);
	} else {
		return i;
	}

}

function tabindex() {
	tab_index_count++;
	return tab_index_count;
}


function updateTakeawayStatus(timenow, status_mode) {
	
	var minsStat = '';
	var fullStat = '';
	var minsLeft = 0;
	var status = 0;
	var changesMade = 0;

	if (collection_start.length == 0) {
		return false;
	}

	for (i=0;i<collection_start.length;i++) {

		status = 0;
		
		// *** START COLLECTION HOURS ***
		
		// time not set, closed OR before opening gap
		if ( (collection_start[i]==0) || (timenow < (collection_start[i]-countdownGapSeconds)) ) {															
			
			fullStat = '<span class="closed">Closed</span>';
			status = TAKEAWAY_STATUS_CLOSED;

		} else if (timenow < collection_start[i]) {											// opening gap


			minsLeft = Math.ceil(((collection_start[i]-timenow)/60));
			if (minsLeft == 1) {
				minsStat = minsLeft+' Minute';
			} else {
				minsStat = minsLeft+' Minutes';
			}


			fullStat = '<span class="collections">Opening&nbsp;in<br />'+minsStat+'</span>';
			status = TAKEAWAY_STATUS_OPENING;

		} else if (timenow < (collection_end[i]-countdownGapSeconds)) {						// open

			fullStat = '<span class="open">Open</span>';
			status = TAKEAWAY_STATUS_OPEN;

		} else if (timenow < collection_end[i]) {											// closing gap

			
			
			minsLeft = Math.ceil(((collection_end[i]-timenow)/60));
			if (minsLeft == 1) {
				minsStat = minsLeft+' Minute';
			} else {
				minsStat = minsLeft+' Minutes';
			}
			
			fullStat = '<span class="collections">Closing&nbsp;in<br />'+minsStat+'</span>';

			status = TAKEAWAY_STATUS_CLOSING;
		} else {

					
			fullStat = '<span class="closed">Closed</span>';
			status = TAKEAWAY_STATUS_CLOSED;
		}
		
		// only change the collection status if we need to

		if (status_mode == CALC_TA_STATUS_LIST_MODE) {
			if ( (collection_stat[i]!=status) || (status==TAKEAWAY_STATUS_OPENING) || (status==TAKEAWAY_STATUS_CLOSING) ) {
				collection_stat[i]=status;
				changesMade++;
				eval("document.getElementById('c"+i+"').innerHTML=fullStat;");
			}
		} else if (status_mode==CALC_TA_STATUS_MENU_MODE) {

			if (status==TAKEAWAY_STATUS_OPENING) {
				col_alt_msg = 'TAKING COLLECTION ORDERS IN '+minsStat;
				col_img_file = '/images/takeaway-status/collection-closed.gif';
			} else if (status==TAKEAWAY_STATUS_CLOSING) {
				col_alt_msg = 'LAST COLLECTION ORDERS IN '+minsStat;
				col_img_file = '/images/takeaway-status/collection-open.gif';
			} else if ( (collection_stat[i]!=status) && (status==TAKEAWAY_STATUS_CLOSED) ) {
				col_alt_msg = 'COLLECTION ORDERS CLOSED';
				col_img_file = '/images/takeaway-status/collection-closed.gif';
			} else if ( (collection_stat[i]!=status) && (status==TAKEAWAY_STATUS_OPEN) ) {
				col_alt_msg = 'OPEN FOR COLLECTION ORDERS';
				col_img_file = '/images/takeaway-status/collection-open.gif';
			} else {
				col_alt_msg = '';
			}

			if (col_alt_msg!='') {
				col_img = fetch_object('img_col_stat');
				col_img.src = col_img_file;
				col_img.alt = ta_name + ' - ' + col_alt_msg;
				col_img.title = ta_name + ' - ' + col_alt_msg;
			}
			

			
		}


		// // *** START DELIVERY HOURS ***

		if (delivery_start[i]==0) {														// time not set, closed
			fullStat = '<span class="closed">Closed</span>';
			status = TAKEAWAY_STATUS_CLOSED;
		} else if (timenow < (delivery_start[i]-countdownGapSeconds)) {					// before opening gap
			fullStat = '<span class="closed">Closed</span>';
			status = TAKEAWAY_STATUS_CLOSED;
		} else if (timenow < delivery_start[i]) {											// opening gap
			minsLeft = Math.ceil(((delivery_start[i]-timenow)/60));
			if (minsLeft == 1) {
				minsStat = minsLeft+' Minute';
			} else {
				minsStat = minsLeft+' Minutes';
			}
			fullStat = '<span class="deliveries">Deliveries&nbsp;start<br />in '+minsStat+'</span>';
			status = TAKEAWAY_STATUS_OPENING;
		} else if (timenow < (delivery_end[i]-countdownGapSeconds)) {						// open
			fullStat = '<span class="open">Open</span>';
			status = TAKEAWAY_STATUS_OPEN;
		} else if (timenow < delivery_end[i]) {											// closing gap
			minsLeft = Math.ceil(((delivery_end[i]-timenow)/60));
			if (minsLeft == 1) {
				minsStat = minsLeft+'&nbsp;Minute';
			} else {
				minsStat = minsLeft+'&nbsp;Minutes';
			}
			fullStat = '<span class="deliveries">Last&nbsp;orders<br />in '+minsStat+'</span>';
			status = TAKEAWAY_STATUS_CLOSING;
		} else {
			fullStat = '<span class="closed">Closed</span>';
			status = TAKEAWAY_STATUS_CLOSED;
		}

		// only change the delivery status if we need to

		if (status_mode == CALC_TA_STATUS_LIST_MODE) {
			if ( (delivery_stat[i]!=status) || (status==TAKEAWAY_STATUS_OPENING) || (status==TAKEAWAY_STATUS_CLOSING) ) {
				delivery_stat[i]=status;
				changesMade++;
				eval("document.getElementById('d"+i+"').innerHTML=fullStat;");
			}
		} else if (status_mode==CALC_TA_STATUS_MENU_MODE) {
			
			if (status==TAKEAWAY_STATUS_OPENING) {
				del_alt_msg = 'TAKING DELIVERY ORDERS IN '+minsStat;
				del_img_file = '/images/takeaway-status/delivery-closed.gif';
			} else if (status==TAKEAWAY_STATUS_CLOSING) {
				del_alt_msg = 'LAST DELIVERY ORDERS IN '+minsStat;
				del_img_file = '/images/takeaway-status/delivery-open.gif';
			} else if ( (collection_stat[i]!=status) && (status==TAKEAWAY_STATUS_CLOSED) ) {
				del_alt_msg = 'DELIVERY ORDERS CLOSED';
				del_img_file = '/images/takeaway-status/delivery-closed.gif';
			} else if ( (collection_stat[i]!=status) && (status==TAKEAWAY_STATUS_OPEN) ) {
				del_alt_msg = 'OPEN FOR DELIVERY ORDERS';
				del_img_file = '/images/takeaway-status/delivery-open.gif';
			} else {
				del_alt_msg = '';
			}


			if (del_alt_msg != '') {
				del_img = fetch_object('img_del_stat');
				del_img.src = del_img_file;
				del_img.alt = ta_name + ' - ' + del_alt_msg;
				del_img.title = ta_name + ' - ' + del_alt_msg;
			}

			


		}
	}
}



function showStatus() {

	
	

	var serverTimeNow = new Date()/1000;
	serverTimeNow -= serverClientDiff;

	var t = new Date(serverTimeNow*1000);
	var displayDate = weekdaysArr[t.getDay()]+', '+monthArr[t.getMonth()]+' '+t.getDate()+', '+t.getFullYear()+' - '+getHour(t.getHours())+':'+padTime(t.getMinutes())+':'+padTime(t.getSeconds())+' '+(t.getHours()>=12?'pm':'am');
	
	// update dynamic clock
	var takeaway_time = fetch_object('takeaway_time');
	
	if (takeaway_time) {
		takeaway_time.innerHTML = displayDate;
	}


	if (countdown_deadline && countdown_div) {
	
		var countdown_obj = fetch_object(countdown_div);
		
		if (countdown_obj) {
	
		
			
			var seconds_left = countdown_deadline-serverTimeNow;

			if (seconds_left <= 0) {
				
				countdown_obj.innerHTML = 'We\'re sorry, this restaurant is now closed and this order cannot be submitted.';
				countdown_obj.style.visibility='visible';
				countdown_obj.style.display='';
				

			} else if (seconds_left <= 900) {

				var time_left = new Date((countdown_deadline-serverTimeNow)*1000);

						
				countdown_obj.innerHTML = 'Time left to complete order:<br />' + time_left.getMinutes() + ' minute'+ (time_left.getMinutes()==1 ?'' :'s') +',&nbsp;' +  time_left.getSeconds() + ' second' + (time_left.getSeconds()==1 ? '':'s');
				countdown_obj.style.visibility='visible';
				countdown_obj.style.display='';


			}
		}


		
	}
		





	if ( (status_mode>0) && (listUpdated==false) && (t.getSeconds() <= 1) ) {
		updateTakeawayStatus((t/1000), status_mode);
		listUpdated = true;
	} else {
		listUpdated = false;
	}


	setTimeout("showStatus()", 1000);
}




// function to toggle the collapse state of an object, and save to a cookie
function toggle_collapse(objid, collapse_mode) {

	if (!is_regexp)	{
		return false;
	}
	
	obj = fetch_object("collapseobj_" + objid);	
	img = fetch_object("collapseimg_" + objid);
	
	if (!obj) {			// nothing to collapse!
		
		if (img) {		// hide the clicky image if there is one
			img.style.display = "none";
		}

		return false;
	}

	if (collapse_mode == 'COLLAPSE') {

		obj.style.display = "none";
		save_collapsed(objid, true);
		if (img) {
			img.src = '/images/buttons/collapse_tcat_collapsed.gif';
		}
		collapsed_count++;

	} else if (collapse_mode == 'EXPAND') {
		obj.style.display = "";
		save_collapsed(objid, false);
		if (img) {
			img.src = '/images/buttons/collapse_tcat.gif';
		}
		collapsed_count--;

	} else {		// handle non-forced modes, collapse or expand as needed


		if (obj.style.display == "none") {
			obj.style.display = "";
			save_collapsed(objid, false);
			if (img) {
				img.src = '/images/buttons/collapse_tcat.gif';
			}
			collapsed_count--;
		} else {
			obj.style.display = "none";
			save_collapsed(objid, true);
			if (img) {
				img.src = '/images/buttons/collapse_tcat_collapsed.gif';
			}
			collapsed_count++;
		}

	}

	if (collapsed_count < 0) { 
		collapsed_count = 0 
	} else if (collapsed_count>(menu_pos_loaded_arr.length-1)) { 
		collapsed_count = (menu_pos_loaded_arr.length-1);
	}
	
	

	if (collapsed_count==0) {
		document.getElementById('button_expand_all').disabled = true;
	} else if (collapsed_count==(menu_pos_loaded_arr.length-1)) {
		document.getElementById('button_collapse_all').disabled = true;
	} else {
		document.getElementById('button_expand_all').disabled = false;
		document.getElementById('button_collapse_all').disabled = false;
	}

	return true;
}

function cats_collapse_all() {
	for (i in cat_id_arr) {
		var temp = toggle_collapse('catid_'+cat_id_arr[i],'COLLAPSE');
	}
	return false;
}

function cats_expand_all() {
	for (i in cat_id_arr) {
		var temp = toggle_collapse('catid_'+cat_id_arr[i],'EXPAND');
	}
	return false;
}


// #############################################################################
// update menu cookie with collapse preferences
function save_collapsed(objid, addcollapsed)
{
	var collapsed = fetch_cookie(menu_cookie);


	var tmp = new Array();

	if (collapsed != null) {
		collapsed = collapsed.split(".");
		
		for (i in collapsed) {
			if (collapsed[i] != objid && collapsed[i] != "") {
				tmp[tmp.length] = collapsed[i];
			}
		}
	}
	
	if (addcollapsed) {
		tmp[tmp.length] = objid;
	}
	

	expires = new Date();
	expires.setTime(expires.getTime() + (1000 * 86400 * 365));

	set_cookie(menu_cookie, tmp.join("."), expires);

	
}

function in_array(needle, haystack) {
	for (h in haystack) {
		if (haystack[h] == needle) {
			return true;
		}
	}
	return false;
} 

function menu_init(mode) {

	// enable expand/collapse buttons
	

	if (collapsed_count==0) {			// if everything is expanded (default)
		document.getElementById('button_collapse_all').disabled = false;		// enable collapse all button
		
	} else if (collapsed_count==(menu_pos_loaded_arr.length-1)) {		// if everything is collapsed	
		document.getElementById('button_expand_all').disabled = false;		// enable expand button
	} else {													// somewhere in the middle, 
		document.getElementById('button_expand_all').disabled = false;
		document.getElementById('button_collapse_all').disabled = false;
	}


	if (mode=='EDIT') {
		document.getElementById('button_save_preview_top').disabled = false;
		document.getElementById('button_save_preview_bottom').disabled = false;
		document.getElementById('button_save_all').disabled = false;
	}

}



// function re-load captcha image
function reload_captcha() {	
	var captcha_img = fetch_object('captcha_img');
	captcha_img.src = '/images/captcha?r='+Math.floor(Math.random()*100000000);
}


// **** CHOOSE/CREATE PASSWORD RELATED ****


var getSpecCharCount = function(inStr) {

	var charTotal = 0;
	var i =0;
	for (i=0;i<inStr.length;i++) {
		
		var charCode = inStr.charCodeAt(i);
		if (!((charCode>=65&&charCode<=90) || (charCode>=97&&charCode<=122) || (charCode>=48&&charCode<=57) || (charCode==32))) {
			charTotal++;
		}
	}
	return charTotal;
}

var getRegCharCount = function(inStr, lowerCode, upperCode) {
	
	var charTotal = 0;
	var i =0;
	
	for (i=0;i<inStr.length;i++) {
		var charCode = inStr.charCodeAt(i);
		if (charCode>=lowerCode&&charCode<=upperCode) {
			charTotal++;
		}
	}
	
	return charTotal;

}


var resetPW = function() {
	
	if (pw_reset==0) {
		document.r.r__r__password.value='';
		document.r.r__r__confirm_password.value='';
		pw_reset=1;
		setStrength(0);
	}
}

var setStrength = function(strength) {
	
	var psStrengthMsg = fetch_object('psStrengthMsg');
	if (strength > 32) {
		strength = 32;
	}

	if (strength == 0) {
		psStrengthMsg.innerHTML = 'Too short';
	} else if (strength < 8) {
		psStrengthMsg.innerHTML = 'Weak';
	} else if (strength <= 16) {
		psStrengthMsg.innerHTML = 'Fair';
	} else if (strength < 24) {
		psStrengthMsg.innerHTML = 'Good';
	} else if (strength < 28) {
		psStrengthMsg.innerHTML = 'Very Good';
	} else if (strength <= 32) {
		psStrengthMsg.innerHTML = 'Strong';
	}
	
	var width = (172/32)*strength;
	new Effect.Morph('psStrength', {style:'width:'+width+'px', duration:'0.2'});


}




var updateStrength = function(pw) {

	var pwLen = pw.length;
	var psStrengthMsg = fetch_object('psStrengthMsg');

	if (pwLen>=8) {
		var strength = getStrength(pw);
		if (strength > 32) {
			strength = 32;
		}
		document.r.r__r__pw_strength.value=strength;
		setStrength(strength);
		
	} else if (pwLen<8) {
		psStrengthMsg.innerHTML = 'Too short';
		new Effect.Morph('psStrength', {style:'width:0px', duration:'0.0'});
	}
	
	


}

var getStrength = function(passwd) {

	intScore = 0;
	if (passwd.match(/[a-z]/)) { // [verified] at least one lower case letter
		intScore = (intScore+1)
	} 
	if (passwd.match(/[A-Z]/)) { // [verified] at least one upper case letter
		intScore = (intScore+5)
	} 
	// LCASE
	var lowerCount = getRegCharCount(passwd, 97, 121);
	if (lowerCount == 1) {
		intScore = (intScore+2);
	} else if (lowerCount > 1) {
		intScore = (intScore+5);
	}

	// UCASE
	var upperCount = getRegCharCount(passwd, 65, 90);
	if (upperCount == 1) {
		intScore = (intScore+5);
	} else if (upperCount > 1) {
		intScore = (intScore+10);
	}

	// NUMBERS
	var numCount = getRegCharCount(passwd, 48, 57);
	if (numCount == 1) {
		intScore = (intScore+5);
	} else if (numCount > 1) {
		intScore = (intScore+10);
	}

	


	// SPECIAL CHAR
	var specCharCount = getSpecCharCount(passwd);
	

	if (specCharCount==1) {
		intScore = (intScore+8);
	} else if (specCharCount>=2) {
		intScore = (intScore+24);
	}

	
	// COMBOS
	
	if (passwd.match(/[a-z]/) && passwd.match(/[A-Z]/)) { // [verified] both upper and lower case
		intScore = (intScore+5)
	} 
	if (passwd.match(/\d/) && passwd.match(/\D/)) { // [verified] both letters and numbers
		
		intScore = (intScore+5)
	} 
	// [Verified] Upper Letters, Lower Letters, numbers and special characters


	if (passwd.match(/[a-z]/) && passwd.match(/[A-Z]/) && passwd.match(/\d/) && (specCharCount>0)) {
			
		intScore = (intScore+2);
	}


	if (passwd.length >= 10) {
		intScore = (intScore+10);
	}
		
			
	return intScore;
}



