var productInfoIcons = {
	init : function () {
		$('.product-info-icons a img').bind('mouseenter', $.proxy( productInfoIcons.hover, this ) );
	},
	hover : function (event) {
		elem = event.target;
		$(elem).parent().addClass('hover-active');
		$(elem).stop(true, true).addClass('active')
		.animate({top: -10, left: -35, width: 148}, {
			duration: 250,
			easing: 'swing',
			queue: true,
			complete:function() {

			}
		}).mouseout(function() {
			$(this).parent().removeClass('hover-active');
			$(this).animate({top: 0, left: 0, width: 78}, {
				duration: 250,
				easing: 'swing',
				queue: true,
				complete:function() {
					$(this).removeClass('active');
				}
			})
		});
	}

}

var qeTool = {
	base: document.getElementsByTagName('base')[0].href,
	action : 'rest/quickEstimate',
	init : function () {
		var self = this;
		$('#quick-estimate-launch').removeAttr('onclick')
		.click(function(e) {
			e.preventDefault();
			self.launch();
		});
	},
	launch : function () {
		var self = this;
		$.get(self.base + 'rest/quickEstimate', function (data) {
			self.show(data);
		});
	},
	show : function (html) {
		var self = this;
		$('body').prepend('<div class="popup-overlay">&nbsp;</div><div class="popup-container  popup-iframe-container"><div class="popup-wrapper"><div class="popup-window"><a href="#" id="popup-close">Close</a><div class="popup-window-content">' + html + '</div></div></div><div class="overlay-close-pane"></div></div>');
		$('.popup-overlay, .popup-container').css({display: 'block'});
		var windowHeight = $(window).height();
		var totalHeight = $('#page').height();
		if (windowHeight < totalHeight) {
			totalHeight = totalHeight + 44;
		}
		$('.popup-wrapper').css({top : $(window).scrollTop() + 50});
		$('.popup-overlay, .popup-container').css({height: totalHeight + 'px'});


		$('#quick-estimate-help-text').html(qeToolHelpHTML).parent().hide();
		if(qeToolSubmitBtnText) {
			$('#qe-submit-button .btnMiddle .text').html(qeToolSubmitBtnText);
		}
		if(qeToolReturnBtnText) {
			$('#qe-form-return .btnMiddle .text').html(qeToolReturnBtnText);
		}

		$('.popup-overlay').animate({opacity: .7}, 300, "swing", function() {
			$('.popup-container').animate({opacity: 1}, 300, "swing", function() {
				self.activateForm();
				$('#popup-close, .overlay-close-pane').click(function(e) {
					e.preventDefault();
					self.closeOverlay();
				});
			});
		});
	},
	closeOverlay: function() {
		$('.popup-container').animate({opacity: 0}, 200, "swing", function() {
			$('.popup-overlay').animate({opacity: 0}, 200, "swing", function() {
				$('.popup-overlay').remove();
				$('.popup-container').remove();
			});
		});
	},
	activateForm : function () {
		var self = this;
		var formHeight = $('#qe-tool-form').height();
		$('#quick-estimate-help-wrapper').css({height : formHeight, overflow : 'hidden'});

		$('#qe-tools-agree').change(function() {
			if($(this).attr('checked')) {
				$('#qe-submit-button').removeClass('dynamicGreyButton');
			} else {
				$('#qe-submit-button').addClass('dynamicGreyButton');
			}
		});

		$('#quick-estimate-help-launch').removeAttr('onclick').click(function(e) {
			e.preventDefault();
			$('#quick-estimate-help-tool').show();
			$('#qe-tool-form').stop(true, true)
			.css({overflow: 'hidden'})
			.animate({height: 0}, {
				duration : 500,
				easing : 'swing'
			});
		});

		$('#qe-form-return').removeAttr('onclick').click(function(e) {
			e.preventDefault();
			$('#qe-tool-form').stop(true, true)
			.animate({height: formHeight}, {
				duration : 500,
				easing : 'swing',
				complete : function () {
					$('#quick-estimate-help-tool').hide();
				}
			});
		});

		$('#qe-submit-button').removeAttr('onclick')
		.click(function(e) {
			e.preventDefault();
			if(!$('#qe-tools-agree').attr('checked')) {
				alert('please agree to the terms!!');
				$('.disc-row label').css({color: '#CC0000', 'font-weight' : 'bold'});
			} else {
				$.get(self.base + self.action, $('#qe-tool-form').serialize(), function(data, textStatus) {
					if(textStatus === 'success') {
						calc = $('response', data).attr('calculation');
						self.closeOverlay();
						$('input#linealMetres').val(calc);
						updateQuantity('lineal');
						updatePrice();
					} else {
						alert('Quick Estimate Tool Unavailable, please try again later, or contact Onlinecarpet');
					}
				});
			}
		});
	}
}

