/*! Laerdal.js
 */
var hideTimer, fadeTimer;
var _appRoot = "";
_siteRoot = "";

var _activeMenu = null;
var _activeMenuTimeout = null;
var _activeMenuImages = {};


if (typeof $ != "undefined") {
    $(document).ready(function () {
        $("a[rel=InlineFlvPlayer]").each(function () {
            replaceLinkWithFlashPlayer(this);
        });
        $("a.trackPageView").each(function () {
            enableLinkTracking(this);
        });

        //Navbar setup
        try {

            $("#navbar-items a.menu-title").click(function () {  // disable click
                return false;
            });

            $("#navbar-items table.navMenuTable li a").bind("mouseover", function () {
                var $t = $(this);
                var img = _activeMenuImages[this.id];
                if (img) {
                    $t.parents("td").find("a>img").attr("src", img);
                }
            });



            function doOpen() {
                if (_activeMenu != null && _activeMenu != this) {
                    $(_activeMenu).children('div.menu-container').hide();
                }
                if (_activeMenuTimeout)
                    window.clearTimeout(_activeMenuTimeout);

                _activeMenu = this;
                $("#navbar-items li.menu-title a.selected").addClass("x-selected").removeClass("selected");


                var $m = $(this).children('div.menu-container');
                $m.show();

                if ($.browser.msie && $.browser.version < 9) {
                    if ($m.find("div.ie-dropShadow").length == 0) {
                        $w = $('<div class="ie-dropShadow">&nbsp;</div>"')
                        $w.css('height', $m.children().height());
                        $w.css('width', $m.children().width());                        
                        $m.append($w);                        
                    }
                }
                

                // scan and load images:
                var imgBase = $("td>a>img").first().attr("src");
                if (imgBase) {
                    imgBase = imgBase.substring(0, imgBase.lastIndexOf("/")) + "/";
                }
                $m.find('a[id^="i_"]').each(function () {
                    if (!_activeMenuImages[this.id]) {
                        var src = imgBase + this.id.substring(2) + ".jpg";
                        _activeMenuImages[this.id] = src;
                        $("<img/>")[0].src = src; // preload the image                        
                    }
                });

            }

            function doClose() {
                var t = this;
                _activeMenuTimeout = window.setTimeout(function () {
                    _activeMenuTimeout = null;
                    $("#navbar-items li.menu-title a.x-selected").addClass("selected").removeClass("x-selected");
                    $(t).children('div.menu-container:visible').slideUp(200);
                }, 250);
            }

            var config = {
                sensitivity: 3,  // sensitivity threshold (must be 1 or higher)    
                interval: 50,    // milliseconds for onMouseOver polling interval    
                over: doOpen,    // function = onMouseOver callback (REQUIRED)    
                timeout: 0,      // milliseconds delay before onMouseOut    
                out: doClose     // function = onMouseOut callback (REQUIRED)
            };

            $("#navbar li.menu-title").hoverIntent(config);


        } catch (exp) { }

        searchSetup();

        if ($.fn.colorbox == null) {
            $.fn.colorbox = function (options) {
                openPopup(options.href, options.width, options.height);
            };
        }

        if ($.fancybox) {
            $('a.popup').fancybox({
                'transitionIn': 'elastic',
                'transitionOut': 'none',
                'type': 'iframe',
                'width': 1000,
                'height': 600
            });
            $('a[rel^=SlideShow]').fancybox({
                'transitionIn': 'elastic',
                'transitionOut': 'none',
                'titlePosition': 'inside',
                'cyclic': true,
                'changeSpeed': 0,
                'titleFormat': function (title, currentArray, currentIndex, currentOpts) {
                    return '<table width=""100%""><tr><td>' + title + '</td><td align=""right"">' + (currentIndex + 1) + ' / ' + currentArray.length + '</td></tr></table>';
                }
            });
        }
    });
}

