// ============================================== //

		// TIMER FUNCTIONS //

// ============================================== //

jQuery.fn.extend({everyTime:function(interval,label,fn,times,belay){return this.each(function(){jQuery.timer.add(this,interval,label,fn,times,belay)})},oneTime:function(interval,label,fn){return this.each(function(){jQuery.timer.add(this,interval,label,fn,1)})},stopTime:function(label,fn){return this.each(function(){jQuery.timer.remove(this,label,fn)})}});jQuery.extend({timer:{guid:1,global:{},regex:/^([0-9]+)\s*(.*s)?$/,powers:{'ms':1,'cs':10,'ds':100,'s':1000,'das':10000,'hs':100000,'ks':1000000},timeParse:function(value){if(value==undefined||value==null)return null;var result=this.regex.exec(jQuery.trim(value.toString()));if(result[2]){var num=parseInt(result[1],10);var mult=this.powers[result[2]]||1;return num*mult}else{return value}},add:function(element,interval,label,fn,times,belay){var counter=0;if(jQuery.isFunction(label)){if(!times)times=fn;fn=label;label=interval}interval=jQuery.timer.timeParse(interval);if(typeof interval!='number'||isNaN(interval)||interval<=0)return;if(times&&times.constructor!=Number){belay=!!times;times=0}times=times||0;belay=belay||false;if(!element.$timers)element.$timers={};if(!element.$timers[label])element.$timers[label]={};fn.$timerID=fn.$timerID||this.guid++;var handler=function(){if(belay&&this.inProgress)return;this.inProgress=true;if((++counter>times&&times!==0)||fn.call(element,counter)===false)jQuery.timer.remove(element,label,fn);this.inProgress=false};handler.$timerID=fn.$timerID;if(!element.$timers[label][fn.$timerID])element.$timers[label][fn.$timerID]=window.setInterval(handler,interval);if(!this.global[label])this.global[label]=[];this.global[label].push(element)},remove:function(element,label,fn){var timers=element.$timers,ret;if(timers){if(!label){for(label in timers)this.remove(element,label,fn)}else if(timers[label]){if(fn){if(fn.$timerID){window.clearInterval(timers[label][fn.$timerID]);delete timers[label][fn.$timerID]}}else{for(var fn in timers[label]){window.clearInterval(timers[label][fn]);delete timers[label][fn]}}for(ret in timers[label])break;if(!ret){ret=null;delete timers[label]}}for(ret in timers)break;if(!ret)element.$timers=null}}}});if(jQuery.browser.msie)jQuery(window).one("unload",function(){var global=jQuery.timer.global;for(var label in global){var els=global[label],i=els.length;while(--i)jQuery.timer.remove(els[i],label)}});

// ============================================== //

		// SHUFFLE ARRAY FUNCTIONS //

// ============================================== //

(function($){
  $.fn.shuffle = function() {
    return this.each(function(){
      var items = $(this).children();
      return (items.length)
        ? $(this).html($.shuffle(items))
        : this;
    });
  }
 
  $.shuffle = function(arr) {
    for(
      var j, x, i = arr.length; i;
      j = parseInt(Math.random() * i),
      x = arr[--i], arr[i] = arr[j], arr[j] = x
    );
    return arr;
  }
})(jQuery);

// ============================================== //

		// IMAGE CAROUSEL //

// ============================================== //

