﻿/*
    Popcorn version 1.0 - © Copyright 2009 by Isotop AB
    Info: Popcorn is an expanded version of Thickbox. 
    Author: Björn Lennartsson



    ::: Usage :::

    a. To load a image popup gallery (if you do not wan't a gallery you just remove the rel-attribute)
    1. <a href="SOURCE_TO_BIG_IMAGE" class="popcorn" rel="gallery"><img src="THUMB" /></a>
    2. FINISHED!

    b. To load Iframed content
    1. <a href="SOURCE_URL?TB_iframe=true&KeepAlive=true&width=XXX&height=YYY" class="popcorn">IFRAME POP</a>
    2. Erhh, FINISHED!

    c. To load a specific div, any possible who is located on the current page.
    1. On the element that is supposed to pop it, put following: onclick="Popcorn.Pop('DIVS ID/CLASS', null, null);return false;"
    2. You will need to have a button in the div so you can close the overlay, add following: onclick="Popcorn.Close();return false;"
    3. The div should have it's style attribute with display:none, THIS IS IMPORTANT!  
    
*/


var Popcorn = {

	_loaderImg: "/media/gfx/loader.gif",
	_imgPreLoader: null,
	_parentObject: null,
	_currentObject: null,

	Init: function() {
		Popcorn._imgPreLoader = new Image();
		Popcorn._imgPreLoader.src = Popcorn._loaderImg;

		$j('a.popcorn').click(function() {
			var action = this.rev || null;
			var a = this.href || this.alt;
			var g = this.rel || false;
			Popcorn.Pop(null, a, g);
			this.blur();
			return false;
		});

		$j('.genericLightbox a, a.genericLightbox').click(function() {
			Popcorn.Pop("ajax", this.href, false);
			this.blur();
			return false;
		});

		$j('a.videoplayer').click(function() {
			var action = this.rev || null;
			var a = this.href || this.alt;
			var g = this.rel || false;
			var splitUrl = a.split("/");
			var trackname = "";
			if (splitUrl[splitUrl.length - 1] == null || splitUrl[splitUrl.length - 1] == "") {
				trackname = splitUrl[splitUrl.length - 2];
			}
			else {
				trackname = splitUrl[splitUrl.length - 1];
			}
			Popcorn.Pop(null, a + "?TB_iframe=true&KeepAlive=true&width=750&height=510&class=videoplayer&closeText=Luk&trackname=" + trackname, g);
			this.blur();
			return false;
		});
	},

	Pop: function(action, url, group) {
		try {
			if (url == null)
				url = "";
			var queryString = url.replace(/^[^\?]+\??/, '');
			var params = Popcorn.ParseQueryString(queryString);

			// netminers tracking
			if (params['trackname'] != null) {
				postPageview($j("#TopMenu").children("ul").children("li.active").text() + " > Reklamefilm > " + params['trackname'] + " > Vis vindue");
			}
			// Check if we are browsing with <= IE6, because we will need to tweak behaviour i.e. hide select-boxes and set height of overlay.
			if (typeof document.body.style.maxHeight === "undefined") {
				$j("body", "html").css({ height: "100%", width: "100%" });
				$j("html").css("overflow", "hidden");
				if (document.getElementById("TB_HideSelect") === null) {//iframe to hide select elements in ie6
					$j("body").append("<iframe id='TB_HideSelect'></iframe><div id='TB_overlay'></div><div id='TB_window'></div>");
					$j("#TB_overlay").bind('click', { trackname: params["trackname"], exitURL: params["exit"] }, Popcorn.CloseAndRedirect);
				}
			}
			else {
				if (document.getElementById("TB_overlay") === null) {
					$j("body").append("<div id='TB_overlay'></div><div id='TB_window'></div>");
					$j("#TB_overlay").bind('click', { trackname: params["trackname"], exitURL: params["exit"] }, Popcorn.CloseAndRedirect);
				}
			}

			// Check if we are browsing with Mac + Firefox because then we will have to use a transparent PNG instead (to hide flash-content)...
			if (Popcorn.DetectIfMacFirefox())
				$j("#TB_overlay").addClass("TB_overlayMacFFBGHack");
			else
				$j("#TB_overlay").addClass("TB_overlayBG");

			// Add our loader image
			$j("body").append("<div id='TB_load'><img src='" + Popcorn._imgPreLoader.src + "' /></div>");
			$j('#TB_load').show();

			if (action == null) {
				var baseURL;
				if (url.indexOf("?") !== -1) { //ff there is a query string involved
					baseURL = url.substr(0, url.indexOf("?"));
				} else {
					baseURL = url;
				}

				var urlString = /\.jpg$|\.jpeg$|\.png$|\.gif$|\.bmp$/;
				var urlType = baseURL.toLowerCase().match(urlString);

				// Check if we are dealing with images or other content
				if (urlType == '.jpg' || urlType == '.jpeg' || urlType == '.png' || urlType == '.gif' || urlType == '.bmp') {
					TB_PrevURL = "";
					TB_PrevHTML = "<div id='TB_prev_btn'><img src='/media/gfx/zoom_prev.gif' alt='Föregående' id='TB_prev' /></div>";

					TB_NextURL = "";
					TB_NextHTML = "<div id='TB_next_btn'><img src='/media/gfx/zoom_next.gif' id='TB_next' alt='Nästa' /></div>";

					TB_imageCount = "";

					TB_FoundURL = false;
					TB_StartURL = "";
					TB_EndURL = "";

					TB_TempArray = [];

					var initiated = false;

					// If we are dealing with a image gallery
					if (group) {
						TB_TempArray = $j("a[rel=" + group + "]").get();

						for (TB_Counter = 0; ((TB_Counter < TB_TempArray.length) && TB_NextURL === ""); TB_Counter++) {
							var urlTypeTemp = TB_TempArray[TB_Counter].href.toLowerCase().match(urlString);
							if (!(TB_TempArray[TB_Counter].href == url)) {
								if (TB_FoundURL) {
									TB_NextURL = TB_TempArray[TB_Counter].href;
								} else {
									TB_PrevURL = TB_TempArray[TB_Counter].href;
								}
							} else {
								TB_FoundURL = true;
								TB_imageCount = "Bild " + (TB_Counter + 1) + " av " + (TB_TempArray.length);
							}

							if (!initiated) {
								TB_StartURL = TB_TempArray[0].href;
								TB_EndURL = TB_TempArray[TB_TempArray.length - 1].href;
								initiated = true;
							}
						}
					}

					// Check if there is only one image or if there is only one image in the gallery and if so remove the HTML for previous/next button.
					if (TB_TempArray.length <= 1) {
						TB_NextHTML = "";
						TB_PrevHTML = "";
					}

					var img = new Image();
					img.src = url;

					if (img.complete) {

						// Set options for Image viewer            
						TB_WIDTH = 639;
						TB_HEIGHT = 649;
						IMG_LEFT = parseInt(((TB_WIDTH - img.width) / 2), 10);

						$j('#TB_window').addClass('imagewindow');
						$j("#TB_window").append("<img id='TB_Image' src='" + url + "' alt='' style='left:" + IMG_LEFT + "px;' />" + "<div id='TB_closeWindow'><img src='/media/gfx/luk_zoom.gif' id='TB_closeWindowButton' alt='St&auml;ng'></div>" + TB_PrevHTML + TB_NextHTML);

						$j("#TB_closeWindowButton").bind('click', { trackname: params["trackname"] }, Popcorn.Close);

						if (!(TB_PrevURL === "")) {
							$j("#TB_prev").click(function() {
								$j("#TB_window").remove();
								$j("body").append("<div id='TB_window'></div>");
								Popcorn.Pop(null, TB_PrevURL, group);
								return false;
							});
						}
						else {
							$j("#TB_prev").click(function() {
								$j("#TB_window").remove();
								$j("body").append("<div id='TB_window'></div>");
								Popcorn.Pop(null, TB_EndURL, group);
								return false;
							});
						}

						if (!(TB_NextURL === "")) {
							$j("#TB_next").click(function() {
								$j("#TB_window").remove();
								$j("body").append("<div id='TB_window'></div>");
								Popcorn.Pop(null, TB_NextURL, group);
								return false;
							});

						}
						else {
							$j("#TB_next").click(function() {
								$j("#TB_window").remove();
								$j("body").append("<div id='TB_window'></div>");
								Popcorn.Pop(null, TB_StartURL, group);
								return false;

							});
						}
						Popcorn.PositionOverlay(params['class'] == "fixposition");
						if (params['class'] == "fixposition")
							$j("#TB_window").css('position', 'fixed');

						$j("#TB_load").remove();
						$j("#TB_window").css({ display: "block" });
					}
					else {

						// Here we will use an onload event for the image so that it will be positioned correctly.
						$j(img).load(function() {

							// Set options for Image viewer            
							TB_WIDTH = 639;
							TB_HEIGHT = 649;
							IMG_LEFT = parseInt(((TB_WIDTH - img.width) / 2), 10);

							$j('#TB_window').addClass('imagewindow');
							$j("#TB_window").append("<img id='TB_Image' src='" + url + "' alt='' style='left:" + IMG_LEFT + "px;' />" + "<div id='TB_closeWindow'><img src='/media/gfx/luk_zoom.gif' id='TB_closeWindowButton' alt='St&auml;ng'></div>" + TB_PrevHTML + TB_NextHTML);

							$j("#TB_closeWindowButton").bind('click', { trackname: params["trackname"] }, Popcorn.Close);

							if (!(TB_PrevURL === "")) {
								$j("#TB_prev").click(function() {
									$j("#TB_window").remove();
									$j("body").append("<div id='TB_window'></div>");
									Popcorn.Pop(null, TB_PrevURL, group);
									return false;
								});
							}
							else {
								$j("#TB_prev").click(function() {
									$j("#TB_window").remove();
									$j("body").append("<div id='TB_window'></div>");
									Popcorn.Pop(null, TB_EndURL, group);
									return false;
								});
							}

							if (!(TB_NextURL === "")) {
								$j("#TB_next").click(function() {
									$j("#TB_window").remove();
									$j("body").append("<div id='TB_window'></div>");
									Popcorn.Pop(null, TB_NextURL, group);
									return false;
								});

							}
							else {
								$j("#TB_next").click(function() {
									$j("#TB_window").remove();
									$j("body").append("<div id='TB_window'></div>");
									Popcorn.Pop(null, TB_StartURL, group);
									return false;

								});
							}
							Popcorn.PositionOverlay(params['class'] == "fixposition");
							if (params['class'] == "fixposition")
								$j("#TB_window").css('position', 'fixed');

							$j("#TB_load").remove();
							$j("#TB_window").css({ display: "block" });
						});
					}

					//Popcorn._imgPreLoader.src = url;
				}
				else {

					if (params['class'] == "deakningskarta") {
						TB_WIDTH = 731;
						TB_HEIGHT = 599;
					}
					else if (params['class'] == "videoplayer") {
						TB_WIDTH = 790;
						TB_HEIGHT = 530;
					}
					else if (params['class'] == "testimonial") {
						TB_WIDTH = 600;
						TB_HEIGHT = 365;
					}
					else if (params['class'] == "validationbox") {
						TB_WIDTH = 400;
						TB_HEIGHT = 250;
					}
					else {
						TB_WIDTH = 292;
						TB_HEIGHT = 424;
					}

					ajaxContentW = (params['width'] * 1);
					ajaxContentH = (params['height'] * 1) - 5;

					var closeText = params['closeText'];


					urlNoQuery = url.split('TB_');
					$j("#TB_iframeContent").remove();

					var iframeUrl = urlNoQuery[0];
					if (params['trackname'] != null && params['trackname'] != "")
						iframeUrl = iframeUrl + "division=" + $j("#TopMenu").children("ul").children("li.active").text();

					$j("#TB_window").addClass("iframewindow");
					$j("#TB_window").addClass(params['class']);
					$j("#TB_window").append("<iframe frameborder='0' hspace='0' src='" + iframeUrl + "' id='TB_iframeContent' name='TB_iframeContent" + Math.round(Math.random() * 1000) + "' onload='Popcorn.ShowIframe();' frameborder='0' scrolling='no' style='width:" + (ajaxContentW) + "px;height:" + (ajaxContentH) + "px;z-index:105;' > </iframe><div id='TB_closeIframeWindow'><span class='iframe-closeText'>" + closeText + "</span><img src='/media/gfx/luk.png' id='TB_closeWindowButton' class='iframe-close' alt='Luk'></div>");

					$j("#TB_closeIframeWindow").bind('click', { trackname: params["trackname"], exitURL: params["exit"] }, Popcorn.CloseAndRedirect);

					Popcorn.PositionOverlay(true);
					if (params['class'] == "videoplayer" || params['class'] == "testimonial") {
						$j("#TB_window").css('position', 'fixed');
					}

					// Our friend Safari will need some help since it won't load the Iframe correctly because it lacks interest in onload :-)
					if ($j.browser.safari)
						Popcorn.ShowIframe();
				}
			}
			else if (action == "ajax") {
				$j.ajax({
					url: url,
					success: function(data) {
						$j("#TB_window").append(data.split('<!-- ajax content -->')[1]);
						$j("#TB_window").css({ display: "block" });
						$j("#TB_Content").height(
							$j("#TB_window > div").height() - ($j("#TB_Heading").height() + 30) //30 = heading margin bottom + lightbox padding bottom
                        );
						//adjust iframe to parent size if no size is set on iframe
						if (!$j("#TB_Content iframe").attr('width')) { $j("#TB_Content iframe").attr('width', '100%'); }
						if (!$j("#TB_Content iframe").attr('height')) { $j("#TB_Content iframe").attr('height', '100%'); }

						TB_WIDTH = $j("#TB_window > div").width();
						TB_HEIGHT = $j("#TB_window > div").height();

						Popcorn.PositionOverlay(true);

						$j("#TB_load").remove();

						$j("#TB_window>div").append("<div id='TB_closeWindow' style='top:10px;right:20px;width:auto !important;'>Luk <img src='/media/gfx/luk.png' id='TB_closeWindowButton' alt='Luk' style='margin-left:5px;position:relative;top:3px;.left:4px;'></div>");
						$j("#TB_closeWindow").bind('click', { exitURL: params["exit"] }, Popcorn.CloseAndRedirect);
						$j(".closeLightbox").bind('click', Popcorn.Close);
						//						if (params['exit'] != null) {
						//							alert(params['exit']);
						//						}

						$j(document).ready(function() {
							if (typeof (curvyCorners) !== 'undefined') {
								setTimeout("curvyCorners.scanStyles();", 1);
							}
						});
					},
					error: function() {
						//alert("error");
					}
				});

			}
			else {
				// Action is set, action is basically the DIV id/class that we should fetch html from and pop.
				Popcorn._currentObject = $j(action);
				Popcorn._parentObject = $j(action).parent();
				var markup = $j(action);
				TB_WIDTH = $j(action).width();
				TB_HEIGHT = $j(action).height();

				$j(markup).show();

				$j('#TB_window').append($j(markup));

				Popcorn.PositionOverlay(!(action == "#loginbox")); // positionera ej vert för loginbox

				$j("#TB_load").remove();
				$j("#TB_window").css({ display: "block" });
			}
		}
		catch (ex) {
			// do nada
		}
	},

	Close: function(event) {
		// netminers tracking
		if (event != null && event.data != null && event.data.trackname != null) {
			postPageview($j("#TopMenu").children("ul").children("li.active").text() + " > Reklamefilm > " + event.data.trackname + " > Luk vindue");
		}
		$j("#TB_imageOff").unbind("click");
		$j("#TB_closeWindowButton").unbind("click");
		$j("#TB_window").fadeOut("fast", function() {
			if (Popcorn._currentObject != null) {
				Popcorn._currentObject.hide();
				Popcorn._parentObject.append(Popcorn._currentObject);
				Popcorn._currentObject = Popcorn._parentObject = null;
			}
			/* $j('#TB_window,#TB_overlay,#TB_HideSelect').trigger("unload").unbind().remove();  Ersattes med raden under pga problem med Flashmodulen  */
			$j('#TB_window,#TB_overlay,#TB_HideSelect').remove();
		});
		$j("#TB_load").remove();


		if (typeof document.body.style.maxHeight == "undefined") {
			$j("body", "html").css({ height: "auto", width: "auto" });
			$j("html").css("overflow", "");
		}

		document.onkeydown = "";
		document.onkeyup = "";

		return false;
	},

	CloseAndRedirect: function(event) {
		if (event.data.exitURL == null || event.data.exitURL == undefined) { // Om ej exitURL finns
			Popcorn.Close();
		}
		else {

			$j("#TB_imageOff").unbind("click");
			$j("#TB_closeWindowButton").unbind("click");
			$j("#TB_window").fadeOut(100, function() {
				if (Popcorn._currentObject != null) {
					Popcorn._currentObject.hide();
					Popcorn._parentObject.append(Popcorn._currentObject);
					Popcorn._currentObject = Popcorn._parentObject = null;
				}
				$j('#TB_window,#TB_overlay,#TB_HideSelect').remove();
			});
			$j("#TB_load").remove();

			if (typeof document.body.style.maxHeight == "undefined") {
				$j("body", "html").css({ height: "auto", width: "auto" });
				$j("html").css("overflow", "");
			}

			document.onkeydown = "";
			document.onkeyup = "";

			document.location = event.data.exitURL;
			return false;
		}
	},

	ShowIframe: function() {
		$j("#TB_load").remove();
		$j("#TB_window").css({ display: "block" });
	},

	GetPageSize: function() {
		var de = document.documentElement;
		var w = window.innerWidth || self.innerWidth || (de && de.clientWidth) || document.body.clientWidth;
		var h = window.innerHeight || self.innerHeight || (de && de.clientHeight) || document.body.clientHeight;
		arrayPageSize = [w, h];
		return arrayPageSize;
	},

	PositionOverlay: function(PositionVertically) {
		$j("#TB_window").css({ marginLeft: '-' + parseInt((TB_WIDTH / 2), 10) + 'px', width: TB_WIDTH + 'px', height: TB_HEIGHT + 'px' });
		if (PositionVertically && ($j(window).height() > TB_HEIGHT)) {
			$j("#TB_window").css('top', '50%');
			if (!(jQuery.browser.msie && jQuery.browser.version < 7)) { // take away IE6
				$j("#TB_window").css({ marginTop: '-' + parseInt((TB_HEIGHT / 2), 10) + 'px' });
			}
			else {
				$j("#TB_window").addClass('ie6VerticalPos');
			}
		}
		else{
			scroll(0,0);
		}
	},

	ParseQueryString: function(query) {
		var Params = {};
		if (!query) { return Params; } // return empty object

		var Pairs = query.split(/[;&]/);
		for (var i = 0; i < Pairs.length; i++) {
			var KeyVal = Pairs[i].split('=');
			if (!KeyVal || KeyVal.length != 2) { continue; }
			var key = unescape(KeyVal[0]);
			var val = unescape(KeyVal[1]);
			val = val.replace(/\+/g, ' ');
			Params[key] = val;
		}

		return Params;
	},

	DetectIfMacFirefox: function() {
		var userAgent = navigator.userAgent.toLowerCase();
		if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox') != -1) {
			return true;
		}

		return false;
	}
}


