
//-------------------- MaxCore.js

var MenuOptionDraggableMethods = {

	initialize: function( htmlElement ) {
	      this.type        = 'MenuOption';
	      this.htmlElement = $(htmlElement);
	//      this.name        = name;
	   },

   select: function() {
      this.selected = true;
      var el = this.htmlElement;
      
      // show the item selected.....
      // el.style.color           = "#ffffff";
      // el.style.backgroundColor = "#08246b";
   },

   deselect: function() {
      this.selected = false;
      var el = this.htmlElement;
      // el.style.color           = "#2b2b2b";
      // el.style.backgroundColor = "transparent";
   },

/*   startDrag: function() {
   
   },

   cancelDrag: function() {
      // Rico.writeDebugMsg("cancelDrag: [" + this.name +"]");
   },

   endDrag: function() {
      // Rico.writeDebugMsg("endDrag: [" + this.name +"]");
   },
*/
   getSingleObjectDragGUI: function() {
      var div = document.createElement("div");
      div.className = 'menu-option-draggable ' + this.htmlElement.className;
//       alert(this.htmlElement.className);
      // div.style.width = 10; // this.htmlElement.offsetWidth - 10;
      //new Insertion.Top( div, this.name );
     // alert( this.getMouseDownHTMLElement().innerHTML);
      new Insertion.Top( div, this.htmlElement.innerHTML);
      
      return div;
   },

   getDroppedGUI: function() {
      var div = document.createElement("div");
      // var names = this.name.split(",");
      // new Insertion.Top( div, "[" + names[1].substring(1) + " " + names[0]+ "]" );
      //new Insertion.Top( div, "DROPPED A MENU" );
      div.className = "crt-calendar-schedule-dnd-result";
      div.sourceId = this.htmlElement.id;
    
      return div;
   }
}

var MenuOptionDropzoneMethods = {

	initialize: function( htmlElement, menuOptionScheduler, showHoverElementClassname ) {
	      this.htmlElement = $(htmlElement);
	      this.moScheduler = menuOptionScheduler;
	      this.showHoverElementClassname = showHoverElementClassname;
	},
	
	activate: function() {
      var htmlElement = this.getHTMLElement();
      if (htmlElement == null  || this.showingActive)
         return;

      this.showingActive = true;
      this.saveBackgroundColor = htmlElement.style.backgroundColor;

     	/*var fallbackColor = "#ffea84";
      
      var currentColor = Rico.Color.createColorFromBackground(htmlElement);
      if ( currentColor == null )
         htmlElement.style.backgroundColor = fallbackColor;
      else {
         currentColor.isBright() ? currentColor.darken(0.2) : currentColor.brighten(0.2);
         htmlElement.style.backgroundColor = currentColor.asHex();
      }*/
      htmlElement.style.backgroundColor = "#F5DEB3";
   },

   deactivate: function() {
      var htmlElement = this.getHTMLElement();
      if (htmlElement == null || !this.showingActive)
         return;

      htmlElement.style.backgroundColor = this.saveBackgroundColor;
      this.showingActive = false;
      this.saveBackgroundColor = null;
   },

   showHover: function() {
      var htmlElement = this.getHTMLElement();
      if ( htmlElement == null || this.showingHover )
         return;

      this.saveBorderWidth = htmlElement.style.borderWidth;
      this.saveBorderStyle = htmlElement.style.borderStyle;
      this.saveBorderColor = htmlElement.style.borderColor;
      
      this.showingHover = true;
      htmlElement.style.borderWidth = "1px";
      htmlElement.style.borderStyle = "solid";
      //htmlElement.style.borderColor = "#ff9900";
      // htmlElement.style.borderColor = "#483D8B";
      htmlElement.style.borderColor = "#483D8B";
      var hoverElement = null;
      var hoverElementList = crtCore.getElementsByClassName(this.showHoverElementClassname, 'div', htmlElement);
      if (hoverElementList.length > 0) {	   	
		   hoverElement = hoverElementList[0];  			   
		} 
		if (hoverElement) {
			this.saveHoverElement = hoverElement;
			this.saveHoverElementBackgroundColor = hoverElement.style.backgroundColor;
			this.saveHoverElementColor = hoverElement.style.color;
      	hoverElement.style.backgroundColor = "#483D8B";
      	hoverElement.style.color = "#FFFFFF";
      }

      
   },

   hideHover: function() {
        
      var htmlElement = this.getHTMLElement();
  
      if ( htmlElement == null || !this.showingHover )
         return;
         
      htmlElement.style.borderWidth = this.saveBorderWidth;
      htmlElement.style.borderStyle = this.saveBorderStyle;
      htmlElement.style.borderColor = this.saveBorderColor;

      var hoverElement = this.saveHoverElement;
     /* var dayHeaderList = crtCore.getElementsByClassName('day-header', 'div', this.htmlElement.id);
      if (dayHeaderList.length > 0) {	   	
		   dayHeader = dayHeaderList[0];  			   
		} */
		if (hoverElement) {
      	hoverElement.style.backgroundColor = this.saveHoverElementBackgroundColor;
      	hoverElement.style.color = this.saveHoverElementColor;
      	this.saveHoverElement = null;
      }
      
      this.showingHover = false;
      
   },

   canAccept: function(draggableObjects) {
      return true;
   },

   accept: function(draggableObjects) {
   
      var htmlElement = this.getHTMLElement();
      if ( htmlElement == null )
         return;

      n = draggableObjects.length;
      for ( var i = 0 ; i < n ; i++ )
      {
         var theGUI = draggableObjects[i].getDroppedGUI();
/*         alert("accepting: " + theGUI.className);
         alert("accepting: " + theGUI.sourceId);    
         alert("accepting date: " + htmlElement.id);   
  */
         
         this.moScheduler.scheduleMenu(theGUI.sourceId, htmlElement.id);

/*         if (Element.getStyle(theGUI,'position')=='absolute')*/
/*alert(RicoUtil.getElementsComputedStyle);
         if ( RicoUtil.getElementsComputedStyle( theGUI, "position" ) == "absolute" )
         {
            theGUI.style.position = "static";
            theGUI.style.top = "";
            theGUI.style.top = "";
         }
         htmlElement.appendChild(theGUI);
*/
      }
  
   }
}

