/* ########################################################################### *
/* ***** DOCUMENT INFO  ****************************************************** *
/* ########################################################################### *
 * ##### NAME:  global.js
 * ##### VERSION: v0.1
 * ##### UPDATED: 10/01/2011 (Markus Giesen - Deloitte's Online Practice)
/* ########################################################################### *

/* ########################################################################### *
/* ***** INDEX *************************************************************** *
/* ########################################################################### *
/* ##### GLOBAL VARIABLES
/* ##### INITIALISATION
/* ##### VISUAL INITIALISATION
/* ##### FUNCTIONAL INITIALISATION
/* ##### UTIL FUNCTIONS
/* ########################################################################### */

/* ########################################################################### *
/* ##### GLOBAL VARIABLES
/* ########################################################################### */

var STATIC_ANIMATION = false;
var BASIC_ANIMATION = false;

var TWITTER_API = "http://search.twitter.com/search.json";

/* ########################################################################### *
/* ##### INITIALISATION
/* ########################################################################### */

$(document).ready(function(){
	init_googleAnalytics(); 
	
	init_visual();
	init_functional();
});

/* ########################################################################### *
/* ##### VISUAL INITIALISATION
/* ########################################################################### */

function init_visual(){
	init_classHelpers();
	init_facebookApi();
	init_equalHeightGrid();
}

/* ########################################################################### *
/* ##### FUNCTIONAL INITIALISATION
/* ########################################################################### */

function init_functional(){
	init_links();
	init_tagFilters();
	init_imageInteraction();
	init_inlineFormValidation();
	init_rememberDetails();
	init_googleMaps();
	init_twitter();
}

/* ########################################################################### *
/* ##### CSS3 HELPER
/* ########################################################################### */

function init_classHelpers(){
	$("body").removeClass("noJS");
	
	if(isIE(6, true)){
		STATIC_ANIMATION = true;
		BASIC_ANIMATION = true;
		init_ie6_classes();
	} else if(isIE(7, true)){
		BASIC_ANIMATION = true;
		init_ie8_classes();	
	} else if(isIE(8, true)){
		BASIC_ANIMATION = true;
		init_ie8_classes();
	}
}

function init_ie6_classes(){
	init_ie8_classes();
	
	//list item
	$("li:first-child").addClass("first");
	
	//replacement for >
	$(".fn_childItems > li").addClass("childItem");
	
	$(".button, button").each(function(){
		var button = $(this);
		var hoverClass = "hover";
		
		if($(button).hasClass("primary")){
			hoverClass += " hover_primary";				
		} else if($(button).hasClass("secondary")){
			hoverClass += " hover_secondary";				
		} else if($(button).hasClass("tertiary")){
			hoverClass += " hover_tertiary";				
		} else if($(button).hasClass("search")){
			hoverClass += " hover_search";				
		}
		
		$(button).hover(function(){
			$(this).addClass(hoverClass);						
		}, function(){
			$(this).removeClass(hoverClass);
		});
	});
	
	$("div.columns > div:first-child, ul.columns > li:first-child").addClass("first");
	
	$("div.columns > div, ul.columns > li").addClass("column");
}

function init_ie8_classes(){
	$(".fn_jumpfix").css("position", "relative").append("<div style=\"position: absolute; zoom: 1;\">&nbsp;</div>");
	$(".fn_zoomfix").delay(100).css("zoom", "1");					
	
	//IE8 and IE7 both handle :first-child 
	//but don't support last-child
	
	//list item
	$("li:last-child").addClass("last");
	
	//table alt styles
	$("table tbody tr:even").each(function(){
		$(this).addClass("alt");
	});
	
	//IE cannot use CSS selectors 
	//a jQuery alternative is required
	$("div.columns > div:last-child, ul.columns > li:last-child").addClass("last");	
	
	$("#contentColumn .columns li:nth-child(3n+1)").addClass("left");
}

function init_facebookApi(){
	if($("#fb-root").length>0){
		window.fbAsyncInit = function() {
			FB.init({appId: '113253908728287', status: true, cookie: true,
					 xfbml: true});
		};
		(function() {
			var e = document.createElement('script'); e.async = true;
			e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
			document.getElementById('fb-root').appendChild(e);
		}());
	};
}

/* ########################################################################### *
/* ##### EQUAL HEIGHT GRID
/* ########################################################################### */

function init_equalHeightGrid(){
	$(".fn_equalHeights").each(function(){
		var maxHeight = 0;
		var list = $(this);
		
		$(list).find("li").each(function(){
			maxHeight = ($(this).height()>maxHeight) ? $(this).height() : maxHeight;
		});
		
		$(list).find("li").height(maxHeight);
		
	});
}

/* ########################################################################### *
/* ##### LINKS
/* ########################################################################### */

function init_links(){
	$("a[rel='external']").live("click", function(){
		var href = $(this).attr("href");
		
		if($(this).hasClass("fn_popup")){
			window.open(href, "Popup", "location=0,menubar=0,status=0,width=600,height=250");
		} else {
			window.open(href);
		}
		
		return false;										 
	});
}

/* ########################################################################### *
/* ##### TAGS
/* ########################################################################### */

