var mousecoords = null;
var current = '';
var locked = false;
var headlineText1 = '';
var headlineText2 = '';
var menu_hold = '';


var campaignIndex;
var campaignLocked;
var campaignLoader;
var campaignImageSequence;
var campaignSpeed;
var campaignTime;
var campaignVideo;

var ExternalFile = DUI.Class.create({
	init: function(filename, type) {
		this.filename = filename;
		if(type == null || type == "") {
			if(filename.indexOf('css') != -1)
				this.type = "css";
			else
				this.type="js";
		} else
			this.type = type;
		this.load();
	},
	load: function() {
		if(this.type == "css") {
			var fileref = document.createElement("link");
			fileref.setAttribute("rel", "stylesheet");
			fileref.setAttribute("type", "text/css");
			fileref.setAttribute("href", this.filename);
		} else {
			var fileref = document.createElement("script");
			fileref.setAttribute("type", "text/javascript");
			fileref.setAttribute("src", this.filename);
		}
		if (typeof fileref!="undefined")
			document.getElementsByTagName("head")[0].appendChild(fileref)
	}
});
var FileLoader = DUI.Class.create({
	init: function() {
		this.files = [];
	},
	load: function(filename) {
		if(!this.find(filename))
			this.files.push(new ExternalFile(filename));
	},
	find: function(filename) {
		for(var i=0; i<this.files.length; i++)
			if(this.files[i].filename == filename)
				return true;
		return false;
	}
});

var fileloader = new FileLoader();

var Loader = DUI.Class.create({
	init: function() {
		this.queue = [];
		this.loading = false;
		this.timeout = 0;
	},
	add: function(name) {
		if(this.queue.length == 0) {
			clearTimeout(this.timeout);
			this.timeout = setTimeout(this.show, 1000);
		}
		this.queue = [];
		this.queue.push(name);
	},
	remove: function(name) {
		if(this.queue.length == 0) { clearTimeout(this.timeout); return; }
		for(var i=0; i<this.queue.length; i++)
			if(this.queue[i] == name)
				this.queue.splice(i, 1);
		if(this.queue.length == 0) {
			clearTimeout(this.timeout);
			this.hide();
		}
	},
	show: function() {
		clearTimeout(this.timeout);
		if(!$.browser.msie || $.browser.version.substr(0,1)>7)
			$("#blackout").stop().css({ display : 'block' }).animate({ opacity : 1 }, { queue : false,  duration : 250 });
		$("#loader").stop().css({ display : 'block' }).animate({ opacity : 1 }, { queue : false,  duration : 500 });
	},
	hide: function() {
		if(!$.browser.msie || $.browser.version.substr(0,1)>7)
			$("#blackout").stop().animate({ opacity : 0 }, { queue : false,  duration : 250, complete : function() { $(this).css({ display : 'none' }); } });
		$("#loader").stop().animate({ opacity : 0 }, { queue : false,  duration : 250, complete : function() { $(this).css({ display : 'none' }); } });
	}
});

var phbRequirement = "";

$(function() {
  document.write = function(evil) {
    phbRequirement += evil;
$('#mailchimpdiv').html(phbRequirement);
  }
});


var loader = new Loader();
/*
 *	JQuery Image Sequences
 *	Developed at Noble Studios
 */