MenuOptionCalendarScheduler = Class.create();

MenuOptionCalendarScheduler.prototype = {

   initialize: function() {
   	  		
   	this.dndOptions = {
		  sourceDesc	: '',
		  targetDesc	: '',
		  url				: '/ccs/dynamic/menuSchedView/ajaxScheduleMenu',
		  id				: 'menu-calendar-scheduler',
		  callback		: this._schedulingComplete
		};
		
   	this.dndManager = new CrtDragAndDropManager(this.dndOptions);
	},
	
   scheduleMenu: function(menuInfo, dayInfo) {
   	this.dndManager.sendDropRequest(menuInfo, dayInfo);
   },
   
   _schedulingComplete: function(options, ajaxResponse) {
   	// just reload, to pull in menu changes
   	//window.location.href = window.location.href;
   }

}

MenuOptionGridScheduler = Class.create();

MenuOptionGridScheduler.prototype = {

   initialize: function() {
   	  		
   	this.dndOptions = {
		  sourceDesc	: '',
		  targetDesc	: '',
		  url				: '/ccs/dynamic/menuSchedView/ajaxScheduleMenuToCycle',
		  id				: 'menu-grid-scheduler',
		  callback		: this._schedulingComplete
		};
		
   	this.dndManager = new CrtDragAndDropManager(this.dndOptions);
	},
	
   scheduleMenu: function(menuInfo, dayInfo) {
   	var refInfoNode = document.getElementById('menu-cycle-name');
   	this.dndManager.sendDropRequest(menuInfo, dayInfo, refInfoNode.value);
   },
   
   _schedulingComplete: function(options) {
   	// just reload, to pull in menu changes
   	// window.location.href = window.location.href;
   }

}

// The main class object for CCS-specific functions

MaxCore = Class.create();

