// DRAG AND DROP LUNCHBOX

function getPosition(e){
	var left = 0;
	var top = 0;
	while (e.offsetParent){
		left += e.offsetLeft + (e.currentStyle?(parseInt(e.currentStyle.borderLeftWidth)).NaN0():0);
		top += e.offsetTop + (e.currentStyle?(parseInt(e.currentStyle.borderTopWidth)).NaN0():0);
		e = e.offsetParent;
	}
	left += e.offsetLeft + (e.currentStyle?(parseInt(e.currentStyle.borderLeftWidth)).NaN0():0);
	top += e.offsetTop + (e.currentStyle?(parseInt(e.currentStyle.borderTopWidth)).NaN0():0);

	return {x:left, y:top};
}

var dD = {
	mouseOffset : null,
	iMouseDown : false,
	lMouseState : false,
	dragObject : null,

	DragDrops : Array,
	curTarget : null,
	lastTarget : null,
	dragHelper : null,
	rootParent : null,
	rootSibling : null,

	buildDragContainer : function(){
		// Create a new "Container Instance" so that items from one "Set" can not be dragged into items from another "Set"
		var cDrag = dD.DragDrops.length;
		dD.DragDrops[cDrag] = [];

		// Each item passed to this function should be a "container". Store each of these items in our current container
		for(var i=0; i<arguments.length; i++){
			var cObj = arguments[i];
			dD.DragDrops[cDrag].push(cObj);
			cObj.setAttribute('DropObj', cDrag);

			// Every top level item in these containers should be draggable. Do this by setting the DragObj attribute on each item and then later checking this attribute in the mouseMove function
			for(var j=0; j<cObj.childNodes.length; j++){
				if(cObj.childNodes[j].nodeName=='#text') continue;// Firefox puts in lots of #text nodes...skip these
				cObj.childNodes[j].setAttribute('DragObj', cDrag);
			}
		}
	},
	mouseDown : function (ev){
		ev = ev || window.event;
		var target = ev.target || ev.srcElement;
		dD.iMouseDown = true;
		if(target.onmousedown || target.getAttribute('DragObj')){
			return false;
		}
	},
	mouseUp : function (ev){
		if(dD.curTarget){
			dD.dragHelper.style.display = 'none';
			if(dD.curTarget.style.display == 'none'){
				if(dD.rootSibling){
					dD.rootParent.insertBefore(dD.curTarget, dD.rootSibling);
				}else{
					dD.rootParent.appendChild(dD.curTarget);
				}
			}
			dD.curTarget.style.display = '';
			dD.curTarget.style.visibility = 'visible';
			gda.calculateGDA();
			portion.extraPortion='n';
		}
		dD.curTarget = null;
		dD.dragObject = null;
		dD.iMouseDown = false;
	},
	getMouseCoords : function(ev){
		if(ev.pageX || ev.pageY){
			return {x:ev.pageX, y:ev.pageY};
		}
		return {x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,y:ev.clientY + document.body.scrollTop - document.body.clientTop};
	},
	getMouseOffset : function (target, ev){
		ev = ev || window.event;
		var docPos = getPosition(target);
		var mousePos = dD.getMouseCoords(ev);
		return {x:mousePos.x - docPos.x, y:mousePos.y - docPos.y};
	},
	mouseMove : function (ev){
		ev = ev || window.event;
		// We are setting target to whatever item the mouse is currently on.  Firefox uses event.target here, MSIE uses event.srcElement
		var target = ev.target || ev.srcElement;
		var mousePos = dD.getMouseCoords(ev);

		// MOUSE OUT FIRED - fires if the item the mouse is on has changed
		if(dD.lastTarget && (target!==dD.lastTarget)){
			// reset the classname for the target element
			var origClass = dD.lastTarget.className;
			if(origClass) {
				if ((dD.lastTarget.nodeName != 'A') && (dD.lastTarget.nodeName != 'FORM') && (dD.lastTarget.nodeName != 'LABEL') && (dD.lastTarget.nodeName != 'EM')){
					dD.lastTarget.className = 'DragBox';
				}
			}
			var oId = dD.lastTarget.id;
			if (oId.indexOf('Item') != -1){
				if (dD.lastTarget.parentNode){
					if (dD.lastTarget.parentNode.id){
						if(dD.lastTarget.parentNode.id == 'Lunchbox'){
							lunchbox.removeCloseOption(dD.lastTarget);
						}
					}
				}
			}
		}
		// dragObj is the grouping our item is in (set from the createDragContainer function).	if the item is not in a grouping we ignore it since it can't be dragged with this script.
		var dragObj = target.getAttribute('DragObj');

		// if the mouse was moved over an element that is draggable
		if(dragObj!=null){
			// MOUSEOVER event - Change the item's class if necessary
			if(target!=dD.lastTarget){
				//Adds the description to the screen when an item in the foodsource is hovered over
				var oClass = target.className;
				if(oClass){
					target.className = 'OverDragBox';
					lunchbox.writeProductDescription(target);
				}

				//Adds the close button to the onHover state of the items in the lunchbox
				//fix - performance... quicker to do a try/catch than a load of ifs? same above.
				var oId = target.id;
				if (oId.indexOf('Item') != -1){
					if(target.parentNode){
						if(target.parentNode.id){
							if(target.parentNode.id == 'Lunchbox'){
								lunchbox.addCloseOption(target);
							}
						}
					}
				}
			}

			// DRAGGING OF CONTAINER HAS BEGUN
			if(dD.iMouseDown && !dD.lMouseState){
				dD.curTarget = target;  // mouseDown target

				dD.rootParent = dD.curTarget.parentNode;
				dD.rootSibling = dD.curTarget.nextSibling;

				dD.mouseOffset = dD.getMouseOffset(target, ev);

				// We remove anything that is in our dD.dragHelper DIV so we can put a new item in it.
				for(var i=0; i<dD.dragHelper.childNodes.length; i++){
					dD.dragHelper.removeChild(dD.dragHelper.childNodes[i]);
				}

				// Make a copy of the current item and put it in our drag helper.
				dD.dragHelper.appendChild(dD.curTarget.cloneNode(true));
				dD.dragHelper.style.display = 'block';

				// set the class on our helper DIV if necessary
				var dragClass = dD.curTarget.className;
				if(dragClass){
					dD.dragHelper.firstChild.className = 'DragDragBox';
				}

				// disable dragging from our helper DIV (it's already being dragged)
				dD.dragHelper.firstChild.removeAttribute('DragObj');

				/*
				Record the current position of all drag/drop targets related to the element. We do this here so that we do not have to do
				it on the general mouse move event which fires when the mouse moves even 1 pixel. If we don't do this here the script
				would run much slower.
				*/
				var dragConts = dD.DragDrops[dragObj];

				// first record the width/height of our drag item. Then hide it since it is going to (potentially) be moved out of its parent.
				dD.curTarget.setAttribute('startWidth', parseInt(dD.curTarget.offsetWidth));
				dD.curTarget.setAttribute('startHeight', parseInt(dD.curTarget.offsetHeight));

				// loop through each possible drop container
				for(var i=0; i<dragConts.length; i++){
					with(dragConts[i]){
						var pos = getPosition(dragConts[i]);
						//	save the width, height and position of each container. Performance booster this.
						setAttribute('startWidth', parseInt(offsetWidth));
						setAttribute('startHeight', parseInt(offsetHeight));
						setAttribute('startLeft', pos.x);
						setAttribute('startTop', pos.y);
					}

					// loop through each child element of each container
					for(var j=0; j<dragConts[i].childNodes.length; j++){
						with(dragConts[i].childNodes[j]){
							if((nodeName=='#text') || (dragConts[i].childNodes[j]==dD.curTarget)) continue;

							var pos = getPosition(dragConts[i].childNodes[j]);

							// save the width, height and position of each element
							setAttribute('startWidth', parseInt(offsetWidth));
							setAttribute('startHeight', parseInt(offsetHeight));
							setAttribute('startLeft', pos.x);
							setAttribute('startTop', pos.y);
						}
					}
				}
			}
		}

		// WE ARE DRAGGING
		if(dD.curTarget){
			// move our helper div to wherever the mouse is (adjusted by mouseOffset)
			dD.dragHelper.style.top = mousePos.y - dD.mouseOffset.y;
			dD.dragHelper.style.left = mousePos.x - dD.mouseOffset.x;

			var dragConts = dD.DragDrops[dD.curTarget.getAttribute('DragObj')];
			var activeCont = null;

			var xPos = mousePos.x - dD.mouseOffset.x + (parseInt(dD.curTarget.getAttribute('startWidth')) / 2);
			var yPos = mousePos.y - dD.mouseOffset.y + (parseInt(dD.curTarget.getAttribute('startHeight')) / 2);

			// check each drop container to see if our target object is "inside" the container
			for(var i=0; i<dragConts.length; i++){
				with(dragConts[i]){
					if((parseInt(getAttribute('startLeft')) < xPos) && (parseInt(getAttribute('startTop')) < yPos) && ((parseInt(getAttribute('startLeft')) + parseInt(getAttribute('startWidth'))) > xPos) && ((parseInt(getAttribute('startTop')) + parseInt(getAttribute('startHeight'))) > yPos)){
						// our target is inside of our container so save the container into the activeCont variable and then exit the loop since we no longer need to check the rest of the containers
						activeCont = dragConts[i];
						break;
					}
				}
			}

			// Our target object is in one of our containers. Check to see where our div belongs
			if(activeCont){
				// beforeNode will hold the first node AFTER where our div belongs
				var beforeNode = null;

				// loop through each child node (skipping text nodes).
				for(var i=activeCont.childNodes.length-1; i>=0; i--){
					with(activeCont.childNodes[i]){
						if(nodeName=='#text') continue;

						// if the current item is "After" the item being dragged
						if(dD.curTarget != activeCont.childNodes[i] && ((parseInt(getAttribute('startLeft')) + parseInt(getAttribute('startWidth'))) > xPos) &&((parseInt(getAttribute('startTop')) + parseInt(getAttribute('startHeight'))) > yPos)){
								beforeNode = activeCont.childNodes[i];
						}
					}
				}

				//FIX THIS BIT - IT can be trimmed down a lot.
				// the item being dragged belongs before another item
				if(beforeNode){
					if(beforeNode!=dD.curTarget.nextSibling){
						//Inserted Before
						if (activeCont.id == 'Lunchbox'){//only add the item if it is being dropped in the lunchbox
							//extra portion test
							var oLunchboxItems = lunchbox.oLunchbox.getElementsByTagName('div');
							var sRemoveThisItem = dD.curTarget.id;
							if (sRemoveThisItem && oLunchboxItems && (portion.extraPortion != 'y')){
								for (var i=0; i<oLunchboxItems.length; i++){
									if (oLunchboxItems[i].id == sRemoveThisItem){
										//increase portion size. do not add another instance
										//fix - needs to be put in on mouse up

										var oPortion = oLunchboxItems[i].getElementsByTagName('em')[0];
										if (oPortion){
											var iCurrentPortion = parseFloat(oPortion.className) + 1;
											oPortion.className = iCurrentPortion;
											var sPortion = oPortion.innerHTML;
											if (sPortion.indexOf('(x') != -1){
												var sPortionContent = sPortion.substring(0,sPortion.indexOf('('));
												oPortion.innerHTML = sPortionContent + ' (x' + iCurrentPortion.toFixed(0) + ')';
											}else{
												oPortion.innerHTML = oPortion.innerHTML + ' (x' + iCurrentPortion.toFixed(0) + ')';
											}
											trkUser.writeLog('A:'+sRemoveThisItem);
											oPortion.className = iCurrentPortion.toFixed(0);
											portion.extraPortion='y';
										}
										var extraPortion='done';
									}
								}
							}

							//new addition to lunchbox. therefore add to lunchbox and keep in foodsource
							if (!extraPortion && (portion.extraPortion != 'y')){
								var oCopyOfItem = dD.curTarget.cloneNode(true);
								oCopyOfItem.style.visibility = 'visible';
								oCopyOfItem.style.display = 'block';

								//Leave the original element in place and copy the cloned node only into the lunchbox
								activeCont.insertBefore(oCopyOfItem, beforeNode);
								
								var oNewCopy = oCopyOfItem.getElementsByTagName('h3')[0];
								if (oNewCopy){
								//	trkUser.writeLog('<p>New Item Before End: ' + oNewCopy.innerHTML + '</p>');
								}	
							}
						}
					}
				// the item being dragged belongs at the end of the current container
				} else {
					if((dD.curTarget.nextSibling) || (dD.curTarget.parentNode!=activeCont)){
						//Inserted at end of
						if (activeCont.id == 'Lunchbox'){//only add the item if it is being dropped in the lunchbox
							//extra portion test
							var oLunchboxItems = lunchbox.oLunchbox.getElementsByTagName('div');
							var sRemoveThisItem = dD.curTarget.id;
							if (sRemoveThisItem && oLunchboxItems && (portion.extraPortion != 'y')){
								for (var i=0; i<oLunchboxItems.length; i++){
									if (oLunchboxItems[i].id == sRemoveThisItem){
										//increase portion size. do not add another instance
										//fix - needs to be put in on mouse up

										var oPortion = oLunchboxItems[i].getElementsByTagName('em')[0];
										if (oPortion){
											var iCurrentPortion = parseFloat(oPortion.className) + 1;
											oPortion.className = iCurrentPortion;
											var sPortion = oPortion.innerHTML;
											if (sPortion.indexOf('(x') != -1){
												var sPortionContent = sPortion.substring(0,sPortion.indexOf('('));
												oPortion.innerHTML = sPortionContent + ' (x' + iCurrentPortion.toFixed(0) + ')';
											}else{
												oPortion.innerHTML = oPortion.innerHTML + ' (x' + iCurrentPortion.toFixed(0) + ')';
											}
											trkUser.writeLog('A:'+sRemoveThisItem);
											oPortion.className = iCurrentPortion.toFixed(0);
											portion.extraPortion='y';
										}
										var extraPortion='done';
									}
								}
							}
							//new addition to lunchbox. therefore add to lunchbox and keep in foodsource
							if (!extraPortion && (portion.extraPortion != 'y')){
								var oCopyOfItem = dD.curTarget.cloneNode(true);
								oCopyOfItem.style.visibility = 'visible';
								oCopyOfItem.style.display = 'block';

								//get product ID
								var sCurrentTargetProductID = dD.curTarget.id.substring(4,dD.curTarget.id.length);

								//Leave the original element in place and copy the cloned node only into the lunchbox
								activeCont.appendChild(oCopyOfItem);

								var oNewCopy = oCopyOfItem.getElementsByTagName('h3')[0];
								if (oNewCopy){
								//	trkUser.writeLog('<p>New Item At End: ' + oNewCopy.innerHTML + '</p>');
								}								
							}
						}
					}
				}

				// the timeout is here because the container doesn't "immediately" resize
				setTimeout(function(){
				var contPos = getPosition(activeCont);
				activeCont.setAttribute('startWidth', parseInt(activeCont.offsetWidth));
				activeCont.setAttribute('startHeight', parseInt(activeCont.offsetHeight));
				activeCont.setAttribute('startLeft', contPos.x);
				activeCont.setAttribute('startTop', contPos.y);}, 5);

				// make our drag item visible
				if(dD.curTarget.style.display!=''){
					dD.curTarget.style.display = '';
					dD.curTarget.style.visibility = 'hidden';
				}
			}
		}
		dD.lMouseState = dD.iMouseDown;	//track the current mouse state so we can compare against it next time
		dD.lastTarget = target;			//mouseMove target

		if(dD.dragObject){
			dD.dragObject.style.position = 'absolute';
			dD.dragObject.style.top = mousePos.y - dD.mouseOffset.y;
			dD.dragObject.style.left = mousePos.x - dD.mouseOffset.x;
		}

		// track the current mouse state so we can compare against it next time
		dD.lMouseState = dD.iMouseDown;
		// this prevents items on the page from being highlighted while dragging
		if(dD.curTarget || dD.dragObject) return false;
	}
}

