var raq_product_modal_q = '#raq-product-modal';
var quote_id_q = '#quote-id';
var quote_item_to_edit_q = '.quote-item-to-edit';
/*********************************************************************************************************************
 * Request A Quote Controller:
 * 		Used to control page loading, hiding/showing of content, content/page navigation, and data submission.
 *
 *
 *********************************************************************************************************************/
var RAQProductController = function(){

	//common query variables
	var raq_product_main_content_q = '.raq-product-main-content';
	var raq_product_main_nav_q = '.raq-product-main-nav';
	var raq_product_main_footer_q = '.raq-product-main-footer';
	var raq_control_item_q = '.raq-control-item';
	var raq_controls_q = '.raq-controls';
	var required_acc_items_q = '.required-acc-items';
	var required_accessory_input_q = '.required-accessory-input';
	var optional_acc_items_q = '.optional-acc-items';
	var raq_select_product_label_q = '.raq-select-product-label';

	var edit_q = '.edit';
	var previous_q = '.previous';
	var next_q = '.next';
	var save_q = '.save';

	var raq_url_to_load_q = '.raq-url-to-load';
	var nav_item_q = '.nav-item';
	var default_nav_item_q = '.default-nav-item';
	var target_for_load_q = '.target-for-load';
	var targeted_content_q = '.targeted-content';
	var nav_selected_q = '.nav-selected';

	var empty_content_q = '.empty-content';
	var options_content_q = '.options-content';
	var install_accs_content_q = '.install-accs-content';
	var accs_content_q = '.accs-content';

	var raq_product_mouseovers_q = '.raq-product-finish-item, .raq-product-trim-option-item';

	//common class variables
	var empty_content = 'empty-content';
	var options_content = 'options-content';
	var install_accs_content = 'install-accs-content';
	var accs_content = 'accs-content';
	var acc_install = 'acc-install';
	var acc_related = 'acc-related';
	var required_accessory_input = 'required-accessory-input';

	var nav_selected = 'nav-selected'; //basically the same as the commonly used 'active' class
	var default_nav_item = 'default-nav-item';

	return {
		//Note: init() gets called every time the dialog/modal is opened. Be sure to either use 'live' events
		//OR unbind then bind your events so that they are NOT registered more than once.
		init: function() {

			//Navigation tabs
			$(raq_product_main_nav_q + ' ' + nav_item_q).live('click', function(){
				RAQProductController.loadPageToTab($(this), RAQProductController.alternateNextButtonCheck);
				return false;
			});

			//Edit button
			$(raq_controls_q + ' ' + edit_q).live('click', function(){
				$(raq_product_modal_q).dialog('close');
				return false;
			});

			//Previous button
			$(raq_controls_q + ' ' + previous_q).live('click', function(e){
				var currentSelected = $(raq_product_main_nav_q + ' ' + nav_item_q + nav_selected_q);
				if (!$(raq_product_main_nav_q + ' ' + nav_item_q + ':first').hasClass(nav_selected)) {
					currentSelected.prev().click();
				}
				return false;
			});

			//Next button
			$(raq_controls_q + ' ' + next_q).live('click', function(e){
				var currentSelected = $(raq_product_main_nav_q + ' ' + nav_item_q + nav_selected_q);
				if (!$(raq_product_main_nav_q + ' ' + nav_item_q + ':last').hasClass(nav_selected)) {
					currentSelected.next().click();
				}
				return false;
			});

			//Save button
			$(raq_controls_q + ' ' + save_q).live('click', function(e){
				e.preventDefault();
				$(raq_product_main_footer_q).addClass('loading');


				var profileId = $('.profile-id-for-quote').val();
				var quoteId = $(quote_id_q).val();
				var quoteItemId = $(".quote-item-to-edit").val();
				var mainProductId = $(".productId").val();
				var mainSkuId = $('.currentSkuId').val();
				var mainPrice = 0;
				var discountPrice = 0;
				var discountAmount = 0;
				var instAccSkuIds = [];
				var instAccProdIds = [];
				var instAccPrices = [];
				var accSkuIds = [];
				var accProdIds = [];
				var accPrices = [];
				var knobHandleFinishId = $(".knobHandleFinishId").val();


				//add sku id, product id, and price of selected "installation accessories"
				$(raq_product_main_content_q).find(required_accessory_input_q + ":checked").each(function(i, item) {
					instAccSkuIds.push($(item).closest(".accessory-item").find(".sku-id-input").val());
					instAccProdIds.push($(item).closest(".accessory-item").find(".product-id-input").val());
					instAccPrices.push("0.0");
				});

				$(raq_product_main_content_q).find(".optional-accessory-input:checked").each(function(i, item) {
					instAccSkuIds.push($(item).closest(".accessory-item").find(".sku-id-input").val());
					instAccProdIds.push($(item).closest(".accessory-item").find(".product-id-input").val());
					instAccPrices.push("0.0");
				});

				//add sku id, product id, and price of selected "accessories"
				$(raq_product_main_content_q).find(".accessories-accessory-input:checked").each(function(i, item) {
					accSkuIds.push($(item).closest(".accessory-item").find(".sku-id-input").val());
					accProdIds.push($(item).closest(".accessory-item").find(".product-id-input").val());
					accPrices.push("0.0");
				});

				if (quoteItemId && quoteItemId.length > 0) {
					RaqDwrFormHandler.updateMainItemWithAccsToQuote(profileId, quoteId, quoteItemId, mainProductId, mainSkuId, mainPrice, discountPrice, discountAmount, instAccProdIds, instAccSkuIds, instAccPrices, accProdIds, accSkuIds, accPrices, knobHandleFinishId, function(data) {
						var jsonData = JSON.parse(data);
						if (!jsonData.error) {
							$(quote_id_q).val(jsonData.quoteId);
							$(quote_item_to_edit_q).val(jsonData.mainQuoteItemId);
						}
						$(raq_product_main_footer_q).removeClass('loading');
						$(raq_product_modal_q).dialog('close');
						window.location.href = $('.my-quote-redirect').val();
					});

				} else {
					//DWR call to SAVE this quote to the current profile
					RaqDwrFormHandler.addMainItemWithAccsToQuote(profileId, quoteId, mainProductId, mainSkuId, mainPrice, discountPrice, discountAmount, instAccProdIds, instAccSkuIds, instAccPrices, accProdIds, accSkuIds, accPrices, knobHandleFinishId, false, function(data) {
						var jsonData = JSON.parse(data);
						if (!jsonData.error) {
							$(quote_id_q).val(jsonData.quoteId);
							$(quote_item_to_edit_q).val(jsonData.mainQuoteItemId);
						}
						$(raq_product_main_footer_q).removeClass('loading');
						$(raq_product_modal_q).dialog('close');
						window.location.href = $('.my-quote-redirect').val();
					});
				}

				return false;
			});

			RAQProductController.loadDefault();
		},
		registerEvents: function(targetedContent) {
			//if no scene7 params are set to a hidden input locally, then use these scene7 params
			var defaultScene7Params = "?fmt=png-alpha&wid=120&hei=100&resmode=sharp2&op_usm=1,1,10,0";

			var sizeColorChange = function() {
				var select = $(this);
				var size = $.trim(select.closest('.accessory-item').find(".raq-product-size-selector option:selected").html());
            	var color = $.trim(select.closest('.accessory-item').find(".raq-product-color-selector option:selected").html());
            	var accProductId = select.closest('.accessory-item').find('.product-id-input').val();

            	if (select.closest('.accessory-item').find(".raq-product-size-selector").length < 1) {
            		SkuFinder.lookupSku(select.closest('.accessory-item').find(".raq-product-color-selector option:selected").val(), function(result) {
                		var instAccsScene7Params = (select.closest('.scene7-params').length > 0 && select.closest('.scene7-params').val().length > 0)
                											? $('input#raq-installation-accessories-scene-seven-params').val() : defaultScene7Params;
                		if (result[0]) {
                			select.closest('.accessory-item').find(".datagrid-image img").attr("src", result[0] + instAccsScene7Params);
                			select.closest('.accessory-item').find(".datagrid-image img").attr("alt", result[1]);
            			}
                		if (result[3]) {
                			select.closest('.accessory-item').find('.sku-id-input').val(result[3]);
            			}
            			if (result[5]) {
            				select.closest('.accessory-item').find('.model-number').html('[' + result[5] + ']');
            			}
                	});
            	} else {
	            	SkuFinder.lookupImageForSku(accProductId, '', '', '', '', '', '', '', '', '', size, color, function(result) {
	            		var instAccsScene7Params = (select.closest('.scene7-params').length > 0 && select.closest('.scene7-params').val().length > 0)
	            											? $('input#raq-installation-accessories-scene-seven-params').val() : defaultScene7Params;
	            		if (result[0]) {
	            			select.closest('.accessory-item').find(".datagrid-image img").attr("src", result[0] + instAccsScene7Params);
	            			select.closest('.accessory-item').find(".datagrid-image img").attr("alt", result[1]);
	        			}
	            		if (result[3]) {
	            			select.closest('.accessory-item').find('.sku-id-input').val(result[3]);
	        			}
	        			if (result[5]) {
	        				select.closest('.accessory-item').find('.model-number').html('[' + result[5] + ']');
	        			}
	            	});
            	}
			};
			var colorChange = function() {
				var color = $(this);
				color.closest('.accessory-item').find(".raq-product-color-selector option:selected").removeAttr("selected");
				color.closest('.accessory-item').find(".raq-product-color-selector option:[value="+color.ident()+"]").attr("selected", "selected");
    			var serverOption = color.closest('.accessory-item').find('.scene7-server-input').val();
				var productId = color.closest('.accessory-item').find('.product-id-input').val();
				var finishId = $(this).find("span").ident();

				if (serverOption == 'VikingRangeRender') {
					SkuFinder.lookupImageForSku(productId, finishId, '', '', '', '', '', '', '', '', '', '', function(result) {
						//console.log(result);
		            	var instAccsScene7Params = (color.closest('.scene7-params').length > 0 && color.closest('.scene7-params').val().length > 0)
		            											? $('input#raq-installation-accessories-scene-seven-params').val() : defaultScene7Params;
	            		if (result[0]) {
	            			color.closest('.accessory-item').find(".datagrid-image img").attr("src", result[0] + instAccsScene7Params + result[6]);
	            			color.closest('.accessory-item').find(".datagrid-image img").attr("alt", result[1]);
	        			}
	            		if (result[3]) {
	            			color.closest('.accessory-item').find('.sku-id-input').val(result[3]);
	        			}
	        			if (result[5]) {
	        				color.closest('.accessory-item').find('.model-number').html('[' + result[5] + ']');
	        			}
					});
					/*
					SkuFinder.lookupImageForSku(productId, finishId, trimOptionId, knobHandleFinishId, knobHandleFinishHex, gasTypeId, burnerConfigId, doorStyleId, doorHingeId, interiorConfigId, sizeOption, colorOption, function(result) {

					});
					*/
				} else {
					SkuFinder.lookupSku(color.ident(), function(result) {
	            		var instAccsScene7Params = (color.closest('.scene7-params').length > 0 && color.closest('.scene7-params').val().length > 0)
	            											? $('input#raq-installation-accessories-scene-seven-params').val() : defaultScene7Params;
	            		if (result[0]) {
	            			color.closest('.accessory-item').find(".datagrid-image img").attr("src", result[0] + instAccsScene7Params);
	            			color.closest('.accessory-item').find(".datagrid-image img").attr("alt", result[1]);
	        			}
	            		if (result[3]) {
	            			color.closest('.accessory-item').find('.sku-id-input').val(result[3]);
	        			}
	        			if (result[5]) {
	        				color.closest('.accessory-item').find('.model-number').html('[' + result[5] + ']');
	        			}
	            	});
				}

			};


			var options = {cls: 'jquery-radio-01', empty: '/consumer/images/empty.png'};
			targetedContent.find('.radio-01 input:checkbox, .radio-01 input:radio').checkbox(options).bind('check', RAQProductController.accessoryChecked).bind('uncheck', RAQProductController.accessoryChecked);

			targetedContent.find('select.raq-product-color-selector, select.raq-product-size-selector').change(sizeColorChange);
			targetedContent.find('.raq-product-finish-item').click(colorChange);


			/************************************************************************************
			 * If no required accessories selected, then select the first one from each group
			 ************************************************************************************/
			targetedContent.find(required_acc_items_q).each(function(){
				if ($(this).find(required_accessory_input_q + ':checked').length < 1 && $(this).find(required_accessory_input_q + ':first').length > 0) {
					$(this).find(required_accessory_input_q + ':first').click().siblings('.add-to-my-kitchen-label').html('<strong>Selected</strong>');
				}
			});
		},
		loadDefault: function() {
			var defaultTarget = null;
			//if an expand option is specified the default tab will NOT be loaded
			//instead, the tab associatied with the expandOption value will be loaded
			if ($('.expand-option').length > 0) {
				var expandOption = $('.expand-option').val();
				$('.expand-option').remove();
				if (expandOption == acc_install) {
					defaultTarget = $("input[value='" + install_accs_content + "']").closest(nav_item_q);
					RAQProductController.changeControlsForInstallationAccessories();
				} else if (expandOption == acc_related) {
					defaultTarget = $("input[value='" + accs_content + "']").closest(nav_item_q);
					RAQProductController.changeControlsForAccessories();
				}
			} else {
				defaultTarget = $(raq_product_main_nav_q + ' ' + nav_item_q + default_nav_item_q);
			}
			if (defaultTarget && defaultTarget.length > 0) {
				RAQProductController.loadPageToTab(defaultTarget, function(){
					//remove the default class so that no uneccessary content is reloaded
					defaultTarget.removeClass(default_nav_item);
				});
			} else if (!$(raq_product_main_content_q + ' ' + options_content_q).hasClass('hide')) {
				//THEN the options tab needs to be checked to see that its options sku matches the currentSku
				RAQProductController.loadPageToTab($(raq_product_main_nav_q + ' ' + nav_item_q + nav_selected_q));
			}
		},
		loadPageToTab: function(navItem, callback) {

			RAQProductController.hideAllTargetedContent();
			RAQProductController.markNavItemSelected(navItem);
			var targetedForLoading = $(raq_product_main_content_q).find('.' + navItem.find(target_for_load_q).val());

			var raqOptionsCurrentSku = $(raq_product_main_content_q + ' .raq-options-current-sku').val();
			var raqKnobHandleFinish = $(raq_product_main_content_q + ' .raq-knob-handle-finish').val();
			var currentSkuId = $('.currentSkuId').val();
			var knobHandleFinishId = $('.knobHandleFinishId').val();

			var optionsTargetToLoad = targetedForLoading.hasClass(options_content);
			var optionsContentAndDiffSku = optionsTargetToLoad ? (currentSkuId.length > 0 && currentSkuId != raqOptionsCurrentSku) || (knobHandleFinishId != raqKnobHandleFinish) : false;

			//then update the sku hidden input for the options content
			if (optionsTargetToLoad) {
				$(raq_product_main_content_q + ' .raq-options-current-sku').val(currentSkuId);
				$(raq_product_main_content_q + ' .raq-knob-handle-finish').val(knobHandleFinishId);
			}

			if (targetedForLoading.hasClass(empty_content) || $.trim(targetedForLoading.html()).length < 1 || optionsContentAndDiffSku) {
				$(raq_product_main_content_q).addClass('loading');
				var productId = $('.productId').val();
				var params = {skuId:currentSkuId, prodId:productId, knobHandleFinishId:knobHandleFinishId};
				if ($('.quote-item-to-edit').length > 0 && $('.quote-item-to-edit').val().length > 0) {
					params.quoteItemId = $('.quote-item-to-edit').val();
				}
				targetedForLoading.removeClass(empty_content).load(navItem.find(raq_url_to_load_q).val(), params, function(){

					if ($(this).closest(targeted_content_q).find(raq_product_mouseovers_q).length > 0) {
						ExclusiveFinish.mouseovers(null, $(this).closest(targeted_content_q).find(raq_product_mouseovers_q));
					}

					RAQProductController.registerEvents($(this));
					$(raq_product_main_content_q).removeClass('loading');
					$(this).closest(targeted_content_q).removeClass('hide');

					if (callback != undefined) {
						callback();
					}
				});
			} else {
				targetedForLoading.removeClass('hide');
				if (callback != undefined) {
					callback();
				}
			}
		},
		markNavItemSelected: function(navItem) {//mark 'navItem' as selected and also 'unmark' all other nav items
			$(raq_product_main_nav_q + ' ' + nav_item_q).removeClass(nav_selected);
			navItem.addClass(nav_selected);
		},
		alternateNextButtonCheck: function() {//alternate the showing/hiding of navigation controls
			if ($(raq_product_main_nav_q + ' ' + nav_item_q + ':first').hasClass(nav_selected)) {
				RAQProductController.changeControlsForOptions();
			} else if ($(raq_product_main_nav_q + ' ' + nav_item_q + ':last').hasClass(nav_selected)) {
				RAQProductController.changeControlsForAccessories();
			} else {
				RAQProductController.changeControlsForInstallationAccessories();
			}
		},
		hideAllTargetedContent: function() {
			$(raq_product_main_content_q).find(targeted_content_q).addClass('hide');
		},
		showContent: function(content) {
			content.removeClass('hide');
		},
		changeControlsForOptions: function() {
			$(raq_controls_q + ' ' + next_q).closest(raq_control_item_q).removeClass('hide');
			$(raq_controls_q + ' ' + save_q).closest(raq_control_item_q).addClass('hide');

			$(raq_controls_q + ' ' + edit_q).closest(raq_control_item_q).removeClass('hide');
			$(raq_controls_q + ' ' + previous_q).closest(raq_control_item_q).addClass('hide');
		},
		changeControlsForInstallationAccessories: function() {
			$(raq_controls_q + ' ' + next_q).closest(raq_control_item_q).removeClass('hide');
			$(raq_controls_q + ' ' + save_q).closest(raq_control_item_q).addClass('hide');

			$(raq_controls_q + ' ' + edit_q).closest(raq_control_item_q).addClass('hide');
			$(raq_controls_q + ' ' + previous_q).closest(raq_control_item_q).removeClass('hide');
		},
		changeControlsForAccessories: function() {
			$(raq_controls_q + ' ' + next_q).closest(raq_control_item_q).addClass('hide');
			$(raq_controls_q + ' ' + save_q).closest(raq_control_item_q).removeClass('hide');

			$(raq_controls_q + ' ' + edit_q).closest(raq_control_item_q).addClass('hide');
			$(raq_controls_q + ' ' + previous_q).closest(raq_control_item_q).removeClass('hide');
		},
		accessoryChecked: function() {
			var checkboxSelected = $(this);
			var editingQuote = $(quote_id_q).val().length > 0 && $(quote_item_to_edit_q).val().length > 0;
			var requiredAcc = checkboxSelected.closest(required_acc_items_q).length > 0;

			if (editingQuote) {
				//DWR parameters
				var profileId = $('.profile-id-for-quote').val();
				var quoteId = $(quote_id_q).val();
				var quoteItemId = $(".quote-item-to-edit").val();
				var accProductId = checkboxSelected.closest('.accessory-item').find('.product-id-input').val();
				var accSkuId = checkboxSelected.closest('.accessory-item').find('.sku-id-input').val();


				//then a REQUIRED ACCESSORY. ONLY 1 can be selected.
				if (requiredAcc) {
					//UN-SELECT all other required accessory items before marking current selected
					checkboxSelected.closest(required_acc_items_q).find(raq_select_product_label_q).html('Select');

					var uncheckedRequiredAccs = [];
					//populate the uncheckedRequiredAccs array
					checkboxSelected.closest(required_acc_items_q).find(":radio[name=" + checkboxSelected.attr("name") + "]").each(function(i, item) {
						uncheckedRequiredAccs.push($(item).closest('.accessory-item').find(".sku-id-input").val());
					});

					/****************************************************************************
					 *	Handles add/select AND remove/unselect REQUIRED ACCESSORIES
					 ****************************************************************************/
					//RaqDwrFormHandler.changeRequiredAccForMainQuoteItem(profileId, quoteId, quoteItemId, accProductId, accSkuId, "0.0", uncheckedRequiredAccs, function(data) {
					//	var jsonData = JSON.parse(data);
					//	if (!jsonData.error) {
							//alert("no errors");
					//	}
					//});

				} else {
					var installAcc = (checkboxSelected.hasClass(required_accessory_input) || checkboxSelected.hasClass("optional-accessory-input"));
					//if (checkboxSelected.is(':checked')) { //then an accessory was just Selected/Checked
					//	RaqDwrFormHandler.addAccToMainQuoteItem(profileId, quoteId, quoteItemId, accProductId, accSkuId, "0.0", installAcc, function(data) {
					//		var jsonData = JSON.parse(data);
					//		if (!jsonData.error) {
								//alert("no errors");
					//		}
					//	});
					//} else {
					//	RaqDwrFormHandler.removeAccFromMainItem(quoteId, quoteItemId, accSkuId, installAcc, function(data) {
					//		var jsonData = JSON.parse(data);
					//		if (!jsonData.error) {
								//alert("no errors");
					//		}
					//	});
					//}
				}

			}

			/**********************************************
			 * change LABEL - to Select/Selected
			 **********************************************/
			if (checkboxSelected.is(':checked')) { //then an accessory was just Selected/Checked
				checkboxSelected.siblings(raq_select_product_label_q).html("<strong>Selected</strong");
			} else {
				checkboxSelected.siblings(raq_select_product_label_q).html('Select');
			}
		}
	};
}();