MaxCore.prototype = {

   initialize: function() {
   	
   	this.suggestOptions = {
		  selectionClassName	: 'selection',
		  matchTextWidth		: false,
        matchAnywhere      : true,
        ignoreCase         : true,
        count					: 20,
        standAlone   		: true,
        title					: 'Select Meal Component',
        suggestSuffix		: 'mc-code',
        value1Suffix			: 'meal-component',
        value2Suffix			: 'mc-code',
        value3Suffix			: 'mc-description'
		};
		
		this.suggestGuardianOptions = {
		  selectionClassName	: 'selection',
		  matchTextWidth		: false,
        matchAnywhere      : true,
        ignoreCase         : true,
        count					: 8,
        standAlone   		: false,
        title					: 'Assign Child To Parent',
        suggestSuffix		: 'gs-description',
        value1Suffix			: 'gs-id-guardian',
        value2Suffix			: 'gs-description'
		};
		
	   this.updateOptions = {
	        updateSuffix		   : 'mc-code',
	        valueArray			: new Array('meal-component', 'mc-code', 'mc-description'),
	        errorSuffix			: 'mc-description'
	   };
	
	   this.updateQtyOptions = {
	        updateSuffix		   : 'mc-fraction',
	        valueArray			: new Array('qty1', 'qty2', 'qty3', 'unit')
	   };
	   
	   var onloadAction=function() { Rico.onLoad( maxCore.windowLoaded ); };
    	if (window.addEventListener)
      	window.addEventListener('load', onloadAction, false);
    	else if (window.attachEvent)
      	window.attachEvent('onload', onloadAction);
	
	},
	
	windowLoaded: function() {

//crtCore.setDebugArea('javascript-debug', true);

//var sidebarMenu = $('subnavigation');
//if (sidebarMenu) {
//Rico.Corner.round(sidebarMenu, {border: '#2e80570'});
//}

		maxCore.resetMealCountTabOrder();
		maxCore.initializeClaimProcess();
		
		document.targetDiv = document.getElementById("crt-calendar-schedule-dnd-target");
		if (document.targetDiv) {
			document.sourceDiv = document.getElementById("crt-calendar-schedule-dnd-source");
			if (document.targetDiv && document.sourceDiv) {
				maxCore.registerCalendarScheduleDndZones();
			}
		} else {
			document.targetDiv = document.getElementById("crt-grid-schedule-dnd-target");
			document.sourceDiv = document.getElementById("crt-grid-schedule-dnd-source");
			if (document.targetDiv && document.sourceDiv) {
				maxCore.registerGridScheduleDndZones();
			}
		}
	
		startVendorList();
	
	},
	
	executeMenuWeekUpdateBehavior: function(id, elementUpdateSuffix) {		
		var options = this.updateOptions;
	
		if (elementUpdateSuffix) {
			options = { updateSuffix : elementUpdateSuffix };
		}
	
		var endIndex = id.length - options.updateSuffix.length;
		
		var ajaxInProgress = document.getElementById(id).ajaxInProgress;
		
		var pfQueryString = window.top.location.search.substring(1); // this should have the query string Trinidad uses to track page flow.
		var proc = '/ccs/dynamic/menuWeekView/ajaxGetMealComponentDetails';
		
		if (pfQueryString) {
			proc += "?" + pfQueryString;
		};
		
		if (ajaxInProgress != 'TextSuggest') {
			update = new TextUpdate(
				id.substring(0, endIndex),
				proc,
				document.getElementById(id).value,
				options
		  	);
		}
  	
	},
   
   executeMenuQtyUpdateBehavior: function(id, analysis) {
		var endIndex = id.length - this.updateQtyOptions.updateSuffix.length;
//alert('innit!!!! ID=' + id);
		var mcCode = $(id.substring(0, endIndex) + 'mc-code').value;
		var fraction = '';
		
		if (mcCode) {
			fraction = $(id).value;
		}

		ajaxEngine.registerAjaxElement(id.substring(0, endIndex) + 'mc-estimated-qty'); // this is so we can directly replace the element with our ajax response
		ajaxEngine.registerAjaxElement(id.substring(0, endIndex) + 'mc-estimated-qty-unit'); // this is so we can directly replace the element with our ajax response
		
		var pfQueryString = window.top.location.search.substring(1); // this should have the query string Trinidad uses to track page flow.
		
		this.updateQtyOptions.requestParameters = [];
		this.updateQtyOptions.requestParameters.push('mc-code=' + mcCode);
		this.updateQtyOptions.requestParameters.push('analysis=' + analysis);
		
		var qParams = pfQueryString.split("&");
		for(var i = 0; i < qParams.length; i++){
			this.updateQtyOptions.requestParameters.push(qParams[i]);
		}
			
		update = new TextUpdate(
				id.substring(0, endIndex),
				'/ccs/dynamic/menuView/ajaxGetMealComponentQuantities',
				fraction,
				this.updateQtyOptions
		 );
		
	},	
	
	executeUpdateHeadCount: function(id, headcount, analysis) {		
		headcount = headcount.replace(/[\s\.]/g, '');
		$(id).value = headcount;
				
		if (headcount != parseInt(headcount)) {
			$(id).value = '';
		}
		
		var sourceDiv = id.substring(0, id.indexOf('-AG')) + '-meal-body';

		var hcOptions = {
		  url	: '/ccs/dynamic/menuView/ajaxUpdateMealEstimatedQuantities',
		  id  : id
		};
		
		var pfQueryString = window.top.location.search.substring(1); // this should have the query string Trinidad uses to track page flow.
			
		var updateList = crtCore.getElementsByClassName('mc-estimated-qty-cont', 'td', sourceDiv);
		
		for (index in updateList) {
			var element = updateList[index];
		   if (element.id) {
		   	ajaxEngine.registerAjaxElement(element.id); // this is so we can directly replace the element with our ajax response
		   }		   		
		}
		
		var reqParams = [];
		reqParams.push('analysis=' + analysis);
		reqParams.push('headcount=' + headcount);
		
		var qParams = pfQueryString.split("&");
	    for(var i = 0; i < qParams.length; i++){
	    	reqParams.push(qParams[i]);
	    }
	      
		var manager = new CrtAjaxManager( hcOptions );
		manager.sendRequest(reqParams);

	},
		
	callbackSuggestBehavior: function(options) {
		var endIndex = options.id.length - options.suggestSuffix.length;
		var fracId = options.id.substring(0, endIndex) + this.updateQtyOptions.updateSuffix;
		updateMealComponent(fracId, options.analysis);	
   },
   
   injectSuggestBehavior: function(id, analysis) {
   
		var endIndex = id.length - this.suggestOptions.suggestSuffix.length;
		
		this.suggestOptions.id = id;
		this.suggestOptions.analysis = analysis;

		this.suggestOptions.callback = this.callbackSuggestBehavior.bind(this);
		
		var pfQueryString = window.top.location.search.substring(1); // this should have the query string Trinidad uses to track page flow.
		var proc = '/ccs/dynamic/menuView/ajaxGetMealComponentOptions';
		
		if (pfQueryString) {
			proc += "?" + pfQueryString;
		}
		
		suggest = new TextSuggest(
			id.substring(0, endIndex),
			proc,
			this.suggestOptions
	  	);
	  	
	  	$(id).onfocus = null;
	  
	},
	
	injectMenuWeekSuggestBehavior: function(id) {
	
		var endIndex = id.length - this.suggestOptions.suggestSuffix.length;
		
		var pfQueryString = window.top.location.search.substring(1); // this should have the query string Trinidad uses to track page flow.
		var proc = '/ccs/dynamic/menuWeekView/ajaxGetMealComponentOptions';
		
		if (pfQueryString) {
			proc += "?" + pfQueryString;
		}
		
		suggest = new TextSuggest(
			id.substring(0, endIndex),
			proc,
			this.suggestOptions
	  	);
	  	
	  	$(id).onfocus = null;
	  	suggest.options.singleUse = true;
	  	var errorId = id.substring(0, endIndex) + this.updateOptions.errorSuffix;
	  	setStyle(errorId, 'color', 'black');
	  	suggest.handleTextInput();
	 },
	 
	 injectGuardianSuggestBehavior: function(id) {
		
		var endIndex = id.length - this.suggestGuardianOptions.suggestSuffix.length;
		
		var pfQueryString = window.top.location.search.substring(1); // this should have the query string Trinidad uses to track page flow.
		var proc = '/ccs/dynamic/center/ajaxGetGuardianOptions';
		
		if (pfQueryString) {
			proc += "?" + pfQueryString;
		}
		
		suggest = new TextSuggest(
			id.substring(0, endIndex),
			proc,
			this.suggestGuardianOptions
	  	);
	  	
	  	$(id).onfocus = null;
	  
	 },
	 
	 updateClaimProviderOptions: function(self) {
	 	var recalcCheckbox = crtCore.getNextSibling(self.parentNode.parentNode).childNodes[3].childNodes[0];
	 	if (!self.checked) {	 		
	 		recalcCheckbox.checked = false;
	 		if (!recalcCheckbox.disabled) {
	 			recalcCheckbox.allowed = true;
	 		}
	 		recalcCheckbox.disabled = true;
	 		this.updateClaimProviderCalcMethod(recalcCheckbox);
	 	} else {
	 		if (recalcCheckbox.allowed) {
	 			recalcCheckbox.disabled = false;
	 			this.updateClaimProviderCalcMethod(recalcCheckbox);
	 		} 
	 	}
	 },
	 
	 updateClaimProviderCalcMethod: function(self) {	
                var node = crtCore.getNextSibling(self.parentNode.parentNode);

		var calcMethodSelect;

		// More tests to account for server differences.
		if (node.childNodes[1].tagName == 'SELECT') {
                  calcMethodSelect = node.childNodes[1];
		} else {
		  calcMethodSelect = node.childNodes[3];
		}

		calcMethodSelect.disabled = !self.checked;
	 },
	 
	 updateMealCountView: function() {
		 maxCore.viewUpdated = false;
		 TrPage.getInstance().getRequestQueue().addStateChangeListener( maxCore.mealCountViewChangeCallback, maxCore ); 
	 },
	 
	 mealCountViewChangeCallback: function(status) {
		if ((status == TrRequestQueue.STATE_READY) && (!maxCore.viewUpdated)) {
			this.viewUpdated = true;
			this.resetMealCountTabOrder();
		}
	 },
	 
	 resetMealCountTabOrder: function() {
		 
		 var node = document.getElementById("tabOrderSelect");
		 
		 if (!node)
			 return;

		 for (nodeindex in node.childNodes) {
			 var childNode = node.childNodes[nodeindex];
			 if (childNode.checked) {
				 this.selectMealCountTabOrder(childNode); 
			 }
		 }
	 },
	 
	 initializeClaimProcess: function() {
		var node = document.getElementById("claimProcessForm");
		
		if (node) {
			var targetList = crtCore.getElementsByClassName("claim-recalculate-option", "span", node);

			for (var index in targetList) {
				var target = targetList[index];
				 
				if (!target.className) continue;
				
				target = crtCore.getPreviousSibling(target);
		
				if (!target) break;
				
				target = crtCore.getPreviousSibling(target);
				target = target.childNodes[0];
				
				maxCore.updateClaimProviderCalcMethod(target);

			}
		} 
	 },
	 
	 selectMealCountTabOrder: function(self) {
		 
		 var idPrefix = "weekCountTable";
		 var targetDiv = document.getElementById(idPrefix);
		 var targetList = crtCore.getElementsByClassName('mealCountDay', 'span', targetDiv);
		 
		 if (targetList.length > 0) {
			
			var childIndex = 3;
			var target = targetList[0];
		    	if ((target.childNodes[childIndex].id.length - target.childNodes[childIndex].id.lastIndexOf("day")) != 4) {
				// we check and possibly modify this, because it's different on the live server vs. the dev server
				childIndex = 1;
			}

			for (index in targetList) {
				target = targetList[index];
		   		
				if (target.childNodes && target.childNodes[childIndex]) {
//alert((target.childNodes[1].id.length - target.childNodes[1].id.lastIndexOf("day")) != 4);
//alert('Childnode ID: ' + target.childNodes[childIndex].id);
					var tabIndex = '';
					
					if (self.value == 'Down') {
						var nodeId = target.childNodes[childIndex].id;
						var dayNum = parseInt(nodeId.substr(nodeId.length - 1, 1));
						var rowNum = parseInt(nodeId.substr(idPrefix.length + 1, nodeId.lastIndexOf(":") - (idPrefix.length + 1)));
						var tabIndex = rowNum + (dayNum * 1000);

					}
//alert('TABINDEX: ' + tabIndex);
					target.childNodes[childIndex].tabIndex = tabIndex;
				}
		   		
			}

		 }
	 },
	 
	 updateDeclarationState: function(self) {			
		 this.checkRightwardDeclarations(self);		 
	 },
	 
	 checkRightwardDeclarations: function(self) {
		 
		 this.toggleDowngroupDeclarations(self);
		 if (self.checked) {
		   var td = self.parentNode.parentNode.parentNode;
		   var sibtd = crtCore.getNextSibling(td);
		   
		   if (sibtd) {
			   
			  var sibcheck = null;
			  // We need to test for child node existence, due to different behaviour depending
			  // on whether code runs on production or development server
			  if (sibtd.childNodes[1]) {
			  	 sibcheck = sibtd.childNodes[1].childNodes[0].childNodes[0];
			  } else {
				 sibcheck = sibtd.childNodes[0].childNodes[0].childNodes[0];
			  }
			  sibcheck.checked = true;		
			  this.checkRightwardDeclarations(sibcheck);
		   }
		   
		}
		
	 },
	 	 
	 toggleDowngroupDeclarations: function(self) {
		 
		 var className = self.parentNode.parentNode.className;
		 // alert(className);
		 
		 var divIndex = className.indexOf("-");
		 var subgroup = className.substring(0, divIndex);
		 // alert("subgroup: " + subgroup);
		 
		 var groupDiv = self.parentNode.parentNode.parentNode.parentNode.parentNode;	
		 		  
		 do {			 
			 subgroup++;
			 var modClassName = subgroup + className.substring(divIndex, className.length);		 		 
			 var grpDeclareList = crtCore.getElementsByClassName(modClassName, 'span', groupDiv);
			 
			// alert("declaration cnt: " + grpDeclareList.length);
			 for (var index in grpDeclareList) {
				if (grpDeclareList[index].className) {
					grpDeclareList[index].childNodes[0].childNodes[0].disabled = self.checked;
				}
			 }
		 } while (grpDeclareList.length > 0);
	 },
	 
	 registerCalendarScheduleDndZones: function(isDelayed, delayCnt) {
	 
	 	var count = 0;
	 	if (delayCnt) {
	 		count = delayCnt;
	 	}
	 
	 	var targetDiv = document.targetDiv;
		var sourceDiv = document.sourceDiv;
			   
	 	if (targetDiv && sourceDiv) {
	 	
	 		var ScrollingDragAndDropManager = Class.create();
			ScrollingDragAndDropManager.prototype = Object.extend(new Rico.DragAndDrop(), ScrollingDragAndDropManagerMethods);
			dndMgr = new ScrollingDragAndDropManager();
			dndMgr.initializeEventHandlers();
	 	
			var moScheduler = new MenuOptionCalendarScheduler();
	   	   	
	   	dndMgr.clearDropZones();
	   	var MenuOptionDropzone = Class.create();
	   	MenuOptionDropzone.prototype = Object.extend(new Rico.Dropzone(), MenuOptionDropzoneMethods);
	   	
	   	// ajaxEngine.registerAjaxElement('crt-calendar-schedule'); // this is so we can directly replace the element with our ajax response
	    	
	   	var targetList = crtCore.getElementsByClassName('day-content day-valid', 'td', targetDiv);
		   if (targetList.length > 0) {

			   var MenuOptionDraggable = Class.create();
		   	MenuOptionDraggable.prototype = Object.extend(new Rico.Draggable(), MenuOptionDraggableMethods);
		   			   
			   var sourceListA = crtCore.getElementsByClassName('crt-dnd-source', 'a', sourceDiv);
			   var sourceListSpan = crtCore.getElementsByClassName('crt-dnd-source', 'span', sourceDiv);
			   var sourceList = sourceListA.concat(sourceListSpan);
			   
			   // Load the source items first (because we may have to abort), then come back to the target items
			   if (sourceList.length > 0) {
			   	
	 // alert('FOUND SOURCE ITEMS: ' + sourceList.length);
			   	for (index in sourceList) {
			   		var source = sourceList[index];
			   		if (source.id) {
			   			
							if ((source.listLoaded === true) && isDelayed && (count < 10)) {
								//alert('list was already loaded; waiting for reload...current delay count: ' + count);
								setTimeout('maxCore.registerCalendarScheduleDndZones(true, ' + (count + 1) + ')', 300);
							 	return; 	
							}
			   			
			   			source.listLoaded = true;
			   		//alert("source ID: " + source.id);
			   			//dndMgr.registerDraggable( new Rico.Draggable('div', source.id) );   
			   			dndMgr.registerDraggable( new MenuOptionDraggable(source.id) );   					
			   		}
			   		
			   	}
			   } else {
			   	// This is in case the previous list had no items, but the new one does have items
			   	// (when switching between menu def list and menu cycle list)
			   	if (isDelayed && (count < 10)) {
						setTimeout('maxCore.registerCalendarScheduleDndZones(true, ' + (count + 1) + ')', 300);
						return; 	
					}
			   }
			   
			   // alert('FOUND TARGET ITEMS: ' + targetList.length);
		   	for (index in targetList) {
		   		var target = targetList[index];
		   		if (target.id) {
		   			dndMgr.registerDropZone( new MenuOptionDropzone(target.id, moScheduler, 'day-header') );
		   			ajaxEngine.registerAjaxElement(target.id); // this is so we can directly replace the element with our ajax response
		   		}
		   		
		   	}
		   
			}
		   
		} 
				
		return;
	 },
	 
	 	registerGridScheduleDndZones: function(isDelayed, delayCnt) {
	 
	 	var count = 0;
	 	if (delayCnt) {
	 		count = delayCnt;
	 	}
	 	
	 	var targetDiv = document.targetDiv;
		var sourceDiv = document.sourceDiv;
	 		   
	 	if (targetDiv && sourceDiv) {
	 	
	 		var ScrollingDragAndDropManager = Class.create();
			ScrollingDragAndDropManager.prototype = Object.extend(new Rico.DragAndDrop(), ScrollingDragAndDropManagerMethods);
			dndMgr = new ScrollingDragAndDropManager();
			dndMgr.initializeEventHandlers();
	 	
			var moScheduler = new MenuOptionGridScheduler();
	   	   	
	   	dndMgr.clearDropZones();
	   	var MenuOptionDropzone = Class.create();
	   	MenuOptionDropzone.prototype = Object.extend(new Rico.Dropzone(), MenuOptionDropzoneMethods);
	   	 	
	   	var targetList = crtCore.getElementsByClassName('cell-content cell-valid', 'td', targetDiv);
		   if (targetList.length > 0) {
		   
		   	var MenuOptionDraggable = Class.create();
		   	MenuOptionDraggable.prototype = Object.extend(new Rico.Draggable(), MenuOptionDraggableMethods);
		   			   
				var sourceList = crtCore.getElementsByClassName('crt-dnd-source', 'span', sourceDiv);
		   
		   	// Load the source items first (because we may have to abort), then come back to the target items
			   if (sourceList.length > 0) {
// alert('FOUND SOURCE ITEMS: ' + sourceList.length);
			   	for (index in sourceList) {
			   		var source = sourceList[index];
			   		if (source.id) {
			   			
			   			if ((source.listLoaded === true) && isDelayed && (count < 10)) {
								//alert('list was already loaded; waiting for reload...current delay count: ' + count);
								setTimeout('maxCore.registerGridScheduleDndZones(true, ' + (count + 1) + ')', 300);
							 	return; 	
							}
			   			
			   			source.listLoaded = true;
	//		   		alert("source ID: " + source.id);
			   			//dndMgr.registerDraggable( new Rico.Draggable('div', source.id) );   
			   			dndMgr.registerDraggable( new MenuOptionDraggable(source.id) );   					
			   		}
			   		
			   	}
			   } 

// alert('FOUND TARGET ITEMS: ' + targetList.length);
		   	for (index in targetList) {
		   		var target = targetList[index];
		   		if (target.id) {
		   			dndMgr.registerDropZone( new MenuOptionDropzone(target.id, moScheduler, 'cell-header') );
		   			ajaxEngine.registerAjaxElement(target.id); // this is so we can directly replace the element with our ajax response
		   		}
		   		
		   	}
		  		   			   
			}
		   
		}
	 }
   
};
   
