﻿

jQuery.loadImage = function(src, callback) {
	var img = new Image();
	$(img).load(function() {
		callback(img);
	}).attr("src", src);
}

jQuery.loadImages = function(urls, callback) {
	var loaded = 0;
	jQuery.each(urls, function(i, val) {
		$.loadImage(val, function() {
			loaded++;
			if (loaded >= urls.length)
				callback(urls);
		});
	});
}

jQuery.setHeadline = function(t, s, a, w, h) {
	$.loadImage(s, function() {
		var img = jQuery("<img>").attr("src", s).attr("alt", a).css({ width: w, height: h }).addClass("png");
		$(t).html(img);
		if ($.browser.msie && $.browser.version == 6.0 && s.indexOf(".png") != -1)
			img.addClass("png");
	});
}

jQuery.navigationMenu = function() {

	var tabHoverTime = 300;
	var tabOutTime = 300;

	$("ul.portal-select li:first").addClass("first");
	$("ul.portal-select li:last").addClass("last");
	$("ul.portal-select").attr("id", "navigation-logo-tab");

	$("ul.portal-select li").hover(function() {
		$(this).addClass("hover");
	},
	function() {
		$(this).removeClass("hover");
	});

	var currentTallest = 34;
	$("ul.portal-select li a").each(function() {
		if ($(this).height() > currentTallest)
			currentTallest = $(this).height();
	});

	$("ul.portal-select li a").each(function() {
		if (currentTallest - $(this).height() > 0) {
			$(this).html($("<span></span>").css("padding-top", currentTallest - $(this).height()).text($(this).text()));
		}
	});

	var tabs = $("#navigation ul.nav li.nav");
	var activeTab = null;

	tabs.each(function(i) {

		var next = $(this).next();
		var prev = $(this).prev();

		if (next.length > 0 && next.hasClass("active"))
			$(this).addClass("active-next");
		else if (prev.length > 0 && prev.hasClass("active") && prev.attr("id") != "menu-navigation-logo")
			$(this).addClass("active-prev");

		$("#" + $(this).attr("id").substr(5) + "-tab").appendTo(this);

		var tabIsActive = false;

		$(this).find(".navigation-block").equalHeights();

		$(this).hover(function() {

			var tab = $(this);
			tabIsActive = true;

			var showTab = function() {

				activeTab = tab;

				if ($.browser.msie && $.browser.version == 6.0) {
					$("select").css("visibility", "hidden");
				}
				tabs.removeClass("hover");
				tabs.removeClass("hover-active-prev");
				tabs.removeClass("hover-active-next");
				tabs.removeClass("navigation-logo-hover");

				if (tab.hasClass("navigation-logo"))
					tab.addClass("navigation-logo-hover");

				if (tab.hasClass("active-prev"))
					tab.addClass("hover-active-prev");
				else if (tab.hasClass("active-next"))
					tab.addClass("hover-active-next");
				else
					tab.addClass("hover");

				$(".nav-tab-container, #navigation-logo-tab").addClass("nav-tab-container-outside-screen");
				tab.find(".nav-tab-container, #navigation-logo-tab").removeClass("nav-tab-container-outside-screen").css("left", tab.position().left - 12);
			};

			if (activeTab != null)
				showTab();
			else {
				setTimeout(function() {
					if (tabIsActive)
						showTab();
				}, tabHoverTime);
			}

		}, function() {

			var tab = $(this);
			tabIsActive = false;

			setTimeout(function() {

				if (!tabIsActive && activeTab != null && activeTab.attr("id") == tab.attr("id")) {

					activeTab = null;

					tab.find(".nav-tab-container, #navigation-logo-tab").addClass("nav-tab-container-outside-screen");

					if ($.browser.msie && $.browser.version == 6.0) {
						var hasActiveTab = false;
						$(".nav-tab-container").each(function() {
							if (!$(this).hasClass("nav-tab-container-outside-screen"))
								hasActiveTab = true;
						});

						if (!hasActiveTab)
							$("select").css("visibility", "visible");
					}

					tab.removeClass("hover");
					tab.removeClass("hover-active-prev");
					tab.removeClass("hover-active-next");
					tab.removeClass("navigation-logo-hover");
				}

			}, tabOutTime);
		});

	});
}

$(function() { $.navigationMenu(); });


$.fn.equalHeights = function() {
	var els = $(this);
	var currentTallest = 0;
	els.each(function() {
		if ($(this).height() > currentTallest)
			currentTallest = $(this).height() + 1;
	});

	// for ie6, set height since min-height isn't supported
	if ($.browser.msie && $.browser.version == 6.0)
		$(this).css('height', currentTallest);
	else
		$(this).css('min-height', currentTallest);

	return this;
};

/*-------------------------------------------------------------------- 
* JQuery Plugin: "EqualHeights"
* by:	Scott Jehl, Todd Parker, Maggie Costello Wachs (http://www.filamentgroup.com)
*
* Copyright (c) 2008 Filament Group
* Licensed under GPL (http://www.opensource.org/licenses/gpl-license.php)
*
* Description: Compares the heights or widths of the top-level children of a provided element 
and sets their min-height to the tallest height (or width to widest width). Sets in em units 
by default if pxToEm() method is available.
* Dependencies: jQuery library, pxToEm method	(article: 
http://www.filamentgroup.com/lab/retaining_scalable_interfaces_with_pixel_to_em_conversion/)							  
* Usage Example: $(element).equalHeights();
Optional: to set min-height in px, pass a true argument: $(element).equalHeights(true);
* Version: 2.0, 08.01.2008
--------------------------------------------------------------------*/