(function($) {
	$.fx.step['imageSequence'] = function(fx) {
		var index = Math.min(parseInt(Math.round(fx.end.frames.length * fx.pos)), fx.end.frames.length - 1);
		if($(fx.elem).data('is_index') != index) {
			fx.elem.innerHTML = '<img src="'+fx.end.frames[Math.max(index - 1, 0)].src+'" \>';
			fx.elem.style.background = 'url('+fx.end.frames[index].src+') 0 0 no-repeat';
			$(fx.elem).data('is_index', index);
		} else if(index == fx.end.frames.length - 1)
			fx.elem.innerHTML = '';
		$(fx.elem).pngFix();
	}
	$.ImageSequence = DUI.Class.create({
		init: function(options) {
			var defaults = jQuery.extend({
				frames : [],
				load : null,
				loadStep : null
			}, options);
			
			jQuery.extend(this, defaults);
			this.numloaded = 0;
			this.loaded = false;
			this.reversed = false;
			
			var parent = this;
			
			$.each(this.frames, function(i, frame) {
				parent.frames[i] = new Image();
				parent.frames[i].src = frame;
				if(parent.frames[i].complete)
					parent.loadImage(parent);
				else
					parent.frames[i].onload = function() {parent.loadImage(parent);}
			});
		},
		loadImage: function(is) {
			is.numloaded++;
			if(is.loadStep) is.loadStep(is.numloaded / is.frames.length, is);
			if(is.numloaded == is.frames.length) {
				this.loaded = true;
				if(is.load) is.runLoad(is);
			}
		},
		addLoad: function(func) {
			if(this.load == null)
				this.load = func;
			else if(typeof this.load == 'function')
				this.load = new Array(this.load, func);
			else
				this.load.push(func);
				
		},
		runLoad:function(is) {
			if(this.load != null) {
				if(typeof this.load == 'function')
					this.load(is);
				else
					for(var i=0; i<this.load.length; i++)
						this.load[i](is);
			}
			this.load = null;
		},
		waitLoad: function(callback) {
			this.addLoad(callback);
			if(this.loaded) this.runLoad();
		},
		addFrames: function(obj) {
			var parent = this;
			if(typeof obj == "object")
				$.each(obj, function(i, frame) {addFrame(frame);});
			else
				addFrame(obj);

			this.loaded = false;

			function addFrame(frame) {
				parent.frames.push(new Image());
				parent.frames[parent.frames.length-1].src = frame;
				if(parent.frames[parent.frames.length-1].complete)
					parent.loadImage(parent);
				else
					parent.frames[parent.frames.length-1].onload = function() {parent.loadImage(parent);}
			}
		},
		setForward: function() {
			if(this.reversed) this.reverseFrames();
		},
		setBackward: function() {
			if(!this.reversed) this.reverseFrames();
		},
		reverseFrames: function() {
			this.reversed = !this.reversed;
			this.frames.reverse();
		}
	});
})(jQuery);
var ImageLoader = DUI.Class.create({
	init: function() {
		this.imageObj = new Image();
		this.callback = null;
	},
	load: function(src, callback) {
		this.callback = callback;
                if($.browser.msie && $.browser.version.substr(0,1)>=9)
		  this.imageObj.onload = callback;
		this.imageObj.onerror = function() {
			alert('Connection lost.  Please refresh the page once the connection has been reestablished.');
		};
		this.imageObj.src = src;
		if(this.imageObj.complete) {
			this.imageObj.onload = function() {};
			this.callback.call(this.imageObj);
		}
	}
});

$(document).ready(function() {
  jQuery.queue.def = false;
  jQuery.easing.def = "easeOutQuad";
  $('body').css({ position : 'static' }).css({ position : 'relative' });

  $.scrollTo('0', 500);

  headlineText1 = $('#header h1').html();
  headlineText2 = $('#header h2').html();
  if($.browser.msie) {
    $('#header h1').html("");
    $('#header h2').html("");
 }

  


  // Main menu hover
  $('#menu a').hover(menuHoverOn, menuHoverOff);
  function menuHoverOn(){
    $(this).find('img.on').stop()
	  .css({ opacity : 0, display : 'inline' })
	  .animate({ opacity : 1 } , { duration : 250 });
	$(this).find('img.caption').stop()
	  .css({ opacity : 0, display : 'inline', marginLeft : -10 })
	  .animate({ opacity : 1, marginLeft : 0 }, { duration : 250 });
  }
  function menuHoverOff(){
    $(this).find('img.on').stop()
      .animate({ opacity : 0 } , { duration : 250, complete:function(){ $(this).css({ display: 'none' }); } });
    $(this).find('img.caption').stop()
      .animate({ opacity : 0, marginLeft : -10 }, { duration : 250, complete:function(){ $(this).css({ display: 'none' }); } });
  }

  // Footer social hover
  $('#social a').hover(socialOn, socialOff);
  function socialOn(){
    $(this).find('img.on').stop()
	  .css({ opacity : 0, display: 'block' })
	  .animate({ opacity : 1 } , { duration : 200 });
  }
  function socialOff(){
    $(this).find('img.on').stop()
	  .animate({ opacity : 0 } , { duration : 300, complete:function(){ $(this).css({ display: 'none' }); } });
  }

  
});


