﻿jQuery.loadImage = function(src, callback) {
	var img = new Image();
	$(img).load(function() {
		callback();
	}).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;

	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);

		if ($("#" + $(this).attr("id").substr(5) + "-tab").length > 0) {
			$(this).addClass("nav-parent");
		}

		var tabIsActive = false;

		$(this).find(".navigation-products-list-2, .navigation-products-list-3").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");
				var tabContainer = tab.find(".nav-tab-container, #navigation-logo-tab");
				tabContainer.removeClass("nav-tab-container-outside-screen");
				if (tab.position().left > 584) {
					tabContainer.css("left", -tabContainer.width() + tab.width() + 28);
				}
			};

			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();
	});

	// 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;
};

// Javascript menu expand/collapse function
$(document).ready(function() {
	if (!($.browser.msie && $.browser.version == 6.0)) {
		$("span.structural").click(function() {
			$(this).next("ul").slideToggle(300);
		});
	}
});

// 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() {
		//alert(this.href);
		//Compare the anchor tag's host name with location's host name
		return this.hostname && this.hostname !== location.hostname && this.hostname !== "dam.husqvarna.com";
	}).attr("target", "_blank");
});

/* Google search textbox and button scripts */
function initGoogleSearch(originalText, textBox, searchButton) {
	var originalColor = textBox.css("color");
	if (textBox.val() != originalText) {
		textBox.css("color", "#fff");
	}
	textBox.focus(function() {
		$(this).css("color", "#fff");
		if ($(this).val() == originalText) {
			$(this).val("");
		}
	});
	textBox.blur(function() {
		if ($.trim($(this).val()) == "") {
			$(this).css("color", originalColor);
			$(this).val(originalText);
		}
	});
	searchButton.click(function(event) {
		if (textBox.val() == originalText) {
			textBox.val("");
			//event.preventDefault();
		}
	});
}

$.fn.tooltip = function(title, text, x, y, ttl) {
	var xOffset = -47;
	var yOffset = 5;
	var item = $(this);
	var currentTip;

	if (ttl > 0) {
		createToolTip();
		updateToolTipPos();
		setTimeout(function() {
			removeToolTip();
		}, ttl);
		return;
	}

	function createToolTip() {
		var t = $('<div style="display: none;" class="tooltip"><div class="tooltip-content"><h4>' + title + '</h4><p>' + text + '</p></div><div class="tooltip-bottom"/></div>');
		currentTip = t.appendTo("body");
		setTimeout(function() {
			if (currentTip != null) {
				if ($.browser.msie)
					currentTip.show();
				else
					currentTip.fadeIn(200);
			}
		}, 300);
	}

	function removeToolTip() {
		if (currentTip != null) {
			if ($.browser.msie)
				currentTip.remove();
			else
				currentTip.fadeOut(200, function() { $(this).remove() });
		}
	}

	function updateToolTipPos(e) {
		if (e) { x = e.pageX; y = e.pageY; };
		if (currentTip == null) return;
		if ($.browser.msie && $.browser.version == 6.0) {
			currentTip.css({
				bottom: $(window).scrollTop() + $(window).height() - y + yOffset,
				left: x + xOffset
			});
		}
		else {
			currentTip.css({
				bottom: $(window).height() - y + yOffset,
				left: x + xOffset
			});
		}
	}

	$(this).hover(function(e) {
		createToolTip();
	}, function() {
		removeToolTip();
	}).mousemove(function(e) {
		updateToolTipPos(e);
	});
}

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 - 50
		            });
		        }
		        else {
		            currentTip.css({
		                bottom: $(window).height() - e.pageY + 5,
		                left: e.pageX - 50
		            });
		        }
		    }
		});
}

function initProductListTooltip(tooManyTitle, tooManyText, tooFewTitle, tooFewText) {
	$("ul.product-list li input:checkbox").click(function(e) {
		var checkbox = $(this);
		if ($("ul.product-list li input:checkbox:checked").length > 4) {
			$(this).tooltip(tooManyTitle, tooManyText, e.pageX, e.pageY, 5000);
			e.preventDefault();
		}
	});

	$("input.compare-btn").click(function(e) {
		$(this).blur();
		if ($("ul.product-list li input:checkbox:checked").length < 1) {
			$(this).tooltip(tooFewTitle, tooFewText, e.pageX, e.pageY, 5000);
			e.preventDefault();
		}
	});
	
}