//use utils
function addEvent( obj, type, fn ) {
	if (obj.addEventListener) {
		obj.addEventListener( type, fn, false );
		EventCache.add(obj, type, fn);
	} else 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] );
		EventCache.add(obj, type, fn);
	} else {
		obj["on"+type] = obj["e"+type+fn];
	}
}

var EventCache = function(){
	var listEvents = [];
	return {
		listEvents : listEvents,
		add : function(node, sEventName, fHandler){
			listEvents.push(arguments);
		},
		flush : function(){
			var i, item;
			for(i = listEvents.length - 1; i >= 0; i = i - 1){
				item = listEvents[i];
				if(item[0].removeEventListener){
					item[0].removeEventListener(item[1], item[2], item[3]);
				};
				if(item[1].substring(0, 2) != "on"){
					item[1] = "on" + item[1];
				};
				if(item[0].detachEvent){
					item[0].detachEvent(item[1], item[2]);
				};
				item[0][item[1]] = null;
			};
		}
	};
}();


var portion = {
	extraPortion : 'n'
}

var lunchbox = {
	oLunchApp : Object,
	oLunchbox : Object,
	oProductDescriptionContainer : Object,
	oProductDescriptionContent : Object,
	oEmptyLunchbox : Object,
	init : function (){
		lunchbox.oLunchApp = document.getElementById('LunchApp');
		if(lunchbox.oLunchApp){
			lunchbox.initFixedObjects();
			lunchbox.setupScroll();
			lunchbox.createDragContainer();
			lunchbox.setupEmptyLunchbox();

			navigation.init();
			gda.init();
			buyLunchbox.init();
			
			trkUser.init();

		//applying properly results in text highlighting problems
			document.onmousemove = dD.mouseMove;
			document.onmousedown = dD.mouseDown;
			document.onmouseup = dD.mouseUp;
		}
	},
	initFixedObjects : function (){
		Number.prototype.NaN0=function(){return isNaN(this)?0:this;}

		lunchbox.oLunchbox = document.getElementById('Lunchbox');
		lunchbox.oProductDescriptionContainer = document.getElementById('ProductDescription');
		lunchbox.oProductDescriptionContent = lunchbox.oProductDescriptionContainer.getElementsByTagName('p')[0];
		lunchbox.oEmptyLunchbox = document.getElementById('emptyLunchbox');
	},
	setupScroll : function (){
		var oScrollLeft = document.getElementById('scrollLeft').getElementsByTagName('a')[0];
		var oScrollRight = document.getElementById('scrollRight').getElementsByTagName('a')[0];
		if (oScrollLeft && oScrollRight){
			oScrollLeft.removeAttribute('href');
			oScrollRight.removeAttribute('href');
			addEvent(oScrollLeft,'click',lunchbox.scrollFood);
			addEvent(oScrollRight,'click',lunchbox.scrollFood);
		}
	},
	createDragContainer : function (){						// Create our helper object that will show the item while dragging
		dD.buildDragContainer(document.getElementById('makeAllSource'), document.getElementById('breadSource'), document.getElementById('spreadSource'), document.getElementById('fillingSource'), document.getElementById('Lunchbox'), document.getElementById('snacksSource'), document.getElementById('dessertsSource'), document.getElementById('drinksSource'));
		dD.dragHelper = document.createElement('div');
		dD.dragHelper.style.cssText = 'position:absolute; display:none;';
		document.body.appendChild(dD.dragHelper);
	},
	writeProductDescription : function(target){
		lunchbox.oProductDescriptionContent.innerHTML=target.getElementsByTagName('p')[0].innerHTML;
	},
	scrollFood : function (){
		var sDirection = this.id;
		var oFood = document.getElementById(navigation.lastTab);
		if (oFood){

			var oItems = oFood.getElementsByTagName('div');
			if (oItems){
				var iItemCount = oItems.length;

				if (iItemCount > 0){
					var oFirstItem = oItems[0];
					var oLastItem = oItems[iItemCount-1];
					if (sDirection == 'goLeft'){
						//oFirstItem.style.width = '30px';							FIX - potential for fade
						//setTimeout(oFood.appendChild(oFirstItem), '1000');
						oFood.appendChild(oFirstItem);
					}else{
						oFood.insertBefore(oLastItem,oFirstItem);
					}
				}
			}
		}
	},
	setupEmptyLunchbox : function(){
		var oEmptyLink = lunchbox.oEmptyLunchbox.getElementsByTagName('a')[0];
		if (oEmptyLink){
			oEmptyLink.removeAttribute('href');
			addEvent(oEmptyLink,'click',lunchbox.emptyLunchbox);
		}
	},
	emptyLunchbox : function(){
		var oCurrentLunchboxItems = document.getElementById('Lunchbox').getElementsByTagName('div');
		if (oCurrentLunchboxItems){
			if (oCurrentLunchboxItems.length > 0){
				do{
					lunchbox.oLunchbox.removeChild(oCurrentLunchboxItems[0]);
				}while (oCurrentLunchboxItems.length > 0);
				gda.updateGDA(0,0,0,0,0);	//no items in lunchbox so reset the counters
				trkUser.writeLog('E');
			}
		}
	},
	addCloseOption : function(target){
		var oImg = target.getElementsByTagName('img')[0];
		if (oImg){
			oImg.style.visibility = 'visible';
			addEvent(target,'click',lunchbox.removeItemFromLunchbox);
		}

	},
	removeCloseOption : function(target){
		//fix - remove the event that is added in lunchbox.addCloseOption() otherwise we will have multiple onclick event handlers. OR only add one if one doesn't exist
		var oImg = target.getElementsByTagName('img')[0];
		if (oImg){
			oImg.style.visibility = '';
		}
		target.style.border='';
	},
	removeItemFromLunchbox : function(){
		var oLunchbox = document.getElementById('Lunchbox');
		var oLunchboxItems = oLunchbox.getElementsByTagName('div');
		var sRemoveThisItem = this.id;
		if (oLunchbox && sRemoveThisItem && oLunchboxItems){
			for (var i=0; i<oLunchboxItems.length; i++){
				if (oLunchboxItems[i].id == sRemoveThisItem){ //cos of duplicate ids
					try{						
						oLunchbox.removeChild(oLunchboxItems[i]);						
						//FIX in here we can improve by making only 1 portion go, rather than the whole stack.
						setTimeout(gda.calculateGDA,5);
						trkUser.writeLog('R:' + sRemoveThisItem);						
					}catch (error){ }
				}
			}
		}
	}
}