// AJAX page request getURL(url#hash)
String.prototype.capitalize = function(){ //v1.0
    return this.replace(/\w+/g, function(a){
        if(a == "and" || a == "of") return a;
        return a.charAt(0).toUpperCase() + a.substr(1).toLowerCase();
    });
};


function convertHash(hash) {
  hash = hash.replace(new RegExp( "_", "g" ), " ");
  if(hash.lastIndexOf("/") == hash.length - 1)
    hash = hash.substring(0, hash.lastIndexOf("/"));
  return hash.replace(new RegExp( "/", "g" ), " > ").capitalize();
}

function getURL(hash, linkObj) {
	hash = hash.substring(hash.lastIndexOf('#') + 1);
	if(!locked && current!=hash ) {
		loader.add("page");
		locked = true;
                pageTracker._trackPageview("/"+hash+".html" );
		var hash_ref = hash.split("/");
		if( hash_ref[0] != 'about' && hash_ref[0] != 'showcase' && hash_ref[0] != 'clients' && hash_ref[0] != 'news' && hash_ref[0] != 'contact' && hash_ref[0] != 'videos')
			hash='';

		//animate content out
		if($.browser.msie) {
		    $('body').css({ position : 'static' }).css({ position : 'relative' });
		    $('#body, #body #showcase, #body div#projects, #body div#showcase_pagination .buttons, #body .clientswrapper, #body .campaign_wrapper, #body #news_wrapper .pagination, #body #map_wrapper').animate({ opacity : 0 }, { duration : 200, queue : false });
		} else
		    $('#body').animate({ opacity : 0 }, { duration : 200, queue : false });

		$('#hidden').load('http://www.noblestudios.com/' + hash + '/content/ajax/', function (responseText, textStatus, XMLHttpRequest) {
			loader.remove("page");
			if(responseText != '') {
				//update title
				if(document.title) document.title = convertHash('Noble Studios, Inc.'+((hash != "") ? ' > '+hash : ' - Marketing and Web Development'));  //$('#content .page_title:first').html();
				//call pngFix() for new content if needed

			  if(!$.browser.msie && (hash_ref[0] == "index" || hash_ref[0] == ""))
				headTextOn();
			  else
				headTextOff();
				//after fade content out is finished:
				setTimeout(function() {
					if ( hash == '' ) hash = 'index';
					current = hash;
					//update url
					window.location.hash = hash;
					//save hash for ie
					$('#hiddenFrame').attr('src', 'http://www.noblestudios.com/incl/store_hash?hash='+hash);
					//determine height of new content
					var h = $('#hidden').height();
					//animate in header
					//if( hash == 'index' && $.browser.msie) headTextOn();
					$('#header').animate({height : '110px'}, { duration : 250, queue : false });
					//animate in body
					$('#body .inner').animate({ height : (h > 121) ? h : 121 },{ duration : 500, complete : function(){$('#body .inner').css({height:'auto', overflow:'visible'});} });

					var tempname = current.split("/")[0];
					var temppath = "http://www.noblestudios.com/index.php/";
					switch(tempname) {
						case "index":
							break;
						default:
//							fileloader.load(temppath+tempname+"/css_"+tempname);
							break;
					}
					//after animate in
					setTimeout(function() {
						//move content from div#hidden to div.inner
						$('#body .inner').html($('#hidden').html());
						$('#hidden').html('');
						
						
						//call initialize functions after new content is loaded
						var current_ref = current.split("/")
						var path = "http://www.noblestudios.com/index.php/";

						if ( current_ref[0] == 'index' )
							initHome();
						else if ( current_ref[0] == 'about' ) {
							var aboutPath = path + 'about/';
							
							if(!fileloader.find(aboutPath+"js_about"))
								fileloader.load(aboutPath+"js_about");
							else
								initAbout();
						} else if ( current_ref[0] == 'showcase' ) {
							var showcasePath = path + 'showcase/';
							if(!fileloader.find(showcasePath+"js_showcase"))
								fileloader.load(showcasePath+"js_showcase");
							else
								initShowcase();
						} else if ( current_ref[0] == 'clients' ) {
							var clientsPath = path + 'clients/';
							if(!fileloader.find(clientsPath+"js_clients"))
								fileloader.load(clientsPath+"js_clients");
							else
								initClients();
						} else if ( current_ref[0] == 'news' ) {
							var newsPath = path + 'news/';
							if(!fileloader.find(newsPath+"js_news"))
								fileloader.load(newsPath+"js_news");
							else
								initNews();
						} else if ( current_ref[0] == 'contact' ) {
							var contactPath = path + 'contact/';
							if(!fileloader.find(contactPath+"js_contact"))
								fileloader.load(contactPath+"js_contact");
							else
								initContact();
						} else if (current_ref[0] == 'videos')
							$('#sub_wrapper h1').each( h1Replace );

						//$('#body').animate({ opacity : 1 }, { duration : 500, complete : function() { if(jQuery.browser.msie) this.style.removeAttribute("filter"); } });
						if($.browser.msie) {
						    $('body').css({ position : 'static' }).css({ position : 'relative' });
						    $('#body, #body #showcase, #body div#projects, #body div#showcase_pagination .buttons, #body .clientswrapper, #body #news_wrapper .pagination, #body #map_wrapper').animate({ opacity : 1 }, { duration : 200, queue : false, complete : function() { if(jQuery.browser.msie) this.style.removeAttribute("filter"); } });
						} else
						    $('#body').animate({ opacity : 1 }, { duration : 200, queue : false, complete : function() { if(jQuery.browser.msie) this.style.removeAttribute("filter"); } });
						$('#pagewrapper').css({'position':'static'}).css({'position':'relative'});
						$('body').css({'position':'static'}).css({'position':'relative'});
						locked = false;
						if (current_ref.length=2)
						  $(linkObj).mouseout();
					}, 500);
				}, 200);
			} else
				locked = false;
		});
	}
}

