////////////////////////////////////////////////////////////////////
//// CUSTOM hotfoot photo gallery plugin.
// Author: Kevin Dutton - kevin@hotfootlabs.com
 
(function($) {
	
		
  	$.fn.hotfoot_photos = function(options) {
		
		// Create jQuery object for results
		var $hot = this;
		// Current image slot
		var hot_slot = 1;
		var ad_slot = 0;
		var click_count = 0;
		// Array to hold preloaded images
		var cache = [];
		// Array to hold all preloaded ads
		var cache_ads = [];
		
		// variable to display ads every so many clicks
		var ad_show = 7; // ad will land on 8th click
		
		// Number of photos in gallery
		var hot_num = 0;
		// Will hold the player height
		var hot_height = 0;
		var hot_loaded = false;
		var hot_width = 0;
		var lplayer = '';
		var container = '';
		
		// extend default configuration properties with user supplied
		var opts = $.extend({}, $.fn.hotfoot_photos.defaults, options);
 
		// Retrieve data, either directly from json source, or scan directory
		var photos = get_photo_data(opts);
	//	console.dir(photos);
	//	var ads = get_ad_data(opts);
		container = this;
	//	console.log('CONTAINTER: %s',container);
		// Set total # of photos for the gallery
		hot_num = photos.length;
	//	hot_num_ads = ads.length;
	//	debug(hot_num,'Photos');
	
		// set the player
		lplayer = this.find('div.hot_viewer');
	//	console.log('PlayerINIT: %s',lplayer);
		
		// Got thorugh object and preload images
		$.each(photos, function(x, value) { 
					// cache original image
					var cacheImage = document.createElement('img');
					cacheImage.onload = function(){
						check_load(this.alt);
					};
					cacheImage.alt = x;
				//	cacheImage.title = value.h_id;
					cacheImage.src = options.directory+opts.h_prefix+value.h_file;
				//	console.log(options.directory+opts.h_prefix+value.h_file);
					cacheImage.lowsrc = options.directory+opts.h_prefix_thumb+value.h_file;
				//	cacheImage.longdesc = value.h_url;
				//	debug(cacheImage.height,'cache height');
					cache.push(cacheImage);
			
		}); // End .each
		
		
			 arguments.callee.load_home = function (id) {
			        load_home();
			 };
		
	
		
		
		return this;
		
		function check_load(lslot){
			// alert(obj);
				//	debug(lslot,'Image Loaded');
			// 		console.dir(obj);
			// Find player height
			find_player_height(lslot);
			load_thumb(lslot);
			if(lslot == 0)
				init_player();
		}
		
		function init_player(){
		//	console.trace()
		//	console.log('Initialize the player')
			// set player height
			//$('#hot_viewer_'+opts.gal_id).css('height',hot_height);
			
		
			// Add listeners to main contorls
			bind_main_controls();
			
			// Add listeners to thumbnails
			bind_gall_controls();
			
			// position player window
			position_player_window();
			
			// move screen to top of player
		//	scroll_top();
				// load the first image
				load_image(1);
			
			
		}
		
		function find_player_height(lslot){
			// Look for horizontal image that will determine player height
			// Should only execute once
			if(hot_height < 1){
				debug(cache[lslot].height,'Checkin Height');
				if(!cache[lslot].width || !cache[lslot].height)
					return false;
				else
					lo = check_orient(cache[lslot].width,cache[lslot].height);
				if(lo == 'W'){
					// He have horizontal image
					hot_height = cache[lslot].height;
					hot_width = opts.h_width;
				//	console.log('found height');
				//	alert(hot_height);
					
				}
			}
		}
		
		function check_orient(lwidth,lheight){
			if(lwidth > 0 && lheight > 0){
				lo = (lwidth / lheight);
				if(lo >= .75)
					return 'W';
				else
					return 'V';
			}
		}
		
		
		function bind_main_controls(){
			// Add previous  button
			// check to see to event exisits
			
		//	debug(hot_slot,'Binding Controls:');
	///	console.log('Bindin!');	
			// Set all buttons to a dead end
		//	$('#hot_prev').click(dead_end);
		//	$('#hot_next').click(dead_end);
			
		//	lbound_prev = $('#hot_prev').data("events");
			//	alert(lbound_prev);
			// Add button
		//	if(hot_slot > 1 && lbound_prev == undefined){
				container.find('a.hot_prev').click(prev_image);
		//	}
			// remove
		//	if(hot_slot == 1 && lbound_prev != undefined)
		//		$('#hot_prev').unbind('click');	
				
						
		//	lbound_next = $('#hot_prev').data("events");
	//		if(hot_num > hot_slot && lbound_next == undefined)
				container.find('a.hot_next').click(next_image);
				
				container.find('a.hot_close').click(close_player);
			// remove
		//	if(hot_slot == hot_num && lbound_next != undefined){
		//		$('#hot_next').unbind('click');
	//		}
			
			
		};
		
		
		function close_player(){
		//	console.log('closin');
			lplayer.fadeOut(200);
				// Swap z-indexes!!
					$('#content_wrap').css('z-index','50');
					$('#header').css('z-index','52');
					$('#nav').css('z-index','53');
					$('#latest_news, #sponsor').css('z-index','54');
			return false;
		}
		
		function dead_end(){
			return false;
		}
		
		
		function position_player_window(){
			loffset = $('#content').offset();
	//		console.log("OFFSET: %s",loffset);
	//		console.dir(loffset);
			
		}
		
		function bind_thumb_controls(){
			$('#hot_thumbs_'+opts.gal_id+' li:not(.leave) a').click(thumb_image);
		};
		
		function bind_gall_controls(){
			$('#hot_gall_'+opts.gal_id).click(load_home);
		}
		
		function load_image(lslot){
//console.log('Load image:'+lslot);
			var lhot_id = '#hotphoto_'+opts.gal_id;
		//	console.log(lhot_id);
			var slot = (+lslot-1);
			var dim = photo_dimensions(slot,hot_width,hot_height);
		//	console.dir(dim);
			$(lhot_id).attr('src',cache[slot].src);
			$(lhot_id).attr('width',dim[0]);
			$(lhot_id).attr('height',dim[1]);
	//		console.log(dim[1]);
			$(lhot_id).attr('title',cache[slot].title);	
			// update share link
		//$('#hot_link input').val(cache[slot].longdesc);
			$('#hotphoto').unbind('click');
			
			
		//	debug(cache[slot].height,'Photo height');
		};
		
		
 
		function load_thumb(lslot){
			// Load thumbnail
			var tdim = photo_dimensions(lslot,115,76);
			var lthumb_id = '#hotphoto_'+opts.gal_id+'_'+(+lslot+1);
			$(lthumb_id).attr('src',cache[lslot].lowsrc);
			$(lthumb_id).attr('width',tdim[0]);
			$(lthumb_id).attr('height',tdim[1]);
			
 
		}
		
		//The the orientation and dimensions of the photo.  resize if nesecassry
		function photo_dimensions(lslot,t_width,t_height){
			
			lh = (+cache[lslot].height) ;
			lw = (+cache[lslot].width) ;
		//	console.log('height:'+lh+' width:'+lw);
		//	console.log('player height:'+hot_height+' player width:'+hot_width)
			// check the height of the photo
			if(lh > t_height)
				return photo_v_resize(lh,lw, t_height);
			
			
			// check for width of photo
			if(lw > t_width)
				return photo_h_resize(lh,lw, t_width);
			
			// if were still here return original size
	//		console.log('original height/width')
			var org = new Array();
			org[0] = lw;
			org[1] = lh;
			return org;
			
		}
		
		function photo_v_resize(lh,lw, lheight){
			// Find the difference between height of the player and photo, as percentage
	//		console.log('resize vertical')
			var ldiff = lheight / lh;
			return photo_resize(ldiff,lh,lw);
		}
		
		function photo_h_resize(lh,lw, lwidth){
			// Find the difference between height of the player and photo, as percentage
	//		console.log('resize horz');
			var ldiff = lwidth / lw;
			return photo_resize(ldiff,lh,lw);
		}
		
		function photo_resize(lper,lh,lw){
			var wh = new Array();
			wh[0] = lw * lper;
			wh[1] = lh * lper;
			return wh;
			
		}
		
		function prev_image(){
				// Check for id
//console.log('Prev image:',hot_slot);
			
			
					// check for beginning of galley
					if(hot_slot == 1)
						hot_slot = hot_num;
					else
						hot_slot-=1;
					
					click_count+=1;
					load_image(hot_slot);
 
			
				return false;
		}
		
		function next_image(){
	//	console.log('Next image:',hot_slot);
		//		event.preventDefault();
			
		
				// Check for last photos of gallery
				if(hot_slot == hot_num)
					hot_slot = 1;
				else
					hot_slot+=1;
				
				
				click_count+=1;
				load_image(hot_slot);
				
		
	
			return false;
		}
		
		function show_ad(){
			if(click_count == ad_show){
				click_count = 0;
				return true
			}else{
				return false;
			}
		}
		
		function visit_ad(){
			window.open($('#hot_link input').val());
		    return false;
		}
		
		
		function thumb_image(){
	
		if(!lplayer.is(":visible")){
			position_player();
			lplayer.fadeIn(200);
		}
	
			lslot = $(this).parent().attr('id');
		//alert(lslot.length);
			hot_slot = (+lslot.substr(10,lslot.length));
		
			load_image(hot_slot);
	//	alert('image loaded');
	//	console.log('thumb image loated: %s',hot_slot);
		//	bind_main_controls();
		//scroll_top();
			return false;
		}
		
		
		function load_home(){
	
				if(!lplayer.is(":visible")){
					position_player();
					lplayer.fadeIn(200);
				
				}
					lslot = 1;
		
					load_image(hot_slot);
	
					return false;
		}
		
		function position_player(){
			//Get the window height and width  
			var winH = $(window).height();  
			var winW = $(window).width();
			var docH = $(document).height();  
			var cPos = $("#content_wrap").offset();
			var dScroll = $(document).scrollTop();
			var lplayer_height = lplayer.height();
	//		console.log('Window: %s',winH);
	//		console.log('doc: %s',docH);
	//			console.log('Content %s',cPos.top);
	//			console.log('Document Position: %s',dScroll);
	//			console.log("PLAYER: %s",lplayer_height);
				        //Set the popup window to center  
			    //lplayer.css('top',  winH/2-lplayer.height()/2);  
				//lplayer.css('left', winW/2-lplayer.width()/2);
				lplayer.css('top', (winH/2 - (lplayer_height/2)) - ((cPos.top + 20)-dScroll));
				lplayer.css('left',122);
				
			// Swap z-indexes!!
			$('#content_wrap').css('z-index','52');
			$('#header').css('z-index','49');
			$('#nav').css('z-index','50');
			$('#latest_news').css('z-index','51');
			$('#sponsor').css('z-index','51');
		}
		
		
		function scroll_top(){
			lscroll = $('#photo_player').position();
			$('html,body').animate({scrollTop: (lscroll.top+(295-80))+'px'}, 600);
		}
		
		function get_photo_data(opts){
			if(opts.photo_data_type == 'json'){
		//		console.log('we have json');
				return jQuery.parseJSON(opts.photo_data);
			}else{
				// Get it from directory
			}
		};
		
		function get_ad_data(opts){
			if(opts.photo_data_type == 'json'){
				return jQuery.parseJSON(opts.ads_data);
			}else{
				// Get it from directory
			}
		};
		
	 	
		// 	// debug function
			function debug(lvar,label) {
			   // if (window.console && window.console.log)
			   // 			     window.console.log(label+': ' + lvar);
			 };
	
	
		
  };
	
	
  // plugin defaults - added as a property on our plugin function
  $.fn.hotfoot_photos.defaults = {
  		photo_data_type: 'dir', // direcotry | json 
		photo_data: '',
		ads_data: '',
  		directory: '', // default to current
		ads_directory: '',
		h_prefix_thumb: '',
		h_prefix: '',
		h_width: '700',
		gal_id: ''
  };
	
	
// End closure
})(jQuery);