/*
--------------------------------------------------

Crescent Electric
Site-Wide Scripts [application.js]

Joe Morrow [joe.morrow@acquitygroup.com]
9/24/2010

Modified by			Date			Changes
Ted Clarke			11/04/2011		added the modal zip functions 

--------------------------------------------------
 */


//start doc ready function
$(document)
		.ready(
				function() {

					// add last class to remove extra border on the end
					$('ul.nav li:last-child').addClass('last');
					$('#productCarousel div:last-child').addClass('last');

					$('div.shade:last').addClass('last');

					$('#navigation ul.nav li:first-child').addClass('products');
					$('#navigation ul.nav li:first-child').addClass('selected');
					$('#navigation ul.subnav li:first-child').removeClass(
							'products');
					$('#navigation ul.subnav li:first-child').removeClass(
							'selected');

					// Search Options Toggle
					$('a.down').click(function() {
						$('#downOptions').toggleClass('hidden');
						return false
					});

					// Numeric Values Only
					$("input.numeric").numeric();

					// Kill Null Links
					$('a[href^="#"]').addClass('null');

					$('a.anchor').removeClass('null');

					$('a.null').click(function() {
						return false;
					});

					$('a.topLink').click(function() {
						$('html, body').animate({
							scrollTop : 0
						}, 'slow');
					});

					// Security Code Toggle
					$('a.whatsThis').click(function() {
						$('#securityCode').toggleClass('hidden');
					});

					// Product Detail Window Shades
					$('a.shadeTrigger').click(function() {
						$(this).toggleClass('expanded');
						$(this).siblings().toggleClass('show');
						return false
					});

					// Quick Order Row Styling
					$('#quickorder table#orderTable tr:odd').addClass('odd');
					$('#quickorder table#orderTableBottom tr:odd').addClass(
							'odd');

					// Quick Order More Functionality
					$('a#moreBtn').click(function() {
						$('#orderTableBottom').removeClass('none');
						$(this).fadeOut('slow');
						return false;
					});

					// Product Details Quantity Validation
					$('#cartButton').click(
							function() {
								// Get what's typed into the zip code field and
								// put in zipCodeField variable
								var itemQuantity = parseInt($('input#quantity')
										.val());
								var maximumQuantity = parseInt($(
										'div#maximumQuantity').html());

								var quantity = parseInt(itemQuantity);
								var maxQuantity = parseInt(maximumQuantity);

								$('div#itemQuantity_validationMessage')
										.addClass('hidden');
								$('div#zeroQuantity_validationMessage')
										.addClass('hidden');
								$('input.quantity').removeClass('error');

								// Check if password is at least 6 characters
								if (quantity > maxQuantity) {
									$('div#itemQuantity_validationMessage')
											.removeClass('hidden');
									$('.max').html(maxQuantity);
									$('input.quantity').addClass('error');
								}

								if (quantity < 1) {
									$('div#zeroQuantity_validationMessage')
											.removeClass('hidden');
									$('input.quantity').addClass('error');
								}

							});

					// Login: set hidden form input for returnURL
					$('form#LoginForm input[name="returnURL"]').val(
							getQuerystring("returnURL", ""));

					// Print Link
					$('a.printLink').click(function() {
						window.print();
						return false;
					});

					// Messages
					$('.success').delay(3200).fadeOut('slow');

					// Global Expanding Form
					$('.expand a.shadeTrigger').addClass('expanded');
					$('.expand .shadeContents').addClass('show');

					// Rockflicker Demos

					// Manage Account
					$('body.E2a #personalShade a.shadeTrigger').addClass(
							'expanded');
					$('body.E2a #personalShade .shadeContents')
							.addClass('show');

					$('body.E2c #shippingShade a.shadeTrigger').addClass(
							'expanded');
					$('body.E2c #shippingShade .shadeContents')
							.addClass('show');

					$('body.E2d #billingShade a.shadeTrigger').addClass(
							'expanded');
					$('body.E2d #billingShade .shadeContents').addClass('show');

					$('body.E2g #formsOfPaymentShade a.shadeTrigger').addClass(
							'expanded');
					$('body.E2g #formsOfPaymentShade .shadeContents').addClass(
							'show');

					$('body.F2 #orderHistoryShade a.shadeTrigger').addClass(
							'expanded');
					$('body.F2 #orderHistoryShade .shadeContents').addClass(
							'show');

					$('body.F3 #invoicesShade a.shadeTrigger').addClass(
							'expanded');
					$('body.F3 #invoicesShade .shadeContents').addClass('show');

					// Checkout
					$('body.E2b #checkoutAddressShade a.shadeTrigger')
							.addClass('expanded');
					$('body.E2b #checkoutAddressShade .shadeContents')
							.addClass('show');

					$('body.E2e #checkoutPaymentShade a.shadeTrigger')
							.addClass('expanded');
					$('body.E2e #checkoutPaymentShade .shadeContents')
							.addClass('show');

					$('body.E2f #checkoutPaymentShade a.shadeTrigger')
							.addClass('expanded');
					$('body.E2f #checkoutPaymentShade .shadeContents')
							.addClass('show');

					$('body.E3a #checkoutMethodsShade a.shadeTrigger')
							.addClass('expanded');
					$('body.E3a #checkoutMethodsShade .shadeContents')
							.addClass('show');

					$('body.E3b #checkoutMethodsShade a.shadeTrigger')
							.addClass('expanded');
					$('body.E3b #checkoutMethodsShade .shadeContents')
							.addClass('show');

					// Product Detail Preview Images Paging

					// Build Paging Links
					var pageLinks = 0;

					if (($("#imageViewer > img").size()) > '1') {
						$('#imageViewer img').each(function() {
							pageLinks++;
							$('#pages a').eq(pageLinks - 1).html(pageLinks);
							// alert(pageLinks);
						});
					}

					if (($("#imageViewer > img").size()) < '2') {
						$('a#prev').addClass('hidden');
						$('a#next').addClass('hidden');
					}

					// Initialize pager with 1st item selected
					$('#pages a:first').addClass('selected');

					// Paging functions
					$('#pages a').click(
							function() {
								$('.productDetailsPager a').removeClass(
										'selected');
								$(this).addClass('selected');
								var pageNumber = $('a.selected').text();
								$('#imageViewer img').addClass('hidden');
								$('#imageViewer img').eq(pageNumber - 1)
										.removeClass('hidden');
								return false;
							});

					$('a#next')
							.click(
									function() {
										if (($('a.selected').text()) < ($('#imageViewer img').length)) {
											$('a.selected').removeClass(
													'selected').next()
													.addClass('selected');
											$('#imageViewer img').addClass(
													'hidden');
											$('#imageViewer img').eq(
													$('a.selected').text()
															- '1').removeClass(
													'hidden').next().addClass(
													'hidden');
										}
										return false
									});

					$('a#prev').click(
							function() {
								if (($('a.selected').text()) > '1') {
									$('a.selected').removeClass('selected')
											.prev().addClass('selected');
									$('#imageViewer img').addClass('hidden');
									$('#imageViewer img').eq(
											$('a.selected').text() - '1')
											.removeClass('hidden').next()
											.addClass('hidden');
								}
								return false
							});

					$('#pages a:empty').remove();

					// Login Buttons
					$('a#forgotPassword').click(function() {
						$(this).addClass('hidden');
						$('fieldset#verifyEmail').removeClass('hidden');
					});

					$('a#newCustomers').click(function() {
						$(this).addClass('hidden');
						$('form#newCustomersForm').removeClass('hidden');
						$('form#CescoNumberForm').addClass('hidden');
						$('a#registerAccount').removeClass('hidden');
						clearB2BRegisterForm();
					});

					$('a#registerAccount').click(function() {
						$(this).addClass('hidden');
						$('form#CescoNumberForm').removeClass('hidden');
						$('form#newCustomersForm').addClass('hidden');
						$('a#newCustomers').removeClass('hidden');
						clearB2CRegisterForm();
					});

					if ($('input[name="accountNumber"]').val() != '') {
						$('a#registerAccount').addClass('hidden');
						$('form#CescoNumberForm').removeClass('hidden');
						clearB2CRegisterForm();
					} else if ($('input[name="firstname"]').val() != '') {
						$('a#newCustomers').addClass('hidden');
						$('form#newCustomersForm').removeClass('hidden');
						clearB2BRegisterForm();
					}

					// Cycle Banner Slideshow Setup
					$('#banner .banners').cycle({
						fx : 'fade', // This will be a CMS variable for the
						// transition effect (some buggy with IE
						// and maybe best not used)
						prev : '#prevPaging',
						next : '#nextPaging',
						speed : 500, // This can be a CMS variable for the
						// transition speen
						timeout : 10000, // This can be a CMS variable for how
						// long each slide is shown
						after : onAfter1
					// Used for current out of total text
					});

					// Cycle Home Secondary Promos
					$('#promos_secondary_slideshow').cycle({
						fx : 'scrollHorz',
						prev : '#prev_secondary',
						next : '#next_secondary',
						speed : 'slow',
						timeout : 10000,
						pager : '#pager_secondary',
						pause : 1
					});

					// remove secondary promos nav numbers
					$('#pager_secondary a').empty();

					// Auto-clear inline prompt text, stored in "title"
					// attribute
					$(".inline-prompt").each(function() {
						if ($(this).attr("title").length == 0)
							$(this).attr("title", $(this).val());
					}).focus(function() {
						if ($(this).val() == $(this).attr("title"))
							$(this).val("").removeClass("inline-prompt");
					}).blur(
							function() {
								if ($(this).val() == "")
									$(this).val($(this).attr("title"))
											.addClass("inline-prompt");
							});

					// Enable Job Number

					/**
					 * @author Michał Bielawski <d3x@burek.it>
					 * @name jQuery disable()
					 * @license WTFPL (http://sam.zoy.org/wtfpl/)
					 */
					(function($) {
						$.fn
								.extend({
									disable : function() {
										return this.each(function() {
											$(this).attr({
												disabled : true
											});
										});
									},
									enable : function() {
										return this.each(function() {
											$(this).removeAttr('disabled');
										});
									},
									toggleDisabled : function(disable) {
										switch (typeof (disable)) {
										case "boolean":
											break;
										case "number":
											disable = disable > 0;
											break;
										default:
											disable = !this.is(':disabled');
										}
										return $(this)[disable ? "disable"
												: "enable"]();
									},
									toggleEnabled : function(enable) {
										switch (typeof (enable)) {
										case "boolean":
											break;
										case "number":
											enable = enable > 0;
											break;
										default:
											enable = this.is(':disabled');
										}
										return $(this)[enable ? "enable"
												: "disable"]();
									}
								});
					})(jQuery);

					// Disable Job Number Box
					$('#jobNum').disable();

					$('#branch').change(function() {
						$('#jobNum').enable();
						$('select option.first:selected').each(function() {
							$('#jobNum').disable();
						});
					});

					// Form Validation
					$('#personalInformation').submit(function() {
						return validateForm();
					});

					$('#newCustomersForm').submit(function() {
						return validateNewCustomerForm();
					});

					$('#CescoNumberForm').submit(function() {
						return validateCescoNumberForm();
					});

					// Breadcrumb Functions
					$('#breadcrumb a:last').addClass('last');

					$('#breadcrumb a.last').click(function() {
						return false;
					});

					$('#breadcrumb span:last-child').addClass('hidden');

					// Search Method
					$('a#bySKU').click(function() {
						$('#searchOption').val('sku');
						$('#quickSearch-form').submit();
					});

					$('a#byAccount').click(function() {
						$('#searchOption').val('account');
						$('#quickSearch-form').submit();
					});
				});
