// Prevent console commands from throwing errors in IE
try { console.log('init console... done'); } catch(e) { console = { log: function() {} }; }
// Fix JS flash of unstyled content by hiding all descendents of HTML until DOM is loaded.


var merillat = {
	setGlobals: function () {
		$mainWrapper = $('#main-wrapper');
		$contentWrapper = $('#content-wrapper');
		$header = $('#header');
		$nav = $('#main-nav');
		$navPoints = $('#main-nav > li > a');
		$signInForm = $('#sign-in-form');
		$myDealers = $('div#my-dealers-container');
		$manageProjectLink = $('a#manage-project');
		$addProjectLink = $('a#add-project');
		$styleDescriptionLink = $('a#style-description');
		$manageDesignLink = $('a#manage-design');
		$curURL = document.URL;
		subnavDisplayCount = 0;
	},

	// this can be loaded after critical content
	setupSubNav: function () {
		if ($('#main-nav').length) {
			var config = {
				sensitivity: 2, // number = sensitivity threshold (must be 1 or higher)    
				interval: 120, // number = milliseconds for onMouseOver polling interval    
				over: function () {
					$('.subnav', $(this)).slideDown(230);
					$('select').addClass('dropped-down'); //Hide <select> tags in IE.
				}, // function = onMouseOver callback (REQUIRED)    
				timeout: 300, // number = milliseconds delay before onMouseOut    
				out: function () {
					$('.subnav', $(this)).slideUp(230, function () {
						subnavDisplayCount = 0;
						$('.subnav').each(function () {
							if ($(this).css('display') === 'block') {
								subnavDisplayCount = subnavDisplayCount + 1;
							};
						});

						if (subnavDisplayCount <= 0) {
							//Reveal <select> tags in IE.
							$('select').removeClass('dropped-down');

						};
					});

				} // function = onMouseOut callback (REQUIRED)    
			};
			$('li.main').hoverIntent(config);

			// Check whether browser is IE using feature detection
			if (jQuery.support.hrefNormalized) { // Not IE
				Cufon.replace('ul.subnav a', { hover: true, textShadow: '-1px -1px rgba(255, 255, 255, 0.4), 1px -1px rgba(255, 255, 255, 0.4), -1px 1px rgba(255, 255, 255, 0.4), 1px 1px rgba(255, 255, 255, 0.4)' });
			} else { // Is IE
				Cufon.replace('ul.subnav a');
			}
		}

	},

	signInSlider: function () {

		var hideDelayTimer = null;
		var beingShown = false;
		var shown = false;
		var menuSpeed = 500;
		var hideDelay = 500;

		$signInForm.hide();
		$('#ideafolio-sign-in-btn').click(function () {
			if (hideDelayTimer) clearTimeout(hideDelayTimer);
			if (beingShown || shown) {
				$signInForm.slideUp(menuSpeed, function () {
					shown = false;
					$('#ideafolio-sign-in-btn').css('background-position', '0 2px');
				});
			} else {
				// reset position of info box
				beingShown = true;
				$('#ideafolio-sign-in-btn').css('background-position', '0 -18px');
				$signInForm.slideDown(menuSpeed, function () {
					$('input#globalLogin_Email').focus();
					beingShown = false;
					shown = true;
				});
			}
			return false;
		});

		$('div.sign-in-form-container a#btnReset').click(function () {
			if (hideDelayTimer) clearTimeout(hideDelayTimer);
			hideDelayTimer = setTimeout(function () {
				hideDelayTimer = null;
				$signInForm.slideUp(menuSpeed, function () {
					$('#ideafolio-sign-in-btn').css('background-position', '0 2px');
					shown = false;
				});

			}, 0);

			return false;
		});
	},

	myDealerSlider: function () {

		var hideDelayTimer = null;
		var beingShown = false;
		var shown = false;
		var menuSpeed = 500;
		var hideDelay = 500;

		$myDealers.hide();
		$('#my-dealer-btn').click(function () {
			if (hideDelayTimer) clearTimeout(hideDelayTimer);
			if (beingShown || shown) {

				$myDealers.slideUp(menuSpeed, function () {
					shown = false;
					$('#my-dealer-btn').css('background-position', '0 2px');
					$('select').removeClass('dropped-down');
				});
			} else {
				// reset position of info box
				beingShown = true;
				$('#my-dealer-btn').css('background-position', '0 -18px');
				$('select').addClass('dropped-down');
				$myDealers.slideDown(menuSpeed, function () {

					beingShown = false;
					shown = true;
				});
			}
			return false;
		});

		$('div#my-dealers-container').mouseover(function () {
			if (hideDelayTimer) clearTimeout(hideDelayTimer);
			return false;
		});

		$('#my-dealer-link').mouseleave(function () {
			if (hideDelayTimer) clearTimeout(hideDelayTimer);
			hideDelayTimer = setTimeout(function () {
				hideDelayTimer = null;

				$myDealers.slideUp(menuSpeed, function () {
					$('select').removeClass('dropped-down');
					$('#my-dealer-btn').css('background-position', '0 2px');
					shown = false;
				});

			}, hideDelay);

			return false;
		});
	},

	viewSelector: function () {
		$('.view-link-container').click(function () {
			$('#list-option-container').find('.selected').removeClass('selected');
			$(this).addClass('selected');
			$('ul.wood-finishes li span').fadeOut('slow', function () {
				//$(this).fadeIn('fast').addClass('thumb_view');
			});
			return false;
		});
	},

	setButtonStyles: function () {
		var $myWidth, $myHeight;
		var $myHorzPadding = 0;
		var $myVertPadding = 0;

		var $myHtml, $curButtonLink, $curButton;
		var i = 0;
		$('button.button-replacer').each(function () {
			$myHtml = $(this).html();
			$(this).css({ 'position': 'absolute', 'width': '20px', 'height': '10px', 'top': '0', 'left': '0' });
			$(this).wrap('<div class="button-replaced-container" style="position: relative; display: inline;"></div>');
			if ($(this).hasClass('arrow')) {
				$(this).after('<a href="#" class="button-replaced button-replacer arrow">' + $myHtml + '</a>');
			} else {
				$(this).after('<a href="#" class="button-replaced button-replacer">' + $myHtml + '</a>');
			}
		});

		$('button.button-replacer-primary').each(function () {
			$myHtml = $(this).html();
			$(this).css({ 'position': 'absolute', 'width': '20px', 'height': '10px', 'top': '0', 'left': '0' });
			$(this).wrap('<div class="button-replaced-container" style="position: relative; display: inline;"></div>');
			if ($(this).hasClass('arrow')) {
				$(this).after('<a href="#" class="button-replaced button-replacer-primary arrow">' + $myHtml + '</a>');
			} else {
				$(this).after('<a href="#" class="button-replaced button-replacer-primary">' + $myHtml + '</a>');
			}
		});

		$('a.button-replaced').each(function () {
			$curButtonLink = $(this);
			$curButtonLink.click(function () {
				$(this).parents('form').submit();
				return false;
			});
			i = i + 1;
		});

		$('a.button-replacer').each(function () {
			if ($(this).hasClass('arrow')) {
				$(this).append('<span class="button-arrow"></span>');
				$(this).css('padding-right', '14px');
			};
		});

		$('a.button-replacer-primary').each(function () {
			if ($(this).hasClass('arrow')) {
				$(this).append('<span class="button-arrow"></span>');
				$(this).css('padding-right', '14px');
			};
		});

		$('.kuppersmith-feature-links a').each(function () {
			if ($(this).hasClass('arrow')) {
				$(this).append('<img src="/images/pic/kuppersmith/grey-arrow.gif" align="absmiddle" style="margin: 4px 0 0 6px;"/>');
			};
		});



	},

	activateCufon: function () {
		var $buttonReplacers = $('a.button-replacer, a.button-replacer-primary').not('.project-dropdown a.button-replacer'), $h2s = $('h2').not('.colorbox-inline-content h2, h2.ignore'), $h3s = $('h3').not('#hardware-window-bottom h3');
		var $subnavLinks = $('.subnav a').not('.sub-subnav a');
		Cufon.replace('h1', { textShadow: '2px 2px rgba(0,0,0,0.1), 1px 1px rgba(0,0,0,0.2)', fontFamily: 'Helvetica Neue' });
		Cufon.replace('.webisode-container p.title', { textShadow: '2px 2px rgba(4,4,4,0.5), 1px 1px rgba(4,4,4,0.5)', fontFamily: 'Helvetica Neue' });
		Cufon.replace('.webisode-container p', { textShadow: '2px 2px rgba(4,4,4,0.5), 1px 1px rgba(4,4,4,0.5)', fontFamily: 'Helvetica Neue' });
		Cufon.replace($h2s, { fontFamily: 'Helvetica Neue' });
		Cufon.replace($h3s, { fontFamily: 'Helvetica Neue' });
		Cufon.replace($subnavLinks, { fontFamily: 'Helvetica Neue' });
		Cufon.replace('#ibs-wrapper h3', { textShadow: '2px 2px rgba(0,0,0,0.1), 1px 1px rgba(0,0,0,0.2)', fontFamily: 'Helvetica Neue' });
		Cufon.replace('#cook-like-curtis .blurb', { fontFamily: 'Helvetica Neue' });
		Cufon.replace('.gift-pack-heading', { fontFamily: 'Helvetica Neue' });
		Cufon.replace('h3.inline-heading, #ibs-wrapper h5', { fontFamily: 'Helvetica Neue' });
		Cufon.replace('.highlights-small a', { fontFamily: 'Helvetica Neue' });
		Cufon.replace('#footer-site-links-title', { fontFamily: 'Helvetica Neue' });
		Cufon.replace('span.heading-choice-hovers h2', { fontFamily: 'Helvetica Neue' });
		Cufon.replace('h3.your-style strong', { textShadow: '2px 2px rgba(0,0,0,0.1), 1px 1px rgba(0,0,0,0.2)', fontFamily: 'Helvetica Neue' });
		//Apply Cufon to form buttons if NOT IE
		if (!$.browser.msie) Cufon.replace($buttonReplacers, { fontFamily: 'Helvetica Neue', textShadow: '1px 1px rgba(0, 0, 0, 0.3), 0 1px rgba(0, 0, 0, 0.3), 1px 0 rgba(0, 0, 0, 0.3)' });
	},

	/*
	* initialize login click handler for global login control
	*/
	loginConfig: function () {
		$('#loginErrorMsg').hide();
		$('#loginMsg').hide();

		merillat.initLoginClick('global-login-form', 'btnLogin', 'globalLogin_Email', 'globalLogin_Password', 'loginMsg', 'loginErrorMsg', '/ideafolio/login-submit.html');
	},

	/*
	* initialize forgot password click handler for global login control
	*/
	forgotPasswordConfig: function () {
		$('#loginErrorMsg').hide();
		$('#loginMsg').hide();

		merillat.initForgotPasswordClick('forgotPass', 'globalLogin_Email', 'loginMsg', 'loginErrorMsg');
	},

	/*
	* bind the login click event for the login control or registration page
	*/
	initLoginClick: function (formId, loginBtnId, emailId, passwordId, loginMsg, loginErrorMsgId, jsonUrl) {
		$('#' + formId).bind('submit', { emailId: emailId, passwordId: passwordId, loginMsg: loginMsg, loginErrorMsgId: loginErrorMsgId, jsonUrl: jsonUrl, formId: formId }, merillat.loginClick);
	},

	/*
	* bind the forgot password click event for the login control or registration page
	*/
	initForgotPasswordClick: function (forgotPasswordId, emailId, loginMsg, loginErrorMsgId) {
		$('#' + forgotPasswordId).bind('click', { emailId: emailId, loginMsg: loginMsg, loginErrorMsgId: loginErrorMsgId }, merillat.forgotPasswordClick);
	},

	/*
	* login click action, performs JSON call that either displays 
	* a message if there is an error or redirects the user to the 
	* scrapbook page if it is successful.
	*/
	loginClick: function (event) {
		var email = $('#' + event.data.emailId).val();
		var password = $('#' + event.data.passwordId).val();

		/* add local scoped variables for event data, IE does not recognize the event data within the getJSON callback */
		var loginErrorMsgId = event.data.loginErrorMsgId;
		var loginMsg = event.data.loginMsg;
		var formId = event.data.formId;
		$('#' + loginErrorMsgId).hide();

		if ($('#' + formId).valid()) {
			var jsonArgs = {};
			jsonArgs[event.data.emailId] = email;
			jsonArgs[event.data.passwordId] = password;
			jsonArgs['nocache'] = (new Date()).getTime();

			$.getJSON(event.data.jsonUrl, jsonArgs, function (data, status) {
				if (data.IsValid) {
					$.cookie('UserLoggedIn', 'true', { expires: 1, path: '/', domain: merillat.getDomain() });
					/* GOOGLE ANALYTICS */
					mr.tracking.google.trackEvent('Login', 'Logged In');
					window.location = '/ideafolio/my-scrapbook.html';
					$('#' + loginErrorMsgId).hide();
				} else {
					$.cookie('UserLoggedIn', null, { expires: 1, path: '/', domain: merillat.getDomain() });
					$('#' + loginErrorMsgId).show();
					$('#' + loginErrorMsgId).text(data.Message);
				}
				$('#' + loginMsg).hide();
			});
		}
		event.preventDefault();
	},

	/*
	* logout click event that will update the cookie flag "UserLoggedIn". This flag is used
	* by the Merillat Pressroom to determine if the user is logged in.
	*/
	logoutConfig: function () {
		$('#idea-folio-sign-out-btn').click(function () {
			$.cookie('UserLoggedIn', null, { expires: 1, path: '/', domain: merillat.getDomain() });
		});
	},

	/* 
	* This function is used to retrieve the domain information, which will be used to
	* set up the cookie for "UserLoggedIn".
	*/
	getDomain: function () {
		var domainFields = document.domain.split('.');
		return domainFields.length == 1 ? null : '.' + domainFields[domainFields.length - 2] + '.' + domainFields[domainFields.length - 1];
	},

	/*
	* forgot password click action that makes a JSON call and 
	* displays either a confirmation or error message.
	*/
	forgotPasswordClick: function (event) {
		var email = $('#' + event.data.emailId).val();

		var jsonArgs = {};
		jsonArgs["email"] = email;
		jsonArgs['nocache'] = (new Date()).getTime();

		$.getJSON('/ideafolio/forgot-password-submit.html', jsonArgs, function (data, status) {
			if (data.IsValid) {
				$('#' + event.data.loginErrorMsgId).hide();
				$('#' + event.data.loginMsg).show();
				$('#' + event.data.loginMsg).text(data.Message);
			} else {
				$('#' + event.data.loginMsg).hide();
				$('#' + event.data.loginErrorMsgId).show();
				$('#' + event.data.loginErrorMsgId).text(data.Message);
			}
		});

		event.preventDefault();
	},

	styleSelectOptions: function () {


		var i = 0, $optionIndex, $curSelect, $curForm;
		//		$('select').css('display', 'none');
		// $('select').each(function() {
		// 	if ($(this).parent().is('form')) {
		// 		$(this).parent().before('<div class="dropdown-list-container design-dropdown"><p>' + $('select:eq(' + i + ') option:selected').html() + '</p><ul class="dropdown-list"></ul></div>');
		// 	} else {
		// 		$(this).before('<div class="dropdown-list-container design-dropdown"><p>' + $('select:eq(' + i + ') option:selected').html() + '</p><ul class="dropdown-list"></ul></div>');
		// 	}

		// $(this).css('display', 'none');
		// 	$(this).find('option').each(function() {
		// 		$(this).parent().parent().parent().find('.dropdown-list').append('<li>' + $(this).html() + '</li>');
		// 	});
		// 	i = i + 1;
		// });
		//console.log(i);
		$('.dropdown-list li').each(function () {
			$(this).click(function () {
				$curForm = $(this).parent().parent().parent().find('form');
				$curSelect = $(this).parent().parent().parent().find('select');
				$optionIndex = $(this).prevAll().length;

				$curSelect.find('option:eq(' + $optionIndex + ')').attr('selected', 'selected');

				$curSelect.change();

			});
		});

		$('ul.dropdown-list').css('display', 'none');

		// var zIndexNumber = 10000;
		// 		$('dl dd').each(function() {
		// 			$(this).css('z-index', zIndexNumber);
		// 			zIndexNumber -= 10;
		// 		});
		// 		$('.project-names li span').each(function() {
		// 			$(this).css('z-index', zIndexNumber);
		// 			zIndexNumber -= 10;
		// 		});
		// 		$('.project-names li').each(function() {
		// 			$(this).css('z-index', zIndexNumber);
		// 			zIndexNumber -= 10;
		// 		});
		// 		$('form p').each(function() {
		// 			$(this).css('z-index', zIndexNumber);
		// 			zIndexNumber -= 10;
		// 		});
		// 		$('form').each(function() {
		// 			$(this).css('z-index', zIndexNumber);
		// 			zIndexNumber -= 10;
		// 		});
		// 		$('div').each(function() {
		// 			$(this).css('z-index', zIndexNumber);
		// 			zIndexNumber -= 10;
		// 		});

		$('#colorbox, #cboxOverlay, #cboxWrapper').css('z-index', '12000');

		// $('p.hidden-form').next().each(function() {
		// 	if (!$(this).hasClass('displayed')) {
		// 		$(this).hide().children().css({ opacity: 0 });
		// 	}
		// });

		var $theSlider;
		var $theLink;
		var inMotion = false;
		var toAppend = '';
		$('.project-form').css('display', 'none');
		var $projectDropdown = $('.project-dropdown');
		$projectDropdown.remove().appendTo('#content-wrapper');
		$('.project-dropdown .displayed').css('display', 'block');

		$('p.hidden-form').next().each(function () {
			if (!$(this).hasClass('displayed')) {
				$(this).children().css('opacity', '0');
			};
		});

		$('p.hidden-form a').click(function () {
			$theLink = $(this);
			$theSlider = $(this).parent().next();

			if (inMotion === true) {
				return false;
			} else {
				inMotion = true;
				if ($theLink.hasClass('selected')) {
					$theLink.removeClass('selected');
				} else {
					$theLink.addClass('selected');
				};

				if ($theSlider.hasClass('displayed')) {
					$theLink.removeClass('selected');
					$theSlider.children().stop().animate({
						opacity: 0
					}, 150, function () {
						$theSlider.slideUp(500, function () {
							inMotion = false;
						});
						$theSlider.removeClass('displayed');
						$theLink.removeClass('selected');
					});
				} else {
					$theLink.addClass('selected');
					inMotion = false;
					$theSlider.slideDown(500, function () {
						$(this).children().stop().animate({
							opacity: 1
						}, 500, function () {
							$theSlider.addClass('displayed');
							$theLink.addClass('selected');
						});
					});
				};
			}
			return false;
		});

		$('.project-dropdown').hide();
		$manageProjectLink.click(function () {
			var wrapOffset = $contentWrapper.offset();
			var offset = $manageProjectLink.offset();
			var dropdownLeft = (offset.left + 15) - (wrapOffset.left + $('#manage-project-dropdown').width());
			var dropdownTop = (offset.top + $manageProjectLink.height());
			$('.project-dropdown').hide();
			$('.project-dropdown .dropdown-list').css('display', 'none');
			$('#manage-project-dropdown').css({ 'left': dropdownLeft, 'top': dropdownTop }).slideDown();
			$('#folioDesignID').addClass('hidden');
		});

		$addProjectLink.click(function () {
			var wrapOffset = $contentWrapper.offset();
			var offset = $addProjectLink.offset();
			var dropdownLeft = (offset.left + 15) - (wrapOffset.left + $('#add-project-dropdown').width());
			var dropdownTop = (offset.top + $addProjectLink.height());
			$('.project-dropdown').hide();
			$('.project-dropdown .dropdown-list').css('display', 'none');
			$('#add-project-dropdown').css({ 'left': dropdownLeft, 'top': dropdownTop }).slideDown();
			$('#folioDesignID').addClass('hidden');
		});

		$styleDescriptionLink.click(function () {
			var wrapOffset = $contentWrapper.offset();
			var offset = $styleDescriptionLink.offset();
			var dropdownLeft = (offset.left + 15) - (wrapOffset.left + $('#style-description-dropdown').width());
			var dropdownTop = (offset.top + $styleDescriptionLink.height());
			$('.project-dropdown').hide();
			$('.project-dropdown .dropdown-list').css('display', 'none');
			$('#style-description-dropdown').css({ 'left': dropdownLeft, 'top': dropdownTop }).slideDown();
			$('#folioDesignID').removeClass('hidden');
		});

		$manageDesignLink.click(function () {
			var wrapOffset = $contentWrapper.offset();
			var offset = $manageDesignLink.offset();
			var dropdownLeft = (offset.left + 15) - (wrapOffset.left + $('#manage-design-dropdown').width());
			var dropdownTop = (offset.top + $manageDesignLink.height());
			$('.project-dropdown').hide();
			$('div#manage-design-dropdown').css({ 'left': dropdownLeft, 'top': dropdownTop }).slideDown();
			$('#folioDesignID').removeClass('hidden');
		});
		$('.project-dropdown .close-dropdown').click(function () {
			$('.project-dropdown').slideUp();
			$('#folioDesignID').removeClass('hidden');
		});



		/*
		$('div.dropdown-list-container').click(function() {
		$(this).find('ul.dropdown-list').slideDown();
		});*/






		var $curDropdownItem;


		$('.design-dropdown').click(function (e) {
			// $('.project-dropdown').hide();
			if (!$(e.target).is('div.dropdown-list-container p')) {
				if ($(e.target).is('ul.dropdown-list li')) {
					$curDropdownItem = $(this).find('p');
					$curDropdownItem.html($(e.target).html());
				}
				$(this).find('ul.dropdown-list').slideUp();
			};
		});



		$('ul.dropdown-list li').hover(
			function () {
				$(this).css('background-color', '#efefef');
				$(this).css('cursor', 'pointer');
			},
			function () {
				$(this).css('background-color', '#fff');
			}
		);

		$('.dropdown-list-container').hover(function () {
			$(this).css('cursor', 'pointer');
		});


	},

	selectOptionTimeout: function () {

		var hideDelayTimer = null;
		var beingShown = false;
		var shown = false;
		var menuSpeed = 500;
		var hideDelay = 500;
		var $this;

		$('div.dropdown-list-container').each(function () {
			$(this).click(function () {
				if (hideDelayTimer) clearTimeout(hideDelayTimer);
				if (beingShown || shown) {
					$(this).find('ul.dropdown-list').slideUp(menuSpeed, function () {
						shown = false;
					});
				} else {
					// reset position of info box
					beingShown = true;

					$(this).find('ul.dropdown-list').slideDown(menuSpeed, function () {
						beingShown = false;
						shown = true;
					});
				}
				return false;
			});


			$(this).find('ul.dropdown-list').mouseover(function () {
				if (hideDelayTimer) clearTimeout(hideDelayTimer);
				return false;
			});

			$(this).find('ul.dropdown-list').each(function () {
				$(this).mouseleave(function () {
					$this = $(this);
					if (hideDelayTimer) clearTimeout(hideDelayTimer);
					hideDelayTimer = setTimeout(function () {
						hideDelayTimer = null;

						$this.slideUp(menuSpeed, function () {
							shown = false;
						});

					}, hideDelay);

				});
			});


		});

	},

	kitchenPlannerLinks: function () {
		if ($('.kitchen-planner-link').length > 0) {
			$('.kitchen-planner-link').click(function () {
				var newwindow = window.open($(this).attr('href'), 'KitchenPlannerWindow');
				newwindow.focus();
				return false;
			});
		}
	},

	//
	// IdeaFolio Save/Remove
	//
	itemSaveRemoveConfig: function () {
		$('.tools-response').css('display', 'none');
		// save click event
		$("a.jsonSave").each(function () {
			$(this).bind('click', { URL: this.href, parentDivId: $(this).parent().attr("id"), itemId: $(this).attr("rel") + "-" + $(this).parent().attr("id"), action: "save" }, function (e) {
				var ctrl = $(this);
				var category = ctrl.attr('data-category');
				var name = ctrl.attr('data-name');
				/* GOOGLE ANALYTICS */
				mr.tracking.google.trackEvent('Products Saved', category, name);
				/* Save to IdeaFolio */
				merillat.itemSaveRemove(e);
			});
		});
		// remove click event
		$("a.jsonDelete").each(function () {
			$(this).bind('click', { URL: this.href, parentDivId: $(this).parent().attr("id"), itemId: $(this).attr("rel") + "-" + $(this).parent().attr("id"), action: "delete" }, merillat.itemSaveRemove);
		});
	},

	itemSaveRemove: function (event) {
		var gJsonURL = event.data.URL;

		var jsonArgs = {};
		jsonArgs['cacheBust'] = (new Date()).getTime();

		$.getJSON(gJsonURL, jsonArgs, function (data, status) {
			merillat.itemSaveRemoveResponse(data, status, event.data.parentDivId, event.data.itemId, event.data.action);
		});
		event.preventDefault();
	},

	itemSaveRemoveResponse: function (data, status, parentDivId, itemId, action) {
		if (status == "success") {
			if (data.Success == true) {
				$("#" + parentDivId).children(".jsonSave").toggle();
				$("#" + parentDivId).children(".jsonDelete").toggle();
				merillat.parentNeedsPositionStart(parentDivId);
				$("#" + parentDivId).children(".tools-response").eq(0).html(data.Message).fadeIn('slow');
				window.setTimeout(function () {
					$("#" + parentDivId).children(".tools-response").eq(0).fadeOut('slow', function () { $("#" + parentDivId).children(".tools-response").eq(0).html(''); merillat.parentNeedsPositionEnd(parentDivId); });
				}, 2500);

			} else {
				merillat.parentNeedsPositionStart(parentDivId);
				$("#" + parentDivId).children(".tools-response").eq(0).html(data.ErrorMessage).fadeIn('slow');
				window.setTimeout(function () {
					$("#" + parentDivId).children(".tools-response").eq(0).fadeOut('slow', function () { $("#" + parentDivId).children(".tools-response").eq(0).html(''); merillat.parentNeedsPositionEnd(parentDivId); });
				}, 2500);

				if (data.HasMaxAnonItems) {
					$.fn.colorbox({
						iframe: true, inline: false, href: '/ideafolio/not-logged-in.html', width: 500, height: 300, open: true
					});
				}
			}
		} else {
			$("#" + parentDivId).children(".tools-response").eq(0).html("An error has occurred.").fadeIn('slow');

		}
	},

	parentNeedsPositionStart: function (obj) {
		console.log(obj);
		if ($("#" + obj).hasClass('needs-position-adjusted')) {
			$("#" + obj).css({ 'position': 'relative' });
		};
	},

	parentNeedsPositionEnd: function (obj) {
		if ($("#" + obj).hasClass('needs-position-adjusted')) {
			$("#" + obj).css({ 'position': 'static' });
		};
	},

	skinCheckboxes: function () {
		$('label input.checkbox').wrap('<span class="checkbox-skin"></span>');
		$('label input.checkbox').css({
			'opacity': '0',
			'position': 'absolute',
			'left': '0',
			'top': '0'
		});
		$('label span.checkbox-skin').parent().addClass('checkbox-label');
		// $('label.checkbox-label').click(function() {
		// 			//alert('yep');
		// 			$(this).children('input.checkbox').checked = true;
		// 		});


		// $('label.checkbox-label').click(function() {
		// 			$(this).children('input.checkbox').click();
		// 			//console.log('yep');
		// 			//return false;
		// 		});
		// $('label.checkbox-label').click(function() {
		// 			$('span.checkbox-skin input.checkbox').each(function() {
		// 				if($(this).hasClass('checked')){
		// 					$(this).parent().css({
		// 						'background-position': '0 -14px'
		// 					});
		// 				}else if($(this).hasClass('disabled')){
		// 					$(this).parent().css({
		// 						'background-position': '0 -28px'
		// 					});
		// 				}else{
		// 					$(this).parent().css({
		// 						'background-position': '0 0'
		// 					});
		// 				}
		// 			});
		// 		});

	},

	setCurrentNavHighlight: function () {
		var myFolder = $curURL.split('/', 8);
		var bgOffset;

		var currentPath = $('html').hasClass('espanol') ? myFolder[7] : myFolder[3];
		if (currentPath != "") {
			switch (currentPath) {
				case 'inspiration-design': bgOffset = '0 -27px'; break;
				case 'door-styles-accessories': bgOffset = '-176px -27px'; break;
				case 'plan-your-space': bgOffset = '-352px -27px'; break;
				case 'where-to-buy': bgOffset = '-528px -27px'; break;
				case 'customer-support': bgOffset = '-704px -27px'; break;
			};
			$('ul#main-nav a#' + currentPath).css({ 'background-position': bgOffset });
		}

	},

	setFilteringSwatchBehaviour: function () {
		$('label.large-swatch').prepend('<span class="large-swatch-hover-active"></span>');
		$('span.large-swatch-hover-active').css({ 'display': 'none' });
		$('label.large-swatch').hover(
			function () {
				if (!$(this).hasClass('disabled')) {
					$(this).find('span.large-swatch-hover-active').css({ 'display': 'block' });
				};
			},
			function () {
				if (!$(this).hasClass('checked')) {
					$(this).find('span.large-swatch-hover-active').css({ 'display': 'none' });
				};
			}
		);
	},

	setTrademarkStyles: function () {
		//var $searchedText = $('h1, h2, h3, h4, h5, h6, p, span, a, blockquote, div, ul, li, ol').text().replace('®', '<span>®</span>');
	},

	removeFlashFromClosingIframe: function () {
		$().bind('cbox_cleanup', function () {
			$('#cboxIframe').contents().find('object, embed').remove();
		});
	},

	setupOffersPromotions: function () {

		$('#offers-promotions-bar, #main-wrapper').css({
			'position': 'relative',
			'top': '-49px'
		});
		$('#offers-promotions-link a').click(function () {
			$('#offers-promotions-bar, #main-wrapper').animate({ 'top': '0' });
			return false;
		});
		$('#offers-promotions-bar #close-link a').click(function () {
			$('#offers-promotions-bar, #main-wrapper').animate({ 'top': '-49px' });
			return false;
		});
		$('.button-replaced-container button').css({
			height: '5px',
			width: '5px',
			border: '0 none'
		});
		$('#offers-promotions-bar .txt-input-container .text').click(function () {
			if ($(this).val() === "Email address") {
				$(this).val('');
			}
		});
		$('#offers-promotions-bar .txt-input-container .text').focus(function () {
			if ($(this).val() === "Email address") {
				$(this).val('');
			}
		});
		$('#offers-promotions-bar .txt-input-container .text').blur(function () {
			if ($(this).val().length === 0) {
				$(this).val('Email address');
			}
		});

		$('#offers-promotions-bar .main-wrapper').append('<p class="thanks" style="display: none; font-size: 18px; font-weight: bold; position: relative; top: 14px; color: white;">Thanks! <span class="thanks" style="font-weight: normal;">You&rsquo;re signed up to receive our offers and promotions!</span></p> <p class="error" style="display: none; font-size: 18px; font-weight: bold; position: relative; top: 14px; color: white;">Sorry. <span class="error" style="font-weight: normal; color: white;">There seems to be an error processing your request. Please try again later.</span></p>');

		//Setup click event for submit button
		$('#offers-promotions-form').bind('submit', merillat.offersPromotionsClick);
	},

	/*
	* Click handler for the offers and promotions form submit.
	*/
	offersPromotionsClick: function () {

		/* GOOGLE ANALYTICS */
		mr.tracking.google.trackEvent('Emails', 'Signup', 'Email Updates');

		var hideShowOffersDelayTimer = null;
		if ($('#offers-promotions-form').valid()) {
			$('.button-container .button-replaced-container').hide();
			$('#offers-promotions-bar .button-container').css({
				'background': 'transparent url(/images/gui/bg/offers-submitting.gif) no-repeat 0 0',
				'width': '110px',
				'height': '32px',
				'position': 'relative',
				'top': '-4px'
			});
			$('#offers-promotions-bar .txt-input-container input').attr('disabled', 'disabled');
			var jsonArgs = {};
			jsonArgs['promotion_email'] = $('#promotion_Email').val();
			jsonArgs['nocache'] = (new Date()).getTime();

			$.getJSON($('#offers-promotions-form').attr('action'), jsonArgs, function (data, status) {
				if (data.Success) {
					$('#offers-promotions-bar .main-wrapper *').not('.error').hide();
					$('#offers-promotions-bar .main-wrapper .thanks').show();
					hideShowOffersDelayTimer = setTimeout(function () {
						hideShowOffersDelayTimer = null;
						$('#offers-promotions-bar, #main-wrapper').animate({ 'top': '-49px' }, 200, function () {
							$('#offers-promotions-bar .main-wrapper *').show();
							$('#offers-promotions-bar .main-wrapper .thanks, #offers-promotions-bar .main-wrapper .error').hide();
							$('#offers-promotions-bar .button-container').css({
								'background': 'none',
								'width': 'auto',
								'height': 'auto',
								'position': 'relative',
								'top': '1px'
							});
							$('#offers-promotions-bar .txt-input-container input').attr('disabled', '');
						});
					}, 1200);

				} else {
					$('#offers-promotions-bar .main-wrapper *').not('.close').hide();
					$('#offers-promotions-bar .main-wrapper .error').show();
					hideShowOffersDelayTimer = setTimeout(function () {
						hideShowOffersDelayTimer = null;
						$('#offers-promotions-bar, #main-wrapper').animate({ 'top': '-49px' }, 200, function () {
							$('#offers-promotions-bar .main-wrapper *').show();
							$('#offers-promotions-bar .main-wrapper .error, #offers-promotions-bar .main-wrapper .thanks').hide();
							$('#offers-promotions-bar .button-container').css({
								'background': 'none',
								'width': 'auto',
								'height': 'auto',
								'position': 'relative',
								'top': '1px'
							});
							$('#offers-promotions-bar .txt-input-container input').attr('disabled', '');
						});
					}, 1200);

				}
			});
		}
		return false;
	},

	/*
	* handler to highlight search terms globally on the page.
	*/
	highlightSearchTerms: function () {
		var getUrlParam = function (name) {
			var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.search);
			if (!results) { return ''; }
			return results[1] || '';
		};

		var searchTerm = decodeURIComponent(getUrlParam('query'));
		if (searchTerm && searchTerm != '') {
			searchTerm = searchTerm.replace(/\+/g, ' ');

			$(document).SearchHighlight({
				style_name: 'searchhighlight',
				exact: 'whole',
				style_name_suffix: false,
				keys: searchTerm,
				min_length: 3,
				highlight: '#content-wrapper',
				nohighlight: '.search-phrase, select option'
			});
		}
	},

	/*
	* Setup colorbox for Send to Phone
	*/
	setupSendToPhone: function () {
		$('.send-to-phone').colorbox({ iframe: true, width: '800px', height: '520px' });
	},

	/*
	* Masthead animations
	*/
	animateMasthead: function () {
		if ($('div.masthead-content').length) {
			var $mhc = $('.masthead-content'),
					$text = $('.masthead-text'),
					$mh = $('.masthead');

			if ($('.masthead').hasClass('left')) {
				$mhc.css({ left: -388 });
				$text.hide();

				setTimeout(function () {
					$mhc.animate({ left: -3 }, 500, 'swing', function () {
						$text.fadeIn(750);
					});
				}, 1000);
			}
			else {
				$mhc.css({ right: -388 });
				$text.hide();

				setTimeout(function () {
					$mhc.animate({ right: 0 }, 500, 'swing', function () {
						$text.fadeIn(750);
					});
				}, 1000);
			}
		}
	},

	ctaBox: function () {
		$('.cta-box').hoverIntent(function () {
			$(this).find('p,ul').slideDown(300, 'easeInOutCubic');
		},
		function () {
			$(this).find('p,ul').hide(100);
		});
	},

	newProductFlag: function () {
		$('span.flag').remove();

		if ($('.hardware-item-wrapper').length) {
			$('div.new-product, a.new-product').each(function () {
				$(this).parent().prepend('<span class="flag">New</span>');
			});
		} else {
			$('div.new-product, a.new-product').each(function () {
				$(this).append('<span class="flag">New</span>');
			});
		}
	}
};