$.fn.equalHeightsOfTopLevelChildren = function(px) {
	$(this).each(function() {
		var currentTallest = 0;
		$(this).children().each(function(i) {
			if ($(this).height() > currentTallest) { currentTallest = $(this).height(); }
		});
		//if (!px || !Number.prototype.pxToEm) currentTallest = currentTallest.pxToEm(); //use ems unless px is specified
		// for ie6, set height since min-height isn't supported
		if ($.browser.msie && $.browser.version == 6.0) { $(this).children().css({ 'height': currentTallest }); }
		$(this).children().css({ 'min-height': currentTallest });
	});
	return this;
};


/* Tooltip */
function initHPLTooltip() {

	$(".hpl-tooltip-item .hpl-wrapper").each(function() {

		var c = "";

		$(this).find(".hpl-homeowner").each(function() {
			c = createHPLTooltip($(".hpl-col-homeowner").html());
		});

		$(this).find(".hpl-professional").each(function() {
			c = createHPLTooltip($(".hpl-col-professional").html());
		});

		$(this).find(".hpl-landowner").each(function() {
			c = createHPLTooltip($(".hpl-col-landowner").html());

		});

		$(this).attr("title", $(c).find("p").text()).after(c);

	});
}

function createHPLTooltip(content) {
	var t = $('<div style="display: none;" id="hpl-tooltip" class="tooltip"><div class="tooltip-content"></div><div class="tooltip-bottom"/></div>');
	var c = t.find(".tooltip-content");
	c.append(content);

	return t;
}

function createTooltip(tooltip) {

	var currentTip;

	$(tooltip).hover(function(e) {

		var item = $(this);
		currentTip = item.find("span").siblings("div.tooltip").clone().appendTo("body");

		setTimeout(function() {

			if (currentTip != null) {

				$(this).trigger("mousemove");

				var s = item.find("span");
				item.t = s.attr("title");
				s.attr("title", "");
				if ($.browser.msie)
					currentTip.show();
				else
					currentTip.fadeIn(200);
			}
		}, 300);
	},
		function() {

			if (currentTip != null) {

				$(this).find("span").attr("title", this.t);
				if ($.browser.msie)
					currentTip.remove();
				else
					currentTip.fadeOut(200, function() { $(this).remove() });
			}

		}).mousemove(function(e) {
			if (currentTip != null) {
				if ($.browser.msie && $.browser.version == 6.0) {
					currentTip.css({
						bottom: $(window).scrollTop() + $(window).height() - e.pageY + 5,
						left: e.pageX - 75
					});
				}
				else {
					currentTip.css({
						bottom: $(window).height() - e.pageY + 5,
						left: e.pageX - 75
					});
				}
			}
		});
}

function initTooltip() {

	$(".tooltip-item:has(span[title])").each(function() {
		createTooltip(this);
	});
}

function initFormTooltip() {
	$(".form-field input:text[title], .form-field textarea[title]").each(function() {

		var parent = $(this).closest(".form-field");

		var title = parent.find("label").text().replace(":", "");
		var text = $(this).attr("title");

		var t = $('<div style="display: none;" class="tooltip"><div class="tooltip-content"></div><div class="tooltip-bottom"/></div><span></span>');
		var c = t.find(".tooltip-content");
		c.append('<h4>' + title + '</h4><p>' + text + '</p>');

		$(this).removeAttr("title");
		parent.append(t);

		createTooltip(parent);
	});
}


// Function to open all external urls and file library links in new window/tab
$(document).ready(function() {
	$("a[href^='/files'], a[href^='/Files']").attr("target", "_blank");
	$("a[href^=http]").filter(function() {
		//Compare the anchor tag's host name with location's host name
		return this.hostname && this.hostname !== location.hostname;
	}).attr("target", "_blank").click(function() {
		if (location.hostname == "www.husqvarna.com") {
			_gaq.push(['local._trackPageview', "/" + location.pathname.split("/")[1] + '/outbound/' + $(this).attr("href").replace("http://", "")]);
		}
	});
});

$(document).ready(function() {
	$(".expandable").prev("h1, h2, h3").addClass("expander");
	$(".expandable").prev("h1, h2, h3").click(function() {
		$(this).toggleClass("expanded");
		$(this).next(".expandable").slideToggle("100");
	});
});

$(document).ready(function() {
	$(".user-guide-menu ul").hide();
	$(".user-guide-content li").hide();

	$(".user-guide-menu > li").children("a").click(function(event) {
		$(".user-guide-menu > li").children("a").removeClass("open");
		$(".user-guide-menu > li").children("a").next().hide();

		$(this).addClass("open");
		$(this).next().show();

		event.preventDefault();
	});

	$(".user-guide-menu a.leaf").click(function(event) {
		$(".user-guide-menu li").removeClass("active");
		$(this).parent().addClass("active");

		$(".user-guide-content li").hide();

		var clickedId = $(this).attr("href").replace("#", "");
		$(".user-guide-content li[id='" + clickedId + "']").show();

		event.preventDefault();
	});

	// Select first user guide
	$(".user-guide-menu li a:eq(0)").click();
	$(".user-guide-menu li a:eq(1)").click();
});

