/**jQuery.noConflict();***/
jQuery(document).ready(function ($) {
   // Product Detail Specifications
	$('#Specifications').hide();
	$('.btn_SeeSpecifications').click(function () {
		$('#Specifications').show();
	});
	// tabs - where to buy
	$('.tab_content').hide();
	$('#tab1_content').show();
	$('.tabbed_nav a').click(function() {
		var id = $(this).parent('li').attr('id');
		$('.tab_content').hide();
		$(this).parent('li').siblings().removeClass('on');
		$(this).parent('li').addClass('on');
		$('#' + id + '_content').show();
		return false;
	});
	// Rotator
	var speed = 10000; // time between rotations
	var timer;
	function cycle(delay) {
		if (!delay) delay = 0;
		$('.rotator div.widget_content:last').fadeOut(delay, function () {
			$(this).remove().prependTo('.rotator').show();
			timer = setTimeout(function () {
				cycle(500);
			}, speed);
		});
	};
	timer = setTimeout(function () {
		cycle(500);
	}, speed);
	$('.rotator_nav a.next').live('click', function () {
		clearTimeout(timer);
		cycle(0);
		return false;
	});
	$('.rotator_nav a.prev').live('click', function () {
		clearTimeout(timer);
		$('.rotator div.widget_content:first').remove().appendTo('.rotator').fadeIn();
		timer = setTimeout(function () {
			cycle(500);
		}, speed);
		return false;
	});
});