function checkURL() {
  if(!locked) {
    var hash_page = window.location.hash.substring(window.location.hash.lastIndexOf('#') + 1);
    if(document.frames && document.frames['hiddenFrame'] && document.frames['hiddenFrame'].getHash && current != document.frames['hiddenFrame'].getHash()) window.location.hash = document.frames['hiddenFrame'].getHash();
    if(current != hash_page ) getURL(hash_page);
  }
}

// flash text replace
function h1Replace(index, element){
    $(this).css({
        width: $(this).width(),
        height:$(this).height()
      }).flash({
      swf: 'http://www.noblestudios.com/images/uploads/fonts/humanist777_light_replace.swf',
      flashvars: { text : encodeURIComponent($(this).html()),  color : '#ffffff',  width : $(this).width(),  height : $(this).height(), size : 35, align : 'left', line : 12,  spacing : -0.5 },
      height: $(this).height(), width: $(this).width(), bgcolor: '#080809', wmode: 'transparent'
      });
}

function h2Replace(index, element){
    $(this).css({
        width: $(this).width(),
        height:$(this).height()
      }).flash({
      swf: 'http://www.noblestudios.com/images/uploads/fonts/humanist777_light_replace.swf',
      flashvars: { text : encodeURIComponent($(this).html()),  color : '#939598',  width : $(this).width(),  height : $(this).height(), size : 20, align : 'left', line : 14,  spacing : 0 },
      height: $(this).height(), width: $(this).width(), bgcolor: '#080809', wmode: 'transparent'
      });
}

function h3Replace(index, element){
    $(this).css({
        width: $(this).width(),
        height:$(this).height()
      }).flash({
      swf: 'http://www.noblestudios.com/images/uploads/fonts/humanist777_light_replace.swf',
      flashvars: { text : encodeURIComponent($(this).html()),  color : '#ffffff',  width : $(this).width(),  height : $(this).height(), size : 28, align : 'left', line : 8,  spacing : -0.5 },
      height: $(this).height(), width: $(this).width(), bgcolor: '#080809', wmode: 'transparent'
      });
}

function headTextOn(){
   $('#header h1').html(headlineText1).flash({
      swf: 'http://www.noblestudios.com/images/uploads/fonts/humanist777_light_replace.swf',
      flashvars: { text : headlineText1,  color : '#ffffff',  width : 976,  height : 44, size : 35, align : 'center', line : 0,  spacing : -0.5 },
      height: 44, width: 976, bgcolor: '#080809', wmode: 'transparent'
      });
   $('#header h2').html(headlineText2).flash({
      swf: 'http://www.noblestudios.com/images/uploads/fonts/humanist777_light_replace.swf',
      flashvars: { text : headlineText2,  color : '#939598',  width : 976,  height : 120, size : 20, align : 'center', line : 14,  spacing : 0 },
      height: 120, width: 976, bgcolor: '#080809', wmode: 'transparent'
      });
}
function headTextOff(){
      $('#header h1').html('');
      $('#header h2').html('');
}

