/* Globals */

/* Asynchronous callback flags:*/
var isLoadedData = false;
var isLoadedShipping = false;
var isLoadedCategories = false;
var isLoadedHolidays = false;

/* json objects */
var jsonContent;
var categoryContent;
var cityLookup;
var orderContent;
var holidaysContent;

/* sorted json content */
var sortedContent = new Array();
var sortedCategories = new Array;

/* Shipping globals*/
var shipping;
var trigger;

/* Current date globals */
var today = new Date();
/* debug */
/*today.setDate(30);
today.setHours(18);*/
/* end debug */
var isWeekend = (today.getDay() == 5 && today.getHours() > 16) || (today.getDay() == 6 && today.getHours() < 18);
var isNoon = today.getHours() >10 && today.getHours() < 16;
var dayNames = new Array('ראשון','שני','שלישי','רביעי','חמישי','שישי','שבת');

/* Totals and price globals */
var totalOrder = 0;
var totalPrice = 0;
var priceBuffer = new Array();

/* End globals */

/* Sending the form */
function processForm(sForm) {
	var errBuffer = new StringBuffer();
	var oForm = document.forms[sForm];
	var formValidator = new FormValidator(sForm);
	/* Check if not a bot */
	if (formValidator.isBot('mib')) {
		oForm.mib.value = ''
		return false;
	}
	/* Set order date and time */
	var orderDate = new Date();
	var minutes = (orderDate.getMinutes().toString().length < 1)?"0" + orderDate.getMinutes():"" + orderDate.getMinutes();
	var hour = orderDate.getHours() + ":" + minutes;

	oForm.orderTime.value = hour;
	/* Check mail details */
	if(oForm['newsLetter'].checked) {
		if (!formValidator.validateMail('email')) {
			errBuffer.append('<p>יש למלא כתובת אימייל תקפה אם רוצים לקבל עדכונים במייל</p>')
		}
		if (formValidator.isTooShort('name')) {
			errBuffer.append('<p>יש למלא שם אם רוצים לקבל עדכונים במייל</p>')
		}
	}

	/* Check phone validity */
	if (!formValidator.validatePhone('phone')) {
		errBuffer.append('<p>בעייה במס הטלפון</p>');
	}

	/* Check St. validity */
	if(formValidator.isTooShort('street')) {
		errBuffer.append('<p>בעיה בשם הרחוב</p>');
	}

	/* Check St. number validity */
	if(formValidator.isEmpty('streetNum')) {
		errBuffer.append('<p>בעיה במספר הבית</p>');
	}

	/* Check if any of the items is different than 0 */
	var flag = 0;
	for (var i = 0;i < oForm.elements.length;i++) {
		if (oForm.elements[i].id.indexOf('qty') > -1) {
			if (oForm.elements[i].value != '0') {
				flag = 1;
			}
		}
	}
	if (flag == 0) {
		errBuffer.append('<p>לא נבחרה אף מנה</p>');
	}
	var nSubTotal = document.forms[0].subTotal.value.replace(/,/g,'')*1;

	/* Check if total is greater than minimum total for shipping  */
	if (nSubTotal < trigger) {
		errBuffer.append('<p>המינימום למשלוח עבור ' + currentLocation +' הוא ' + trigger + ' ₪</p>');
	}

	/* If err message buffer is anything but '', alert err message and return false. Else, process form. */
	if (errBuffer != '') {
		var errBox = new AlertBox('alert');
		errBox.show();
		errBox.box.innerHTML = errBuffer.toString();
		var confirmOk = document.createElement('span');
		confirmOk.className = 'button';
		confirmOk.innerHTML = 'אישור';
		confirmOk.onclick = function() {
			errBox.hide();
		}
		errBox.box.appendChild(confirmOk);
		return false;
	}
	else {
		/* Show a box containing the order details */
		/* Ths box should also contain an option to add the right coupon */
		var nDueIn = document.forms[0].dueIn.value*1;
		var nShipping = document.forms[0].shipping.value*1;
		var nTotal = document.forms[0].total.value.replace(/,/g,'')*1;
		var promoTriggers = new Array();
		var divs = document.getElementsByTagName('div');
		var promoId;
		var promoCounter = 0;
		for (var i = 0;i < divs.length;i++) {
			if (divs[i].id.indexOf('promo') > -1) {
				promoId = divs[i].id.replace(/promo/,'')*1;
				promoTriggers[promoCounter] = new Object();
				promoTriggers[promoCounter].trigger = document.getElementById('price_triggerPr' + promoId).value*1;
				promoTriggers[promoCounter].price = document.getElementById('pricePr' + promoId).value*1;
				promoTriggers[promoCounter].id = promoId;
				promoTriggers[promoCounter].title = document.getElementById('promoTitle' + promoId).innerHTML;
				promoCounter ++;
			}
		}
		promoTriggers = promoTriggers.sort(promoSort);
		var tmpString = new StringBuffer();
		tmpString.append('<p>סה&quot;כ הזמנתך הוא ');
		tmpString.append(nSubTotal);
		tmpString.append(' ₪</p>');
		/* Check if special price for 'happy hour' */
		var nSubTotalGross = nSubTotal;
		var happyHour = document.getElementById('happyHour').value;
		if (happyHour != '') {
			happyHourPCT = 1*happyHour;
			happyHourDiscount = (100 - happyHour)/100;
			tmpString.append('<p><strong>סה"כ לאחר הנחת Happy Hour של %');
			tmpString.append(happyHourPCT);
			tmpString.append(' :</strong></p>');
			nSubTotal *= happyHourDiscount;
			tmpString.append('<p><strong>');
			tmpString.append(formatOutputWithTrim(nSubTotal));
			tmpString.append(' ₪</strong></p>');
		}
		tmpString.append('<p>תוספת דמי משלוח בסך ');
		tmpString.append(nShipping);
		tmpString.append(' ₪</p>');
		tmpString.append('<p>סה&quot;כ כולל דמי משלוח: ');
		nTotal = formatOutputWithTrim(nSubTotal + nShipping);
		tmpString.append(nTotal);
		tmpString.append(' ₪</p>');
		tmpString.append('<p>זמן הגעה משוער: ');
		tmpString.append(nDueIn);
		tmpString.append(' דקות</p>');
		var promoFlag = false;
		for (var i = 0;i < promoTriggers.length;i++) {
			var thisId;
			if (nSubTotalGross  > promoTriggers[i].trigger) {
				document.forms[0].coupon.value = '';
				document.forms[0].couponName.value= '';
				thisId = promoTriggers[i].id;
				if(!promoFlag) {
					tmpString.append('<p>____________</p>')
					tmpString.append('<p><strong>הנך זכאי ל:</strong></p>');
					promoFlag = true;
				}
				tmpString.append('<p><strong>' + document.getElementById('promoTitle' + thisId).innerHTML);
				tmpString.append(' במחיר מבצע של ');
				tmpString.append(promoTriggers[i].price);
				tmpString.append(' ₪</strong></p>');
				if (document.getElementById('promoImg' + thisId)) {
					var promoImg = document.getElementById('promoImg' + thisId).src;
					promoImg = promoImg.replace(/^.*_/,'Files/');
					tmpString.append('<img src="');
					tmpString.append(promoImg);
					tmpString.append('" alt="" width="152px" height="235px" />');
				}
				tmpString.append('<p><strong><input type="checkbox" id="addCoupon' + thisId + '" /> הוסף להזמנה שלי </strong></p>');
				tmpString.append('<p>____________</p>');
			}
		}
		/* Reset the coupon details on the coupon hidden inputs within the form. */
		document.forms[0].coupon.value = '';
		document.forms[0].couponName.value = '';
		var alertBox = new AlertBox('alert');
		alertBox.show();
		alertBox.box.innerHTML = tmpString.toString();
		var goOn = document.createElement('span');
		goOn.className = 'button';
		goOn.innerHTML = 'שלח&nbsp;&nbsp;|';
		goOn.onclick = function() {
			alertBox.hide();
			var currentCheckBox;
			for(var i = 0;i < promoTriggers.length;i++) {
				currentCheckBox = document.getElementById('addCoupon' + promoTriggers[i].id)
				if (currentCheckBox && currentCheckBox.checked) {
					/* Add the coupon details to hidden inputs within the form so they are passed to the action page. */
					couponDetails = promoTriggers[i].title + '#' + promoTriggers[i].id
					document.forms[0].coupon.value += promoTriggers[i].price + '^';
					document.forms[0].couponName.value += couponDetails + '^';
				}
			}
			document.forms[0].subTotal.value = nSubTotal;
			document.forms[0].total.value = nTotal;
			oForm.action = sForm + 'FormAction.php';
			oForm.submit();
		}
		alertBox.box.appendChild(goOn);
		var goBack = document.createElement('span');
		goBack.className = 'button';
		goBack.innerHTML = '&nbsp;&nbsp;תקן';
		goBack.onclick = function() {
			alertBox.hide();
		}
		alertBox.box.appendChild(goBack);
	}
}