var dropDownNav = {
	fadeInDuration : 250,
	init: function() {
		$primaryNavList = $('.primaryNavigationInner ul');
		totalItems = $('.main-level', $primaryNavList).length;

		$('.dropdownNav', $primaryNavList).css({
			display: 'none',
			opacity: 0
		});
		dropDownNav.enableHover();
	},
	enableHover: function() {
		$('.main-level', $primaryNavList).mouseenter(function() {
			dropDownNav.showNavItem($('li.main-level', $primaryNavList).index($(this)));
		});
		$primaryNavList.mouseleave(function() {
			$('li.main-level .dropdownNav', $primaryNavList).css({
				opacity: 0,
				display: 'none'
			});
			$('li.main-level a.main-level-link', $primaryNavList).removeClass('main-level-link-active');
		});
	},
	showNavItem: function(index) {
		$('li.main-level .dropdownNav').stop(true, true).css({
			opacity:0,
			display: 'none'
		});
		$('li.main-level a.main-level-link').removeClass('main-level-link-active');
		$('li.main-level:eq(' + index + ') a.main-level-link').addClass('main-level-link-active');
		$('li.main-level:eq(' + index + ') .dropdownNav', $primaryNavList).css({
			display: 'block'
		}).animate({
			opacity: 1
		}, {
			duration: dropDownNav.fadeInDuration,
			queue: true
		});
	}
}

var dropDownSubNav = {
	fadeInDuration : 250,
	init: function() {
		$subNavList = $('ul.secondaryNav');
		totalItems = $('.main-level', $subNavList).length;

		$('.dropdownNav', $subNavList).css({
			display: 'none',
			opacity: 0
		});
		dropDownSubNav.enableHover();
	},
	enableHover: function() {
		$('.main-level', $subNavList).mouseenter(function() {
			dropDownSubNav.showNavItem($('li.main-level', $subNavList).index($(this)));
		});
		$subNavList.mouseleave(function() {
			$('li.main-level .dropdownNav', $subNavList).css({
				opacity: 0,
				display: 'none'
			});
			$('li.main-level a.main-level-link', $subNavList).removeClass('main-level-link-active');
		});
	},
	showNavItem: function(index) {
		$('li.main-level .dropdownNav', $subNavList).stop(true, true).css({
			opacity:0,
			display: 'none'
		});
		$('li.main-level a.main-level-link', $subNavList).removeClass('main-level-link-active');
		$('li.main-level:eq(' + index + ') a.main-level-link', $subNavList).addClass('main-level-link-active');
		$('li.main-level:eq(' + index + ') .dropdownNav', $subNavList).css({
			display: 'block'
		}).animate({
			opacity: 1
		}, {
			duration: dropDownSubNav.fadeInDuration,
			queue: true
		});
	}
}

var trims = {
	init : function() {
		var self = this;

		self.$trims = $('#trims');
		self.$trimDescription = $('#trim-description');
		self.$trimLink = $('#trim-detail-link');
		self.$trimCloseLink = $('.trim-close', self.$trims);
		self.$inputTrigger = $('#additionalItems_7');

		self.$trimLink.hide();
		self.$trims.css({
			opacity: 0
		});

		self.$inputTrigger.change(function() {
			if(Number($(this).attr('value')) > 0) {
				self.$trimLink.show();
			}
		})

		self.$trimLink.removeAttr('onclick').click(function(e) {
			e.preventDefault();
			self.showTrims();
		});
		self.$trimCloseLink.click(function(e) {
			e.preventDefault();
			if($(this).attr('id') === 'trim-close') {
				self.hideTrims(false);
			} else {
				self.hideTrims(true);
			}
		});

		$('#trim-title', self.$trims).keypress(function(e) {
			if (e.keyCode === 13) {
				e.preventDefault();
				self.updateTrims($(this).attr('value'));
				self.hideTrims(true);
			}
		});

		self.enableTrims();
	},
	enableTrims : function() {
		var self = this;
		$('input.trim-radio-select', self.$trims).change(function() {
			if($('.standardButton', self.$trims).is(':hidden')) {
				$('.standardButton', self.$trims).show();
			}
			if($(this).attr('id') === 'trim-other') {
				self.updateTrims($('#trim-title', self.$trims).attr('value'));
				$('#trim-title', self.$trims).change(function() {
					self.updateTrims($(this).attr('value'));
				});
			} else {
				self.updateTrims($('label strong', $(this).parent()).html());
			}
		});
		$('#trim-title', self.$trims).focus(function() {
			$('#trim-other').attr('checked', true);
		});
	},
	updateTrims : function(text) {
		var self = this;
		self.$trimDescription.html(text);
	},
	showTrims : function () {
		var self = this;
		self.$trims.css({
			display: 'block',
			top: ($(window).scrollTop())
			}).animate({
			opacity: 1
		} , {
			duration: 500,
			queue: true,
			easing: 'swing'
		});
	},
	hideTrims : function (validate) {
		var self = this;
		self.$trims.stop(true, true);
		if($('#trim-other', self.$trims).attr('checked') && $('#trim-title', self.$trims).attr('value') === '' && validate === true) {
			$('.description-highlight', self.$trims).css({
				color: '#CC0000',
				'font-weight' : 'bold'
			});
		} else {
			self.$trims.animate({
				opacity: 0
			} , {
				duration: 750,
				easing: 'swing',
				queue: true,
				complete: function() {
					self.$trims.css({
						display: 'none'
					});
				}
			});
		}
	}
}