/* Google search textbox and button scripts */
function initGoogleSearch(originalText, textBox, searchButton) {
	if (textBox.val() != originalText) {
		textBox.css("color", "#000");
	}
	textBox.focus(function() {
		$(this).css("color", "#000");
		if ($(this).val() == originalText) {
			$(this).val("");
		}
	});
	textBox.blur(function() {
		if ($.trim($(this).val()) == "") {
			$(this).css("color", "#999");
			$(this).val(originalText);
		}
	});
	searchButton.click(function(event) {
		//if (textBox.val() == originalText || $.trim(textBox.val()) == "") {
		if (textBox.val() == originalText) {
			textBox.val("");
			//event.preventDefault();
		}
	});
}


/* Slider */
(function($) {

	$.fn.carousel = function(o) {
		return this.each(function() {
			new $c(this, o);
		});
	};

	var defaults = {};

	$.carousel = function(e, o) {

		var self = this;
		this.options = $.extend({}, defaults, o || {});

		this.w = null;
		this.sw = null;
		this.rgb1 = null;
		this.rgb2 = null;
		this.sliderObj = null;

		this.container = $(e);
		this.slider = this.container.find(".carousel-slider");
		this.content = this.container.find(".carousel-content");
		this.list = this.container.find(".carousel-list");
		this.prev = this.container.find(".carousel-prev");
		this.next = this.container.find(".carousel-next");
		this.anchors = this.container.find(".carousel-anchors a");

		this.container.disableTextSelect();

		this.init();

		this.mouseIsDown = false;

		this.container.find(".slider-product-image").parent().hover(function() {
			$(this).find(".slider-hover").css("visibility", "visible");
		},
		function() {
			$(this).find(".slider-hover").css("visibility", "hidden");
		});

		var contentWidth = this.content[0].scrollWidth;
		//$(this.content[0]).css("overflow", "hidden");
		if (contentWidth > this.width()) {
			this.sliderObj = this.initSlider();

			$(".carousel-slider-prev").css("display", "inline");
			$(".carousel-slider-next").css("display", "inline");
			this.content.css("overflow", "hidden");
			this.next.css("display", "block");
			this.prev.css("display", "block");
			this.hide(this.prev);

			$(".carousel-anchors").css("display", "block");

			this.prev.click(function() {
				self.slideToPrev();
			});

			this.next.click(function() {
				self.slideToNext();
			});

			this.container.find(".carousel-slider-next, .carousel-slider-prev").mouseout(function() {

				$(this).unbind("mouseup").unbind("mousedown");
				self.mouseIsDown = false;

			}).mouseover(function() {

				$(this).mouseup(function() {
					self.mouseIsDown = false;
				}).mousedown(function() {
					self.mouseIsDown = true;
					if ($(this).hasClass("carousel-slider-next"))
						self.continousSlideRight();
					else
						self.continousSlideLeft();
				});
			});

			$(".carousel-anchors li").addClass("carousel-anchors-border");
			$(".carousel-anchors li:first").removeClass("carousel-anchors-border");

			this.anchors.each(function(i) {
				var target = $($(this).attr("href"));
				var left = target[0].offsetLeft;
				$(this).bind("mousedown", function(e) {
					if ($.browser.safari)
						left = target[0].offsetLeft;
					self.slideToPos(left - parseInt(self.list.css("padding-left")));
					return false;
				});
				$(this).click(function(e) {
					e.preventDefault();
				});
			});

			this.highlightLinks(0);

			if (/Safari/i.test(navigator.userAgent)) { //Test for Safari
				var _timer = setInterval(function() {
					if (/loaded|complete/.test(document.readyState)) {
						clearInterval(_timer);
						self.initLinkColors();
						self.slideToPos(0);
					}
				}, 10)
			}
		}

		this.container.find(".slider-desc").equalHeights();
		this.container.find(".product-title").equalHeights();
		this.container.find(".list-price").equalHeights();

	};

	// Create shortcut for internal use
	var $c = $.carousel;

	$c.fn = $c.prototype = {
		carousel: '0.1'
	};

	$c.fn.extend = $c.extend = $.extend;

	$c.fn.extend({

		initSlider: function() {

			var self = this;

			if (self.sliderObj != null)
				return self.sliderObj;

			this.slider.css("display", "block");

			var handler = this.slider.find(".carousel-slider-handle");

			var obj = {

				handler: handler,
				handlerWidth: handler.width(),
				posPx: 0,
				pos: 0,
				max: self.slider.width() - handler.width(),
				moveTo: function(p) {

					p = p > 100 ? 100 : p < 0 ? 0 : p;

					self.slide(p);
					self.highlightLinks(p);

					if (p == 0)
						self.hide(self.prev);
					else
						self.show(self.prev);
					if (p == 100)
						self.hide(self.next);
					else
						self.show(self.next);

					var l = obj.max * (p / 100);
					obj.handler.css("left", l < 0 ? 0 : l < obj.max ? l : obj.max);

					obj.posPx = parseInt(obj.handler.css("left"));
					obj.pos = p; ;

				}
			};

			obj.handler.bind("mousedown.slider-handle", function(e) {

				var x = e.pageX;
				var o = obj.posPx;

				$("body").bind("mousemove.slider-handle", function(e) {

					var l = o + e.pageX - x;
					var p = (l / obj.max) * 100;

					obj.moveTo(p);
				});

				$("body").bind("mouseup.slider-handle", function() {
					$("body").unbind("mousemove.slider-handle");
					$("body").unbind("mouseup.slider-handle");
				});

			});

			self.slider.mousedown(function(e) {
				if (e.pageX < obj.handler.offset().left || e.pageX > obj.handler.offset().left + obj.handlerWidth) {
					obj.moveTo(((e.pageX - $(this).offset().left - obj.handlerWidth / 2) / obj.max) * 100);
				}
			});

			self.sliderObj = obj;
			return obj;
		},

		continousSlideLeft: function() {
			var self = this;
			if (this.mouseIsDown) {
				this.sliderObj.moveTo(this.sliderObj.pos - 1);
				setTimeout(function() { self.continousSlideLeft(); }, 20);
			}
		},

		continousSlideRight: function() {
			var self = this;
			if (this.mouseIsDown) {
				this.sliderObj.moveTo(this.sliderObj.pos + 1);
				setTimeout(function() { self.continousSlideRight(); }, 20);
			}
		},

		slide: function(x) {
			if (this.list.queue("fx").length == 0) {
				this.list.css("left", "-" + (x * this.scrollWidth()) / 100 + "px");
			}
		},

		slideLeft: function(x) {
			this.slideToPos(this.pos() - x);
		},

		slideRight: function(x) {
			this.slideToPos(this.pos() + x);
		},

		slideToPos: function(pos) {
			var self = this;
			if (pos != this.pos()) {
				this.list.animate({
					left: "-" + (pos < self.scrollWidth() ? (pos > 0 ? pos : 0) : self.scrollWidth()) + "px"
				}, 500);
				this.sliderObj.moveTo((pos / this.scrollWidth()) * 100);
			}
		},

		slideToNext: function() {
			var left = (Math.floor(this.pos() / this.slideWidth()) * this.slideWidth()) + this.slideWidth();
			this.slideToPos(left);
		},

		slideToPrev: function() {
			var left = (Math.floor(this.pos() / this.slideWidth()) * this.slideWidth());
			left = left == this.pos() ? left - this.slideWidth() : left;
			this.slideToPos(left);
		},

		pos: function() {
			return -parseInt(this.list.css("left"));
		},

		scrollWidth: function() {
			if (this.sw == null || this.sw == 0) {
				this.sw = this.content[0].scrollWidth + this.pos() - this.width();
			}
			return this.sw;
		},

		slideWidth: function() {
			return this.width() - parseInt(this.list.css("margin-left")) - parseInt(this.list.css("padding-right"));
		},

		width: function() {
			if (this.w == null || this.w == 0)
				this.w = this.content[0].offsetWidth;
			return this.w;
		},

		highlightLinks: function(val) {

			var self = this;
			var p = (val / 100) * this.scrollWidth();

			this.anchors.each(function(i) {

				var target = $($(this).attr("href"));
				var left = target[0].offsetLeft;
				var width = target[0].offsetWidth;


				if ((left + width) < p || left > (p + self.width())) {
					$(this).css("color", self.calcColor(0));
				}
				else if (left > p && (left + width) < (p + self.width())) {
					$(this).css("color", self.calcColor(1));
				}
				else if ((left + width) > p && (left + width) < (p + self.width())) {
					$(this).css("color", self.calcColor((left - (p - width)) / width));
				}
				else {
					$(this).css("color", self.calcColor(1 - (((left + width) - (p + self.width())) / width)));
				}
			});
		},

		initLinkColors: function() {

			var c1 = $(document.createElement("div"));
			c1.addClass("carousel-slider-text-on");
			var c2 = $(document.createElement("div"));
			c2.addClass("carousel-slider-text-off");

			$("body").append(c1);
			$("body").append(c2);

			this.rgb1 = this.getRGB(c2.css("color"));
			this.rgb2 = this.getRGB(c1.css("color"));

			c1.remove();
			c2.remove();
		},

		calcColor: function(p) {

			if (p > 1)
				p = 0;

			if (this.rgb1 == null || this.rgb2 == null)
				this.initLinkColors();

			var r = Math.round((this.rgb1[0] - this.rgb2[0]) * p + this.rgb2[0]);
			var g = Math.round((this.rgb1[1] - this.rgb2[1]) * p + this.rgb2[1]);
			var b = Math.round((this.rgb1[2] - this.rgb2[2]) * p + this.rgb2[2]);

			return "rgb(" + r + "," + g + "," + b + ")";
		},

		getRGB: function(color) {
			var result;

			// Check if we're already dealing with an array of colors
			if (color && color.constructor == Array && color.length == 3)
				return color;

			// Look for #a0b1c2
			if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color))
				return [parseInt(result[1], 16), parseInt(result[2], 16), parseInt(result[3], 16)];

			// Look for rgb(num,num,num)
			if (result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color))
				return [parseInt(result[1]), parseInt(result[2]), parseInt(result[3])];

			// Look for rgb(num%,num%,num%)
			if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color))
				return [parseFloat(result[1]) * 2.55, parseFloat(result[2]) * 2.55, parseFloat(result[3]) * 2.55];

			// Look for #fff
			if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color))
				return [parseInt(result[1] + result[1], 16), parseInt(result[2] + result[2], 16), parseInt(result[3] + result[3], 16)];

			// Look for rgba(0, 0, 0, 0) == transparent in Safari 3
			if (result = /rgba\(0, 0, 0, 0\)/.exec(color))
				return colors['transparent'];
		},

		hide: function(el) {
			if ($(el).hasClass("carousel-next") && $(el).css("right") == "5px")
				$(el).stop(true, false).animate({ "right": "-59px" }, 500, function() { });
			else if ($(el).hasClass("carousel-prev") && $(el).css("left") == "5px")
				$(el).stop(true, false).animate({ "left": "-59px" }, 500, function() { });
		},

		show: function(el) {
			if ($(el).hasClass("carousel-next") && $(el).css("right") == "-59px") {
				$(el).stop(true, false).animate({ "right": "5px" }, 500, function() { });
			}
			else if ($(el).hasClass("carousel-prev") && $(el).css("left") == "-59px")
				$(el).stop(true, false).animate({ "left": "5px" }, 500, function() { });
		},

		init: function() {
			this.w = null;
			this.content.scrollTop(0);
			this.content.scrollLeft(0);
			this.slideToPos(0);
		}

	});

})(jQuery);