//------------------ End MaxCore Class ---------------------------------

var maxCore = new MaxCore();

startVendorList = function() {

	if (document.all&&document.getElementById) {
	
		navRoot = document.getElementById("vendorTrigger");
			
		if (navRoot == null) return;
		
		navRoot.onmouseout=function() {
		  this.className=""; 
		}
		navRoot.onmouseover=function() {
			this.className="hover";
		}
		
		for (i=0; i<navRoot.childNodes.length; i++) {
			node = navRoot.childNodes[i];
			
			if ((node.nodeName=="UL")) {
			
				node.onmouseover=function() {
					document.getElementById("vendorTrigger").className="hover";
				}
			  			  
			}
		}
	}
}

executeMenuWeekUpdateBehavior = function(id, updateSuffix) {
	maxCore.executeMenuWeekUpdateBehavior(id, updateSuffix);
}

executeMenuQtyUpdateBehavior = function(id, analysis) {
	maxCore.executeMenuQtyUpdateBehavior(id, analysis);
}

injectSuggestBehavior = function(id, analysis) {
	maxCore.injectSuggestBehavior(id, analysis);
}

injectMenuWeekSuggestBehavior = function(id) {
	maxCore.injectMenuWeekSuggestBehavior(id);
}

/*
maxLoad = function() {
	Rico.loadModule('Accordion');

	var regFunction;
	document.targetDiv = document.getElementById("crt-calendar-schedule-dnd-target");
	if (document.targetDiv) {
		document.sourceDiv = document.getElementById("crt-calendar-schedule-dnd-source");
		regFunction = maxCore.registerCalendarScheduleDndZones
	} else {
		document.targetDiv = document.getElementById("crt-grid-schedule-dnd-target");
		document.sourceDiv = document.getElementById("crt-grid-schedule-dnd-source");
		regFunction = maxCore.registerGridScheduleDndZones
	}
	
	if (document.targetDiv && document.sourceDiv) {
		alert('dragging and dropping...');
		Rico.loadModule('DragAndDrop');
		Rico.loadModule('Corner');
		Rico.onLoad( regFunction );
	}
	
	startVendorList();
}
*/