/* Toggle between the "credit card" or "cash" options*/
function togglePayment() {
	var c = document.getElementById('payment').value;
	if (c == 'cc'){
		show('cc');
		hide('ca');
	}
	else {
		show('ca');
		hide('cc');
		if (document.forms[0].change.checked) {
			document.forms[0].change.checked = false;
		}
	}
}

/* The sorting function for the promoTriggers array */
function promoSort (a,b) {
	var x = a.trigger;
    var y = b.trigger;
    return ((x > y) ? 1 : ((x < y) ? -1 : 0));
}

/* This function shows the main course choice table on changing the QTY in the 801 or 409 fixed menus */
function showFixedOptions(buId) {
	var myTable = document.getElementById('table' + buId);
	var oRows = myTable.rows.length;
	/* Deleting all table rows */
	if (oRows > 1) {
		for (var i = oRows - 1;i >= 1;i--) {
			myTable.deleteRow(i);
		}
	}
	/* Refilling the table rows */
	var qty = document.getElementById('qtyBu' + buId).value*1;
	if (document.getElementById('actual' + buId + 'Price')) { /* If there's an 'actual price' total box for the menu, like in bu801, then update it. */
		var fixedbuIdPrice = document.getElementById('cost' + buId).innerHTML * 1;
		var fixedbuIdtotal = fixedbuIdPrice * qty;
		document.getElementById('priceBu' + buId).innerHTML = fixedbuIdtotal;
	}
	if (qty != 0) {
		show('table' + buId);
		for (var i = 1;i <= qty;i++){
			var oRow = document.getElementById('table' + buId).insertRow(i);
			var oCell = oRow.insertCell(0);
			oCell.innerHTML = i;
			oCell = oRow.insertCell(1);
			oCell.innerHTML = '<select onchange="updatebuIdPrice(\'' + buId + '\');" name="first' + buId + '_' + i +'" id="first' + buId + '_' + i +'"></select>';
			setFixedMenuItemsDropDown('first' + buId + '_' + i);
			oCell = oRow.insertCell(2);
			if (buId == '801') {
				oCell.innerHTML = '<select onchange="updatebuIdPrice(\'' + buId + '\');" name="main' + buId + '_' + i + '" id="main' + buId + '_' + i + '"></select>';
				setFixedMenuItemsDropDown('main' + buId + '_' + i);
				oCell = oRow.insertCell(3);
			}
			oCell.innerHTML = '<select onchange="updatebuIdPrice(\'' + buId + '\');" name="dessert' + buId + '_' + i +'" id="dessert' + buId + '_' + i +'"><option value="none">--</option></select>';
			setFixedMenuItemsDropDown('dessert' + buId + '_' + i);
		}
	}
	else {
		hide('table' + buId);
	}
	updateTotal();
}