/* End Slider */


/* Lightbox */

(function($) {

	$.fn.lightbox = function(o) {
		return this.each(function() {
			new $lb(this, o);
		});
	};

	var defaults = {
		transparent: vpath + "images/spacer.gif",
		images: [{ large: vpath + 'images/contact.jpg', small: vpath + 'images/contact.jpg', alt: 'test'}],
		title: vpath + "images/hq_logo_r.gif",
		size: { width: "1001px", height: "651px" }
	};

	$.lightbox = function(e, o) {
		this.options = $.extend({}, defaults, o || {});
		var self = this;
		$(e).click(function(e) {
			e.preventDefault();
			self.setup(); ;
		});
	};

	// Create shortcut for internal use
	var $lb = $.lightbox;

	$lb.fn = $lb.prototype = {
		lightbox: '0.1'
	};

	$lb.fn.extend = $lb.extend = $.extend;

	$lb.fn.extend({

		setup: function() {

			var self = this;

			showOverlay(function() {
				self.destroy();
			});


			$("body").append('<div id="lightbox-container"><img class="lightbox-bg" src="' + vpath + 'images/lightbox/product-details-popup-bg.png' + '" /><div id="lightbox-loading"></div><div id="lightbox-close"></div><div id="lightbox-image-container"><div id="lightbox-image-slider"></div></div><img id="lightbox-title-image" /></div>');

			this.background = $(".lightbox-bg");
			this.container = $("#lightbox-container");
			this.close = $("#lightbox-close");
			this.imageContainer = $("#lightbox-image-container");
			this.slider = $("#lightbox-image-slider");
			this.image = $("#lightbox-image");
			this.loading = $("#lightbox-loading");
			this.title = $("#lightbox-title-image");

			if ($.browser.msie && $.browser.version == 6.0)
				this.background.attr("src", vpath + "images/ie6/lightbox/product-details-popup-bg.gif");

			this.thumbs = $('<div class="lightbox-thumbs"></div>');
			this.container.append(this.thumbs);

			this.slider.css("left", self.options.size.width);
			this.title.attr("src", self.options.title);

			this.firstThumbLoaded = true;
			$(this.options.images).each(function() {
				self.addThumb(this.large, this.small, this.alt);
			});

			this.close.click(function() {
				self.destroy();
			});

			$(window).bind("resize.lightbox", function() {
				self.position();
			});

			if (!$.browser.msie || $.browser.version > 6.0) {
				this.container.css("position", "fixed");
			}
			else {
				$(window).bind("scroll.lightbox", function() {
					self.position();
				});
			}
			this.position();
		},

		addThumb: function(large, small, alt) {

			var self = this;

			var thumb = $(document.createElement("img"));
			thumb.addClass("lightbox-thumb");
			thumb.attr("src", self.options.transparent);
			thumb.attr("alt", alt);
			thumb.hover(function() {
				$(this).addClass("lightbox-thumb-current");
			},
				function() {
					$(this).removeClass("lightbox-thumb-current");
				});
			thumb.click(function() {
				if (image[0].offsetLeft - parseInt(image.css("margin-left")) > 0) {
					self.slider.animate({
						left: "-" + (image[0].offsetLeft - parseInt(image.css("margin-left"))) + "px"
					}, 500);
				}
				else {
					self.slider.animate({
						left: image[0].offsetLeft + parseInt(image.css("margin-left")) + "px"
					}, 500);
				}
				$(".lightbox-thumb").removeClass("lightbox-thumb-selected"); ;
				thumb.addClass("lightbox-thumb-selected");
			});

			var container = $(document.createElement("div"));
			container.addClass("lightbox-thumb-container");
			container.css("background-image", "url('" + small + "')");
			container.append(thumb);

			var img = new Image();
			var image = $(document.createElement("img"));
			image.addClass("lightbox-image");
			image.attr("src", large);
			image.attr("alt", alt);

			img.onload = function() {

				if (self.firstThumbLoaded) {
					self.firstThumbLoaded = false;
					thumb.addClass("lightbox-thumb-selected");
					self.loading.css("display", "none");
					self.slider.animate({
						left: "-" + image[0].offsetLeft + "px"
					}, 500);
				}

				var h = self.imageContainer.height();
				var w = img.width * (h / img.height);
				var margin = "0px " + ((self.imageContainer.width() - w) / 2) + "px";

				image.css({
					width: w + "px",
					height: h + "px",
					margin: margin
				});

				self.slider.append(image);
				self.thumbs.append(container);
			}
			img.src = large;
		},

		destroy: function() {
			var self = this;
			$(window).unbind("resize.lightbox");
			$(window).unbind("scroll.lightbox");
			self.container.remove();
			closeOverlay();
		},

		position: function() {

			var maxWidth = parseInt(this.options.size.width);
			var maxHeight = parseInt(this.options.size.height);

			var p = 1;

			if ($(window).width() < (this.container.outerWidth(true) + 60)) {
				p = $(window).width() / (this.container.outerWidth(true) + 60);
			}
			else if ($(window).width() > maxWidth) {
				p = maxWidth / this.container.outerWidth(true);
			}
			else {
				p = $(window).width() / (this.container.outerWidth(true) + 60);
			}

			if ($(window).height() < (this.container.outerHeight(true) + 60)) {
				var p2 = $(window).height() / (this.container.outerHeight(true) + 60);
				if (p2 < p)
					p = p2;
			}
			else if ($(window).height() > maxHeight) {
				var p2 = maxHeight / this.container.outerHeight(true);
				if (p2 < p)
					p = p2;
			}
			else {
				var p2 = $(window).height() / (this.container.outerHeight(true) + 60);
				if (p2 > p)
					p = p2;
			}

			this.background.css({
				width: (this.background.width() * p) + "px",
				height: (this.background.height() * p) + "px"
			});

			this.imageContainer.css({
				height: (this.imageContainer.height() * p) + "px",
				width: (this.imageContainer.width() * p) + "px"
			});

			var h = this.imageContainer.height();
			var w = $(".lightbox-image").width() * (h / $(".lightbox-image").height());
			var margin = "0px " + ((this.imageContainer.width() - w) / 2) + "px";

			$(".lightbox-image").css({
				width: w + "px",
				height: h + "px",
				margin: margin
			});

			this.container.css({
				width: (this.container.width() * p) + "px",
				height: (this.container.height() * p) + "px"
			}).show();

			this.slider.css("left", (parseInt(this.slider.css("left")) * p) + "px");

			if (this.container.css("position")) {
				this.container.css({
					top: ($(window).height() / 2) - (this.container.outerHeight(true) / 2),
					left: ($(window).width() / 2) - (this.container.outerWidth(true) / 2)
				}).show();
			}
			else {
				this.container.css({
					top: $(window).scrollTop() + ($(window).height() / 2) - (this.container.outerHeight(true) / 2),
					left: ($(window).width() / 2) - (this.container.outerWidth(true) / 2)
				}).show();
			}
		}

	});

})(jQuery);
/* Lightbox end */