$j(document).ready(function() {
    Popcorn.Init();
});


// Netminers tracking below

document.nmCustomerId = 'tre';
function createCookie(name, value, days) { if (days) { var date = new Date(); date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); var expires = "; expires=" + date.toGMTString(); } else var expires = ""; document.cookie = name + "=" + value + expires + "; path=/"; }
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; }
function eraseCookie(name) { createCookie(name, "", -1); }
function postEvent(type, subType, name, text, number, ignorePageReload) {
	if (ignorePageReload) { var cn = type + '_' + subType + '_' + name + '_' + text + '_' + number; var c = readCookie(cn); if (c == document.location) return; createCookie(cn, document.location); eraseCookie(cn); }
	try {
		var loc = new String(window.document.location); if (loc.length > 800) loc = loc.slice(0, 796) + '...'; var post = document.createElement('script');
		post.src = 'http' + (document.location.protocol == 'https:' ? 's' : '') + '://' + document.nmCustomerId + '.netminers.dk/tracker/dispatch.aspx?action=' + type + '&n=' + Math.random() + '&nav=' + encodeURIComponent(loc) + '&cid=' + document.nmCustomerId + '&sub=' + subType + '&ti1=' + encodeURIComponent(name) + '&tva=' + encodeURIComponent(text) + '&num=' + encodeURIComponent('' + number);
		var parent = document.getElementsByTagName('body'); if (parent.length == 0) parent = document.getElementsByTagName('head'); parent[0].appendChild(post)
	} catch (e) { }
}

// Page View
function postFlashEvent(eventName) { postEvent('PageView', 'Flash', eventName, '', ''); }
function postPageview(eventName) { postEvent('PageView', '', eventName, '', ''); }