function replaceLinkWithFlashPlayer(anchor) {
	$img = $("img", anchor);

	var w = $img.width();
	var h = $img.height();

	if (w == null) { w = 400; }
	if (h == null) { h = 300; }

	var imgPath = escape($img.attr('src'));

	var url = escape(anchor.href);

	var html = '<embed src="http://www.laerdal.com/script/flv_player/player_flv_maxi.swf" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="' + w + '" height="' + h + '"'
			 + ' FlashVars="flv=' + url + '&amp;startimage=' + imgPath + '&amp;showplayer=autohide&amp;showiconplay=1&amp;autoplay=0&amp;margin=4&amp;playercolor=000000&amp;bgcolor1=d0d0d0&amp;bgcolor2=808080&amp;videobgcolor=ffffff&amp;volume=100&amp;showstop=1&amp;showvolume=1&amp;showtime=1&amp;showfullscreen=1&amp;"></embed>';

	$(anchor).replaceWith(html);
}


function enableLinkTracking(linkEl) {
	if (typeof (_gaq) == 'undefined') {
		return;
	}

	$(linkEl).click(function () {
		_gaq.push(["_trackPageview", $(this).attr('href')]);
	});
}

function openCountryPopup(evt) {
	var div = $('#countryPopup');
	var setupHideFn = function () {
		window.setTimeout(function () {
			$(document).click(function (e) {
				$('#countryPopup').hide();
				$(document).unbind(e);
			});
		}, 100);
	};
	if (div.length > 0) {
		if (!div.is(":visible")) {
			div.show();
			setupHideFn();
		}
		return;
	}
	var showFn = function (html) {
		html = html.replace(/\{0\}/g, _appRoot);
		var url = document.location.pathname.replace(_siteRoot, '');
		html = html.replace(/\{1\}/g, url);

		div = $('<div id="countryPopup">' + html + '</div>');
		$('#countrySelect').after(div);
		div.click(function (e) {
			e.stopPropagation();
		});
		setupHideFn();
	};
	$.get(_appRoot + "/countries.htm", null, showFn);
}

function searchSetup() {
	var cache = {},
		lastXhr;
	$("#call2action #searchForm #search-button").click(function (e) {
		var t = $("#call2action #searchForm input")[0];
		if (t.value == t.defaultValue) {
			t.focus();
			t.value = '';
		} else {
			$("#call2action #searchForm").submit();
		}
	});


	$("#call2action #searchForm input").each(function () {
		var info = this.id.split('_');
		var t = this;
		$(this).blur(function () {
			if (t.value === '') {
				t.value = t.defaultValue;
			}
		});
		$(this).click(function () {
			if (t.value == t.defaultValue) {
				t.value = '';
			}
		}).autocomplete({
			minLength: 3,
			source: function (request, response) {
				request.term = request.term.replace(/[^\w-\+]+/, " ");
				if (request.term == t.defaultValue) {
					return;
				}
				for (c in cache) {
					if (request.term.indexOf(c) == 0) {
						var matches = filterSearch(request.term, cache[c], 10);
						response(matches);
						return;
					}
				}
				request['site'] = info[1];
				request['lang'] = info[2];
				lastXhr = $.getJSON(_siteRoot + "/services/search.ashx", request, function (data, status, xhr) {
					if (xhr === lastXhr) {
						cache[request.term] = data;
						response(data.slice(0, 10));
					}
				});
			},
			select: function (event, ui) {
				window.location.href = _siteRoot + "/" + ui.item.url;
			}
		});
	});
}

function filterSearch(term, list, maxCount) {
	var matcher = new RegExp($.ui.autocomplete.escapeRegex(term), "i");
	var newList = [];
	for (var i = 0; i < list.length; i++) {
		var s = (list[i].value || list[i]).replace(/[^\w-\+]+/, " ");
		if (matcher.test(s)) {
			newList.push(list[i]);
			if (newList.length >= maxCount) break;
		}
	}
	return newList;
}


// PREVENT ERROR MESSAGES
try {
	window.onerror = function () {
		return false;
	};
} catch (e) { }


function youtube_popup(id, w, h) {
	if (w == null) {
		w = 560;
	}
	if (h == null) {
		h = 340;
	}
	var url = 'http://www.youtube.com/v/' + id + '&hl=en&fs=1&rel=0&color1=0x111111&color2=0x444444';
	var html = '<embed src="' + url + '" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="' + w + '" height="' + h + '"></embed>';

	doHtmlPopup(html, null, null, '#000');
}