(function($){
	$.fn.initCarousel = function() {
		var target = $(this);
		//
		var itemArray = [];
		var arrayItem = 0;
		var arrayLength = 0;
		var speed = 4000;
		var zDepth = 50;
		var prevItem = null;
		//
		var controlHtml = '<ul id="carousel_cont">';
		//
		target.find('ul:first li').each(function(i) {
			$(this).animate({ opacity: 0 }, 0.001, function(){
				$(this).css({ 'position' : 'absolute', 'top' : 0, 'left' : 0 });
				$(this).find('img').css({ 'display' : 'block'});
				$(this).find('h3').css({ 'display' : 'block'});
				$(this).find('p').css({ 'display' : 'block'});
			});
			controlHtml+= '<li><a href="#">'+$(this).find('h3').html()+'<\/a><\/li>';
			itemArray.push(i);
		});
		controlHtml+='<\/ul>';
		//
		arrayLength = itemArray.length;
		itemArray = $.shuffle(itemArray);
		//
		if (arrayLength>1){
			target.append(controlHtml);
		};
		//
		target.find('ul#carousel_cont').css({ 'z-index' : 1000});
		//
		revealImage = function(){
			zDepth++;
			target.find('ul#carousel_cont li.active').removeClass('active');
			target.find('ul#carousel_cont li').eq(arrayItem).addClass('active');
			currItem.css({ 'z-index' : zDepth}).animate({ opacity: 1 }, 500, function(){
				if(prevItem!==null){
					prevItem.animate({ opacity: 0 }, 0.001);
				}																  
			});
			//
			if (arrayLength>1){
				target.stopTime().oneTime(speed, function() {
					advanceImage();
				});
			};
		};
		//
		advanceImage = function(){
			prevItem = currItem;
			if(arrayItem<(arrayLength-1)){
				arrayItem++;
			}else{
				arrayItem = 0;
			}
			currItem = target.find('ul:first li').eq(itemArray[arrayItem]);
			revealImage();
		};
		// clicking functions
		target.find('ul#carousel_cont li').click(function(){
			var thisIndex = $("ul#carousel_cont li").index(this);
			//
			if(thisIndex!=arrayItem){
				currItem.stop();
				target.stopTime();
				arrayItem = thisIndex;
				prevItem = currItem;
				currItem = target.find('ul:first li').eq(itemArray[arrayItem]);
				revealImage();
			}
			return false;
		});
		//load first image
		var currItem = target.find('ul:first li').eq(itemArray[arrayItem]);
		var currImage = currItem.find('img').attr('src');
		var img = new Image();
		//
		$(img).load(function() {
			revealImage();
		}).attr('src', currImage);
		//
	}
})(jQuery);

// ============================================== //

		// BASE NAV ROLLOVERS //

// ============================================== //

(function($){
	$.fn.initBaseNav = function() {
		var target = $(this);
		target.find('li a').hover(function() {
			$(this).find('span').animate({'opacity':1},200);
		}, function() {
			$(this).find('span').animate({'opacity':0},300);
		}).find('span').animate({ opacity: 0 }, 0.001).show();
	}
})(jQuery);	

// ============================================== //

		// THUMB NAV COLOUR BOX //

// ============================================== //

(function($){
	$.fn.initThumbgrid = function() {
		var target = $(this);
		//
		var overHtml = '<div id="img_overlay"><img src="" width="700" height="394" \/><\/div>';
		$('#content_a').append(overHtml);
		//
		var setOffset = function(){
			var offset = $('#movie_wrapper').offset();
			$('#img_overlay').css({'left' : offset.left, 'top' : offset.top});
		};
		//
		$('#img_overlay').animate({'opacity':0},0.001, function(){
			$(this).show();
		});
		setOffset();
		//
		target.find('li a').each(function() {
			$(this).hover(function() {
				var thisPath = $(this).find('img').attr('src');
				$('#img_overlay').stop().show().animate({'opacity':0},0.001,function(){
					$(this).find('img').attr('src',thisPath).parent().animate({'opacity':1},200);
				});
			}, function() {
				$('#img_overlay').stop().animate({'opacity':0},300,function(){
					$(this).hide();															
				});
			}).click(function(){
				return false;
			});				  
		});
		//
		$(window).resize(function() {
  			setOffset();
		});
	};
})(jQuery);	

// ============================================== //

		// PHOTO GALLERY PAGE //

// ============================================== //

