(function ($){
	$.fn.extend({
		imageviewer: function(options){
			
			
			 var defaults = {  width:700,
							   height:400,
							   thumbWidth:105,
							   thumbHeight:50,
							   bordercolor:'#AAA',
							   darkcolor:'#CCC',
							   hilightcolor:'#C00',
							   backgroundcolor:'transparent',
							   showUI:false,
							   kbshortcuts:true,
							   data:null
	 						};  
              
            var options = $.extend(defaults, options);  
			
			return this.each(function(){
				o = options;
				var obj = $(this);  
				var isIE6 = false;
				 if($.browser.msie && $.browser.version < 7){
					isIE6 = true;
				}
				
				//var htmlFrameWork = '<div class="iv-images"><img  alt="" /></div><div class="iv-title"><div class="iv-ui-bg"></div><div class="iv-title-text"></div><div class="iv-title-close"><img src="../images/ui-close.png" alt=""  class="iv-ui-close"/></div></div><div class="iv-ui-container"><div class="iv-ui"><div class="iv-ui-bg"></div><div class="iv-ui-content"><div class="iv-controls"><img src="../images/ui-left-arrow.png" alt="" class="iv-ui-prev" /><img src="../images/ui-right-arrow.png" alt="" class="iv-ui-next" /></div><div class="iv-counter">1/100</div><div class="iv-info"><img src="../images/ui-info.png" alt=""  class="iv-ui-info" /></div></div></div></div><div class="iv-thumbnails"><a class="iv-dock-next"></a><a class="iv-dock-prev"></a><div class="iv-dock-mask"><div class="iv-dock"></div></div></div>';
				
				var htmlFrameWork = '<span class="iv-thumbnail-show-hide"><span></span></span><div class="iv-images"><img  alt="" /></div><div class="iv-ui-container"><div class="iv-ui"><div class="iv-ui-prev-wrapper"><img src="img/left-chevron.png" class="iv-ui-prev" /></div><div class="iv-ui-next-wrapper"><img src="img/right-chevron.png" class="iv-ui-next"  /></div></div></div><div class="iv-thumbnails"><a class="iv-dock-next"></a><a class="iv-dock-prev"></a><div class="iv-dock-mask"><div class="iv-dock"></div></div></div>';
				
				obj.html(htmlFrameWork);
				var bigImage = $(".iv-images img", obj);
				var dock  = $(".iv-dock", obj);
				var titleElement = $(".iv-title", obj);
				var dockItems =$(".iv-thumbnails img", obj);
				var UI =  $(".iv-ui", obj);
				var dock_next = $(".iv-dock-next", obj);
				var dock_prev = $(".iv-dock-prev", obj);
				
				//scoping properties
				currentSelectionIndex = 0;
				currentSelectionItem = null;
				
				var links;
				var images;
				var dockWidth 
				var min_left
				var max_left
				
				var inited = false;
				
				
				//cookie for thumbnials
				//console.log($.cookie('thumbnailsvisible'))
				if(! $.cookie('thumbnailsvisible')) $.cookie('thumbnailsvisible', 'true');
				if($.cookie('thumbnailsvisible')=='true'){
					$('.iv-thumbnail-show-hide span').html('thumbnails-')
				}else{
					$('.iv-thumbnail-show-hide span').html('thumbnails+')
				}
				
				
				hideUI()
				applyCSS();
				
				is_video = false;
				bits = o.data[0].desc.split('---')
				desc = $.trim(bits[0]);
				
				if(desc=='vimeo'){
					is_video = true;
					video_id= $.trim(bits[1]);
				}
				
				
				if(o.data.length > 0){
					if(is_video==true){
						loadVideo(video_id)
					}else{
						loadBigImage(o.data[0].large, true);
					}
				}else{
					throwError('noimages');
				}
				
				function continueInit(){
				if(inited == true)return;
				inited= true;
				if(o.data ==null){
					links = $( "a", obj); 
					images = $( "img", obj)
				}else{
					imageList =  '<div>'
					for ( i = 0; i < o.data.length; i++ ) {
						imageList +=  '<a href="'+  o.data[i].large +'" title="'+ o.data[i].desc +'" ><img src="'+  o.data[i].small +'" /></a>';
					}
					imageList +=  '</div>'
					images = $( "img", imageList)
					links = $( "a", imageList)
				}
				images.appendTo(dock);
				
				titleElement = $(".iv-title", obj);
				dockItems =$(".iv-thumbnails img", obj);
				totalItems = dockItems.length;
				UI =  $(".iv-ui", obj);
				dock_next = $(".iv-dock-next", obj);
				dock_prev = $(".iv-dock-prev", obj);
				if(dockItems.length>1){
				$(dockItems, obj).each(
					function(i,v){
						var d = '<div class="iv-dockitem iv-dockitem'+i+'"><div class="iv-dockitem-highlight iv-dockitem-highlight'+i+'"></div></div>';
						dock.append(d);
						$(v).appendTo($('div.iv-dockitem:last', obj)); 							
						$(v).addClass("di-" +  i, obj);		
					}
				)
	
			
				applyDockCSS();
				initDockEvents();
				$('.iv-dockitem-highlight0', obj).show();
			}else{
				$('.iv-thumbnail-show-hide').hide()
			}
		   }
			
	function applyCSS(){
			//init styles
			obj.css({'position':'relative', 'width': (o.width) +'px', 'height': (o.height + o.thumbHeight)+'px', 'background-color': o.backgroundcolor});
			$(".iv-images", obj).css({'height': o.height+'px', 'width': o.width+'px'});
			bigImage.css({'height': o.height+'px', 'width': o.width+'px' });
			titleElement.css({'width': (o.width-10) + 'px', 'bottom': o.thumbHeight +44 + 'px'}).hide();
			$(".iv-thumbnail-show-hide span", obj).css({'background-color':o.backgroundcolor})
/*needs to be in js*/
		
		
		if(isIE6){
			obj.css('width', (o.width+ 14) +'px')
			obj.css('height', (o.height+ o.thumbHeight + 21) +'px')
			 $(".iv-thumbnails", obj).css('top', o.height + 4+ 'px')
			dock_prev.css('height',o.thumbHeight+'px');
			dock_next.css('height',o.thumbHeight+'px');		
	   }

	}
	
	function applyDockCSS(){
			//console.log('init');
			//position vars for dock
			dockWidth = (o.thumbWidth+4) * (dockItems.length) +30// * (dockItems.length);
			//console.log(dockWidth,o.thumbWidth )
			min_left = 0;
			max_left = -dockWidth + o.width  -22 //width of dock, width of element
			$('.iv-dock',obj).css('left','0px')
			
			$('.iv-ui-container', obj).css({'width': o.width+'px', 'bottom': o.thumbHeight+'px'});
			$(".iv-thumbnails", obj).css({	'top': o.height + 'px', 'width':o.width +'px', 'height':o.thumbHeight + 'px'});
			if($.cookie('thumbnailsvisible')=='false'){
				$(".iv-thumbnails", obj).css({'display':'none'});
			}
			dock.css({'width': dockWidth+ 'px'});
			if(dockWidth < o.width){
				dock_next.css({	'visible':'hidden'});
				dock_prev.css({	'visible':'hidden'});
				$(".iv-dock", obj).css({'left':max_left + 10});
				
			}else{
				dock_next.css({	'height':o.thumbHeight+'px', 'background-color': o.darkcolor,'cursor':'pointer'});
				dock_prev.css({	'height':o.thumbHeight+'px', 'background-color': o.darkcolor,'cursor':'pointer'});	
				$('.iv-dockitem', obj).css({'width':o.thumbWidth+ 'px','height': (o.thumbHeight+20) + 'px','cursor':'pointer'})
				$('.iv-dockitem:first', obj).css({'margin-left':0})
				$('.iv-dockitem-highlight', obj).css({'width':o.thumbWidth+ 'px','background':o.hilightcolor}).hide();
			}
			//$('.iv-dock-mask', obj).css({'height': o.height+'px', 'width': o.width - 50+'px'});
	}
	
	function loadBigImage(src){

		is_video = false;
				bits = o.data[currentSelectionIndex].desc.split('---')
				desc = $.trim(bits[0]);
				
				if(desc=='vimeo'){
					is_video = true;
					video_id= $.trim(bits[1]);
				}
		
		if(is_video==true){
			loadVideo(video_id)
		}else{
			
		
	
		obj.trigger('new-image');
		bigImage.hide();
		
		$(bigImage).load(function () {
       		 $(this).fadeIn();
       		  
       		 continueInit();
       		 updateTitle();
       		 
        }).error(function () {
            // notify the user that the image could not be loaded
        }).attr('src', src);
        
        }
	}
	
	function loadVideo(src){
		//console.log('src=' , src);
		obj.trigger('new-image');
		bigImage.hide();
		$('.iv-ui-container').append('<iframe src="http://player.vimeo.com/video/'+ src +'?title=0&amp;byline=0&amp;portrait=0" width="700" height="400" frameborder="0"></iframe>');
		$('#txtarea').html('');
		continueInit();
		
	}
	
	
	function throwError(e){
		if(e=='noimages'){
			obj.html('No images to display');
		}
	}

	function setCurrentImage(){
		//highlight  
		
		$('.iv-dockitem-highlight', obj).hide();
		$('.iv-dockitem-highlight' + currentSelectionIndex , obj).show();
		//image swap
		
		loadBigImage(links[currentSelectionIndex]);
		//show titles
		//titleElement.hide();
		//updateTitle();
		
		//$(".iv-counter", obj).html((currentSelectionIndex+1) +'/'+ totalItems);
		//move thumbnail onscreen when new image is selected
		var wleft = Math.abs(removeMetric( $(".iv-dock",obj).css('left')));
		var wright =  o.width + wleft
		var tmin =  currentSelectionIndex * (o.thumbWidth + 4)
		var tmax = currentSelectionIndex * (o.thumbWidth + 4) +  o.thumbWidth
			
		if(tmax > wright ){
			slideTo(-tmin);
		}
		
		if(tmin < wleft ){
			slideTo(-tmin);
		}
		
	}
	
	//title
   function updateTitle(){
		var title =$(links[currentSelectionIndex],obj).attr('title');
		//console.log('TITLE = > ', title, $(links[currentSelectionIndex]));
			if(title!=''){
				$('#txtarea').html(title);
			}else{
				$('#txtarea').html('');
			}
		}
	
	function showTitle(){
		var title =$(links[currentSelectionIndex], obj).attr('title');
			if(title!='')titleElement.show();
			}
  function hideTitle(){
  	titleElement.hide();
  }
  
  
     //dock sliding
 	 function slideLeft(){
 	   			var next_left =  removeMetric($('.iv-dock',obj).css('left')) - o.width +250 ;//was +40
 	   			if(next_left < max_left)next_left = max_left;
 	   			//trace($('.iv-dock',obj).css('left') +"  " + o.width);
 	   			slideTo(next_left)
 	   }
      function slideRight(){
 	   			var next_left =  removeMetric($('.iv-dock',obj).css('left')) + o.width -250;//was -40
 	   			if(next_left > min_left)next_left = min_left;
 	   			
 	   			slideTo(next_left)
 	   }
 	   function slideTo(p){
 	   		if(p < max_left)p = max_left;
 	   		$('.iv-dock',obj).animate( { left:p }, 750);
 	   }
 	   
 	   
	function removeMetric(s){
			return Number(s.substr(0, s.length-2))
	}
	
	
	function initDockEvents(){
	
	//prefs
			if(o.kbshortcuts==true){
				keyboardShortCut();
			}
			
	dockItems.click(function (e) {
			index = Number($(e.target).attr('class').split(' ')[0].split('-')[1])
			if(currentSelectionIndex != index){
      			currentSelectionIndex = index;
      			setCurrentImage();
 				e.preventDefault();
 			}
      		return false;
 	   });
	$('.iv-thumbnail-show-hide').click(function (e) {
		$('.iv-thumbnails').slideToggle("fast");
		if($('.iv-thumbnail-show-hide span').html()=='thumbnails-'){
			$('.iv-thumbnail-show-hide span').html('thumbnails+');
			 $.cookie('thumbnailsvisible', 'false');
		}else{
			$('.iv-thumbnail-show-hide span').html('thumbnails-');
			$.cookie('thumbnailsvisible','true')
		}
		
		//console.log($.cookie('thumbnailsvisible'))
	});
	dock_next.click(function (e) {
		slideLeft();	
	});
		
	 dock_prev.click(function (e) {
			slideRight();
		});
 	  nextItem = function(){
		   if(currentSelectionIndex == totalItems-1){
			currentSelectionIndex=0;
		   }else{
			 currentSelectionIndex++;        
		   }
		   	setCurrentImage();
 	   }
 	     prevItem = function(){
 	     	if(currentSelectionIndex == 0){
			currentSelectionIndex=totalItems-1;
			}else{
			 currentSelectionIndex--;        
		   }
		   	setCurrentImage();
		//	$(dockItems[currentSelectionIndex]).click();
 	   }
 	 } 
 	   	//ui   
 	if(o.showUI){
		$('.iv-ui-container', obj).hover(function(){showUI()}, function(){hideUI()});
	}
	function showUI(){;if(!o.showUI)return;if(totalItems==1)return;UI.show()};function hideUI(){UI.hide()}
	
 	 $('.iv-ui-next-wrapper', obj).click(function(){nextItem()});
 	 $('.iv-ui-prev-wrapper', obj).click(function(){prevItem()});
 	// $('.iv-ui-info', obj).click(function(){showTitle()});
 	 //$('.iv-ui-close', obj).click(function(){hideTitle()});
 	 
 	  
 	   function keyboardShortCut(){
		   $(document).keydown(function(e){
		   switch(e.keyCode) { 
			 // User pressed "up" arrow
			 case 39:
			   self.nextItem();
			 break;
			 // User pressed "down" arrow
			 case 37:
			   self.prevItem();
			 break;
			}  });
		}
			
			});
		}
	})
	
	
$.fn.imageviewer.setCurrentPic = function(newImage) {
	//o.data[currentSelectionIndex] = newImage;
};
	
$.fn.imageviewer.getCurrentPic = function() {
	return(currentSelectionIndex);
};

$.fn.imageviewer.getCurrentPicArtist = function() {
	return(o.data[currentSelectionIndex].artist);
};


	
}) (jQuery);