function sizeFlash() {
  var screenWidth = $(this).width();
  var screenHeight = $(this).height();
  $('#fourthWard').width( screenWidth );
  $('#fourthWard').height( screenHeight );
  $('#fourthWard object').width( screenWidth );
  $('#fourthWard object').height( screenHeight );
}

$(document).mousemove(function(e) {
	mousecoords = { x : e.pageX, y : e.pageY };
});

$(document).ready(function() {
	$('#blackout').css('opacity', 0).click(hideVideo);
	$('#lightbox').click(function(e){e.stopPropagation()});});
function showVideo(src) {
	$('#lightbox').animate({width:800,height: 600,marginTop:-310,marginLeft:-410},{queue:false,duration:500}).html('').flash({
		swf: 'http://www.noblestudios.com/images/uploads/template/swf/flv_player_big.swf',
		flashvars: { file : src },
		height: '100%', width: '100%', wmode: 'opaque'
	});//.append('<a href="javascript:void(0)" onclick="hideVideo()">Close</a>');
	$('#blackout').css('display','block').animate({opacity:1},{queue:false,duration:500});}
function hideVideo() {
	$('#lightbox').animate({width:0,height: 0,marginTop:-10,marginLeft:-10},{queue:false,duration:500});
	$('#blackout').animate({opacity:0},{queue:false,duration:250,complete:function() {
		$(this).css('display','none');
		$('#lightbox').html();
	}});
}

(function($) {
  var cache = [];
  // Arguments are image paths relative to the current page.
  $.preLoadImages = function() {
    var args_len = arguments.length;
    for (var i = args_len; i--;) {
      var cacheImage = document.createElement('img');
      cacheImage.src = arguments[i];
      cache.push(cacheImage);
    }
  }
})(jQuery)

var campaigns = [

{
  description: "",
  source: "http://noblestudios.com/images/uploads/campaign/ArtWallCampaign_v1.jpg",
  link: "http://www.noblestudios.com/news/page/artists"},
{
  description: "You can follow us... wherever we may go.  There isn't an ocean too deep. A mountain so high it can keep. Keep us away. ",
  source: "http://noblestudios.com/images/uploads/campaign/2010_0112_CampaignImage_social.jpg",
  link: "http://noblestudios.com/news/page/social_noble"},
{
  description: "Noble Studios wishes everyone a very happy holidays!",
  source: "http://noblestudios.com/images/uploads/campaign/2010_HolidayCard.jpg",
  link: "http://noblestudios.com/happy_holidays/"},
{
  description: "Noble Studios received four 2010 Awards of Excellence (Gold) and three Awards of Distinction (Silver) from the Communicator Awards, the leading international awards program honoring creative excellence.",
  source: "http://noblestudios.com/images/uploads/campaign/20100607_CommunicatorAwards_v4.jpg",
  link: "http://www.noblestudios.com/news/page/communicator_awards"},
{
  description: "The Nevada District office of the U. S. Small Business Administration has selected its small business award honorees for 2010. Jarrod Lopiccolo, co-owner of Noble Studios in Carson City, has been named Young Entrepreneur of the Year for the State of Nevada. Jarrod and the other honorees will be recognized at an after-hours awards reception the week of May 3rd in Las Vegas.  ",
  source: "http://noblestudios.com/images/uploads/campaign/Campaign_EntrepreneurAward.jpg",
  link: "http://www.noblestudios.com/news/page/entrepreneur_of_the_year"},
{
  description: "",
  source: "http://noblestudios.com/images/uploads/campaign/20100129_CampaignImage_dave.jpg",
  link: "http://www.noblestudios.com/about/awards/"},
{
  description: "Microsoft Photosynth - Noble Studios is working on a project using the new Microsoft Photosynth software released in 2009.",
  source: "http://noblestudios.com/images/uploads/campaign/synth.jpg",
  link: "http://www.noblestudios.com/contact/"},
{
  description: "Congratulations Nevada Magazine Wins First Place in 2008 National Headliner Awards",
  source: "http://noblestudios.com/images/uploads/campaign/20090825_CampaignImage_nevm.jpg",
  link: "http://www.noblestudios.com/about/awards/"},
{
  description: "Here's to happy memories in 2009!",
  source: "http://noblestudios.com/images/uploads/campaign/karma.jpg",
  link: "javascript:addFlvPlayer('http://www.noblestudios.com/images/uploads/flv_player/video.flv')"},
{
  description: "Congratulations Holland Project Wins in the 2008 Communicator Awards",
  source: "http://noblestudios.com/images/uploads/campaign/20090825_CampaignImage_holl.jpg",
  link: "http://www.noblestudios.com/about/awards/"},
{
  description: "From our desk to Autodesk.",
  source: "http://noblestudios.com/images/uploads/campaign/fromourdesk.jpg",
  link: "http://www.noblestudios.com/showcase/"},
{
  description: "Nice work Michelangelo! We'll see you soon at the 2009 Noble Retreat.",
  source: "http://noblestudios.com/images/uploads/campaign/europe.jpg",
  link: "http://www.noblestudios.com/news/page/we_made_our_goal2"},
{
  description: "Autodesk Dragonfly is alive!",
  source: "http://noblestudios.com/images/uploads/campaign/dragonfly.jpg",
  link: "http://www.noblestudios.com/news/page/autodesk_project_dragonfly"},
{
  description: "Happy Birthday Noble!",
  source: "http://noblestudios.com/images/uploads/campaign/bday.jpg",
  link: "http://www.noblestudios.com/about/"}
];

