(function($) {
    var options = {
        priceSelector: '#sellPrice-',
		dialog: {
			constructorHtml: '<div id="bulkPricePopup"></div>',
            selector: '#bulkPricePopup',
	        options: {
		        title: 'Discount Pricing Tiers',
		        autoOpen: false,
		        modal: true,
		        width: 775,
		        minHeight: 300,
		        height: 'auto',
		        buttons: {
		            'Done': function() {
		                $(this).dialog('close');
		            }
		        }
			},
			templateUrl: '/content/make/inc/product-pricing-popup.html',
			css: {
				'display': 'none',
	            'text-align': 'left'
			},
			headerTextSelector: '#bulkPricingProductName'
		},
		data: {
			rootUrl: '/content/make/js/bulk-pricing',
			availableProductsFile: '/bulk-pricing-available-products.js',
			productDetailsJsonFilePattern: '/bulk-pricing-product-type-'
		},
		displayTable: {
			selector: '#bulkPricingDiscountTiers',
			attributes: {
                'id': 'bulkPricingDiscountTiers',
                'border': '0',
                'cellspacing': '1',
                'cellpadding': '0',
				'align': 'center'
			},
			labelClass: 'rowLabel',
			firstRowLabel: 'Items',
			secondRowLabel: 'Price',
			firstColumnClass: 'columnA',
			secondColumnClass: 'columnB'
        },
		buttonAttributes: {
			'src': '/content/make/img/view-bulk-pricing.gif',
			'width': 82,
			'height': 10,
			'alt': 'View Bulk Pricing',
			'border': 0
		},
		buttonAnchorAttributes: {
			'href': '#',
			'title': ''
		},
        isDebugOn: false,
        jqueryUiUrl: '/content/make/js/jquery/jqueryui/1.8.2/jquery-ui.min.js'
    };
    
    // Main function, initialize and set behaviors here
    $.fn.bulkPricingDialog = function(callerOptions) {
        options = $.extend(options, callerOptions || {});
		var $elements = this;
        
        if (options.isDebugOn) {
            console.dir(options);
            console.log('jQuery Elements before loading jQuery UI');
            console.log($elements);
        }
		
		$.getScript(options.jqueryUiUrl, function() {
            $(options.dialog.constructorHtml).css(options.dialog.css).append('body').dialog(options.dialog.options).load(options.dialog.templateUrl);
            
			$.getJSON(options.data.rootUrl + options.data.availableProductsFile, function(data) {
                if (options.isDebugOn) {
                    console.log('jQuery Elements after loading jQuery UI, creating the dialog, and getting the available products JSON.');
                    console.log($elements);
                }
	            $elements.each(function(z) {
	                var $this = $(this);
					var productTypeNo = Number($this.attr('id').replace('merch-', ''));
                    
                    if (options.isDebugOn) {
                        console.log($this);
                        console.log('productTypeNo: ' + productTypeNo);
                        console.log('is in available products list: ' + ($.inArray(productTypeNo, data) > (-1)));
                    }
					
					if ($.inArray(productTypeNo, data) > (-1)) {
		                $this.append('| ').append(
		                    $('<a></a>').attr(options.buttonAnchorAttributes).click(function() { generateBulkPriceBehavior($this); return false; })
								.html('See Bulk Pricing &raquo;')
		                );
					} // END: if ($.inArray(productTypeNo, data) > (-1))
	            }); // END: $(options.productPriceSelector).each(function(z)
			}); // END: $.getJSON(options.bulkPricing.availableProductsJsonUrl, function(data)
        }); // END: $.getScript(options.jqueryUiUrl, function()
    };
    
	var generateBulkPriceBehavior = function($element) {
        var $dialog = $('#bulkPricePopup');
        var productTypeNo = Number($element.attr('id').replace('merch-', ''));
                  
        $.getJSON(options.data.rootUrl + options.data.productDetailsJsonFilePattern + productTypeNo + '.js?20110623', function(data) {
            var $bulkPricingTable = $('<table></table>');
            $bulkPricingTable.attr(options.displayTable.attributes);
			
			var $qtyRow = $('<tr></tr>');
			$('<td></td>').addClass(options.displayTable.labelClass).html(options.displayTable.firstRowLabel).appendTo($qtyRow);
			
			var $priceRow = $('<tr></tr>');
			$('<td></td>').addClass(options.displayTable.labelClass).html(options.displayTable.secondRowLabel).appendTo($priceRow);
            
            $(data).each(function(z) {
                var columnClassName = options.displayTable.secondColumnClass;
                
                if (z%2) {
                    columnClassName = options.displayTable.firstColumnClass;
                }
                
                if (z == 0) {
					if (this.tierQuantity > 1)
					{
						$('<td></td>').addClass(options.displayTable.firstColumnClass).html('1-' + (this.tierQuantity-1)).appendTo($qtyRow);
						$('<td></td>').addClass(options.displayTable.firstColumnClass).html($(options.priceSelector + productTypeNo).html()).appendTo($priceRow);
						columnClassName = options.displayTable.secondColumnClass;
					}
                }
                
                $('<td></td>').addClass(columnClassName).html(this.tierQuantityRange).appendTo($qtyRow);
				$('<td></td>').addClass(columnClassName).html('$' + (this.tierPrice.toFixed(2))).appendTo($priceRow);
            });
			
			$bulkPricingTable.append($qtyRow).append($priceRow);
            
            $dialog.find(options.dialog.headerTextSelector).html(data[0].productName);
            $dialog.find(options.displayTable.selector).replaceWith($bulkPricingTable);
            $dialog.dialog('open');
        });
    }
})(jQuery);

