/**
 * jQuery.timers - Timer abstractions for jQuery
 * Written by Blair Mitchelmore (blair DOT mitchelmore AT gmail DOT com)
 * Licensed under the WTFPL (http://sam.zoy.org/wtfpl/).
 * Date: 2009/02/08
 *
 * @author Blair Mitchelmore
 * @version 1.1.2
 *
 **/

jQuery.fn.extend({
	everyTime: function(interval, label, fn, times, belay) {
		return this.each(function() {
			jQuery.timer.add(this, interval, label, fn, times, belay);
		});
	},
	oneTime: function(interval, label, fn) {
		return this.each(function() {
			jQuery.timer.add(this, interval, label, fn, 1);
		});
	},
	stopTime: function(label, fn) {
		return this.each(function() {
			jQuery.timer.remove(this, label, fn);
		});
	}
});

jQuery.event.special

jQuery.extend({
	timer: {
		global: [],
		guid: 1,
		dataKey: "jQuery.timer",
		regex: /^([0-9]+(?:\.[0-9]*)?)\s*(.*s)?$/,
		powers: {
			// Yeah this is major overkill...
			'ms': 1,
			'cs': 10,
			'ds': 100,
			's': 1000,
			'das': 10000,
			'hs': 100000,
			'ks': 1000000
		},
		timeParse: function(value) {
			if (value == undefined || value == null)
				return null;
			var result = this.regex.exec(jQuery.trim(value.toString()));
			if (result[2]) {
				var num = parseFloat(result[1]);
				var mult = this.powers[result[2]] || 1;
				return num * mult;
			} else {
				return value;
			}
		},
		add: function(element, interval, label, fn, times, belay) {
			var counter = 0;
			
			if (jQuery.isFunction(label)) {
				if (!times) 
					times = fn;
				fn = label;
				label = interval;
			}
			
			interval = jQuery.timer.timeParse(interval);

			if (typeof interval != 'number' || isNaN(interval) || interval <= 0)
				return;

			if (times && times.constructor != Number) {
				belay = !!times;
				times = 0;
			}
			
			times = times || 0;
			belay = belay || false;
			
			var timers = jQuery.data(element, this.dataKey) || jQuery.data(element, this.dataKey, {});
			
			if (!timers[label])
				timers[label] = {};
			
			fn.timerID = fn.timerID || this.guid++;
			
			var handler = function() {
				if (belay && this.inProgress) 
					return;
				this.inProgress = true;
				if ((++counter > times && times !== 0) || fn.call(element, counter) === false)
					jQuery.timer.remove(element, label, fn);
				this.inProgress = false;
			};
			
			handler.timerID = fn.timerID;
			
			if (!timers[label][fn.timerID])
				timers[label][fn.timerID] = window.setInterval(handler,interval);
			
			this.global.push( element );
			
		},
		remove: function(element, label, fn) {
			var timers = jQuery.data(element, this.dataKey), ret;
			
			if ( timers ) {
				
				if (!label) {
					for ( label in timers )
						this.remove(element, label, fn);
				} else if ( timers[label] ) {
					if ( fn ) {
						if ( fn.timerID ) {
							window.clearInterval(timers[label][fn.timerID]);
							delete timers[label][fn.timerID];
						}
					} else {
						for ( var fn in timers[label] ) {
							window.clearInterval(timers[label][fn]);
							delete timers[label][fn];
						}
					}
					
					for ( ret in timers[label] ) break;
					if ( !ret ) {
						ret = null;
						delete timers[label];
					}
				}
				
				for ( ret in timers ) break;
				if ( !ret ) 
					jQuery.removeData(element, this.dataKey);
			}
		}
	}
});

jQuery(window).bind("unload", function() {
	jQuery.each(jQuery.timer.global, function(index, item) {
		jQuery.timer.remove(item);
	});
});

/*
 * Thickview (aka Thickbox 3.1) - One Box To Rule Them All.
 * By Cody Lindley (http://www.codylindley.com)
 * Copyright (c) 2007 cody lindley
 * Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php
*/
		  
var TB_IMAGELOADING = "/js/thickview/images/loading.gif";
var TB_IMAGEPATH = "/js/thickview/images";
var TB_SLIDESHOW = false;
var TB_VISIBLE = false;
var TB_TempArray;

var TB_ImageGroup = '';

/*!!!!!!!!!!!!!!!!! edit below this line at your own risk !!!!!!!!!!!!!!!!!!!!!!!*/