$(document).ready(function() {
for(var i=0; i<campaigns.length; i++) {jQuery.preLoadImages(campaigns[i]['source']);}
});

function initHome(){
  if($('#header h1').css('display') == 'none') {
    $('#header h1').css('display', 'block');
    $('#header h2').css('display', 'block');
  }
  
  $('#home_wrapper h3').each( h3Replace );
}

var introTimeout = null;
function introAnimation() {
  $('*').stop( true );
  clearTimeout(introTimeout);
  $('#header').css({ height : 110});
  //$('#header .content').css({ opacity : 0, visibility : 'visible' });
  //$('#header-overlay').css({ opacity : 1, visibility : 'visible' });
  $('.module').css({ opacity : 0, visibility : 'visible', marginTop : 0 });
  $('.campaign').css({ opacity : 0, visibility : 'visible' });
if($.browser.msie)
  $('.campaign_wrapper').css({ opacity : 0, visibility : 'visible' });
  $('#header').animate({ height : 340 }, { duration : 1000, complete : function() { if($.browser.msie) headTextOn(); } });
  introTimeout = setTimeout(function() {
    //$('#header .content').animate({ opacity : 1 }, { duration : 1000 });
    //$('#header-overlay').animate({ opacity : 0 }, { duration : 1000 });
    $('.module:first').animate({ opacity : 1, marginTop : 20 }, { duration : 300, complete : animateModule });
    introTimeout = setTimeout(function() {
      $('.campaign').animate({ opacity : 1 }, { duration : 1000, complete : initCampaign });
if($.browser.msie)
  $('.campaign_wrapper').animate({ opacity : 1 }, { duration : 1000 });
      //$('#header-overlay').css({ visibility : 'hidden' });
    }, 1000);
  }, 700);
}

function animateModule() {
  $(this).find('+.module').animate({ opacity : 1, marginTop : 20 }, { duration : 300, complete : animateModule });
}

function initCampaign() {
        var directory = "http://www.noblestudios.com/images/uploads/loader/";
	$('.campaign').css({opacity:'none'});
	campaignIndex = 0;
	campaignVideo = false;
	campaignLoader = new ImageLoader();
	campaignLoaderLocked = false;
	campaignTime = 0;
	campaignSpeed = 750;
	$('#campaign_loader').css({ opacity : 0 });
	for(var i=0; i<campaigns.length; i++)
		$('.pagination').append('<span></span>');
	$('.pagination span:eq(0)').addClass('active');
	
	campaignImageSequence = new $.ImageSequence({
		frames: new Array(directory+'_0000.png',directory+'_0001.png',directory+'_0002.png',directory+'_0003.png',directory+'_0004.png',directory+'_0005.png',directory+'_0006.png',directory+'_0007.png'),
		load: function() {
			$('.pagination span').click(function(e) {
				var index = $('.pagination span').index(this);
				if(index != campaignIndex)
					campaignGoto(index);
			});
			$('.left_arrow').click(function(e) { campaignGoto(null, 'left') });
			$('.right_arrow').click(function(e) { campaignGoto(null, 'right') });
		}
	});
}

