﻿/*
* this file is for javascript functions specific for xyron.
*/

xyron = {
	preinit: function() {
		//not required
	},
	initializeHomePage: function() {

		BannerRotator.initialize();

		// add rollover action to categories
		j$(".item").hover(
			function() {
				j$('.default', this).hide();
				j$('.rollover', this).show();
				j$('.rollover h2', this).css('background-image', 'url(/img/xyron/icons/pointer-down.gif)');
			},
			function() {
				j$('.rollover', this).hide();
				j$('.default', this).show();
			}
		);
	},
	initializeContactUs: function() {
		common.drivingDirections.initialize();
	},
	initializePrivacydefault: function() {
	},
	initializeBio: function() {
	}
}

xyron.product = {

	initializeProductLanding: function() {

		// add rollover action to categories
		j$(".item").hover(
			function() {
				j$('.default', this).hide();
				j$('.rollover', this).show();
				j$('.rollover h2', this).css('background-image', 'url(/img/xyron/icons/pointer-down.gif)');
			},
			function() {
				j$('.rollover', this).hide();
				j$('.default', this).show();
			}
		);
	},
	initializeProductListings: function() {
		//not required
	},
	initializeProductDetail: function() {
		j$('.tabs').slttabs();

		common.scrollable.initialize();
		common.video.initialize();
		common.hires.initialize();
	}
}

xyron.solutions = {

	initializeSolutions: function() {
	}
}

xyron.templates = {

	initializeTemplates: function() {
	}
}

xyron.campaign = {

	initializeCampaignLanding: function() {
		//not required
	},
	initializeCampaign: function() {
		var myRelatedProductsCarousel = new Carousel('carouselRelatedProducts');
		myRelatedProductsCarousel.initialize();    
	}
}

xyron.innovations = {

	initializeLandingPage: function() {
		//not required
	}
}

xyron.gallery = {
	initializeGallery: function() {
		common.scrollable.initialize();
	}
};

xyron.video = {
	initialize: function() {
		common.scrollable.initialize();

		j$('.tabs').slttabs({
			beforeChange: xyron.video.populateTab
		});		
	},
	
	populateTab: function(tab, tabcontent) {

		var tabId = j$(tab).attr('id');
		if (tabId == 'mostViewed' || tabId == 'highestRated') {
			
			var tabContent = j$(tab).data('tabid');
			
			var jsonParams = {
				categoryName: tabId,
				numResults: j$(tab).parents('.tabs').data('displaycount')
			}

			var tabcontentId = j$(tabcontent).attr('id');
			document.body.style.cursor= 'wait';
			new Ajax.Request('/' + locale + '/GetVideos.json',
			{
				method: 'get',
				parameters: { useResponseBody: 'true', jsonString: Object.toJSON(jsonParams) },
				onSuccess: function(transport) {
					var json = transport.responseText.evalJSON();
					switch (json.type) {
						case "JsonMethodMessage":
							xyron.video.populateVideos(json.result, tabcontent);
							break;
						case "JsonValidationMessage":
							handleValidationError(tabcontentId, json.messages);
							break;
						case "JsonSystemExceptionMessage":
							handleSystemExceptionError(tabcontentId, json.messages);
							break;
					}
				},
				onFailure: function() {
					handleSystemExceptionError(tabcontentId, json.message);
				},
				onComplete: function() {
					document.body.style.cursor = 'default';
				}
			})
		}
	},

	populateVideos: function(jsonVideoObject, tabcontent) {

		var videosArray = jsonVideoObject.toArray();
		var videoDiv = "<div>";
		for (var i = 0; i < videosArray.size(); i++) {
			var videoUrl = "/" + locale + "/Videos/" + videosArray[i].videoURL + ".html";
			videoDiv += "<div class=\"thumbnailItem video\">"
			videoDiv += "<h2>";
			videoDiv += "<a href=" + videoUrl + ">";
			videoDiv += videosArray[i].name;
			videoDiv += "</a></h2>";
			videoDiv += "<div class=\"image\">";
			videoDiv += "<a href=" + videoUrl + ">";
			videoDiv += "<img src=" + videosArray[i].thumbImage + " alt=\"\" border=\"0\" /></a></div>";
			videoDiv += "<div class=\"description\">";
			videoDiv += "</div>";
	//        videoListDiv += "<div class=\"publishDate\" style=\"display:none;\">"+ array[i].publishDate +"</div>"
	//        videoListDiv += "<div class=\"numberOfViews\">"+ array[i].views +"</div>"
	//        videoListDiv += "<div class=\"userRating\">"+ array[i].rating +"</div>"
			videoDiv += "</div>"
		}
		videoDiv += "</div>"
		j$(tabcontent).html(videoDiv);
	}	
};

