var offerController = {
	populatedQuantiyFields : {},
	populatedQuantiyFieldsSize : 0,
    initialState : null,
    mainForm : null,
    
    onVariationPageLoad : function() {
        this.mainForm = $('#addItemMainFormFloating');
        this.onPageLoad();        

        this.initialState = $.extend({}, offerListingDisplayInfo);
        $("thead > tr .columnFilterSelect", this.mainForm).each(function() {
            offerController.initialState[$(this).attr("name")] = this.options[this.selectedIndex].value;
        });
        var inStock = $("thead > tr #showInStockOnly", this.mainForm)[0];
        this.initialState[inStock.name] = inStock.checked;
        
        if(!this.restoreFromHash(window.location.hash)) {
            this.mainForm.get(0).reset();
        }
        
        $(window).bind("beforeunload", this.onPageUnload);
    },

	onPageLoad : function() {
	    if (!this.mainForm) {
	        this.mainForm = $('#addItemMainFormFloating');
	    }
	    this.mainForm.submit(function() {
	        offerController.handleSubmit();
	    });
	    
	    this.mainForm.delegate("tbody > tr", "click", function() {
	       $(this).find('.inputQty').focus().addClass('modInput').select();
	    });
	    this.mainForm.delegate(".wishListContinueBtn", "click", function() {
	       if (offerController.hasPopulatedQuantityInput()) {
	         var mainForm = $("#addItemMainFormFloating")[0];
	         var action = mainForm.action;
	         action = action.replace("/cart?", "/wishlist?");
	         mainForm.action = action;
	         return true;
	       } else {
	         return false;
	       }
	    });
	    this.mainForm.delegate(".cartBtn", "mouseenter", function(e) {
	       if (!offerController.hasPopulatedQuantityInput()) {
	           toolTipManager.showTooltip("invalidQuantity", $(e.target));    
	       }
	    });
	    this.mainForm.delegate(".cartBtn", "mouseleave", function(e) {
	        toolTipManager.hideTooltip();    
	    });
	    this.mainForm.delegate(".cartBtn", "click", function(e) {
	       return offerController.hasPopulatedQuantityInput();
	    });
	    this.mainForm.delegate(".inputQty", "keyup", function(e) {
	        offerController.handleQuantityInputValueChanged($(e.target));
	     });
	},

	onPageUnload : function() {
		if (offerListingDisplayInfo.lastAjaxHash.length > 0) {
            var historyAwareLoc = window.location.toString();
            if (historyAwareLoc.indexOf("#") > 0) {
                historyAwareLoc = historyAwareLoc.substring(0, historyAwareLoc.indexOf("#"));
            }
            window.location.replace(historyAwareLoc + "#" + offerListingDisplayInfo.lastAjaxHash);
        }
	},
	
	handleQuantityInputValueChanged : function (input) {
	    var usrInput = $.trim(input.val());
	    var inputName = $(input).attr("name");
	    if (usrInput.length > 0) {
	        if (!this.populatedQuantiyFields[inputName]) {
	            this.populatedQuantiyFieldsSize++;
	        }
	        this.populatedQuantiyFields[inputName] = usrInput;
	        toolTipManager.hideTooltip();
	    } else {
	        if (this.populatedQuantiyFields[inputName]) {
	            this.populatedQuantiyFields[inputName] = null;
	            this.populatedQuantiyFieldsSize--;
	        }
	    }
	},
	
	hasPopulatedQuantityInput : function() {
	    return this.populatedQuantiyFieldsSize > 0;
	},

    refreshVariation : function(paramMap) {
		if (!paramMap) {
	        paramMap = {};
	    }
	    
        $("thead > tr .columnFilterSelect", this.mainForm).each(function() {
              paramMap[this.name] = $(this).val();
        });
        //filter by "in stock"
        var inStock = $("thead > tr #showInStockOnly", this.mainForm)[0];
        if (inStock.checked) {
              paramMap[inStock.name] = $(inStock).val();
        }

	    this.loadVariationTable(offerListingDisplayInfo.enableAjaxForVariation, paramMap);
	},

	loadVariationTable : function (viaAjax, paramMap) {
	    if (viaAjax) {
	        var hashForBrowserHistory = "";
	        for (var key in paramMap) {
	           if (paramMap[key]) {
	               if (hashForBrowserHistory.length > 0) {
	            	   hashForBrowserHistory += "&";
	               }
	               hashForBrowserHistory = hashForBrowserHistory + key + "=" + encodeURIComponent(paramMap[key]);  
	           }
	        } 
	       $.ajax({
	           url : "/gajax",
	           timeout : 30000,
	           data: paramMap,
	           beforeSend : function(xhr) {
	               var img = $("#ajaxInProgress");
	               var table = $("table#tblVariations", offerController.mainForm);
	               var offset = table.position();
	               var yOffset = 105;
	               if (table.height() > 300) {
	                   yOffset = 150;
	               }
	               
	               var top = offset.top + yOffset;
	               var left = (offset.left + (table.width()/2) - 20 );
	               img.css("top", top+"px").css("left", left+"px");
	               img.show();
	           },
	           success : function(data, textStatus) {
	               if (data) { 
	                $("div#offeringAjaxWrapper", offerController.mainForm).html(data);
	                offerListingDisplayInfo.lastAjaxHash = hashForBrowserHistory;
	               } else {
	                this.error();
	               }
	           },
	           error : function (xhr, textStatus, errorThrown) {
	               $("div#offeringAjaxWrapper", offerController.mainForm).html("");
	               $("#ajaxError").show();
	           },
	           complete : function (xhr, textStatus) {
	               $("#ajaxInProgress").hide();
	               offerListingDisplayInfo.performedShowFewerViaJS = false;
	               if (textStatus == "success") {
	                    registerRegistryEvents.call();
	               }
	           }
	       });
	    } else {
	        var urlParams = jQuery.param(paramMap);
	        var currentUrl = offerListingDisplayInfo.currentUrl;
	        window.location.href = currentUrl + (currentUrl.indexOf("?") > 0 ? "&" : "?") + urlParams;
	    }
	},

	handleFilterChanged : function(filterElement) {
		offerListingDisplayInfo.limitRows = false;
	    var params = offerListingDisplayInfo.getParamAsMap();
	    params["ref_"] = "sp_dp_fltr_" + filterElement.name.substring(filterElement.name.indexOf(".") + 1);
	    this.refreshVariation(params);
	},

	clearAllFilterValues : function () {
	    $("thead > tr .columnFilterSelect", this.mainForm).each(function() {
	        $(this).val("");
	    });
	    $("#showInStockOnly")[0].checked = false;
	    offerListingDisplayInfo.limitRows = false;
	    var params = offerListingDisplayInfo.getParamAsMap();
	    params["ref_"] = "sp_dp_showall";
	    this.refreshVariation(params);
	    return false;
	},

	clearFilterValue : function(id) {
	    offerListingDisplayInfo.limitRows = false;
	    $(id).val("");
	    $(id).change();
	    return false;
	},
	
	sortVariations : function (sortBy, sortDirection) {
	    offerListingDisplayInfo.sortBy = sortBy;
	    offerListingDisplayInfo.sortDirection = sortDirection;
	    var map = offerListingDisplayInfo.getParamAsMap();
	    map["ref_"] = offerListingDisplayInfo["ref_"] == null ? "sp_dp_sort_" + sortBy : offerListingDisplayInfo["ref_"];
	    this.refreshVariation(map);
	},

	showFewerVariations : function () {
	    var allChildren = $("#tblVariations > tbody > tr");
	    for (var i=offerListingDisplayInfo.limitRowsTo; i < allChildren.length; i++) {
	        allChildren[i].style.display = "none";
	    } 
	    
	    $("#tblVariations a.showFewerJS").each(
	            function() {$(this).hide()}
	        );
	    $("#tblVariations a.showAllJS").each(
	        function() {$(this).show()}
	    );
	    $("#tblVariations .showing").each(
	        function() {
	            offerListingDisplayInfo.currentlyShowingAll = $(this).html();
	            $(this).html(offerListingDisplayInfo.currentlyShowingFewer);
	        }
	    );
	    offerListingDisplayInfo.performedShowFewerViaJS = true;
	},

	showAll : function() {
	    if (offerListingDisplayInfo.performedShowFewerViaJS) {
	        var allChildren = $("tbody > tr", this.mainForm);
	        var displayStyle = allChildren[0].style.display; 
	        for (var i=offerListingDisplayInfo.limitRowsTo; i < allChildren.length; i++) {
	            allChildren[i].style.display = displayStyle;
	        }
	        
	        $("#tblVariations a.showAllJS", this.mainForm).each(
	            function() {$(this).hide()}
	        );
	        $(" a.showFewerJS", this.mainForm).each(
	                function() {$(this).show()}
	         );
	        $(" .showing", this.mainForm).each(
	            function (){$(this).html(offerListingDisplayInfo.currentlyShowingAll);}
	        );
	        offerListingDisplayInfo.performedShowFewerViaJS = false;
	    } else {
	        this.clearAllFilterValues();
	    }
	},

	recoverFromAjaxError : function() {
	    offerListingDisplayInfo.enableAjaxForVariation=false;
	    var urlParams = jQuery.param(offerListingDisplayInfo.getParamAsMap());
	    var currentUrl = offerListingDisplayInfo.currentUrl;
	    window.location.href = currentUrl + (currentUrl.indexOf("?") > 0 ? "&" : "?") + urlParams;
	},

	handleSubmit : function(event){
	    if (!this.hasPopulatedQuantityInput()) {
	        return false;
	    }
	    
		var registryIdSelected = $("input[@name=registryId]:checked").val();
	    var newList = registryIdSelected == "new_list";
	
	    if (newList && jQuery.trim(($("#new_wishlist_name").val())).length == 0) {
	        $("#errorMessage").html("Please specify a name for the new list.");
	        $("#importantMessageBox").show();
	        return false;
	    }
	
	    var indexMatcher =/item\.(\d+)\.qty/;
	     $("form#addItemMainFormFloating input[name^='item'][name$='qty']:text").each(
	            function(index) {
	                var input = $(this);
	                if (!input.val()) {
	                    var i = indexMatcher.exec(input.attr("name"))[1];
	                    $("input#itemNumToAdd_"+i + ":checkbox").attr("checked", false);
	                }
	            }
	    );
	
	    return true;
	},

    restoreFromHash : function(hash) {
	    var paramsFromHash = this.parseHash(hash);
	    if (paramsFromHash["mn_pid"] && this.hasStateChanged(paramsFromHash)) {
	        for (paramName in paramsFromHash) {
			    if (typeof(offerListingDisplayInfo[paramName]) != "undefined") {
		            offerListingDisplayInfo[paramName] = paramsFromHash[paramName];
			    }
	        }
            this.loadVariationTable(true, paramsFromHash);
            return true;
        }
	    return false;
	},
	
	parseHash : function (hash) {
	    if (hash.indexOf("#") == 0) {
	        hash = hash.substring(1);
	    }
	    var params = hash.split('&');
	    var newParams = {};
	    for (var i = 0; i < params.length; i++) {
	        var splitPoint = params[i].indexOf("="); 
	        if (splitPoint > 0 && (params[i].length > (splitPoint+1))) {
	           var name = params[i].substring(0, splitPoint);
	           var value = decodeURIComponent(params[i].substring(splitPoint + 1));
	           newParams[name] = value;
	        }
	     }

	    return newParams;
	},

	hasStateChanged : function (newState) {
		var originalState = this.initialState;

		if (originalState["sortBy"] != newState["sortBy"] || originalState["sortDirection"] != newState["sortDirection"]) {
		    return true;
		}
		
		var result = false;
		$("thead > tr .columnFilterSelect", this.mainForm).each(function() {
			var filterName = $(this).attr("name");
			var originallySelected = typeof(originalState[filterName]) == "undefined" ? "" : originalState[filterName].toString();
			var newlySelected = typeof(newState[filterName]) == "undefined" ? "" : newState[filterName].toString();
			
            result = result || (originallySelected != newlySelected);
        });

	    result = result || (originalState["showInStockOnly"] && !newState["showInStockOnly"]) || (!originalState["showInStockOnly"] && newState["showInStockOnly"]);
        return result;
	}
}
