var linkAddress ="";
var currentHost = "";
var linkHost = "";
var defaultTemplate = "xml";

initiateCommonFunctionality = function() {
	$(document).ready(function() {
		// Preload the background images to enable smooth transitions
		$.preLoadImages("includes/images/wrappers/v07/bg_business.jpg", "includes/images/wrappers/v07/bg_integration.jpg", "includes/images/wrappers/v07/bg_jive.jpg", "includes/images/wrappers/v07/bg_people.jpg", "includes/images/wrappers/v07/bg_people2.jpg", "includes/images/wrappers/v07/bg_social.jpg", "includes/images/wrappers/v07/bg_specializeddesign.jpg", "includes/images/wrappers/v07/bg_technology.jpg");

		// Implement the PNG fix for only IE6 or earlier
		if (jQuery.browser.msie && jQuery.browser.version <= 6) {
			$(document).pngFix();
		}

		$.address.change(function(event) {
			if(event.value != "/") {
				doPageTransition(window.location, event.value);
			}
		});

		/***************************************************************************************/
		// Contact Us / Support
		/***************************************************************************************/

		// When the user clicks the "Contact Us" link, show the contact information container element
		$(".elementDetailPopupCtrlContactUs").click(function() {
			// Hide any other detail box
			_gaq.push(['_trackPageview', '/virtual/contactus']);
			$(".containerDetailPopup").hide();
			$(this).next(".containerDetailPopup").fadeIn();
		});
		$(".elementDetailPopupCtrlSupport").click(function() {
			// Hide any other detail box
			_gaq.push(['_trackPageview', '/virtual/support']);
			$(".containerDetailPopup").hide();
			$(this).next(".containerDetailPopup").fadeIn();
		});
		$(".containerDetailPopup a").click(function() {
			$(".containerDetailPopup").hide();
		});
		$(".elementCloseBtn").click(function() {
			$(this).parent().hide();
		});
		
		/***************************************************************************************/

		/***************************************************************************************/
		// Main navigation
		/***************************************************************************************/
		// Registers the current cursor state against the quick menu control
		var quickNavMousedOver = false;
		// Protects the menu from being clicked continuously by users and throwing the menu in a panic
		var clickShieldOn = false;

		$("#elementQuickNav").hover(
			function() {
				$(this).addClass("active");
				quickNavMousedOver = true;
			},
			function() {
				if ($("#elementMainNavigation").is(":not(:visible)")) {
					$(this).removeClass("active");
				}
				quickNavMousedOver = false;
			}
		);

		// Quick nav rollout effect
		$("#elementQuickNav").toggle(
			function() {
				// If the click shield is not on, then process the toggle
				if (!clickShieldOn) {
					// Turn on the click shield
					clickShieldOn = true;
					$("#elementMainNavigationTop").animate({"height": "110"});
					$("#elementMainNavigation").slideDown(500,
						function() {
							clickShieldOn = false;
							$("#elementMainNavigationRollup").fadeIn();
						} 
					);
				}
			},
			function() {
				// If the click shield is not on, then process the toggle
				if (!clickShieldOn) {
					// Turn on the click shield
					clickShieldOn = true;
					$("#elementMainNavigationRollup").fadeOut();
					$("#elementMainNavigationTop").animate({"height": "45"});
					$("#elementMainNavigation").slideUp(500,
						function() {
							clickShieldOn = false;
							// If the cursor is not currently hovering over the quick menu control
							if (!quickNavMousedOver) {
								// Remove the active (aka red text) class
								$("#elementQuickNav").removeClass("active");
							}
						}
					);
				}
			}
		);

		// Expand any item that may have a hidden submenu
		$("#elementMainNavigation a.subMenuCtrl").click(function() {
			var target = $(this).parents("li").children("ul");
			$("ul.subMenu:visible").not(target).slideUp();
			target.slideToggle();
		});

		$("#elementMainNavigationRollup").hover(
			function() {
				$(this).addClass("active");
			},
			function() {
				$(this).removeClass("active");
			}
		);
		$("#elementMainNavigationRollup").click(function() {
			$("#elementQuickNav").click();
		});
		/***************************************************************************************/


		/***************************************************************************************/
		// Page transitioning
		/***************************************************************************************/
		// Bind all the a tags in the document to a click event
		$("a.hijaxCtrl").livequery("click", function() {
			// Store the link address
			linkAddress = $(this).attr("href");
			// Parse the current link
			$.url.setUrl(window.location);
			currentHost = $.url.attr("host");
			// Parse the current link
			$.url.setUrl(linkAddress);
			linkHost = $.url.attr("host");

			// If the splash page was requested, overwrite the default xml template
			if($.url.param("page") != undefined &&  $.url.param("page") == "splash") {
				defaultTemplate = "splash_xml";
			}

			// Display "busy" animation
			$.fancybox.showActivity();
			// Perform an ajax.get request to retrieve the background image and content of the linked page
			$.ajax({
				type		: "GET",
				url			: "index.php", 
				cache		: false,
				data		: { "page": $.url.param("page"), "template_overwrite": defaultTemplate },
				success		: 
					function(data) {
						// Store the title of the page 
						var pageTitle = $(data).find("page_title").text();
						// Store the new image
						var backgroundImage = $(data).find("bg_image").text();
						// Store the content returned from the xml template
						var content = $(data).find("content").text();

						// Run the transition effect
						doPageTransitionEffect(true, content, backgroundImage, linkAddress, pageTitle);
						// Hide "busy" animation
						$.fancybox.hideActivity();

						return false;
					},
				error		:
					function(xhr, textStatus, errorThrown) {
						// Hide "busy" animation
						$.fancybox.hideActivity();

						alert("AJAX Error:\n"
								+ "\nSource Document:\t" + linkAddress
								+ "\nReason:\t\t" + $.trim(xhr.responseXML.parseError.reason)
								+ "\nSource Text:\t" + $.trim(xhr.responseXML.parseError.srcText)
								+ "\nLocation:\t\t" + xhr.responseXML.parseError.line + " (character: " + xhr.responseXML.parseError.linepos + ")"
						);
					}
			}); // $.get
			
			// Cancel the link request - if everything is operating normally, the link should be taken care of by the ajax request
			return false;
		});
		/***************************************************************************************/
	});
};