$(document).ready(function() {
	if($('.product-info-icons').length) {
		productInfoIcons.init();
	}

	if ($('.primaryNavigationInner .dropdownNav').length > 0) {
		dropDownNav.init();
	}
	if ($('.secondaryNav .dropdownNav').length > 0) {
		dropDownSubNav.init();
	}
	if ($('#trims').length > 0) {
		trims.init();
	}

	if($('.result-image-container').length) {
		$('.result-image-container').click(function(e) {
			$parentContainer = $(this).parents('.result-images');
			location.href =  document.getElementsByTagName('base')[0].href + $('.result-image-controls a.productLink', $parentContainer).attr('href');
		});
	}

	if($('#flagContactTenant').length) {
		$('#flagContactTenant').change(function() {
			if($(this).attr('checked')) {
				$('li.contact-tenant-field').show();
			} else {
				$('li.contact-tenant-field').hide();
			}
		});

		if($('#flagContactTenant').attr('checked')) {
			$('li.contact-tenant-field').show();
		} else {
			$('li.contact-tenant-field').hide();
		}
	}

	if($('#quick-estimate-launch').length) {
		qeTool.init();
		}

	if($('#service-areas').length) serviceAreas.init();

	if ($('.primaryNavigationInner li:first').hasClass('selected')) {
		$('.leftEdge').addClass('selectedLeftEdge');
	} else if ($('.primaryNavigationInner li:last').hasClass('selected')) {
		$('.primaryNavigationInner li:last').css({
			'padding-right': '20px'
		});
		$('.rightEdge').addClass('selectedRightEdge');
	}
	if ($('.formBackBtn').length == 0) {
		if ($('.paymentSuccessWrapper').length == 0) {
			$('.contentHeader').append('<a class="genericBackLink" href="#" onclick="javascript: history.back(); return false;">&lt; Back</a>');
		}
	}
	$('.dynamicButton').each(function() {
		if (!$(this).hasClass('standardButton')) {
			$(this).addClass('standardButton');
			buttonText = $(this).html();
			buttonWidth = $(this).width();
			$(this).html('<span class="btnLeft"></span><span class="btnMiddle">' + buttonText + '<span class="arrows">&#160;&#187;</span></span><span class="btnRight"></span>');
		}
	});

	CompareList.init();

	if (window.location.hash == '#login-popup') {
		$('#headerClientLogin').click();
	}
});

