/**
 * Sitewide javascript variables.
 */
var section = "project-management";
var group = "association-for-project-management";



/**
 * A generic caching function which takes a function which makes a request of some kind and ensures that this request 
 * is only made once.  All other calls are queued to the callback of that first request.
 */
$.createCache = function (requestFunction) {
	var cache = {};
	return function(key, callback) {
		if(!cache[key]) {
			cache[key] = $.Deferred(function (dfd) {
				requestFunction(dfd, key);
			}).promise();
		}
		return cache[key].done(callback);
	};
};



/**
 * Specialisation of the generic cache function to handle scripts.
 */
$.getScriptCached = $.createCache(function (dfd, url) {
	$.getScript(url).then(dfd.resolve, dfd.reject);
});


/**
 * Configure required deferred objects.
 */
jsCompleted = {};
jsCompleted['/js/tracker/tracker.js'] = $.Deferred();
jsCompleted['/js/eCommerce/eCommerceAddition.js'] = $.Deferred();



$.getScriptCached('/js/rsh04/dhtmlHistory.js');
$.getScriptCached('/js/tracker/tracker.js');
$.getScriptCached('/js/jQuery/jquery.form.js');
$.getScriptCached('/js/script.js');
$.getScriptCached('/js/md5.js');
$.getScriptCached('/js/user.js');
$.getScriptCached('/js/positioning.js');
$.getScriptCached('/js/jQuery/jquery.easing-1-1.js');
$.getScriptCached('/js/jQuery/jquery.dimensions.js');
$.getScriptCached('/js/jQuery/jquery-ui-1.8.2.custom.min.js');
$.getScriptCached('/js/jQuery/jquery.timers-1.1.2.js');
$.getScriptCached('/js/jQuery/jquery.overlabel.js');
$.getScriptCached('/js/coursePage.js');
$.getScriptCached('/js/dates.js');



/**
 * ON DOCUMENT READY FUNCTION
 */
$(function ()
	{
		$.getScriptCached('/js/script.js').done(function () {
			// Initialise JS Dark Ribbon
			$('.dark_menu_list_item')
				.bind('mouseover', function () { showRibbon(this); })
				.bind('mouseout', function (event) { checkMenu(event, this); });
	
			// Initialise JS Light Ribbon
			$('.white_ribbon_top, .white_ribbon_bottom')
				.bind('mouseout', function (event) { checkMenu(event, this); })
				.bind('mouseover', function () { $('.dark_menu_list_item_active').stopTime(); });
		});

		// Execute any additional on ready JS sent from the server.
$.when($.getScriptCached('/js/RotatingFeature.class.js')).done(function ()
	{
		tccFeature = new RotatingFeature('#primaryFeature');
tccFeature.addFeature('/sections/agile-methods/images/landing/apm-agile-project-management-advert.gif', 'APM Agile Project Management', '/agile-methods/agile-project-management/training/agile-project-management-practitioner/', '')
		tccFeature.addFeature('/sections/agile-methods/images/landing/dsdm-atern-advert.gif', 'DSDM Atern Training Advert', '/agile-methods/dsdm-atern/', '')
				tccFeature.preloadFeatures();
		tccFeature.beginRotation();
	});
	});



/**
 * Create and position an overlay which appears to dim the content behind it.
 * Other content can then be positioned on top of this dimmed screen.
 *
 * @param String id A unique ID for the object. Use this when dimming the screen more than once at the same time.
 * @param int z A value for the Z-Index of the dimming layer.  Use this when you wish to dim multiple times.
 */
function dimScreen(callback, z, id)
{
	if(z == null) z = 100;
	if(id == null) id = "overlay";

	// Check whether a dimmer layer by this name exists and if so, adjust it's z-index.
	if($("div#"+id).size() > 0)
	{
		$("div#"+id).css({"z-index": z});
	}
	else
	{
		$("body").prepend('<div id="'+id+'" class="overlay" style="z-index: '+z+'"></div>');
	}
	if(callback) callback();
}

/**
 * Remove an already existing dimming layer from the screen.
 *
 * @param String id The ID for the dimming layer. Leaving this blank will assume the default.
 */
function undimScreen(callback, id)
{
	if(id == null) id = "overlay";

	$("div#"+id).remove();
	//$("div#"+id).fadeOut("normal", function() {$("div#"+id).remove();});
	if(callback) callback();
}



var statusImageTimers = [];

/**
 * Display an animated status image in the centre of the page.
 *
 * @param String id A unique ID for the object. Use this when displaying more than one status image at the same time.
 * @param int z A value for the Z-Index of the image.  Use this when you've altered the Z-Index of the dimming layer.
 * @param String imageName The name of the image containing the text to place on top of the status animation.
 */