(function( $ ) {
	
	var CURRENT_TABBODY_CLASS		= 'currentTabBody',
		CURRENT_TABLINK_CLASS		= 'currentTabLink',
		HAS_BCEXPERIENCE_CLASS		= 'hasBCPlayer';
		
	var urlParams = {},
		playertype,
		bcAPIavailable = true,
		settings,
		defaults = { 
			'playerID'				: '1398208656001',
			'playerKey'				: 'AQ~~,AAAAAEhanQU~,W-snzgQB-E-PRGHXlILi6r7B2K-cUoYZ',
/*			'playerID'				: '1375786155001',
			'playerKey'				: 'AQ~~,AAAAAEhanQU~,W-snzgQB-E8zEQeiRhHrPUwu30-c9Sdj', */
			'bgcolor'				: '#FFFFFF',
			'width'					: '798',
			'height'				: '603',
			'isVid'					: 'true',
			'isUI'					: 'true',
			'dynamicStreaming'		: 'true',
			'includeAPI'			: 'true',
			'wmode'					: 'transparent' };/*,
			'templateLoadHandler' : '$.fn.createBCPlayer.handlePlayerEvent',
			'templateReadyHandler' : '$.fn.createBCPlayer.handlePlayerEvent',
			'templateErrorHandler'	: '$.fn.createBCPlayer.handlePlayerEvent'					
		};*/

// http://www.masterlock.com/services_and_support/video_library.jsp?bcpid=1375786155001&bckey=AQ~~,AAAAAEhanQU~,W-snzgQB-E8zEQeiRhHrPUwu30-c9Sdj&bclid=1370633158001&bctid=18383259001
	var methods = {
		init : function( options ) {

			if ( typeof brightcove === "undefined" )
			{
				$.error( 'Brightcove API not available.' );
				return false;
			}
			
			methods.getURLParams();
			// if ( options.linkBaseURL !== null )
			
			if ( typeof options.linkBaseURL !== "undefined" ) { defaults.linkBaseURL = options.linkBaseURL; }
			
			return this.each( function() { 

				var flashVersion = 0;
				if ( typeof swfobject !== "undefined" )
				{
					var playerVersion = swfobject.getFlashPlayerVersion();
					flashVersion = playerVersion.major;
				}
				else $.error( 'SWFObject is not available.' ); 
				
				if ( flashVersion > 0 )
				{
					playertype = 'flash';
					var tabBody = document.createElement('div')
					tabBody.id = 'tab-'+options.flashPlayer.id;
					$(tabBody).addClass( CURRENT_TABBODY_CLASS ).addClass( 'video-tab' );;
					this.appendChild( tabBody )
					methods.createSinglePlayer( options.flashPlayer, tabBody, true );
				}
				else
				{
					playertype = 'html5';
					methods.createHTML5Players( options.html5Players, this );
				}
					
				$(this).append( '<div id="downloadLink"></div>' );
			});
		
		},
		createSinglePlayer : function( playerData, container, createExperience ) {
			settings = $.extend( defaults, playerData );
			
			var player = brightcove.createElement("object");
			player.id = 'player'+settings.id;
			
			var parameter
			$.each( settings, function( k, v ) {
				if ( (k == 'id') || (k == 'title') ) return true;
				parameter = brightcove.createElement('param');
				parameter.name = k;
				parameter.value = v;
				player.appendChild(parameter);
				
			});
			container.appendChild( player );
			
			if ( createExperience ) brightcove.createExperience( player, container, true );
		},
		createHTML5Players : function( playerData, container ) {
			var tabBody, tabItem, tabLink,
				createExperience,
				startIndex = methods.getStartIndex( playerData );
			var videoNav = document.createElement('ul');
			container.appendChild( videoNav );
			$.each( playerData, function( k, v ) {
				createExperience = false;
				tabItem = document.createElement( 'li' );
				tabLink = document.createElement( 'a' );
				$( tabLink ).bind( 'click.createBCPlayer', function() { return methods.changeTab( this ); } );
				tabLink.href = '#tab-'+v.id;
				tabLink.innerHTML = tabLink.title = v.title;
				tabItem.appendChild( tabLink );
				videoNav.appendChild( tabItem );
				tabBody = document.createElement('div');
				$( tabBody ).addClass( 'video-tab' );
				tabBody.id = 'tab-'+v.id;
				if ( k == startIndex )
				{
					createExperience = true;
					$(tabBody).addClass( CURRENT_TABBODY_CLASS ).addClass( HAS_BCEXPERIENCE_CLASS );
					$(tabLink).addClass( CURRENT_TABLINK_CLASS );
				}
				container.appendChild(tabBody);
				methods.createSinglePlayer( playerData[k], tabBody, createExperience );
			});
			
		},
		changeTab : function( evtTab ) {

			if ( evtTab.className.indexOf( CURRENT_TABLINK_CLASS )  >=0 ) return false;
			
			var divID = evtTab.href.split( '#' )[1];		
			var container = $( '#'+divID )[0];
			
			
			var player = $( 'object', container )[0];
			if ( container.className.indexOf( HAS_BCEXPERIENCE_CLASS ) < 0 )
			{
				$( container ).addClass( HAS_BCEXPERIENCE_CLASS );
				brightcove.createExperience( player, container, true );
			}

			var playerID = $('#brightCovePlayer .'+CURRENT_TABBODY_CLASS)[0].id.replace( 'tab-' , 'player' );
			if ( typeof bcAPI[playerID] !== 'undefined' ) bcAPI[playerID].BCLvideoPlayer.pause( true );
			
			$( '#brightCovePlayer .'+CURRENT_TABBODY_CLASS ).removeClass( CURRENT_TABBODY_CLASS );
			$( '#brightCovePlayer .'+CURRENT_TABLINK_CLASS ).removeClass( CURRENT_TABLINK_CLASS );
			$( container ).addClass( CURRENT_TABBODY_CLASS );
			$( evtTab ).addClass( CURRENT_TABLINK_CLASS );
			
			
			return false;
		},
		getDownloadLink : function( id ) {
			// object for search parameters
			var searchParams = new Object();
			// set Media API token - MUST BE URL ACCESS READ token!!
			BCMAPI.token = "22a0LNqORDivPDLtZN6x3NptD1ZvLBB5CBmiZ8DxsMA.";
			// set callback for Media API call
			BCMAPI.callback = "$.fn.createBCPlayer.onSearchResult";
			// set command
			BCMAPI.command = "find_video_by_id";
			// set search params
			searchParams.video_id = id;
			// need this if the delivery for the account is streaming, and Universal Delivery Service must be enabled!
			searchParams.media_delivery = "HTTP";
			// just get the field we need for better performance
			searchParams.video_fields = "FLVURL";
			// execute the search
			BCMAPI.find(BCMAPI.command,searchParams);
		},
		updateShareLink : function( playerID, videoId, playlistId ) {
			// Brightcove players published using the standard JavaScript publishing code 
			// automatically listen for bclid and bctid in order to select featured items. 
			// If your application is setup in another format, such as ActionScript, you can
			// choose to alter these key names to something compatible with your application.
			// Your application will be responsible for properly setting the featured content.
		 
			var playlistKey = "bclid",
				videoKey = "bctid";
		 
			var currentLink = bcAPI[playerID].BCLsocial.getLink();
		 
			// Get the current URL and remove any existing URL parameter
			if(currentLink.indexOf("?") != -1) {
				currentLink = currentLink.substring(0,currentLink.indexOf("?"));
			}
		 
			var newLink = currentLink + "?" + playlistKey + "=" + playlistId + "&"
			  + videoKey + "=" + videoId;
			bcAPI[playerID].BCLsocial.setLink(newLink);
		},
		getURLParams : function( ) {
			var e,
				a = /\+/g,  // Regex for replacing addition symbol with a space
				r = /([^&=]+)=?([^&]*)/g,
				d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
				q = window.location.search.substring(1);
		
			while (e = r.exec(q))
			   urlParams[d(e[1])] = d(e[2]);
		},
		getStartIndex : function( playerData ) {
			var i = 0,
				playlistFound = false;

			if ( urlParams.bclid === undefined ) return i;

			$.each( playerData, function( k , v ) {
				if ( urlParams.bclid == v['@playlistTabs'] ) {
					playlistFound = true;
					return false;
				}
				
				i++;
			} );
			return (playlistFound) ? i : 0;
		}
	};
	
	$.fn.createBCPlayer = function( method )
	{
		
		if ( methods[method] ) {
			return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
		} else if ( typeof method === 'object' || ! method ) {
			return methods.init.apply( this, arguments );
		} else {
			$.error( 'Method ' + method + ' does not exist on jQuery.createBCPlayer.' );
		}
			
	}
	
	$.fn.createBCPlayer.onSearchResult = function(jsondata) {
		// create the link and write it into the HTML
		var str = '<p><a class="link-download" href="'+jsondata.FLVURL+'">Download Video</a> <b>Right-click</b> on the &#8216;Download Video&#8217; link to save the video (MP4 format) to your computer.</p>';
		$("#downloadLink").css({'display':'block'}).html( str );
	}
	
	var bcAPI = new Object;
	
	$.fn.createBCPlayer.handlePlayerEvent = function( evt )
	{
		if ( !bcAPIavailable ) { return false; }
		
		if ( typeof evt === 'string' )
		{
			bcAPI[evt] = new Object;
			bcAPI[evt].BCLplayer = brightcove.getExperience(evt);
			if ( typeof bcAPI[evt].BCLplayer !== 'object' ) {
				bcAPIavailable = false;
				return false;	
			}
		}
		else if ( typeof evt === 'object' )
		{

			switch( evt.type )
			{
				case 'templateReady' :
					var playerID = $('#brightCovePlayer .'+CURRENT_TABBODY_CLASS)[0].id.replace( 'tab-' , 'player' );

					// get a reference to the various APIs
					bcAPI[playerID].BCLvideoPlayer = bcAPI[playerID].BCLplayer.getModule(APIModules.VIDEO_PLAYER);
					bcAPI[playerID].BCLsocial = bcAPI[playerID].BCLplayer.getModule(APIModules.SOCIAL);
					bcAPI[playerID].BCLexperienceModule = bcAPI[playerID].BCLplayer.getModule(APIModules.EXPERIENCE);
					bcAPI[playerID].BCLtabBar = bcAPI[playerID].BCLexperienceModule.getElementByID('playlistTabs');

					// add a listener for media change events
					bcAPI[playerID].BCLvideoPlayer.addEventListener(BCMediaEvent.BEGIN, $.fn.createBCPlayer.handlePlayerEvent);
					bcAPI[playerID].BCLvideoPlayer.addEventListener(BCMediaEvent.CHANGE, $.fn.createBCPlayer.handlePlayerEvent);
					// get the ID of the current video as it starts playing
					var BCLcurrentVideoID = bcAPI[playerID].BCLvideoPlayer.getCurrentVideo().id;
					// pass the video ID to getDownloadLink()
					methods.getDownloadLink( BCLcurrentVideoID );

					break;
				case 'mediaBegin' :
					var playerID = $('#brightCovePlayer .'+CURRENT_TABBODY_CLASS)[0].id.replace( 'tab-' , 'player' );
					var BCLcurrentVideoID = bcAPI[playerID].BCLvideoPlayer.getCurrentVideo().id;
					methods.getDownloadLink( BCLcurrentVideoID );
					break;
				case 'mediaChange' :
					if ( typeof settings.linkBaseURL === 'undefined' ) { break; }
					
					var playerID = $('#brightCovePlayer .'+CURRENT_TABBODY_CLASS)[0].id.replace( 'tab-' , 'player' );
					var BCLcurrentVideoID = bcAPI[playerID].BCLvideoPlayer.getCurrentVideo().id;
					var BCLcurrentTabID = bcAPI[playerID].BCLtabBar.getSelectedData().id;

					methods.updateShareLink( playerID, BCLcurrentVideoID, BCLcurrentTabID );
					
					break;
				default :
					break;	
			}
		}
		
	}
	
})( jQuery );