function flv_popup(url, w, h, dummy) {
	if (w == null) {
		w = 560;
	}
	if (h == null) {
		h = 340;
	}

	var playerHtml = '<embed src="' + _appRoot + '/script/flv_player/player_flv_maxi.swf" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="' + w + '" height="' + h + '"' + ' FlashVars="flv=' + escape(url) + '&amp;autoplay=1&amp;margin=0&amp;videobgcolor=000000&amp;volume=75&amp;showstop=1&amp;showvolume=1&amp;showtime=1&amp;showfullscreen=1"></embed>';

	doHtmlPopup(playerHtml, null, null, '#000');
}

function doHtmlPopup(popupHtml, w, h, bgColor) {
	var args = {};

	if (h || w) {
		popupHtml = '<div style="' + (w ? 'width:' + w + ';' : '') + (h ? 'height:' + h + ';' : '') + '">' + popupHtml + '</div>';
	}

	args["content"] = popupHtml;

	if (bgColor) {
		args['onStart'] = function () {
			$("#fancybox-outer").css('backgroundColor', bgColor);
		};
		args['onCleanup'] = function () {
			$("#fancybox-outer").css('backgroundColor', '');
		};
	}

	$.fancybox(args);
}

function openPopup(url, w, h, cssClass) {
	var args = {
		href: url,
		type: 'iframe'
	};

	if (w) {
		args["width"] = w;
	}
	if (h) {
		args["height"] = h;
	}

	$.fancybox(args);
}

function loaderImage(id) {
	return $("<img />").attr({
		'id': id,
		'src': _appRoot + '/images/static/ajax-loader.gif',
		'alt': 'loading'
	});
}

function showImages() {
	$("a[rel=SlideShow]:first").click();
}

function closePopup() {
	$.fancybox.close();
}



var laerdal = {
	ui: {},
	trace: function (msg) {
		if (typeof console != 'undefined' && console.trace)
			console.trace(msg)
	},
	log: function (msg) {
		if (typeof console != 'undefined' && console.log)
			console.log(msg)
	}
};

laerdal.ui.tabs = {
    currentTabId: "?",
    iframesLoaded: [],
    // implement / override in client code
    loadAjax: function (loadTabEl, cmd, qryOpts) {
        alert('implement laerdal.ui.tabs.loadAjax(cmd)');
    },

    showTab: function (id) {        
        id = id.replace('/', '');
        if (id == this.currentTabId)
            return;

        this.currentTabId = id;        

        $("ul#product-tabs li a").removeClass("selected");

        var tab = $("#product-tabs a[href=#" + id + "]").addClass("selected");
        var tabContent = $("#" + tab.attr('id').replace('tab_', 'content_'));
        if (tabContent.length == 0)
            return;

        $(".product-tab-panel").hide();
        tabContent.show();

        var title = tab.text().replace('\u203a', '');

        $.address.title($.address.title().split(' | ')[0] + ' | ' + title);
        var cmd = $("input[name=ajaxcmd]", tabContent);
        if (cmd.length > 0) {
            var opts = cmd.val().split('|');
            if (opts[0] == 'iframe') {
                var reload = opts[1] == null ? false : opts[1] == 'true' ? true : false;
                if (!laerdal.ui.tabs.iframesLoaded["#content_" + id] || reload) {
                    var iframe = $(tabContent).find('iframe');
                    iframe.attr('src', opts[2])
                    laerdal.ui.tabs.iframesLoaded["#content_" + id] = true;
                }
            }
            else {
                laerdal.ui.tabs.loadAjax(tabContent, cmd);
            }
        }
    },
    // call on document ready
    loadFromUrl: function () {
        var t = location.hash.replace("#", "");
        if (t.length > 0)
            laerdal.ui.tabs.showTab(t);
    }
}