function setFixedMenuItemsDropDown(sId) {
	var category1;
	var category2;
	if (sId.indexOf('main') > -1) {
		category1 = 'מעדני עוף';
		category2 = 'מעדני בקר';
	}
	else if (sId.indexOf('first') > -1){
		category1 = 'מתאבנים';
		category2 = 'מרקים';
	}
	else {
		category1 = 'קינוחים';
		category2 = 'קינוחים';
	}
	for(var i = 0;i < sortedContent.length;i++) {
		if (sortedContent[i].fixed_menu == 'on' && sortedContent[i].is_hidden != 'on') {
			if (sortedContent[i].category == category1 || sortedContent[i].category == category2) {
				var fixedOption = document.createElement('option');
				fixedOption.value = sortedContent[i].title + '#' + sortedContent[i].courses_id;
				fixedOption.text = sortedContent[i].title;
				try {
					document.getElementById(sId).add(fixedOption,null);
				}
				/* IE only */
				catch(e) {
					document.getElementById(sId).add(fixedOption);
				}
			}
		}
	}
}

function updatebuIdPrice(buId) {
	if (buId == '409') {
		return false;
	}
	var fixedbuIdtotal = document.getElementById('cost' + buId).innerHTML*1;
	var qtybuId = document.getElementById('qtyBu' + buId).value*1;
	var myTable = document.getElementById('table' + buId);
	fixedbuIdtotal *= qtybuId;
	var oRows = myTable.rows.length;
		for (var i = 1;i < oRows;i++) {
			if (document.getElementById('dessert' + buId + '_' + i).value != 'none') {
				fixedbuIdtotal += 5;
			}
		}
	document.getElementById('priceBu' +  buId).innerHTML = fixedbuIdtotal;
	updateTotal();
	return true;
}

