/*
 * 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
*/
		  
/*!!!!!!!!!!!!!!!!! edit below this line at your own risk !!!!!!!!!!!!!!!!!!!!!!!*/

//on page load call ib_init
$(document).ready(function(){   
	ib_init('a.imagebox, area.imagebox, input.imagebox');//pass where to apply imagebox
});

//add imagebox to href & area elements that have a class of .imagebox
function ib_init(domChunk){
	$(domChunk).click(function(){
	var t = this.title || this.name || null;
	var a = this.href || this.alt;
	var g = this.rel || false;
	ib_show(t,a,g);
	this.blur();
	return false;
	});
}

function ib_show(caption, url, imageGroup) {//function called when the user clicks on a imagebox link

	try {
		if (typeof document.body.style.maxHeight === "undefined") {//if IE 6
			$("body","html").css({height: "100%", width: "100%"});
			$("html").css("overflow","hidden");
			if (document.getElementById("IB_HideSelect") === null) {//iframe to hide select elements in ie6
				$("body").append("<iframe id='IB_HideSelect'></iframe><div id='IB_overlay'></div><div id='IB_window'></div>");
				$("#IB_overlay").click(ib_remove);
			}
		}else{//all others
			if(document.getElementById("IB_overlay") === null){
				$("body").append("<div id='IB_overlay'></div><div id='IB_window'></div>");
				$("#IB_overlay").click(ib_remove);
			}
		}
		
		if(ib_detectMacXFF()){
			$("#IB_overlay").addClass("IB_overlayMacFFBGHack");//use png overlay so hide flash
		}else{
			$("#IB_overlay").addClass("IB_overlayBG");//use background and opacity
		}
		
		if(caption===null){
			caption="";
		}
		else{
			caption = "<h2 id='vb-title'>"+caption+"</h2>";
		}
		$("body").append("<div id='IB_load'></div>");//add loader to the page
		$('#IB_load').show();//show loader

		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);

		if(urlType == '.jpg' || urlType == '.jpeg' || urlType == '.png' || urlType == '.gif' || urlType == '.bmp'){//code to show images
				
			IB_PrevCaption = "";
			IB_PrevURL = "";
			IB_PrevHTML = "";
			IB_NextCaption = "";
			IB_NextURL = "";
			IB_NextHTML = "";
			IB_imageCount = "";
			IB_FoundURL = false;
			if(imageGroup){
				IB_TempArray = $("a[rel="+imageGroup+"]").get();
				for (IB_Counter = 0; ((IB_Counter < IB_TempArray.length) && (IB_NextHTML === "")); IB_Counter++) {
					var urlTypeTemp = IB_TempArray[IB_Counter].href.toLowerCase().match(urlString);
						if (!(IB_TempArray[IB_Counter].href == url)) {						
							if (IB_FoundURL) {
								IB_NextCaption = IB_TempArray[IB_Counter].title;
								IB_NextURL = IB_TempArray[IB_Counter].href;
								IB_NextHTML = "<span id='IB_next'>&nbsp;&nbsp;<a href='#'>Následující &gt;</a></span>";
							} else {
								IB_PrevCaption = IB_TempArray[IB_Counter].title;
								IB_PrevURL = IB_TempArray[IB_Counter].href;
								IB_PrevHTML = "<span id='IB_prev'>&nbsp;&nbsp;<a href='#'>&lt; Předchozí</a></span>";
							}
						} else {
							IB_FoundURL = true;
							IB_imageCount = "<p id='vb-imgCount'>Obrázek " + (IB_Counter + 1) +" z "+ (IB_TempArray.length)+ '</p>';											
						}
				}
			}

			imgPreloader = new Image();
			imgPreloader.onload = function(){		
			imgPreloader.onload = null;
				
			// Resizing large images - orginal by Christian Montoya edited by me.
			var pagesize = ib_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
			
			IB_WIDTH = imageWidth + 34;
			IB_HEIGHT = imageHeight + 60;

			
	//<table id='vb-wrap'><tr><td id='vb-tl'></td><td id='vb-t'></td><td id='vb-tr'></td></tr><tr><td id='vb-l'></td><td id='vb-content'>
	//</td><td id='vb-r'></td></tr><tr><td id='vb-bl'></td><td id='vb-b'></td><td id='vb-br'></td></tr></table>
	
	
			$("#IB_window").append("<table id='vb-wrap'><tr><td id='vb-tl'></td><td id='vb-t'></td><td id='vb-tr'></td></tr><tr><td id='vb-l'></td><td id='vb-content'>"+IB_imageCount + caption+"<a href='' id='IB_ImageOff' title='Zavřít'><img id='IB_Image' src='"+url+"' width='"+imageWidth+"' height='"+imageHeight+"' alt=''/></a></td><td id='vb-r'></td></tr><tr><td id='vb-bl'></td><td id='vb-b'></td><td id='vb-br'></td></tr></table><a href='#' id='IB_closeWindowButton'>Zavřít</a>" + IB_PrevHTML + IB_NextHTML); 		
			
			$("#IB_closeWindowButton").click(ib_remove);
			
			if (!(IB_PrevHTML === "")) {
				function goPrev(){
					if($(document).unbind("click",goPrev)){$(document).unbind("click",goPrev);}
					$("#IB_window").remove();
					$("body").append("<div id='IB_window'></div>");
					ib_show(IB_PrevCaption, IB_PrevURL, imageGroup);
					return false;	
				}
				$("#IB_prev").click(goPrev);
			}
			
			if (!(IB_NextHTML === "")) {		
				function goNext(){
					$("#IB_window").remove();
					$("body").append("<div id='IB_window'></div>");
					ib_show(IB_NextCaption, IB_NextURL, imageGroup);				
					return false;	
				}
				$("#IB_next").click(goNext);
				
			}

			document.onkeydown = function(e){ 	
				if (e == null) { // ie
					keycode = event.keyCode;
				} else { // mozilla
					keycode = e.which;
				}
				if(keycode == 27){ // close
					ib_remove();
				} else if(keycode == 190){ // display previous image
					if(!(IB_NextHTML == "")){
						document.onkeydown = "";
						goNext();
					}
				} else if(keycode == 188){ // display next image
					if(!(IB_PrevHTML == "")){
						document.onkeydown = "";
						goPrev();
					}
				}	
			};
			
			ib_position();
			$("#IB_load").remove();
			$("#IB_ImageOff").click(ib_remove);
			$("#IB_window").css({display:"block"}); //for safari using css instead of show
			};
			
			imgPreloader.src = url;
		}else{//code to show html
			
			var queryString = url.replace(/^[^\?]+\??/,'');
			var params = ib_parseQuery( queryString );

			IB_WIDTH = (params['width']*1) + 34 || 630; //defaults to 630 if no paramaters were added to URL
			IB_HEIGHT = (params['height']*1) + 34 || 440; //defaults to 440 if no paramaters were added to URL
			ajaxContentW = IB_WIDTH - 34;
			ajaxContentH = IB_HEIGHT - 34;
			
			if(url.indexOf('IB_iframe') != -1){// either iframe or ajax window		
					urlNoQuery = url.split('IB_');
					$("#IB_iframeContent").remove();
					if(params['modal'] != "true"){//iframe no modal

						
						$("#IB_window").append("<table id='vb-wrap'><tr><td id='vb-tl'></td><td id='vb-t'></td><td id='vb-tr'></td></tr><tr><td id='vb-l'></td><td id='vb-content'>"+caption+"<iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='IB_iframeContent' name='IB_iframeContent"+Math.round(Math.random()*1000)+"' onload='ib_showIframe()' style='width:"+(ajaxContentW)+"px;height:"+(ajaxContentH)+"px;' > </iframe></td><td id='vb-r'></td></tr><tr><td id='vb-bl'></td><td id='vb-b'></td><td id='vb-br'></td></tr></table><a href='#' id='IB_closeWindowButton'>Zavřít</a>"); 
						
					}else{//iframe modal
					$("#IB_overlay").unbind();
						$("#IB_window").append("<table id='vb-wrap'><tr><td id='vb-tl'></td><td id='vb-t'></td><td id='vb-tr'></td></tr><tr><td id='vb-l'></td><td id='vb-content'><iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='IB_iframeContent' name='IB_iframeContent"+Math.round(Math.random()*1000)+"' onload='ib_showIframe()' style='width:"+(ajaxContentW)+"px;height:"+(ajaxContentH)+"px;' > </iframe></td><td id='vb-r'></td></tr><tr><td id='vb-bl'></td><td id='vb-b'></td><td id='vb-br'></td></tr></table>");
					}
			}else{// not an iframe, ajax
					if($("#IB_window").css("display") != "block"){
						if(params['modal'] != "true"){//ajax no modal
						$("#IB_window").append("<table id='vb-wrap'><tr><td id='vb-tl'></td><td id='vb-t'></td><td id='vb-tr'></td></tr><tr><td id='vb-l'></td><td id='vb-content'>"+ caption + "<div id='vb-ajax' style='width:"+ajaxContentW+"px; height:"+ajaxContentH+"px'></div></td><td id='vb-r'></td></tr><tr><td id='vb-bl'></td><td id='vb-b'></td><td id='vb-br'></td></tr></table><a href='#' id='IB_closeWindowButton'>Zavřít</a>");

						}else{//ajax modal
						$("#IB_overlay").unbind();
						$("#IB_window").append("<table id='vb-wrap'><tr><td id='vb-tl'></td><td id='vb-t'></td><td id='vb-tr'></td></tr><tr><td id='vb-l'></td><td id='vb-content'><div id='vb-ajax' style='width:"+ajaxContentW+"px; height:"+ajaxContentH+"px'></div></td><td id='vb-r'></td></tr><tr><td id='vb-bl'></td><td id='vb-b'></td><td id='vb-br'></td></tr></table>");
						}
					}else{//this means the window is already up, we are just loading new content via ajax
						$("#IB_ajaxContent")[0].style.width = ajaxContentW +"px";
						$("#IB_ajaxContent")[0].style.height = ajaxContentH +"px";
						$("#IB_ajaxContent")[0].scrollTop = 0;
						$("#IB_ajaxWindowTitle").html(caption);
					}
			}
					
			$("#IB_closeWindowButton").click(ib_remove);
			
				if(url.indexOf('IB_inline') != -1){	
					$("#vb-ajax").append($('#' + params['inlineId']).children());
					$("#IB_window").unload(function () {
						$('#' + params['inlineId']).append( $("#vb-ajax").children() ); // move elements back when you're finished
					});
					ib_position();
					$("#IB_load").remove();
					$("#IB_window").css({display:"block"}); 
				}else if(url.indexOf('IB_iframe') != -1){
					ib_position();
					if($.browser.safari){//safari needs help because it will not fire iframe onload
						$("#IB_load").remove();
						$("#IB_window").css({display:"block"});
					}
				}else{
					$("#vb-ajax").load(url += "&random=" + (new Date().getTime()),function(){//to do a post change this load method
						ib_position();
						$("#IB_load").remove();
						ib_init("#IB_ajaxContent a.imagebox");
						$("#IB_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
					ib_remove();
				}	
			};
		}
		
	} catch(e) {
		//nothing here
	}
}

//helper functions below
function ib_showIframe(){
	$("#IB_load").remove();
	$("#IB_window").css({display:"block"});
}

function ib_remove() {
 	$("#IB_imageOff").unbind("click");
	$("#IB_closeWindowButton").unbind("click");
	$("#IB_window").fadeOut("fast",function(){$('#IB_window,#IB_overlay,#IB_HideSelect').trigger("unload").unbind().remove();});
	$("#IB_load").remove();
	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 ib_position() {
$("#IB_window").css({marginLeft: '-' + parseInt((IB_WIDTH / 2),10) + 'px', width: IB_WIDTH + 'px'});
	if ( !(jQuery.browser.msie && jQuery.browser.version < 7)) { // take away IE6
		$("#IB_window").css({marginTop: '-' + parseInt((IB_HEIGHT / 2),10) + 'px'});
	}
}

function ib_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 ib_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 ib_detectMacXFF() {
  var userAgent = navigator.userAgent.toLowerCase();
  if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox')!=-1) {
    return true;
  }
}



