(function($) {

jQuery.fn.gallery = function(settings) {
	var slideLineLeft = 0;
	var gallery_on = false;
	var windowed = false;
	var thisgallery = this;
	thisgallery.currentImg = 0;
	settings = jQuery.extend({
		width: 800,
		height: 600,
		slideshow: false,
		fadespeed: 1000,
	    global: true,
	    addicon: false,
	    overlayclose: false,
	    button: false,
	    window: false
	}, settings);


	if($(thisgallery).length > 0){
		gallery_init();
	}else{
		return;
	}

    if(settings.slideshow){
		var galleryGroups = new Array();
		var galleryGroup = false
		$(thisgallery).each(function(){
			var g = this.rel || false;
			if(g != galleryGroup ){
				galleryGroup = g;
				galleryGroups.push(galleryGroup);
			}
		});
		for(i in galleryGroups){
			var gal = $("a[@rel="+galleryGroups[i]+"]");
			if(gal.length > 1){
				gallery_slideshow(gal);
			}
		}
    }


    function gallery_slideshow(thisgallery){

    	var thisDelay = settings.slideshow;
    	thisgallery.currentImg = 0;


    	$(thisgallery).wrapAll('<div style="position:relative;"></div>');
    	$(thisgallery).css('position','absolute');
    	//$(thisgallery).css('top','50%');
    	$(thisgallery).css('left','0');
    	//$(thisgallery).css('margin','auto');
    	$(thisgallery).hide();
    	//alert($(thisgallery).parent().width())
    	$(thisgallery[thisgallery.currentImg]).show();
    	setTimeout(slideShowNext,thisDelay);

    	function slideShowNext(){
    		if(!gallery_on){
    			$(thisgallery[thisgallery.currentImg]).fadeOut(settings.fadespeed);
    			if(thisgallery.currentImg < thisgallery.length-1){
    				thisgallery.currentImg++;
    			}else{
    				thisgallery.currentImg = 0;
    			}
    			$(thisgallery[thisgallery.currentImg]).fadeIn(settings.fadespeed);

    		}
    		setTimeout(slideShowNext,thisDelay);
    	}
    }


//    add thickbox to href & area elements that have a class of .thickbox
    function gallery_init(){
    	if(settings.addicon){
    		$(thisgallery).each(function(){
    			$(this).append('<img src="'+settings.addicon+'" style="position:absolute;bottom:0;right:0;width:auto;height:auto"/>');
    		});
    	}

    	if(top != self){
    		settings.window = true;
    	}

    	if(window.name == "galleryWindow" ){
    		windowed = true;
    	}

    	if(windowed){
    		thisgallery.currentImg = galleryWindowCurImg;
    		var t = thisgallery[thisgallery.currentImg].title || thisgallery[thisgallery.currentImg].name || null;
    		var a = thisgallery[thisgallery.currentImg].href || thisgallery[thisgallery.currentImg].alt;
    		var g = thisgallery[thisgallery.currentImg].rel || false;

    		$("*","body").hide();

    		gallery_show(t,a,g);



    	}else{

    		if(settings.button){
    			$(settings.button).click(function(){

    	    		var t = thisgallery[thisgallery.currentImg].title || thisgallery[thisgallery.currentImg].name || null;
    	    		var a = thisgallery[thisgallery.currentImg].href || thisgallery[thisgallery.currentImg].alt;
    	    		var g = thisgallery[thisgallery.currentImg].rel || false;

    	    		if(settings.window & !windowed ){
                		openGalleryWindow(t,a,g);
                	}else{
                		gallery_show(t,a,g);
                	}
            		this.blur();
            		return false;
            	});
    		}

    		$(thisgallery).click(function(){
        		var t = this.title || this.name || null;
        		var a = this.href || this.alt;
        		var g = this.rel || false;

            	if(settings.window & !windowed ){
            		openGalleryWindow(t,a,g);
            	}else{
            		gallery_show(t,a,g);
            	}

        		this.blur();
        		return false;
        	});

    	}


    }



    function gallery_show(caption, url, imageGroup) {//function called when the user clicks on a thickbox link
    	gallery_on = true;
    	slideLineLeft = 0;


    	try {
    		if (typeof document.body.style.maxHeight === "undefined") {//if IE 6
    			$("body","html").css({height: "100%", width: "100%"});
    			// Yaml IEHack body{position:relative} ausschalten
    			$("body","html").css({position: "static"});
    			$("html").css("overflow","hidden");
    			if (document.getElementById("gallery-HideSelect") === null) {//iframe to hide select elements in ie6
    				$("body").append("<iframe id='gallery-HideSelect'></iframe><div id='gallery-overlay'></div><div id='gallery-window'></div>");
    				$("#gallery-window,#gallery-HideSelect,#gallery-overlay").fadeIn("normal");
    			}
    		}else{//all others
    			if(document.getElementById("gallery-overlay") === null){
    				$("body").append("<div id='gallery-overlay'></div><div id='gallery-window'></div>");
    				$("#gallery-window,#gallery-overlay").fadeIn("normal");
    			}
    		}

    		if(gallery_detectMacXFF()){
    			$("#gallery-overlay").addClass("gallery-overlayMacFFBGHack");//use png overlay so hide flash
    		}else{
    			$("#gallery-overlay").addClass("gallery-overlayBG");//use background and opacity
    		}

    		if(caption===null){caption="";}
    		$("body").append("<div id='gallery-load'></div>");//add loader to the page
    		$('#gallery-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

    			gallery_PrevCaption = "";
    			gallery_PrevURL = "";
    			gallery_PrevHTML = "";
    			gallery_NextCaption = "";
    			gallery_NextURL = "";
    			gallery_NextHTML = "";
    			gallery_imageCount = "";
    			gallery_FoundURL = false;
    			var gallery_ThumbsHTML = "<table id='gallery-slideTab'><tr>";
    			gallery_ThumbsCaption = new Array();
    			gallery_ThumbsURL = new Array();
    			var closeButton = "";
    			if(imageGroup){
    				var gallery_TempArray = $("a[@rel="+imageGroup+"]").get();
    				//for (gallery_Counter = 0; ((gallery_Counter < gallery_TempArray.length) && (gallery_NextHTML === "")); gallery_Counter++) {
    				for (gallery_Counter = 0; (gallery_Counter < gallery_TempArray.length); gallery_Counter++) {
    					var urlTypeTemp = gallery_TempArray[gallery_Counter].href.toLowerCase().match(urlString);
    					if(gallery_NextHTML === "" && gallery_TempArray.length > 1){
    						if (gallery_TempArray[gallery_Counter].href != url) {
    							if (gallery_FoundURL) {
    								gallery_NextCaption = gallery_TempArray[gallery_Counter].title;
    								gallery_NextURL = gallery_TempArray[gallery_Counter].href;
    								gallery_NextHTML = "<div id='gallery-next'></div>";
    							} else {
    								gallery_PrevCaption = gallery_TempArray[gallery_Counter].title;
    								gallery_PrevURL = gallery_TempArray[gallery_Counter].href;
    								gallery_PrevHTML = "<div id='gallery-prev'></div>";
    							}

    						} else {
    							gallery_FoundURL = true;
    							//gallery_imageCount = "Image " + (gallery_Counter + 1) +" of "+ (gallery_TempArray.length);
    							gallery_imageCount = "";

    							if(gallery_PrevHTML === ""){
    								gallery_PrevCaption = gallery_TempArray[gallery_Counter].title;
    								gallery_PrevURL = gallery_TempArray[gallery_Counter].href;
    								gallery_PrevHTML = "<div id='gallery-prev'></div>";
    							}
    							if(gallery_NextHTML === "" && gallery_Counter == gallery_TempArray.length - 1){
    								gallery_NextCaption = gallery_TempArray[gallery_Counter].title;
    								gallery_NextURL = gallery_TempArray[gallery_Counter].href;
    								gallery_NextHTML = "<div id='gallery-next'></div>";
    							}
    						}
    					}
    					if(gallery_TempArray.length > 1){
    						var image = gallery_TempArray[gallery_Counter];
    						if(image.getElementsByTagName("img") != "" ){

    							gallery_ThumbsCaption[gallery_Counter] = gallery_TempArray[gallery_Counter].title;
    							gallery_ThumbsURL[gallery_Counter] = gallery_TempArray[gallery_Counter].href;
    							var activethumb = "";
    							if(gallery_ThumbsURL[gallery_Counter] == url){
    								thisgallery.currentImg = gallery_Counter;
    								activethumb=" active";
    							};
    							var imagesrc = image.getElementsByTagName("img")[0].src;

    							gallery_ThumbsHTML += "<td><img id='gallery-thumb_"+gallery_Counter+"' class='gallery-thumb"+activethumb+"' src='"+imagesrc+"' /></td>";
    							closeButton = "<a href='#' id='gallery-closeWindowButton' title='Close[ESC]'></a>";
    						}
    					}else{
    						closeButton = "";
    					}
    				}
    				gallery_ThumbsHTML += "</tr></table>";
    			}


    			var imgPreloader = new Image();
    			imgPreloader.onload = function(){
    				imgPreloader.onload = null;


    				// Resizing large images - orginal by Christian Montoya edited by me.
    				var pagesize = gallery_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




	    			gallery_WIDTH = imageWidth + 12;
	    			gallery_HEIGHT = imageHeight + 12;

	    			$("#gallery-window").append(
	    		        "<div id='gallery-ImageOff'>"+
	    		          "<div id='gallery-Image' style='width:"+imageWidth+"px;'>"+
	    		      			"<img id='gallery-Img' src='"+url+"' width='"+imageWidth+"' height='"+imageHeight+"' alt='"+caption+"'/>"+
	    		            "<div id='gallery-closeWindowButton'></div>"+
	    		          "</div>"+
	    		        "</div>"+
	    		        //"<div id='gallery-caption'>"+caption+"</div>";
	    		        ""
	    			);
	    			if(gallery_TempArray.length > 1){
	    				$("#gallery-window").append(
	    					"<div id='gallery-Control'>" +
	    					gallery_PrevHTML +
	    					"<div id='gallery-slideBox'>" +
	    					"<div id='gallery-slideLine'>"+
	    					  gallery_ThumbsHTML +
	    					"</div>"+
	    					"</div>"+
	    					gallery_NextHTML +
	    					"<div style='clear:both'></div></div>"
	    				);
	    			}

	    			if (!(gallery_PrevHTML === "")) {
	    				function goPrev(){
	    					if(thisgallery.currentImg > 0){
	    						thisgallery.currentImg=thisgallery.currentImg-1;
	    						loadImage(gallery_ThumbsCaption[thisgallery.currentImg], gallery_ThumbsURL[thisgallery.currentImg], imageGroup);
	    						controlNav();
	    						return true;
	    					}else{
	    						return false;
	    					}
	    				}
	    				$("#gallery-prev").bind("click", goPrev);
	    				controlNav();
	    			}

	    			if (!(gallery_NextHTML === "")) {
	    				function goNext(){
	    					if(thisgallery.currentImg < gallery_ThumbsURL.length - 1){
	    						thisgallery.currentImg=thisgallery.currentImg+1;
	    						loadImage(gallery_ThumbsCaption[thisgallery.currentImg], gallery_ThumbsURL[thisgallery.currentImg], imageGroup);
	    						controlNav();
	    						return true;
	    					}else{
	    						return false;
	    					}
	    				}
	    				$("#gallery-next").bind("click", goNext);
	    				$("#gallery-ImageOff").bind("click", goNext);
	    				controlNav();
	    			}

	    			function controlNav(){
	    				if(thisgallery.currentImg==0){
	    					$("#gallery-prev").addClass("inactive");
	    				}else{
	    					$("#gallery-prev").removeClass("inactive");
	    				}

	    				if(thisgallery.currentImg == gallery_ThumbsURL.length-1){
	    					$("#gallery-next").addClass("inactive");
	    				}else{
	    					$("#gallery-next").removeClass("inactive");
	    				}

	    				$(".gallery-thumb").removeClass("active");
	    				$("#gallery-thumb_"+thisgallery.currentImg).addClass("active");
	    			}

	    			if (!(gallery_ThumbsHTML === "")) {
	    				function viewImage(event){
	    					if(thisgallery.currentImg != event.data.n){
	    						thisgallery.currentImg = event.data.n
	    						$(".gallery-thumb").removeClass("active");
	    						$(this).addClass("active");
	    						loadImage(gallery_ThumbsCaption[thisgallery.currentImg], gallery_ThumbsURL[thisgallery.currentImg], imageGroup);
	    						controlNav();
	    						return true;
	    					}else{
	    						return false;
	    					}
	    				}
	    				for(var i=0; i < gallery_ThumbsURL.length; i++){
	    					$("#gallery-thumb_"+i).bind("click", {n: i}, viewImage);
	    					$("#gallery-thumb_"+i).mouseover(function(){
	    						var $this = $(this);
	    						$this.addClass("over");
	    					});
	    					$("#gallery-thumb_"+i).mouseout(function(){
	    						var $this = $(this);
	    						$this.removeClass("over");
	    					});
	    				}

	    			}


	    			document.onkeydown = function(e){
	    				if (e == null) { // ie
	    					keycode = event.keyCode;
	    				} else { // mozilla
	    					keycode = e.which;
	    				}
	    				if(keycode == 27){ // close
	    					gallery_remove();
	    				} else if(keycode == 190){ // display previous image
	    					if(!(gallery_NextHTML == "")){
	    						document.onkeydown = "";
	    						goNext();
	    					}
	    				} else if(keycode == 188){ // display next image
	    					if(!(gallery_PrevHTML == "")){
	    						document.onkeydown = "";
	    						goPrev();
	    					}
	    				}
	    			};

	    			gallery_position();
	    			$("#gallery-load").remove();
	    			$("#gallery-closeWindowButton").click(gallery_remove);
	    			$("#gallery-window").css({display:"block"}); //for safari using css instead of show
	    			if(settings.overlayclose){
	    				$("#gallery-overlay").click(gallery_remove);
	    			}

	    			if(windowed){
			    		$("#gallery-closeWindowButton").unbind("click").click(function(){window.close()});
		    			if(settings.overlayclose){
		    				$("#gallery-overlay").unbind("click").click(function(){window.close()});
		    			}
		    		}



	    		};

	    		imgPreloader.src = url;




	    		function loadImage(ImageCaption, ImageURL, ImageGroup){


	    			imgPreloader = new Image();
	    			imgPreloader.onload = function(){
	    				imgPreloader.onload = null;

	    				// Resizing large images - orginal by Christian Montoya edited by me.
	    				var pagesize = gallery_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

	    				gallery_WIDTH = imageWidth + 12;
	    				gallery_HEIGHT = imageHeight + 12;

	    				$("#gallery-Image").fadeOut("normal",function(){

	    					$("#gallery-Image").css({ width:imageWidth+2, height:imageHeight+2 })
	    					$("#gallery-Img").attr({ src:ImageURL, alt:ImageCaption });

	    					if ( !(jQuery.browser.msie && jQuery.browser.version < 7)) { // take away IE6
	    						margTop = parseInt((gallery_HEIGHT / 2),10) +50;
	    						$("#gallery-window").css({marginTop: '-'+margTop + 'px'});
	    					}
	    					$("#gallery-window").css({width: gallery_WIDTH + 'px',marginLeft: '-' + parseInt((gallery_WIDTH / 2),10) + 'px'});
	    					$("#gallery-slideBox").css({width: gallery_WIDTH - 50 +'px'});
	    					$("#gallery-Img").css({ width:imageWidth, height:imageHeight })
	    					$("#gallery-Image").fadeIn("normal");
	    				});
	    			}
	    			imgPreloader.src = ImageURL;
	    		}


    		}
    		/*
    		if(!params['modal']){
    			document.onkeyup = function(e){
    				if (e == null) { // ie
    					keycode = event.keyCode;
    				} else { // mozilla
    					keycode = e.which;
    				}
    				if(keycode == 27){ // close
    					gallery_remove();
    				}
    			};
    		}

    		*/

    	} catch(e) {
    		//nothing here
    	}
    	//openGalleryWindow1(imageGroup);



    }

//    helper functions below


	function openGalleryWindow(caption, url, imageGroup){


		galleryHead = $("head").html();
		galleryImages = $("a[@rel="+imageGroup+"]");
		galleryWindow=window.open('','galleryWindow','width='+settings.width+',height='+settings.height);
		galleryHTML = "";
		count = 0;
		$(galleryImages).each(function(){

    		var t = this.title || this.name || null;
    		var a = this.href || this.alt;
    		var g = this.rel || false;
    		var i = $(this).attr('id');
    		var c = $(this).attr('class');
    		//alert(url +" " + a);
    		if(url == a){
    			thisgallery.currentImg = count;
    			//alert(galleryCurImage);
    		}
    		count++;

			galleryHTML += "<a class='"+c+"' href='"+a+"' title='"+t+"' rel='"+g+"'>" + $(this).html() + "</a>";
		});


		galleryWindow.document.write( "<html><head><script>var galleryWindowCurImg = "+thisgallery.currentImg+"</script>" + galleryHead + "</head><body><div style='display:none'>"+ galleryHTML + "</div></body></html>" );
		galleryWindow.document.close();

		//IE Hook, reload window for script evaluating
		galleryWindow.location.reload();
		galleryWindow.name = 'galleryWindow';
		galleryWindow.focus();

	}







    function gallery_showIframe(){
    	$("#gallery-load").remove();
    	$("#gallery-window").css({display:"block"});
    }

    function gallery_remove() {
     	//$("#gallery-imageOff").unbind("click");
    	$("#gallery-closeWindowButton").unbind("click");
    	$("#gallery-window").fadeOut("normal",function(){
    		$('#gallery-window,#gallery-overlay,#gallery-HideSelect').trigger("unload").unbind().remove();
    		if (typeof document.body.style.maxHeight == "undefined") {//if IE 6
    			$("body","html").css({height: "auto", width: "auto"});
    			// Yaml IEHack body{position:relative} widerherstellen
    			$("body","html").css({position: "relative"});
    			$("html").css("overflow","");
    		}
    	});
    	$("#gallery-load").remove();

    	document.onkeydown = "";
    	document.onkeyup = "";
    	gallery_on = false;
    	return false;
    }

    function gallery_position() {

    	$("#gallery-window").css({marginLeft: '-' + parseInt((gallery_WIDTH / 2),10) + 'px', width: gallery_WIDTH + 'px'});
    	if ( !(jQuery.browser.msie && jQuery.browser.version < 7)) { // take away IE6
    		$("#gallery-window").css({marginTop: '-' + parseInt((gallery_HEIGHT / 2),10) - 50 + 'px'});
    	}
    	$("#gallery-slideBox").css({width: gallery_WIDTH - 50 +'px'});
    /*
    $("#gallery-window").css({marginLeft: '-' + parseInt((600 / 2),10) + 'px', width: 600 +12+ 'px'});
    	if ( !(jQuery.browser.msie && jQuery.browser.version < 7)) { // take away IE6
    		$("#gallery-window").css({marginTop: '-' + parseInt((gallery_HEIGHT / 2),10) + 'px'});
    	}
    */
    }

    function gallery_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 gallery_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 gallery_detectMacXFF() {
      var userAgent = navigator.userAgent.toLowerCase();
      if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox')!=-1) {
        return true;
      }
    }


}


})(jQuery);