mealScheduleOnclick = function(selectedEventId, eventValue) {

	document.getElementById(selectedEventId).value=eventValue; 
	document.getElementById(selectedEventId).form.submit();
}

gridScheduleOnclick = function(selectedEventId, eventValue) {
	// Do nothing for now
	// document.getElementById(selectedEventId).value=eventValue; 
	// document.getElementById(selectedEventId).form.submit();
}

getNextSibling = function(startBrother) {
	endBrother=startBrother.nextSibling;

	while(endBrother && endBrother.nodeType!=1) {
		endBrother=endBrother.nextSibling;
	}
	return endBrother;
}

getPreviousSibling = function(startBrother) {
	endBrother=startBrother.previousSibling;
	while(endBrother && endBrother.nodeType!=1) {
		endBrother=endBrother.previousSibling;
	}
	return endBrother;
}

updateMealFraction = function(id, primaryClass, secondaryClass, fractionClass, totalClass, hiddenClass) {

	var node = document.getElementById(id);
	var fracVal = node.value;
	
	var sibNode = null;
	var isPrimary = null;
	var noFraction = null;

	if (node.parentNode.parentNode.className.indexOf(primaryClass) >= 0) {

		sibNode = getNextSibling(node.parentNode.parentNode);

		if (!sibNode || !sibNode.className || !(sibNode.className.indexOf(secondaryClass) >= 0)) {
			return;
		}
		
		noFraction = (Math.floor(node.value)==1);
		isPrimary=true;

	} else if (node.parentNode.parentNode.className.indexOf(secondaryClass) >= 0) {

		sibNode = getPreviousSibling(node.parentNode.parentNode);
		
		if (!sibNode || !sibNode.className || !(sibNode.className.indexOf(primaryClass) >= 0)) {
			return;
		}
		
		noFraction = (node.value==0);
		isPrimary=false;
	} else {
		return;
	}
	
	node = node.parentNode.parentNode;
	
	for (x=0; x < sibNode.childNodes.length; x++)
	{		
		var sibNodeData = sibNode.childNodes[x];
		var nodeData = (isPrimary) ? null : node.childNodes[x];
		
		for (x2=0; x2 < sibNodeData.childNodes.length; x2++) {
			
			var sibChild = sibNodeData.childNodes[x2];
			
			if (sibChild.nodeType==1) {
			
				if (sibChild.className==fractionClass) {
					
					for (f=0; f < sibChild.childNodes.length; f++) {
				
						var frac = sibChild.childNodes[f];
							
						if (frac.nodeType==1) {
								
							if (Math.abs((1 - fracVal) - (+frac.value)) < 0.001 ) {
								sibChild.value = frac.value;							
								break;
							}
						}
					}
					
				}
				
				if (noFraction) {
					if (isPrimary) {					
						sibChild.disabled=true;		
						if (sibChild.className==totalClass) {
							sibChild.className += " " + hiddenClass;
						}							
					} else {
													
						if (x2 < nodeData.childNodes.length) {											
							var nodeChild = nodeData.childNodes[x2];	
		
							if (nodeChild.type=='select-one' || nodeChild.type=='text') {
								nodeChild.disabled=true;
								if (nodeChild.type=='select-one') {
									nodeChild.value='0';
								}
							}
							
							if (nodeChild.className==totalClass ) {
								nodeChild.className += " " + hiddenClass;
							}							
						}
					
					}
				} else {
						
					if (isPrimary) {
						sibChild.removeAttribute("disabled");
						
						if (sibChild.className.indexOf(totalClass) >= 0 ) {
							sibChild.className = sibChild.className.replace(" " + hiddenClass, "");								
						}
					}
									
				}
		
			} else if (sibChild.parentNode.className) {
					
				var textNode = (isPrimary) ? sibChild.parentNode : nodeData;
				
				if (noFraction) {
					textNode.className += " " + hiddenClass;
				} else {
					textNode.className = sibChild.parentNode.className.replace(" " + hiddenClass, "");
				}
			}
			
		}
			
	}

}