var gda = {
	iGDACalories : Number,
	iGDASugar : Number,
	iGDAFat : Number,
	iGDASaturates : Number,
	iGDASalt : Number,
	oNutrition : Object,
	oAdult : Object,
	oKid : Object,
	init : function (){
		gda.oNutrition = document.getElementById('nutrition');
		gda.setupGDAswitch();
	},
	setupGDAswitch : function (){
		gda.oAdult = document.getElementById('adultGDA');
		gda.oKid = document.getElementById('childGDA');
		if (gda.oAdult && gda.oKid){
			gda.oAdult.removeAttribute('href');
			gda.oKid.removeAttribute('href');
			addEvent(gda.oAdult,'click',gda.switchGDA);
			addEvent(gda.oKid,'click',gda.switchGDA);

			gda.switchGDA();
		}
	},
	switchGDA : function (){
		var sSwitchTo = this.id;
		if (sSwitchTo == 'childGDA'){
			gda.iGDACalories = 1800;
			gda.iGDASugar = 85;
			gda.iGDAFat = 70;
			gda.iGDASaturates = 20;
			gda.iGDASalt = 4;
			this.parentNode.className = 'childGDA';

			trkUser.writeLog('C');
		}else{
			gda.iGDACalories = 2000;
			gda.iGDASugar = 90;
			gda.iGDAFat = 70;
			gda.iGDASaturates = 20;
			gda.iGDASalt = 6;
			if (this.parentNode){this.parentNode.className = 'adultGDA';}
			else{gda.oAdult.parentNode.className = 'adultGDA';}

			trkUser.writeLog('Z');
		}
		gda.calculateGDA();
	},
	updateGDA : function(fCalsTotal,fSugarTotal,fFatTotal,fSaturatesTotal,fSaltTotal){
		var oGDAamounts = gda.oNutrition.getElementsByTagName('strong');
		if (oGDAamounts){
			oGDAamounts[0].innerHTML = fCalsTotal.toFixed(0);
			oGDAamounts[1].innerHTML = fSugarTotal.toFixed(1) + 'g';
			oGDAamounts[2].innerHTML = fFatTotal.toFixed(1) + 'g';
			oGDAamounts[3].innerHTML = fSaturatesTotal.toFixed(1) + 'g';
			oGDAamounts[4].innerHTML = fSaltTotal.toFixed(1) + 'g';
		}

		var oGDApc = gda.oNutrition.getElementsByTagName('em');
		if (oGDApc){
			oGDApc[0].innerHTML = ((fCalsTotal / gda.iGDACalories) * 100).toFixed(0) + '%';
			oGDApc[1].innerHTML = ((fSugarTotal / gda.iGDASugar) * 100).toFixed(0) + '%';
			oGDApc[2].innerHTML = ((fFatTotal / gda.iGDAFat) * 100).toFixed(0) + '%';
			oGDApc[3].innerHTML = ((fSaturatesTotal / gda.iGDASaturates) * 100).toFixed(0) + '%';
			oGDApc[4].innerHTML = ((fSaltTotal / gda.iGDASalt) * 100).toFixed(0) + '%';
		}
	},
	calculateGDA : function (){
		var oLunchboxItems = document.getElementById('Lunchbox').getElementsByTagName('p');
		if (oLunchboxItems){
			var fCalsTotal = 0;
			var fSugarTotal = 0;
			var fFatTotal = 0;
			var fSaturatesTotal = 0;
			var fSaltTotal = 0;
			for (var i=0; i<oLunchboxItems.length; i++){
				if (oLunchboxItems[i].className){
					var sItemClass = oLunchboxItems[i].className;
					if (sItemClass == 'gda'){
						var aItems = new Array();
						aItems = oLunchboxItems[i].innerHTML.split(',');
						if (aItems){
							var oItemParent = oLunchboxItems[i].parentNode;
							if (oItemParent){
								var oPortionSize = oItemParent.getElementsByTagName('em')[0];
								if (oPortionSize){
									var iPortionSize = parseFloat(oPortionSize.className);
								}
							}

							var sCal = aItems[0].slice(aItems[0].indexOf(':') + 1);
							if (sCal.indexOf('tr') != -1){sCal = '0';}
							fCalsTotal = fCalsTotal + (parseFloat(sCal) * iPortionSize);
							var sSug = aItems[1].slice(aItems[1].indexOf(':') + 1);
							if (sSug.indexOf('tr') != -1){sSug = '0';}
							fSugarTotal = fSugarTotal + (parseFloat(sSug) * iPortionSize);
							var sFat = aItems[2].slice(aItems[2].indexOf(':') + 1);
							if (sFat.indexOf('tr') != -1){sFat = '0';}
							fFatTotal = fFatTotal + (parseFloat(sFat) * iPortionSize);
							var sSat = aItems[3].slice(aItems[3].indexOf(':') + 1);
							if (sSat.indexOf('tr') != -1){sSat = '0';}
							fSaturatesTotal = fSaturatesTotal + (parseFloat(sSat) * iPortionSize);
							var sSal = aItems[4].slice(aItems[4].indexOf(':') + 1);
							if (sSal.indexOf('tr') != -1){sSal = '0';}
							fSaltTotal = fSaltTotal + (parseFloat(sSal) * iPortionSize);

							var updateGDA = true;
						}
					}
				}
			}

			if (updateGDA){
				gda.updateGDA(fCalsTotal,fSugarTotal,fFatTotal,fSaturatesTotal,fSaltTotal);
			}else{
				gda.updateGDA(0,0,0,0,0);	//no items in lunchbox so reset the counters
			}
		}
	}
}

