var lockedID = '';
var isLocked = false;
var filmFest = {};

function showDetail(detailID) {
	jQuery('.sizeInfoTitle').css('display', 'none');
	jQuery('#' + detailID).css('display', 'block');
}

function showLockedDetail() {
	if(isLocked) {
		showDetail(lockedID);
  }
}

function lockDetail(detailID, rowID) {
	jQuery('.rodOptions').removeClass('locked');
	
	if (detailID != lockedID){
		jQuery('#'+rowID).addClass('locked');
		lockedID = detailID;
		isLocked = true;
	} else{
		isLocked = false;
		lockedID = '';
	}
}

jQuery(document).ready(function() {
      
	// submit form on state/country change
	jQuery('#country, #state').change(function() {
		jQuery('#location-picker').submit();
	});
      
	// FLIR replacements
	jQuery('#noShadowHeader h1.banner, #LandingTitle').each(function() {
		FLIR.replace(this, new FLIRStyle({cFont: 'morgaave-boldcap', mode: 'quickeffects',qe_Shadow:'low'}));
	});
	
      
	// Initialize gallery FancyBox
	jQuery('a.galleryItem').fancybox({
		'zoomSpeedIn'   : 750,
		'zoomSpeedOut'  : 750,
		'overlayShow'   : true,
		'easingIn'      : 'easeOutBack',
		'overlayColor'  : '#000'
	});
	
	// Handle opening of gallery on rod type page via header links
	jQuery('#photoGalleryLink').click(function() {
		jQuery('ul.photoGallery a.firstEntry').click();
		return false;
	});
	
	/* Begin dual hover state code */
	 
	$('#leftNav li a, .rodLeftNav a').each(function() {
		var url = $(this).attr('href');
		var matches = $("#right a[href='" + url + "']");
		
		$(matches).hover(function() {
			$("#leftNav a[href='" + url + "'], .rodLeftNav a[href='" + url + "']").addClass('hoverState');
		}, function() {
			$("#leftNav a[href='" + url + "'], .rodLeftNav a[href='" + url + "']").removeClass('hoverState');
		});
		
		$(this).hover(function() {
			$(matches).addClass('hoverState');
		}, function() {
			$(matches).removeClass('hoverState');
		});
		
	});
	
	/* End dual hover state code */
	
	
	
	/* Fancyplayer... */
	var videoclip = 'video';
	
	var videopath = '/swf'; //"http://www.burconsult.com/tutorials/fp2/";
	var swfplayer = videopath + "/flowplayer-3.1.5.swf";
	var swfcontent = videopath + "/flowplayer.content-3.1.0.swf";
	var swfcaptions = videopath + "/flowplayer.captions-3.1.4.swf";
	var capShow = false;
	var ccbutShow = false;
	var vidid = 0;
	var vid_prefix = '/download?id=';
	
	// Attribute used to locate the FLV's file ID
	var vid_id_attr = 'name';

	jQuery('#videoGalleryLink').click(function() {
		var first_sel = 'ul.videoGallery a.firstEntry';
		videoclip = vid_prefix + jQuery(first_sel).attr(vid_id_attr);
		vidid = 0;
		setTimeout(function() {
			jQuery(first_sel).click();
		}, 250);
		return false;
	});
	
	jQuery(".video_link").fancybox({
		'hideOnContentClick': false,
		'overlayOpacity' : .6,
		'zoomSpeedIn'    : 400,
		'zoomSpeedOut'   : 400,
		'easingIn'		   : 'easeOutBack',
		'easingOut'		   : 'easeInBack',
		
		'callbackOnShow' : function() {
			if (videoclip == 'image') {
				jQuery("#fancy_right, #fancy_left").css({height:jQuery("#fancy_div").height(), bottom: '0'});  
			} else {
				player = $f("fancy_content",
					{
						src: swfplayer,
						wmode: 'opaque'
					}, {
						play: {
							opacity:0
						}, // play
						plugins: {
							captions: { 
								url: swfcaptions, 					 
								// pointer to a content plugin (see below) 
								captionTarget: 'content',
								showCaptions: capShow,
								button: ccbutShow
							}, // captions
							content: { 
								url: swfcontent, 
								bottom: 25, 
								height:40, 
								backgroundColor: 'transparent', 
								backgroundGradient: 'none', 
								border: 0, 
								textDecoration: 'outline', 
								style: {  
									body: {  
										fontSize: 16,  
										fontFamily: 'Arial', 
										textAlign: 'center', 
										color: '#ffffff' 
									}  
								}  
							}, // content
							controls: {
								backgroundColor: 'transparent',
								progressColor: 'transparent',
								bufferColor: 'transparent',
								all:false,
								scrubber:true,
								volume:true,
								mute:true,
								play:true,
								height:30,
								autoHide: 'always'		
							} // controls
		
						}, // plugins
						clip: {
							autoPlay: true,
							autoBuffering: true,
							url: videoclip,
							onStart: function(clip) {
								var wrap = jQuery(this.getParent());
								var clipwidth = clip.metaData.width;
								var clipheight= clip.metaData.height;
								var pos = jQuery.fn.fancybox.getViewport();
								jQuery("#fancy_outer").css({width:clipwidth+20,height:clipheight+20});
								jQuery("#fancy_outer").css('left', ((clipwidth + 36) > pos[0] ? pos[2] : pos[2] + Math.round((pos[0] - clipwidth	- 36)	/ 2)));
								jQuery("#fancy_outer").css('top',  ((clipheight + 50) > pos[1] ? pos[3] : pos[3] + Math.round((pos[1] - clipheight - 50)	/ 2)));
								jQuery("#fancy_right, #fancy_left").css({height:clipheight-60, bottom: '70px'});
								//$('#fancy_title').css({'position':'absolute','bottom':null,'top':null,'visibility':'visible','display':'block'});
								$.fn.fancybox.scrollBox();
							}, // onStart
							onFinish:function() {
								jQuery('#fancy_close').trigger('click');
							} // onFinish
						} // clip
					}
				);
				player.load();
			}
			
			jQuery('#fancy_right, #fancy_right_ico').click(function(){
				vidid++;
				videoclip = vid_prefix + jQuery(".video_link").eq(vidid).attr(vid_id_attr);
				if (jQuery(".video_link").eq(vidid).hasClass('captions')) {
					captions = '/swf/empty.srt'; //jQuery(".video_link").eq(vidid).attr(vid_id_attr)+'.srt';
					capShow = false; //true;
					ccbutShow = { width: 20, height: 15, right: 5, bottom: 32, label: 'CC' };
				} else {
					captions = '/swf/empty.srt';
					capShow = false;
					ccbutShow = null;
				}
			});
			
			jQuery('#fancy_left, #fancy_left_ico').click(function(){
				vidid--;
				videoclip = vid_prefix + jQuery(".video_link").eq(vidid).attr(vid_id_attr);
				if (jQuery(".video_link").eq(vidid).hasClass('captions')) {
					captions = '/swf/empty.srt'; //jQuery(".video_link").eq(vidid).attr(vid_id_attr)+'.srt';
					capShow = false; //true;
					ccbutShow = { width: 20, height: 15, right: 5, bottom: 32, label: 'SUBS' };
				} else {
					captions = '/swf/empty.srt';
					capShow = false;
					ccbutShow = null;
				}
			});
		},
		'callbackOnClose': function() {
			jQuery("#fancy_content_api").remove();
		}
	});


	var tip;
	
	function registerTooltips() {
		$(".tip_trigger").hover(function() {
	
			//Caching the tooltip and removing it from container; then appending it to the body
			tip = $(this).find('.tip').remove();
			$('body').append(tip);
	
			tip.show(); //Show tooltip
	
		}, function() {
	
			tip.hide().remove(); //Hide and remove tooltip appended to the body
			$(this).append(tip); //Return the tooltip to its original position
	
		}).mousemove(function(e) {
			var mousex = e.pageX + 15; //Get X coodrinates
			var mousey = e.pageY + 15; //Get Y coordinates
			var tipWidth = tip.width(); //Find width of tooltip
			var tipHeight = tip.height(); //Find height of tooltip

		 //Distance of element from the right edge of viewport
			var tipVisX = $(window).width() - (mousex + tipWidth);
			var tipVisY = $(window).height() - (mousey + tipHeight);
	
			if ( tipVisX < 20 ) { //If tooltip exceeds the X coordinate of viewport
				mousex = e.pageX - tipWidth - 20;
				$(this).find('.tip').css({  top: mousey, left: mousex });
			} if ( tipVisY < 20 ) { //If tooltip exceeds the Y coordinate of viewport
				mousey = e.pageY - tipHeight - 20;
				tip.css({  top: mousey, left: mousex });
			} else {
				tip.css({  top: mousey, left: mousex });
			}
		});
	} // registerTooltips()
	
	/* ###### filmFest Controller ###### */
	filmFest = {
		films: [],
		festivals: [],
		hidden: [],
		filters: {},
		animating: false,
		activeFestival: -1,
		specificFestival: null,
		festListPage: -1,
		festName: '',
		perPage: 3,
		maxFest: 0,
		firstID: null,
		queued: null,
		lowres: false,
		useLowResPlayer: function(state) {
			this.lowres = state;
		},
		addFilm: function(film) {
			if (this.films.length < 1) {
				this.firstID = film.id;
			}
			this.films[film.id] = film;
		},
		newestFestival: function() {
			var id = 0;
			var name = 0;
			var num_rgx = /^\d+$/i;
			
			for (i = 0; i < this.festivals.length; i++) {
				if (this.festivals[i] > name && num_rgx.test(this.festivals[i])) {
					name = this.festivals[i];
					id = i;
				}
			}
			
			return name;
		},
		addFestival: function(id, name, hidden) {
			this.festivals[name] = name;
			this.hidden[name] = hidden;
			if (name > this.maxFest) { this.maxFest = name; }
		},
		playFilm: function(film_id, auto_play) {
			if (typeof auto_play == 'undefined') {
				auto_play = true;
			}
			
			var player_width = this.lowres ? '480' : '750';
			var player_height = this.lowres ? '360' : '392';
			
			var film = this.films[film_id];
			
			if (typeof film != 'undefined') {
			  
				if (typeof pageTracker !== 'undefined' && typeof pageTracker._trackPageview === 'function') {
					var track_url = ('/video-play/' + film.filmfest_name + '/' + film.id + '/' + film.title).replace(' ', '-').replace(/[^-A-Za-z0-9\/]+/gi, '-');
					pageTracker._trackPageview(track_url);
				}
			
				
				document.location.hash = '#' + this.festName + '/' + film_id;
				
				$('#movieTitle').html(film.title);
				$('#movieDescription').html(film.description);
				//var cfg = "{'clip': {'url':'/download?id=" + film.videofile_id  + "','autoPlay':" + auto_play + "}}"
				var cfg = "{'clip': {'url':'" + film.videofile.replace("'", "\\'")  + "','autoPlay':" + auto_play + "}}"
				swfobject.embedSWF("/swf/flowplayer-3.1.5.swf", "movieStage", player_width, player_height, "9.0.0", null, { 
					config: cfg
					}
				);
				
				var $win = $(window);
				var $mt = $('#movieTitle');
				var $ms = $('#movieStage');
				var $mw = $('#movieWaterType');
				var $ma= $('#movieAward');
				
				if (film.saltwater) {
					$mw.removeClass('freshwater').addClass('saltwater').html('Saltwater');
				} else {
					$mw.removeClass('saltwater').addClass('freshwater').html('Freshwater');
				}
				
				
				var award_markup = '';
				
				switch (film.award) {
					case 'gold':
						award_markup = '<img src="/images/gold_player.png" /><strong>Golden Trout Winner</strong>';
						break;
					case 'silver':
						award_markup = '<img src="/images/silver_player.png" /><strong>Silver Trout Winner</strong>';
						break;
					case 'bronze':
						award_markup = '<img src="/images/bronze_player.png" /><strong>Bronze Trout Winner</strong>';
						break;
				}
				$ma.html(award_markup);
			
				
				if ($ms.height() <= $win.height() && ($win.scrollTop() > $mt.position().top || $win.scrollTop() + $win.height() < $ms.position().top + $ms.height())) {				
					$('html, body').animate({scrollTop: $('#movieTitle').position().top}, 1000);
				}
			}
		},
		firstFilm: function(container_selector) {
			var container = (typeof container_selector == 'undefined') ? '#movieGallery' : container_selector;
			var first_id = $(container + ' .movieContainer:eq(0) a').attr('rel');
			return first_id;
		},
		festivalFilms: function(festival_name) {
			var fest_films = [];
			for (var i = 0; i < filmFest.films.length; i++) {
				var film = filmFest.films[i];
				if (typeof film != 'undefined' && film.filmfest_name == festival_name) {
					fest_films.push(film);
				}
			}
			
			return fest_films.sort(function(a,b) { return a.position - b.position; });
		},
		playFirst: function() {
			var first_id = this.firstFilm();
			this.playFilm(first_id, true);
		},
		filter: function(opts) {
			var film = {};
			var skip = false;
			var film_list = [];
			
			for (film_idx in this.films) {
				skip = false;
				film = this.films[film_idx];
				if (typeof opts.filmfest_id != 'undefined' && film.filmfest_name != opts.filmfest_id) { skip = true; }
				if (typeof this.filters.saltwater != 'undefined' && film.saltwater != this.filters.saltwater) { skip = true; }
				if (typeof this.filters.favorite != 'undefined' && film.favorite != this.filters.favorite && (this.filters.favorite && film.award == 'none')) { skip = true; }
				if (!skip) {
					film_list.push(film);
				}
			}
			
			function sortFunc(a, b) {
				return a.position - b.position; 
			}
			
			film_list = film_list.sort(sortFunc);
			return film_list;
		},
		filmFestList: function(film_list, gallery_container) {
			var dbg = '';
			var film = {};
			
			if (typeof gallery_container == 'undefined') {
				gallery_container = '#movieGallery';
			}
			
			var list = '';
			var row_cnt = 0;
			var thumb_cnt = 0;
			var thumbs = $(gallery_container + ' .movieContainer').get().reverse();
			
			var delay = 0;
			
			this.animating = true;
			
			if (thumbs.length < 1) {
				continueAnimation();
			} else { 
				$(thumbs).each(function() {
					var ctxt = this;
					thumb_cnt++;
					setTimeout(function() {
						$(ctxt).fadeOut(250);
						thumb_cnt--;
						if (thumb_cnt == 0) {
							continueAnimation();
						}
					}, delay);
					delay += 100;
				});
			}
			
			function continueAnimation() {
				
				for (i = 0; i < film_list.length; i++) {
					film = film_list[i];
					row_cnt++;
					if (row_cnt == 1) {
						list += '<div class="movieRow clearfix">';
					}
					optional_container_class = row_cnt == 4 ? ' last' : '';
					list += filmFest.filmListEntry(film, optional_container_class)
					if (row_cnt == 4) {
						list += "</div><!-- movieRow-->\n";
						list += "<div style=\"clear:both;\"></div>\n";
						row_cnt = 0;
					}
				}
				$(gallery_container).html(list);
				var height = $(gallery_container).height();
				$(gallery_container + ' .movieContainer').hide();
				$(gallery_container).height(height);
				var delay = 0;
				thumb_cnt = 0;
				$('.movieContainer').each(function() {
					var ctxt = this;
					thumb_cnt++;
					setTimeout(function() {
						$(ctxt).fadeIn(250);
						thumb_cnt--;
						if (thumb_cnt == 0) {
							this.animating = false;
							registerTooltips();
							if (filmFest.queued != null) {
								filmFest.playFilm(filmFest.queued, true);
							} else {
								filmFest.playFilm(filmFest.firstFilm(), true);
							}
							
							filmFest.queued = null;
						}
					}, delay);
					delay += 100;
				});
				
			}; // continueAnimation()
		},
		filmListEntry: function(film, opt_class) {
			film_id = film.id;
			water_class = film.saltwater ? 'sw' : 'fw';
			water_label = film.saltwater ? 'SW' : 'FW';
			film_title = film.title;
			film_description = film.description;
			thumb_id = film.thumbnailfile_id;
			video_id = film.videofile_id;
			award = film.award;
			
		
			award_badge = '';
			if (award == 'gold') {
				award_badge = '<a href="#" class="tip_trigger"><img src="/images/goldentrout.png" /><div class="tip">Golden Trout Winner</div></a>';
			} else if (award == 'silver') {
				award_badge = '<a href="#" class="tip_trigger"><img src="/images/silvertrout.png" /><div class="tip">Silver Trout Winner</div></a>';
			} else if (award == 'bronze') {
				award_badge = '<a href="#" class="tip_trigger"><img src="/images/bronzetrout.png" /><div class="tip">Bronze Trout Winner</div></a>';
			}
			
			var entry = '';
			
			//entry += '<div class="movieContainer ' + water_class + '_movie clearfix' + opt_class + '">';
			entry += '<div class="movieContainer clearfix' + opt_class + '">';
			entry += '  <div class="movieBox clearfix">';
			entry += '  	<div class="movieClipper clearfix">';
			entry += '      <a href="javascript:filmFest.playFilm(' + film_id + ', true);" class="moviePlay" rel="' + film_id + '"></a><!-- end moviePlay -->';
			entry += '			<img src="/image?id=' + thumb_id + '&amp;width=170&amp;height=98" alt="' + film_title + '" title="' + film_title + '" />';
			if (this.specificFestival == null) {
				entry += '			<div class="' + water_class + '">' + water_label + '</div>';
			}
			entry += '		</div><!-- end movieClipper -->';
			entry += '	</div><!-- end movieBox -->'
			entry += '	<div class="movieMeta">';
			entry += '	<strong>' + film_title +  '</strong><br/>';
			entry += '  ' + film_description + award_badge
			entry += '	</div><!-- end movieMeta -->'
			entry += '</div><!-- end movieContainer -->';
			
			return entry;
		},
		listFestival: function(filmfest_id, gallery_container) {
			$('.festButton').removeClass('active');
			$('.festButton' + filmfest_id).addClass('active');
			this.activeFestival = filmfest_id;
			var new_page = Math.ceil(filmfest_id / this.perPage);
			if (new_page != this.festListPage) {
				this.festListPage = new_page;
				this.buildFestList();
			}
			this.festName = filmfest_id;
			document.location.hash = '#' + this.festName;
			
			this.filmFestList(this.filter({'filmfest_id': filmfest_id}), gallery_container);
		},
		setFilter: function(filter, state, toggle) {
			$('#waterSelector a').removeClass('active');
			$('#waterSelector a.' + toggle).addClass('active');
			
			this.filters[filter] = state;
			this.filmFestList(this.filter({'filmfest_id': this.activeFestival}));
		},
		init: function() {
			this.listFestival(this.newestFestival());
			this.setFilter('saltwater', undefined, 'water_all');
		},
		getFestivalIDByName: function(name) {
			for (var fname in this.festivals) {
				if(this.festivals.hasOwnProperty(fname) && name == this.festivals[fname]) {
					return fname;
				}
			}
			return false;
		},
		setSpecificFestival: function(name) {
			this.specificFestival = name;
		},
		buildFestList: function() {
			$ffl = $('#festivalSelector');
			var idx = -1;
			$ffl.children().each(function() {
				idx++;
				if ($(this).val() == filmFest.activeFestival) {
					$(this).addClass('active')
					$ffl.get(0).selectedIndex = idx;
				} else {
					$(this).removeClass('active');
				}
			});			
		},
		selectFest: function(a) {
			var $ffl = $('#festivalSelector'); 
			this.festName = $ffl.children().get($ffl.get(0).selectedIndex).value;
			filmFest.listFestival(this.festName);
			document.location.hash = '#' + this.festName;
		},
		nextPage: function() {
			this.festListPage++;
			this.buildFestList();
		},
		prevPage: function() {
			this.festListPage--;
			this.buildFestList();
		}
	}; // filmFest Controller
	
	if (typeof loadFilms == 'function') {
		loadFilms();
		
		$('.bonusGallery').each(function() {
			var ctxt = this;
			var id = $(ctxt).attr('id');
			var fest_name = $(ctxt).attr('rel');
			var fest_id = filmFest.getFestivalIDByName(fest_name);
			filmFest.listFestival(fest_id, '#' + id);
		});
		
		var hash = self.document.location.hash.substring(1);
		var initial_id = filmFest.newestFestival();
		var parts = [];
		
		
		if (hash) {
			parts = hash.split('/');
			if (parts.length > 0) {
				initial_id = parts[0];
			}
		}
		
		if (hash && filmFest.getFestivalIDByName(hash)) {
			initial_id = filmFest.getFestivalIDByName(hash);
		}
		if (filmFest.getFestivalIDByName(filmFest.specificFestival) != false) {
			initial_id = filmFest.getFestivalIDByName(filmFest.specificFestival);
		}

		var initial_vid = filmFest.festivalFilms(initial_id)[0].id;
		if (parts.length > 1) {
			initial_vid = parts[1];
		}
		
		if (typeof initial_vid != 'undefined') {
			document.location.hash = '#' + initial_id
			
			filmFest.setFilter('saltwater', undefined, 'water_all');
			filmFest.queued = initial_vid;
			filmFest.listFestival(initial_id);
		}
	}
}); // document ready