/* This function is called on changing the "when" and "time" select - i.e. when selecting a different order time than today */
function setPrices() {
	var theDay = document.forms[0].when.value;
	var theTime = document.forms[0].time.value;
	if (theDay == '5' && theTime == 'evening' || theDay == '6' && theTime == 'noon' ) {
		isWeekend = true;
	}
	else {
		/* if this is a regular week day, the day should be converted to a date object, to see if holiday. */
		var dDay = new Date();
		/* Substract the set day from today to find the day of month difference */
		var dayDelta = theDay*1 - dDay.getDay();
		if (dayDelta < 0) {
			dayDelta += 7;
		}
		var newDate = dDay.getDate() + dayDelta;
		dDay.setDate(newDate);
		dDay.setMinutes(0);
		if (theTime == 'evening') {
			dDay.setHours(19);
		}
		else {
			dDay.setHours(12);
		}
		if (checkIfHoliday(dDay)) {
			isWeekend = true;
		}
		else {
			isWeekend = false;
		}
	}
	if (theTime == 'noon' && !isWeekend) {
		isNoon = true;
	}
	else {
		isNoon = false;
	}
	adjustView();
}


/* The sorting functions passed to the array.sort() function */
function quisineSort(a,b) {
	var x = a.quisine.toLowerCase();
    var y = b.quisine.toLowerCase();
    return ((x > y) ? -1 : ((x < y) ? 1 : 0));
}

function categorySort (a,b) {
	var x = a.weight*1;
    var y = b.weight*1;
    return ((x > y) ? 1 : ((x < y) ? -1 : 0));
}

/* Sorting inside a sorted array */
function arrangeCategories (dataArray) {
	var index = '';
	var theArray = new Array();
	for (var i = 0;i < dataArray.length;i++) {
		if (dataArray[i].quisine != index) {
			index = dataArray[i].quisine;
			var tmpArr = new Array();
			var counter = 0;
			for (var j = 0;j < dataArray.length; j++) {
				if (dataArray[j].quisine == index) {
					tmpArr[counter] = dataArray[j];
					counter++;
				}
			}
			tmpArr = tmpArr.sort(categorySort)
			counter = 0;
			theArray = theArray.concat(tmpArr);
		}
	}
	return theArray;
}

/* Turning an object to array so it is sortable */
function makeArray(rawData) {
	var dataArray = new Array();
	for (var i in rawData) {
		dataArray[i] = rawData[i];
	}
	return dataArray;
}

/* Draw the side menu (the call for this function is cancelled) */
function drawSideMenu () {
	var tmpBuffer = new StringBuffer();
	var index = '';
	for (var i = 0;i < sortedCategories.length;i++) {
		if (sortedCategories[i].quisine != index) {
			index = sortedCategories[i].quisine;
			tmpBuffer.append('<li><strong><a href="#' + sortedCategories[i].quisine + '">' + sortedCategories[i].quisine + '</strong></a>');
			tmpBuffer.append('<ul id="cMenu">');
			var catIndex = '';
			for (var j = 0;j < sortedCategories.length;j++) {
				if(sortedCategories[j].quisine == index) {
					tmpBuffer.append('<li><a href="#' + sortedCategories[j].title + '">' + sortedCategories[j].title + '</a></li>');
				}
			}
			tmpBuffer.append('</ul>');
			tmpBuffer.append('</li>');
		}

	}
	document.getElementById('sideMenu').innerHTML = tmpBuffer.toString();
}

function showCategoryTable(sId) {
	if (document.getElementById('table' + sId)) {
		if (document.getElementById('tableHolder' + sId).style.display != 'block') {
			document.getElementById('xpcl' + sId).src = "Images/collapse.gif";
			show ('tableHolder' + sId);
		}
		else {
			document.getElementById('xpcl' + sId).src = "Images/expand.gif";
			hide ('tableHolder' + sId)
		}
	}
	else {
		document.getElementById('xpcl' + sId).src = "Images/collapse.gif";
		var container = document.getElementById('tableHolder' + sId);
		var tmpBuffer = new StringBuffer();
		tmpBuffer.append('<table id="table' + sId +'" class="sectionHolder" cellpadding="0" cellspacing="0" border="0">')
		tmpBuffer.append('<tr>');
		tmpBuffer.append('<th class="title">מנה</th>');
		tmpBuffer.append('<th class="fPrice">מחיר משפחתי</th>')
		tmpBuffer.append('<th class="qty">כמות</th>');
		tmpBuffer.append('<th class="price">מחיר אישי</th>');
		tmpBuffer.append('<th class="qty">כמות</th>');
		tmpBuffer.append('<th class="price">מחיר רגיל</th>');
		tmpBuffer.append('<th class="qty">כמות</th>');
		tmpBuffer.append('<th width="85px">הערות</th>');
		tmpBuffer.append('</tr>');
		var catIndex = -1;
		for (var i = 0;i < sortedCategories.length;i++) {
			if (sortedCategories[i].categories_id == sId) {
				catIndex = i;
			}
		}
		for (var j = 0;j < sortedContent.length;j++) {
			if (sortedContent[j].category == sortedCategories[catIndex].title && sortedContent[j].is_hidden != 'on') {
				var tmpClone = document.getElementById('tableTemplate').innerHTML;
			if (sortedContent[j].imgUrl) {
				tmpClone = tmpClone.replace(/<h4>__TITLE__/gi, '<h4>__TITLE__<img src="Files/' + sortedContent[j].imgUrl + '" alt="" class="courseImg" width="150px" />');
			}
			/* Forcing IE to wrap the input value with quotes, otherwise, only the content's first word is entered. :-\' */
				tmpClone = tmpClone.replace(/value=__TITLE__/gi,'value="__TITLE__"');
				tmpClone = tmpClone.replace(/__ID__/gi, sortedContent[j].courses_id);
				tmpClone = tmpClone.replace(/__TITLE__/gi, sortedContent[j].title);
				if (sortedContent[j].content != '') {
					tmpClone = tmpClone.replace(/__CONTENT__/gi, sortedContent[j].content);
				}
				else {
					/* If no comments for this course, we should hide its containing p element. We use a regExp to replace the "details" p with an empty string. */
					/* IE renders the innerHTML in his own creative way: so, the string "<p class="details"><span>__CONTENT__</span></p>" becomes "<P CLASS=details><SPAN>__CONTENT__</SPAN></P>". Notice - all tag names uppercased, an no quotes around attributes. This should be considered in the RegXp. */
					tmpClone = tmpClone.replace(/<p class="?details"?><span>__CONTENT__<\/span><\/p>/gi,'');
				}
				tmpBuffer.append(tmpClone.toString());
			}
		}
		tmpBuffer.append('</table>');
		container.innerHTML = tmpBuffer.toString();
		addPrices();
		show('tableHolder' + sId);
	}
}

