/*!
 * jQuery JGallery
 * Copyright (c) 2010 Dave Kent
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 */
jQuery.fn.slickgallery = function(options) {
	var settings 		= parseOptions(options)
	var doneClass 		= 'slicked'
    return this.each(function(i,e){
    	$e = jQuery(e)
    	if ($e.hasClass(doneClass)) return
    	$e.addClass(doneClass)
    	var thumbwidth = (((settings.width -2) - ( ((settings.thumbpadding + settings.thumbborder ) *2) * (settings.thumbcount - 1))) / settings.thumbcount )
    	var thumbpanelwidth = (((settings.panelwidth -2) - ( ((settings.thumbpadding + settings.thumbborder ) *2) * (settings.thumbpanelcount - 1))) / settings.thumbpanelcount )
    	var thumb		= new Array()
    		a_href		= new Array()
    		a_title		= new Array()
    		a_alt		= new Array()
			panelthumb 	= new Array()
			started 	= false
			contHeight	= 0;
			toggle 		= -1
			tid = 0
			IMloaded = 0
			
		if (typeof settings.thumbwrapper == 'number'){
			$e.find('a').each(function(ii,ei) {    		
				a_href[ii] = $(ei).attr('href')
				a_title[ii] = $(ei).attr('title')
				a_alt[ii] = $(ei).attr('alt')
				if (ii == 0) {
					mainimage 	= new Image() 
					$.get('/lib/img.php?im=' + a_href[0] + '&tn=' + settings.width + ',' + settings.height + ',1&ca=1', function (data) {
    				mainimage.src = data
    				mainimage.alt = a_alt[0]
    				mainimage.onload = function(){
    					IMloaded = 1
    				}	
    				});
				} 
				thumb[ii]		= new Image();
			$.get('/lib/img.php?im=' + a_href[ii] + '&ct=' + Math.round(thumbwidth*10)/10 + ','+ Math.round(thumbwidth*10)/10 + '&ca=1', function (data) {
				thumb[ii].src	= data
				thumb[ii].alt	= a_alt[ii]
    		});			})		
		} else { /* PHOTO GALLERY MODULE */
			$('#'+settings.thumbwrapper).find('li.thumbli').each(function(ii,ei) {    
				thumb[ii]		= new Image();
				a_href[ii] = $(ei).attr('o_img')
								
			})
			
			$.ajax({
			   	type: 'POST',
			   	url: '/lib/img.php',
			   	dataType: 'json',
				data: ({ ahref : a_href , 'ct' : Math.round(thumbwidth*10)/10 + ','+ Math.round(thumbwidth*10)/10 , 'ca': 1 }),

			   	success: function(json){
				 	$.each( json, function( ii, ei ){
				 		thumb[ii].src	= ei
				 	})
			   }
			 });
			
			$.getJSON("/jquery_ajax/photo_captions.php",{ 
					ipg: settings.ipg
				}, function(json) {
					$.each( json, function( ii, ei ){
						a_title[ii] = ei['img_title']						
					})
			});			
			$('#photo').delegate( '.zoom' , 'click' , function() {
				$('#main_lightbox #img0').css('display', 'block')
				/* CLEAR SLIDESHOW */
				if(slideshow == 1) {
					clearInterval(img_play)
					slideshow=0
					$PP.addClass('slideshow_play').removeClass('slideshow_pause');
				}	
				$(this).addClass('slideshow_play').removeClass('slideshow_pause');
				closeme = $('<a style="display:block" id="slickClose"></a>').click(function(){
					closeSlickBox()
			})
			lightboxes( $('<div style="width:'+ settings.panelwidth+'px"><h3 id="slick_title"></h3><div id="slick_description"></div></div>')
				.append(closeme).append( getThumbs(thumb, thumbpanelwidth)) , null, $('#photo_counter_current').text()-1)
				$(document).pngFix(); 
			});	
    	} /* END PHOTO GALLERY MODULE */
    	if (typeof mainimage == 'undefined')  return false
    	
    	mainimagetable = $('<table cellpadding="0" cellspacing="0" valign="middle" id="mainImageTable"><tr><td id="mainImageTD"></td></tr></table>')
    	mainimagetable.find('td').html(mainimage)
    	$e.append($('<div id="sg_mainimage"></div>').data('tid', 0).append(mainimagetable)
    	.click(function(){
    		$('#main_lightbox #img0').css('display', 'block')
    		closeme = $('<a style="display:block" id="slickClose"></a>').click(function(){
 						closeSlickBox()
 					})
    		lightboxes($('<div style="width:' + settings.width + 'px"><h3 id="slick_title">'+ $('#slick #title').html() + '</h3><div id="slick_description">' +  $('#slick #description').html() + '</div></div>')
    		.append(closeme)
    		.append(getThumbs(thumb, thumbwidth)) ,null, $(this).data('tid') )
    		$(document).pngFix(); 
    	
    	}))
    	midiv = $('#sg_mainimage')
    	midiv.css({ 'width'	: settings.width})
    	if (thumb.length>1){
			$e.append('<div style="width:' + (settings.width + 2) + 'px" id="sg_thumb_wrapper"></div>')
            for ( var l=0, len=thumb.length; l<len; ++l ){
				if (l % settings.thumbcount == 0) {
					thumbclass = 'sg_thumb first'
					thumbstyle = 'margin-bottom:' + (settings.thumbpadding * 2) + 'px;border:' + settings.thumbborder + 'px ' + settings.thumbborderstyle + ' ' + settings.thumbbordercolor + '; float:left;clear:left;width:' + Math.round(thumbwidth) + 'px ;height:' + Math.round(thumbwidth) + 'px '
				} else {
					thumbclass = 'sg_thumb'
					thumbstyle = 'margin-bottom:' + (settings.thumbpadding * 2) + 'px;margin-left:' + (settings.thumbpadding * 2) + 'px; border:' + settings.thumbborder + 'px ' + settings.thumbborderstyle + ' ' + settings.thumbbordercolor + '; float:left;width:' + Math.round(thumbwidth) + 'px ;height:' + Math.round(thumbwidth) + 'px '
				} 	
				$('#sg_thumb_wrapper').append($('<div id="sg_thumb_' + l + '" style="' + thumbstyle + '" class="' + thumbclass + '"></div>')
				.hoverIntent(function(){
					o = $('#sg_mainimage img')
					if (!o.length) return false;
					if (!IMloaded) return false;
					if (contHeight == 0){
						contHeight = midiv.height()
						midiv.css('height',contHeight)
					} 
					/* swap main image */
					tid = parseInt(this.id.match(/sg_thumb_(\d+)/)[1], 10) 				
						$.get('/lib/img.php?im=' + a_href[tid] + '&tn=' + settings.width + ',' + contHeight + ',1&ca=1', function (data) {
						o.removeAttr('height').removeAttr('width').attr('src', data ).attr('alt', a_alt[tid])
					});
					$('#sg_mainimage').data('tid', tid)
				},
				function(){}).append(thumb[l]).click(function(){
						$('#main_lightbox #img0').css('display', 'block')
						closeme = $('<a style="display:block" id="slickClose"></a>').click(function(){
							closeSlickBox()
						})
						lightboxes( $('<div style="width:'+ settings.panelwidth+'px"><h3 id="slick_title">'+ $('#slick #title').html() + '</h3><div id="slick_description">' + $('#slick #description').html()+ '</div></div>')
						.append(closeme).append( getThumbs(thumb, thumbpanelwidth)) , null, tid )
						$(document).pngFix(); 
					}))
			}
		}	
  })
	function getThumbs(thumb, thumbwidth){
		$html = $('<div style="width:' + (settings.panelwidth*1 + 5 ) + 'px" class="thumb_panel"></div>')
    	if (thumb.length>1){
			for ( var l=0, len=thumb.length; l<len; ++l ){
				panelthumb[l]		= new Image() 
				panelthumb[l].src 	= thumb[l].src
				if (l % settings.thumbpanelcount == 0) {
					thumbclass = 'sg_thumb first'
					thumbstyle = 'margin-bottom:' + (settings.thumbpadding * 2) + 'px;float:left;clear:left;width:' + Math.round(thumbwidth) + 'px ;height:' + Math.round(thumbwidth) + 'px '
				} else {
					thumbclass = 'sg_thumb'
					thumbstyle = 'margin-bottom:' + (settings.thumbpadding * 2) + 'px;margin-left:' + (settings.thumbpadding * 2) + 'px;float:left;width:' + Math.round(thumbwidth) + 'px ;height:' + Math.round(thumbwidth) + 'px '
				} 	
				$html.append($('<div id="sg_pa_thumb_' + l + '" style="' + thumbstyle + '" class="' + thumbclass + '"></div>')
				.append(panelthumb[l]).data('th_id',l)
				.click(function(){
						crossFade($(this).data('th_id'))
					}) )
			}
		}
		return $html 
	}
	function crossFade(imgID){
			WST = $(window).scrollTop()
			maxHeight 	= $(window).height() + WST - theLightbox.position().top - 80 - titleheight
			maxWidth 	= theLightbox.position().left - (boxmargin*2) - 40
			$.ajax({
				url: '/scripts/jquery_ajax/img.php',
				data: { 'src': a_href[imgID],'maxHeight': maxHeight,'maxWidth':maxWidth,'mtime':settings.mtimeA[imgID] },
				success: function(data) {    			
					if (toggle == -1){
						imgIN = '1'
						imgOUT= '0'
					} else {
						imgIN = '0'
						imgOUT= '1'
					}
					toggle = toggle * -1
					$inbox = $('#main_lightbox #img' + imgIN)
					$inbox.html(data)
					$('#main_caption').hide()
					$('#main_lightbox #img' + imgOUT).fadeOut("slow")
					$inbox.fadeIn("slow")
					if (a_title[imgID]) {
						$inbox.append('<div  class="main_caption">' + a_title[imgID] + '</div>')
				 	}
				 }
			})
	}
	function closeSlickBox(){
		$('#lightbox').fadeOut("fast")
		$('#main_lightbox').fadeOut("slow")
		$('#main_lightbox #img0').fadeOut("medium")
		$('#main_lightbox #img1').fadeOut("medium")
		$('#lightbox_shadow').hide()
	}
	function lightboxes(insertContent, ajaxContentUrl,imgID){
		WST = $(window).scrollTop()
		if($('#lightbox').size() == 0){
			theLightbox = $('<div id="lightbox"></div>')
			theLightbox.css('top', WST + 50)
			theMainLightbox = $('<div id="main_lightbox"><div id="img0"></div><div id="img1"></div></div>')
			theMainLightbox.css('top', $(window).scrollTop() + 50)
			var theShadow = $('<div id="lightbox_shadow"></div>');
			$('body').append(theShadow);
			$('body').append(theLightbox);
			$('body').append(theMainLightbox)
		} else {
			theLightbox = $('#lightbox')
			theLightbox.css('top', $(window).scrollTop() + 50)
			theMainLightbox = $('#main_lightbox')
			theMainLightbox.css('top', WST + 50)
			var theShadow = $('#lightbox_shadow')
		}
		$('#lightbox').empty()
		if(insertContent != null){
			$('#lightbox').append(insertContent);
		}
		if(ajaxContentUrl != null){
			$('#lightbox').append('<p class="loading">Loading...</p>');
			$.ajax({
				type: 'GET',
				url: ajaxContentUrl,
				success:function(data){
					// remove "Loading..." message and append AJAX content
					$('#lightbox').empty();
					$('#lightbox').append(data);
				},
				error:function(){
					alert('AJAX Failure!')
				}
			})
		}
		$('#lightbox').show()
		boxmargin = 20
		titleheight = (a_title[imgID]) ? 20 : 0
		maxHeight 	= $(window).height() + WST - (theLightbox.position().top) - 80 - titleheight
		maxWidth 	= theLightbox.position().left - (boxmargin*2) - 40
		rightOff 	= $(window).width() - theLightbox.position().left		
		
		if(insertContent != null){
			largeimage 	= new Image() 
			largeimage.src 	= '/lib/img.php?im=' + a_href[imgID] + '&tn=' + maxWidth + ',' + maxHeight +',1&us=1'

			$('#main_lightbox').css('right', rightOff + boxmargin).find('#img0')
			.html(largeimage)
			if (a_title[imgID]) {
				$('#main_lightbox').find('#img0').append('<div class="main_caption">' + a_title[imgID] + '</div>')
			}
		}
		$('#main_lightbox').show()
		$('#lightbox_shadow').show()
	}
	function parseOptions(options) {
    var options = options || ''
    var s = { height:650, width:300, title:'gallery',  thumbcount:3, thumbpadding:2, thumbborder:1, thumbborderstyle:'solid', thumbbordercolor:'#AAAAAA', captiontintcolor: 'f7f4f3', mtimeA: Array() ,panelwidth :0, thumbpanelcount:0, thumbwrapper:0, ipg:0 }
    if (options) {
      s.width 					= (options.width) 				? options.width 				: s.width
      s.panelwidth 				= (options.panelwidth) 			? options.panelwidth 			: s.width
      s.height 					= (options.height) 				? options.height 				: s.height
      s.descriptionContainer 	= (options.descriptionContainer)? options.descriptionContainer 	: s.descriptionContainer
      s.title 					= (options.title)				? options.title 				: s.title
      s.thumbcount				= (options.thumbcount)			? options.thumbcount 			: s.thumbcount
      s.thumbpanelcount			= (options.thumbpanelcount)		? options.thumbpanelcount 		: s.thumbcount
      s.thumbpadding			= (options.thumbpadding)		? options.thumbpadding 			: s.thumbpadding
      s.thumbborder 			= (options.thumbborder)			? options.thumbborder 			: s.thumbborder
      s.thumbborderstyle		= (options.thumbborderstyle)	? options.thumbborderstyle 		: s.thumbborderstyle
      s.thumbbordercolor		= (options.thumbbordercolor)	? options.thumbbordercolor 		: s.thumbbordercolor
      s.captiontintcolor		= (options.captiontintcolor)	? options.captiontintcolor 		: s.captiontintcolor
      s.captiontintcolor		= (options.captiontintcolor)	? options.captiontintcolor 		: s.captiontintcolor
      s.mtimeA					= (options.mtimeA)				? options.mtimeA 				: s.mtimeA      
      s.thumbwrapper			= (options.thumbwrapper)		? options.thumbwrapper 			: s.thumbwrapper
      s.ipg						= (options.ipg)					? options.ipg 					: s.ipg
    }
    return s
  }
}