//on page load call thickview_init
$(document).ready(function(){   
	thickview_init('a.thickview, a.xbox, a.thickbox, a.lightview');//pass where to apply thickbox
	imgLoader = new Image();// preload image
	imgLoader.src = TB_IMAGELOADING;
});

//add thickbox to href & area elements that have a class of .thickbox
function thickview_init(domChunk){
	$(domChunk).click(function(){
		var t = this.title || this.name || null;
		var a = this.href || this.alt;
		var g = this.rel || false;
		thickview_show(t,a,g);
		this.blur();
		return false;
	});
}

function thickview_slideshow_stop(){
	if (TB_SLIDESHOW) {
		TB_SLIDESHOW = false;
		$(document).stopTime('slideshow');
		$("#TB_slideshow").unbind("click");
	}else{
		return;
	}
}

CLK_COUNTER = 0;

function thickview_show(caption, url, imageGroup) {//function called when the user clicks on a thickbox link

	try {
		
		TB_ImageGroup = imageGroup;
		
		if (TB_VISIBLE === false) {
			
			if (typeof document.body.style.maxHeight === "undefined") {//if IE 6
				$("body","html").css({height: "100%", width: "100%"});
				$("html").css("overflow","hidden");
				if (document.getElementById("TB_HideSelect") === null) {//iframe to hide select elements in ie6
					$("body").append("<iframe id='TB_HideSelect'></iframe><div id='TB_overlay'></div><div id='TB_window'></div>");
				}
			}else{//all others
				if(document.getElementById("TB_overlay") === null){
					$("body").append("<div id='TB_overlay'></div><div id='TB_window'></div>");
				}
			}
			
			if(thickview_detectMacXFF()){
				$("#TB_overlay").addClass("TB_overlayMacFFBGHack");//use png overlay so hide flash
			}else{
				$("#TB_overlay").addClass("TB_overlayBG");//use background and opacity
			}
			
			if(caption===null){caption="";}
			
			// hide flashmovies
			$("object, embed, video").css({"visibility":"hidden"});
			
			$("body").append("<div id='TB_load'><img src='"+imgLoader.src+"' /></div>");//add loader to the page
			$('#TB_load').show();//show loader
			
		}
		
		var hasCaption = (caption.length > 4) ? true : false;
		
		var baseURL;
		if (url.indexOf("?") !== -1) { //ff there is a query string involved
			baseURL = url.substr(0, url.indexOf("?"));
		}else{ 
			baseURL = url;
		}
		
		var urlString, urlType;
		
		var isFlash = false;
		var isImage = false;
		var isMovie = false;
		var isAjax = false;
		var isIframe = false;
		
		/*urlString = /\.swf$/;
		urlType = baseURL.toLowerCase().match(urlString);
		if (urlType == '.swf'){
			isFlash = true;
		}*/
   
		urlString = /\.jpg$|\.jpeg$|\.png$|\.gif$|\.bmp$/;
		urlType = baseURL.toLowerCase().match(urlString);
		if (urlType == '.jpg' || urlType == '.jpeg' || urlType == '.png' || urlType == '.gif' || urlType == '.bmp'){
			isImage = true;
		}
		
		if (isImage){
		
			if (TB_VISIBLE === false) {
			
				$("#TB_overlay").click(function(){
					thickview_remove_image();
					thickview_remove();
				});
				
				TB_PrevHTML = "<span id='TB_prev'><img src='"+TB_IMAGEPATH+"/inner_prev.png' alt='Previous' title='Previous Image' /></span>";
				TB_NextHTML = "<span id='TB_next'><img src='"+TB_IMAGEPATH+"/inner_next.png' alt='Next' title='Next Image' /></span>";
				TB_NextPlayIMAGE = "<img src='"+TB_IMAGEPATH+"/inner_slideshow_play.png' alt='Play' title='Play Slideshow' />";
				TB_NextStopIMAGE = "<img src='"+TB_IMAGEPATH+"/inner_slideshow_stop.png' alt='Stop' title='Stop Slideshow' />";
				TB_NextPlayHTML = "<span id='TB_slideshow'>"+TB_NextPlayIMAGE+"</span>";
				TB_NextStopHTML = "<span id='TB_slideshow'>"+TB_NextStopIMAGE+"</span>";
				
			}
			
			TB_PrevCaption = "";
			TB_PrevURL = "";
			TB_NextCaption = "";
			TB_NextURL = "";
			
			TB_imageCount = "";
			TB_imageCountText = "";
				
			TB_FoundURL = false;
			
			TB_SlideShowHTML = (TB_SLIDESHOW) ? TB_NextStopHTML : TB_NextPlayHTML;
			
			TB_NextLINK = false;
			TB_PrevLINK = false;
			
			TB_Counter = 0;
			CLK_COUNTER++;
			
			if (imageGroup) {
			
				TB_TempArray = $("a[rel="+imageGroup+"]").get();

				for (TB_Counter = 0; TB_Counter < TB_TempArray.length; TB_Counter++) {

					if (TB_TempArray[TB_Counter].href.toLowerCase().indexOf(url.toLowerCase()) !== -1) {
					
						TB_FoundURL = true;
						TB_imageCountText = "Bild " + (TB_Counter + 1) + " von " + (TB_TempArray.length);
						TB_imageCount = "<span id='TB_countview'>" + TB_imageCountText + "</span>";
						TB_FirstCaption = TB_TempArray[0].title;
						TB_FirstURL = TB_TempArray[0].href;
						
						if (TB_Counter > 0) {
							TB_PrevCaption = TB_TempArray[TB_Counter-1].title;
							TB_PrevURL = TB_TempArray[TB_Counter-1].href;
							TB_PrevLINK = true;
						}
						
						if (TB_Counter < TB_TempArray.length-1) {
							TB_NextCaption = TB_TempArray[TB_Counter+1].title;
							TB_NextURL = TB_TempArray[TB_Counter+1].href;
							TB_NextLINK = true;
						}
						
						break;
						
					}
					
				}
			}
			
			if (TB_VISIBLE === true) {
				$("#TB_ImageSizer").addClass('TB_ImageOverlay');
				$("#TB_ImageSizer").append("<div id='TB_load'><img src='"+imgLoader.src+"' /></div>");//add loader to the page
				$("#TB_ImageSizer").css({height:$("#TB_Image").height()+"px"});
				$("#TB_Image").stop(true, true);
				$("#TB_Image").fadeOut("fast", function() {$('#TB_load').show();}); 
			}
			
			
			imgPreloader = new Image();
			imgPreloader.onload = function(){
			
				imgPreloader.onload = null;
					
				// Resizing large images - orginal by Christian Montoya edited by me.
				var pagesize = thickview_getPageSize();
				var x = pagesize[0] - 150;
				var y = pagesize[1] - 150;
				var imageWidth = imgPreloader.width;
				var imageHeight = imgPreloader.height;
				if (imageWidth > x) {
					imageHeight = imageHeight * (x / imageWidth); 
					imageWidth = x; 
					if (imageHeight > y) { 
						imageWidth = imageWidth * (y / imageHeight); 
						imageHeight = y; 
					}
				} else if (imageHeight > y) { 
					imageWidth = imageWidth * (y / imageHeight); 
					imageHeight = y; 
					if (imageWidth > x) { 
						imageHeight = imageHeight * (x / imageWidth); 
						imageWidth = x;
					}
				}
				// End Resizing
				imageHeight = parseInt(imageHeight);
				imageWidth = parseInt(imageWidth);
				
				TB_WIDTH = (imageWidth+30);
				TB_HEIGHT = (imageHeight+60);
				
				if (TB_VISIBLE === false) {
				
					TB_CONSTRUCT = "<div id='TB_ImageSizer'><img id='TB_Image' src='"+url+"' width='"+imageWidth+"' height='"+imageHeight+"' alt='"+caption+"'/></div><div id='TB_closeWindowButton'><img src='"+TB_IMAGEPATH+"/close_large.png' alt='Close' /></div>";
					if (hasCaption) TB_CONSTRUCT += "<div id='TB_caption'>"+caption+"</div>";
					if (imageGroup)	TB_CONSTRUCT += "<div id='TB_control'>" + TB_imageCount + " | " + TB_PrevHTML + TB_NextHTML + " | " + TB_SlideShowHTML + "</div>";
				
					$("#TB_window").append(TB_CONSTRUCT);
					
					$("#TB_Image").hide();
					$("#TB_control").hide();
					
				} else {
				
					$("#TB_Image").css({width:imageWidth+"px", height:imageHeight+"px"});
					$("#TB_Image").attr({src:url});

					if (hasCaption) {
						$("#TB_caption").text(caption);
					}
					if (imageGroup) {
						$("#TB_countview").text(TB_imageCountText);
					}
					
				}
				
				if (hasCaption) $("#TB_caption").width(TB_WIDTH-125);
				if (TB_PrevLINK || TB_NextLINK) $("#TB_control").width(TB_WIDTH-125).show();
				
				if (TB_VISIBLE === false) {
				
					/*$("#TB_closeWindowButton").css({"opacity":0.6}).hover(
						function () {$(this).animate({opacity:0.9})},
						function () {$(this).animate({opacity:0.6})}
					);*/
				
					$("#TB_closeWindowButton").click(function(){
						thickview_remove_image();
						thickview_remove();
					});
					
				}
				
				if (imageGroup) {
					
					function goPrev(){
						if (!TB_PrevLINK) { return; }
						thickview_show(TB_PrevCaption, TB_PrevURL, imageGroup);
						return false;
					}

					if (TB_PrevLINK) {
						$("#TB_prev").unbind("click");
						$("#TB_prev").bind("click", function () {
							thickview_slideshow_stop(); 
							goPrev();
						});
					}else{
						$("#TB_prev").css("opacity","0.5");
					}
					
					function goNext(){
						if (!TB_NextLINK) { return; }
						thickview_show(TB_NextCaption, TB_NextURL, imageGroup);
						return false;
					}

					if (TB_NextLINK) {
						$("#TB_next").unbind("click");
						$("#TB_next").bind("click", function () {
							thickview_slideshow_stop(); 
							goNext();
						});
					}else{
						$("#TB_next").css("opacity","0.5");
					}
					
				}

				
				if (TB_VISIBLE === false) {
					$("#TB_window").css({display:"block"}); //for safari using css instead of show
				}
				
				$("#TB_Image").stop(true, true);
				$("#TB_load").hide().remove();
				$("#TB_ImageSizer").removeClass('TB_ImageOverlay').css({width:imageWidth+"px", height:imageHeight+"px"});
				
				thickview_position();
				
				$("#TB_Image").fadeIn("normal");
				
				/*$("#TB_ImageSizer").animate({width:imageWidth+"px", height:imageHeight+"px"}, 500, "linear", function() {
					$("#TB_Image").fadeIn("normal");
				});*/
				
				
				/*function TB_KeyListener(e) {
					if (e == null) { // ie
						keycode = event.keyCode;
					} else { // mozilla
						keycode = e.which;
					}
					if(keycode == 27){ // close
						thickview_remove();
					} else if(TB_NextLINK && keycode == 39){ // display previous image (190)
						goNext();
					} else if(TB_PrevLINK && keycode == 37){ // display next image (188)
						goPrev();
					}
				}
				
				$("#TB_window").unbind("keydown")
				$("#TB_window").bind("keydown", TB_KeyListener);*/
				
				if (imageGroup) {
			
					var arrowTop = ((imageHeight/2)+8);
					
					var prevWidthBox = ((imageWidth/2)-30);
					if (TB_VISIBLE === false) { $("#TB_window").append("<div id='TB_prev_box'></div>"); }
					$("#TB_prev_box").css({width:prevWidthBox+"px", height:imageHeight+"px", left:"0px", top:"0px"}).hide();
					
					if (TB_VISIBLE === false) { $("#TB_window").append("<div id='TB_prev_arrow'><img src='"+TB_IMAGEPATH+"/prev.png' alt='Next' /></div>"); }
					$("#TB_prev_arrow").css({top:arrowTop+"px"});

					var nextWidthBox = ((imageWidth/2)-30);
					if (TB_VISIBLE === false) { $("#TB_window").append("<div id='TB_next_box'></div>"); }
					$("#TB_next_box").css({width:nextWidthBox+"px", height:imageHeight+"px", left:(imageWidth+30-nextWidthBox)+"px", top:"0px"}).hide();
					
					if (TB_VISIBLE === false) { $("#TB_window").append("<div id='TB_next_arrow'><img src='"+TB_IMAGEPATH+"/next.png' alt='Prev' /></div>"); }
					$("#TB_next_arrow").css({top:arrowTop+"px"});
					
					if (TB_PrevLINK) {
						$("#TB_prev_box").unbind("click");
						$("#TB_prev_box").show().bind("click", function () {
							thickview_slideshow_stop(); 
							goPrev();
						});
						$("#TB_prev_box").hover(
							function () {$("#TB_prev_arrow").show();},
							function () {$("#TB_prev_arrow").hide();}
						);
					}		
						
					if (TB_NextLINK) {
						$("#TB_next_box").unbind("click");
						$("#TB_next_box").show().bind("click", function () {
							thickview_slideshow_stop(); 
							goNext();
						});
						$("#TB_next_box").hover(
							function () {$("#TB_next_arrow").show();},
							function () {$("#TB_next_arrow").hide();}
						);
					}
					
					if (TB_VISIBLE === false) {
						$("#TB_slideshow").toggle(
							function () {
								$("#TB_Image").stop(true, true);
								$(this).html(TB_NextStopIMAGE);
								TB_SLIDESHOW = true;
								goNext();
								$(document).everyTime(4000, 'slideshow', function(){
									if (TB_NextLINK){
										goNext();
									}else{
										thickview_show(TB_FirstCaption, TB_FirstURL, imageGroup);
									}
								});
							},
							function () {
								$("#TB_Image").stop(true, true);
								$(this).html(TB_NextPlayIMAGE);
								TB_SLIDESHOW = false;
								thickview_slideshow_stop();
							}
						);
					}
				
				}
				
				TB_VISIBLE = true;
				
			};
			
			$(imgPreloader).attr({src:url});
			
		} else {//code to show html
			
			$("#TB_overlay").click(thickview_remove);
			
			TB_VISIBLE = true;
			
			var queryString = url.replace(/^[^\?]+\??/,'');
			var params = thickview_parseQuery( queryString );

			TB_WIDTH = (params['width']*1) + 30 || 630; //defaults to 630 if no paramaters were added to URL
			TB_HEIGHT = (params['height']*1) + 40 || 440; //defaults to 440 if no paramaters were added to URL
			ajaxContentW = TB_WIDTH - 30;
			ajaxContentH = TB_HEIGHT - 40;
			
			if( url.indexOf('TB_iframe') != -1){// either iframe or ajax window
			
				urlNoQuery = url.split('TB_');
				$("#TB_iframeContent").remove();
				if(params['modal'] != "true"){//iframe no modal
					
					TB_CONSTRUCT = "<iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='thickview_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;' > </iframe><div id='TB_closeWindowButton' title='Close'><img src='"+TB_IMAGEPATH+"/close_large.png' alt='Close' /></div>";
					if (hasCaption) TB_CONSTRUCT += "<div id='TB_caption'>"+caption+"</div>";
					
					$("#TB_window").append(TB_CONSTRUCT);
					if (hasCaption) $("#TB_caption").width(TB_WIDTH-125);
					
				}else{//iframe modal
					
					$("#TB_overlay").unbind();
					$("#TB_window").append("<iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='thickview_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;'> </iframe>");
					
				}
					
			}else{// not an iframe, ajax
			
				if($("#TB_window").css("display") != "block"){
					
					if(params['modal'] != "true"){//ajax no modal
						
						
						TB_CONSTRUCT = "<div id='TB_ajaxContent' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px'></div><div id='TB_closeWindowButton' title='Close'><img src='"+TB_IMAGEPATH+"/close_large.png' alt='Close' /></div>";
						if (hasCaption) TB_CONSTRUCT += "<div id='TB_caption'>"+caption+"</div>";
						
						$("#TB_window").append(TB_CONSTRUCT);
						if (hasCaption) $("#TB_caption").width(TB_WIDTH-125);
				
					}else{//ajax modal
						$("#TB_overlay").unbind();
						$("#TB_window").append("<div id='TB_ajaxContent' class='TB_modal' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px;'></div>");	
					}
				
				}else{//this means the window is already up, we are just loading new content via ajax
				
					$("#TB_ajaxContent")[0].style.width = ajaxContentW +"px";
					$("#TB_ajaxContent")[0].style.height = ajaxContentH +"px";
					$("#TB_ajaxContent")[0].scrollTop = 0;
					$("#TB_ajaxWindowTitle").html(caption);
					
				}
					
			}
				
			/*$("#TB_closeWindowButton").css({"opacity":0.6}).hover(
				function () {$(this).animate({opacity:0.9})},
				function () {$(this).animate({opacity:0.6})}
			);*/
			
			$("#TB_closeWindowButton").click(thickview_remove);
			
			if(url.indexOf('TB_inline') != -1){	
				$("#TB_ajaxContent").append($('#' + params['inlineId']).children());
				$("#TB_window").unload(function () {
					$('#' + params['inlineId']).append( $("#TB_ajaxContent").children() ); // move elements back when you're finished
				});
				thickview_position();
				$("#TB_load").remove();
				$("#TB_window").css({display:"block"}); 
			}else if(url.indexOf('TB_iframe') != -1){
				thickview_position();
				if($.browser.safari){//safari needs help because it will not fire iframe onload
					$("#TB_load").remove();
					$("#TB_window").css({display:"block"});
				}
			}else{
				$("#TB_ajaxContent").load(url += "&random=" + (new Date().getTime()),function(){//to do a post change this load method
					thickview_position();
					$("#TB_AjaxLoadingText").remove();
					$("#TB_load").remove();
					thickview_init("#TB_ajaxContent a.thickbox");
					$("#TB_window").css({display:"block"});
				});
			}
			
		}

		if(!params['modal']){
			document.onkeyup = function(e){
				if (e == null) { // ie
					keycode = event.keyCode;
				} else { // mozilla
					keycode = e.which;
				}
				/*if(keycode == 27){ // close
					thickview_remove();
				}*/
			};
		}
		
	} catch(e) {
		//nothing here
	}
}

