$(function() {
	PT.Home.Carousel.init();
	PT.Home.init();
});

PT.Home = {

	settings: {
		jsIsReady: false,
		slider: null
	},

	init: function() {
	
		PT.Global.isJSReady = true;
	
		PT.Home.tabs();
		
		/*$('#footer-flash-blue').css('z-index', 999990 );
		$('#footer-flash').css('z-index', 999999 );
		$( 'object' ).css('z-index', 99999999 );*/
	},
	
	tabs: function () {
		
		if ( $( '#social-media-tabs' ).length > 0 ) {
		
			$('#social-media-tabs').addClass('start-tracking');
		
			$( '#social-media-tabs' ).tabs({
				show: function ( event, ui ) {
					var activeText = $('#social-media-tabs').find('li.ui-state-active').text();
					
					if ( $('#social-media-tabs').hasClass( 'start-tracking' ) ) {
						$( '#social-media-tabs').removeClass( 'start-tracking' );
					} else {
						BGC.track( 'home|click|' + activeText );
					}
					
				}
			});
		}
		
	},
	
	youTube: {
	
		init: function() {
		
			PT.Home.youTube.embedVideos();
		
		},
		
		embedVideo: function ( containerID ) {
			PT.Home.settings.slider.pause();
			var movie = $("#" + containerID ).parent().data('movie');
			if ( ! movie.match ( /\&enablejsapi\=1/i ) ) {
				movie += '&enablejsapi=1';
			}
			if ( ! movie.match ( /\&wmode\=transparent/i ) ) {
				movie += '&wmode=transparent';
			}
			var height = $("#" + containerID ).parent().data('height');
			var width = $("#" + containerID ).parent().data('width');
			var params = { allowScriptAccess: "always" };
    		var atts = { id: containerID };
    		
    		swfobject.embedSWF(movie, containerID, width, height, "8", null, null, params, atts );
		},
		
		embedVideos: function() {
			$( '.youtube-video div' ).each(function() {
				$(this).parent().data('videoid', $(this).attr('id'));
				PT.Home.youTube.embedVideo ( $(this).attr('id') );
			});
		}
	
	},
	
	doesMovieObjectExist: function( name ) {
		return ( $('object[name="' + name + '"]' ).length > 0 ? true : false );
	},
	
	sliderEmbedFlash: function( parentID, movieFile ) {
		
		var protocol = window.location.protocol;
		var hostname = window.location.hostname;
		var myDomain = protocol + '//' + hostname + '/';
		
		var myID = parentID + '-replace';
		
		var flashvars = {
			domain: myDomain,
			moviePath: $('#' + parentID ).data('f4v')
		};
		
		var params = {
			movie: $('#' + parentID ).data('swf'),
			play: true,
			wmode: 'transparent'
		};
		
		var attributes = {
			id: myID,
			name: myID
		};
		
		swfobject.embedSWF ( $('#' + parentID ).data('swf'), myID, 960, 550, "9.0.0", "expressInstall.swf", flashvars, params, attributes, function() {});
		
	},
	
	playMovie: function ( movieID ) {
		movieID = movieID.replace( /^\#/, '' );
		movieID = 'object#' + movieID;
		if ( $(movieID).length > 0 ) {
			$( movieID ).externalInterface({
				method: 'beginCarouselItem',
				success: function ( response ) {
					//alert ( 'success: ' + response );
				},
				error: function ( error ) {
					alert ( 'error: ' + error );
				}
			});
		} else {
			PT.Home.playMovie ( movieID );
		}
		
	}

};

PT.Home.Carousel = {

	settings: {
		carousel: null,
		currentSlideIndex: 1,
		hardPause: false,
		paused: false,
		videoState: -1,
		mousex: 0,
		mousey: 0
	},

	init: function ( options ) {
		
		if ( options ) {
			$.extend ( PT.Home.Carousel.settings, options );
		}
		
		$(document).mousemove(function(e) {
			PT.Home.Carousel.settings.mousex = e.pageX;
			PT.Home.Carousel.settings.mousey = e.pageY;
		});
		
		PT.Home.Carousel.embedYouTubeVideo();
		
		$( '#carousel' ).jcarousel({
			auto: 4,
			scroll: 1,
			start: 1,
			itemFallbackDimension: 950,
			wrap: 'both',
			initCallback: PT.Home.Carousel.initCallback,
			itemFirstInCallback: PT.Home.Carousel.itemFirstInCallback,
			itemFirstOutCallback: PT.Home.Carousel.itemFirstOutCallback,
			// This tells jCarousel NOT to autobuild prev/next buttons
        	buttonNextHTML: null,
        	buttonPrevHTML: null
		});
		
	},
	
	initCallback: function ( carousel, state ) {
	
		PT.Home.Carousel.settings.carousel = carousel;
	
		jQuery('.jcarousel-control a.jump-to').bind('click', function() {
			var slideIndex = jQuery.jcarousel.intval(jQuery(this).text());
			PT.Home.Carousel.pauseYouTubeVideos();
			PT.Home.Carousel.resumeSlider();
    	    carousel.scroll(slideIndex);
    	    return false;
    	});
		
		$( '.jcarousel-control a.prev-next.prev' ).bind('click', function() {
			PT.Home.Carousel.pauseYouTubeVideos();
			PT.Home.Carousel.resumeSlider();
			carousel.prev();
			return false;
		});
		
		$( '.jcarousel-control a.prev-next.next' ).bind('click', function() {
			PT.Home.Carousel.pauseYouTubeVideos();
			PT.Home.Carousel.resumeSlider();
			carousel.next();
			return false;
		});
		
		carousel.clip.hover(function() {
			PT.Home.Carousel.pauseSlider();
		}, function() {
		
			if ( PT.Home.Carousel.settings.hardPause == true ) {
				PT.Home.Carousel.pauseSlider();
			} else {
				PT.Home.Carousel.resumeSlider();
			}
		});
		
	},
	
	itemFirstInCallback: function( carousel, item, idx, state ) {
		PT.Home.Carousel.embedFlashVideo( carousel, item, idx, state );
		
		var activeIdx = parseInt($(item).attr('jcarouselindex')) - 1;
		$( '.jcarousel-control a.jump-to.active' ).removeClass('active');
		$( '.jcarousel-control a.jump-to:eq(' + activeIdx + ')' ).addClass('active');
		
	},
	
	
	
	itemFirstOutCallback: function( carousel, item, idx, state ) {
		PT.Home.Carousel.settings.carousel = carousel;
	},
	
	pauseYouTubeVideos: function() {
		if ( PT.Home.Carousel.settings.videoState == 1 ) {
			var player = document.getElementById ( $( '.jcarousel-item.has-youtube-video object' ).attr('id') );
			player.stopVideo();
		}
	},
	
	embedFlashVideo: function ( carousel, item, idx, state ) {
		PT.Home.Carousel.settings.carousel = carousel;
		PT.Home.Carousel.settings.currentSlideIndex = idx;
		
		if ( $(item).find('.flash-video-bg').length > 0 && $(item).find('.flash-video-bg').find('.flash-video-bg-replace').length > 0 ) {
			
			
			PT.Home.Carousel.pauseSlider();
			
			var protocol = window.location.protocol;
			var hostname = window.location.hostname;
			var myDomain = protocol + '//' + hostname + '/';
			
			
			var myID = $(item).find('.flash-video-bg').find('.flash-video-bg-replace').attr('id');
			
			
			var flashvars = {
				domain: myDomain,
				moviePath: $('#' + myID ).data('f4v')
			};
		
			var params = {
				movie: $('#' + myID ).data('swf'),
				play: true,
				wmode: 'transparent'
			};
		
			var attributes = {
				id: myID,
				name: myID,
				'class': 'flash-video-bg'
			};

			swfobject.embedSWF ( $('#' + myID ).data('swf'), myID, 960, 550, "9.0.0", "expressInstall.swf", flashvars, params, attributes );

		}
	},
	
	embedYouTubeVideo: function () {
		var params = { allowScriptAccess: "always" };
    	var atts = { id: "myytplayer" };
    	// Uncomment for production
    	swfobject.embedSWF("http://www.youtube.com/v/SrKhnBlfYn4?enablejsapi=1&playerapiid=ytplayer&version=3&wmode=transparent&rel=0", "ytapiplayer", "486", "302", "8", null, null, params, atts);
    	// Comment out for production
    	//swfobject.embedSWF("http://www.youtube.com/v/dL-W3pXU84c?enablejsapi=1&playerapiid=ytplayer&version=3&wmode=transparent&rel=0", "ytapiplayer", "486", "302", "8", null, null, params, atts);
	},
	
	pauseSlider: function() {
		PT.Home.Carousel.settings.paused = true;
		PT.Home.Carousel.settings.carousel.stopAuto();
	},
	
	resumeSlider: function() {
		PT.Home.Carousel.settings.paused = false;
		PT.Home.Carousel.settings.carousel.startAuto();
	}
	
};

function onMovieEnd() {
	var pcOffset = $( '#primary-content').offset();
	var pcWidth = $( '#primary-content').outerWidth();
	var pcHeight = $( '#primary-content').outerHeight();
	
	var offsetLeft = pcOffset.left;
	var offsetRight = pcOffset.left + pcWidth;
	var offsetTop = pcOffset.top;
	var offsetBottom = pcOffset.top + pcHeight;
	
	if ( PT.Home.Carousel.settings.mousex >= offsetLeft && PT.Home.Carousel.settings.mousex <= offsetRight ) {
		if ( PT.Home.Carousel.settings.mousey >= offsetTop || PT.Home.Carousel.settings.mousey <= offsetBottom ) {
			//alert('youre still over me!');
			PT.Home.Carousel.pauseSlider();
		} else {
			PT.Home.Carousel.resumeSlider();
		}
	} else {
		PT.Home.Carousel.resumeSlider();	
	}
	

}

function onYouTubePlayerReady(playerId) {
  ytplayer = document.getElementById("myytplayer");
  ytplayer.addEventListener("onStateChange", "onytplayerStateChange");
}

function onytplayerStateChange(newState) {
	newState = parseInt(newState);
	
	switch ( newState ) {
		case 1: // Playing
			PT.Home.Carousel.pauseSlider();
			PT.Home.Carousel.settings.hardPause = true;
			break;
		case 3: // Buffering
			PT.Home.Carousel.pauseSlider();
			PT.Home.Carousel.settings.hardPause = true;
			break;
		default:
			PT.Home.Carousel.resumeSlider();
			PT.Home.Carousel.settings.hardPause = false;
			break;
	}
	
	PT.Home.Carousel.settings.videoState = newState; 
}

(function(){var a=document.all,b="http://www.adobe.com/go/getflashplayer",c=typeof jQuery=="function",d=/(\d+)[^\d]+(\d+)[^\d]*(\d*)/,e={width:"100%",height:"100%",id:"_"+(""+Math.random()).slice(9),allowfullscreen:!0,allowscriptaccess:"always",quality:"high",version:[3,0],onFail:null,expressInstall:null,w3c:!1,cachebusting:!1};window.attachEvent&&window.attachEvent("onbeforeunload",function(){__flash_unloadHandler=function(){},__flash_savedUnloadHandler=function(){}});function f(a,b){if(b)for(var c in b)b.hasOwnProperty(c)&&(a[c]=b[c]);return a}function g(a,b){var c=[];for(var d in a)a.hasOwnProperty(d)&&(c[d]=b(a[d]));return c}window.flashembed=function(a,b,c){typeof a=="string"&&(a=document.getElementById(a.replace("#","")));if(a){typeof b=="string"&&(b={src:b});return new j(a,f(f({},e),b),c)}};var h=f(window.flashembed,{conf:e,getVersion:function(){var a,b;try{b=navigator.plugins["Shockwave Flash"].description.slice(16)}catch(c){try{a=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7"),b=a&&a.GetVariable("$version")}catch(e){try{a=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6"),b=a&&a.GetVariable("$version")}catch(f){}}}b=d.exec(b);return b?[b[1],b[3]]:[0,0]},asString:function(a){if(a===null||a===undefined)return null;var b=typeof a;b=="object"&&a.push&&(b="array");switch(b){case"string":a=a.replace(new RegExp("([\"\\\\])","g"),"\\$1"),a=a.replace(/^\s?(\d+\.?\d*)%/,"$1pct");return"\""+a+"\"";case"array":return"["+g(a,function(a){return h.asString(a)}).join(",")+"]";case"function":return"\"function()\"";case"object":var c=[];for(var d in a)a.hasOwnProperty(d)&&c.push("\""+d+"\":"+h.asString(a[d]));return"{"+c.join(",")+"}"}return String(a).replace(/\s/g," ").replace(/\'/g,"\"")},getHTML:function(b,c){b=f({},b);var d="<object width=\""+b.width+"\" height=\""+b.height+"\" id=\""+b.id+"\" name=\""+b.id+"\"";b.cachebusting&&(b.src+=(b.src.indexOf("?")!=-1?"&":"?")+Math.random()),b.w3c||!a?d+=" data=\""+b.src+"\" type=\"application/x-shockwave-flash\"":d+=" classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\"",d+=">";if(b.w3c||a)d+="<param name=\"movie\" value=\""+b.src+"\" />";b.width=b.height=b.id=b.w3c=b.src=null,b.onFail=b.version=b.expressInstall=null;for(var e in b)b[e]&&(d+="<param name=\""+e+"\" value=\""+b[e]+"\" />");var g="";if(c){for(var i in c)if(c[i]){var j=c[i];g+=i+"="+encodeURIComponent(/function|object/.test(typeof j)?h.asString(j):j)+"&"}g=g.slice(0,-1),d+="<param name=\"flashvars\" value='"+g+"' />"}d+="</object>";return d},isSupported:function(a){return i[0]>a[0]||i[0]==a[0]&&i[1]>=a[1]}}),i=h.getVersion();function j(c,d,e){if(h.isSupported(d.version))c.innerHTML=h.getHTML(d,e);else if(d.expressInstall&&h.isSupported([6,65]))c.innerHTML=h.getHTML(f(d,{src:d.expressInstall}),{MMredirectURL:location.href,MMplayerType:"PlugIn",MMdoctitle:document.title});else{c.innerHTML.replace(/\s/g,"")||(c.innerHTML="<h2>Flash version "+d.version+" or greater is required</h2><h3>"+(i[0]>0?"Your version is "+i:"You have no flash plugin installed")+"</h3>"+(c.tagName=="A"?"<p>Click here to download latest version</p>":"<p>Download latest version from <a href='"+b+"'>here</a></p>"),c.tagName=="A"&&(c.onclick=function(){location.href=b}));if(d.onFail){var g=d.onFail.call(this);typeof g=="string"&&(c.innerHTML=g)}}a&&(window[d.id]=document.getElementById(d.id)),f(this,{getRoot:function(){return c},getOptions:function(){return d},getConf:function(){return e},getApi:function(){return c.firstChild}})}c&&(jQuery.tools=jQuery.tools||{version:"v1.2.6"},jQuery.tools.flashembed={conf:e},jQuery.fn.flashembed=function(a,b){return this.each(function(){jQuery(this).data("flashembed",flashembed(this,a,b))})})})();
