// media-gallery.js

var gallery = ({
	t: null,
	active: 0,
	galleries: [],
	copy: [],
	imgs: [],
	shortname: [],
	hash: window.hash,
	defaults: [
		{
			name: "NASCAR",
			img: '/images/media-gallery/nascar-default.jpg',
			copy: 'View photos and videos of Valvoline at NASCAR. Experience the rush!',
			shortname: 'nascar',
			active: true
		},
		{
			name: "NHRA",
			img: '/images/media-gallery/nhra-default.jpg',
			copy: 'Check out the full-throttle action of Valvoline NHRA drivers and teams.',
			shortname: 'nhra',
			active: true
		},
		{
			name: "Other League",
			img: '',
			copy: '',
			shortname: 'other-league',
			active: false
		},
		{
			name: "Racing Video",
			img: '',
			copy: '',
			shortname: 'racing-video',
			active: false
		},
		{
			name: "Commercials",
			img: '/images/media-gallery/commercials-default.jpg',
			copy: 'View the latest and greatest Valvoline commercials.',
			shortname: 'commercials',
			active: true
		},
		{
			name: "Other Videos",
			img: '/images/media-gallery/other-videos-default.jpg',
			copy: 'View other great videos from Valvoline.',
			shortname: 'other-videos',
			active: true
		},
		{
			name: "Other Media",
			img: '/images/media-gallery/other-media-default.jpg',
			copy: 'Download desktop wallpapers and other Valvoline media.',
			shortname: 'other-media',
			active: true
		}
	],
	cHolder: null,
	init: function(){
		var gButtons = $("#gallery-nav li a");
		var gContainers = $("#gallery-nav li");
		$("div.promo-button").css({
			opacity: 0
		});
		
		if(ie6){
		   $("#container div").css({
		      position: "relative"
		   });
		}
		
		$.get('/include/media-gallery/gallery-landing-xml.jsf', function(xml){
			var json = $.xml2json(xml);
				
			var isActive = false;		
			for(i=0;i<json.section.length;i++){
				isActive = gallery.isActive(json.section[i].name);
				if(isActive){
					gallery.galleries[gallery.galleries.length] = json.section[i].name;
				}
			}
			
			
			for(i=0;i<json.section.length;i++){
				
				if(isActive){
					
					var hasImg = json.section[i].img ? true : false; 
					var hasCopy = json.section[i].copy ? true : false; 

					var name = json.section[i].name;
					var shortname = json.section[i].shortname;

					// set copy
					if(hasCopy){
						gallery.copy[gallery.copy.length] = json.section[i].copy;
					}else{
						$(gallery.defaults).each(function(index){
							if(gallery.defaults[index].name == name){
								gallery.copy[gallery.copy.length] = gallery.defaults[index].copy;
							}
							
						});

					}


					// set images
					if(hasImg){
						gallery.imgs[gallery.imgs.length] = json.section[i].img;
					}else{
						$(gallery.defaults).each(function(index){
							if(gallery.defaults[index].name == name){
								gallery.imgs[gallery.imgs.length] = gallery.defaults[index].img;
							}
							
						});
					}
					$(gallery.defaults).each(function(index){
						if(gallery.defaults[index].name == name){
							gallery.shortname[gallery.shortname.length] = gallery.defaults[index].shortname;
						}
						
					});


					
				}
				
			}
					
			gButtons.click(function(ev){
				ev.preventDefault();
            
				window.clearTimeout(gallery.t);
				gallery.active = $("#gallery-nav li a").index(this);

				gContainers.each(function(i){

					if(i == gallery.active){
						$(this).animate({
							opacity: 1.0
						});
					}else{
						$(this).animate({
							opacity: 0.5
						});
					}

				});

				gallery.swap(gallery.active);
				gallery.slideshow();

			});

			$(gButtons.get(gallery.active)).trigger("click");

			gallery.slideshow();

			$("#frame").mouseenter(function(){
				window.clearTimeout(gallery.t);
			});

			$("#frame").mouseleave(function(){
				gallery.slideshow();
			});
			
		});

			
	},
	isActive: function(name){
	      var isActive = false;
	   
	      for(x=0;x<gallery.defaults.length;x++){
		      if(gallery.defaults[x].name == name){isActive = true;}
	      }
	      return isActive;
	      
	},
	swap: function(newIndex){
	   	   
		var newTitle = gallery.galleries[newIndex];
		var newCopy = gallery.copy[newIndex];
		var newImg = gallery.imgs[newIndex];
		var newHref = gallery.shortname[newIndex];
		if (newTitle === undefined) {
			newTitle = "";
		}
		newTitle.toLowerCase().replace(" ","-");


		var frame = $("#frame");
		var swapEls = $(".call h3, .call p, .call div.promo-button");
		
		
		$("#frame img").animate({
			opacity: 0
		},function(){

			$("#frame img").attr("src",newImg);

			swapEls.animate({
				left: '-999px'
			}, 500, 'swing', function(){
				
				if($("div.promo-button").css("opacity") == 0){
					$("div.promo-button").css({
						opacity: 1
					});
				}
				
				
				$(".call h3").text(newTitle);
				$(".call p").text(newCopy);
				$(".call div a").attr("href","/media-gallery/" + newHref + "/");
            if($.browser.msie && $.browser.version.substr(0,1)<7){
               $(".call").unbind("click");
               $(".call").bind("click",function(){
                  window.location.href = "/media-gallery/" + newHref + "/";
               });
            }


			}).animate({
				left: 0
			}, 500, 'swing', function(){
				
				$("#frame img").animate({
					opacity: 1
				});
				
			});

		});
		
		
		
	},
	slideshow: function(){
		var gButtons = $("#gallery-nav li a");
		gallery.t = setTimeout(function(){
			if( (gallery.active+1) < gButtons.length){
				gallery.active++;
			}else{
				gallery.active = 0;
			}
			$(gButtons.get(gallery.active)).trigger("click");
			
		},6000);
		
	},
	proper: function(){
		
		var thumbs = $("#thumb-list a");

		$.preload("#thumb-list a");

		// check/add history state
		$.historyInit(gallery.grab);

		if(location.hash){
			var cStart = jQuery.jcarousel.intval(location.hash.replace(/^.*#/, ''));
		}else{
			var cStart = 0;
		}
		
		// get images
		$("#thumb-list a").each(function(index){
			
			gallery.imgs[index] = $(this).attr("href");
			
		});

		// get copy
		$("#thumb-list a img").each(function(index){
			
			gallery.copy[index] = $(this).attr("title");
			
		});
		
		// add carousel functionality to thumbs
	    jQuery('#thumb-list').jcarousel({
	    	start: 0,
			scroll: 10,
			visible: 10,
			initCallback: function(carousel){
				var t = setTimeout(function(){carousel.scroll(cStart)},750);
				var gButtons = $("#thumb-list a");
				var el = $(gButtons.get(cStart));
				el.parent().addClass('here');
				gallery.cHolder = carousel;
				
				if(ie6){
					var ieWidth = parseFloat($(".jcarousel-list").css("width")) + 20;
					$(".jcarousel-list").css({
						width: ieWidth
					});

				}
				
			}
	    });
		
		$("#count").html("Image " + (cStart + 1) + " of " + (thumbs.length));
		
		thumbs.click(function(ev){
			ev.preventDefault();
			
			// add highlight to clicked thumb
			var index = $("#thumb-list a").index(this);
			thumbs.each(function(i){
				
				if (i == index){
					$(this).parent().addClass('here');
					gallery.active = i;
				}else{
					$(this).parent().removeClass('here');
				}
				
			});
			
			// update hash
			gallery.hash = gallery.active;
			$.historyLoad(gallery.hash);

			if(location.hash){
				var cStart = jQuery.jcarousel.intval(location.hash.replace(/^.*#/, ''));
			}else{
				var cStart = 0;
			}

			$("#count").html("Image " + (cStart + 1) + " of " + (thumbs.length));
			
		});
		
		$("#races").bind("change",function(){
			window.location.href = $("option:selected", this).val();
		});
		
	},
	grab: function(){
		var gButtons = $("#thumb-list a");

		// need the location.hash.length check for Internet Explorer,  
		// as it will return an empty hash at the initial history state
		if(location.hash && location.hash.length > 1){
			
			var cStart = jQuery.jcarousel.intval(location.hash.replace(/^.*#/, ''));
		}else{
			var cStart = 0;
		}

		gallery.active = cStart;


		// image transition
		if(location.hash && location.hash.length > 1){
			
			var lh = location.hash.replace(/^.*#/, '');
			var el = $(gButtons.get(lh));
		}else{

			var el = $(gButtons.get(gallery.active));
		}
		
		var newImgSrc = $(el).attr("href");
		var oldImg = $("#frame img");


		
		oldImg.animate({
			opacity: 0
		}, function(){
			
			oldImg.remove();
			
			var newImg = "<img src=\"" + newImgSrc + "\" />";
			$("#frame").append(newImg);
			oldImg = $("#frame img");
			oldImg.css("opacity",0);
			if (oldImg.width() > 700) oldImg.width(700);

			// delay so browser has time to render the image,
			// and therefore provide accurate dimensions back to us
			var t = setTimeout(function(){
				// using innerWidth & height for IE6 compatibility
				var newWidth = oldImg.innerWidth();
				var newHeight = oldImg.innerHeight();

				$("#frame").animate({
					width: newWidth,
					height: newHeight
				}, function(){
					
					$("#caption").animate({
						opacity: 0
					}).html(gallery.copy[gallery.active]).animate({
						opacity: 1
					});
					
					
					oldImg.animate({
						opacity: 1
					});

					var t = setTimeout(function(){gallery.cHolder.scroll(cStart)},250);
					var gButtons = $("#thumb-list a");
					// add highlight to clicked thumb
					var index = $("#thumb-list a").index(cStart);
					gButtons.each(function(i){

						if (i == cStart){
							$(this).parent().addClass('here');
							gallery.active = i;
						}else{
							$(this).parent().removeClass('here');
						}

					});
					
					
				});
				
			},950);
			
							
		});

		
	},
	videoEls: [],
	video: function(){
	
		var section = $.trim($("#gallery :first-child").text().replace(/<!--(.|\s)*-->/g,""));
		for (var i = 0; i < this.defaults.length; i++) {
			if (this.defaults[i].name === section) {
				section = this.defaults[i].shortname;
				break;
			}
		}

		if(location.hash){
			var cStart = jQuery.jcarousel.intval(location.hash.replace(/^.*#/, ''));
		}else{
			var cStart = 0;
		}

		$("#frame").css({
			textAlign: "center",
			backgroundColor: "black"
		});

		
		// fetch xml reference
		$.get('/include/media-gallery/media-gallery-videos.jsf', {section: section}, function(xml){

			var json = $.xml2json(xml);
			gallery.videoEls = json;

			$.historyLoad(cStart);
			
			// setup externalInterface button actions

				var buttons = $("#thumb-list a");

      		// add carousel functionality to thumbs
      	    jQuery('#thumb-list').jcarousel({
      	    	start: 0,
      			scroll: 10,
      			visible: 10,
      			initCallback: function(carousel){
      				var t = setTimeout(function(){carousel.scroll(cStart)},750);
      				var gButtons = $("#thumb-list a");
      				var el = $(gButtons.get(cStart));
      				el.parent().addClass('here');
      				gallery.cHolder = carousel;

      				if(ie6){
      					var ieWidth = parseFloat($(".jcarousel-list").css("width")) + 20;
      					$(".jcarousel-list").css({
      						width: ieWidth
      					});
      				}

      			}
      	    });


				
				buttons.click(function(ev){
					ev.preventDefault();
					
					var pos = $.inArray(this,buttons);
					gallery.active = pos;
					
					$("#gallery").css("height","500");

         		var thumbs = $("#thumb-list a");
					
      			// add highlight to clicked thumb
      			var index = $("#thumb-list a").index(this);
      			thumbs.each(function(i){

      				if (i == index){
      					$(this).parent().addClass('here');
      					gallery.active = i;
      				}else{
      					$(this).parent().removeClass('here');
      				}

      			});


					// update hash
					gallery.hash = gallery.active;
					$.historyLoad(gallery.hash);

					if(location.hash){
						var cStart = jQuery.jcarousel.intval(location.hash.replace(/^.*#/, ''));
					}else{
						var cStart = 0;
					}
					
				});
			
		});

		// check/add history state
		$.historyInit(gallery.grabVideo);
		
		// prevent addThis button from loading first video (href="#")
		$("#add-this a").click(function(ev){
		   ev.preventDefault();
		});
		
		
	},
	grabVideo: function(vIndex){

		var gButtons = $("#thumb-list a");

		// need the location.hash.length check for Internet Explorer,  
		// as it will return an empty hash at the initial history state
		if(location.hash && location.hash.length > 1){
			var cStart = jQuery.jcarousel.intval(location.hash.replace(/^.*#/, ''));
		}else{
			var cStart = 0;
		}

		gallery.active = cStart;
		
		if(!vIndex){
			vIndex = gallery.active;
		}
		
		var obj = swfobject.getObjectById("videoFrame");
		if (obj && typeof obj._videoSwap != "undefined") {
			obj._videoSwap(vIndex);
		}
		
	},
	vidFrameResize: function(vIndex,newWidth,newHeight){
		$("#frame").animate({
			width: newWidth,
			height: newHeight
		});
		
	},
	fetchVideoCopy: function(vIndex){
		var buttons = $("#thumb-list a");
		
		var copyEls = $("#count, #caption, #desc");
		
		copyEls.animate({
			opacity: 0
		},function(){
			
			$("#count").html("Video " + (vIndex + 1) + " of " + (buttons.length));
			$("#caption").html(gallery.videoEls.image[vIndex].caption);
			$("#desc").html(gallery.videoEls.image[vIndex].description);

			copyEls.animate({
				opacity: 1
			});
		})
		
		
	},
	externalInterfaceHook: function(movieName){
         if (navigator.appName.indexOf("Microsoft") != -1) {
             return window[movieName];
         } else {
             return document[movieName];
         }
	},
	flashMsg: function(msg){
		if($.browser.msie){
			alert("as: " + msg);
		}else{
			console.log("as: " + msg);
		}
	},
	landing: function(){
		
		$("#races").bind("change",function(){
			window.location.href = $("option:selected", this).val();
		});
		
		jQuery('#races-list').jcarousel({
	    	start: 0,
			scroll: 1,
			visible: 1,
			initCallback: function(carousel){

   			   if(carousel.options.size == 1){
   			      if(ie6){
   			         // ie6... /facepalm
      			      $(".jcarousel-prev").css({
      			         marginLeft: "-80px"
      			      });
   			         
   			      }
   			   }

			}
	    });
	    
		
	}
	
});


/**
 *
 * History extension for jQuery
 * Credits to http://www.mikage.to/
 *
**/


/*
 * jQuery history plugin
 *
 * Copyright (c) 2006 Taku Sano (Mikage Sawatari)
 * Licensed under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 * Modified by Lincoln Cooper to add Safari support and only call the callback once during initialization
 * for msie when no initial hash supplied.
 */


jQuery.extend({
	historyCurrentHash: undefined,
	
	historyCallback: undefined,
	
	historyInit: function(callback){
		jQuery.historyCallback = callback;
		var current_hash = location.hash;
		
		jQuery.historyCurrentHash = current_hash;
		if(jQuery.browser.msie) {
			// To stop the callback firing twice during initilization if no hash present
			if (jQuery.historyCurrentHash === '') {
			jQuery.historyCurrentHash = '#';
		}
		
			// add hidden iframe for IE
			$("body").prepend('<iframe id="jQuery_history" style="display: none;"></iframe>');
			var ihistory = $("#jQuery_history")[0];
			var iframe = ihistory.contentWindow.document;
			iframe.open();
			iframe.close();
			iframe.location.hash = current_hash;
		}
		else if ($.browser.safari) {
			// etablish back/forward stacks
			jQuery.historyBackStack = [];
			jQuery.historyBackStack.length = history.length;
			jQuery.historyForwardStack = [];
			
			jQuery.isFirst = true;
		}
		jQuery.historyCallback(current_hash.replace(/^#/, ''));
		setInterval(jQuery.historyCheck, 100);
	},
	
	historyAddHistory: function(hash) {
		// This makes the looping function do something
		jQuery.historyBackStack.push(hash);
		
		jQuery.historyForwardStack.length = 0; // clear forwardStack (true click occured)
		this.isFirst = true;
	},
	
	historyCheck: function(){
		if(jQuery.browser.msie) {
			// On IE, check for location.hash of iframe
			var ihistory = $("#jQuery_history")[0];
			var iframe = ihistory.contentDocument || ihistory.contentWindow.document;
			var current_hash = iframe.location.hash;
			if(current_hash != jQuery.historyCurrentHash) {
			
				location.hash = current_hash;
				jQuery.historyCurrentHash = current_hash;
				jQuery.historyCallback(current_hash.replace(/^#/, ''));
				
			}
		} else if ($.browser.safari) {
			if (!jQuery.dontCheck) {
				var historyDelta = history.length - jQuery.historyBackStack.length;
				
				if (historyDelta) { // back or forward button has been pushed
					jQuery.isFirst = false;
					var i;
					if (historyDelta < 0) { // back button has been pushed
						// move items to forward stack
						for (i = 0; i < Math.abs(historyDelta); i++) {
							jQuery.historyForwardStack.unshift(jQuery.historyBackStack.pop());
						}
					} else { // forward button has been pushed
						// move items to back stack
						for (i = 0; i < historyDelta; i++) {
							jQuery.historyBackStack.push(jQuery.historyForwardStack.shift());
						}
					}
					var cachedHash = jQuery.historyBackStack[jQuery.historyBackStack.length - 1];
					if (cachedHash !== undefined) {
						jQuery.historyCurrentHash = location.hash;
						jQuery.historyCallback(cachedHash);
					}
				} else if (jQuery.historyBackStack[jQuery.historyBackStack.length - 1] === undefined && !jQuery.isFirst) {
					// back button has been pushed to beginning and URL already pointed to hash (e.g. a bookmark)
					// document.URL doesn't change in Safari
					if (document.URL.indexOf('#') >= 0) {
						jQuery.historyCallback(document.URL.split('#')[1]);
					} else {
						current_hash = location.hash;
						jQuery.historyCallback('');
					}
					jQuery.isFirst = true;
				}
			}
		} else {
			// otherwise, check for location.hash
			current_hash = location.hash;
			if(current_hash != jQuery.historyCurrentHash) {
				jQuery.historyCurrentHash = current_hash;
				jQuery.historyCallback(current_hash.replace(/^#/, ''));
			}
		}
	},
	historyLoad: function(hash){
		var newhash;
		if (jQuery.browser.safari) {
			newhash = hash;
		}
		else {
			newhash = '#' + hash;
			location.hash = newhash;
		}

		jQuery.historyCurrentHash = newhash;
		
		if(jQuery.browser.msie) {
			var ihistory = $("#jQuery_history")[0];
			var iframe = ihistory.contentWindow.document;
			iframe.open();
			iframe.close();
			iframe.location.hash = newhash;
			jQuery.historyCallback(hash);
		}
		else if (jQuery.browser.safari) {
			jQuery.dontCheck = true;
			// Manually keep track of the history values for Safari
			this.historyAddHistory(hash);
			
			// Wait a while before allowing checking so that Safari has time to update the "history" object
			// correctly (otherwise the check loop would detect a false change in hash).
			var fn = function() {jQuery.dontCheck = false;};
			window.setTimeout(fn, 200);
			jQuery.historyCallback(hash);
			// N.B. "location.hash=" must be the last line of code for Safari as execution stops afterwards.
			//      By explicitly using the "location.hash" command (instead of using a variable set to "location.hash") the
			//      URL in the browser and the "history" object are both updated correctly.
			location.hash = newhash;
		}
		else {
		  jQuery.historyCallback(hash);
		}
	}
});