/***************************************************************************************/
// Function performs the background transition on content swap
/***************************************************************************************/
function doPageTransition(currentURL, linkURL) {
	// Store the link address
	var linkAddress = linkURL;
	// Parse the current link
	$.url.setUrl(currentURL);
	var currentHost = $.url.attr("host");
	// Parse the current link
	$.url.setUrl(linkAddress);
	var linkHost = $.url.attr("host");

	// If the splash page was requested, overwrite the default xml template
	if(($.url.param("page") == undefined) || ($.url.param("page") != undefined && $.url.param("page") == "splash")) {
		defaultTemplate = "splash_xml";
	}

	// Display "busy" animation
	$.fancybox.showActivity();
	// Perform an ajax.get request to retrieve the background image and content of the linked page
	$.ajax({
		type		: "GET",
		url			: "index.php", 
		cache		: false,
		data		: { "page": $.url.param("page"), "template_overwrite": defaultTemplate },
		success		: 
			function(data) {
				// Store the title of the page 
				var pageTitle = $(data).find("page_title").text();
				// Store the new image
				var backgroundImage = $(data).find("bg_image").text();
				// Store the content returned from the xml template
				var content = $(data).find("content").text();

				// Run the transition effect
				doPageTransitionEffect(true, content, backgroundImage, linkAddress, pageTitle);
				// Hide "busy" animation
				$.fancybox.hideActivity();

				return false;
			},
		error		:
			function(xhr, textStatus, errorThrown) {
				// Hide "busy" animation
				$.fancybox.hideActivity();

				alert("AJAX Error:\n"
						+ "\nSource Document:\t" + linkAddress
						+ "\nReason:\t\t" + $.trim(xhr.responseXML.parseError.reason)
						+ "\nSource Text:\t" + $.trim(xhr.responseXML.parseError.srcText)
						+ "\nLocation:\t\t" + xhr.responseXML.parseError.line + " (character: " + xhr.responseXML.parseError.linepos + ")"
				);
			}
	}); // $.get
	
	// Cancel the link request - if everything is operating normally, the link should be taken care of by the ajax request
	return false;
}
/***************************************************************************************/