function init_tagFilters(){
	$(".fn_tagFilters").each(function(){
		//Don't want fade animations on INIT, so we use this variable to check
		var TAGFILTERS_INIT = true;
		var TAGFILTERS_PAGETITLE = $("head title").html();
		var TAGFILTERS_GRID = true;
		var TAGFILTERS_NUMPERPAGE = 12;
		
		var TAGFILTERS_BASETAG = "";
		
		//Define areas that we are using multiple times
		var leftColumn = $(this).find("#leftColumn");
		var filterContainer = $(this);
		var filterItemList, filterItems, pagination;
		
		if($(filterContainer).find("#contentColumn ul.fn_tagFilters_list").length>0){
			filterItemList = $(filterContainer).find("#contentColumn ul.fn_tagFilters_list");
			filterItems = $(filterContainer).find("#contentColumn ul.fn_tagFilters_list > li");
			
			TAGFILTERS_GRID = false;
		} else {
			filterItemList = $(filterContainer).find("#contentColumn ul.fn_tagFilters_grid");
			filterItems = $(filterContainer).find("#contentColumn ul.fn_tagFilters_grid > li");
		}
		
		//Tags arrays (one for all tags, and one for unique tags only)
		var allTags = [];
		var uniqueTags = [];
		
		var tagCategoryLookup = new Lookup();
		
		//get the length of grid items
		var itemLength = $(filterItems).length;
		var maxHeight = 0;
		
		$(filterItems).each(function(){
			maxHeight = ($(this).height() > maxHeight) ? $(this).height() : maxHeight;
		});
		
		$(filterItems).each(function(){
			var filterItem = $(this);
			
			if(TAGFILTERS_GRID){
				$(filterItem).height(maxHeight+15);
			}
			
			//get the tags from the item, split them into an array
			var tags = $(filterItem).find(".tags");
			var formattedTags = $(tags).text().replace(/^\s*|\s*$/g,'');
			formattedTags = formattedTags.split(",");
				
			var thisTags = [];
			
			//push all tags on this item, into the global tags array
			for(var i in formattedTags){
				var tag = String(formattedTags[i]).replace(/^\s*|\s*$/g,'');
				
				if(tag!=""){
					var category = $(tags).find("span:contains('"+tag+"')").attr("class");
					if(category=="" || category==null || category==undefined){
						category = "default";	
					}
					
					tagCategoryLookup.addTag(tag, category);
					
					allTags.push(tag);
					thisTags.push(tag);
				}
			}
			
			//store the tags in data so it's quicker to access later
			$(filterItem).data("tags", thisTags);

		});
		
		//create a unique list of tags, and sort alphabetically
		uniqueTags = eliminateDuplicateTags(allTags);
		uniqueTags.sort();
		
		var categories = tagCategoryLookup.categories;
		
		//for each unique category create a UL	
		for(var j in categories){
			var category = categories[j];
			
			$(leftColumn).find(".fn_tagFilters_showAll_list").after("<ul class=\"fn_tagFilters_filters_"+category+"\"></ul>");
			var filterList = $(leftColumn).find("ul.fn_tagFilters_filters_"+category);
			
			var tags = tagCategoryLookup.getTagsOfCategory(category);
			tags.sort();
			
			//for each unique tag, in each category, add an LI
			for(var k in tags){
				var thisTag = tags[k];
				var fragment = thisTag.toLowerCase().replace(/\s|\//g, "-");
				
				$(filterList).append("<li><a href=\"#/"+fragment+"/\" rel=\"fragment\">"+thisTag+"</a></li>");	
			}
		}
		
		
		//sets the filterItem's display state (as filtered, or not) and fades out each item
		//this function is called in the onUrlFragmentChange function
		var setfilterItemDisplayState = function(filterItem, display, callback){
			//set display state data variable
			if(display){
				$(filterItem).data("filtered", true);
			} else {
				$(filterItem).data("filtered", false)
			}
			
			//if initial don't waste time by animating
			if(TAGFILTERS_INIT || STATIC_ANIMATION){
				$(filterItem).hide();
			
				if(callback!=null){
					callback();
				}
			} else {
				$(filterItem).stop().fadeOut(150);
			
				if(callback!=null){
					setTimeout(callback, 250);	
				}
			}
		}
		
		//the grid needs to remove padding-top on the top three, and padding-left on the left items
		//this function loops through each item, checks if it is to be displayed, sets the appropriate
		//classes to the grid item, and then fades it in.
		var updatefilterItemClasses = function(){
			var pageNumber = 0;
			var currentPageCounter = 0;
			var counter = 0;
			
			var currentPage = $(filterItems).data("currentPage");
			
			$(filterItems).each(function(){
				var filterItem = $(this);
				
				//we remove the "opacity" css top stop some animation artifacts from occurring
				$(filterItem).stop().hide().css("opacity", null);
				
				$(filterItem).removeClass("top").removeClass("left").removeClass("first").removeClass("last");
				
				//only update the counter and apply the classes to items that should be visible
				if($(filterItem).data("filtered")==true){
					currentPageCounter = (counter % TAGFILTERS_NUMPERPAGE == 0) ? 0 : currentPageCounter+1;
					
					if(TAGFILTERS_GRID){
						if(currentPageCounter<=2){
							$(filterItem).addClass("top");
						}
						
						if(currentPageCounter==0 || currentPageCounter % 3 == 0){
							$(filterItem).addClass("left");
						}
					} else {
						if(currentPageCounter==0){
							$(filterItem).addClass("first");	
						}
					}
					
					pageNumber = (counter % TAGFILTERS_NUMPERPAGE == 0) ? pageNumber+1 : pageNumber;
					
					if(currentPage==pageNumber){
						if(STATIC_ANIMATION){
							$(filterItem).stop().show();
						} else {
							$(filterItem).stop().fadeIn(150, function(){
								if(BASIC_ANIMATION){
									$(filterItem).css("filter", null);
								}
							});
						}
					} else {
						
					}
					
					counter++;
				}
			});
			
			var startNum = (currentPage * TAGFILTERS_NUMPERPAGE) - TAGFILTERS_NUMPERPAGE + 1;
			var endNum = startNum + TAGFILTERS_NUMPERPAGE - 1;
			
			endNum = (endNum > counter) ? counter : endNum;
			
			//Update pagination
			$(pagination).find("p").html(startNum+"&ndash;"+endNum+" of "+counter+" items");
			
			var baseTag = (TAGFILTERS_BASETAG=="") ? "#/" : "#/"+TAGFILTERS_BASETAG+"/";
			
			$(pagination).find("ul").html("");
			for(var i=1; i<=pageNumber; i++){
				var classes = "";
				
				if(currentPage==i){
					classes = " class=\"active\"";
				} else {
					classes = "";	
				}
				
				$(pagination).find("ul").append("<li"+classes+"><a href=\""+baseTag+i+"/"+"\" rel=\"fragment\">"+i+"</a></li>");
			}
			
			if(currentPage>1){
				$(pagination).find("ul").prepend("<li><a href=\""+baseTag+(currentPage-1)+"/"+"\" rel=\"fragment\">&laquo; Previous</a></li>");
			}
			
			if(currentPage<pageNumber){
				$(pagination).find("ul").append("<li><a href=\""+baseTag+(currentPage+1)+"/"+"\" rel=\"fragment\">Next &raquo;</a></li>");	
			}
			
			if(TAGFILTERS_GRID==false){
				$(filterContainer).find("#contentColumn ul.fn_tagFilters_list > li:visible:last").addClass("last");
			}
			
			if(TAGFILTERS_INIT){
				//init process has ended so remove
				TAGFILTERS_INIT = false;
				
				//set event listener for if the URL changes from now on
				SWFAddress.addEventListener(SWFAddressEvent.CHANGE, onUrlFragmentChange);
			}
		}
		
		//this event is called from the SWFAddress Event Listeners
		var onUrlFragmentChange = function(event){
			//event.pathNames is the fragment passed through by SWFAddress in array form (split by '/')
			var pathNames = event.pathNames;
			var thisTag = pathNames[0];
			var pageNum = 1;
			
			if(isNaN(thisTag)==false){
				thisTag = "";
				pageNum = Number(pathNames[0]);
			}
			
			if(pathNames.length>1){
				pageNum = Number(pathNames[1]);
			}
			
			//set the current page
			$(filterItems).data("currentPage", pageNum);
			
			//check the left column for a link with the href of the tag in the URL
			var tagLink = $(leftColumn).find("a[href$='#/"+thisTag+"/']");
			
			//if we can't find the tag in any of the links, we reset it to "Show all" instead
			if($(tagLink).length==0){
				thisTag = "";
				tagLink = $(leftColumn).find("a[href$='#']");
			}
			
			TAGFILTERS_BASETAG = thisTag;
			
			//remove the currently active class, and set the new tag to active
			$(leftColumn).find("li.active").removeClass("active");
			$(tagLink).parent().addClass("active");
			
			//we need to know the text of the link, because that's what we've saved
			//to the data object earlier
			tagText = $(tagLink).text();
			
			//update the page title
			if(thisTag==""){
				SWFAddress.setTitle(TAGFILTERS_PAGETITLE);
			} else {
				SWFAddress.setTitle(TAGFILTERS_PAGETITLE+" - "+tagText);	
			}
			
			$(filterItems).each(function(counter){
				var filterItem = $(this);
				
				var tags = $(filterItem).data("tags");
				var display = false;
				
				if(thisTag==""){
					//if this tag is blank, show all
					display = true;	
				} else {
					//if this filterItem has the current tag, it should be displayed
					for(var i in tags){
						if(tagText==tags[i]){
							display = true;
						}
					}
				}
				
				//if this filterItem is the last, run the callback
				if(counter==itemLength-1){
					setfilterItemDisplayState(filterItem, display, updatefilterItemClasses);
				} else {
					setfilterItemDisplayState(filterItem, display, null);	
				}
			});
		}
		
		//setup the initial classes on the items so we can get the appropriate height for the container
		$(filterItems).each(function(counter){
			var thisItem = $(this);
			
			$(thisItem).removeClass("top").removeClass("left").removeClass("first").removeClass("last");
			
			if(TAGFILTERS_GRID){
				if(counter<=2){
					$(thisItem).addClass("top");
				}
				
				if(counter==0 || counter % 3 == 0){
					$(thisItem).addClass("left");
				}
			} else {
				if(counter==0){
					$(thisItem).addClass("first");
				}
			}
			
			if(counter>11){
				$(thisItem).hide();	
			}
		});
		
		//set a fixed container height
		$(filterItemList).css("height", filterItemList.height());
		
		//create pagination controls
		$(filterItemList).after("<div class=\"pagination clearfix\"></div>");
		pagination = $(filterItemList).parent().find("div.pagination");
		
		$(pagination).html("<p>&nbsp;</p><ul></ul>");
		
		$(filterItems).data("currentPage", 1);
		
		//cancel all current animation, and hide all of the items
		$(filterItems).stop().hide();
		
		$("a[rel='fragment']").live("click", function(event){
			event.preventDefault();
			
			var href = $(this).attr("href");
			href = href.substring(href.indexOf("#")+1);
			
			ga_trackEvent(
				$("body h1").text(),
				"Filter Tags", 
				$(this).text()
			);
			
			SWFAddress.setValue(href);
			
			return false;									 
		});
		
		//setup the initial event handler for the SWFAddress, this fires straight away
		SWFAddress.addEventListener(SWFAddressEvent.INIT, onUrlFragmentChange);
	});
}

/* ########################################################################### *
/* ##### IMAGE INTERACTION
/* ########################################################################### */

function init_imageInteraction(){
	heroBanner_interaction();
	videoPlayer_interaction();
	imageTile_interaction();
}

function heroBanner_interaction(){
	$(".fn_heroBanner").each(function(){
		var container = $(this).find(".container");
		var bannersList = $(container).find(".banners ul");
		var numBanners = $(bannersList).find("li").length;
		var totalWidth = 0;
		
		//setup banner actions
		$(bannersList).find("li").each(function(){
			var banner = $(this);
			var href = $(banner).find(".caption a").attr("href");
			
			totalWidth += $(banner).width();
			
			$(banner).bind("click", function(){
				ga_trackEvent("Homepage Hero Banner", "Click", $(banner).find(".caption h2").text());
				
				window.location = href;	
				return false;							 
			});
			
			$(banner).hover(function(){
				$(banner).find("img").stop().fadeTo(250, 0.9);									 
			}, function(){
				$(banner).find("img").stop().fadeTo(250, 1);
			});
			
			$(banner).addClass("clickable");	
		});
		
		$(bannersList).width(totalWidth);
		
		if(numBanners>1){
			//add controls
			$(container).append("<a class='nav previous' href='#'>Previous Banner<span></span></a><a class='nav next' href='#'>Next Banner<span></span></a>");
			var buttons = $(container).find("a.nav");
			
			if(isIE(8, true)){
				$(buttons).stop().fadeTo(0, 0);
				
				$(buttons).hover(function(){
					$(this).stop().fadeTo(0, 1).css("filter", null);
				}, function(){
					$(this).stop().fadeTo(0, 0);
				});
			} else {
				$(buttons).stop().fadeTo(0, 0);
				
				$(buttons).hover(function(){
					$(this).stop().fadeTo(250, 1);
				}, function(){
					$(this).stop().fadeTo(250, 0);
				});
			}
			
			//setup container functions
			var animationSpeed = 1000;
			var autoAnimationTimeout = 7500;
			
			var currentIndex = 0;
			var bannerWidth = totalWidth/numBanners;
			
			var isAnimating = false;
			
			var isAutoAnimating = true;
			var autoAnimateTimer = null;
			
			$(container).bind("banner.next", function(){
				if(isAnimating==false){
					isAnimating = true;
					
					var readjust = false;
					var tempBanner;
					
					if(currentIndex == numBanners-1){
						//adjust banner position
						tempBanner = $(bannersList).find("li:first-child").clone();
						$(bannersList).width(totalWidth + bannerWidth);
						$(bannersList).append(tempBanner);
						
						readjust = true;
					}
					
					var nextPos = -(currentIndex + 1) * bannerWidth;
					
					$(bannersList).animate({"left": nextPos}, animationSpeed, function(){
						currentIndex++;
						
						if(readjust){
							currentIndex = 0;
							
							$(tempBanner).remove();
							$(bannersList).css("left", 0).width(totalWidth);	
						}
						
						if(isAutoAnimating){
							autoAnimate();	
						}
						
						isAnimating = false;
					});
				}
			});
			
			$(container).bind("banner.previous", function(){
				if(isAnimating==false){
					isAnimating = true;
					
					var readjust = false;
					var tempBanner;
					
					if(currentIndex == 0){
						//adjust banner position
						tempBanner = $(bannersList).find("li:last-child").clone();
						$(bannersList).width(totalWidth + bannerWidth);
						$(bannersList).prepend(tempBanner);
						$(bannersList).css("left",-bannerWidth);
						
						readjust = true;
					}
					
					var prevPos = (currentIndex==0) ? 0 : -(currentIndex - 1) * bannerWidth;
					
					$(bannersList).animate({"left": prevPos}, animationSpeed, function(){
						currentIndex--;
						
						if(readjust){
							currentIndex = numBanners-1;
							
							$(tempBanner).remove();
							$(bannersList).css("left", -(numBanners - 1) * bannerWidth).width(totalWidth);	
						}
						
						isAnimating = false;
					});
				}
			});
			
			var autoAnimate = function(){
				if(isAutoAnimating){
					autoAnimateTimer = setTimeout(function(){
						autoAnimateTimer = null;
						$(container).trigger("banner.next");
					}, autoAnimationTimeout);
				}
			}
			
			$(container).find("a.nav.next").bind("click", function(){
				isAutoAnimating = false;
				clearTimeout(autoAnimateTimer);
				
				$(container).trigger("banner.next");
				return false;
			});
			
			$(container).find("a.nav.previous").bind("click", function(){
				isAutoAnimating = false;
				clearTimeout(autoAnimateTimer);
				
				$(container).trigger("banner.previous");
				return false;
			});
			
			autoAnimate();
		}
	});
}

function videoPlayer_interaction(){
	//Banner to be used on the Case Study Pages
	$(".fn_videoBanner").each(function(){
		var banner = $(this).find(".container");
		
		if($(banner).find(".caption a").length > 0){
			var href = $(banner).find(".caption a").attr("href");
			var videoId = href.substr(href.lastIndexOf("/")+1);
			
			$(banner).bind("video.show", function(){
				
				$(banner).unbind('mouseenter mouseleave');
				$(banner).removeClass("clickable");
				$(banner).find("img, .caption").fadeOut(250, function(){
					$(banner).html("<div class='videoContainer fn_videoContainer'></div>");
					
					var videoContainer = $(banner).find(".fn_videoContainer");
					$(videoContainer).hide();
					
					/*var agent = navigator.userAgent.toLowerCase();
					var is_iphone = (agent.indexOf('iphone')!='-1');
					var is_ipad = (agent.indexOf('ipad')!='-1');
					var is_android = (agent.indexOf('android')!='-1');
					
					if (is_iphone || is_ipad || is_android) {
						$(videoContainer).html("<video src='http://www.vimeo.com/play_redirect?clip_id="+videoId+"&quality=mobile' controls='controls' width='691' height='389'></video>");
					} else {
						$(videoContainer).html("<object width='691' height='389'><param name='allowfullscreen' value='true' /><param name='allowscriptaccess' value='always' /><param name='movie' value='http://vimeo.com/moogaloop.swf?clip_id="+videoId+"&server=vimeo.com&show_title=0&show_byline=0&show_portrait=0&color=ffffff&fullscreen=1' /><embed src='http://vimeo.com/moogaloop.swf?clip_id="+videoId+"&server=vimeo.com&show_title=0&show_byline=0&show_portrait=0&color=ffffff&fullscreen=1' type='application/x-shockwave-flash' allowfullscreen='true' allowscriptaccess='always' width='691' height='389'></embed></object>");
					}*/
					
					$(videoContainer).html("<iframe src='http://player.vimeo.com/video/"+videoId+"?byline=0&amp;portrait=0&amp;autoplay=1' width='691' height='389' frameborder='0'></iframe>");
					
					$(banner).animate({height: "389px"}, 250, function(){
						$(videoContainer).show();
					});
					
				});
				
			});
			
			$(banner).find(".caption a").bind("click", function(){
				ga_trackEvent("Video Case Study", "Click", $("body").find("h1").text());
				
				$(banner).trigger("video.show");
				
				return false;
			});
			
			$(banner).bind("click", function(){
				ga_trackEvent("Video Case Study", "Click", $("body").find("h1").text());
				
				$(banner).trigger("video.show");
				
				return false;							 
			});
			
			$(banner).hover(function(){
				$(banner).find("img").stop().fadeTo(250, 0.9);									 
			}, function(){
				$(banner).find("img").stop().fadeTo(250, 1);
			});
			
			$(banner).addClass("clickable");
		}
	});
	
	//Inline Video Player for Article Pages
	$(".fn_videoPlayer").each(function(){
		var player = $(this);
		
		var href = $(player).find("a").attr("href");
		var videoId = href.substr(href.lastIndexOf("/")+1);
		
		var width = $(player).parents("#content").width();
		var height = Math.round(width * (9/16));
		
		$(player).html("<iframe src='http://player.vimeo.com/video/"+videoId+"?byline=0&amp;portrait=0&amp;autoplay=0' width='"+width+"' height='"+height+"' frameborder='0'></iframe>");
		
		$(player).addClass("videoPlayer");
	});
	
	//Inline Video Player for Article Pages (Youtube)
	$(".fn_youtubePlayer").each(function(){
		var player = $(this);
		
		var href = $(player).find("a").attr("href");
		var videoId = href.substr(href.lastIndexOf("=")+1);
		
		var width = $(player).parents("#content").width();
		var height = Math.round(width * (9/16)) + 30; //needs additional 30px due to controls height
		
		$(player).html("<iframe src='http://www.youtube.com/embed/"+videoId+"' width='"+width+"' height='"+height+"' frameborder='0'></iframe>");
		
		$(player).addClass("videoPlayer");
	});
}

function imageTile_interaction(){
	$(".fn_imageTile li").each(function(){
		var listItem = $(this);
		
		var linkItem = $(listItem).find("h2 a, h3 a")[0];
		
		var image = $(listItem).find("img");
		
		$(image).addClass("clickable").bind("click", function(){
			window.location = $(linkItem).attr("href");
			
			return false;											  
		});
		
		$(image).add(linkItem).hover(function(){
			$(image).stop().fadeTo(250, 0.85);
			$(linkItem).addClass("hover");
		}, function(){
			$(image).stop().fadeTo(250, 1);
			$(linkItem).removeClass("hover");
		});
	});
}

/* ########################################################################### *
/* ##### INLINE FORM VALIDATION
/* ########################################################################### */

function init_inlineFormValidation(){
	/* Form Validation Script */
	if($("#form.fn_inlineValidation").length>0){
		$("#form.fn_inlineValidation").each(function(){
			var form = $(this);
			var currentErrors = "";
			
			$(form).find("input[type='text'], select, textarea").each(function(){
				$(this).blur(function(){
					isFormFieldValid(this, false);
				});
			});
			
			$(form).find("input[type='checkbox'], input[type='radio']").each(function(){
				$(this).bind("change", function(){
					isFormFieldValid(this, false);
				});
			});
			

			$(form).find("input[type='submit'], button[type='submit']").unbind("click").bind("click", function(e){
				if(checkFormValidation($(form))){
					return true;
				} else {
					//display error box
					$(form).find("div.success").remove();
					
					if($(form).find("div.errors").length>0){
						$(form).find("div.errors ul").remove();
					} else {
						$(form).prepend("<div class=\"errors\" style=\"display:none\"><p>The following requires your attention before proceeding:</p></div>");
					}
					
					$(form).find("div.errors").attr("id", "formErrors").append(currentErrors).fadeIn(250, function(){
						if(BASIC_ANIMATION){
							$(form).find("div.errors").css("filter", null);
						}
					});
					 
					$('html,body').animate({
						scrollTop: $(form).offset().top-50
					}, 250); 
				}
				
				return false;
			});
			
			var checkFormValidation = function(form){
				var isValid = true;
				
				currentErrors = "";
				
				//Check field validation of elements that are NOT disabled
				$(form).find(".fn_valid_mandatory:not(:disabled), .fn_valid_email:not(:disabled)").each(function(){
					fieldValid = isFormFieldValid(this, true);
					
					if(!fieldValid&&isValid){
						isValid = false;	
					}
				});
				
				currentErrors = "<ul>" + currentErrors + "</ul>";
				
				return isValid;
			}
			
			var isFormFieldValid = function(field, onSubmit){
				var control = $(field);
				var controlHolder = $(field).parents(".ctrlHolder");
				var label = $(controlHolder).find("label, .label")[0];
				label = $(label).text();
				label = label.replace("*", "");
				
				var controlId = $(control).attr("id");
				
				var isValid = true;
				var tagName = field.tagName;
				
				if($(control).attr("type")=="radio"||$(control).attr("type")=="checkbox"){
					tagName = "DIV";
					control = $(field).parents(".optionHolder");
				}
				
				var errorMessage = "Please enter "+label;
				
				if($(controlHolder).hasClass("hidden")==true||$(control).attr("disabled")==true){
					//skip this field
				} else {
					if($(control).hasClass("fn_valid_mandatory")){
						if(tagName=="INPUT"){
							if($(control).val()==""){
								errorMessage = "Please enter a value";
								isValid = false;	
							}
							
							if($(control).hasClass("fn_hint")){
								if($(control).val()==$(control).data("hintText")){
									errorMessage = "Please enter a value";
									isValid = false;	
								}	
							}
						} else if(tagName=="TEXTAREA"){
							if($(control).val()==""){
								errorMessage = "Please enter text";
								isValid = false;	
							}
						} else if(tagName=="SELECT"){
							if($(control).find("option:selected").val()==""||$(control).find("option:selected").val()=="null"){
								errorMessage = "Please select an option";
								isValid = false;	
							}
						} else if(tagName=="DIV"){
							if($(control).find("input:checked").length<1){
								var firstControl = $(control).find("input:first")[0];
								controlId = $(firstControl).attr("id");
								
								if($(firstControl).attr("type")=="checkbox"){
									errorMessage = "Please select at least one option";
								} else {
									errorMessage = "Please select an option";
								}
								
								isValid = false;	
							}
						}
					}
					
					if($(control).hasClass("fn_valid_email")){
						var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
						if(emailReg.test($(control).val())==false){
							errorMessage = "Please enter a valid email address";
							isValid = false;	
						}
					}
				}
				
				if(isValid==false){
					$(controlHolder).addClass("error");
					
					if($(controlHolder).find(".inlineError").length<1){
						if($(controlHolder).find(".inlineHint").length>0){
							$(controlHolder).find(".inlineHint").before("<div class=\"inlineError\" style=\"display: none\"></div>");
						} else {
							$(controlHolder).append("<div class=\"inlineError\" style=\"display: none\"></div>");
						}
					}
					
					if(STATIC_ANIMATION){
						$(controlHolder).find(".inlineError").show().html(errorMessage);
					} else {
						$(controlHolder).find(".inlineError").animate({"opacity": 0}, 0).html(errorMessage).slideDown(250, function(){
							$(controlHolder).find(".inlineError").animate({"opacity": 1}, 250, function(){
								$(controlHolder).css("filter", "none");																			
							});
						});
					}
				} else {
					$(controlHolder).removeClass("error");
					
					if($(controlHolder).find(".inlineError").length>0){
						if(STATIC_ANIMATION){
							$(controlHolder).find(".inlineError").html("").hide();
						} else {
							$(controlHolder).find(".inlineError").animate({"opacity": 0}, 250, function(){
								$(controlHolder).find(".inlineError").slideUp(250, function(){
									$(controlHolder).find(".inlineError").html("");													
								});
							});
						}
					}
				}
				
				if(onSubmit && isValid==false){
					currentErrors += "<li><a href=\"#"+controlId+"\">"+label+"</a>: "+errorMessage+"</li>";
				}
				
				return isValid;
			}
		});
	}
	
	$(".fn_hint").each(function(i){
		$(this).data("hintText", $(this).attr("title"));
		
		if($(this).val()==""){
			$(this).val($(this).data("hintText"));	
		}
		
		$(this).focusin(function(){
			if ($(this).val() == $(this).data("hintText")) {
				$(this).val("");
			}
		}).focusout(function(){
			if ($.trim($(this).val()) == "") {
				$(this).val($(this).data("hintText"));
			}
		});
	});
}

/* ########################################################################### *
/* ##### REMEMBER DETAILS
/* ########################################################################### */

function init_rememberDetails(){
	$("#form.fn_rememberDetails").each(function(){
		var form = $(this);
		
		var rememberedDetails = $.cookie('dop_rememberedDetails');
		
		if(rememberedDetails!=null){
			var fields = rememberedDetails.split('&');
			
			$(form).find("input[type='checkbox'].fn_rememberDetails").attr("checked", "checked");
			
			for(var i in fields){
				var value = fields[i].split('=');
				
				$(form).find("input[name='"+unescape(value[0])+"']").val(unescape(value[1]));
			}
		}
		
		$(form).bind("submit", function(e){
			//Only if the rememberDetails checkbox is checked
			if($(form).find("input[type='checkbox'].fn_rememberDetails:checked").length>0){
				//store form information for input fields (we don't need the textarea)
				var details = $(form).find("input").serialize();
				//write cookie
				$.cookie('dop_rememberedDetails', details);
			}
		});
	});
}

/* ########################################################################### *
/* ##### GOOGLE MAPS
/* ########################################################################### */

function init_googleMaps(){
	$(".fn_officeMap").each(function(){
		var mapContainer = $(this);
		
		var mapId = $(mapContainer).parents("li").find("h2").text().toLowerCase()
		$(mapContainer).attr("id", mapId);
	
		var mapData = $(mapContainer).find("ul.mapDetails");
		var details = {};
		details.lat = $(mapData).find("li.lat").text();
		details.lng = $(mapData).find("li.lng").text();
		details.title = $(mapData).find("li.title").text();
		details.icon = $(mapData).find("li.icon").text();
		
		// Google Maps
		var latlng = new google.maps.LatLng(details.lat, details.lng);
		var myOptions = {
		  zoom: 17,
		  center: latlng,
		  mapTypeId: google.maps.MapTypeId.SATELLITE
		};
		var map = new google.maps.Map(document.getElementById(mapId), myOptions);
		
		var marker = new google.maps.Marker({
		  position: latlng, 
		  map: map, 
		  title: details.title,
		  icon: details.icon
	  	});
	});
}

/* ########################################################################### *
/* ##### TWITTER DISPLAY
/* ########################################################################### */

function init_twitter(){
	if($(".fn_twitter").length>0){
		$(".fn_twitter").each(function(){
			var container = $(this);
			var searchTerm = $(container).find(".fn_twitter_searchTerm").text();
			
			var post = $(container).find("p:not(.date, .hidden)");
			var date = $(container).find("p.date");
			
			$(post).hide();
			$(date).hide();
			
			var formatPost = function(raw){
				var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
				raw = raw.replace(exp, "<a href='$1' rel='external'>$1</a>");
				var exp = /[\@]+([A-Za-z0-9-_]+)/ig;
				raw = raw.replace(exp, "<a href='http://search.twitter.com/search?q=from%3A$1' rel='external'>@$1</a>");
				var exp = /[\#]+([A-Za-z0-9-_]+)/ig;
				raw = raw.replace(exp, "<a href='http://search.twitter.com/search?q=%23$1' rel='external'>#$1</a>");
				
				return raw;
			}
			
			var getDateString = function(timeBetween, interval, text) {
				var time = Math.round(timeBetween / interval) + " " + text;
				var timeString = time;
				if (time !=  1  ) {
				   timeString = timeString + "s";
			  	}
			
			   	return timeString;
			}
			
			var formatTwitterDate = function(created_at) {
				var one_sec = 1000;
			
				var one_min = one_sec * 60;
			
				var one_hr = one_min * 60;
			
				var one_day = 1000 * 60 * 60 * 24;
			
				var tweetDate = new Date(created_at);
			
				var date = new Date();
			
				//time in milliseconds
				var timeBetween = (date - tweetDate);
			
				var timeString = "";
			
				if (timeBetween > one_day) {
					timeString = getDateString(timeBetween, one_day, "day");
				}
				else if (timeBetween > one_hr) {
					timeString = getDateString(timeBetween, one_hr, "hour");
				}
				else if (timeBetween > one_min) {
					timeString = getDateString(timeBetween, one_min, "minute");
				}
				else {
					timeString = getDateString(timeBetween, one_sec, "second");
				}
			
				return timeString;
			}
			
			$.ajax({
				url: TWITTER_API,
				type: "GET",
				data: ({
					q: searchTerm,
					result_type: "recent",
					rpp: 1
				}),
				success: function(json){
					$(post).html(formatPost(json.results[0].text));
					$(date).html(formatTwitterDate(json.results[0].created_at)+" ago");
					
					if(BASIC_ANIMATION){
						$(post).add(date).show();
					} else {
						$(post).fadeIn(250, function(){
							$(date).fadeIn(250, function(){
								
							});							 
						});
					}
					
				},
				error: function(){
					$(post).html("Sorry, we are unable to contact the twitter search page...");
					$(date).html("0 seconds ago");
					
					if(BASIC_ANIMATION){
						$(post).add(date).show();
					} else {
						$(post).fadeIn(250, function(){
							$(date).fadeIn(250, function(){
								
							});							 
						});
					}
				},
				dataType: "jsonp",
				timeout: 1000
			})
			
		});
	}
}

function init_googleAnalytics(){
	ga_init_eventTracking();
}

function ga_init_eventTracking(){
	//share links
	$(".module.share ul.linksList li a").bind("click", function(){
		ga_trackEvent("Share", "Click", $(this).text());
		return true;
	});
}

function ga_trackEvent(category, action, label){
	if(_gaq){
		_gaq.push(["_trackEvent", category, action, label]);	
	}
}

/* ########################################################################### *
/* ##### UTIL FUNCTIONS
/* ########################################################################### */

function isIE(version, lessThan){
	version = (version==undefined) ? 6 : version;
	lessThan = (lessThan==undefined) ? false : lessThan;
	
	if(lessThan){
		if (($.browser.msie)&&(parseInt($.browser.version)<=version)){
			return true;
		}
	} else {
		if (($.browser.msie)&&(parseInt($.browser.version)==version)){
			return true;
		}
	}
	
	return false;	
}

//Returns an array without duplicates
function eliminateDuplicateTags(arr) {
  var i, len=arr.length, out=[], obj={};

  for (i=0;i<len;i++) {
    obj[arr[i]]=0;
  }
  for (i in obj) {
    out.push(i);
  }
  return out;
}

jQuery.log = jQuery.fn.log = function (msg) {  
      if (console){  
         console.log("%s: %o", msg, this);  
      }  
      return this;  
};

jQuery.fn.outerHTML = function(s) {
	return (s) ? this.before(s).remove() : jQuery("<p>").append(this.eq(0).clone()).html();
}


//******************************************************************************
//* Lookup Object
//******************************************************************************

// Create the Lookup function, with a data property, containing the categories
// and tags and a categories property, containing a list of all categories.
function Lookup() {
	this.data = {};
	this.categories = [];
};

// Add a tag to a category.
Lookup.prototype.addTag = function(tag, category) {
	// If the category does not exist, create it, with a tag property.
	if (this.data[category]) {
	} else {
		this.categories.push(category);
		this.data[category] = {};
		this.data[category].tags = [];
	};

	// Add the tag to the category.
	this.data[category].tags.push(tag);
};

// Get the *first* category that a tag appears in.
Lookup.prototype.getCategoryOfTag = function(tag) {
	// Iterate through the master list of categories.
	for (var i = 0, n = this.categories.length; i < n; i++) {
		// Iterate through the tags for each category in the master list.
		for (var j = 0, o = this.data[this.categories[i]].tags.length; j < o; j++) {
			// If the tag is the same value and type as that requested, return
			// the category.
			if (this.data[this.categories[i]].tags[j] === tag) {
				return this.categories[i];
			}
		}
	}
};

// Get all unique tags in a category, if a category exists, otherwise return
// nothing, i.e. will be undefined.
Lookup.prototype.getTagsOfCategory = function(category) {
	if (this.data[category]) {
		return eliminateDuplicateTags(this.data[category].tags);
	};
};


/* ########################################################################### *
/* ##### PLUGINS
/* ########################################################################### */

/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

/**
 * SWFAddress 2.4: Deep linking for Flash and Ajax <http://www.asual.com/swfaddress/>
 *
 * SWFAddress is (c) 2006-2009 Rostislav Hristov and contributors
 * This software is released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
 *
 */
if(typeof asual=="undefined"){var asual={}}if(typeof asual.util=="undefined"){asual.util={}}asual.util.Browser=new function(){var b=navigator.userAgent.toLowerCase(),a=/webkit/.test(b),e=/opera/.test(b),c=/msie/.test(b)&&!/opera/.test(b),d=/mozilla/.test(b)&&!/(compatible|webkit)/.test(b),f=parseFloat(c?b.substr(b.indexOf("msie")+4):(b.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/)||[0,"0"])[1]);this.toString=function(){return"[class Browser]"};this.getVersion=function(){return f};this.isMSIE=function(){return c};this.isSafari=function(){return a};this.isOpera=function(){return e};this.isMozilla=function(){return d}};asual.util.Events=new function(){var c="DOMContentLoaded",j="onstop",k=window,h=document,b=[],a=asual.util,e=a.Browser,d=e.isMSIE(),g=e.isSafari();this.toString=function(){return"[class Events]"};this.addListener=function(n,l,m){b.push({o:n,t:l,l:m});if(!(l==c&&(d||g))){if(n.addEventListener){n.addEventListener(l,m,false)}else{if(n.attachEvent){n.attachEvent("on"+l,m)}}}};this.removeListener=function(p,m,n){for(var l=0,o;o=b[l];l++){if(o.o==p&&o.t==m&&o.l==n){b.splice(l,1);break}}if(!(m==c&&(d||g))){if(p.removeEventListener){p.removeEventListener(m,n,false)}else{if(p.detachEvent){p.detachEvent("on"+m,n)}}}};var i=function(){for(var m=0,l;l=b[m];m++){if(l.t!=c){a.Events.removeListener(l.o,l.t,l.l)}}};var f=function(){if(h.readyState=="interactive"){function l(){h.detachEvent(j,l);i()}h.attachEvent(j,l);k.setTimeout(function(){h.detachEvent(j,l)},0)}};if(d||g){(function(){try{if((d&&h.body)||!/loaded|complete/.test(h.readyState)){h.documentElement.doScroll("left")}}catch(m){return setTimeout(arguments.callee,0)}for(var l=0,m;m=b[l];l++){if(m.t==c){m.l.call(null)}}})()}if(d){k.attachEvent("onbeforeunload",f)}this.addListener(k,"unload",i)};asual.util.Functions=new function(){this.toString=function(){return"[class Functions]"};this.bind=function(f,b,e){for(var c=2,d,a=[];d=arguments[c];c++){a.push(d)}return function(){return f.apply(b,a)}}};var SWFAddressEvent=function(d){this.toString=function(){return"[object SWFAddressEvent]"};this.type=d;this.target=[SWFAddress][0];this.value=SWFAddress.getValue();this.path=SWFAddress.getPath();this.pathNames=SWFAddress.getPathNames();this.parameters={};var c=SWFAddress.getParameterNames();for(var b=0,a=c.length;b<a;b++){this.parameters[c[b]]=SWFAddress.getParameter(c[b])}this.parameterNames=c};SWFAddressEvent.INIT="init";SWFAddressEvent.CHANGE="change";SWFAddressEvent.INTERNAL_CHANGE="internalChange";SWFAddressEvent.EXTERNAL_CHANGE="externalChange";var SWFAddress=new function(){var _getHash=function(){var index=_l.href.indexOf("#");return index!=-1?_ec(_dc(_l.href.substr(index+1))):""};var _getWindow=function(){try{top.document;return top}catch(e){return window}};var _strictCheck=function(value,force){if(_opts.strict){value=force?(value.substr(0,1)!="/"?"/"+value:value):(value==""?"/":value)}return value};var _ieLocal=function(value,direction){return(_msie&&_l.protocol=="file:")?(direction?_value.replace(/\?/,"%3F"):_value.replace(/%253F/,"?")):value};var _searchScript=function(el){if(el.childNodes){for(var i=0,l=el.childNodes.length,s;i<l;i++){if(el.childNodes[i].src){_url=String(el.childNodes[i].src)}if(s=_searchScript(el.childNodes[i])){return s}}}};var _titleCheck=function(){if(_d.title!=_title&&_d.title.indexOf("#")!=-1){_d.title=_title}};var _listen=function(){if(!_silent){var hash=_getHash();var diff=!(_value==hash);if(_safari&&_version<523){if(_length!=_h.length){_length=_h.length;if(typeof _stack[_length-1]!=UNDEFINED){_value=_stack[_length-1]}_update.call(this,false)}}else{if(_msie&&diff){if(_version<7){_l.reload()}else{this.setValue(hash)}}else{if(diff){_value=hash;_update.call(this,false)}}}if(_msie){_titleCheck.call(this)}}};var _bodyClick=function(e){if(_popup.length>0){var popup=window.open(_popup[0],_popup[1],eval(_popup[2]));if(typeof _popup[3]!=UNDEFINED){eval(_popup[3])}}_popup=[]};var _swfChange=function(){for(var i=0,id,obj,value=SWFAddress.getValue(),setter="setSWFAddressValue";id=_ids[i];i++){obj=document.getElementById(id);if(obj){if(obj.parentNode&&typeof obj.parentNode.so!=UNDEFINED){obj.parentNode.so.call(setter,value)}else{if(!(obj&&typeof obj[setter]!=UNDEFINED)){var objects=obj.getElementsByTagName("object");var embeds=obj.getElementsByTagName("embed");obj=((objects[0]&&typeof objects[0][setter]!=UNDEFINED)?objects[0]:((embeds[0]&&typeof embeds[0][setter]!=UNDEFINED)?embeds[0]:null))}if(obj){obj[setter](value)}}}else{if(obj=document[id]){if(typeof obj[setter]!=UNDEFINED){obj[setter](value)}}}}};var _jsDispatch=function(type){this.dispatchEvent(new SWFAddressEvent(type));type=type.substr(0,1).toUpperCase()+type.substr(1);if(typeof this["on"+type]==FUNCTION){this["on"+type]()}};var _jsInit=function(){if(_util.Browser.isSafari()){_d.body.addEventListener("click",_bodyClick)}_jsDispatch.call(this,"init")};var _jsChange=function(){_swfChange();_jsDispatch.call(this,"change")};var _update=function(internal){_jsChange.call(this);if(internal){_jsDispatch.call(this,"internalChange")}else{_jsDispatch.call(this,"externalChange")}_st(_functions.bind(_track,this),10)};var _track=function(){var value=(_l.pathname+(/\/$/.test(_l.pathname)?"":"/")+this.getValue()).replace(/\/\//,"/").replace(/^\/$/,"");var fn=_t[_opts.tracker];if(typeof fn==FUNCTION){fn(value)}else{if(typeof _t.pageTracker!=UNDEFINED&&typeof _t.pageTracker._trackPageview==FUNCTION){_t.pageTracker._trackPageview(value)}else{if(typeof _t.urchinTracker==FUNCTION){_t.urchinTracker(value)}}}};var _htmlWrite=function(){var doc=_frame.contentWindow.document;doc.open();doc.write("<html><head><title>"+_d.title+"</title><script>var "+ID+' = "'+_getHash()+'";<\/script></head></html>');doc.close()};var _htmlLoad=function(){var win=_frame.contentWindow;var src=win.location.href;_value=(typeof win[ID]!=UNDEFINED?win[ID]:"");if(_value!=_getHash()){_update.call(SWFAddress,false);_l.hash=_ieLocal(_value,TRUE)}};var _load=function(){if(!_loaded){_loaded=TRUE;if(_msie&&_version<8){var frameset=_d.getElementsByTagName("frameset")[0];_frame=_d.createElement((frameset?"":"i")+"frame");if(frameset){frameset.insertAdjacentElement("beforeEnd",_frame);frameset[frameset.cols?"cols":"rows"]+=",0";_frame.src="javascript:false";_frame.noResize=true;_frame.frameBorder=_frame.frameSpacing=0}else{_frame.src="javascript:false";_frame.style.display="none";_d.body.insertAdjacentElement("afterBegin",_frame)}_st(function(){_events.addListener(_frame,"load",_htmlLoad);if(typeof _frame.contentWindow[ID]==UNDEFINED){_htmlWrite()}},50)}else{if(_safari){if(_version<418){_d.body.innerHTML+='<form id="'+ID+'" style="position:absolute;top:-9999px;" method="get"></form>';_form=_d.getElementById(ID)}if(typeof _l[ID]==UNDEFINED){_l[ID]={}}if(typeof _l[ID][_l.pathname]!=UNDEFINED){_stack=_l[ID][_l.pathname].split(",")}}}_st(_functions.bind(function(){_jsInit.call(this);_jsChange.call(this);_track.call(this)},this),1);if(_msie&&_version>=8){_d.body.onhashchange=_functions.bind(_listen,this);_si(_functions.bind(_titleCheck,this),50)}else{_si(_functions.bind(_listen,this),50)}}};var ID="swfaddress",FUNCTION="function",UNDEFINED="undefined",TRUE=true,FALSE=false,_util=asual.util,_browser=_util.Browser,_events=_util.Events,_functions=_util.Functions,_version=_browser.getVersion(),_msie=_browser.isMSIE(),_mozilla=_browser.isMozilla(),_opera=_browser.isOpera(),_safari=_browser.isSafari(),_supported=FALSE,_t=_getWindow(),_d=_t.document,_h=_t.history,_l=_t.location,_si=setInterval,_st=setTimeout,_dc=decodeURI,_ec=encodeURI,_frame,_form,_url,_title=_d.title,_length=_h.length,_silent=FALSE,_loaded=FALSE,_justset=TRUE,_juststart=TRUE,_ref=this,_stack=[],_ids=[],_popup=[],_listeners={},_value=_getHash(),_opts={history:TRUE,strict:TRUE};if(_msie&&_d.documentMode&&_d.documentMode!=_version){_version=_d.documentMode!=8?7:8}_supported=(_mozilla&&_version>=1)||(_msie&&_version>=6)||(_opera&&_version>=9.5)||(_safari&&_version>=312);if(_supported){if(_opera){history.navigationMode="compatible"}for(var i=1;i<_length;i++){_stack.push("")}_stack.push(_getHash());if(_msie&&_l.hash!=_getHash()){_l.hash="#"+_ieLocal(_getHash(),TRUE)}_searchScript(document);var _qi=_url?_url.indexOf("?"):-1;if(_qi!=-1){var param,params=_url.substr(_qi+1).split("&");for(var i=0,p;p=params[i];i++){param=p.split("=");if(/^(history|strict)$/.test(param[0])){_opts[param[0]]=(isNaN(param[1])?/^(true|yes)$/i.test(param[1]):(parseInt(param[1])!=0))}if(/^tracker$/.test(param[0])){_opts[param[0]]=param[1]}}}if(_msie){_titleCheck.call(this)}if(window==_t){_events.addListener(document,"DOMContentLoaded",_functions.bind(_load,this))}_events.addListener(_t,"load",_functions.bind(_load,this))}else{if((!_supported&&_l.href.indexOf("#")!=-1)||(_safari&&_version<418&&_l.href.indexOf("#")!=-1&&_l.search!="")){_d.open();_d.write('<html><head><meta http-equiv="refresh" content="0;url='+_l.href.substr(0,_l.href.indexOf("#"))+'" /></head></html>');_d.close()}else{_track()}}this.toString=function(){return"[class SWFAddress]"};this.back=function(){_h.back()};this.forward=function(){_h.forward()};this.up=function(){var path=this.getPath();this.setValue(path.substr(0,path.lastIndexOf("/",path.length-2)+(path.substr(path.length-1)=="/"?1:0)))};this.go=function(delta){_h.go(delta)};this.href=function(url,target){target=typeof target!=UNDEFINED?target:"_self";if(target=="_self"){self.location.href=url}else{if(target=="_top"){_l.href=url}else{if(target=="_blank"){window.open(url)}else{_t.frames[target].location.href=url}}}};this.popup=function(url,name,options,handler){try{var popup=window.open(url,name,eval(options));if(typeof handler!=UNDEFINED){eval(handler)}}catch(ex){}_popup=arguments};this.getIds=function(){return _ids};this.getId=function(index){return _ids[0]};this.setId=function(id){_ids[0]=id};this.addId=function(id){this.removeId(id);_ids.push(id)};this.removeId=function(id){for(var i=0;i<_ids.length;i++){if(id==_ids[i]){_ids.splice(i,1);break}}};this.addEventListener=function(type,listener){if(typeof _listeners[type]==UNDEFINED){_listeners[type]=[]}_listeners[type].push(listener)};this.removeEventListener=function(type,listener){if(typeof _listeners[type]!=UNDEFINED){for(var i=0,l;l=_listeners[type][i];i++){if(l==listener){break}}_listeners[type].splice(i,1)}};this.dispatchEvent=function(event){if(this.hasEventListener(event.type)){event.target=this;for(var i=0,l;l=_listeners[event.type][i];i++){l(event)}return TRUE}return FALSE};this.hasEventListener=function(type){return(typeof _listeners[type]!=UNDEFINED&&_listeners[type].length>0)};this.getBaseURL=function(){var url=_l.href;if(url.indexOf("#")!=-1){url=url.substr(0,url.indexOf("#"))}if(url.substr(url.length-1)=="/"){url=url.substr(0,url.length-1)}return url};this.getStrict=function(){return _opts.strict};this.setStrict=function(strict){_opts.strict=strict};this.getHistory=function(){return _opts.history};this.setHistory=function(history){_opts.history=history};this.getTracker=function(){return _opts.tracker};this.setTracker=function(tracker){_opts.tracker=tracker};this.getTitle=function(){return _d.title};this.setTitle=function(title){if(!_supported){return null}if(typeof title==UNDEFINED){return}if(title=="null"){title=""}title=_dc(title);_st(function(){_title=_d.title=title;if(_juststart&&_frame&&_frame.contentWindow&&_frame.contentWindow.document){_frame.contentWindow.document.title=title;_juststart=FALSE}if(!_justset&&_mozilla){_l.replace(_l.href.indexOf("#")!=-1?_l.href:_l.href+"#")}_justset=FALSE},10)};this.getStatus=function(){return _t.status};this.setStatus=function(status){if(!_supported){return null}if(typeof status==UNDEFINED){return}if(status=="null"){status=""}status=_dc(status);if(!_safari){status=_strictCheck((status!="null")?status:"",TRUE);if(status=="/"){status=""}if(!(/http(s)?:\/\//.test(status))){var index=_l.href.indexOf("#");status=(index==-1?_l.href:_l.href.substr(0,index))+"#"+status}_t.status=status}};this.resetStatus=function(){_t.status=""};this.getValue=function(){if(!_supported){return null}return _dc(_strictCheck(_ieLocal(_value,FALSE),FALSE))};this.setValue=function(value){if(!_supported){return null}if(typeof value==UNDEFINED){return}if(value=="null"){value=""}value=_ec(_dc(_strictCheck(value,TRUE)));if(value=="/"){value=""}if(_value==value){return}_justset=TRUE;_value=value;_silent=TRUE;_update.call(SWFAddress,true);_stack[_h.length]=_value;if(_safari){if(_opts.history){_l[ID][_l.pathname]=_stack.toString();_length=_h.length+1;if(_version<418){if(_l.search==""){_form.action="#"+_value;_form.submit()}}else{if(_version<523||_value==""){var evt=_d.createEvent("MouseEvents");evt.initEvent("click",TRUE,TRUE);var anchor=_d.createElement("a");anchor.href="#"+_value;anchor.dispatchEvent(evt)}else{_l.hash="#"+_value}}}else{_l.replace("#"+_value)}}else{if(_value!=_getHash()){if(_opts.history){_l.hash="#"+_dc(_ieLocal(_value,TRUE))}else{_l.replace("#"+_dc(_value))}}}if((_msie&&_version<8)&&_opts.history){_st(_htmlWrite,50)}if(_safari){_st(function(){_silent=FALSE},1)}else{_silent=FALSE}};this.getPath=function(){var value=this.getValue();if(value.indexOf("?")!=-1){return value.split("?")[0]}else{if(value.indexOf("#")!=-1){return value.split("#")[0]}else{return value}}};this.getPathNames=function(){var path=this.getPath(),names=path.split("/");if(path.substr(0,1)=="/"||path.length==0){names.splice(0,1)}if(path.substr(path.length-1,1)=="/"){names.splice(names.length-1,1)}return names};this.getQueryString=function(){var value=this.getValue(),index=value.indexOf("?");if(index!=-1&&index<value.length){return value.substr(index+1)}};this.getParameter=function(param){var value=this.getValue();var index=value.indexOf("?");if(index!=-1){value=value.substr(index+1);var p,params=value.split("&"),i=params.length,r=[];while(i--){p=params[i].split("=");if(p[0]==param){r.push(p[1])}}if(r.length!=0){return r.length!=1?r:r[0]}}};this.getParameterNames=function(){var value=this.getValue();var index=value.indexOf("?");var names=[];if(index!=-1){value=value.substr(index+1);if(value!=""&&value.indexOf("=")!=-1){var params=value.split("&"),i=0;while(i<params.length){names.push(params[i].split("=")[0]);i++}}}return names};this.onInit=null;this.onChange=null;this.onInternalChange=null;this.onExternalChange=null;(function(){var _args;if(typeof FlashObject!=UNDEFINED){SWFObject=FlashObject}if(typeof SWFObject!=UNDEFINED&&SWFObject.prototype&&SWFObject.prototype.write){var _s1=SWFObject.prototype.write;SWFObject.prototype.write=function(){_args=arguments;if(this.getAttribute("version").major<8){this.addVariable("$swfaddress",SWFAddress.getValue());((typeof _args[0]=="string")?document.getElementById(_args[0]):_args[0]).so=this}var success;if(success=_s1.apply(this,_args)){_ref.addId(this.getAttribute("id"))}return success}}if(typeof swfobject!=UNDEFINED){var _s2r=swfobject.registerObject;swfobject.registerObject=function(){_args=arguments;_s2r.apply(this,_args);_ref.addId(_args[0])};var _s2c=swfobject.createSWF;swfobject.createSWF=function(){_args=arguments;var swf=_s2c.apply(this,_args);if(swf){_ref.addId(_args[0].id)}return swf};var _s2e=swfobject.embedSWF;swfobject.embedSWF=function(){_args=arguments;if(typeof _args[8]==UNDEFINED){_args[8]={}}if(typeof _args[8].id==UNDEFINED){_args[8].id=_args[1]}_s2e.apply(this,_args);_ref.addId(_args[8].id)}}if(typeof UFO!=UNDEFINED){var _u=UFO.create;UFO.create=function(){_args=arguments;_u.apply(this,_args);_ref.addId(_args[0].id)}}if(typeof AC_FL_RunContent!=UNDEFINED){var _a=AC_FL_RunContent;AC_FL_RunContent=function(){_args=arguments;_a.apply(this,_args);for(var i=0,l=_args.length;i<l;i++){if(_args[i]=="id"){_ref.addId(_args[i+1])}}}}})()};