//helper functions below
function thickview_showIframe(){
	$("#TB_load").remove();
	$("#TB_window").css({display:"block"});
}

function thickview_remove_image(){
	if (TB_SLIDESHOW) {
		TB_SLIDESHOW = false;
		$(document).stopTime('slideshow');
		$("#TB_slideshow").unbind("click");
	}
	$("#TB_prev_box,#TB_next_box").trigger("unload").unbind().remove();
}

function thickview_remove() {
	
	//$("#TB_closeWindowButton").unbind("hover");
	$("#TB_closeWindowButton").unbind("click");
	$("#TB_window").fadeOut("fast",function(){$('#TB_window,#TB_overlay,#TB_HideSelect').trigger("unload").unbind().remove();});
	$("#TB_window").remove();
	$("#TB_load").remove();
	
	TB_VISIBLE = false;
	
	// show flashmovies
	$("object, embed, video").css({"visibility":"visible"});
	
	if (typeof document.body.style.maxHeight == "undefined") {//if IE 6
		$("body","html").css({height: "auto", width: "auto"});
		$("html").css("overflow","");
	}
	
	document.onkeydown = "";
	document.onkeyup = "";
	
	return false;
	
}

function thickview_position() {
	$("#TB_window").css({marginLeft: '-' + parseInt((TB_WIDTH / 2),10) + 'px', width: TB_WIDTH + 'px'});
	if ( !(jQuery.browser.msie && jQuery.browser.version < 7)) { // take away IE6
		$("#TB_window").css({marginTop: '-' + parseInt((TB_HEIGHT / 2),10) + 'px'});
	}
}