$(document).ready(function() {
	$('#video-wrapper ul li').each(function(){
		
		$(this).hover(
			function() {
				$(this).append('<img src="/images/pic/webisodes/freshfood/arrow-tip.png" style="right: -11px; top: 0px; position: absolute;"/>').stop();
					},
			function() {
				$(this).children('img').remove().stop();
					}
		);
			
	});
	$('#video-wrapper ul li.active').append('<img src="/images/pic/webisodes/freshfood/arrow-tip.png" style="right: -11px; top: 0px; position: absolute;"/>').each(function(){
	$(this).hover(
			function() {
				$(this).append('<img src="/images/pic/webisodes/freshfood/arrow-tip.png" style="right: -11px; top: 0px; position: absolute;"/>').stop();
					},
			function() {
				$(this).append('<img src="/images/pic/webisodes/freshfood/arrow-tip.png" style="right: -11px; top: 0px; position: absolute;"/>').stop();
					}
		);
		});
});
	

$(document).ready(function() {	
	merillat.setGlobals();	
	lib.addFormClasses();
	lib.inputDefault();
	lib.fileLinks();
//	merillat.setTrademarkStyles();
	merillat.signInSlider();
	merillat.setupSubNav();
	lib.externalLinks();
	merillat.myDealerSlider();
	merillat.viewSelector();
	merillat.setButtonStyles();
	merillat.loginConfig();
	merillat.logoutConfig();
	merillat.forgotPasswordConfig();
	merillat.styleSelectOptions();
	merillat.selectOptionTimeout();
	merillat.itemSaveRemoveConfig();
//	merillat.skinCheckboxes();
	merillat.setFilteringSwatchBehaviour();	
	merillat.activateCufon();
	merillat.setCurrentNavHighlight();
	merillat.kitchenPlannerLinks();
	merillat.setupOffersPromotions();
	merillat.removeFlashFromClosingIframe();
	merillat.highlightSearchTerms();
	merillat.animateMasthead();
	merillat.ctaBox();
});