/***************************************************************************************/
// Function used to perform the background transitioning
/***************************************************************************************/
function doPageTransitionEffect(swapContent, content, backgroundImage, linkAddress, pageTitle) {
	// GA tracking for content load
	_gaq.push(['_trackEvent', 'ajax_page_call', linkAddress]);
	_gaq.push(['_trackPageview', linkAddress]);

	// Track the AJAX history
	$.address.value(linkAddress);

	// Change the background of the placeholder to the image specified in the next page
	$(".elementImgPlaceholder.last").css("background-image", "url(" + backgroundImage + ")");

	// Scroll to the top of the document
	if($.browser.ie) {
		// IE is stupid
		window.scrollTo(0);
	} else {
		$(window).scrollTop(0);
	}

	// If the current wrapper image is the same as the upcoming contents image, do not perform the transition 
	if ($(".elementImgPlaceholder.first").css("background-image") == $(".elementImgPlaceholder.last").css("background-image")) {
		// Determine whether the content should be swapped
		if(swapContent) {
			// Replace the content of the containerContent element with the content returned by the requested page
			removeSWF("elementSplashNavigation");
			$("#containerContent > *:not(#containerFooter)").remove();
			$("#containerContent").prepend(content);
		}
	} else {
		// Slide this pages background placeholder aside
		$(".elementImgPlaceholder.first").animate({ "left": "-=100%" }, 500,
			function() {
				// Determine whether the content should be swaped
				if(swapContent) {
					// Replace the content of the containerContent element with the content returned by the requested page
					removeSWF("elementSplashNavigation");
					$("#containerContent > *:not(#containerFooter)").remove();
					$("#containerContent").prepend(content);
				}
				// Change the background of the main background placeholder to match that of the secondary background placeholder and 
				// reposition it to its default location
				$(".elementImgPlaceholder.first").css({
					"background-image": "url(" + backgroundImage + ")",
					"left": 0
				});
			}
		);
	}

	// If the splash page was requested, overwrite the default xml template
	if($.url.param("page") != undefined &&  $.url.param("page") == "splash") {
		$("#containerFooter").addClass("splash");
	} else {
		$("#containerFooter").removeClass("splash");
	}

	// If anything but the splash page was requested, change the page title to whatever is set in the config of the content piece being loaded
	if($.url.param("page") != undefined && $.url.param("page") != "splash") {
		document.title = "Lixar - " + pageTitle;
		$("#containerHeader #elementLogo").removeClass("splash");
	}

	// Implement the PNG fix for only IE6 or earlier
	if (jQuery.browser.msie && jQuery.browser.version <= 6) {
		$(document).pngFix();
	}
}
/***************************************************************************************/

/***************************************************************************************/
// Image preloader
/***************************************************************************************/
(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);
/***************************************************************************************/

/***************************************************************************************/
// Cross-browser SWF removal
// - Especially needed to safely and completely remove a SWF in Internet Explorer
/***************************************************************************************/
function removeSWF(id) {
	var obj = getElementById(id);
	if (obj && obj.nodeName == "OBJECT") {
		if ($.browser.msie) {
			obj.style.display = "none";
			(function(){
				if (obj.readyState == 4) {
					removeObjectInIE(id);
				}
				else {
					setTimeout(arguments.callee, 10);
				}
			})();
		}
		else {
			obj.parentNode.removeChild(obj);
		}
	}
}

function removeObjectInIE(id) {
	var obj = getElementById(id);
	if (obj) {
		for (var i in obj) {
			if (typeof obj[i] == "function") {
				obj[i] = null;
			}
		}
		obj.parentNode.removeChild(obj);
	}
}

/* Functions to optimize JavaScript compression
*/
function getElementById(id) {
	var el = null;
	try {
		el = document.getElementById(id);
	}
	catch (e) {}
	return el;
}
/***************************************************************************************/