$(document).ready(function(){

	//initialize the Request A Quote product modal/dialog
	$(raq_product_modal_q).dialog({
		autoOpen: false, bgiframe: true, modal: true, dialogClass: 'raq-modal-override',
		width: 725, height: 750, position: ['center','center'],
		draggable: false, resizable: false,
		title: 'To change any of these options, just click the Edit button below:',
		open: function(){
			//initialize the request a quote product controller when this modal opens
			RAQProductController.init();
		}
	});

	//Request A Quote Button
	$('.product-configuration').on('click', '.request-a-quote-link', function(e){
		e.preventDefault();

		if(typeof ClickTaleExec=='function') {
			ClickTaleExec("$('.request-a-quote-link').click()");
		}
		//$(raq_product_modal_q).dialog('open');
		$("#load-options-product-id").val($(".productId").val());
		$("#load-options-sku-id").val($(".currentSkuId").val());
		$("#load-options-knob-handle-finish-id").val($(".knobHandleFinishId").val());
		$("#load-options-knob-handle-finish-hex").val($(".knobHandleFinishHexValue").val());
		if ($("#doorPanelSkuId").val()) {
			$("#load-options-door-panel-product-id").val($("#doorPanelProductId").val());
			$("#load-options-door-panel-sku-id").val($("#doorPanelSkuId").val());
			$("#load-options-door-panel-finish-id").val($("#doorPanelFinishId").val());
		} else {
			$("#load-options-door-panel-product-id").val(null);
			$("#load-options-door-panel-sku-id").val(null);
			$("#load-options-door-panel-finish-id").val(null);
		}

		if ($("#raq-form").length > 0) {
			$("#raq-form").submit();
		} else {
			$("#raq-form-sellable").submit();
		}
	});
});