/* Draw the main menu */
function drawMainMenu() {
	var i = 0;
	var tmpBuffer = new StringBuffer();
	var index = '';
	for (var i = 0;i < sortedCategories.length;i++) {
		if (sortedCategories[i].quisine != index) {
			index = sortedCategories[i].quisine;
			tmpBuffer.append('<h2 id="' + sortedCategories[i].quisine + '">' + sortedCategories[i].quisine + '</h2>');
		}
		var notEmptyCat = 0;
		for (var j = 0;j < sortedContent.length;j++) {
			if (sortedContent[j].category == sortedCategories[i].title && sortedContent[j].quisine == index && sortedContent[j].is_hidden != 'on') {
				notEmptyCat++;
			}
		}
		if (notEmptyCat !=0) {
			tmpBuffer.append('<h3 onclick="showCategoryTable(' + sortedCategories[i].categories_id + ')" id="header' + sortedCategories[i].categories_id +'" class="button" title="הצג/הסתר ' + sortedCategories[i].title + '"><img src="Images/expand.gif" id="xpcl' + sortedCategories[i].categories_id + '" width="11px" height="11px" alt="" /> ' + sortedCategories[i].title + '<span> ' + sortedCategories[i].content + '</span></h3>');
			tmpBuffer.append('<div id="tableHolder' + sortedCategories[i].categories_id + '" class="tableHolder">&nbsp;</div>');
			for (var j = 0;j < sortedContent.length;j++) {
				if (sortedContent[j].category == sortedCategories[i].title && sortedContent[j].quisine == index && sortedContent[j].is_hidden != 'on') {
					priceBuffer[j] = new Object();
					priceBuffer[j].theId = sortedContent[j].courses_id;
					priceBuffer[j].price = sortedContent[j].price;
					priceBuffer[j].price2 = sortedContent[j].price2;
					priceBuffer[j].price3 = sortedContent[j].price3;
					priceBuffer[j].price_wkend = sortedContent[j].wkend_price;
				}
			}
		}
		document.getElementById('menuHolder').innerHTML = tmpBuffer.toString();
		}
}

function setWeekDays() {
	var days = new Array();
	days[0] = 'היום';
	days[1] = 'מחר';
	days[2] = 'מחרתיים';
	for (var i = 0;i < 7;i++) {
		theOption = document.createElement('option');
		theOption.value = (today.getDay() + i)%7;
		if (i < 3) {
			theOption.text = days[i];
		}
		else {
			theOption.text = dayNames[(today.getDay() + i)%7];
		}
		/*standards compliant*/
		try {
			document.getElementById('when').add(theOption,null);
		}
		/* IE only */
		catch(e) {
			document.getElementById('when').add(theOption);
		}
	}
}


function resetTotals() {
	/* This function resets all item qantities back to 0 */
	if (document.getElementById('alert').style.display == 'block') {
	/* This for IE6, where the select inputs keep appearing over the screen block element, and can still be modified. */
		return false;
	}
	var selects = document.getElementsByTagName('select');
	for (var i = 0;i < selects.length;i++) {
		if (selects[i].id.indexOf('qty') > -1 && selects[i].id.indexOf('__') < 0) {
			selects[i].options.selectedIndex = 0;
		}
	}
	showFixedOptions('801');
	showFixedOptions('409');
	updateTotal();
	return true;
}



