/*
    anythingSlider v1.2
    
    By Chris Coyier: http://css-tricks.com
    with major improvements by Doug Neiner: http://pixelgraphics.us/
    based on work by Remy Sharp: http://jqueryfordesigners.com/


	To use the navigationFormatter function, you must have a function that
	accepts two paramaters, and returns a string of HTML text.
	
	index = integer index (1 based);
	panel = jQuery wrapped LI item this tab references
	@return = Must return a string of HTML/Text
	
	navigationFormatter: function(index, panel){
		return index + " Panel"; // This would have each tab with the text 'X Panel' where X = index
	}
*/

(function($){
	
    $.anythingSlider = function(el, options){
        // To avoid scope issues, use 'base' instead of 'this'
        // to reference this class from internal events and functions.
        var base = this;
        
        // Access to jQuery and DOM versions of element
        base.$el = $(el);
        base.el = el; 

		// Set up a few defaults
        base.currentPage = 1;
		base.timer = null;
		base.playing = false;

        // Add a reverse reference to the DOM object
        base.$el.data("AnythingSlider", base);
        
        base.init = function(){
            base.options = $.extend({},$.anythingSlider.defaults, options);
			
			// Cache existing DOM elements for later 
			base.$wrapper = base.$el.find('> div').css('overflow', 'hidden');
            base.$slider  = base.$wrapper.find('> ul');
            base.$items   = base.$slider.find('> li');
            base.$single  = base.$items.filter(':first');

			// Build the navigation if needed
			if(base.options.buildNavigation) base.buildNavigation();
        
        	// Get the details
            base.singleWidth = base.$single.outerWidth();
            base.pages = base.$items.length;

            // Top and tail the list with 'visible' number of items, top has the last section, and tail has the first
			// This supports the "infinite" scrolling
			base.$items.filter(':first').before(base.$items.filter(':last').clone().addClass('cloned'));
            base.$items.filter(':last' ).after(base.$items.filter(':first').clone().addClass('cloned'));

			// We just added two items, time to re-cache the list
            base.$items = base.$slider.find('> li'); // reselect
            
			// Setup our forward/backward navigation
			base.buildNextBackButtons();
		
			// If autoPlay functionality is included, then initialize the settings
			if(base.options.autoPlay) {
				base.playing = !base.options.startStopped; // Sets the playing variable to false if startStopped is true
				base.buildAutoPlay();
			};
			
			// If pauseOnHover then add hover effects
			if(base.options.pauseOnHover) {
				base.$el.hover(function(){
					base.clearTimer();
				}, function(){
					base.startStop(base.playing);
				});
			}
			
			// If a hash can not be used to trigger the plugin, then go to page 1
			if((base.options.hashTags == true && !base.gotoHash()) || base.options.hashTags == false){
				// // Next line is buggy. The first played media runs fine
				// // but got covered by the image from the last element :P
				// base.setCurrentPage(base.options.startPage);
				base.gotoPage(base.options.startPage);
			};
        };
		
		base.goForward = function(autoplay){
			if(autoplay !== true) autoplay = false;
			base.gotoPage(base.currentPage + 1, autoplay);
		};
		
		base.goBack = function(){
		 	base.gotoPage(base.currentPage - 1);
		};
		
		// This method tries to find a hash that matches panel-X
		// If found, it tries to find a matching item
		// If that is found as well, then that item starts visible
		base.gotoHash = function(){
			if(/^#?panel-\d+$/.test(window.location.hash)){
				var index = parseInt(window.location.hash.substr(7));
				var $item = base.$items.filter(':eq(' + index + ')');
				if($item.length != 0){
					base.setCurrentPage(index);
					return true;
				};
			};
			return false; // A item wasn't found;
		};

		base.gotoPage = function(page, autoplay){
			// When autoplay isn't passed, we stop the timer
			if(autoplay !== true) autoplay = false;
			if(!autoplay) base.startStop(false);
			
			if(typeof(page) == "undefined" || page == null) {
				page = 1;
				// base.setCurrentPage(1);
			};
			
			// Just check for bounds
			if(page > base.pages + 1) page = base.pages;
			if(page < 0 ) page = 1;

			var dir = page < base.currentPage ? -1 : 1,
                n = Math.abs(base.currentPage - page),
                left = base.singleWidth * dir * n;
			
			// // Clear player(s) before animation
			var currentTab = jQuery('#currentTab').val();
			if(currentTab=="video"){
				base.deathToAllPlayers(false);
			}
			
			base.$wrapper.filter(':not(:animated)').animate({
                scrollLeft : '+=' + left
            }, base.options.animationTime, base.options.easing, function () {
                var wrapperScrollLeft = base.singleWidth;
                if (page == 0) {
					page = base.pages;
                    wrapperScrollLeft = base.singleWidth * base.pages;
                } else if (page > base.pages) {
                    // reset back to start position
                    page = 1;
                }
                base.$wrapper.scrollLeft(wrapperScrollLeft);
				base.setCurrentPage(page);
            });
		};
		
		base.deathToAllPlayers = function(destroy){
			var players = ['#jquery_jplayer_1' , '#jquery_ajplayer_1', '#jquery_jplayer_hidden'];
			var player;
			for (i in players) {
				player = players[i];
				if (jQuery(player).length > 0) {
					jQuery(player).jPlayer('stop');
					jQuery(player).jPlayer('clearMedia');
					if (destroy) {
						jQuery(player).jPlayer('destroy');
					}
					// jQuery(player).remove();
				}
			}
			
			// // Remarking these 3 alleviates the jerkiness
			// $(".jp-video").remove();
			// $(".jp-audio").remove();
			// $(".jp-player").remove();
		};
	
		base.setCurrentPage = function(page, move){
			// Set visual
			if(base.options.buildNavigation){
				base.$nav.find('.cur').removeClass('cur');
				$(base.$navLinks[page - 1]).addClass('cur');	
			};
			
			// Only change left if move does not equal false
			if(move !== false) base.$wrapper.scrollLeft(base.singleWidth * page);

			// Update local variable
			base.currentPage = page;
			var sasit_temp_switch = base.$slider.find(".sasitsolution_currentSlide");
			sasit_temp_switch.find(".textSlide .jp-video").remove();
			sasit_temp_switch.find(".textSlide .jp-audio").remove();
			sasit_temp_switch.find(".textSlide .jp-player").remove();
			sasit_temp_switch.find(".textSlide img.photo").show();
			sasit_temp_switch.removeClass("sasitsolution_currentSlide");
			
			base.$items.filter(":eq("+page+")").addClass("sasitsolution_currentSlide");
			/******************* ADD HANDLE VIDEO PLAYER - SAS IT SOLUTION*******************/
			var currentTab = jQuery('#currentTab').val();
			if(currentTab=="video"){
				$("#videotab .sasitsolution_currentSlide>.textSlide img.photo").hide();
				
				//BOF Parse vidinfo
				
				var sasit_mtype,sasit_mp4path,sasit_ogvpath,sasit_posterpath,sasit_autoplay;
				var  sasit_minfo = $("#videotab .sasitsolution_currentSlide>.textSlide>.sasitsolution_mediainfo");
				//find type of media
				if(sasit_minfo.hasClass("sasitsolution_video"))
				{
					sasit_mtype = "video";
				}
				else
				{
					sasit_mtype = "audio";
				}
				//if video, get video info
				if(sasit_mtype=="video")
				{
					sasit_mp4path = sasit_minfo.find(">.sasitsolution_mp4path").attr("title");
					sasit_ogvpath = sasit_minfo.find(">.sasitsolution_ogvpath").attr("title");
					sasit_posterpath = sasit_minfo.find(">.sasitsolution_posterpath").attr("title");
				}
				else
				{
					sasit_mp4path = sasit_minfo.find(">.sasitsolution_mp4path").attr("title");
					sasit_posterpath = sasit_minfo.find(">.sasitsolution_posterpath").attr("title");
				}
				//Check autoplay
				if(sasit_minfo.hasClass("sasitsolution_autoplay"))
				{
					sasit_autoplay=true;
				}
				else
				{
					sasit_autoplay=false;
				}
				//EOF Parse vidinfo
				
				//SASITSOLUTION - Set up video or audio
				if(sasit_mtype=="video")
				{
					var jplayer_video_background_css = 'video_no_autoplay';
					if(sasit_autoplay==true) { 
						jplayer_video_background_css = 'video_with_autoplay'; 
					}

					$("#videotab .sasitsolution_currentSlide>.textSlide").append(
						"<div class='jp-video jp-video-270p'>"
							+"<div class='jp-type-single'>"
								+"<div id='jquery_jplayer_1' class='jp-jplayer " + jplayer_video_background_css + "'></div>"
								+"<div id='jp_interface_1' class='jp-interface'>"
									+"<div class='jp-video-play'></div>"
									+"<ul class='jp-controls'>"
										+"<li><a href='#' class='jp-play' tabindex='1'>play</a></li>"
										+"<li><a href='#' class='jp-pause' tabindex='1'>pause</a></li>"
										+"<li><a href='#' class='jp-mute' tabindex='1'>mute</a></li>"
										+"<li><a href='#' class='jp-unmute' tabindex='1'>unmute</a></li>"
									+"</ul>"
									+"<div class='jp-progress-container'>"
										+"<div class='jp-progress'>"
											+"<div class='jp-seek-bar'>"
												+"<div class='jp-play-bar'></div>"
											+"</div>"
										+"</div>"
									+"</div>"
									+"<div class='jp-volume-bar-container'>"
										+"<div class='jp-volume-bar'>"
											+"<div class='jp-volume-bar-value'></div>"
										+"</div>"
									+"</div>"
									+"<div class='jp-current-time'></div>"
									+"<div class='jp-duration'></div>"
								+"</div>"
							+"</div>"
						+"</div>");
						
						
						if(sasit_autoplay==true)
						{
							$("#jquery_jplayer_1").jPlayer({
								preload : 'auto',
								ready: function () {									
									// // START : Previously stable code
									/*
									$(this).jPlayer("setMedia", {
										m4v: sasit_mp4path,
										ogv: sasit_ogvpath,
										poster: sasit_posterpath
									}).jPlayer('play');
									*/
									// // END : Previously stable code
									
									// // START : Wait until fully loaded before playing.
									var _e = $(this);
									// var lastTime = 0; // intentional. not a bug :)
									var nameSpace = '.raygun';
									// // Timer which starts playback after media has fully loaded.
									var timer;

									// // Common function(s)
									var removeLoadingIndicator = function() {
										// // Remove loading indicator
										var transBG = _e.find('.loading');
										if (transBG.length > 0) {
											transBG.remove();
													
											// // Dim up the poster
											_e.find('img').css({
												// '-ms-filter' : 'progid:DXImageTransform.Microsoft.Alpha(Opacity=30)', 
												'filter':'alpha(opacity = 100)',
												'opacity':'1.0',
												'zoom':'1'
											});
										}
									};

									// // When media loading starts, initiate the
									// // timer which checks if download is complete.
									_e.bind($.jPlayer.event.loadstart + nameSpace, function(event) {
										// lastTime = -1; // intentional. not a bug :)
										// _e.jPlayer('pause');
										_e.data('lastTime', -1);
										
										/*
										// // Dim down the poster
										_e.find('img').css({
											// '-ms-filter' : 'progid:DXImageTransform.Microsoft.Alpha(Opacity=30)', 
											'filter':'alpha(opacity = 30)',
											'opacity':'0.3',
											'zoom':'1'
										});
										*/
										
										// // Display loading indicator
										var loadingDiv = jQuery('<div class="loading"><img src="assets/ajax-loader-transparent.gif" /></div>');
										loadingDiv.css({
											position:'absolute',
											top: (_e.height() - 24)/2,
											left: (_e.width() - 24)/2,
											zIndex:_e.css('zIndex') + 1,
											width:'24px',
											height:'24px'
										});
										loadingDiv.appendTo(_e);
										
										timer = setInterval(function(){
											var lastTime = _e.data('lastTime');
											if (lastTime == -1) {
												// _e.jPlayer('pause');
												return;
											}
											
											var nowTime = 
												new Date().getTime();
												// Date.now(); // no go in IE8 & lower
											var diffTime = nowTime - lastTime;
											if ($.browser.mozilla) {
												console.log('diffTime ' + diffTime);
											}

											// // If there has been some time when no
											// // download was detected, play the media.
											if (diffTime > 1666) {
												clearInterval(timer); // clear the interval
												_e.unbind($.jPlayer.event.loadstart + nameSpace);
												_e.unbind($.jPlayer.event.progress + nameSpace);
												_e.unbind($.jPlayer.event.play + nameSpace);

												// // Remove loading indicator
												removeLoadingIndicator();

											   _e.jPlayer('play');
											} else if (isNaN(diffTime)) {
												// // If the value is absurd, that means we are out of scope.
											   clearInterval(timer); // clear the interval
											}
										},1000);
									});
									
									// // Record the last time a download was detected.
									_e.bind($.jPlayer.event.progress + nameSpace, function(event) {
										var lastTime =
											new Date().getTime();
											// Date.now(); // no go in IE8 & lower
										_e.data('lastTime', lastTime);
										if ($.browser.mozilla) {
											console.log('downloading video ... ' + lastTime);
										}
									});

									// // Clean up work in case there was any action 
									// // before the media was fully loaded.
									_e.bind($.jPlayer.event.play + nameSpace, function(event) {
										// // Remove loading indicator
										removeLoadingIndicator();

										// // clear the interval
										clearInterval(timer);
									});

									// // Load media after bindings been declared. 
									// // Can be done earlier too as most browsers don't complaint.
									$(this).jPlayer("setMedia", {
										m4v: sasit_mp4path,
										ogv: sasit_ogvpath,
										poster: sasit_posterpath
									});
									$(this).jPlayer('load');
									// // END : Wait until fully loaded before playing.
									
								},
								ended: function (event) {},
								swfPath: "js",
								supplied: "ogv,m4v"
							});
							
							// setTimeout(function(){$("#jquery_jplayer_1").jPlayer("play");},1000);
						}
						else
						{
							$("#jquery_jplayer_1").jPlayer({
								ready: function () {
									
									// // Tip : If browssr is safari or IE, keep it simple ?
									
									// // START : manual init
									var _e = $(this);
									// var lastTime = 0; // intentional. not a bug :)
									var nameSpace = '.raygun';
									// // Timer which starts playback after media has fully loaded.
									var timer;

									// // Common function(s)
									var removeLoadingIndicator = function() {
										// // Remove loading indicator
										// var loadingDiv = _e.find('.loading');
										var loadingDiv = jQuery('#loadingDiv');
										if (loadingDiv.length > 0) {
											loadingDiv.remove();
										}
									};

									var addLoadingIndicator = function() {
									// if ($.browser.safari || $.browser.webkit) {
										
										if (jQuery('#loadingDiv', _e).length > 0) {
											return;
										}

										// // Black background
										var loadingDiv = jQuery('<div id="loadingDiv"></div>');
										loadingDiv.css({
											position:'absolute',
											top: 0,
											left: 0,
											// zIndex:_e.css('zIndex') + 1,
											zIndex:9900 + 1,
											backgroundColor:'#000000',
											width:'100%',
											height:'100%'
										});
										
										// // Get or clone the dimmed poster behind the loading indicator
										var firstImage = _e.find('img:first');
										var backgroundImage = firstImage.clone();
										backgroundImage.css({
											position:'absolute',
											top: 0,
											left: 0,
											// zIndex:_e.css('zIndex') + 2,
											zIndex:9900 + 2,
											// '-ms-filter' : 'progid:DXImageTransform.Microsoft.Alpha(Opacity=30)', 
											'filter':'alpha(opacity = 30)',
											'opacity':'0.3',
											'zoom':'1',
											'display': 'block'
										});

										// // Display loading indicator
										var indicatorGif = jQuery('<div class="loading"><img src="assets/ajax-loader-transparent.gif" /></div>');
										indicatorGif.css({
											position:'absolute',
											top: (_e.height() - 24)/2,
											left: (_e.width() - 24)/2,
											// zIndex:_e.css('zIndex') + 3,
											zIndex:9900 + 3,
											width:'24px',
											height:'24px'
										});

										loadingDiv.append(backgroundImage);
										loadingDiv.append(indicatorGif);
										loadingDiv.appendTo(_e);										
									};
										
									// // When media loading starts, initiate the
									// // timer which checks if download is complete.
									_e.bind($.jPlayer.event.loadstart + nameSpace, function(event) {
										// lastTime = -1; // intentional. not a bug :)
										// _e.jPlayer('pause');
										_e.data('lastTime', -1);
										
										// if (!($.browser.safari || $.browser.webkit)) {}
										
										addLoadingIndicator();
										
										timer = setInterval(function(){
											var lastTime = _e.data('lastTime');
											if (lastTime == -1) {
												return;
											}
											
											// // Brute force pause :D
											_e.jPlayer('pause');
											
											var nowTime = 
												new Date().getTime();
												// Date.now(); // no go in IE8 & lower
											var diffTime = nowTime - lastTime;
											if ($.browser.mozilla) {
												console.log('diffTime ' + diffTime);
											}

											// // If there has been some time when no
											// // download was detected, play the media.
											if (diffTime > 1666) {
												clearInterval(timer); // clear the interval
												_e.unbind($.jPlayer.event.loadstart + nameSpace);
												_e.unbind($.jPlayer.event.progress + nameSpace);
												_e.unbind($.jPlayer.event.play + nameSpace);

												// // Remove loading indicator
												removeLoadingIndicator();

												_e.data('loaded', true);
												
											   _e.jPlayer('play');
											} else if (isNaN(diffTime)) {
												// // If the value is absurd, that means we are out of scope.
											   clearInterval(timer); // clear the interval
											}
										},1000);
									});
									
									// // Record the last time a download was detected.
									_e.bind($.jPlayer.event.progress + nameSpace, function(event) {
										var lastTime =
											new Date().getTime();
											// Date.now(); // no go in IE8 & lower
										_e.data('lastTime', lastTime);
										if ($.browser.mozilla) {
											console.log('downloading video ... ' + lastTime);
										}
									});
									
									// // Clean up work in case there was any action 
									// // before the media was fully loaded.
									_e.bind($.jPlayer.event.play + nameSpace, function(event) {
										// // Remove loading indicator
										// removeLoadingIndicator();

										// // clear the interval
										// clearInterval(timer);
										
										if (_e.data('loaded') != true) {
											_e.jPlayer('pause');
										}
									});
									// // END : manual init

									$(this).jPlayer("setMedia", {
										m4v: sasit_mp4path,
										ogv: sasit_ogvpath,
										poster: sasit_posterpath
									});
								},
								ended: function (event) {},
								swfPath: "js",
								supplied: "ogv,m4v",
								// solution: "flash,html",
								// wmode: "opaque",
								preload: "none"
							});
						}
				}
				else if(sasit_mtype=="audio")
				{
					var jplayer_audio_background_css = 'jplayer_audio_background_no_autoplay';
					if(sasit_autoplay==true) { 
						jplayer_audio_background_css = 'jplayer_audio_background_with_autoplay';
					}
					
					$("#videotab .sasitsolution_currentSlide>.textSlide").append(
						"<div class='jp-audio'>"
						+"<div id='jquery_ajplayer_1' class='jp-jplayer'></div>"
							+"<div id='jplayer_audio_background' class='" + jplayer_audio_background_css + "'><img src='"+sasit_posterpath+"'/></div>"
							+"<div class='jp-type-single'>"
								+"<div id='jp_interface_1' class='jp-interface'>"
									+"<ul class='jp-controls'>"
										+"<li><a href='#' class='jp-play' tabindex='1'>play</a></li>"
										+"<li><a href='#' class='jp-pause' tabindex='1'>pause</a></li>"
										+"<li><a href='#' class='jp-mute' tabindex='1'>mute</a></li>"
										+"<li><a href='#' class='jp-unmute' tabindex='1'>unmute</a></li>"
									+"</ul>"
									+"<div class='jp-progress-container'>"
										+"<div class='jp-progress'>"
											+"<div class='jp-seek-bar'>"
												+"<div class='jp-play-bar'></div>"
											+"</div>"
										+"</div>"
									+"</div>"
									+"<div class='jp-volume-bar-container'>"
										+"<div class='jp-volume-bar'>"
											+"<div class='jp-volume-bar-value'></div>"
										+"</div>"
									+"</div>"
									+"<div class='jp-current-time'></div>"
									+"<div class='jp-duration'></div>"
								+"</div>"
							+"</div>"
						+"</div>");
						
						
						if(sasit_autoplay==true)
						{
							$("#jquery_ajplayer_1").jPlayer({
								ready: function () {
									// // START : Previously stable code
									/*
									$(this).jPlayer("setMedia", {
										// poster: sasit_posterpath,
										mp3: sasit_mp4path
									}).jPlayer("play");
									*/
									// // END : Previously stable code
									
									// // START : Wait until fully loaded before playing.
									var _e = $(this);
									var _p = $('#jplayer_audio_background', $(this).parent());
									var _i = _p.find('img');
									var nameSpace = '.raygun';
									// // Timer which starts playback after media has fully loaded.
									var timer;

									// // Common function(s)
									var removeLoadingIndicator = function() {
										// // Remove loading indicator
										var transBG = _p.find('.loading');
										if (transBG.length > 0) {
											transBG.remove();
											
											// // Dim up the poster
											_i.css({
												// '-ms-filter' : 'progid:DXImageTransform.Microsoft.Alpha(Opacity=30)', 
												'filter':'alpha(opacity = 100)',
												'opacity':'1.0',
												'zoom':'1'
											});
										}
									};

									// // When media loading starts, initiate the
									// // timer which checks if download is complete.
									_e.bind($.jPlayer.event.loadstart + nameSpace, function(event) {
										_e.data('lastTime', -1);
										
										/*
										// // Dim down the poster
										_i.css({
											// '-ms-filter' : 'progid:DXImageTransform.Microsoft.Alpha(Opacity=30)', 
											'filter':'alpha(opacity = 30)',
											'opacity':'0.3',
											'zoom':'1'
										});
										*/
										
										// // Display loading indicator within the poster
										var loadingDiv = jQuery('<div class="loading"><img src="assets/ajax-loader-transparent.gif" /></div>');
										loadingDiv.css({
											position:'absolute',
											marginTop:parseInt(_i.css('marginTop'), 10)/2,
											top: (_p.height() - 24)/2,
											left: (_p.width() - 24)/2,
											zIndex:_p.css('zIndex') + 1,
											width:'24px',
											height:'24px'
										});
										loadingDiv.appendTo(_p);
										
										timer = setInterval(function(){
											var lastTime = _e.data('lastTime');
											if (lastTime == -1) {
												return;
											}
											
											var nowTime =
												new Date().getTime();
												// Date.now(); // no go in IE8 & lower
											var diffTime = nowTime - lastTime;
											if ($.browser.mozilla) {
												console.log('diffTime ' + diffTime);
											}

											if (diffTime > 1666) {
												clearInterval(timer);
												_e.unbind($.jPlayer.event.loadstart + nameSpace);
												_e.unbind($.jPlayer.event.progress + nameSpace);
												_e.unbind($.jPlayer.event.play + nameSpace);

												// // Remove loading indicator
												removeLoadingIndicator();

											   _e.jPlayer('play');
											} else if (isNaN(diffTime)) {
											   clearInterval(timer);
											}
										},1000);
									});
									
									// // Record the last time a download was detected.
									_e.bind($.jPlayer.event.progress + nameSpace, function(event) {
										var lastTime =
											new Date().getTime();
											// Date.now(); // no go in IE8 & lower
										_e.data('lastTime', lastTime);
										if ($.browser.mozilla) {
											console.log('downloading audio ... ' + lastTime);
										}
									});

									// // Clean up work in case there was any action 
									// // before the media was fully loaded.
									_e.bind($.jPlayer.event.play + nameSpace, function(event) {
										// // Remove loading indicator
										removeLoadingIndicator();

										// // Clear the interval
										clearInterval(timer); 
									});

									// // Load media after bindings been declared. 
									// // Can be done earlier too as most browsers don't complaint.
									$(this).jPlayer("setMedia", {
										// poster: sasit_posterpath,
										mp3: sasit_mp4path
									});
									$(this).jPlayer('load');
									// // END : Wait until fully loaded before playing.
									
								},
								ended: function (event) {},
								swfPath: "js",
								supplied: "mp3"
							});
						}
						else
						{
							$("#jquery_ajplayer_1").jPlayer({
								ready: function () {

									// // START : manual init
									var _e = $(this);
									var _p = $('#jplayer_audio_background', $(this).parent());
									var _i = _p.find('img');
									var nameSpace = '.raygun';
									// // Timer which starts playback after media has fully loaded.
									var timer;

									// // Common function(s)
									var removeLoadingIndicator = function() {
										// // Remove loading indicator
										var transBG = _p.find('.loading');
										if (transBG.length > 0) {
											transBG.remove();

											// // Dim up the poster
											_i.css({
												// '-ms-filter' : 'progid:DXImageTransform.Microsoft.Alpha(Opacity=30)', 
												'filter':'alpha(opacity = 100)',
												'opacity':'1.0',
												'zoom':'1'
											});
										}
									};

									// // When media loading starts, initiate the
									// // timer which checks if download is complete.
									_e.bind($.jPlayer.event.loadstart + nameSpace, function(event) {
										_e.data('lastTime', -1);
										
										// // Dim down the poster
										_i.css({
											// '-ms-filter' : 'progid:DXImageTransform.Microsoft.Alpha(Opacity=30)', 
											'filter':'alpha(opacity = 30)',
											'opacity':'0.3',
											'zoom':'1'
										});
										
										// // Display loading indicator within the poster
										var loadingDiv = jQuery('<div class="loading"><img src="assets/ajax-loader-transparent.gif" /></div>');
										loadingDiv.css({
											position:'absolute',
											marginTop:parseInt(_i.css('marginTop'), 10)/2,
											top: (_p.height() - 24)/2,
											left: (_p.width() - 24)/2,
											zIndex:_p.css('zIndex') + 1,
											width:'24px',
											height:'24px'
										});
										loadingDiv.appendTo(_p);
										
										timer = setInterval(function(){
											var lastTime = _e.data('lastTime');
											if (lastTime == -1) {
												return;
											}
											
											var nowTime =
												new Date().getTime();
												// Date.now(); // no go in IE8 & lower
											var diffTime = nowTime - lastTime;
											if ($.browser.mozilla) {
												console.log('diffTime ' + diffTime);
											}

											if (diffTime > 1666) {
												clearInterval(timer);
												_e.unbind($.jPlayer.event.loadstart + nameSpace);
												_e.unbind($.jPlayer.event.progress + nameSpace);
												_e.unbind($.jPlayer.event.play + nameSpace);

												// // Remove loading indicator
												removeLoadingIndicator();

											   _e.jPlayer('play');
											} else if (isNaN(diffTime)) {
											   clearInterval(timer);
											}
										},1000);
									});
									
									// // Record the last time a download was detected.
									_e.bind($.jPlayer.event.progress + nameSpace, function(event) {
										var lastTime =
											new Date().getTime();
											// Date.now(); // no go in IE8 & lower
										_e.data('lastTime', lastTime);
										if ($.browser.mozilla) {
											console.log('downloading audio ... ' + lastTime);
										}
									});

									// // Clean up work in case there was any action 
									// // before the media was fully loaded.
									_e.bind($.jPlayer.event.play + nameSpace, function(event) {
										// // Remove loading indicator
										// removeLoadingIndicator();

										// // Clear the interval
										// clearInterval(timer); 
										
									   _e.jPlayer('pause');
									   
									   // // Display the pause button ? Maybe not ...
									   // $('ul li a:first','#jp_interface_1').removeClass('jp-play');
									   // $('ul li a:first','#jp_interface_1').addClass('jp-pause');
									});
									// // END : manual init

									$(this).jPlayer("setMedia", {
										// poster: sasit_posterpath,
										mp3: sasit_mp4path
									});
								},
								ended: function (event) {},
								swfPath: "js",
								supplied: "mp3",
								preload: "none"
							});
						}
				}
            }
            
			/******************* EOF VIDEO PLAYER *************************/
		};
        
		// Creates the numbered navigation links
		base.buildNavigation = function(){
			base.$nav = $("<div id='thumbCaption'></div>").appendTo(base.$el);
			base.$nav = $("<div id='thumbNav'></div>").appendTo(base.$el);
			base.$holder = $("<div id='holder'></div>").appendTo(base.$nav); 
			base.$length = base.$items.length;			
			base.$items.each(function(i,el){
			
				var index = i + 1;
				if(index == 1) {
					var $a = $("<a id='first' href='#'></a>");
				} else if(index == base.$length) {
					var $a = $("<a id='last' href='#'></a>");
				} else {
					var $a = $("<a href='#'></a>");
				}
				// If a formatter function is present, use it
				if( typeof(base.options.navigationFormatter) == "function"){
					if ($(this).children().children('img.photo').attr('src') == undefined) {
						$a.html("<img class='slideThumb' src="+base.options.defaultThumb+" alt="+base.options.navigationFormatter(index, $(this))+" title='undefined'/>");
					} else {  
						$a.html("<img class='slideThumb' src="+$(this).children().children('img.photo').attr('src')+" alt='"+$(this).children().children('img.photo').attr('alt')+"' title='"+$(this).children().children('img.photo').attr('alt')+"' />");
					}
				} else { 
					$a.text(index);
				}
				$a.click(function(e){
					// // Copy the current page index before it gets updated
					var oldIndex = base.currentPage;
					
                    base.gotoPage(index);
                    
					var dir = index < oldIndex ? -1 : 1;
					if (dir == -1) {
						// // Remove visual artifacts for specific browsers.
						// // Video tab does not need this as its artifacts will
						// // eventually be gone once the media players are created.
						var affectedVersions = ['7.0.1', '9.0.1'];
						if (($.browser.mozilla) && (affectedVersions.indexOf($.browser.version) != -1)) {
							// $("#imagetab #holder:not(:animated)").animate({"marginLeft": "-=1px"}, "fast", null, function(){
							$("#imagetab #holder:last").animate({"marginRight": "-=1px"}, "fast", null, function(){
								$("#imagetab #holder:last").animate(
									{
										"marginRight" : "+=1px"
									}, 
									"fast" 
								)
							});
						}
					}
                    
                    if (base.options.hashTags)
						base.setHash('panel-' + index);
						
                    e.preventDefault();
				});
				base.$holder.append($a); 

			});
			base.$navLinks = base.$holder.find('> a');
		};
		
		
		// Creates the Forward/Backward buttons
		base.buildNextBackButtons = function(){
			var $forward = $('<a id="arrowForward" class="arrow forward"><img id="forwardImage" src="assets/arrow-right.png" /></a>'),
				$back = $('<a id="arrowBack" class="arrow back"><img id="backImage" src="assets/arrow-left.png" /></a>');

			// // IE8 & below has limitations which impede them from supporting the opacity animation on the navigational arrows
			// if ($.browser.msie && $.browser.version.substr(0,1)<9) {

			// $('#backImage').hover(function(){
			$back.hover(function(){
				$('img', this).animate({"opacity":"1"},200)
			},function(){
				$('img', this).animate({"opacity":"0.2"},200)
			});
			
			// $('#forwardImage').hover(function(){
			$forward.hover(function(){
				$('img', this).animate({"opacity":"1"},200)
			},function(){
				$('img', this).animate({"opacity":"0.2"},200)
			});
			
			/*
			var $forward = $('<a id="arrowForward" class="arrow forward">&gt;</a>'),
				$back = $('<a id="arrowBack" class="arrow back">&lt;</a>');


			// // Does not work in IE8
			var defaultArrowCss = {
				// 'background-color' : '#000000',
				// // Standards Compliant Browser
				'opacity' : '0.2',
				// // IE 7 and Earlier
				'filter' : 'alpha(opacity=20)'
				// // Next 2 lines IE8
				// '-ms-filter' : '"progid:DXImageTransform.Microsoft.Alpha(Opacity=20)"',
				// 'filter' : 'progid:DXImageTransform.Microsoft.Alpha(Opacity=20)'		
			};	
			
			var hoverArrowCss = {
				// 'background-color' : '#000000',
				// // Standards Compliant Browser
				'opacity' : '1',
				// // IE 7 and Earlier
				'filter' : 'alpha(opacity=100)'
				// // Next 2 lines IE8
				// '-ms-filter' : '"progid:DXImageTransform.Microsoft.Alpha(Opacity=100)"',
				// 'filter' : 'progid:DXImageTransform.Microsoft.Alpha(Opacity=100)'		
			};

			$forward.css(defaultArrowCss);
			$back.css(defaultArrowCss);
			*/
			
			
            // Bind to the forward and back buttons
            $back.click(function(e){
				base.goBack(false);
            	var element = $("a#first");
            	var position = element.position();
				//work out if the first element is past the yard arm
				var currentTab = jQuery('#currentTab').val();
				if(currentTab=="images")
				{
					// // Remove visual artifacts for specific browsers.
					// // Video tab does not need this as its artifacts will
					// // eventually be gone once the media players are created.
					var removeVisualArtifact = function() {
						var affectedVersions = ['7.0.1', '9.0.1'];
						if (($.browser.mozilla) && (affectedVersions.indexOf($.browser.version) != -1)) {
							// $("#imagetab #holder:not(:animated)").animate({"marginLeft": "-=1px"}, "fast", null, function(){
							$("#imagetab #holder:last").animate({"marginRight": "-=1px"}, "fast", null, function(){
								$("#imagetab #holder:last").animate(
									{
										"marginRight" : "+=1px"
									}, 
									"fast" 
								)
							});
						}
					};
						
					if($("#imagetab #holder a#first").hasClass("cur"))
					{
						var visibleThumbCount = 6;
						var thumbCount = $("#imagetab #holder>a").size();
						if (thumbCount < visibleThumbCount + 1) {
							removeVisualArtifact();
						} else {
							var mm = "-"+((thumbCount - visibleThumbCount)*91)+"px";
							$("#imagetab #holder:not(:animated)").animate({"marginLeft": mm}, "slow");
						}
						
						// var mm = "-"+(($("#imagetab #holder>a").size()-6)*91)+"px";
						// $("#imagetab #holder:not(:animated)").animate({"marginLeft": mm}, "slow");
					}
					else if(position.left < 0) {
						$("#imagetab #holder:not(:animated)").animate({"marginLeft": "+=91px"}, "slow");
					} else {
						removeVisualArtifact();
					}
				}
				else
				{
					if($("#videotab #holder a#first").hasClass("cur"))
					{
						var mm = "-"+(($("#videotab #holder>a").size()-5)*91)+"px";
						$("#videotab #holder:not(:animated)").animate({"marginLeft": mm}, "slow");
					}
					else if(position.left < 0) {
						$("#videotab #holder:not(:animated)").animate({"marginLeft": "+=91px"}, "slow");
					}
				}
            });
			
            $forward.click(function(e){
				base.goForward(false);
				var element = $("a#last");
            	var position = element.position();	
				//work out if the last element is past the yard elbow
				var currentTab = jQuery('#currentTab').val();
				if(currentTab=="images")
				{
					if($("#imagetab #holder a#last").hasClass("cur"))
					{
						$("#imagetab #holder:not(:animated)").animate({"marginLeft": "0px"}, "slow");
					}
					else if(position.left >= 540) {
						$("#imagetab #holder:not(:animated)").animate({"marginLeft": "-=91px"}, "slow");
					}
				}
				else
				{
					if($("#videotab #holder a#last").hasClass("cur"))
					{
						$("#videotab #holder:not(:animated)").animate({"marginLeft": "0px"}, "slow");
					}
					else if(position.left >= 450) {
						$("#videotab #holder:not(:animated)").animate({"marginLeft": "-=91px"}, "slow");
					}
				}
            });

			// // Append elements to page
			// base.$wrapper.after($back).after($forward);
			base.$el.append($back).append($forward);
		};

		// Creates the Start/Stop button
		base.buildAutoPlay = function(){

			base.$startStop = $("<a href='#' id='start-stop'></a>").html(base.playing ? base.options.stopText :  base.options.startText);
			base.$el.append(base.$startStop);            
            base.$startStop.click(function(e){
				base.startStop(!base.playing);
				e.preventDefault();
            });

			// Use the same setting, but trigger the start;
			base.startStop(base.playing);
		};
		
		// Handles stopping and playing the slideshow
		// Pass startStop(false) to stop and startStop(true) to play
		base.startStop = function(playing){
			if(playing !== true) playing = false; // Default if not supplied is false
			
			// Update variable
			base.playing = playing;
			
			// Toggle playing and text
			if(base.options.autoPlay) base.$startStop.toggleClass("playing", playing).html( playing ? base.options.stopText : base.options.startText );
			
			if(playing){
				base.clearTimer(); // Just in case this was triggered twice in a row
				base.timer = window.setInterval(function(){
					base.goForward(true);
				}, base.options.delay);
			} else {
				base.clearTimer();
			};
		};
		
		base.clearTimer = function(){
			// Clear the timer only if it is set
			if(base.timer) window.clearInterval(base.timer);
		};
		
		// Taken from AJAXY jquery.history Plugin
		base.setHash = function ( hash ) {
			// Write hash
			if ( typeof window.location.hash !== 'undefined' ) {
				if ( window.location.hash !== hash ) {
					window.location.hash = hash;
				};
			} else if ( location.hash !== hash ) {
				location.hash = hash;
			};
			
			// Done
			return hash;
		};
		// <-- End AJAXY code


		// Trigger the initialization
        base.init();
    };

	
    $.anythingSlider.defaults = {
        easing: "swing",                // Anything other than "linear" or "swing" requires the easing plugin
        autoPlay: true,                 // This turns off the entire FUNCTIONALY, not just if it starts running or not
        startStopped: false,            // If autoPlay is on, this can force it to start stopped
        delay: 3000,                    // How long between slide transitions in AutoPlay mode
        animationTime: 600,             // How long the slide transition takes
        hashTags: true,                 // Should links change the hashtag in the URL?
        buildNavigation: true,          // If true, builds and list of anchor links to link to each slide
        pauseOnHover: true,             // If true, and autoPlay is enabled, the show will pause on hover
		startText: "Start",             // Start text
		stopText: "Stop",               // Stop text
		navigationFormatter: null,       // Details at the top of the file on this use (advanced use)
		defaultThumb: '',    //set the default thumbnail if no other are found
		startPage: 1
    };
	

    $.fn.anythingSlider = function(options){
		if(typeof(options) == "object"){
		    return this.each(function(i){			
				(new $.anythingSlider(this, options));

	            // This plugin supports multiple instances, but only one can support hash-tag support
				// This disables hash-tags on all items but the first one
				options.hashTags = false;
	        });	
		} else if (typeof(options) == "number") {

			return this.each(function(i){
				var anySlide = $(this).data('AnythingSlider');
				if(anySlide){
					anySlide.gotoPage(options);
				}
			});
		}
    };

	
})(jQuery);

