// This first section overrides ootb functions to prevent errors from not including the ootb js
function ProcessImn() { }
if (typeof WPSC === 'undefined') {
	WPSC = {
		Init: function() { },
		WebPartPage: {
			Parts: {
				Register: function() { }
			}
		}
	};
}
if (typeof UpdateFormDigest === 'undefined') {
	UpdateFormDigest = function() { };
}
if (typeof _spFormOnSubmitWrapper === 'undefined') {
	_spFormOnSubmitWrapper = function() { };
}

$(document).ready(function () {

	// ================================================================================
	// ================================================================================
	// SEARCH
	var trimWs = /(^\s+|\s+$)/gm,
		emptyString = '',
		txtSearch = $('input.search:first'),
		btnSearch = $('input.submitSearch:first'),
		searchEnabled = txtSearch.length && btnSearch.length && btnSearch.attr('src'),
		defaultSearch;
	if (searchEnabled) {
		defaultSearch = txtSearch.val() ? txtSearch.val().replace(trimWs, emptyString) : 'SEARCH';
		txtSearch.keypress(function (e) {
			var term;
			if (e.which == 13) {
				e.preventDefault();
				term = txtSearch.val().replace(trimWs, emptyString);
				if (term && defaultSearch.toLocaleLowerCase() != term.toLocaleLowerCase()) {
					location = btnSearch.attr('src') + '?k=' + encodeURIComponent(term);
				} else {
					return false;
				}
			}
		}).blur(function (e) {
			var term = txtSearch.val().replace(trimWs, emptyString);
			if (defaultSearch.toLocaleLowerCase() == term.toLocaleLowerCase()) {
				$(e.target).val(defaultSearch);
			} else {
				$(e.target).val(term);
			}
		});
		btnSearch.click(function (e) {
			var term = txtSearch.val().replace(trimWs, emptyString);
			if (defaultSearch.toLocaleLowerCase() != term.toLocaleLowerCase()) {
				location = btnSearch.attr('src') + '?k=' + encodeURIComponent(term);
			} else {
				e.preventDefault();
				return false;
			}
		});
	}

	// ================================================================================
	// ================================================================================
	// TOP NAVIGATION
	// If drop down item has a sub nav, don't do anything on click
	$('#mainNav > li > a.head, .level-0 > li > a').click(function () {
		if ($(this).parent().children('div').length) {
			return false;
		} else {
			return;
		}
	});

	// Add 'over' class on mouseover to all li with 'nav'
	$('#mainNav li').mouseover(function () {
		$(this).addClass('over');
	}).mouseleave(function () {
		$(this).removeClass('over');
	});

	// If on the product nav dropdown, open sub categories and highlighted items
	$("#productNav a").click(function () {
		if (this.id.length && $('ul.' + this.id + ' li').length) { // If this has children, a.k.a. has id 'in-workplace' etc.
			if ($(this).parent().parent().hasClass('col1')) { // If first col is clicked, remove active class from all second col items
				$('.col2 li').removeClass('active');
			}
			productNavSet(this); // Run actions on product nav
			return false;
		} else {
			return;
		}
	});

	// Dynamically set width of dropdowns if smaller than width of nav item for all browsers (dynamic min-width)
	$('#mainNav > li').each(function () {
		var $this = $(this);
		var liWidth = $this.outerWidth(true);
		if ($this.find('.navSubContainer').width() < liWidth) {
			$this.find('.navContent > ul').width(liWidth - 10);
		}
	});

	// Fix variable width in sub sub menues to always show up consistently (except in IE6)
	// NOTE: has to happen on hover becuase when subcontainers are 'display:none' javascript cannot get their widths
	$('#mainNav > li').hover(function () {
		if (isIE(6)) { } else {
			var thisSubContainerWidth = $(this).find('.navSubContainer .navContent').width() - 26;
			if (isIE(7)) {
				thisSubContainerWidth = thisSubContainerWidth + 7;
			}
			$(this).find('.navSubSubContainer').css('left', thisSubContainerWidth);
		}
	});


	// ================================================================================
	// ================================================================================
	// ACCORDIONS
	$('.contentCordion, #leftNav, .pageOptions').accordion();
	// Always default follow us page to have steelcase open
	$('.contentCordion .active').addClass('active').find('.contentSub').show();


	// ================================================================================
	// ================================================================================
	// SHOW COMMENT FORM
	var comments = $(".comments"),
		txt = comments.find('input:text, textarea'),
		thx = $(".commentThanks");
	if (!comments.hasClass('open')) {
		comments.hide();
	}
	$("a.showCommentForm").click(function () {
		txt.removeClass('error');
		txt.each(function () {
			$(this).val(this.defaultValue);
		});
		comments.slideToggle(1000);
		return false;
	});
	txt.focus(function (e) {
		$(e.target).removeClass('error');
	}).blur(function (e) {
		var $this = $(e.target);
		if ($this.val().length === 0 || $this[0].defaultValue.toLocaleLowerCase() === $this.val().toLocaleLowerCase()) {
			$this.addClass('error');
		}
	});
	comments.find('.submit').click(function () {
		// Ajax submit the form
		var obj = {
			question: $(txt[0]).val(),
			name: $(txt[1]).val(),
			email: $(txt[2]).val(),
			region: $(txt[3]).val(),
			url: location + emptyString
		};
		this.blur();
		txt.each(function () {
			$(this).blur();
		});
		if (txt.hasClass('error')) {
			return false;
		}
		$.ajax({
			type: 'POST',
			url: '/_vti_bin/steelcasebrand/quickfeedback.asmx/send',
			contentType: 'application/json; charset=utf-8',
			dataType: 'json',
			data: JSON.stringify(obj),
			success: function (data) {
				if (data.d.Success) {
					comments.slideUp(1000, function () {
						thx.slideDown(1000);
						setTimeout(function () {
							thx.slideUp(1000);
						}, 5000);
					});
				} else {
					for (var f = 0; f < data.d.InvalidFields.length; f++) {
						var elm = comments.find('.' + data.d.InvalidFields[f]);
						if (elm.length) {
							elm.val(elm[0].defaultValue);
							elm.addClass('error');
						}
					}
				}
			},
			error: function (xhr, status, err) {
				try {
					err = JSON.parse(xhr.responseText);
					alert(status + ': ' + err.Message);
				} catch (e) {
					alert(status + ': ' + xhr.statusText);
				}
			}
		});

		return false;
	});

	// ================================================================================
	// ================================================================================
	// PLUGINS
	// focus remove content, blur (if empty) add it back in
	var displayMode = $("#MSOSPWebPartManager_DisplayModeName").val();
	if (!displayMode || displayMode === "Browse") {
		$('form').focusMagic();
	}
	// this needs to be done after focusmagic
	if (searchEnabled && location.search && btnSearch.attr('src').toLocaleLowerCase() == location.pathname.toLocaleLowerCase()) {
		var matches = (/[\?&]k=([^&$]+)/).exec(location.search);
		if (matches.length > 0) {
			txtSearch.val(decodeURIComponent(matches[1]).replace(/\+/, ' '));
		}
	}

	// slides
	$('.sliderJS').slides({ containerWidth: 646 });
	$('.homePage .homeJS, .landingJS').slides({ containerWidth: 479, numOfSlideJump: 2 });
	$('.mediaPRHome .homeJS, .longTextHome .homeJS').slides({ containerWidth: 312, numOfSlideJump: 1 });

	// lightbox
	$('.lightbox').lightBox({ overlayOpacity: 0.8 });

	// lightbox with video
	$('.vidLightbox').click(function () {
		var thisClass = '.' + this.id;
		$('.vidlightbox-container-image').hide();

		// position
		$('#vidjquery-overlay').height($(document).height());

		// size
		var newHeight = $(thisClass).find('embed').attr('height') + 'px';
		var newWidth = $(thisClass).find('embed').attr('width') + 'px';

		$(thisClass).parent('#vidlightbox-container-image-box').height(newHeight).width(newWidth);
		$('#vidjquery-lightbox').css('top', $(window).scrollTop() + ($(window).height() / 10));

		$(window).resize(function () {
			$('#vidjquery-lightbox').css('top', $(window).scrollTop() + ($(window).height() / 10));
		});

		$(thisClass).show();

		$('#vidjquery-overlay, #vidjquery-lightbox').fadeIn(function () {
			$('#vidlightbox-secNav-btnClose').click(function () {
				$('#vidjquery-overlay, #vidjquery-lightbox').fadeOut();
				return false;
			});
		});
		return false;
	});

	// lightbox auto-pop when hash is included in gallery url from a tunnel link
	var sHash = document.location.hash;
	if (sHash && sHash.length > 1) {
		$("#ig-" + sHash.substr(1) + ":first.lightbox").click();
	}



	// ================================================================================
	// ================================================================================
	// HOMEPAGE
	// left rollovers
	$(".homeNav > li").hover(
		function () {
			$(this).addClass('over');
			$('.homeRollover').addClass('parent' + $(this).attr('class')).parent().addClass('over'); // Add current li class to 'homeRollover' and control bg images through CSS
		},
		function () {
			$(this).removeClass('over');
			$('.homeRollover').removeClass('parent' + $(this).attr('class')).removeClass('over').removeClass('parentover').parent().removeClass('over');
		}
	);
	// brand image swaps
	$('.ourBrands img').hide().filter('.for-none').show();
	$('.ourBrands a').mouseover(function () {
		$(this).closest('.homeContent').children('img').hide();
		$(this).closest('.homeContent').find('.for-' + this.id).show();
	}).mouseleave(function () {
		$(this).closest('.homeContent').children('img').hide();
		$(this).closest('.homeContent').find('.for-none').show();
	});

	// Home tunnels fade in / out
	$('.homeSlider ul.slider li div.overlay').hide();
	$('.homeSlider ul.slider li').mouseover(function () {
		$(this).children('div.overlay').show();
	}).mouseleave(function () {
		$(this).children('div.overlay').hide();
	});

	// ================================================================================
	// ================================================================================
	// PRODUCT PAGE
	// Main image scroll up info from image alt tag
	var imgAlt = $('.mainInfo img.mainImage').attr('alt');
	if (imgAlt) {
		$('.mainInfo .info').append('<div>' + imgAlt + '</div>');
	}

	// Show main image info on hover of 'i'
	$('.mainInfo .info img').mouseover(function () {
		$(this).next('div').animate({ top: 0 }, 'fast', 'easeOutQuint');
	}).mouseout(function () {
		$(this).next('div').animate({ top: '35px' }, 'fast', 'easeOutQuint');
	});

	// if text over image or image info has no text, hide.  If text over image has more than 70 characters, make text smaller
	var $vertText = $('.mainInfo .textOverImg .verticalText');
	var $info = $('.mainInfo .info div');
	// Main image info info
	if ($info.html() && $info.html().length > 0) { } else { $('.mainInfo .info').hide(); }
	// Text over image
	if ($vertText.html() && $vertText.html().length > 0) {
		if ($vertText.html().length < 70) {
			$vertText.css({ 'font-size': '18px', 'line-height': '25px' });
		}
	} else {
		$('.mainInfo .textOverImg').hide();
	}

	// ================================================================================
	// ================================================================================
	// GOOGLE ANALYTICS
	if (typeof _gaq !== 'undefined') {
		var urlBase = '',
		pageRegex = new RegExp("\\.aspx|\\.asp|\\.htm|\\.html|\\.shtm|\\.shtml", "i"),
		jsRegex = new RegExp("^javascript:", "i"),
		mailtoRegex = new RegExp("^mailto:(.+)", "i"),
		hostRegex = new RegExp("^" + document.location.hostname + "|^(?:dev\\.www\\.|www\\.)?steelcase.(?:.{2}|com|co\\.uk)", "i"),
		validAs = $.grep($("a"), function (item, i) {
			return (item.protocol.length > 0 && !jsRegex.test(item.protocol)) &&
				  ((item.protocol.length > 0 && mailtoRegex.test(item.href)) ||
				   (item.hostname.length > 0 && !hostRegex.test(item.hostname)) ||
				   (item.hostname.length > 0 && hostRegex.test(item.hostname) && !pageRegex.test(item.pathname)));
		});
		$(validAs).click(function (e) {
			var m, path = "";
			var file = /([^\/]+)$/.exec(this.href);
			var fileName = "";
			if (file != null) {
				fileName = file[1];
			}
			if (jsRegex.test(this.href)) {
				// do nothing to not track these
			} else if ((pageRegex.test(this.pathname) ||
						this.pathname == "" ||
						fileName == "") &&
						hostRegex.test(this.hostname)) {
				// do nothing to not track these
			} else if ((m = mailtoRegex.exec(this.href)) != null) {
				path = "/mailto/" + m[1];
			} else if (!hostRegex.test(this.hostname)) {
				path = "/outgoing/" + this.href.substr(this.protocol.length + 2);
			} else if (this.pathname) {
				path = (this.pathname.length > 0 && this.pathname[0] === '/') ? this.pathname : '/' + this.pathname;
			}
			if (path.length > 0) {
				path = path.toLowerCase();
				_gaq.push(["_trackPageview", path]);
			}
		});
	}


	// ================================================================================
	// ================================================================================
	// FUNCTIONS
	function isIE(vers) {
		var IE = $.browser.msie;
		var browserVersion = parseInt($.browser.version, 10);

		if (vers) {
			if (vers == 6) {
				return (IE && browserVersion == 6) ? true : false;
			} else if (vers == 7) {
				return (IE && browserVersion == 7) ? true : false;
			} else if (vers == 8) {
				return (IE && browserVersion == 8) ? true : false;
			}
		} else {
			return (IE) ? true : false;
		}
	}

	function productNavSet(value) {
		var $selectedLink = $(value),
			$id = $selectedLink.attr('id'); // Grab the ID for the selected link (used for setting active parent)

		if ($id.length > 0) {
			// The newly displayed ul / div.highlighted
			var $activeUL = $('.' + $selectedLink.attr('id'));

			// Show / Hide / activate / deactivate elements
			$selectedLink.parent().addClass('active').siblings().removeClass('active');
			$activeUL.siblings().not('.col1').hide();
			$activeUL.show();
			$selectedLink.parent().parent().show();

			// Account for .col1 with classes we set during load (in if(load==true))
			$('.col1 a.' + $id).parent().addClass('active').siblings().removeClass('active');
		}
	}
});