function showOverlay(closeFunc) {

	var id = "lightbox-overlay";
	var cssClass = "lightbox-overlay transparent-80";
	var overlay = $("<div></div>").attr("id", id).attr("class", cssClass);

	$("embed, object, select").css({ "visibility": "hidden" });
	$("body").css("overflow", "hidden").append(overlay);

	$(document).keydown(function(event) {
		if (event.keyCode == 27) {
			closeOverlay();
			closeFunc();
		}
	});

	overlay.click(function() {
		closeOverlay();
		closeFunc();
	});

	if ($.browser.msie && $.browser.version == 6.0) {
		/* IE6 only */

		$(window).resize(function() {
			resizeOverlay();
		});

		resizeOverlay();
	}
}

/* IE6 Only */
function resizeOverlay() {

	var height = $("body").outerHeight(true);

	if ($("html").outerHeight(true) > height)
		height = $("html").outerHeight(true);

	$("#lightbox-overlay").css({
		position: "absolute",
		width: $(window).width(),
		height: height
	});
}

function closeOverlay() {
	$("#lightbox-overlay").fadeOut(300, function() {
		$(this).remove();
		$("embed, object, select").css({ "visibility": "visible" });
	});
	$("body").css("overflow", "visible");
	window.scrollBy(0, 100);
}


