﻿/**
 * jGalleryLite - jQuery plugin to navigate images/any content in a carousel style widget.
 * @requires jQuery v1.2 or above
 *
 * extends from jCarrouselLite http://gmarwaha.com/jquery/jcarousellite/
 *
 * Copyright (c) 2007 Ganeshji Marwaha (gmarwaha.com)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 * Version: 1.0.1
 * Note: Requires jquery 1.2 or above from version 1.0.1
 */


(function($) {                                          // Compliant with jquery.noConflict()
$.fn.jGalleryLite = function(o) {
    o = $.extend({
        btnPrev: null,
        btnNext: null,
		  btnHover:false,
        btnGo: null,
		  btnShow:null,
		  
		  mouseWheel: false,
        auto: null,
		  
		
		  
		  btnClose:null,
        
		  gallery : null,
		  galleryBtnClose:null,
		  galleryBtnNext:null,
		  galleryBtnPrev:null,
		  gallerySource:null,
		  gallerySourceAllInOn:'auto',
		  gallerySourceAllBtn:false,
		  galleryNavHide:false,
		  galleryNavSpeed:1000,
		  galleryLoop:true,
		  
		  rollSpeed:80,
		  rollOn:0.95,
		  rollOff:0.7,
		  
        speed: 200,
        easing: 'linear',

        vertical: false,
        circular: false,
        visible: 'auto',
		  container: null,
		  start: 0,
		  startHide: false,
        scroll: 1,

        beforeStart: null,
        afterEnd: null,
		  imagesPath:''
    }, o || {});


	
	 
	 
    return this.each(function() {                           // Returns the element collection. Chainable.

			var navItem = $(this),curSource=null;
			var running = false,autoInt=false, animCss=o.vertical?"top":"left", sizeCss=o.vertical?"height":"width";
        	
			var galleryImage1=false,galleryImage2=false, galleryVideo=false, galleryMediaCurr=false,galleryImageLoaded=false;
			var div=null , ul=null , tLi , tl , v ;
			var li=null , itemLength=null , curr=null ;
   		var liSize=null ,ulSize=null,divSize =null;
			 
			/* gallery */
			if(o.gallery)
			{
				$(o.gallery).prepend('<iframe id="gmId3" src="" class="galleryMedia gMwidth gMheight" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen alt="" >');
				$(o.gallery).prepend('<img id="gmId1" src="' + o.imagesPath + 'vide.gif" class="galleryMedia"  alt="">');
				$(o.gallery).prepend('<img id="gmId2" src="' + o.imagesPath + 'vide.gif" class="galleryMedia" alt="">');
				$(o.gallery).prepend('<div class="galleryNavMask"></div>');
				
				galleryImage1= $(o.gallery + " #gmId1");
				galleryImage2= $(o.gallery + " #gmId2");
				galleryVideo= $(o.gallery + " #gmId3");
				
			
				$(o.gallery).show();		
				if(o.gallerySource)
				{
						if($(o.gallerySource).length<=0)
						{
							$(o.gallery).hide();
							return false;
						}
					
					
						if((o.gallerySourceAllInOn == 'auto' )&& ($(o.gallerySource+'.allinone').length >0 ))
						{
							curSource= $(o.gallerySource +'.allinone');
							o.gallerySourceAllInOn=true;
						}
						else if(o.gallerySourceAllInOn==true )
						{
							curSource= $(o.gallerySource );
						}						
						else						
						{
							curSource= $(o.gallerySource + ':first');
							o.gallerySourceAllInOn=false;
						}
							
				
						initSource(curSource);
				
				
						var gsId=0;
						$(o.gallerySource + ' li:not(.empty)')
							.each(function(){
								if(o.gallerySourceAllInOn)
								{
									$(this).addClass('gsId' + gsId);
									gsId+= 1;
								}
							})							
							.click(function(){
									if($.fn.browserTouchSupport.touches)
										$('html, body').animate({scrollTop:0}, 0);
						
									stop();
									$(o.gallery).show();
									$(o.container).slideDown();
									launch();
									
									var to = 0;
									if( (!o.gallerySourceAllInOn) || ((o.gallerySourceAllInOn == 'auto' )&& ($(o.gallerySource+'.allinone').length >0 )) )
									{
										initSource($(this).parentsUntil(o.gallerySource).parent());
										to = $('li',$(this).parentsUntil(o.gallerySource)).index($(this));
										load(to,0);
									}
									else
									{
											
											$($(this).attr('class').split(' ')).each(function() { 
												if (this.indexOf("gsId") >= 0) {
													to = parseInt(this.replace( 'gsId',''))
													load(to);
												}
											});
													

									}
									resize();
									go(to);
									
									if(!$.fn.browserTouchSupport.touches)
										$(o.container).mouseleave();
							});
							
							if(o.gallerySourceAllBtn)
							{
								$(o.gallerySourceAllBtn).click(function(){
									curSource= $(o.gallerySource);
									$(o.gallery).show();
									$(o.container).slideDown();
									initSource(curSource);
									resize();
									launch();
									load(0);
									go(0);
									$(o.container).mouseleave();								
								});
							}
							
				}
				
				
				if($.fn.browserTouchSupport.touches)
				{
				
					if(o.galleryBtnClose)
						$(o.galleryBtnClose).bind('touchstart',function(){galleryClose();});
				
					$(o.gallery).prepend('<div class="galleryWipe"></div>');
					$('.galleryWipe',o.gallery).touchwipe({
						 wipeLeft: function() {
							galleryNext();
						},
						 wipeRight: function() {
							galleryPrev();
						},
						wipeUp: function() {						
						},
						wipeDown: function() {						
						}
					});
				}
				else
				{
					if(o.galleryBtnClose)
						$(o.galleryBtnClose).click(function(){	galleryClose();});

					if(o.galleryBtnPrev)
					{
						var $btnGalleryPrev=$(o.galleryBtnPrev);
						$btnGalleryPrev.bindDelayed('mouseenter', function(event){
									if(itemLength>1) $btnGalleryPrev.children('img').fadeIn(160);
								},80,'mouseleave');
						$btnGalleryPrev.bindDelayed('mouseleave', function(event){
									$btnGalleryPrev.children('img').fadeOut(160);
								},80,'mouseenter');
						$btnGalleryPrev.click(function(){galleryPrev();});
					}
					
					if(o.galleryBtnNext)
					{
						var $btnGalleryNext=$(o.galleryBtnNext);
						$btnGalleryNext.bindDelayed('mouseenter', function(event){
									if(itemLength>1) $btnGalleryNext.children('img').fadeIn(160);
								},80,'mouseleave');
						$btnGalleryNext.bindDelayed('mouseleave', function(event){
									$btnGalleryNext.children('img').fadeOut(160);
								},80,'mouseenter');
						$btnGalleryNext.click(function(){galleryNext()});
					}
					
					if(o.galleryNavHide)
					{
						$(o.gallery + " .galleryNavMask").bindDelayed('mouseenter', function(event){
										$(o.container).slideDown(o.galleryNavSpeed/3);
									}
									,50);
							
							$(o.container).bindDelayed('mouseleave', function(event){
										$(o.container).slideUp(o.galleryNavSpeed);
									}
									,o.galleryNavHide,'mouseenter');
					}
					
				}
				
				
        }
		  else
			{
				initSource();
			}
        	
			$('.mask',$(this)).fadeTo(0,0.7);
			
		  resize();

			if(!o.startHide )
		  {
				if(o.auto)
				{
					load(curr);
					launch();
				}
			}
			else
			{
				$(o.gallery).hide();
			}		  
		
		  $(window).resize(function()	 {
				if(o.gallery)
				{
				var selected=$('ul li.on:first',navItem);
					if(selected)	go($('ul li',navItem).index(selected)); // when resize mode to selected
					else go(0);
				}
				resize();
		  });
		  
			if ($.fn.browserTouchSupport.touches) {
				navItem.touchwipe({
					 wipeLeft: function() {
						stop();
						var indexToGo = curr+v-1;
						if(indexToGo>(itemLength-v))
							indexToGo=itemLength-v;
						go(indexToGo);
					},
					 wipeRight: function() {
						stop();
						var indexToGo = curr-v+1;
						if(indexToGo<0)
							indexToGo=0;
						go(indexToGo);
						 }
				});
			}
			
        if(o.btnPrev)
		  {
            $(o.btnPrev)
					.click(function() {
						 stop();
						 return go(curr-o.scroll);
					});
				
				if(o.btnHover && (!$.fn.browserTouchSupport.touches) )
				{
					$(o.btnPrev).mouseenter(function() {
						
						if(curr>=itemLength-v)
						curr=itemLength-v;
						stop();
						go(curr-o.scroll);
						ints = setInterval(function(){	go(curr-o.scroll)},o.speed+50);
					});
					$(o.btnPrev).mouseleave( function() {
						clearInterval(ints);
					});
				}
			}
				
        if(o.btnNext)
		  {
            $(o.btnNext).click(function() {
					stop();
                return go(curr+o.scroll);
            });
				
				if(o.btnHover && (!$.fn.browserTouchSupport.touches) )
				{
					$(o.btnNext).mouseenter(function() {
						stop();
						go(curr+o.scroll);
						ints = setInterval(function(){go(curr+o.scroll)}, o.speed+50);
					});
					$(o.btnNext).mouseleave( function() {
						clearInterval(ints);
					});
				}
			}

        if(o.btnGo)
            $.each(o.btnGo, function(i, val) {
                $(val).click(function() {
                    return go(o.circular ? o.visible+i : i);
                });
            });

		
			
				
        if(o.mouseWheel && div.mousewheel)
            div.mousewheel(function(e, d) {
                return d>0 ? go(curr-o.scroll) : go(curr+o.scroll);
            });

        

	
		function initSource($source)
		{
			if($source)
			{
				var newHtml = "<ul>";
				$source.each(function(){ newHtml += $(this).children('ul').html(); });
				newHtml += "</ul>";
				navItem.html(	newHtml);
				$('ul li.empty',navItem).remove();
			}
			$('ul li',navItem)
				.removeClass('rollover')
				.mouseenter(function(){
						if(!$(this).hasClass('on'))
						{
							$(this).children('img').stop().fadeTo(o.rollSpeed,o.rollOn);		
							$(this).children('.text').stop().fadeTo(o.rollSpeed,o.rollOn);		
						}
						})
				.mouseleave(function(){
						if(!$(this).hasClass('on'))
						{
							$(this).children('img').stop().fadeTo(o.rollSpeed,o.rollOff);
							$(this).children('.text').stop().fadeTo(o.rollSpeed,o.rollOff);		
						}
						})
				.each(function(){
						if(!$(this).hasClass('on'))
						{
							$(this).children('img').stop().fadeTo(o.rollSpeed,o.rollOff);
							$(this).children('.text').stop().fadeTo(o.rollSpeed,o.rollOff);
						}
						
						});
			
				if(o.gallery)
				{
					$('ul li',navItem).click(function()	{
						stop();
						var indexClicked=$(this).parent().children().index($(this));
						load(indexClicked);
						curr=indexClicked;
						});			
				}
				else
				{
					$('ul li',navItem).click(function(event)	{
						event.preventDefault();
						document.location.href = $(this).find('a').attr('href');
						});
				}

		 
				div = navItem;
				ul = $("ul", div);
				tLi = $("li", ul);
				tl = tLi.size();
				v = o.visible;
				
			  if(o.circular) {
					ul.prepend(tLi.slice(tl-v-1+1).clone())
					  .append(tLi.slice(0,v).clone());
					o.start += v;
			  }

			  li = $("li", ul);
		  
			 itemLength = li.size();
			 
			  curr = o.start;
			
			  div.css("visibility", "visible");

			  li.css({overflow: "hidden", float: o.vertical ? "none" : "left"});
			  ul.css({margin: "0", padding: "0", position: "relative", "list-style-type": "none", "z-index": "1"});
			  div.css({overflow: "hidden", position: "relative", "z-index": "2", left: "0px"});

			
			 liSize = o.vertical ? height(li) : width(li);   // Full li size(incl margin)-Used for animation
			 ulSize = liSize * itemLength;                   // size of full ul(total length, not just for the visible items)
			 divSize = liSize * v;                           // size of entire div(total length for just the visible items)

			  li.css({width: li.width(), height: li.height()});
			  ul.css(sizeCss, ulSize+"px").css(animCss, -(curr*liSize));

			  div.css(sizeCss, divSize+"px");                     // Width of the DIV. length of visible images
				
				resize();
				
				go(0,0);
				
				$('ul li.on:first',navItem).each(function(){
					var liOnIndex=$(this).parent().children().index($(this));
					//if(liOnIndex>=v)
						go(liOnIndex-parseInt(v/2));
					}
				);
					
		}
			
		function launch(){
			 autoInt = setInterval(function() {
				if(galleryImageLoaded)
				{
					if(curr+o.scroll>=itemLength ) 
					{
						if(o.galleryLoop)
							curr=-1;
						else
						{
							stop();
							return;
						}
							
					}
						
					load(curr+o.scroll);
					go(curr+o.scroll);
				}
			  
			}, o.auto+o.speed);
			
		}
		function stop(){
			if(autoInt) clearInterval(autoInt);	
		}
        function vis() {
            return li.slice(curr).slice(0,v);
        };
 
        function resize() {
								
				if(o.gallery)
				{
					if($.fn.browserTouchSupport.touches)
					{
						var wheight = window.innerHeight ? window.innerHeight : $(window).height();
						$(o.gallery).height(wheight*2);
						$(o.container).css('top',wheight-navItem.height());
					}
						
								
					resizeMedia(galleryImage1);
					resizeMedia(galleryImage2);
					
				}
				
				
				if(o.visible=='auto')
				{
					 var cSize = o.vertical ? $(o.container).height() : $(o.container).width(); 
					 
					 var prevSize=0,nextSize=0;
					 
					 if(o.btnPrev) { prevSize = o.vertical ?  css($(o.btnPrev), 'min-height')  : css($(o.btnPrev), 'min-width')  }
					 if(o.btnNext) { nextSize = o.vertical ?  css($(o.btnNext), 'min-height')  : css($(o.btnNext), 'min-width')  }
					v = Math.floor( (cSize - prevSize - nextSize ) / liSize);
					
					if(v>=itemLength)
					{
						v=itemLength;
						$(o.btnPrev + "," +  o.btnNext ).hide();
					}
					else
					{
						$(o.btnPrev + "," +  o.btnNext ).show();
					}
					
					var galleryBorder = parseInt(navItem.css('borderRightWidth').replace('px',''));
					if(!galleryBorder) galleryBorder=0;
					
					var prevNextSize=Math.floor((cSize- (liSize * v) - galleryBorder)/2);
					$(o.btnPrev ).css(sizeCss, prevNextSize+"px");
					$(o.btnNext ).css(sizeCss, prevNextSize+"px");
					div.css(sizeCss, (liSize * v )+"px");     
				  
					//go(0);
				}
				
		  }
		  
		   function resizeMedia(media) 
			{
				if(media)
				{
					var theWindow        = $(window),
					  aspectRatio      = media.width() / media.height();
					
					
					if (( (theWindow.width() / theWindow.height()) < aspectRatio )&&(theWindow.width()>theWindow.height())) {
						 media
							.removeClass('gMheight')
							.removeClass('gMwidth')
							.addClass('gMheight');
					} else {
						 media
							.removeClass('gMheight')
							.removeClass('gMwidth')
							.addClass('gMwidth');
					}
				}
			}
		
		  function load(to,speed) {
            
				if(speed==undefined)
					speed=700;
					
				if(o.gallery)
				{
					var newItem = $('ul li:eq('+ to + ')',navItem);
					
					
					var nextIndex = to+1;
					if(nextIndex>=itemLength) nextIndex=0;
					var nextItem = $('ul li:eq('+ nextIndex + ')',navItem);
					
					
					var newImg =newItem.children("img:first").attr('longDesc');
					var nextImg = nextItem.children("img:first").attr('longDesc');					
					
					$('ul li.on',navItem).each(function(){
						$(this).children('img').fadeTo(0,o.rollOff);
						$(this).children('.text').fadeTo(0,o.rollOff);
						$(this).removeClass('on');
					});
					
					newItem.children('img').fadeTo(o.rollSpeed,1);
					newItem.children('.text').fadeTo(o.rollSpeed,1);
					newItem.addClass('on');
					
					if(newItem.hasClass('video'))
						stop();
					
				  // get last used display
				  var lastDisplay=false;
				  var newDisplay=false;
				  var nextDisplay=false;
				  
				  if(galleryMediaCurr)
				  {
						if(galleryMediaCurr==galleryImage1.attr('id'))
						{
							lastDisplay=galleryImage1;
							if(newItem.hasClass('video'))
								newDisplay=galleryVideo;
							else
								newDisplay=galleryImage2;
								
							if(!nextItem.hasClass('video'))
								nextDisplay=galleryImage1;
						}
						else if(galleryMediaCurr==galleryImage2.attr('id'))
						{
							lastDisplay=galleryImage2;
							if(newItem.hasClass('video'))
								newDisplay=galleryVideo;
							else
								newDisplay=galleryImage1;
																	
							if(!nextItem.hasClass('video'))
								nextDisplay=galleryImage2;
						}
						else if(galleryMediaCurr==galleryVideo.attr('id'))
						{
							lastDisplay=galleryVideo;
							
							if(newItem.hasClass('video'))
							{
								lastDisplay=false;
								newDisplay=galleryVideo;
							}
							else
							{
								lastDisplay=galleryVideo;
								lastDisplay.attr('src','');
								newDisplay=galleryImage1;
							}
															
							if(!nextItem.hasClass('video'))
								nextDisplay=galleryImage2;
						}
						else
						{
							lastDisplay=false;
							if(newItem.hasClass('video'))
								newDisplay=galleryVideo;
							else
								newDisplay=galleryImage1;
								
							if(!nextItem.hasClass('video'))
								nextDisplay=galleryImage2;
								
						}
					}
					else
					{
						if(newItem.hasClass('video'))
							newDisplay=galleryVideo;
						else
							newDisplay=galleryImage1;
							

						if(!nextItem.hasClass('video'))
							nextDisplay=galleryImage2;
					}
				
					if(lastDisplay) 
						lastDisplay
							.fadeTo(speed,0,'linear',function(){
									if(nextDisplay) 
									{
										nextDisplay.attr('src', nextImg);
									}
								});
					
					newDisplay.fadeTo(0,0);
					if(newDisplay.attr('src')!=newImg)
					{
						newDisplay.attr('src', '');
						newDisplay.attr('src', newImg);
					}

					$(o.gallery).removeClass('galleryPreloading');
					galleryImageLoaded=false;
					newDisplay
						.stop()
						.fadeTo(700,1,'linear',function(){
								if(!galleryImageLoaded)
									$(o.gallery).addClass('galleryPreloading');
							})
						.load(function(){
							galleryImageLoaded=true;
							$(o.gallery).removeClass('galleryPreloading');
							resize()
						});
							
					galleryMediaCurr=newDisplay.attr('id');
				}	
			}
		 
			function galleryNext()
			{
				if(!$('#'+ galleryMediaCurr ).is(':animated'))
				{
					var to = curr+1;
					if(to>=itemLength) to=0;
					stop();
					load(to);
					go(to);					
				}			
			}
			function galleryPrev()
			{
				if(!$('#'+ galleryMediaCurr ).is(':animated'))
				{
					var to = curr-1;
					if(to<0)
						to=itemLength-1;
					stop();
					load(to);
					go(to);						
				}
			}
			
			function galleryClose()
			{
				
				$(o.gallery).fadeOut(100);
				stop();
						
				galleryImage1.attr('src', o.imagesPath + 'vide.gif');
				galleryImage2.attr('src', o.imagesPath + 'vide.gif');
				galleryVideo.attr('src','');
				galleryMediaCurr=false;
				galleryImage1.hide();
				galleryImage2.hide();
				galleryVideo.hide();
			}
        function go(to,speed) {
            
				if(speed==undefined)
					speed=o.speed;
				
				if(!running) {

                if(o.beforeStart)
                    o.beforeStart.call(this, vis());

                if(o.circular) {            // If circular we are in first or last, then goto the other end
                    if(to<=o.start-v-1) {           // If first, then goto last
                        ul.css(animCss, -((itemLength-(v*2))*liSize)+"px");
                        // If "scroll" > 1, then the "to" might not be equal to the condition; it can be lesser depending on the number of elements.
                        curr = to==o.start-v-1 ? itemLength-(v*2)-1 : itemLength-(v*2)-o.scroll;
                    } else if(to>=itemLength-v+1) { // If last, then goto first
                        ul.css(animCss, -( (v) * liSize ) + "px" );
                        // If "scroll" > 1, then the "to" might not be equal to the condition; it can be greater depending on the number of elements.
                        curr = to==itemLength-v+1 ? v+1 : v+o.scroll;
                    } else curr = to;
                } else {                    // If non-circular and to points to first or last, we just return.
                    if(to<0)								
								return;
						  else if( to>itemLength)
						  {
								return;
							}
                    else 
								curr = to;
                }                           // If neither overrides it, the curr will still be "to" and we can proceed.

               
					var max= curr;
					if(max>=itemLength-v)
						max=itemLength-v;
					running = true;
					 ul.animate(
						  animCss == "left" ? { left: -(max*liSize) } : { top: -(max*liSize) } , speed, o.easing,
						  function() {
								if(o.afterEnd)
									 o.afterEnd.call(this, vis());
								running = false;
						  }
					 );
					 
                // Disable buttons when the carousel reaches the last/first, and enable when not
					 if(!o.circular) {
                    $(o.btnPrev + "," + o.btnNext).removeClass("disabled");
                    $( (curr-o.scroll<0 && o.btnPrev)
                        ||
                       (curr+o.scroll > itemLength-v && o.btnNext)
                        ||
                       []
                     ).addClass("disabled");
                }

            }
				
			
            return false;
        };

    });
};

function css(el, prop) {
    return parseInt($.css(el[0], prop)) || 0;
};
function width(el) {
    return  el[0].offsetWidth + css(el, 'marginLeft') + css(el, 'marginRight');
};
function height(el) {
    return el[0].offsetHeight + css(el, 'marginTop') + css(el, 'marginBottom');
};

})(jQuery);