initGalleryPage = function(){
	var firstImg = $('#content_a ul:first li:first a').attr('href');
	var target = $('#gallery_main img');
	var visibleLi = 0;
	target.attr('src', firstImg);
	// set content UL
	$('#gallery_content li').each(function(i){
		if(i!=0){
			$(this).animate({'opacity':0},0.001);
		};
		$(this).css({'position':'absolute','top':0, 'left':0});
	});
	//
	//
	$('#content_a ul').each(function(i){
		$(this).data('ulpos',i);				 
		$(this).find('li').each(function(){
			$(this).find('a').click(function(){
				var tempIndex = $(this).parent().parent().data('ulpos');
				setGalleryImg($(this).attr('href'),tempIndex);
				//
				return false;
			});
		});
	});
	//
	setGalleryImg = function(thisTarget,textId){
		if(textId!=visibleLi){
			$('#gallery_content li').eq(visibleLi).animate({'opacity':0},200,function(){
				$('#gallery_content li').eq(textId).animate({'opacity':1},500);
				visibleLi=textId;
			});
		}
		//
		target.animate({'opacity':0},200,function(){
			$(this).attr('src', thisTarget).animate({'opacity':1},300)
		});
	};
};


// ============================================== //

		// WORK PAGE PLAYER //

// ============================================== //

initWorkPlayer = function(){
	var target = $('#player');
	var imagePath = target.find('img').attr('src');
	var moviePath = target.attr('href');
	target.html('');
	setPlayer('player', imagePath, moviePath);
};


// ============================================== //

		// WORK PAGE SCROLL //

// ============================================== //

(function($){
	$.fn.initWorkScroll = function() {
		var target = $(this);
		var liTotal = target.find('ul li').length;
		//
		var liWidth = 178;
		var currentScroll = 0;
		var isScrolling = false;
		//
		target.find('ul').css({'width':liTotal*liWidth});
		//
		target.after('<div id="work_scroll_cont"><a id="prev" href="#" title="Previous">< <<\/a><a id="next" href="#" title="Next">> ><\/a><\/div>');
		//
		target.scrollLeft(0);
		//
		setButtons = function(){
			if(currentScroll==0){
				$('#prev').data('isActive', false).removeAttr('title').removeAttr('href').animate({'opacity':0.3},0.001);
			}
			if(currentScroll>0){
				$('#prev').data('isActive', true).attr('title','Previous').attr('href','#').animate({'opacity':1},0.001);
			}
			if((currentScroll+4)<liTotal){
				$('#next').data('isActive', true).attr('title','Next').attr('href','#').animate({'opacity':1},0.001);
			}
			if((currentScroll+4)==liTotal){
				$('#next').data('isActive', false).removeAttr('title').removeAttr('href').animate({'opacity':0.3},0.001);
			}
			//
		};
		//
		setButtons();
		//
		setHovers = function(thisTarget){
			thisTarget.hover(function() {
				if($(this).data('isActive')){
					$(this).css('cursor', 'pointer');
				};
			}, function() {
				$(this).css('cursor', 'default');
			});
		};
		//
		setHovers($('#next'));
		//
		//=============================================== NEXT //
		$('#next').click(function(event) {
			event.preventDefault();
		});
		
		$('#prev').click(function(event) {
			event.preventDefault();
		});
		
		$('#next').mousedown(function() {
			// bind mouseup outside
			var upHandler = function() {
				$(document).unbind("mouseup", upHandler);
				isScrolling = false;
			};
			$(document).mouseup(upHandler);
			//
			isScrolling = true;	
			scrollLeft();
		}).mouseup(function(){
			isScrolling = false;
		});
		
		scrollLeft = function(){
			if((currentScroll+4)<liTotal){
				currentScroll++;
				var scrollPos = currentScroll*liWidth;
				target.animate({scrollLeft: scrollPos}, 400, function(){
					if(isScrolling){
						scrollLeft();
					}
				});
			}else{
				isScrolling = false;
			}
			setButtons();
		};
		//
		//=============================================== PREV //
	
		setHovers($('#prev'));
		
		$('#prev').mousedown(function() {
			// bind mouseup outside
			var upHandler = function() {
				$(document).unbind("mouseup", upHandler);
				isScrolling = false;
			};
			$(document).mouseup(upHandler);
			//
			isScrolling = true;	
			scrollRight();
			//
		}).mouseup(function(){
			isScrolling = false;
		});
		
		scrollRight = function(){
			if(currentScroll>0){
				currentScroll--;
				var scrollPos = currentScroll*liWidth;
				target.animate({scrollLeft: scrollPos}, 400, function(){
					if(isScrolling){
						scrollRight();
					}
				});
			}else{
				isScrolling = false;
			}
			setButtons();
		};
	};
})(jQuery);	