function playVideo(src, w, h, x, y) {

	var id = "video-player";
	var player = $("<div></div>").attr("id", "video-player");

	$("body").append(player);

	var flashvars = {
		videoURL: "http://" + location.host + src,
		maxVideoHeight: h,
		maxVideoWidth: w,
		xPos: x,
		yPos: y
	};

	var params = {
		scale: "noScale",
		salign: "tl",
		wmode: "transparent"
	};

	var attributes = {
		style: "position:fixed; top: 0; left: 0; z-index: 9999;"
	};

	if ($.browser.msie && $.browser.version <= 6.0) {
		attributes = {
			style: "position:absolute; top: " + $(window).scrollTop() + "; left: 0; z-index: 9999;"
		};
		$(window).scroll(function() {
			$("#" + id).css("top", $(window).scrollTop());
		});
	}

	var player = vpath + "flash/videoWindow.swf";

	swfobject.embedSWF(player, id, "100%", "100%", "9.0.0", "", flashvars, params, attributes);

	return false;
}

function resizeVideo(w, h) {

	var top = $(window).scrollTop();

	$("#video-player").css({
		position: "absolute",
		top: top,
		left: 0,
		zIndex: "9999",
		width: $(window).width(),
		height: $(window).height()
	});
}

function closeVideo() {

	$("#video-player").remove();
	//closeOverlay();
}