updateMealComponent = function(id, analysis) {
	updateMealFraction(id, 'mc-primary', 'mc-secondary', 'mc-fraction', 'mc-total', 'hidden');
	var prefix = id.substring(0, 20);
	var primaryId = $(prefix + "0-mc-fraction");
	var secondaryId = $(prefix + "1-mc-fraction");
	if (primaryId) {
		maxCore.executeMenuQtyUpdateBehavior(prefix + "0-mc-fraction", analysis);
	}

	if (secondaryId) {
		maxCore.executeMenuQtyUpdateBehavior(prefix + "1-mc-fraction", analysis);
	}
}

markAttendance = function(id) {
	
	var mark = document.getElementById(id.substring(0, id.lastIndexOf('-') + 1) + "mark");
	
	var found = false;
	cellNode = mark.parentNode;
	cellNode = getPreviousSibling(cellNode);
	
	var childIndex = 0;
	
	if (cellNode.childNodes[0].nodeType == 3) {
		childIndex = 1;
	}
	
	while(cellNode.childNodes[childIndex].id.indexOf('meal') > 0) {
		
		if (cellNode.childNodes[childIndex].checked == true) {
			found=true;
			break;
		}
		
		cellNode = getPreviousSibling(cellNode);
		if (!cellNode.childNodes[childIndex])
			break; 	
	}
	
	if (found & !mark.checked) {
		mark.checked = true;
	}

}



   