function thickview_parseQuery ( 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;
}

function thickview_getPageSize(){
	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;
}

function thickview_detectMacXFF() {
  var userAgent = navigator.userAgent.toLowerCase();
  if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox')!=-1) {
    return true;
  }
}

/*
 * -- grayscale.js --
 * Copyright (C) James Padolsey (http://james.padolsey.com)
 *
 */

var grayscale = (function(){
    
    var config = {
            colorProps: ['color','backgroundColor','borderBottomColor','borderTopColor','borderLeftColor','borderRightColor','backgroundImage'],
            externalImageHandler : {
                /* Grayscaling externally hosted images does not work
                   - Use these functions to handle those images as you so desire */
                /* Out of convenience these functions are also used for browsers
                   like Chrome that do not support CanvasContext.getImageData */
                init : function(el, src) {
                    if (el.nodeName.toLowerCase() === 'img') {
                        // Is IMG element...
                    } else {
                        // Is background-image element:
                        // Default - remove background images
                        data(el).backgroundImageSRC = src;
                        el.style.backgroundImage = '';
                    }
                },
                reset : function(el) {
                    if (el.nodeName.toLowerCase() === 'img') {
                        // Is IMG element...
                    } else {
                        // Is background-image element:
                        el.style.backgroundImage = 'url(' + (data(el).backgroundImageSRC || '') + ')';
                    }
                }
            }
        },
        log = function(){
            try { window.console.log.apply(console, arguments); }
            catch(e) {};
        },
        isExternal = function(url) {
            // Checks whether URL is external: 'CanvasContext.getImageData'
            // only works if the image is on the current domain.
            return (new RegExp('https?://(?!' + window.location.hostname + ')')).test(url);
        },
        data = (function(){
            
            var cache = [0],
            expando = 'data' + (+new Date());
            
            return function(elem) {
                var cacheIndex = elem[expando],
                    nextCacheIndex = cache.length;
                if(!cacheIndex) {
                    cacheIndex = elem[expando] = nextCacheIndex;
                    cache[cacheIndex] = {};
                }
                return cache[cacheIndex];
            };
            
        })(),
        desatIMG = function(img, prepare, realEl) {
            
            // realEl is only set when img is temp (for BG images)
            
            var canvas = document.createElement('canvas'),
                context = canvas.getContext('2d'),
                height = img.naturalHeight || img.offsetHeight || img.height,
                width = img.naturalWidth || img.offsetWidth || img.width,
                imgData;
                
            canvas.height = height;
            canvas.width = width;
            context.drawImage(img, 0, 0);
            try {
                imgData = context.getImageData(0, 0, width, height);
            } catch(e) {}
            
            if (prepare) {
                desatIMG.preparing = true;
                // Slowly recurse through pixels for prep,
                // :: only occurs on grayscale.prepare()
                var y = 0;
                (function(){
                    
                    if (!desatIMG.preparing) { return; }
                    
                    if (y === height) {
                        // Finished!
                        context.putImageData(imgData, 0, 0, 0, 0, width, height);
                        realEl ? (data(realEl).BGdataURL = canvas.toDataURL())
                               : (data(img).dataURL = canvas.toDataURL())
                    }
                    
                    for (var x = 0; x < width; x++) {
                        var i = (y * width + x) * 4;
                        // Apply Monoschrome level across all channels:
                        imgData.data[i] = imgData.data[i+1] = imgData.data[i+2] =
                        RGBtoGRAYSCALE(imgData.data[i], imgData.data[i+1], imgData.data[i+2]);
                    }
                    
                    y++;
                    setTimeout(arguments.callee, 0);
                    
                })();
                return;
            } else {
                // If desatIMG was called without 'prepare' flag
                // then cancel recursion and proceed with force! (below)
                desatIMG.preparing = false;
            }
            
            for (var y = 0; y < height; y++) {
                for (var x = 0; x < width; x++) {
                    var i = (y * width + x) * 4;
                    // Apply Monoschrome level across all channels:
                    imgData.data[i] = imgData.data[i+1] = imgData.data[i+2] =
                    RGBtoGRAYSCALE(imgData.data[i], imgData.data[i+1], imgData.data[i+2]);
                }
            }
            
            context.putImageData(imgData, 0, 0, 0, 0, width, height);
            return canvas;
        
        },
        getStyle = function(el, prop) {
            var style = document.defaultView && document.defaultView.getComputedStyle ? 
                        document.defaultView.getComputedStyle(el, null)[prop]
                        : el.currentStyle[prop];
            // If format is #FFFFFF: (convert to RGB)
            if (style && /^#[A-F0-9]/i.test(style)) {
                    var hex = style.match(/[A-F0-9]{2}/ig);
                    style = 'rgb(' + parseInt(hex[0], 16) + ','
                                   + parseInt(hex[1], 16) + ','
                                   + parseInt(hex[2], 16) + ')';
            }
            return style;
        },
        RGBtoGRAYSCALE = function(r,g,b) {
            // Returns single monochrome figure:
            return parseInt( (0.2125 * r) + (0.7154 * g) + (0.0721 * b), 10 );
        },
        getAllNodes = function(context) {
            var all = Array.prototype.slice.call(context.getElementsByTagName('*'));
            all.unshift(context);
            return all;
        };
        
    var init = function(context) {
        
        // Handle if a DOM collection is passed instead of a single el:
        if (context && context[0] && context.length && context[0].nodeName) {
            // Is a DOM collection:
            var allContexts = Array.prototype.slice.call(context),
                cIndex = -1, cLen = allContexts.length;
            while (++cIndex<cLen) { init.call(this, allContexts[cIndex]); }
            return;
        }
        
        context = context || document.documentElement;
        
        if (!document.createElement('canvas').getContext) {
            context.style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(grayscale=1)';
            context.style.zoom = 1;
            return;
        }
        
        var all = getAllNodes(context),
            i = -1, len = all.length;
            
        while (++i<len) {
            var cur = all[i];
            
            if (cur.nodeName.toLowerCase() === 'img') {
                var src = cur.getAttribute('src');
                if(!src) { continue; }
                if (isExternal(src)) {
                    config.externalImageHandler.init(cur, src);
                } else {
                    data(cur).realSRC = src;
                    try {
                        // Within try statement just encase there's no support....
                        cur.src = data(cur).dataURL || desatIMG(cur).toDataURL();
                    } catch(e) { config.externalImageHandler.init(cur, src); }
                }
                
            } else {
                for (var pIndex = 0, pLen = config.colorProps.length; pIndex < pLen; pIndex++) {
                    var prop = config.colorProps[pIndex],
                    style = getStyle(cur, prop);
                    if (!style) {continue;}
                    if (cur.style[prop]) {
                        data(cur)[prop] = style;
                    }
                    // RGB color:
                    if (style.substring(0,4) === 'rgb(') {
                        var monoRGB = RGBtoGRAYSCALE.apply(null, style.match(/\d+/g));
                        cur.style[prop] = style = 'rgb(' + monoRGB + ',' + monoRGB + ',' + monoRGB + ')';
                        continue;
                    }
                    // Background Image:
                    if (style.indexOf('url(') > -1) {
                        var urlPatt = /\(['"]?(.+?)['"]?\)/,
                            url = style.match(urlPatt)[1];
                        if (isExternal(url)) {
                            config.externalImageHandler.init(cur, url);
                            data(cur).externalBG = true;
                            continue;
                        }
                        // data(cur).BGdataURL refers to caches URL (from preparation)
                        try {
                            var imgSRC = data(cur).BGdataURL || (function(){
                                    var temp = document.createElement('img');
                                    temp.src = url;
                                    return desatIMG(temp).toDataURL();
                                })();
                            
                            cur.style[prop] = style.replace(urlPatt, function(_, url){
                                return '(' + imgSRC + ')';
                            });
                        } catch(e) { config.externalImageHandler.init(cur, url); }
                    }
                }
            }
        }
        
    };
    
    init.reset = function(context) {
        // Handle if a DOM collection is passed instead of a single el:
        if (context && context[0] && context.length && context[0].nodeName) {
            // Is a DOM collection:
            var allContexts = Array.prototype.slice.call(context),
                cIndex = -1, cLen = allContexts.length;
            while (++cIndex<cLen) { init.reset.call(this, allContexts[cIndex]); }
            return;
        }
        context = context || document.documentElement;
        if (!document.createElement('canvas').getContext) {
            context.style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(grayscale=0)';
            return;
        }
        var all = getAllNodes(context),
            i = -1, len = all.length;
        while (++i<len) {
            var cur = all[i];
            if (cur.nodeName.toLowerCase() === 'img') {
                var src = cur.getAttribute('src');
                if (isExternal(src)) {
                    config.externalImageHandler.reset(cur, src);
                }
                cur.src = data(cur).realSRC || src;
            } else {
                for (var pIndex = 0, pLen = config.colorProps.length; pIndex < pLen; pIndex++) {
                    if (data(cur).externalBG) {
                        config.externalImageHandler.reset(cur);
                    }
                    var prop = config.colorProps[pIndex];
                    cur.style[prop] = data(cur)[prop] || '';
                }
            }
        }
    };
    
    init.prepare = function(context) {
        
        // Handle if a DOM collection is passed instead of a single el:
        if (context && context[0] && context.length && context[0].nodeName) {
            // Is a DOM collection:
            var allContexts = Array.prototype.slice.call(context),
                cIndex = -1, cLen = allContexts.length;
            while (++cIndex<cLen) { init.prepare.call(null, allContexts[cIndex]); }
            return;
        }
        
        // Slowly recurses through all elements
        // so as not to lock up on the user.
        
        context = context || document.documentElement;
        
        if (!document.createElement('canvas').getContext) { return; }
        
        var all = getAllNodes(context),
            i = -1, len = all.length;
        
        while (++i<len) {
            var cur = all[i];
            if (data(cur).skip) { return; }
            if (cur.nodeName.toLowerCase() === 'img') {
                if (cur.getAttribute('src') && !isExternal(cur.src)) {
                    desatIMG(cur, true);
                }
                
            } else {
                var style = getStyle(cur, 'backgroundImage');
                if (style.indexOf('url(') > -1) {
                    var urlPatt = /\(['"]?(.+?)['"]?\)/,
                        url = style.match(urlPatt)[1];
                    if (!isExternal(url)) {
                        var temp = document.createElement('img');
                        temp.src = url;
                        desatIMG(temp, true, cur);
                    }
                }
            }
        }
    };
    
    return init;

})();

$(document).ready(function(){
	
	$("a[href][target$='blank']").filter(function(){
			return (this.firstChild.nodeType === 3);
		}).css({
			"background":"transparent url(/js/thickview/icons/external.png) scroll no-repeat center right",
			"paddingRight":"12px"
	});
	
	$(window).bind("beforeunload", function(){
		$("object, embed").hide();
	});
	
});