/**
* jQuery custom checkboxes
* 
* Copyright (c) 2008 Khavilo Dmitry (http://widowmaker.kiev.ua/checkbox/)
* Licensed under the MIT License:
* http://www.opensource.org/licenses/mit-license.php
*
* @version 1.1.0 Beta
* @author Khavilo Dmitry
* @mailto wm.morgun@gmail.com
**/

(function($) {

	$.fn.checkbox = function(options) {

		/* IE6 background flicker fix */
		try { document.execCommand('BackgroundImageCache', false, true); } catch (e) { }

		/* Default settings */
		var settings = {
			cls: 'wip-checkbox',  /* checkbox  */
			empty: vpath + 'Images/blank.gif'  /* checkbox  */
		};

		/* Processing settings */
		settings = $.extend(settings, options || {});

		/* Adds check/uncheck & disable/enable events */
		var addEvents = function(object) {
			var checked = object.checked;
			var disabled = object.disabled;
			var $object = $(object);

			if (object.stateInterval)
				clearInterval(object.stateInterval);

			object.stateInterval = setInterval(
				function() {
					if (object.disabled != disabled)
						$object.trigger((disabled = !!object.disabled) ? 'disable' : 'enable');
					if (object.checked != checked)
						$object.trigger((checked = !!object.checked) ? 'check' : 'uncheck');
				},
				10 /* in miliseconds. Low numbers this can decrease performance on slow computers, high will increase responce time */
			);
			return $object;
		}
		/* try { console.log(this); } catch (e) { } */
		/* Wrapping all passed elements */
		return this.each(function() {
			var ch = this;
			var $ch = addEvents(ch); /* Adds custom eents and returns */

			if (ch.wrapper) {
				ch.wrapper.remove();
			}

			/* Creating div for checkbox and assigning "hover" event */
			ch.wrapper = $('<span class="' + settings.cls + '"><span class="mark"><img src="' + settings.empty + '" /></span></span>');
			ch.wrapperInner = ch.wrapper.children('span');
			ch.wrapper.hover(
				function() { ch.wrapperInner.addClass(settings.cls + '-hover'); },
				function() { ch.wrapperInner.removeClass(settings.cls + '-hover'); }
			);

			/* Wrapping checkbox */
			$ch.css({ position: 'absolute', left: '-9999px' }).after(ch.wrapper);

			/* Fixing IE6 label behaviour */
			var parents = $ch.parents('label');
			/* Creating "click" event handler for checkbox wrapper*/
			if (parents.length) {
				parents.click(function(e) { $ch.trigger('click', [e]); return ($.browser.msie && $.browser.version < 7); });
			}
			else {
				ch.wrapper.click(function(e) { $ch.trigger('click', [e]); });
			}

			delete parents;

			$ch.bind('disable', function() { ch.wrapperInner.addClass(settings.cls + '-disabled'); }).bind('enable', function() { ch.wrapperInner.removeClass(settings.cls + '-disabled'); });
			$ch.bind('check', function() { ch.wrapper.addClass(settings.cls + '-checked'); }).bind('uncheck', function() { ch.wrapper.removeClass(settings.cls + '-checked'); });

			/* Disable image drag-n-drop  */
			$('img', ch.wrapper).bind('dragstart', function() { return false; }).bind('mousedown', function() { return false; });

			/* Firefox div antiselection hack */
			if (window.getSelection)
				ch.wrapper.css('MozUserSelect', 'none');

			/* Applying checkbox state */
			if (ch.checked)
				ch.wrapper.addClass(settings.cls + '-checked');
			if (ch.disabled)
				ch.wrapperInner.addClass(settings.cls + '-disabled');
		});
	};


})(jQuery);

(function($) {
	$("input:checkbox").not(".keep-standard").checkbox();
	$("input:radio").checkbox({ cls: "wip-radiobutton" });
})(jQuery);

function reloadPageWithParam(name, value) {
	var baseURL = document.URL.replace(new RegExp("(&|\\?)" + name + "=.*?(?=$|&)"), "");

	if (baseURL.indexOf("?") == -1 && baseURL.indexOf("&") > -1)
		baseURL = baseURL.replace("&", "?");

	var token = baseURL.indexOf("?") == -1 ? "?" : "&";

	window.location = baseURL + token + name + "=" + value;
}

///Campaign tracking
$(function() {

	try {

		if (location.hash.indexOf("cm=") < 0)
			return;

		var vals = location.hash.substring(location.hash.indexOf("cm=") + 3).split(",");

		if (vals.length < 3)
			return;

		_gaq.push(['local._trackEvent', vals[0], vals[2], vals[1]]);
		_gaq.push(['global._trackEvent', vals[0], vals[2], vals[1]]);

	} catch (err) { }

});