// ============================================== //

		// EMBED FLOWPLAYER //

// ============================================== //

setPlayer = function(playerId, imagePath, moviePath){
	jwplayer(playerId).setup({ 
		flashplayer: "http://www1.unit.tv/includes/flash/jwplayer.swf", 
		file: moviePath,
		image: imagePath,
		bufferlength: 10,
		/*controlbar: 'bottom',*/
		skin: "http://www1.unit.tv/includes/flash/unit.zip",
		controlbar: 'over',
		stretching:'fill',
		height: 394, 
		width: 700 
	});
};

// ============================================== //

		// CLIENT LOGIN //

// ============================================== //

initClientLogin = function(){
	$('.submit_form').click(function() {  
		$('p.form_error').show();						 
		return false;
	}); 								 
};

// ============================================== //

		// SHARE LINKS //

// ============================================== //

initShareLinks = function(){
	var pathname = window.location;
	var fbUrl = 'http://api.addthis.com/oexchange/0.8/forward/facebook/offer?url='+pathname+'&username=unittv'
	$('#content_b a.share_fb').attr('href', fbUrl);
	//
	var twUrl = 'http://api.addthis.com/oexchange/0.8/forward/twitter/offer?url='+pathname+'&username=unittv&template=Unit TV - '+$('#content_b h3 cufontext').html()+': '+pathname;
	$('#content_b a.share_tw').attr('href', twUrl);
	/*var thisUrl:String = "http://api.addthis.com/oexchange/0.8/forward/twitter/offer?url=http%3A%2F%2Fdisneyvideoplanner.co.uk%2Fview.php%3Fuser_id%3D"+urlId+"&username=disneymasher&template=Disney+Parks+Video+Masher+-+Watch+my+unique+holiday+planning+video%3A+http%3A%2F%2Fdisneyvideoplanner.co.uk%2Fview.php%3Fuser_id%3D"+urlId;

	.click(function() {  
		//var shareUrl = ;
		//http://api.addthis.com/oexchange/0.8/forward/facebook/offer?url=http%3A%2F%2Fdisneyvideoplanner.co.uk%2Fview.php%3Fuser_id%3D"+urlId+"&username=disneymasher"
		//$('p.form_error').show();
		var pathname = window.location;
		alert(pathname);
		return false;
	}); */										 
};
		
// ============================================== //

		// INITIALISE //

// ============================================== //

$(document).ready(function(){
	// Safari Nav
	//A. Target Safari
	if( $.browser.safari ){
		$('#header ul li a').css('padding-top', '2px');
		$('#header ul li.phone').css('padding-top', '2px');
	}
	// Font replacement
	Cufon.replace('h2, h3, h4, #img_carousel ul li p, ul#base_nav li a span, #header ul li.phone');
	Cufon.replace('#header ul li a', {hover: true});
	//
	Cufon.now();
	// Image Carousel
	if ($('#img_carousel').length) {
		$('#img_carousel').initCarousel();
	};
	// Facilities thumbs
	if ($('#thumb_grid').length) {
		$('#thumb_grid').initThumbgrid();
	};
	// Work movie
	if ($('#page_work_item #player').length) {
		initWorkPlayer();
	};
	if ($('#page_service #player').length) {
		initWorkPlayer();
	};
	// Client Login
	if ($('#page_clients').length) {
		initClientLogin();
	};
	// Share This
	if ($('#page_work_item').length || $('#page_service').length) {
		initShareLinks();
	};
	// About Unit Image gallery
	if ($('#page_about_gallery').length) {
		initGalleryPage();
	};
	// work scroll
	if ($('#work_nav ul li').length>4) {
		$('#work_nav').initWorkScroll();
	};
});