var CompareList = {
	cookieName: "rangeCompareIds",
	baseHref: document.getElementsByTagName('base')[0].href,
	ajaxUrl: 'rest/rangeCompareUpdate',
	total: 0,
	init: function() {
		$compareNavItem = $('#compareNavItem a');
		$compareButton = $('#compareAdd');
		this.total = this.getRangeIds().length;
		if ($compareButton.length) {
			$compareButton.click(function(e) {
				e.preventDefault();
				CompareList.toggleRange($(this).attr('href'));
			});
			this.updateButton();
		}
		this.updateNav();
		$compareButton.css({
			display: 'block'
		});
		$compareNavItem.click(function(e) {
			e.preventDefault();
			CompareList.launchComparisonWindow();
		});
		if ($('.product-compare-add').length) {
			$('.product-compare-add').click(function(e) {
				e.preventDefault();
				CompareList.toggleRange($(this).attr('href'), $(this));
			});
			$('.product-compare-add').each(function() {
				CompareList.updateButton($(this));
			});

		}
	},
	getRangeIds: function() {
		var rangeIds = unescape(readCookie(this.cookieName));
		if (rangeIds !== null && rangeIds !== "null") {
			rangeIds = rangeIds.split(',');
		} else {
			rangeIds = [];
		}
		return rangeIds;
	},
	getRangeStatus: function(rangeId) {
		rangeIds = this.getRangeIds();
		this.total = rangeIds.length;
		for (var i = 0, length = this.total; i < length; i++) {
			if (parseInt(rangeIds[i]) == parseInt(rangeId)) return true;
		}
		return false;
	},
	addRange: function(rangeId, $clickedObj) {
		$.get(CompareList.baseHref + CompareList.ajaxUrl, {
			'addRangeId': rangeId
		}, function() {
			CompareList.updateButton($clickedObj);
		});
	},
	removeRange: function(rangeId, $clickedObj) {
		$.get(CompareList.baseHref + CompareList.ajaxUrl, {
			'removeRangeId': rangeId
		}, function() {
			CompareList.updateButton($clickedObj);
		});
	},
	toggleRange: function(rangeId, $clickedObj) {
		if (CompareList.getRangeStatus(rangeId)) {
			CompareList.removeRange(rangeId, $clickedObj);
		} else {
			CompareList.addRange(rangeId, $clickedObj);
		}
	},
	updateNav : function () {
		if (this.getRangeIds().length) {
			$('span', $compareNavItem).html(' (' + this.getRangeIds().length + ')');
		} else {
			$('span', $compareNavItem).html('');
		}
	},
	updateButton : function ($clickedObj) {
		if ($clickedObj) {
			if (CompareList.getRangeStatus($clickedObj.attr('href'))) {
				$clickedObj.addClass('added').html('Remove from list');
			} else {
				$clickedObj.removeClass('added').html('Add to compare list');
			}
		} else {
			if (CompareList.getRangeStatus($compareButton.attr('href'))) {
				$compareButton.addClass('added').html('Remove from compare list');
			} else {
				$compareButton.removeClass('added').html('Add to compare list');
			}
		}
		this.updateNav();
	},
	launchComparisonWindow: function() {
		var windowWidth = screen.width * .75;
		var windowHeight = screen.height * .75;
		var windowTop = (screen.height - windowHeight) / 2;
		var windowLeft = (screen.width - windowWidth) / 2;
		var compareWindow = window.open(this.baseHref + 'carpet-comparison', 'Compare', 'location=no, menubar=no, resizable=yes, scrollbars=yes, toolbar=no, width=' + windowWidth + ', height=' + windowHeight + ', top=' + windowTop + ', left=' + windowLeft);
		compareWindow.focus();
	}
};

function popupWindow(url, name, attributes) {
	var newWindow = window.open(url, name, attributes);
	newWindow.focus();
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for (var i = 0; i < ca.length; i++) {
		var c = ca[i];
		while (c.charAt(0) == ' ') c = c.substring(1, c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
	}
	return null;
}

//Extend jQuery to include new easing equations
jQuery.easing['jswing'] = jQuery.easing['swing'];
jQuery.extend(jQuery.easing,
{
	def: 'easeOutQuad',
	swing: function (x, t, b, c, d) {
		//alert(jQuery.easing.default);
		return jQuery.easing[jQuery.easing.def](x, t, b, c, d);
	},
	easeInQuad: function (x, t, b, c, d) {
		return c * (t /= d) * t + b;
	},
	easeOutQuad: function (x, t, b, c, d) {
		return -c * (t /= d) * (t - 2) + b;
	},
	easeInOutQuad: function (x, t, b, c, d) {
		if ((t /= d / 2) < 1) return c / 2 * t * t + b;
		return -c / 2 * ((--t) * (t - 2) - 1) + b;
	},
	easeInExpo: function (x, t, b, c, d) {
		return (t == 0) ? b : c * Math.pow(2, 10 * (t / d - 1)) + b;
	},
	easeOutExpo: function (x, t, b, c, d) {
		return (t == d) ? b + c : c * (-Math.pow(2, -10 * t / d) + 1) + b;
	},
	easeInOutExpo: function (x, t, b, c, d) {
		if (t == 0) return b;
		if (t == d) return b + c;
		if ((t /= d / 2) < 1) return c / 2 * Math.pow(2, 10 * (t - 1)) + b;
		return c / 2 * (-Math.pow(2, -10 * --t) + 2) + b;
	}
});