laerdal.cart = {
	addItemToCart: function ($qty, $btn, itemNo) {
		$btn.hide();
		var $loadImg = $('<img class="loader" src="' + _appRoot + '/images/static/ajax-loader-small.gif" />');
		$btn.after($loadImg);

		var handler1 = function(o) {
			$loadImg.fadeOut();
			$btn.show();
			var $existingPopup = $("#cboxLoadedContent .addedToCartInfo");
			var html = (o.ResponseHTML ? o.ResponseHTML : o);
			if ($existingPopup.length > 0)
				$existingPopup.fadeOut('fast', function() { $(this).replaceWith(html); });
			else {
				$.fancybox({ content: '<div style="width: 800px">' + html + '</div>' });
			}
			//Update call to action shopping cart item total
			laerdal.cart.updateCartSummary(o);
		};

		var args = { "method": "add", "partId": itemNo, "qty": parseInt($qty.val()), "source": "shop" };
		$.ajax({ url: _siteRoot + "/Services/Cart.ashx", type: "POST", dataType: "json", data: args, success: handler1 });
	},

	updateCartSummary: function (result) {
		if (typeof (result) == "object") {
			var showWithTax = result.ShowSinglePriceWithTax;
			laerdal.call2Action.updateCartSummary(showWithTax ? result.TotalAfterTax : result.TotalBeforeTax, result.Count);
		}
	}
}

/////////////////////////////////////
//Namespace: call2Action
//Info: Methods related to the Call2Action box
/////////////////////////////////////
laerdal.call2Action = {
	updateCartSummary: function (price, itemCount) {
		var hasItems = itemCount && itemCount > 0;
		$("#call2action .cartSummary").toggle(hasItems);
		$("#call2action a#cart-link").toggleClass('expanded', hasItems);
		$("#call2action .totalPrice").html(price);
	}

}

/////////////////////////////////////
//Namespace: shopItems
//Info: Methods related to ShopItemList.ascx usercontrol
/////////////////////////////////////
laerdal.shopItems = {
	addOnEnter: function (evt, itemNo) {
		if (evt.keyCode == 13)
			this.addItemToCart(itemNo);
	},
	addItemToCart: function (itemNo, ic) {  // ic=inputcontainer
		var $container = ic ? $(ic) : $("#item_" + itemNo);
		var $qty = $(".qty", $container);
		var $btn = $("a.cart,.CartButton,.CartButton2", $container);

		laerdal.cart.addItemToCart($qty, $btn, itemNo);
	},
	removeFavItem: function (partNo) {
		var self = this;
		var handler1 = function (result) {
			$(".product-items #item_" + partNo).each(function (i) {
				var index = $(this).index();
				$(this).animate({ opacity: "hide" }, "slow", function () { $(this).remove(); self.rearrangeAfterRemove(index - 2); });
			});
		};

		var args = { method: "delFav", partId: partNo };
		$.ajax({ url: _siteRoot + "/Services/Cart.ashx", type: "POST", dataType: "json", data: args, success: handler1 });
	},
	rearrangeAfterRemove: function (index) {
		var offsetSelector = (index < 0) ? '' : ":gt(" + (index) + ")";

		$(".product-items li" + offsetSelector).each(function (i2, val) {
			$el = $(val);
			if ($el.hasClass("sep")) {
				$el.remove();
			} else if ($el.hasClass("col-1")) {
				$el.removeClass("col-1").addClass("col-3").after('<li class="sep"></li>');
			} else if ($el.hasClass("col-2")) {
				$el.removeClass("col-2").addClass("col-1");
			} else if ($el.hasClass("col-3")) {
				$el.removeClass("col-3").addClass("col-2");
			}
		});
	},

	checkNoData: function (text) {

	}
}

/////////////////////////////////////
//Namespace: Auto Resize IFrame
//Info: Resizes the height of an IFrame according to its content, does not work on remote content
/////////////////////////////////////
laerdal.iframe = {

	resize: function (frameId) {

		var frame = document.getElementById(frameId);

		function iResize() {
			var innerDoc = (frame.contentDocument) ? frame.contentDocument : frame.contentWindow.document;
			frame.height = innerDoc.body.offsetHeight + 10;
		}

		// Check if browser is Safari or Opera.
		if ($.browser.safari || $.browser.opera) {
			// Start timer when loaded.
			$('#' + frameId).load(function () {
				setTimeout(iResize, 100);
			});

			// Safari and Opera need a kick-start.
			var iSource = frame.src;
			frame.src = '';
			frame.src = iSource;
		}
		else {
			$('#' + frameId).load(function () {
				var innerDoc = (frame.contentDocument) ? frame.contentDocument : frame.contentWindow.document;
				frame.height = innerDoc.body.scrollHeight + 10;
			});
		}

	}
}