/* This function goes through all span that contain price and sum everything up to the total price */
function updateTotal() {
	if (document.getElementById('alert').style.display == 'block') {
	/* This is for IE6, where the select inputs keep appearing over the screen block element, and can still be modified. */
		return false;
	}
	totalPrice = 0;
	var spanElements = document.getElementsByTagName('span');
	for (var i = 0;i < spanElements.length;i++) {
		/* filter only the relevant spans, which contain the price */
		if (spanElements[i].id.indexOf('price') > -1 && spanElements[i].id.indexOf('__') < 0) {
			var currentId = spanElements[i].id.replace(/price/,'');
			var itemQty = 1*(document.getElementById('qty' + currentId).value);
			var itemPrice = 1*(spanElements[i].innerHTML);
			/* The price contained in 'Bu801' is already summed up, so no need to multiply with the qty. */
			if (currentId == 'Bu801') {
				totalPrice += itemPrice;
			}
			else {
				totalPrice += itemQty*itemPrice;
			}
		}
	}

	var happyHour = document.getElementById('happyHour').value;
	if (happyHour != '') {
		happyHourPCT = 1*happyHour;
		happyHourDiscount = (100 - happyHour)/100;
		hHourIncluded = totalPrice * happyHourDiscount;
		document.getElementById('happy').innerHTML = formatOutputWithTrim(hHourIncluded) + '₪';
		document.getElementById('happyInput').value = hHourIncluded; 
		/*
		tmpString.append('<p><strong>סה"כ לאחר הנחת Happy Hour של %');
		tmpString.append(happyHourPCT);
		tmpString.append(' :</strong></p>');
		
		tmpString.append('<p><strong>');
		tmpString.append(formatOutputWithTrim(nSubTotal));
		tmpString.append(' ₪</strong></p>');
		
		*/
	}
	totalOrder = totalPrice + shipping;
	document.forms[0].subTotal.value = formatOutputWithTrim(totalPrice);
	document.forms[0].total.value = formatOutputWithTrim(totalOrder);
	return true;
}

function addShipping() {
	/* This function adjusts the shipping rates in relation to weekdays */
	cityId = document.forms[0].city.value*1;
	var cityIndex = -1;
	for (var i in cityLookup) {
		if(cityId == cityLookup[i].shipping_id) {
			cityIndex = i;
			break;
		}
	}
	shipping = cityLookup[cityIndex].rate*1;
	var deliveryTime;
	if (isWeekend) {
		deliveryTime = cityLookup[cityIndex].wkend_d_time;
	}
	else {
		deliveryTime = cityLookup[cityIndex].delivery_time;
	}
	totalOrder = totalPrice + shipping;
	currentLocation = cityLookup[cityIndex].title;
	document.forms[0].cityName.value = cityLookup[cityIndex].title;
	document.forms[0].dueIn.value = deliveryTime;
	document.forms[0].shipping.value = shipping;
	document.forms[0].total.value = totalOrder;
	trigger = cityLookup[cityIndex].shipping_trigger*1;
	document.forms[0].shipping_trigger.value = trigger;
}

