/* Standard Macromedia functions for rollovers */
function preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
	var i,j=d.MM_p.length,a=preloadImages.arguments; for(i=0; i<a.length; i++)
	if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}

function swap_back() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
	d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function swap() { //v3.0
  var i,j=0,x,a=swap.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
/* ====================================================================================== */
/* jQuery document-is-ready function. Place all calls here */
jQuery(document).ready(function() {
	preloadImages('images/mb_brands_f2.png','images/mb_campaigns_f2.png','images/mb_client_area_f2.png','images/mb_client_list_f2.png','images/mb_contact_us_f2.png','images/mb_interactive_f2.png','images/mb_latest_f2.png','images/mb_literature_f2.png','images/mb_login_f2.png','images/mb_news_f2.png','images/mb_newsletter_f2.png','images/mb_opportunities_f2.png','images/mb_our_clients_f2.png','images/mb_our_experience_f2.png','images/mb_our_expertise_f2.png','images/mb_our_team_f2.png','images/mb_our_unique_points_f2.png','images/mb_testimonials_f2.png','images/mb_who_we_are_f2.png','images/mf_brands_f2.png','images/mf_campaigns_f2.png','images/mf_interactive_f2.png','images/mf_literature_f2.png');
	
	$("a[rel^='prettyPhoto']").prettyPhoto();
	$("img[rel^='prettyPhoto']").prettyPhoto();
	
	$("a[rel^='prettyPopin']").prettyPopin();
	$("area[rel^='prettyPopin']").prettyPopin();

	
	// Stick > on bullet points
	// http://docs.jquery.com/DOM/Traversing/Selectors
	$("#left_content li:not(.factsheets)").prepend("> ");

	
	// ============================================================
	// Font Resize methods. Provide 3 links with classes 
	// .resetFont, .increaseFont, decreaseFont. Size is saved in a 
	// Cookie (requires jqery.cookie.js as well as jquery.js)
	// Set size of body {} font
	// ------------------------------------------------------------
/*	var originalFontSize = $('body').css('font-size');
	var originalFontSizeNum = parseFloat(originalFontSize);

	var cookie_name = 'textsize';
	
	if($.cookie(cookie_name))
		$('body').css('font-size', $.cookie(cookie_name));
	else
		$('body').css('font-size', originalFontSize);
	// ------------------------------------------------------------
	// Reset Cookie
	$(".resetFont").click(function() {
		$('body').css('font-size', originalFontSize);
		$.cookie(cookie_name, null);
	});
	// ------------------------------------------------------------
	// Increase Font Size
	$(".increaseFont").click(function(){
		var currentFontSize = $('body').css('font-size');
		var currentFontSizeNum = parseFloat(currentFontSize);
		if(currentFontSizeNum < 20) {
			var newFontSize = currentFontSizeNum*1.2;
			$('body').css('font-size', newFontSize);
			$.cookie(cookie_name, newFontSize);
		}
		return false;
	});
	// ------------------------------------------------------------
	// Decrease Font Size
	$('.decreaseFont').click(function(){
		var currentFontSize = $('body').css('font-size');
		var currentFontSizeNum = parseFloat(currentFontSize, 10);
		if(currentFontSizeNum > 8) {
			var newFontSize = currentFontSizeNum*0.8;
			$('body').css('font-size', newFontSize);
			$.cookie(cookie_name, newFontSize);
		}
		return false;
	});*/
	// ============================================================
	// convert our taEmail class of links from a standard email link
	// to a non-clickable version. But on click, convert it back!
/*	$(".taEmail").each(function() {
		var newhref = this.href.replace(/@/," @ ");
		//alert(newhref);
		$(this).attr("href",newhref);
	});*/
	$(".taEmail").click(function() {
		var newhref = this.href.replace(/%20@%20/,"@");
		//alert(newhref);
		$(this).attr("href",newhref).click();
	});
	// ============================================================
	// Play the homepage intro movie

	// Show the intro movie slides
	var introSlides = new Array('intro_01.png',3000,true,'intro_02.png',3000,true,'intro_03.png',3500,false,'intro_04.png',4000,false,'intro_05.png',4000,false,'intro_06.png',5000,true,'intro_07.png',5000,false,'intro_08.png',5000,true);
	var count = introSlides.length;
	var onSlide = 0;
	var timer;
	
	if( ! $.cookie('twu_cookie_intro')) {
		$.cookie('twu_cookie_intro','true',{expires:14,path: '/'});
		
		$("#homepage_slides").add("<img class=\"intro\">");
		//showHomepageIntro();
		showIntroSlides();
	} else
		showHomepageIntro();
	
	// ============================================================
	// Function calls itself via a setTimeout call and each time displays
	// the next available slide from the array. If there are no more slides
	// the timer is cleared and the homepageIntro is shown instead
	function showIntroSlides() {
		slideURL = introSlides[onSlide];
		displayTime = introSlides[(onSlide+1)];
		fadeOut = introSlides[(onSlide+2)];
		//alert(slideURL+' > '+displayTime+' > '+fadeOut);
		if(fadeOut) {
			$("#homepage_slides").fadeOut("slow",function() {
				onSlide+=3;
				if(onSlide <= count) {
					$("#homepage_slides").html("<img src=\"/Filestore/Images/"+slideURL+"\" />").fadeIn("slow",function() {
						timer = setTimeout(showIntroSlides,displayTime);
					});
				} else {
					showHomepageIntro();
					clearTimeout("timer");
				}
			});
		} else {
			// Simply replace one slide with another
			onSlide+=3;
			if(onSlide <= count) {
				$("#homepage_slides img").attr("src","/Filestore/Images/"+slideURL);
				timer = setTimeout(showIntroSlides,displayTime);
			} else {
				showHomepageIntro();
				clearTimeout("timer");
			}
		}
	}
	// ============================================================
	// Show opening para and animated picture of projects
	function showHomepageIntro() {
		$("#homepage_slides").fadeOut("slow",function() {
			$("#homepage_welcome").fadeIn("slow");
			//$("#homepage_gallery").fadeIn("slow");
		});
		showHomepageGallery();
	}
	// ============================================================
	// Moving image gallery. Great effect, but processor intensive
	// And difficult to overlay text or other things, so for now,
	// leave it out!
	function _showHomepageGallery() {
		var imagePath = '/Filestore/Images/Homepage/';
		if($('#homepage_gallery').length) {
			$('#homepage_gallery').crossSlide({
				fade:1    //in sec
			},[
				{	src:  imagePath + 'hp_help_hospices.jpg',
					from: '100% 80% 1x',
					to:   '30% 50% 1.2x',
					time: 8
				},{
					src:  imagePath + 'hp_nhs_surveys.jpg',
					from: '100% 80% 1.2x',
					to:   '100% 0% 1x',
					time: 8
				},{
					src:  imagePath + 'hp_anthony_nolan.jpg',
					from: '100% 80% 1x',
					to:   '100% 0% 1.2x',
					time: 8
				},{
					src:  imagePath + 'hp_rcs_club.jpg',
					from: '100% 80% 1.2x',
					to:   '100% 0% 1x',
					time: 8
				}
			]);
		}
	}
	
	var homepage_image;
	
	// ============================================================
	// Controlling function that sets up the homepage gallery loop
	function showHomepageGallery() {
		if($('#homepage_gallery').length) {
			homepage_image = Math.round(Math.random()*(gallery_array.length-1));
			showHomepageImage();
			setInterval(showHomepageImage,8000);
		}
	}

	// ============================================================
	// Called intermittently and selects the next picture to show
	function showHomepageImage() {
		var imagePath = '/Filestore/Images/Homepage/';
		var this_image;
		var bgcol_style = "";
		
		homepage_image ++;
		if(homepage_image >= gallery_array.length)
			homepage_image = 0;
		
		var g_image		= gallery_array[homepage_image][0];
		var g_stats		= gallery_array[homepage_image][1];
		var g_link 		= gallery_array[homepage_image][2];
		var g_bgcol		= gallery_array[homepage_image][3];
		var g_statspos	= gallery_array[homepage_image][4];
		var g_client	= gallery_array[homepage_image][5];

		if(g_bgcol != "")
			bgcol_style = " style=\"color:#" + g_bgcol + " !important;\"";

		this_image = "<div id=\"gallery_stats\" class=\"" + g_statspos + "\"" + bgcol_style + "><h3>" + g_client + "</h3><p>" + g_stats + "</p><p class=\"link\">> <a href=\"" + g_link + "\"" + bgcol_style + ">VIEW THIS PROJECT</a></p></div>";

	//	this_image += "<div id=\"gallery_client\">" + g_client + "</div>";
		this_image += "<a href=\"" + g_link + "\"><img src=\"/Filestore/Images/Homepage/" + g_image + "\" /></a>";
		
	
		$('#homepage_gallery').fadeOut(function() {
			$(this).empty().append(this_image).fadeIn();
		});
	}
	
	// ============================================================
	$("#signup").submit(function(e){
     				
		// stop normal link click
		e.preventDefault();

		// send request
		if(this.signup_email.value != "Email address" && this.signup_email.value != "" && this.signup_name.value != "First name" && this.signup_name.value != "") {
			$("#signup_status").empty().addClass("ajax-loading");
			
			$.post("newsletterSignup.php", {signup_email:$("#signup_email").val(),signup_name:$("#signup_name").val()}, function(result) {
				// format and output result. fadeTo(3000,1) simulates delay(), which isn't in jQuery
				$("#signup_status").html(result).show("fast").fadeTo(3000,1).hide("fast");
				$("#signup_status").removeClass("ajax-loading");
			});
		}
	});
	// ============================================================
	$("#news_nav a#up").click(function(e) {
		e.preventDefault();	// stop normal link click
		var news_height = $("#news").height();
		var news_top = parseFloat($("#news").css('top'));
		var page_height = 360;

		if(Math.abs(news_top) > 0) {
			var news_up = news_top + page_height + "px";
			$("#news").stop().animate({top:news_up},'fast');
		}
	});

	$("#news_nav a#down").click(function(e) {
		e.preventDefault();	// stop normal link click
		var news_height = $("#news").height();
		var news_top = parseFloat($("#news").css('top'));
		var page_height = 360;
		
		if(Math.abs(news_top) < (news_height - page_height)) {
			var news_down = parseFloat($("#news").css('top')) - page_height + "px";
			$("#news").stop().animate({top:news_down},'fast');
		}
	});
	// =====================================================================
	// Case Study / Portfolio page. 
	
	// Case study chooser. Shows single image for each case study
	var cs_chooser_on_page = 1;
	
	// On 1024 x 768 screens, and I'm thinking IE 7 here, resize the
	// case study area to fit otherwise the page keeps jumping down to the bottom
	// When moving to the next page in the case study
	//if(screen.height == 768)
	//	$("#case_study_container").css("height","440px");
	
	$(".nextprojectpage").click(function(e) {
		e.preventDefault();	// stop normal link click
		var cs = $("#case_study_chooser .page_group");
		var cs_count = $("#case_study_chooser .page_group").attr("id");
		//alert(cs_chooser_on_page + ' / ' + cs_count);
		if(cs_chooser_on_page < cs_count)
			cs.animate({"left":"-=1038px"});
		cs_chooser_on_page ++;
			
		// Display / Hide nav buttons
		if(cs_chooser_on_page == cs_count)
			$(".nextprojectpage").fadeOut();//css("display","none");
		if(cs_chooser_on_page > 1)
			$(".prevprojectpage").fadeIn();//("display","block");
	});
	$(".prevprojectpage").click(function(e) {
		e.preventDefault();	// stop normal link click
		var cs = $("#case_study_chooser .page_group");
		var cs_count = $("#case_study_chooser .page_group").attr("id");
		if(cs_chooser_on_page > 1)
			cs.animate({"left":"+=1038px"});
		cs_chooser_on_page --;

		// Display / Hide nav buttons
		if(cs_chooser_on_page == 1)
			$(".prevprojectpage").fadeOut();//css("display","none");
		if(cs_chooser_on_page < cs_count)
			$(".nextprojectpage").fadeIn();//css("display","block");

	});
	
	
	
	var pp = 0; // current page user is on
	var ps = "";
	
	// GO to the first page of the case study if there is one.
	// This file is loaded only ONCE for the whole case study 
	// so the call happens only the first time the page is loaded
	if($("#case_study_navigation").length)
		get_ca_page(1);
	
	// Clicking a page number to visit a page of a case study
	$("#case_study_navigation a").click(function() {
		var t = $(this);
		var page = t.attr("id");	
		get_ca_page(page);
	});
	// -----------------------------------------------------
	function get_ca_page(page) {
		var offset = 300;
	/*	jQuery.each(jQuery.browser, function(i, val) {
			//if(i=="mozilla" && jQuery.browser.version.substr(0,3)=="1.9")
			// Safari or Mozilla 2 / Camino
			if(i == "safari")
				offset = 640;
			if(i == "mozilla" && jQuery.browser.version.substr(0,3)=="1.8")
				offset = 650;
		});	*/
		
/*	jQuery.each(jQuery.browser, function(i, val) {
		$("<div>" + i + " : <span>" + val + "</span>").appendTo(document.body);
    });
*/		
		var cs = $("#case_study");
		var cs_id = $("#case_study").attr("class");
		
		$.ajax({
			url: "../getca.php?case_study=" + cs_id + "&ca_page=" + page,
			async: false,
			success: function(results,status) {
				// Hide the previous slide and show the new one
				if(parseInt(page) > pp) { // <<<<<<
					cs.animate({"left":"-=300px"},{queue:false}).animate({"opacity":"hide"},function() {
						cs.css({"left":"300px"}).html(results).animate({"left":"-="+offset+"px"},{queue:false}).animate({"opacity":"show"},updateControls(page));
					});
				} else if(parseInt(page) < pp) { // >>>>>>
					cs.animate({"left":"+=300px"},{queue:false}).animate({"opacity":"hide"},function() {
						cs.css({"left":"-"+offset+"px"}).html(results).animate({"left":"+=300px"},{queue:false}).animate({"opacity":"show"},updateControls(page));
					});
				}
				pp = page;
				// Update the visual aspect of the 'this page' indicator
				$("#case_study_navigation_pages a").each(function() {
					var th = $(this);
					if(parseInt(th.attr("id")) <= page) {
						th.animate({opacity:.3},100,function() {
							th.css({"background-color":"#a73ba0","color":"#fff"});
							th.animate({opacity:1},100);
						});
					} else
						th.css({"background-color":"#fff","color":"#ccc"});
				});
			},
			error: function (XMLHttpRequest, textStatus, errorThrown) {
				alert(textStatus);
			}
		})
	}
	// Once we've successfully pulled our Case Study page, update the
	// page / stage indicators
	function updateControls(page) {
		// Highlight appropriate stage. Get title of class from ThinkAdmin
		//alert($(".stage").html());
		var stage = $(".stage").attr("title");
		var si = $("span[class=" + stage + "]");
		if(stage != ps) {
			$("span[class=" + ps + "]").css("color","#ccc");
			si.animate({opacity:.3},100,function() {
				si.css("color","#a73ba0");
				si.animate({opacity:1},100);
			});
			ps = stage;
		}
		var sc = $("#cscount").attr("class"); // stage count
		// Add a Next or Prev button to our description block
		var np = parseInt(page) + 1;
		var pp = parseInt(page) - 1;	
		// Add [next] [prev] buttons to the body text as needed and
		// handle the Click of them -- pass to our page-slide function 
		//$(".case_study_text").append("<br /><p><a class=\"next\" href=\"#\" rel=\"" + np + "\"><img src=\"../images/b_next.png\" width=\"33\" height=\"11\" /></a></p>");
		$(".case_study_text").append("<br /><p>");
		if(parseInt(page) > 1)
			$(".case_study_text").append("<img src=\"../images/left.png\" width=\"5\" height=\"9\" /> <a class=\"next\" href=\"#\" rel=\"" + pp + "\"> Previous</a> &nbsp; &nbsp;");
		if(parseInt(page) < sc)
			$(".case_study_text").append(" <a class=\"next\" href=\"#\" rel=\"" + np + "\">Next</a> <img src=\"../images/right.png\" width=\"5\" height=\"9\" /></p>");
		$(".case_study_text a").click(function() {
			var t = $(this);
			var page = t.attr("rel");
			//var page = hr.substring(1,hr.length);
			get_ca_page(page);
		});
	}
	// =====================================================================
	// Any slider. Give it class 'jqslider' then name="1"
	// then a div of the text called id='jqslider_content1'
	// different number for different ones on the same page
	if($(".jqslider").length) {
		var sliderContent
		$(".jqslider").click(function() {
			var theLink = $(this);
		
			// CLIENT LIST -------------------------------------------------
			// close any open sliders and reset link color first
			$(".client_factsheets").slideUp("fast",function() {
				$("a.jqslider").css({"color":"#777","font-weight":"normal"});
			});
			// Slide out the hidden list of fact sheets
			$("#jqslider_content"+theLink.attr("name")).slideDown("fast",function(){
				theLink.css({"color":"#ff9100","font-weight":"bold"});
			});
			// -------------------------------------------------------------
		});
	}
	
	
	// PROCESS -------------------------------------------------
	// Display the four process buttons, handle rollovers and
	// displaying of the four hidden divs
	var lastProcessTab = 0;
	var lastProcessBG = 0;
	
	// LISTEN --------------------------------------------------
	$("#bp1").hover(function() {
		$("#process_header").css("background-position","0 -34px"); 
	},function(){ 
		$("#process_header").css("background-position","0 "+lastProcessBG); 
	});
	$("#bp1").click(function(e) {
		e.preventDefault();
		$("#p"+lastProcessTab).hide();
		$("#p1").slideDown("fast");
		lastProcessTab = 1;
		lastProcessBG = "-34px"
	});
	// THINK ---------------------------------------------------
	$("#bp2").hover(function() {
		$("#process_header").css("background-position","0 -68px"); 
	},function(){ 
		$("#process_header").css("background-position","0 "+lastProcessBG); 
	});
	$("#bp2").click(function(e) {
		e.preventDefault();
		$("#p"+lastProcessTab).hide();
		$("#p2").slideDown("fast");
		lastProcessTab = 2;
		lastProcessBG = "-68px"
	});
	// CREATE --------------------------------------------------
	$("#bp3").hover(function() {
		$("#process_header").css("background-position","0 -102px"); 
	},function(){ 
		//if(!("#p3").is(":hidden"))
		$("#process_header").css("background-position","0 "+lastProcessBG); 
	});
	$("#bp3").click(function(e) {
		e.preventDefault();
		$("#p"+lastProcessTab).hide();
		$("#p3").slideDown("fast");
		lastProcessTab = 3;
		lastProcessBG = "-102px"
	});
	// MANAGE --------------------------------------------------
	$("#bp4").hover(function() {
		$("#process_header").css("background-position","0 -136px"); 
	},function(){ 
		$("#process_header").css("background-position","0 "+lastProcessBG); 
	});
	$("#bp4").click(function(e) {
		e.preventDefault();
		$("#p"+lastProcessTab).hide();
		$("#p4").slideDown("fast");
		lastProcessTab = 4;
		lastProcessBG = "-136px"
	});


	$("#search_news_list").change(function() {
		location.href=$(this).val();
		//$("#search_news_form").submit();
	});
	
	// =====================================================================
	$(".nexttestimonial").click(function(e) {
		e.preventDefault();	// stop normal link click
		var cs = $("#testimonials");
		//var cs_count = $("#case_study_chooser .page_group").attr("id");
		//alert(cs_chooser_on_page + ' / ' + cs_count);
		//if(cs_chooser_on_page < cs_count)
			cs.animate({"left":"-=1100px"});
		//cs_chooser_on_page ++;
			
		// Display / Hide nav buttons
	/*	if(cs_chooser_on_page == cs_count)
			$(".nextprojectpage").fadeOut();//css("display","none");
		if(cs_chooser_on_page > 1)
			$(".prevprojectpage").fadeIn();//("display","block");	*/
	});
	$(".prevtestimonial").click(function(e) {
		e.preventDefault();	// stop normal link click
		var cs = $("#testimonials");
		//var cs_count = $("#case_study_chooser .page_group").attr("id");
		//if(cs_chooser_on_page > 1)
			cs.animate({"left":"+=1100px"});
		//cs_chooser_on_page --;

		// Display / Hide nav buttons
	/*	if(cs_chooser_on_page == 1)
			$(".prevprojectpage").fadeOut();//css("display","none");
		if(cs_chooser_on_page < cs_count)
			$(".nextprojectpage").fadeIn();//css("display","block");	*/

	});
	
	// =====================================================================
});

// *************************************************************************
function checkQT() {
	if (navigator.plugins) {
		for (i=0; i < navigator.plugins.length; i++ ) {
			if (navigator.plugins[i].name.indexOf("QuickTime") >= 0) {
				haveqt = true;
			}
		}
	}
	if ((navigator.appVersion.indexOf("Mac") > 0) && (navigator.appName.substring(0,9) == "Microsoft") && (parseInt(navigator.appVersion) < 5) ) {
		haveqt = true;
	}
}
// =========================================================================
// Delay Plugin for jQuery
// - http://www.evanbot.com
// - © 2008 Evan Byrne

jQuery.fn.delay = function(time,func){
	return this.each(function(){
		setTimeout(func,time);
	});
};

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

// *************************************************************************