function initFormTooltip() {
	$(".form-field input:text[title], .form-field textarea[title]").each(function() {
		var title = $(this).closest(".form-field").find("label").text();
		var text = $(this).attr("title");
		$(this).removeAttr("title").tooltip(title, text);
	});
}

/* 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></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: src,
		maxVideoHeight: h,
		maxVideoWidth: w,
		skin: vpath + '/flash/VideoSkin.swf'
	};

	if (typeof (x) != "undefined" && typeof (y) != "undefined") {
		flashvars.xPos = x;
		flashvars.yPos = y;
	}

	var params = {
		scale: "noScale",
		salign: "tl",
		wmode: "transparent",
		menu: false
	};

	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();
}


///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) { }

});

function trackVirtualPageView(path) {
	var url = location.pathname + path;
	_gaq.push(['local._trackPageview', url]);
	_gaq.push(['global._trackPageview', url]);
}

/**
* 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.3.0 Beta 1
* @author Khavilo Dmitry
* @mailto wm.morgun@gmail.com
**/

(function($) {
    /* Little trick to remove event bubbling that causes events recursion */
    var CB = function(e) {
        if (!e) var e = window.event;
        e.cancelBubble = true;
        if (e.stopPropagation) e.stopPropagation();
    };

    $.fn.checkbox = function(options) {
        /* IE6 background flicker fix */
        try { document.execCommand('BackgroundImageCache', false, true); } catch (e) { }

        /* Default settings */
        var settings = {
            cls: 'jquery-checkbox',  /* checkbox  */
            empty: 'empty.png'  /* 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; /* Reference to DOM Element*/
            var $ch = addEvents(ch); /* Adds custom events and returns, jQuery enclosed object */

            /* Removing wrapper if already applied  */
            if (ch.wrapper) ch.wrapper.remove();

            /* Creating wrapper 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:eq(0)');
            ch.wrapper.hover(
				function(e) { ch.wrapperInner.addClass(settings.cls + '-hover'); CB(e); },
				function(e) { ch.wrapperInner.removeClass(settings.cls + '-hover'); CB(e); }
			);

            /* Wrapping checkbox */
            $ch.css({ position: 'absolute', zIndex: -1, visibility: 'hidden' }).after(ch.wrapper);

            /* Ttying to find "our" label */
            var label = false;
            if ($ch.attr('id')) {
                label = $('label[for=' + $ch.attr('id') + ']');
                if (!label.length) label = false;
            }
            if (!label) {
                /* Trying to utilize "closest()" from jQuery 1.3+ */
                label = $ch.closest ? $ch.closest('label') : $ch.parents('label:eq(0)');
                if (!label.length) label = false;
            }
            /* Labe found, applying event hanlers */
            if (label) {
                label.hover(
					function(e) { ch.wrapper.trigger('mouseover', [e]); },
					function(e) { ch.wrapper.trigger('mouseout', [e]); }
				);
                label.click(function(e) { $ch.trigger('click', [e]); CB(e); return false; });
            }
            ch.wrapper.click(function(e) { $ch.trigger('click', [e]); CB(e); return false; });
            $ch.click(function(e) { CB(e); });
            $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 for IE */
            $('img', ch.wrapper).bind('dragstart', function() { return false; }).bind('mousedown', function() { return false; });

            /* Firefox 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").checkbox({
        cls: 'pmc-checkbox',  /* checkbox  */
        empty: vpath + 'images/blank.gif'  /* checkbox  */
    });
})(jQuery);

//
$(document).ready(function() {

    var $productLists = $('ul.product-list'), productListsCount = $productLists.length, i;

    for (i = 0; i < productListsCount; i++) {
	    $('li.product-item', $productLists[i]).equalHeights();
    }

    $('li.product-item').prepend('<div class="product-item-hover"></div>').each(function() {
        var $div = $('> div.product-item-hover', this).css('opacity', 0);
        $(this).hover(function() {
            $div.stop().fadeTo(500, 1);
        }, function() {
            $div.stop().fadeTo(500, 0);
        });
    });

    $('a.productCategoryStartImage').prepend('<span class="productCategoryStartImage-hover"></div>').each(function() {
    var $span = $('> span.productCategoryStartImage-hover', this).css('opacity', 0);
        $(this).hover(function() {
            $span.stop().fadeTo(500, 1);
        }, function() {
            $span.stop().fadeTo(500, 0);
        });
    });

	if(window.PIE) {
		PIE.attach($('#navigation')[0]);
		$('ul.product-list li.product-item').each(function () {
			PIE.attach(this);
		});
	}
});

/*
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);
}