function addPrices() {
	/* This function adds the right prices to the menu items. It is done separately because prices may be altered ocaasionally without refreshing the page. For instance - ordering for the weekend */
	var spanElements = document.getElementsByTagName('span');
	for (var i = 0;i < spanElements.length;i++) {
		/* filter only the relevant spans, which contain the price and are not a fixed menu id */
		if (spanElements[i].id.indexOf('price') > -1 && spanElements[i].id.indexOf('__') < 0 && spanElements[i].id.indexOf('Bu') < 0) {
			var currentId = spanElements[i].id.replace('price','');
			var currentIndex = '';
			/*go thru the content array and find the right record for this span */
			for (var j = 0;j < sortedContent.length;j++) {
				/* This boolean tests if japanese menu. Then - the menu prices are not changed during weekend. */
				var isJapaneseMenu = sortedContent[j].quisine == 'יפני';
				/* First, find the right record, to be related to the right match on sortedContent array, and all its variants (family or personal price, identified by the '& and @ tags')*/
				if (sortedContent[j].courses_id == currentId.replace(/\&?@?/gi,'')) {
					currentIndex = j;
					break;
				}
			}
			try {
				/* If it is the course regular price (i.e. not personal or family price )*/
				var todaysPrice;
				if (spanElements[i].id.indexOf('@') <  0 ) {
					todaysPrice = formatOutput(sortedContent[currentIndex].price);
					if (isWeekend && !isJapaneseMenu) {
						todaysPrice = formatOutput(sortedContent[currentIndex].wkend_price);
					}
					else {
						todaysPrice = formatOutput(sortedContent[currentIndex].price);
					}
					spanElements[i].innerHTML = todaysPrice;
					document.getElementById('actualPrice' + currentId).value = todaysPrice;
				}
				/* Else if it is the course's personal or family price '*/
				else {
					/* Hide during weekend */
					if (isWeekend && !isJapaneseMenu) {
						spanElements[i].innerHTML = 0;
						document.getElementById('actualPrice' + currentId).value = 0;
						hide('qty' + currentId);
						hide('price' + currentId);
					}
					else {
						if (spanElements[i].id.indexOf('&') >  0 ) {
							if (sortedContent[currentIndex].price3 != '0') {
								spanElements[i].innerHTML = formatOutput(sortedContent[currentIndex].price3);
								document.getElementById('actualPrice' + currentId).value = formatOutput(sortedContent[currentIndex].price3);
								show('qty' + currentId);
								show('price' + currentId);
							}
							else {
								spanElements[i].innerHTML = 0;
								document.getElementById('actualPrice' + currentId).value = 0;
								spanElements[i].style.display = 'none';
								hide('qty' + currentId);
								hide('price' + currentId);
							}
						}
						else {
							if (sortedContent[currentIndex].price2 != '0') {
								spanElements[i].innerHTML = formatOutput(sortedContent[currentIndex].price2);
								document.getElementById('actualPrice' + currentId).value = formatOutput(sortedContent[currentIndex].price2);
								show('qty' + currentId);
								show('price' + currentId);
							}
							else {
								spanElements[i].innerHTML = 0;
								document.getElementById('actualPrice' + currentId).value = 0;
								spanElements[i].style.display = 'none';
								hide('qty' + currentId);
								hide('price' + currentId);
							}
						}
					}
				}
			}
			catch(e) {
				spanElements[i].innerHTML = 0;
			}
		}
	}
}

/* view setup sequence */
function adjustView() {
	addShipping();
	addPrices();
	updateTotal();
	if (isWeekend) {
		show('weekendPrices');
	}
	else {
		hide('weekendPrices');
	}
	if (isNoon && !isWeekend) {
		show('fixedMenu');
	}
	else {
		hide('fixedMenu');
	}
}

function setCityDropDown() {
	for (var i in cityLookup) {
		if (i != '') {
			var theOption = document.createElement('option');
			theOption.value = cityLookup[i].shipping_id;
			theOption.text = cityLookup[i].title;
			if (cityLookup[i].title==currentLocation) {
				theOption.selected = true;
			}
			/*standards compliant*/
			try {
				document.getElementById('city').add(theOption,null);
			}
			/* IE only */
			catch(e) {
				document.getElementById('city').add(theOption);
			}
		}
	}
}

function doTheShippingThing() {
	setCityDropDown()
	adjustView();
}

function doTheJsonThing() {
	sortedContent = makeArray (jsonContent);
	sortedCategories = makeArray (categoryContent);
	sortedCategories = arrangeCategories(sortedCategories);
	 //drawSideMenu();
	drawMainMenu();
}


/* This function goes through the holidaysContent object and checks if today is a holiday. If yes - the prices should be changed accordingly. */
function checkIfHoliday(oDate) {
	var fromDate = new Date();
	var toDate = new Date();
	var tmpDateArray = new Array();
	var tmpTimeArray = new Array();
	for (var i in holidaysContent) {
		var isHoliday = false;
		if (i != '') {
			/*setting the lower date bracket:*/
			tmpDateArray = holidaysContent[i].from_date.split('-');
			tmpTimeArray = holidaysContent[i].from_hour.split(':');
			fromDate.setFullYear(tmpDateArray[0]*1);
			fromDate.setMonth(tmpDateArray[1]*1 - 1);
			fromDate.setDate(tmpDateArray[2]*1);
			fromDate.setHours(tmpTimeArray[0]*1);
			fromDate.setMinutes(tmpTimeArray[1]*1);
			/*setting the upper date bracket:*/
			tmpDateArray = holidaysContent[i].to_date.split('-');
			tmpTimeArray = holidaysContent[i].to_hour.split(':');
			toDate.setFullYear(tmpDateArray[0]*1);
			toDate.setMonth(tmpDateArray[1]*1 - 1);
			toDate.setDate(tmpDateArray[2]*1);
			toDate.setHours(tmpTimeArray[0]*1);
			toDate.setMinutes(tmpTimeArray[1]*1);
			if (fromDate < oDate && oDate < toDate) {
				isHoliday = true;
				break;
			}
		}
	}
	return isHoliday;
}

