﻿var Step1Controller = (function() {
	function fnStep1ControllerConstructor(oNewModel, oNewView, oNewEventDispatcher) {
		/****************************************************/
		/*                                                  */
		/*                                                  */
		/*                 Private Variables                */
		/*                                                  */
		/*                                                  */
		/****************************************************/
		
		var hCalculators = $H();
		var oModal;
		
		var oModel;
		var oView;
		var oValidator;
		var oViewHelper;
		var oEventDispatcher;
		
		var bLicenseFinderModification = false;
		var oLicenseFinderRow;
		
		/****************************************************/
		/*                                                  */
		/*                                                  */
		/*                  Event Handlers                  */
		/*                                                  */
		/*                                                  */
		/****************************************************/

		function window_onUnLoad(event) {
			var aCalculators = hCalculators.values();
			var oCalculator;
			for (var iCalculator = 0; iCalculator < aCalculators.length; iCalculator++) {
				oCalculator = aCalculators[iCalculator];
				if (!oCalculator.closed) {
					oCalculator.close();
				}
			}
		}
		
		function oCalculator_onGetProductCategory(oEvent) {
		    hCalculators.each(function(oPair) {
		        if (oPair.value == oEvent.dialog) {
		            switch (oPair.key) {
		                case "Network Performance Monitor (NPM)":
		                    oPair.value.setProductCategory(1);
                            break;
		                case "Network Configuration Manager (NCM)":
		                    oPair.value.setProductCategory(2);
		                    break;
		            }
		            throw $break;
		        }
		    });
		}
		
		function oCalculator_onAddToQuote(oEvent) {
		    hCalculators.each(function(oPair) {
		        if (oPair.value == oEvent.dialog) {
		            var sProductCategory;
		            switch (oPair.key) {
		                case "Network Performance Monitor (NPM)":
		                    sProductCategory = "ORION NPM LICENSES";
		                    break;
		                case "Network Configuration Manager (NCM)":
		                    sProductCategory = "ORION NCM";
		                    break;
		            }
		            if (oLicenseFinderRow.up("ul")) {
		                bLicenseFinderModification = true;
		                oModel.modifyLicenseItemAt(sProductCategory, oLicenseFinderRow.previousSiblings().length, oEvent.product, oEvent.quantity);
		            }
		            else
                        oModel.addLicenseItem(sProductCategory, new LicenseItem(oEvent.product, oEvent.quantity));
		            throw $break;
		        }
		    });
		}

		function accProductGroups_onClick(event) {
			var oElement = Event.element(event);
			if (oElement.match(".Title") || oElement.up(0).match(".Title")) {
				oViewHelper.toggleAccordionItemDisplay(oElement);
			}
			else if (oElement.match("img[alt='License Calculator']")) {
				openCalculator(oElement.up("ul.Accordion > li").firstDescendant().innerHTML, oElement.up("li"));
			}
			else if (oElement.match("ul.ProductList > li > a")) {
				oModel.removeLicenseItemAt(oElement.up("ul.ProductList").previous("h5").firstDescendant().innerHTML, oElement.up("li").previousSiblings().length);
			}
			else if (oElement.match("a") && oElement.name == "addAnother") {
				detachListItemEvents();
				oModel.addLicenseItem(oElement.up("span.AddAnother").previous("h5").firstDescendant().innerHTML, new LicenseItem());
				attachListItemEvents();
			}
		}
		
		function accProductGroups_onKeyDown(event) {
		    var oElement = Event.element(event);
			if (oElement.match("input[name='Quantity']")) {
				var oEvent;
				var iKeyCode;
				if (window.event) {
					oEvent = window.event;
					iKeyCode = window.event.keyCode;
				}
				else {
					oEvent = event;
					iKeyCode = event.which;
				}
				var bNumber = (iKeyCode > 47 && iKeyCode < 58) || (iKeyCode > 95 && iKeyCode < 106);
				var bArrow = (iKeyCode > 36 && iKeyCode < 41);
				var bDelete = (iKeyCode == 8 || iKeyCode == 46);
				if (event.shiftKey || !(bNumber || bArrow || bDelete))
					Event.stop(event);
			}
		}

		function accProductGroups_onKeyUp(event) {
		    var oElement = Event.element(event);
			if (oElement.match("input"))
				oModel.modifyLicenseItemAt(oElement.up("ul.ProductList").previous("h5").firstDescendant().innerHTML, oElement.up("li").previousSiblings().length, oElement.previous("select").value, oElement.value);
		}

		function accProductGroups_onMouseOver(event) {
			var oElement = Event.element(event);
			var oParentPositioning, oScrollOffsets, iLeft, iTop;
			if (oElement.match("select[name='LicenseType'] + a")) {
				oViewHelper.showLicenseRequirement();
			}
			else if (oElement.match("img[alt='Special Offer']")) {
			    oViewHelper.showSpecialOffers(oModel.getNetSuiteItemArray(), oModel.getPromotions(), oModel.getRegionByName(oModel.getRegion()), oElement.previous().firstDescendant().innerHTML, Event.pointerX(event), Event.pointerY(event));
			}
		}

		function accProductGroups_onMouseOut(event) {
			var oElement = Event.element(event);
			if (oElement.match("select[name='LicenseType'] + a")) {
				oViewHelper.hideLicenseRequirement();
			}
			else if (oElement.match("img[alt='Special Offer']")) {
				oViewHelper.hideSpecialOffers();
			}
		}

		function btnStep1Continue_onClick(event) {
		    if (oValidator.isValid()) {
		        oEventDispatcher.dispatchEvent("Continue", {step: 1});
		    }
		    else {
		        oEventDispatcher.dispatchEvent("Clear Error Modal Header", null);
		        if (oValidator.isLicenseItemSelected()) {
		            var hErrorList = oValidator.getAllErrors();
		            oEventDispatcher.dispatchEvent("Set Error Modal List", {errors: hErrorList});
		            oEventDispatcher.dispatchEvent("Show Error Modal", null);
		            oViewHelper.showErrorMessages(hErrorList);
		        }
		        else {
		            oEventDispatcher.dispatchEvent("Clear Error Modal List", null);
		            oEventDispatcher.dispatchEvent("Add Error To List", {error: "No Products Selected"});
		            oEventDispatcher.dispatchEvent("Show Error Modal", null);
		            oViewHelper.enableErrorMessages();
		        }
		    }
		}
		
		function grpStep1ContentHeader_onClick(event) {
			var oElement = Event.element(event);
			if (oElement.match("a#lnkExpandAll")) {
				oViewHelper.expandAllAccordionItems();
			}
			else if (oElement.match("a#lnkCollapseAll")) {
				oViewHelper.collapseAllAccordionItems();
			}
		}
		
		function lstLicenseType_onChange(event) {
		    var oElement = Event.element(event);
		    oModel.modifyLicenseItemAt(oElement.up("ul.ProductList").previous("h5").firstDescendant().innerHTML, oElement.up("li").previousSiblings().length, oElement.value, oElement.next("input").value);
		}
		
		function region_onChange(oEvent) {
		    oModel.setRegion(oEvent.name);
		}
		
		/****************************************************/
		/*                                                  */
		/*                                                  */
		/*            Class Level Private Methods           */
		/*                                                  */
		/*                                                  */
		/****************************************************/

		function attachEventListeners() {
		    oEventDispatcher.attachEventListener("Get Product Category", oCalculator_onGetProductCategory);
		    oEventDispatcher.attachEventListener("Region Changed", region_onChange);
			oEventDispatcher.attachEventListener("AddToQuote", oCalculator_onAddToQuote);
			oEventDispatcher.attachEventListener("CloseLicenseFinder", closeCalculator);
		}
		
		function attachEvents() {
			Event.observe(window, "unload", window_onUnLoad);
			Event.observe($("accProductGroups"), "click", accProductGroups_onClick);
			Event.observe($("accProductGroups"), "keydown", accProductGroups_onKeyDown);
			Event.observe($("accProductGroups"), "keyup", accProductGroups_onKeyUp);
			Event.observe($("accProductGroups"), "mouseover", accProductGroups_onMouseOver);
			Event.observe($("accProductGroups"), "mouseout", accProductGroups_onMouseOut);
			Event.observe($("btnStep1Continue"), "click", btnStep1Continue_onClick);
			Event.observe($("grpStep1ContentHeader"), "click", grpStep1ContentHeader_onClick);
			attachListItemEvents();
		}
		
		function attachListItemEvents() {
			attachLicenseTypeListBoxEvents();
		}
		
		function attachLicenseTypeListBoxEvents() {
			var aLicenseTypeListBoxes = $$("select[name='LicenseType']");
			for (var iLicenseTypeListBox = 0; iLicenseTypeListBox < aLicenseTypeListBoxes.length; iLicenseTypeListBox++)
			{
				Event.observe(aLicenseTypeListBoxes[iLicenseTypeListBox], "change", lstLicenseType_onChange);
				if (aLicenseTypeListBoxes[iLicenseTypeListBox].attachEvent)
				    aLicenseTypeListBoxes[iLicenseTypeListBox].attachEvent("onchange", lstLicenseType_onChange);
			}
				
		}

		function closeCalculator(oEvent) {
			var aKeys = hCalculators.keys();
			var sKey;
			var oCalculator;
			for (var iKey = 0; iKey < aKeys.length; iKey++) {
				sKey = aKeys[iKey];
				oCalculator = hCalculators.get(sKey);
				if (oCalculator == oEvent.dialog) {
					hCalculators.unset(sKey);
					break;
				}
			}
		}
		
		function detachListItemEvents() {
			detachLicenseTypeListBoxEvents();
		}
		
		function detachLicenseTypeListBoxEvents() {
			var aLicenseTypeListBoxes = $$("select[name='LicenseType']");
			for (var iLicenseTypeListBox = 0; iLicenseTypeListBox < aLicenseTypeListBoxes.length; iLicenseTypeListBox++)
			{
				Event.stopObserving(aLicenseTypeListBoxes[iLicenseTypeListBox], "change", lstLicenseType_onChange);
			}
		}
		
		function openCalculator(sProductCategory, oSelectedRow) {
			var oCalculator = hCalculators.get(sProductCategory);
			if (oCalculator && !oCalculator.closed)
				oCalculator.focus();
			else {
				/*switch (sProductCategory) {
					case "Network Performance Monitor (NPM)":
						oCalculator = window.open("controls/calculator/orionnpmcalculator.htm", "_blank", "height=476, width=264");
						break;
					case "Network Configuration Manager (NCM)":
						oCalculator = window.open("controls/calculator/orionncmcalculator.htm", "_blank", "height=580, width=264");
						break;
					default:
						oCalculator = window.open("controls/calculator/ipmonitorcalculator.htm", "_blank", "height=450, width=264");
				}*/
				oLicenseFinderRow = oSelectedRow;
				oCalculator = window.open("controls/calculator/calculator.htm", "_blank", "height=476, width=264");
				hCalculators.set(sProductCategory, oCalculator);
			}
		}
		
		/****************************************************/
		/*                                                  */
		/*                                                  */
		/*                Accessors/Mutators                */
		/*                                                  */
		/*                                                  */
		/****************************************************/
		
		this.setEventDispatcher = function(oNewEventDispatcher) {
			if (oNewEventDispatcher)
				oEventDispatcher = oNewEventDispatcher;
		}
		
		this.setModel = function(oNewModel) {
			if (oNewModel) {
				oModel = oNewModel;
				oModel.addObserver(this);
			}
		}
		
		this.setView = function(oNewView) {
			if (oNewView)
				oView = oNewView;
		}
		
		/****************************************************/
		/*                                                  */
		/*                                                  */
		/*                Observer Interface                */
		/*                                                  */
		/*                                                  */
		/****************************************************/
		
		this.update = function(oArguments) {
		    var sProductCategory = oArguments.category;
			var iIndex = oArguments.index;
			switch (oArguments.event) {
				case "License Item Added":
				    oViewHelper.addLicenseItem(sProductCategory, oModel.getLicenseItemsByProductCategory(sProductCategory)[iIndex]);
				    break;
				case "License Item Modified":
				    oViewHelper.modifyLicenseItemAt(sProductCategory, oModel.getLicenseItemsByProductCategory(sProductCategory)[iIndex], iIndex, bLicenseFinderModification);
				    bLicenseFinderModification = false;
				    break;
				case "License Item Removed":
				    oViewHelper.removeLicenseItemAt(sProductCategory, oModel.getLicenseItemsByProductCategory(sProductCategory), iIndex);
					break;
			    case "Region Changed":
			        oViewHelper.setSalesPhoneNumber(oModel.getSubsidiaries(), oModel.getRegionByName(oModel.getRegion()));
			        oViewHelper.changeLicenseItemDisplays(oModel.getNetSuiteItemArray(), oModel.getPromotions(), oModel.getRegionByName(oModel.getRegion()));
			        var rRegion = oModel.getRegion();
			        oViewHelper.changecontactlinks(rRegion);
			        oViewHelper.updateCurrentCurrencyAndSubsidiary(oModel.getCurrentSubsidiaryAndCurrencyByRegion(rRegion));
			        break;
			}
			oValidator.validateProductCategoryByName(sProductCategory);
			oViewHelper.updateErrorMessages(oValidator.getAllErrors());
		}
		
		/****************************************************/
		/*                                                  */
		/*                                                  */
		/*                 Initialize Class                 */
		/*                                                  */
		/*                                                  */
		/****************************************************/
		
		this.setModel(oNewModel);
		this.setView(oNewView);
		this.setEventDispatcher(oNewEventDispatcher);
		if (oModel && oView && oEventDispatcher) {
		    oValidator = new LicenseItemModelPropertyValidator(oModel);
			oViewHelper = new Step1ViewHelper(oView);
			attachEventListeners();
			attachEvents();
	        var rRegion = oModel.getRegion();
	        oViewHelper.changecontactlinks(rRegion);
			oViewHelper.updateCurrentCurrencyAndSubsidiary(oModel.getCurrentSubsidiaryAndCurrencyByRegion(rRegion));
		}
		
	}
	
	return fnStep1ControllerConstructor;
})();