//----------------------------------
// jBoxed Lightbox
// by Tanner Hildebrand
// and BenchSketch.com
// ---------------------------------
// jbModal - фон
// ---------------------------------
// Keyboard:
//	Esc - exit
//	PgDn or Right arrow - next
//	PgUp or Left arrow - prev
//----------------------------------
// setGaleryName(string galeryName)
// jboxed()


(function($) {
	$.fn.extend({
		jboxed : function(options) {
		   var oldKeydownHook = "";

		   var tmp = $(location);
		   var host = tmp.attr("protocol") + "//" + tmp.attr("host");

		   // options
		   var opts = $.extend({}, $.fn.jboxed.defaults, options);
   
		   var wS=$(window).height();

		   // add background
		   $("body").append("<div id='jbModal'></div>");

                   // add image placeholder
		   $("body").append("<div id='jbInterface'><div id='jbInfoTop'><span id='jbLink'>Linkies</span><a id='jbClose'><img src='/web_i/lib/imgs/close.png'></a></div><div id='jbImage'><div id='jbImageBox'><img src=''/></div></div><div id='jbInfoBottom'>Bottom Info here</div><a id='jbLeft' href='prev' class='jBoxed_swapBox' title='Skip To First'></a><a id='jbRight' href='next' class='jBoxed_swapBox' title='Skip To Last'></a></div>");

                   // add image preloader
		   $("body").append("<div id='jbTemporary'></div>");
		   var jTemp=$("#jbTemporary");
		   jTemp.css({"border-width":"0px", "height":"2px", "width":"1px", "overflow":"hidden"});
   
		   // Fix Initial Position
		   var jMod=$("#jbModal");

		   var full=$("#jbModal, #jbInterface");
		   full.hide();

		   var iFace=$("#jbInterface");
		   iFace.css({"height":150,"width":150});
		   iFace.css({"marginTop":-75,"marginLeft":-75});

		   var iBox=$("#jbImageBox");
		   iBox.css({"height":"100%","width":"100%"});
   
		   //var jImg=$("#jbImage");

		   var aR="#jbRight";
		   $(aR).css("marginLeft",120);

		   var aL="#jbLeft";
		   $(aR+", "+aL).css("opacity",0);
   
		   var jSrc="#jbImage img";
		   var bInfo=$("#jbInfoBottom");
		   var tInfo=$("#jbInfoTop");

		   // хранилище ссылок на картинки.
                   // будет заполнено при первом клике.
		   var jLnk=$("#jbLink");
		   
		   var rBi=$(aR).css("background-image");
		   var lBi=$(aL).css("background-image");
		   // And boom goes the dynamite
   
		   // переопределяем обработчик click для фона и для ссылки "Close"
		   //$("#jbModal, #jbClose").click(function() { full.fadeOut(opts.speed); });
		   $("#jbModal, #jbClose").click(function() { full.fadeOut(opts.speed); document.onkeydown=oldKeydownHook; });

		   $(aR).hover(
		   	function() { $(this).css("opacity",1); },
		   	function() { $(this).css("opacity",0); }
		   );
		   $(aL).hover(
		   	function() { $(this).css("opacity",1);},
		   	function() { $(this).css("opacity",0);}
		   );
   
		   // work gallery links
		   $("#jbLink a, #jbRight, #jbLeft").live(
		   	"click",
		   	function() {
				var hr=$(this);
				var hTtl=hr.attr("title");
				var hRel=hr.attr("rel");
				var hRef=hr.attr("href");
				imageChange(hRef, hTtl, hRel);
				return false;
		   	}
		   );

		   t=this;
		   // so we know what we are clicking...
		   t.each(
		   	function() {
				var x = $(this);
				//when click show box
				if (x.attr("href") != "") {
					x.click(
						function() {
						//var dd=$(location);
						//alert(dd.attr("protocol") + "://" + dd.attr("host") + "://" + dd.attr("port"));
						//alert($(location).attr("hostname"));
						//alert
				 			var rel = $(this).attr("rel");
				 			var title = $(this).attr("title");
			 				var href = $(this).attr("href");
							showBoxed(rel, title, href);
							return false;
						}
					);
				}
			}
		   );

		   return false;


   
		   // *************************
		   // Functions
		   // *************************


                   //-----------------------------------------
		   // Точка входа (Initial click)
		   function showBoxed ( rel , title , href ) {
		   	init();
			full.fadeIn(opts.speed);
		   	setKeyboardHook();
		   	setGallery(rel); // собираем ссылки
			imageChange(href , title , rel);
			return;
		   }


                   //---------------
		   function init() {
	                // set background color
			jMod.css({"background-color":opts.bgcolor});
	                // set opacity
			jMod.css({"opacity":opts.modal});
	                // duplicate opacity for IE
			jMod.css({"filter":"alpha(opacity=" + (opts.modal*100) + ")"});
		   	// document's height is dynamically so calc it everytime
			jMod.css({"height": (document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px')});

			if (jQuery.browser.msie) {
				iFace.css({"position":"absolute", "margin-top": (0 - parseInt(document.body.offsetHeight / 2) + (TBWindowMargin = document.documentElement && document.documentElement.scrollTop || document.body.scrollTop) + 'px')});
			} else {
				iFace.css({"position":"fixed"});
			}
			return;
		   }


                   //--------------------------
		   function setKeyboardHook() {
		   	oldKeydownHook = document.onkeydown;
			document.onkeydown = function(e){   
			        if (e == null) { // ie
					keycode = event.keyCode;
				} else { // mozilla
					keycode = e.which;
			        }
			        if (keycode == 27) { // close
					$("#jbClose").click();
		        	} else if (keycode == 33 || keycode == 37) { // PgUp or Left arrow
		        		$("#jbLeft").click();
				} else if (keycode == 34 || keycode == 39) { // PgDn or Right arrow
					$("#jbRight").click();
			        }  
			};
		   	return;
		   }


		   //---------------------------------- 
		   // function to set the gallery links
		   function setGallery ( gallery ) {
			jLnk.html(""); // очищаем хранилище ссылок
			var rCount=0;
			var rString="";
			//$("a[rel="+gallery+"]");
                        
                        // получаем список ссылок с нужным значением атрибута rel
			var gal=t.filter("a[rel="+gallery+"]");

                        // собираем строку
			gal.each(
				function(){
					rCount+=1;
					var hr=$(this), gRef=hr.attr("href"), fTtl=hr.attr("title");
					rString += "<a href='" + gRef + "' title='" + fTtl + "' class='jBoxed_swapBox' rel='" + gallery + "'>" + rCount + "</a> &nbsp;";
				}
			);

                        // сохраняем ее в хранилище
			jLnk.html(rString);
			return;
		   }


		   //------------------------------------------ 
		   // Apply the changes
		   function imageChange ( src , info , gal ) {
		   	// удаляем текущую картинку
			var iImg=iBox.children("img");
			iImg.fadeOut(opts.speed).remove();

			//jImg.css({"height":"100%"});
			iBox.css({"height":"100%"});
			
                        // добавляем новую картинку
                        if (!jQuery.browser.msie) {
	                        var c = jQuery("<img rel='curImg' />");
        	                //var c = jQuery("<img src='" + src + "' rel='curImg' >");
                	        c.load(function() {
                        		var d=jTemp.children("img");
                        		d.hide();
	                        	iBox.append(d);
        	                	raBox();
                	        });
                        	jTemp.append(c);
	                        c.attr({"src": src});
                        } else {
	                        var c = jQuery("<img src='" + src + "' rel='curImg'>");
	                        //c.load(function() {alert(1);});
				iBox.append(c);//"<img src='"+src+"' rel='curImg' >");
				raBox();
                        }
			//iBox.append(c);//"<img src='"+src+"' rel='curImg' >");
			//c.hide();
			//iImg=iBox.children("img");
			//iImg.hide();
			
			setInfo(info);
			setNext(gal, c);
			//setNext(gal, iImg);
			//imageLoad(iImg);
			
			return;
		   }


		   //------------------------------------------- 
		   // Set the info
		   // don't know why I made this a whole funtion
		   function setInfo ( info ) {
			bInfo.fadeOut(opts.speed).html("<span>"+info+"</span>");   
		   }


		   //---------------------------------- 
		   // Set the next and previous buttons
		   function setNext ( gal , img ) {
			var lnk=jLnk.children("a");
			var iSrc=img.attr("src");
			if (iSrc.charAt(0) == "'") {
				iSrc = iSrc.substr(1);
			}
			if (iSrc.charAt(iSrc.length - 1) == "'") {
				iSrc = iSrc.substr(0, iSrc.length - 1);
			}
			var lngt=lnk.length;
			var nCount=0; // Set the count to zero
			lnk.each(
				function() { // go thru all
					var h=$(this); 
					nCount+=1;
					if (nCount == 1) { 
						frst=$(this);   
					} // that was find the first element
					if (h.attr("href") == iSrc || h.attr("href") == host + iSrc) { // matched links 
						if (nCount == 1) { // matched is first
							n=h.next("a");
							p=false;
					   	} else if (nCount == lngt) { // matched is last
							p=h.prev("a");
							n=frst;
			   			} else { // matched is anything else
							p=h.prev("a");
							n=h.next("a");
					   	}
					}
	
					lst=$(this);
				}
			);

			// if we don't have a previous link yet
			if (!p) {
				p=lst;  
			}
			// and assign our variables
			pL=p.attr("href"), pT=p.attr("title");
			nL=n.attr("href"), nT=n.attr("title");
			$(aR).attr({"href":nL,"title":nT});
			$(aL).attr({"href":pL,"title":pT});
			return;
		   }


		   //----------------------------- 
		   // When image is loaded realign it
		   function imageLoad ( image ) {
			image.load(
				function() {
					// when image is loaded
					//image.hide();
					iBox.append(image);
					raBox(iBox.children("img"));//image);
				}
			);
			return;
		   }

   
                   //-----------------
		   // realign box
		   function raBox () {
			var img=iBox.children("img");
			imageFit(img);

			var a2 = new Image(); // because of IE
			a2.src = img.attr("src");
			
			var iH = a2.height;//img.height();
			var iW = a2.width;//img.width();
			iBox.css("height","100%");
			//jImg.css("height","100%");
			var ieOffset = 0;
			if (jQuery.browser.msie) {
				ieOffset = $(window).scrollTop();
			}
			iFace.animate(
				{"height":iH,"width":iW,"marginTop":-iH*.5-20+ieOffset,"marginLeft":-iW*.5},
				opts.speed,
				function() {
					img.fadeIn(opts.speed); // when animate is done, show the image
					//jImg.css({"height":""});
					iBox.css({"height":""});
					bInfo.slideDown(opts.speed); // and slide in the info
					return;
				}
			);
			$(aR).css({"marginLeft":iW*.5,"width":iW*.5+1,"height":iH-15,"marginTop":-iH*.5+22});
			$(aL).css({"width":iW*.5,"height":iH-15,"marginTop":-iH*.5+22});
			return;
		   }


		   //---------------------------- 
		   // fit the image to the window
		   function imageFit ( image ) {
			var a2 = new Image(); // because of IE
			a2.src = image.attr("src");
			
			var iHt = a2.height;//image.height();
			if (iHt+40 > wS) {
			   var iFdif = iHt-wS+80;
			   image.css({"height":iHt-iFdif});
			}
			return;
		   }
		
		} // end jBoxed    

	}); // end extend

	// Plugin Defaults
	$.fn.jboxed.defaults = {
		bgcolor:"#000",//"#ffffff",
		modal:.8,	// opacity
		speed:"normal", // slow, normal, fast
		fit:true,
		border:1
	};

})(jQuery); // end all