function getData(theUrl,theSync) {
	var oXml = new XmlHttpReq();
	oXml.open('GET',theUrl,theSync);
	oXml.onreadystatechange = function() {
		if(oXml.readyState != 4) {
			return;
		}
		else {
			try {
				jsonContent = eval('(' + oXml.responseText + ')');
				//xmlContent = oXml.responseXml;
				isLoadedData = true;
			}
			catch (e) {
				alert("Courses err: " + e);
			}
				return jsonContent;
		}
	};
	oXml.send(null);
}

function resetAllTables () {
	var tableHolders = document.getElementsByTagName('div') ;
	for (var i = 0;i < tableHolders.length;i++) {
		if (tableHolders[i].id.indexOf('tableHolder') > -1) {
			hide(tableHolders[i].id);
		}
	}
}

function getOrder(nId) {
	/* This functions get all the data of a former order. */
	resetTotals();
	resetAllTables();
	if (nId == 0) {
		return false;
	}
	var oXml = new XmlHttpReq();
	var theUrl = 'jsonOrderSrc.php?orderid=' + nId;
	oXml.open('GET',theUrl,'true');
	oXml.onreadystatechange = function() {
		if(oXml.readyState != 4) {
			show('orderLoader','inline');
			return;
		}
		else {
			try {
				orderContent = eval('(' + oXml.responseText + ')');
				var courseId;
				var courseQty;
				var courseCategory;
				if (orderContent != '') {
					var arrayLength = 0;
					while (orderContent[arrayLength] != undefined) {
						arrayLength++;
					}
					for (var i = 0;i < arrayLength;i++) {
						courseId = orderContent[i].courses_id;
						courseQty = orderContent[i].qty;
						courseCategory = orderContent[i].categories_id;
						showCategoryTable(courseCategory);
						if (orderContent[i].type.indexOf('משפחתי') > -1) {
							courseId += '&@';
						}
						else if (orderContent[i].type.indexOf('אישי') > -1) {
							courseId += '@';
						}
						var qtyElements = document.forms[0].elements;
						for (var j = 0;j < qtyElements.length;j++) {
							if (qtyElements[j].id == 'qty' + courseId) {
								qtyElements[j].value = courseQty;
							}
						}
						hide('orderLoader');
						updateTotal();
					}
				}
			}
			catch(e) {
				hide('orderLoader');
				return false;
			}
		}
	}
	oXml.send(null);
}

function getCategories(theUrl,theSync) {
	var oXml = new XmlHttpReq();
	oXml.open('GET',theUrl,theSync);
	oXml.onreadystatechange = function() {
		if(oXml.readyState != 4) {
			return;
		}
		else {
			try {
				categoryContent = eval('(' + oXml.responseText + ')');
				//xmlContent = oXml.responseXml;
				isLoadedCategories = true;
			}
			catch(e) {
				alert("categories err: " + e);
			}
		}
	};
	oXml.send(null);
}

function getShipping(theUrl,theSync) {
	var oXml = new XmlHttpReq();
	oXml.open('GET',theUrl,theSync);
	oXml.onreadystatechange = function() {
		if(oXml.readyState != 4) {
			return;
		}
		else {
			try {
				cityLookup = eval('(' + oXml.responseText + ')');
				//xmlContent = oXml.responseXml;
				isLoadedShipping = true;
			}
			catch(e) {
				alert("city err: " + e);
			}
		}
	};
	oXml.send(null);
}

function getHolidays(theUrl, theSync) {
	var oXml = new XmlHttpReq();
	oXml.open('GET',theUrl,theSync);
	oXml.onreadystatechange = function() {
		if(oXml.readyState != 4) {
			return;
		}
		else {
			try {
				holidaysContent = eval('(' + oXml.responseText + ')');
				isLoadedHolidays = true;
			}
			catch(e) {
				alert("hoidays err: " + e);
			}
		}
	};
	oXml.send(null);
}

function init () {
	initializemarquee();
	if (document.getElementById('order')) {
		/* get json data: */
		getData('jsonItemSrc.php',true);
		getShipping('jsonShippingSrc.php',true);
		getCategories('jsonCategorySrc.php',true);
		getHolidays('jsonHolidaysSrc.php',true);
		/* Check if data is loaded every int */
		var checkLoadedAllJson = setInterval(function () {
			if (isLoadedData && isLoadedShipping && isLoadedCategories && isLoadedHolidays) {
				clearInterval(checkLoadedAllJson);
				doTheJsonThing();
				isHoliday = checkIfHoliday(today);
				if (isHoliday) {
					isWeekend = true;
				}
				doTheShippingThing();
				hide('preloader');
			}
		},50);
		resetTotals()
		setWeekDays()
		togglePayment();
		detectIe6();
	}
}

window.onload = init;