function addFlvPlayer(flv) {
	campaignVideo = true;
	if(flv == '' || flv == null) flv = 'http://www.noblestudios.com/images/uploads/flv_player/video.flv';
	$('#campaign_container').empty().flash({swf:'http://www.noblestudios.com/images/uploads/flv_player/flv_player.swf', flashvars:{video:flv}, height:352, width:907, wmode: 'transparent' });	
}
function removeFlvPlayer() {
	campaignVideo = false;
	$('#campaign_container').empty().html('<a href="'+campaigns[campaignIndex].link+'"><img src="'+campaigns[campaignIndex].source+'" width="907" height="352" alt="'+campaigns[campaignIndex].description+'" /></a>');
}
function updatePagination(i) {
	$('.campaign .pagination span').removeClass('active');
	$('.campaign .pagination span:eq('+i+')').addClass('active');
}
function campaignPaginate() {
	$('.pagination span').removeClass('active');
	$('.pagination span:eq('+campaignIndex+')').addClass('active');
}
function campaignSpeedUpdate() {
	var current = new Date();
	campaignSpeed = Math.min(750, current.getTime() - campaignTime);
	campaignTime = current.getTime();
}
function campaignGoto(index, direction) {
	var directory = "http://www.noblestudios.com/images/uploads/loader/";
	if(index == null && direction == null)
		return;
	if(index == null)
		index = ((direction == 'left') ? ((campaignIndex == 0) ? campaigns.length - 1 : campaignIndex-1) : ((campaignIndex == campaigns.length - 1) ? 0 : campaignIndex+1));
	if(direction == null) {
		if(index != campaignIndex) {
			if(index < campaignIndex)
				direction = 'left';
			else
				direction = 'right';
		} else
			return;
	}
	campaignSpeedUpdate();
	if($.browser.msie && $.browser.version.substr(0,1)<7)
		$('#campaign_loader').html('<img src="'+directory+'loader.gif" width="34" height="34" />');
	else if(!campaignLoaderLocked)
		animateLoader();
	$('#campaign_loader').css('display', 'block').animate({ opacity : 1 }, { duration : 500, queue: false });
	$('#campaign_container').stop(true, true).animate({ opacity : .5 }, { duration : 500, queue: false });
	if(campaignVideo)
		removeFlvPlayer();
	campaignIndex = index;
	campaignPaginate();
	campaignLoader.load(campaigns[index].source, function() {
		campaigns[index].source = this.src;
		$('#campaign_loader').stop().animate({ opacity : 0 }, { duration : 500, queue: false });
		$('#campaign_container').stop().animate({ opacity : 1 }, { duration : 500, queue: false });
		campaignLoaderLocked = false;
		var insert = '<a href="'+campaigns[index].link+'"><img src="'+this.src+'" width="907" height="352" alt="'+campaigns[index].description+'" /></a>';
		if(direction == 'left')
			$('#campaign_container').prepend(insert);
		else
			$('#campaign_container').append(insert);
		$('#campaign_container')
			.css('left', ((direction == 'left') ? -907 : 0))
			.animate({ left : ((direction == 'left') ? 0 : -907) }, { duration : campaignSpeed, queue: false, easing: 'easeOutQuad', complete:
			((direction == 'left')
			? function() {
					$('#campaign_container a:eq(1)').remove();
				}
			: function() {
					$('#campaign_container a:eq(0)').remove();
					$('#campaign_container').css('left', 0);
				}
			)
		});
	});
	function animateLoader() {
		campaignLoaderLocked = true;
		$('#campaign_loader').animate({ imageSequence: campaignImageSequence }, { duration: 1000, queue: false, easing: 'linear', complete: animateLoader });
	}
}