var navigation = {
	homePane : Object,
	gdaPane : Object,
	buyPane : Object,
	saladSource : Object,
	snackSource : Object,
	dessertsSource : Object,
	drinksSource : Object,
	makeAllSource : Object,
	breadSource : Object,
	spreadSource : Object,
	fillingSource : Object,
	oNavigation : Object,
	oSubNavigation : Object,
	lastTab : null,
	init : function(){
		navigation.oNavigation = document.getElementById('nav');
		navigation.initFixedObjects();
		navigation.setupNavigation();
	},
	initFixedObjects : function (){
		navigation.lunchbox = document.getElementById('LunchApp');
		navigation.homePane = document.getElementById('homePane');
		navigation.gdaPane = document.getElementById('GDAinfoPane');
		navigation.buyPane = document.getElementById('buyLunchboxPane');
		navigation.makeAllSource = document.getElementById('makeAllSource');
		navigation.breadSource = document.getElementById('breadSource');
		navigation.spreadSource = document.getElementById('spreadSource');
		navigation.fillingSource = document.getElementById('fillingSource');
	//	navigation.saladSource = document.getElementById('saladsSource');
		navigation.snackSource = document.getElementById('snacksSource');
		navigation.dessertsSource = document.getElementById('dessertsSource');
		navigation.drinksSource = document.getElementById('drinksSource');
		navigation.oSubNavigation = document.getElementById('subNav');
	},
	setupNavigation : function (){
		navigation.oSubNavigation.style.display='none';

		var oNavItems = navigation.oNavigation.getElementsByTagName('a');
		if (oNavItems){
			for (var i=0; i<oNavItems.length; i++){
				var sRel = oNavItems[i].getAttribute('rel');
				if (sRel){
					addEvent(oNavItems[i],'click',navigation.switchmakeAllSource);
				}else{
					addEvent(oNavItems[i],'click',navigation.changePane);
				}
			}
			navigation.homePane.style.display='block';
		}
		var oNavItems = navigation.oSubNavigation.getElementsByTagName('a');
		if (oNavItems){
			for (var i=0; i<oNavItems.length; i++){
				addEvent(oNavItems[i],'click',navigation.sarnySourceSwitcher);
			}
		}
	},
	sarnySourceSwitcher : function(){
		//clear class names
		var oNavItems = navigation.oSubNavigation.getElementsByTagName('a');
		if (oNavItems){
			for (var i=0; i<oNavItems.length; i++){
				oNavItems[i].className='';
			}
			this.className='sel';//give this a sel class
		}

		//hide all sarny panes
		navigation.makeAllSource.style.display='none';
		navigation.breadSource.style.display='none';
		navigation.spreadSource.style.display='none';
		navigation.fillingSource.style.display='none';

		var sTargetPane = this.rel;
		var oPane = document.getElementById(sTargetPane);
		oPane.style.display='block';

		navigation.lastTab = sTargetPane;
	},
	clearNavigationIds : function(){
		var oNavItems = navigation.oNavigation.getElementsByTagName('a');
		if (oNavItems){
			for (var i=0; i<oNavItems.length; i++){
				oNavItems[i].id=' ';
			}
		}
	},
	changePane : function(){
		navigation.clearNavigationIds();
		navigation.oSubNavigation.style.display='none';
		this.id='selected';

		//Set pane click
		navigation.lunchbox.style.display='none';
		navigation.homePane.style.display='none';
		navigation.gdaPane.style.display='none';
		navigation.buyPane.style.display='none';

		var sPane = this.parentNode.id + 'Pane';
		if (sPane == 'buyLunchboxPane'){
			buyLunchbox.init();
		}
		var oPane = document.getElementById(sPane);
		oPane.style.display='block';
	},
	switchmakeAllSource : function (){
		navigation.clearNavigationIds();
		this.id='selected';

		//Set pane to 'LunchApp
		navigation.homePane.style.display='none';
		navigation.gdaPane.style.display='none';
		navigation.buyPane.style.display='none';
		navigation.lunchbox.style.display='block';

		//Show correct food source
	//	navigation.saladSource.style.display='none';
		navigation.snackSource.style.display='none';
		navigation.dessertsSource.style.display='none';
		navigation.drinksSource.style.display='none';
		navigation.makeAllSource.style.display='none';
		navigation.breadSource.style.display='none';
		navigation.spreadSource.style.display='none';
		navigation.fillingSource.style.display='none';

		var sRequiredPane = this.parentNode.id + 'Source';
		if (sRequiredPane == 'makeAllSource'){
			sRequiredPane = 'breadSource';
		}
		var oTargetFoodSource = document.getElementById(sRequiredPane);
		if (oTargetFoodSource){
			if (this.parentNode.id == 'makeAll'){
				navigation.oSubNavigation.style.display='block';
			}else{
				navigation.oSubNavigation.style.display='none';
			}
			navigation.lastTab = sRequiredPane;

			setTimeout(function(){oTargetFoodSource.style.display='block'},5);
		}
	}
}