function displayStatusImage(imageName, z, id, minimumDisplayMS)
{
	if(z == null) z = 150;
	if(id == null) id = "statusImage";
	if(imageName == null) imageName = "/images/statusImages/statusLoading.png";
	if(minimumDisplayMS == null) minimumDisplayMS = 2000;

	h=100; w=100;

	screenDimensions = getScreenDimensions();
	scrollOffsets = getScrollOffsets();

	vPosition = scrollOffsets[1] + (screenDimensions[1] / 2) - (h/2);
	//hPosition = (screenWidth / 2) - (w/2);
	hPosition = (w/2);

	$("body").append('<div class="horizontalHorizon" style="z-index: '+z+'; position:absolute; top:'+vPosition+'px;"><div id="'+id+'" class="statusImage" style="z-index: '+z+'"><img src="/images/statusImages/statusAnimation.gif" style="position:absolute" /><img src="'+imageName+'" /></div></div>')

	statusImageTimers[id] = [new Date(), minimumDisplayMS];

	// Return the millisecond value when the statusImage was created for use in minimum display time.
	return new Date();
}

/**
 * Destroy an existing status image.
 *
 * @param String id The unique ID for the status image to be destroyed. Blank will assume the default.
 */
function destroyStatusImage(callback, id)
{
	if(id == null) id = "statusImage";

	// Check that this image has been displayed for the minimum time.
	var currentTime = new Date();
	var timeLeft = statusImageTimers[id][1] - (currentTime - statusImageTimers[id][0]);

	if(timeLeft > 0)
	{
		setTimeout("destroyStatusImage2('"+id+"', "+callback+")", timeLeft);
		return;
	}
	destroyStatusImage2(id, callback);
}

function destroyStatusImage2(id, callback)
{
	$("div#"+id).remove();

	if(callback) callback();
}



function displayHTMLPopup(h, w, title, source, noTitle, z, id, minimumDisplayMS)
{
	if(minimumDisplayMS == null) minimumDisplayMS = 300;
	if(noTitle == null) noTitle = false;

	extraCSS = "";
	isImage = false;
	var imageFileTypes = new Array();
	imageFileTypes[".png"] = 1;
	imageFileTypes[".jpg"] = 1;
	imageFileTypes[".gif"] = 1;
	imageFileTypes[".bmp"] = 1;

	if(z == null) z = 150;
	if(id == null) id = "htmlPopup";

	dimScreen();

	if(noTitle)
	{
		$("div#overlay").css("background-color", "#6f8aa8");
	}

	if(imageFileTypes[source.substring(source.lastIndexOf("."), source.length)] == 1)
	{
		displayStatusImage(null, null, null, 0);

		isImage = true;
		extraCSS = "overflow: hidden";
		image = new Image();
		image.onload =  function () { displayHTMLPopup2(h, w, title, source, noTitle, z, id, minimumDisplayMS) };
		image.onerror =  function () { alert('Error loading photograph.'); };
		image.src = source;
	}
	else
	{
		displayHTMLPopup2(h, w, title, source, noTitle, z, id, minimumDisplayMS);
	}
}

function displayHTMLPopup2(h, w, title, source, noTitle, z, id, minimumDisplayMS)
{
//	noTitle=true;
	// Now the image has loaded, get its size.
	if(isImage)
	{
		if(!w) w = image.width + 20;
		if(!h) h = image.height + 20;

		destroyStatusImage();
	}

	if (!noTitle)
	{
		imgH=h-20;
	}
	else
	{
		imgH=h;
	}

	newContent = '<div id="'+id+'" style="height: '+h+'px; width: '+w+'px; visibility:hidden" class="htmlPopup">'
				+'		<div id="'+id+'Content" class="htmlPopupContent" style="height: '+imgH+'px;'+extraCSS+'">'
				+'		</div>';

	if(!noTitle)
	{
		newContent = newContent+'		<div style="font-size:1.4em; font-weight:bold; padding-left:10px; padding-right:10px; text-align:center;">'+title+'</div>';
	}

	newContent = newContent+'	</div>';


	$("body").append(newContent);

	// If this is an image, handle directly with no AJAX call.
	if(isImage)
	{
		$("div#htmlPopupContent").append('<img src="'+source+'" class="htmlPopupImage" />');

		htmlPopupT = null;

		$("#htmlPopup").centre();
		$('#htmlPopup').css("display", "none").css("visibility", "visible");
		$(window).bind("resize", function() { $('#htmlPopup').centreVertically(); });
		$(window).bind("scroll", function() { clearTimeout(htmlPopupT); htmlPopupT = setTimeout("$('#htmlPopup').centreVertically();", 100); });

		$("div#htmlPopup").fadeIn("normal");
	}
	else
	{
		displayStatusImage(null, null, null, minimumDisplayMS);

		// Make an ajax call for the content and set the callback.
		$.ajax({url: "/ajax"+source, success: displayHTMLPopupContent});
	}

	$("div#overlay").bind("click", function () { destroyHTMLPopup(id, undimScreen); });
	$('#htmlPopup').bind("click", function () { destroyHTMLPopup(id, undimScreen); });
}