//AddThis tracking
var links = $('a[href^="http://www.addthis.com/bookmark.php"]:not(.addthis_button)');

links.addClass("addthis_button_compact");

$(links).each(function(i, link) {
	link = $(link);
	var parent = link.parent();

	var container = $('<div class="addthis_default_style"></div>');
	container.append(link).appendTo(parent);
});

function trackVirtualPageView(path) {
	var url = location.pathname + path;
	_gaq.push(['local._trackPageview', url]);
	_gaq.push(['global._trackPageview', url]);
}

function validateEmail(email) {
	var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	return reg.test(email);
}

/*
jQuery Vertical Align for tabnum-X
*/

(function($) {
    $.fn.vAlignTab = function() {
        return this.each(function(i) {
            var ah = $(this).height();
            var li = $(this).parent();
            var ul = $(this).parent().parent();
            var ulh = ul.height();
            ul.height(ulh);
            li.height(ulh);
            var mh = Math.ceil((ulh - ah) / 2);
            $(this).css('padding-top', mh + 'px');
            $(this).css('padding-bottom', mh + 'px');
        });
    };
})(jQuery);

(function($) {
    $(".tabnum-4 li a, .tabnum-5 li a, .tabnum-6 li a, .tabnum-7 li a, .tabnum-8 li a, .tabnum-9 li a, .tabnum-10 li a").vAlignTab();
})(jQuery);


/*
Check if mobile unit 
*/
function CheckIsMobile() {
   	var currentMobileBrowserKeywords = new Array();
   	currentMobileBrowserKeywords[0] = "cldc";
   	currentMobileBrowserKeywords[1] = "symbian";
   	currentMobileBrowserKeywords[2] = "midp";
   	currentMobileBrowserKeywords[3] = "j2me";
   	currentMobileBrowserKeywords[4] = "mobile";
   	currentMobileBrowserKeywords[5] = "wireless";
   	currentMobileBrowserKeywords[6] = "palm";
   	currentMobileBrowserKeywords[7] = "phone";
   	currentMobileBrowserKeywords[8] = "pocket pc";
   	currentMobileBrowserKeywords[9] = "netfront";
   	currentMobileBrowserKeywords[10] = "bolt";
   	currentMobileBrowserKeywords[11] = "iris";
   	currentMobileBrowserKeywords[12] = "brew";
   	currentMobileBrowserKeywords[13] = "openwave";
   	currentMobileBrowserKeywords[14] = "windows ce";
   	currentMobileBrowserKeywords[15] = "wap2";
   	currentMobileBrowserKeywords[16] = "android";
   	currentMobileBrowserKeywords[17] = "opera mini";
   	currentMobileBrowserKeywords[18] = "opera mobi";
   	currentMobileBrowserKeywords[19] = "maemo";
   	currentMobileBrowserKeywords[20] = "fennec";
   	currentMobileBrowserKeywords[21] = "blazer";
   	currentMobileBrowserKeywords[22] = "160x160";
   	currentMobileBrowserKeywords[23] = "tablet";
   	currentMobileBrowserKeywords[24] = "webos";
   	currentMobileBrowserKeywords[25] = "sony";
   	currentMobileBrowserKeywords[26] = "nintendo";

   	var ua = navigator.userAgent.toLowerCase();

   	if (ua.indexOf('ipad') > 0)
   		return false;
	
   	for (var i = 0; i < currentMobileBrowserKeywords.length; i++) {
   		if (ua.indexOf(currentMobileBrowserKeywords[i]) != -1)
   			return true;
   	}

   	return false;
}

function GetMobileUrl(handlerUrl, queryString, text, isStartPage) {
	if (queryString.length > 0) {
		$.getJSON(handlerUrl + queryString + "&callback=?", function (data) {
			mobileUrlFound(data, text, isStartPage);
		});	
	}
}

function mobileUrlFound(data, text, isStartPage) {
	if (data != null && data.status == "Ok") {
   		if (isStartPage)
   			window.location = data.url;
   		else {
   			var content = "<div id='mobile-redirect-box'><a href='" + data.url + "'>" + text + "</a></div>";

   			$('#wrap').prepend(content);
   		}
	}
}

function performMobileCheck(handlerUrl, queryString, text, isStartPage) {
	if (CheckIsMobile())
   		GetMobileUrl(handlerUrl, queryString, text, isStartPage);
}

function getTweets(tweeturl, tweetErrorText) {
	var html = "<ul>";

	try {
		$.getJSON(tweeturl, function (d) {
			$.each(d, function (i, item) {
				html += "<li>" + urlify(item.text) + "</li>";
			});

			html += "</ul>";

			$('#tweets').html(html);
		});
	} catch (e) {
		$('#tweets').html(tweetErrorText);
	}

	setTimeout('setErrorAfterTimeout()', 3000);
}

function setErrorAfterTimeout(tweetLoadingText, tweetErrorText) {
	if ($('#tweets').html() == tweetLoadingText)
		$('#tweets').html(tweetErrorText);
}

function urlify(text) {
	var urlRegex = /(https?:\/\/[^\s]+)/g;
	return text.replace(urlRegex, function (url) {
		return '<a href="' + url + '" target="_blank">' + url + '</a>';
	});
}