xyron.dealerSupport = {

	initialize: function() {
		/* Dialog events from menus links */
		j$(".emailFeedback").click(xyron.dealerSupport.showFeedbackDialog);
		j$(".sellSheet").click(xyron.dealerSupport.showSellSheetDialog);
		j$(".productSample").click(xyron.dealerSupport.showProductSampleDialog);
		/* ButtonEvents from dialogs to call server */
		j$("#sendFeedbackSubmitButton").click(xyron.dealerSupport.sendFeedbackRequest);
		j$("#ProductInformationSubmitButton").click(xyron.dealerSupport.productInformationRequest);
		j$("#ProductSampleSubmitButton").click(xyron.dealerSupport.productSampleRequest);

		/* Initialize Autocomplete product search 
		j$(productList).each(function(idx, item) {
		//productList[idx].label = productList[idx].Name + "-" + productList[idx].Sku;
		//productList[idx].value = productList[idx].Name + "-" + productList[idx].Sku;
		});*/

		xyron.dealerSupport.initAutoComplete(".sellSheetProductSelect");
		xyron.dealerSupport.initAutoComplete(".sampleRequestProductSelect");

		j$(".product-row-delete").live('click', function(e) {
			//alert(j$(this).parent().data('product'));
			j$(this).parent().remove();
			return false;
		});

		var countriesHtml = '<option value="" selected="selected">Select...</option>';
		for (i = 0; i < countryList.length; i++) {
			countriesHtml += "<option value='" + countryList[i].Key + "'>" + countryList[i].Value + "</option>";
		}
		var statesHtml = '<option value="" selected="selected">Select...</option>';
		for (i = 0; i < stateList.length; i++) {
			statesHtml += "<option value='" + stateList[i].Key + "'>" + stateList[i].Value + "</option>";
		}

		j$("#ps_Country,#pi_Country").append(countriesHtml);
		j$("#ps_State,#pi_State").append(statesHtml);
	},

	initializeProductDetail: function() {
		xyron.dealerSupport.initialize();
	
		j$('.tabs').slttabs();

		//common.scrollable.initialize();
		common.video.initialize();
		common.hires.initialize();


		j$(".relatedProjectsOverlay").appendTo(j$("body"));

		j$("#relatedProducts").appendTo(".col2");
		j$("#relatedProjects").appendTo(".col2");

		j$(".projectLink").each(
			function(idx, el) {
				j$(el).bind("click",
					function(event) {
						var id = j$(this).data("link");
						var target = j$("#RelatedProjectOverlay"); // this is the overlay to fill
						var source = j$(j$("#" + id));
						target.data("title", source.data("title"));
						target.find("#projectInfo").html(j$(source.find(".projectInfo")).html());
						target.find("#instructions").html(j$(source.find(".instructions")).html());
						// only if necessary...
						//target.find("#othermaterials").html(j$(source.find(".othermaterials")).html());
						xyron.dealerSupport.showDialog(target);
					}
				);

			}
		);
		
		j$(".requestInfoDiv a").bind("click",
			function () {
				var sku = j$(this).data("sku");
				var item = j$(productList).filter( function(idx) { return productList[idx].Sku==sku; })[0];
				xyron.dealerSupport.showSellSheetDialog();
				xyron.dealerSupport.addProductToSelection(item, j$(xyron.dealerSupport.productInformationOverlay).find(".feedbackPanel"));
				
			}
		);

		j$(".requestSampleDiv a").bind("click",
			function () {
				var sku = j$(this).data("sku");
				var item = j$(productList).filter( function(idx) { return productList[idx].Sku==sku; })[0];
				xyron.dealerSupport.showProductSampleDialog();
				xyron.dealerSupport.addProductToSelection(item, j$(xyron.dealerSupport.productSampleOverlay).find(".feedbackPanel"));
				
			}
		);
		
		/**
		 * Carousel
		 */
		var myRelatedProductsCarousel = new Carousel( 'carouselRelatedProducts' );
		myRelatedProductsCarousel.initialize();
		
		var myRelatedProjectsCarousel = new Carousel( 'carouselRelatedProjects' );
		myRelatedProjectsCarousel.initialize();

	},
	

	initAutoComplete: function(item) {
		j$.ui.autocomplete.prototype._renderItem = function(ul, item) {
			var re = new RegExp("^" + this.term, "i");
			var t = item.Name.replace(re, "<span class='search-highlight'>" + this.term + "</span>");
			var sku = item.Sku.replace(re, "<span class='search-highlight'>" + this.term + "</span>");
			//alert(sku);
			return j$("<li></li>")
					.data("item.autocomplete", item)
					.append("<a>" + t + "(" + sku + ")" + "</a>")
					.appendTo(ul);
		};

		j$(item).autocomplete({ minLength: 1,
			/*appendTo: "#ProductInformationOverlay",*/
			source: function(request, response) {
				var matcher = new RegExp(j$.ui.autocomplete.escapeRegex(request.term), "i");
				var foundCount = 0;
				var maximumSearchResultsToReturn = 20;
				response(j$.grep(productList, function(value) {
					var productSearchResult = matcher.test(value.Name) || matcher.test(value.Sku);
					if (productSearchResult) { foundCount++; }

					var show = productSearchResult && foundCount < maximumSearchResultsToReturn;
					return show;
				}));
			},
			focus: function(event, ui) {
				j$(event.target).val(ui.item.Name);
				return false;
			},
			select: function(e, ui) {
				xyron.dealerSupport.addProductToSelection(ui.item, j$(e.target));
				return true;
			}
		});
	},
	addConsoleMessage: function(message) {
		if (j$.browser.msie)
			alert(message);
		else
			console.log(message);
	},

	addProductToSelection: function(item, control) {
		//debugger;
		//alert(control);
		var controlToRender = control.parent().find(".productSelectionResults");

		var itemRow =
            "<div class='product-row'> <a href='#' class='product-row-delete ui-icon ui-icon-closethick' title='Remove'> Remove </a><input type='text' value='1' class='product-count' />"
                + "<span>" + item.Name + "</span>" +
            "</div>";

		var row = j$(itemRow)
			.data("product", item)
            .appendTo(controlToRender)
            .effect('highlight', {}, 1500);
	},

	// Overlays
	productSampleOverlay: "#ProductSampleOverlay",
	productInformationOverlay: "#ProductInformationOverlay",
	sendFeedbackOverlay: "#sendFeedbackOverlay",

	// helper function for displaying overlays
	showDialog: function(container) {
		var $overlay = j$(container);

		var dialog_options = {
			modal: true,
			position: 'center',
			width: '680px',
			closeText: common.overlayCloseText,
			title: $overlay.data("title"),
			close: function() { j$(".productSelectionResults").html(""); }
		}		

		$overlay.dialog(dialog_options)
				.find(".feedbackPanel").html('').end()
				.find(":input").val('');
	},

	showFeedbackDialog: function(evt) {
		xyron.dealerSupport.showDialog(xyron.dealerSupport.sendFeedbackOverlay);

		var overlay = j$(xyron.dealerSupport.sendFeedbackOverlay);
		var feedbackPanel = overlay.find(".feedbackPanel");


		new Ajax.Request(xyron.dealerSupport.endpoints.getSalesRepEmail,
		{
			method: 'get',
			parameters: { useResponseBody: 'true' },
			onSuccess: function(transport) {
				var json = transport.responseText.evalJSON();
				switch (json.type) {
					case "JsonMethodMessage":
						if (json.result.hasSalesRep) {

							var salesRepEmailAddress = json.result.salesRepEmailAddress;
							// insert checkbox to feeback
							var checkbox = "<div class=\"label\">" +
										"<label for=\"salesRepEmail\">Copy Xyron Sales Rep</label></div>" +
										"<div class=\"field\">" +
										"<input type=\"checkbox\" checked=\"checked\" value=\"" + salesRepEmailAddress + "\" id=\"salesRepEmail\"></input>" +
										"</div>";
						} else {
							checkbox = ""
						}
						j$("#repEmailField").html(checkbox);
						break;
					case "JsonValidationMessage":
						xyron.dealerSupport.renderErrorMessagesToPanel(j$.makeArray(json.message), feedbackPanel);
						break;
						break;
					case "JsonSystemExceptionMessage":
						xyron.dealerSupport.renderErrorMessagesToPanel(j$.makeArray(json.message), feedbackPanel);
						break;
				}
			},
			onFailure: function() {
				xyron.dealerSupport.renderErrorMessagesToPanel(j$.makeArray(json.message), feedbackPanel);
			},
			onComplete: function() {
				//document.body.style.cursor = 'default';
			}
		});

		return false;
	},

	showSellSheetDialog: function(e) {
		xyron.dealerSupport.showDialog(xyron.dealerSupport.productInformationOverlay);
		return false;
	},

	showProductSampleDialog: function(e) {
		xyron.dealerSupport.showDialog(xyron.dealerSupport.productSampleOverlay);
		return false;
	},

	// JSON endpoints
	endpoints: {
		sendFeedback: "/enUS/DealerSendFeedback.json",
		getSalesRepEmail: "/enUS/GetSalesRepEmail.json",
		productInformation: "/enUS/DealerProductInformation.json",
		producSample: "/enUS/DealerProductSample.json"
	},

	sendFeedbackRequest: function(evt) {
		var overlay = j$(xyron.dealerSupport.sendFeedbackOverlay);

		var feedbackPanel = overlay.find(".feedbackPanel").html('');

		var jsonParams = {
			type: j$("#sendFeedbackType").val(),
			text: j$("#sendFeedbackText").val(),
			hasSalesRep: j$("#salesRepEmail").is(':checked'),
			salesRepEmailAddress: j$("#salesRepEmail").val()
		};

		var jsonRequestString = Object.toJSON(jsonParams);

		var $submitButton = j$(evt.target);
		// disable button to prevent multiple long-running requests to mail service
		$submitButton.attr('disabled', 'disabled');

		j$.get(xyron.dealerSupport.endpoints.sendFeedback,
			  { useResponseBody: 'true', jsonString: jsonRequestString },
			  function(data, textstatus) {

			  	data = j$.parseJSON(data);

			  	switch (data.type) {
			  		case "JsonValidationMessage":
			  			xyron.dealerSupport.renderErrorMessagesToPanel(data.messages, feedbackPanel);
			  			break;
			  		case "JsonSystemExceptionMessage":
			  			xyron.dealerSupport.renderErrorMessagesToPanel(j$.makeArray(data.message), feedbackPanel);
			  			break;
			  		case "JsonMethodMessage":
			  			xyron.dealerSupport.renderSuccessToPanel(data.userMessage, overlay);
			  			break;
			  	}
			  });

		// reenable button to continue
		$submitButton.removeAttr('disabled');

		return false;
	},

	productInformationRequest: function(evt) {

		var overlay = j$(xyron.dealerSupport.productInformationOverlay);
		var feedbackPanel = overlay.find(".feedbackPanel");
		feedbackPanel.html('');

		var jsonParams = {
			products: [],
			address1: j$("#pi_address1").val(),
			address2: j$("#pi_address2").val(),
			postalCode: j$("#pi_postcode").val(),
			city: j$("#pi_city").val(),
			state: j$("#pi_State").val(),
			country: j$("#pi_Country").val(),
			reason: j$("#pi_Reason").val()
		};

		overlay.find(".productSelectionResults .product-row").each(
			function(idx, item) {
				var itemRow = j$(item).data("product");
				var itemCount = j$(item).find("input.product-count").val();
				jsonParams.products.push({ sku: itemRow.Sku, count: itemCount });
			});

		new Ajax.Request(xyron.dealerSupport.endpoints.productInformation,
		{
			method: 'get',
			parameters: { useResponseBody: 'true', jsonString: Object.toJSON(jsonParams) },
			onSuccess: function(transport) {
				var json = transport.responseText.evalJSON();
				switch (json.type) {
					case "JsonMethodMessage":
						xyron.dealerSupport.renderSuccessToPanel("Your Product Information Request has been sent.", overlay);
						break;
					case "JsonValidationMessage":
						xyron.dealerSupport.renderErrorMessagesToPanel(j$.makeArray(json.message), feedbackPanel);
						break;
					case "JsonSystemExceptionMessage":
						xyron.dealerSupport.renderErrorMessagesToPanel(j$.makeArray(json.message), feedbackPanel);
						break;
				}
			},
			onFailure: function() {
				xyron.dealerSupport.renderErrorMessagesToPanel(j$.makeArray(json.message), feedbackPanel);
			},
			onComplete: function() {
				//document.body.style.cursor = 'default';
			}
		});

		return false;
	},

	productSampleRequest: function(evt) {

		var overlay = j$(xyron.dealerSupport.productSampleOverlay);
		var feedbackPanel = overlay.find(".feedbackPanel");
		feedbackPanel.html('');

		var jsonParams = {
			products: [],
			address1: j$("#ps_address1").val(),
			address2: j$("#ps_address2").val(),
			postalCode: j$("#ps_postcode").val(),
			city: j$("#ps_city").val(),
			state: j$("#ps_State").val(),
			country: j$("#ps_Country").val(),
			reason: j$("#ps_Reason").val()
		};

		overlay.find(".productSelectionResults .product-row").each(
			function(idx, item) {

				var $product = j$(item);
				var itemRow = $product.data("product");
				var itemCount = $product.find("input.product-count").val();
				jsonParams.products.push({ sku: itemRow.Sku, count: itemCount });
			});

		new Ajax.Request(xyron.dealerSupport.endpoints.producSample,
		{
			method: 'get',
			parameters: { useResponseBody: 'true', jsonString: Object.toJSON(jsonParams) },
			onSuccess: function(transport) {
				var json = transport.responseText.evalJSON();
				switch (json.type) {
					case "JsonMethodMessage":
						xyron.dealerSupport.renderSuccessToPanel("Your Product Sample Request has been sent.", overlay);
						break;
					case "JsonValidationMessage":
						xyron.dealerSupport.renderErrorMessagesToPanel(j$.makeArray(json.message), feedbackPanel);
						break;
					case "JsonSystemExceptionMessage":
						xyron.dealerSupport.renderErrorMessagesToPanel(j$.makeArray(json.message), feedbackPanel);
						break;
				}
			},
			onFailure: function() {
			xyron.dealerSupport.renderErrorMessagesToPanel(j$.makeArray(json.message), feedbackPanel);
			},
			onComplete: function() {
				//document.body.style.cursor = 'default';
			}
		});

		return false;
	},

	renderErrorMessagesToPanel: function(messages, container) {
		var displayMessage = "<ul class='validation-message'>";
		j$(messages).each(function(idx, item) {
			displayMessage += "<li>" + item + "</li>";
		});
		j$(container).append(displayMessage)
					 .show('blind', {}, 500, function(e) {
					 	// instantiate glow
					 	// highlight with background colour animation
					 });
	},

	renderSuccessToPanel: function(message, overlay) {

		j$(overlay).dialog('close');
		j$("#DealerOverlaySuccess .dealerSuccessMessage").html(message);
		j$("#DealerOverlaySuccess").dialog({
			title: "Success",
			width: '300px',
			position: 'center',
			modal: true,
			close: function() { }
		});
	}

};