var buyLunchbox = {
	yourLunchbox : Object,
	init : function(){
		buyLunchbox.yourLunchbox = document.getElementById('yourLunchbox');
		buyLunchbox.clearBuyList();
		buyLunchbox.fillBuyList();
		buyLunchbox.setupUtils();
	},
	setupUtils : function(){
		var oUtils = buyLunchbox.yourLunchbox.getElementsByTagName('a');
		if (oUtils){
			for (var i=0; i<oUtils.length; i++){
				oUtils[i].removeAttribute('href');
				if (oUtils[i].className=='minus'){
					addEvent(oUtils[i],'click',buyLunchbox.updateQuantity);
				}
				if (oUtils[i].className=='plus'){
					addEvent(oUtils[i],'click',buyLunchbox.updateQuantity);
				}
				if (oUtils[i].className=='remove'){
					addEvent(oUtils[i],'click',buyLunchbox.updateQuantity);
				}
			}
		}
		var oBuyButtonContainer = document.getElementById('buy');//FIX - this function is called twice so the event handler gets added twice which means in ie when you add to basket it does it twice.
		if (oBuyButtonContainer){
			var oLink = oBuyButtonContainer.getElementsByTagName('input')[0];
			if (oLink){
				if (oLink.id){
				}else{
					if (oBuyButtonContainer.className=='buyPartDeux'){
						addEvent(oLink,'click',buyLunchbox.addToBasketExternally);						
					}else{
						addEvent(oLink,'click',buyLunchbox.addToBasket);
					}
					oLink.id='buyHack';					
				}
			}
		}		

		var oClosePane = document.getElementById('closePane');
		if (oClosePane){
			addEvent(oClosePane,'click',buyLunchbox.closeWindow);
		}
	},
	closeWindow : function(){
		window.close();
	},
	fillBuyList : function(){
		var oLunchboxItems = lunchbox.oLunchbox.getElementsByTagName('div');
		if (oLunchboxItems){
			for (var i=0; i<oLunchboxItems.length; i++){
				var oDescription = oLunchboxItems[i].getElementsByTagName('p')[0];
				var sDescription = oDescription.innerHTML;
				var oPrice = oLunchboxItems[i].getElementsByTagName('h3')[0];
				var sPrice = oPrice.className;
				var oPortion = oLunchboxItems[i].getElementsByTagName('em')[0];
				var sPortion = oPortion.className;
				var sPid = oLunchboxItems[i].id;
				var sPidnew = sPid.substring(4, sPid.length);

				buyLunchbox.createBuyListItem(sPidnew,sDescription,sPortion,sPrice);
			}
		}
	},
	createBuyListItem : function(sPid,sDescription,sPortion,sPrice){
		var oUtils = buyLunchbox.yourLunchbox.getElementsByTagName('ul')[0];
		if (!oUtils){
			var oUtils = document.createElement('ul');
			buyLunchbox.yourLunchbox.appendChild(oUtils);
		}

		var oLi = document.createElement('li');
		oLi.id = sPid;

		var oP = document.createElement('p');
		var oPtxt = document.createTextNode(sDescription);

		var oA1 = document.createElement('a');
		oA1.className='minus';
		var oSpan1 = document.createElement('span');
		oSpan1.className=sPrice;
		var oSpan1txt = document.createTextNode('Remove One Item');
		var oA2 = document.createElement('a');
		oA2.className='plus';
		var oSpan2 = document.createElement('span');
		var oSpan2txt = document.createTextNode('Add One Item');
		var oA3 = document.createElement('a');
		oA3.className='remove';
		var oSpan3 = document.createElement('span');
		var oSpan3txt = document.createTextNode('Remove This Item');

		var oStrong = document.createElement('strong');
		var oStrongTxt = document.createTextNode('1');  //FIX - sPortion.... no because here we are dealing with whole products rather than individual products.

		oP.appendChild(oPtxt);

		oA1.appendChild(oSpan1);
		oSpan1.appendChild(oSpan1txt);
		oA2.appendChild(oSpan2);
		oSpan2.appendChild(oSpan2txt);
		oA3.appendChild(oSpan3);
		oSpan3.appendChild(oSpan3txt);

		oStrong.appendChild(oStrongTxt);

		oLi.appendChild(oP);
		oLi.appendChild(oA1);
		oLi.appendChild(oStrong);
		oLi.appendChild(oA2);
		oLi.appendChild(oA3);

		oUtils.appendChild(oLi);
	},
	clearBuyList : function(){
		var oUtils = buyLunchbox.yourLunchbox.getElementsByTagName('ul')[0];
		if (oUtils){
			buyLunchbox.yourLunchbox.removeChild(oUtils);
			trkUser.writeLog('X');
		}
	},
	updateQuantity : function(){
		var oParent = this.parentNode;
		var oQuantity = oParent.getElementsByTagName('strong')[0];
		var iQuantity = parseFloat(oQuantity.innerHTML);
		var sAction = this.className;
		//alert(iQuantity);
		if ((sAction == 'minus') && (iQuantity > 0)){
			oQuantity.innerHTML=iQuantity-1;
		//	trkUser.writeLog('<p>-1 quantity</p>');
		}else if (sAction == 'plus'){
			oQuantity.innerHTML=iQuantity+1;
		//	trkUser.writeLog('<p>+1 quantity</p>');
		}else if (sAction == 'remove'){
			var oGrandparent = oParent.parentNode;
			oGrandparent.removeChild(oParent);			
		//	trkUser.writeLog('<p>remove all from basket</p>');
		}
	},
	addToBasket : function(){
		var oYourLunchbox = document.getElementById('yourLunchbox');
		if (oYourLunchbox){
			var oProds = oYourLunchbox.getElementsByTagName('li');
			if (oProds){
				for (var i=0; i<oProds.length; i++){
					var sID = oProds[i].id;
					var oDesc = oProds[i].getElementsByTagName('p')[0];
					var sDesc = oDesc.innerHTML;
					var oPrice = oProds[i].getElementsByTagName('span')[0];
					var sPrice = oPrice.className;
					var oAmount = oProds[i].getElementsByTagName('strong')[0];
					var sAmount = oAmount.innerHTML;
					var iAmount = parseFloat(sAmount);

					for (var j=0; j<iAmount; j++){
						add(parseFloat(sID),sDesc,sPrice);// add(id, desc, price, looseWeightIndicator, mode, voucherId)
						trkUser.writeLog('B:' + sID);
					}					
				}
			}
		}
		
		window.location = "finish.asp?f=groc&aT="+sTrack;
	},
	addToBasketExternally : function(){
		var oYourLunchbox = document.getElementById('yourLunchbox');
		if (oYourLunchbox){
			var oProds = oYourLunchbox.getElementsByTagName('li');
			if (oProds){
				var sProductIDs = '';
				for (var i=0; i<oProds.length; i++){
					var sID = oProds[i].id;
					sProductIDs = sProductIDs + ',' + sID;					
				}
				var sFinalProductString = sProductIDs.substring(1,sProductIDs.length);				
				var sURL = 'http://www.tesco.com/superstore/?url=%2Fsuperstore%2Fframes%2Fmain%2Easp%3Furl%3D%2Fsuperstore%2Fframes%2FmainContent%2Easp%3Fmain%3D%2Fsuperstore%2Fproduct%2Flist.aspx?items=' + sFinalProductString + '%26listId=Customer%20Favourites%26leftnav%3D%2Fsuperstore%2Fp%2FLeftBar%2FnavHomePage%2Ehtm';

				window.open(sURL,'grocery','status=1,menubar=1,resizable=1,toolbar=1,directories=1,scrollbars=1,fullscreen=0');
			}
		}
		window.location = "finish.asp?aT="+sTrack;
	}

//superstore/?url=%2Fsuperstore%2Fframes%2Fmain%2Easp%3Furl%3D%2Fsuperstore%2Fframes%2FmainContent%2Easp%3Fmain%3D%2Fsuperstore%2Fhomepages%2Fdepartmental.aspx?ParentCode=B%26leftnav%3D%2Fsuperstore%2Fp%2FLeftBar%2FnavHomePage%2Ehtm
//superstore%2Fproduct%2Flist.aspx?items=<PRODUCTID>,<PRODUCTID>,<PRODUCTID>%26listId=Customer%20Favourites
//superstore/product/list.aspx?items=<PRODUCTID>,<PRODUCTID>,<PRODUCTID>&amp;listId=Customer%20Favourites

	//window.open('/superstore/','grocery','status=1,menubar=1,toolbar=1,directories=0,width=600,height=500,top=60,left=60');

}


var trkUser = {
	oHistory : Object,
	init : function(){
		trkUser.oHistory = document.getElementById('aT');
		if (trkUser.oHistory){
			trkUser.oHistory.value = '';
		}
	},
	writeLog : function(newAction){
		var sTemp = trkUser.oHistory.value;
		/*
			A - Add a product
			R - Remove a product
			C - Switch to Child GDA
			Z - Switch to Adult GDA
			E - Empty Lunchbox
			X - Clear Buy List
			B - Add To Basket
		*/

		var sNewAction = newAction.replace('Item','');
		trkUser.oHistory.value = sTemp + '|' + sNewAction;
	}
}

//trkUser.writeLog();

addEvent(window,'load',lunchbox.init);