//end doc ready function


// start modal zip functions

// date variables for cookie
var modalZipToday = new Date();
var maxAge = 31556952;
var modalZipExpiry = new Date(modalZipToday.getTime() + maxAge);

//user submitted zip code value
function submitModalZipcode() {
	//get zip code value
	var modalZipCodeInput = document.getElementById('modalZipCode').value;
	//create cookie
	SetModalZipCookie('modalZipCodeCookie', (modalZipCodeInput != '' ?
	modalZipCodeInput : '00001'), modalZipExpiry);
	location.reload();
}

//user canceled zip code entry
function cancelModalZipcode() {
	var modalZipCodeInput = document.getElementById('modalZipCode').value;
	//create cookie
	SetModalZipCookie('modalZipCodeCookie', (modalZipCodeInput != '' ?
	modalZipCodeInput : '00001'), modalZipExpiry);
	location.reload();
}

//get the zip code value from the cookie
function getModalZipCookieVal (offset) {
	var endstr = document.cookie.indexOf (";", offset);
	if (endstr == -1) { endstr = document.cookie.length; }
	return unescape(document.cookie.substring(offset, endstr));
}

//check if cookie exists and get it
function GetModalZipCookie (name) {
	var arg = name + "=";
	var alen = arg.length;
	var clen = document.cookie.length;
	var i = 0;
	while (i < clen) {
		var j = i + alen;
		if (document.cookie.substring(i, j) == arg) {
			return getModalZipCookieVal (j);
		}
		i = document.cookie.indexOf(" ", i) + 1;
		if (i == 0) break;
	}
	return null;
}

//create the cookie and set the zip code value in it
function SetModalZipCookie (name,value,expires,path,secure) {
	document.cookie = name+"="+value+"; expires="+expires.toGMTString()+"; path=/";
}
  
//open the modal zip code box manually
function openModalZipCode() {
	$("#modalZipCodeDiv").overlay({
		// custom top position
		top: 260,
		// some mask tweaks
		mask: {
			color: '#000000',
			loadSpeed: 200,
			opacity: 0.60
		},
		// disable this for modal dialog-type of overlays
		closeOnClick: false,
		// load it immediately after the construction
		load: true
	});
	document.forms['modalZipCodeForm'].elements['modalZipCode'].focus();
}
// end modal zip functions