function displayHTMLPopupContent(xmlHttp)
{
	/*
		This is a big hack. Basicly, for some strange reason, if the .append function
		is called to soon, Safari crashes. I'm guessing it might have something to do with the fact
		that destroyStatusImage is called asynchronously from displayStatusImage, so they might be
		in race condition. However, for now, simply for loop loads lol!
	*/
	for (i = 0; i < 100000; i++){

	}

	$("div#htmlPopupContent").append(xmlHttp.responseText);
	destroyStatusImage(displayHTMLPopupContent2);
}

function displayHTMLPopupContent2()
{
	verticalCentre("htmlPopup"); $("#htmlPopup").css("visibility", "visible");
	window.onresize = function() {	verticalCentre("htmlPopup") };
	window.onscroll = function() {	verticalCentre("htmlPopup") };

	$("div#htmlPopup").fadeIn("normal");
}

function destroyHTMLPopup(id, callback, noTitle)
{
	if(id == null) id = "htmlPopup";

	if(noTitle)
	{
		$("div#shadowdiv").show();
		$("div#headershadowdiv").show();
		$("div#bottomSpacer").show();
		$("div#cart_feedback").show();
		$("div#standard_bar").show();
	}

	$("div#"+id).fadeOut("normal", function () { $("div#"+id).remove(); callback(); });
}


function isset(varname)
{
  return (typeof(window[varname])!='undefined');
}


function goToPage(page)
{
	var pages = new Array();
	pages["myAccount"] = "/mytcc/myaccount.php";

	document.location.href = pages[page];
}








/* METHODS UNDER DEVELOPMENT OR RETIRED */
function center(div)
{
	// Get relevant sizings.
	var pagesize = getPageSize();
	var divsize = getDivSize(div);

	$("#RG_feedback").css({left: ((pagesize[0]/2)-(divsize[0]/2))+"px", top: ((pagesize[1]/2)-(divsize[1]/2))+"px"});
}

function getPageSize()
{
	var de = document.documentElement;
	var w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
	var h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight
	arrayPageSize = new Array(w,h)
	return arrayPageSize;
}

function getDivSize(div)
{
	var w = div.offsetWidth; // || div.document.width;
	var h = div.offsetHeight; // || div.document.height;

	arrayDivSize = new Array(w,h)
	return arrayDivSize;
}

// Not sure if this works.
function getPageScrollTop(){
	var yScrolltop;
	var xScrollleft;
	if (self.pageYOffset || self.pageXOffset) {
		yScrolltop = self.pageYOffset;
		xScrollleft = self.pageXOffset;
	} else if (document.documentElement && document.documentElement.scrollTop || document.documentElement.scrollLeft ){	 // Explorer 6 Strict
		yScrolltop = document.documentElement.scrollTop;
		xScrollleft = document.documentElement.scrollLeft;
	} else if (document.body) {// all other Explorers
		yScrolltop = document.body.scrollTop;
		xScrollleft = document.body.scrollLeft;
	}
	arrayPageScroll = new Array(xScrollleft,yScrolltop)
	return arrayPageScroll;
}


function setScrollY(scrollY)
{
	var scrollX, scrollY;
	if (self.pageYOffset) // all except Explorer
	{
		self.pageYOffset = scrollY;
	}
	else if (document.documentElement && document.documentElement.scrollTop) // Explorer 6 Strict
	{
		document.documentElement.scrollTop = scrollY
	}
	else if (document.body) // all other Explorers
	{
		document.body.scrollTop = scrollY;
	}
}

function getScrollOffsets()
{
	var scrollX, scrollY;
	if (self.pageYOffset) // all except Explorer
	{
		scrollX = self.pageXOffset;
		scrollY = self.pageYOffset;
	}
	else if (document.documentElement && document.documentElement.scrollTop) // Explorer 6 Strict
	{
		scrollX = document.documentElement.scrollLeft;
		scrollY = document.documentElement.scrollTop;
	}
	else if (document.body) // all other Explorers
	{
		scrollX = document.body.scrollLeft;
		scrollY = document.body.scrollTop;
	}
	return new Array(scrollX, scrollY);
}
function getScreenDimensions()
{
	var screenX, screenY;
	if (self.innerHeight) // all except Explorer
	{
		screenX = self.innerWidth;
		screenY = self.innerHeight;
	}
	else if (document.documentElement && document.documentElement.clientHeight) // Explorer 6 Strict Mode
	{
		screenX = document.documentElement.clientWidth;
		screenY = document.documentElement.clientHeight;
	}
	else if (document.body) // other Explorers
	{
		screenX = document.body.clientWidth;
		screenY = document.body.clientHeight;
	}
	return new Array(screenX, screenY);
}


Array.prototype.in_array = function(search_term) {
  var i = this.length;
  if (i > 0) {
	 do {
		if (this[i] === search_term) {
		   return true;
		}
	 } while (i--);
  }
  return false;
}

