function trim1 (str) {
	return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}

/**
 * Create the list of recently visited pages
 * @param number	Number of elements to show
 * @param element	Element (ID) of place to add it to
 */
function lastPagesVisited(number, element) {
	var prefix = "learndirect -";
	var pagesVisited = eval(jQuery.cookie("pagesVisited"));

	if (pagesVisited != null) {
		jQuery(element).empty();
		for(var i = 0, l = pagesVisited.length; i < l; i++) {
			if (i > number) {
				break; // we're done
			}
			var page = pagesVisited[i];
			var title = page.title;
			if (title.indexOf(prefix) >= 0) {
				if (page.url.indexOf("/", 7) != page.url.lastIndexOf("/")) {
					title = trim1(title.substring(title.indexOf(prefix) + prefix.length));
				} else {
					title = "Homepage";
				}
			}
			jQuery(element).append("<li><a href=\"" + page.url + "\">" + title + "</a></li>");
		}
	}
}

/**
 * Show banners on the RHS for main site
 * @param elementId	ID of element to attach banners to
 * @param itemCode	?
 * @param noBanners	Number of banners to show
 */
function showBanners(elementId, itemCode, noBanners) {
	// request a list of banners for the given item code (JSON)
	var bannersUrl = document.URL.replace(/view=[A-Za-z0-9]+(&)?/, ""); // remove any view in the QS as not required
	var bannersPath = bannersUrl.substring(bannersUrl.indexOf("/", 8));
	
	// centre details
	if (bannersPath.indexOf("/aboutlearndirect/centresearch/centredetails") == 0) {
		bannersUrl = bannersUrl.substring(0, bannersUrl.indexOf(bannersPath))+'/aboutlearndirect/centresearch/centredetails';
		bannersPath = "/aboutlearndirect/centresearch/centredetails";
	}

	// form submissions
	if (/\.action$/.test(bannersPath)) {
		bannersUrl = bannersUrl.substring(0, bannersUrl.indexOf(bannersPath))+'/contact/';
		bannersPath = "/contact/";
	}

	// check see if we already have a view
	if (bannersPath.indexOf("/v/") != 0) {
		bannersUrl = bannersUrl.substring(0, bannersUrl.indexOf(bannersPath))+'/v/bannerList'+bannersPath;
	} else {
		bannersUrl = bannersUrl.replace(/\/v\/[^\/]+/g, "/v/bannerList");
	}

	jQuery.ajax({
		url: bannersUrl,
		dataType: 'json',
		success: function(results) {
			var banners = [];

			// If first time user, add first time users to banner list
			firstTimeUserBanners(banners, results, noBanners);

			// fill remainder of list
			var b = banners.length;
			var availableBanners = bannersLeft(results);

			if (b < noBanners) {
				attachedBanners(banners, availableBanners, noBanners);
				availableBanners = bannersLeft(results);
			}
			if (b < noBanners) {
				qualificationBasedBanners(banners, availableBanners, noBanners);
				availableBanners = bannersLeft(results);
			}
			b = banners.length;
			if (b < noBanners) {
				timeBasedBanners(banners, availableBanners, noBanners);
				availableBanners = bannersLeft(results);
			}
			b = banners.length;
			if (b < noBanners) {
				keywordBasedBanners(banners, availableBanners, noBanners);
				availableBanners = bannersLeft(results);
			}
			b = banners.length;
			if (b < noBanners) {
				randomBanners(banners, availableBanners, noBanners);
				availableBanners = bannersLeft(results);
			}
			b = banners.length;
			// Tell page to load each banner
			for (var i = 0; i < b; i++) {
				loadBanner(elementId, banners[i].url);
			}
		}
	});
}

/**
 * Loads a banner into a div and appends it to the banners
 * @param elementId	ID to append banner to
 * @param bannerUrl	URL of banner
 */
function loadBanner(elementId, bannerUrl) {
	var banner = jQuery("<div/>").load(bannerUrl);
	jQuery(elementId).append(banner);
}

function attachedBanners(banners, availableBanners, noBanners) {
	for (var i = 0, l = availableBanners.length; i < l; i++) {
		if (banners.length >= noBanners) return;
		if (availableBanners[i].attached == 'true') {
			banners[banners.length] = availableBanners[i];
			availableBanners[i] = null;
		}
	}
}
function qualificationBasedBanners(banners, availableBanners, noBanners) {}
function timeBasedBanners(banners, availableBanners, noBanners){
	var now = new Date();
	var minutesSinceMidnight = (now.getHours() * 60) + now.getMinutes();
	for (var i = 0, l = availableBanners.length; i < l; i++) {
		if (banners.length >= noBanners) return;
		if (availableBanners[i].startMinutes != '' && availableBanners[i].endMinutes != '') {
			if (availableBanners[i].startMinutes <= minutesSinceMidnight &&
			 	availableBanners[i].endMinutes > minutesSinceMidnight) {
				banners[banners.length] = availableBanners[i];
				availableBanners[i] = null;
			} else {
				availableBanners[i] = null;		// exclude this banner
			}
		}
	}
}

function keywordBasedBanners(banners, availableBanners, noBanners) {
	try {
		var keywords = jQuery('meta[name=keywords]').attr('content').split(',');

		for (var i = 0, l = keywords.length; i < l; i++) {
			for (var b = 0, bl = availableBanners.length; b < bl; b++) {
				if ($defined(availableBanners[b])) {
					if (trim1(availableBanners[b].keywords) != "") {
						var bannerKeywords = availableBanners[b].keywords.split(',');
						for (bk = 0, bkl = bannerKeywords.length; bk < bkl; bk++) {
							if (trim1(bannerKeywords[bk]).toLowerCase() == trim1(keywords[i]).toLowerCase()) {
								if (banners.length <= noBanners) {
									banners[banners.length] = availableBanners[b];
									availableBanners[b] = null;
								}
							}
						}
					}
				}
			}
		}
	} catch (keywordsE) {}
}

function randomBanners(banners, availableBanners, noBanners) {
	var i = 0;
	while(i < 10 && banners.length < noBanners) {
		// pick a banner at random
		var index = Math.floor(availableBanners.length * Math.random());
		if (availableBanners[index] != null) {
			banners[banners.length] = availableBanners[index];
			availableBanners[index] = null;
			availableBanners = bannersLeft(availableBanners);
		}
		i++;
	}
}

function bannersLeft(bannerList) {
	var bannersLeft = [];
	var b = 0;
	for(var i = 0, l = bannerList.length; i < l; i++) {
		if (bannerList[i] != null) {
			bannersLeft[b++] = bannerList[i];
		}
	}
	return bannersLeft;
}

function firstTimeUserBanners(banners, availableBanners, noBanners) {
	var b = 0;
	for (var i = 0, l = availableBanners.length; i < l; i++) {
		if (b == noBanners) break; // max number reached
		if (availableBanners[i].firstTimeUser.toLowerCase() == 'yes') {
			if (isFirstTimeUser()) {
				banners[b] = availableBanners[i];
				b++;
			} else {
				availableBanners[i] = null; // remove this banner so it can't be used on page again
			}
		}
	}
}

/**
 * Check to see if this user is known
 * @return true/false depending yes/no
 */
function isFirstTimeUser() {
	var knownUser = jQuery.cookie("knownUser");
	var now = new Date();
	if (knownUser === null) {
		jQuery.cookie("knownUser", now.toString('yyyy-MM-dd HH:mm:ss'), { path: '/', 'expires': 365 });
		return true;
	} else {
		// parse the cookie and determine how long they've been on the site
		if (now.getTime() - knownUser < 1800000) { // half-hour
			return true;
		}
	}
	return false;
}

/* QueueCPP.js - a function for creating an efficient queue in JavaScript
 *
 * The author of this program, Safalra (Stephen Morley), irrevocably releases
 * all rights to this program, with the intention of it becoming part of the
 * public domain. Because this program is released into the public domain, it
 * comes with no warranty either expressed or implied, to the extent permitted
 * by law.
 *
 * For more public domain JavaScript code by the same author, visit:
 *
 * http://www.safalra.com/web-design/javascript/
 */


/* Creates a new Queue. A Queue is a first-in-first-out (FIFO) data structure.
 * Functions of the Queue object allow elements to be enqueued and dequeued, the
 * first element to be obtained without dequeuing, and for the current size of
 * the Queue and empty/non-empty status to be obtained.
 */
function Queue(){

  // the list of elements, initialised to the empty array
  var queue = [];

  // the amount of space at the front of the queue, initialised to zero
  var queueSpace = 0;

  /* Returns the size of this Queue. The size of a Queue is equal to the number
   * of elements that have been enqueued minus the number of elements that have
   * been dequeued.
   */
  this.size = function(){

    // return the number of elements in the queue
    return queue.length - queueSpace;

  }

  /* Returns true if this Queue is empty, and false otherwise. A Queue is empty
   * if the number of elements that have been enqueued equals the number of
   * elements that have been dequeued.
   */
  this.empty = function(){

    // return true if the queue is empty, and false otherwise
    return (queue.length == 0);

  }

  /* Enqueues the specified element in this Queue. The parameter is:
   *
   * element - the element to enqueue
   */
  this.push = function(element){
    queue.push(element);
  }

  /* Dequeues an element from this Queue. The oldest element in this Queue is
   * removed and returned. If this Queue is empty then undefined is returned.
   */
  this.pop = function(){

    // initialise the element to return to be undefined
    var element = undefined;

    // check whether the queue is empty
    if (queue.length){

      // fetch the oldest element in the queue
      element = queue[queueSpace];

      // update the amount of space and check whether a shift should occur
      if (++queueSpace * 2 >= queue.length){

        // set the queue equal to the non-empty portion of the queue
        queue = queue.slice(queueSpace);

        // reset the amount of space at the front of the queue
        queueSpace=0;

      }

    }

    // return the removed element
    return element;

  }

  /* Returns the oldest element in this Queue. If this Queue is empty then
   * undefined is returned. This function returns the same value as the pop
   * function, but does not remove the returned element from this Queue.
   */
  this.front = function(){

    // initialise the element to return to be undefined
    var element = undefined;

    // if the queue is not element then fetch the oldest element in the queue
    if (queue.length) element = queue[queueSpace];

    // return the oldest element
    return element;

  }

  this.toArray = function(){
	return queue;
  }
}

/*
 * Tracks last X pages vistied.
 *
 * Stores:
 *  Page Title, URL, and Keywords
 *
 *Requires:
 * jQuery 1.4.2, jquery.cookie, JSON
 */
function rebuildQueue(array) {
	var queue = new Queue();
	try {
		for (var i = 0, len = array.length; i < len; i++) {
			queue.push(array[i]);
		}
	} catch (arrayE) {}
	return queue;
}

function serializeQueue(queue) {
	var pages = new Array(queue.size());
	var i = 0;
	while(!queue.empty()){
		pages[i++] = queue.pop();
	}
	return JSON.stringify(pages);
}

function trackPage() {
	if (!document.URL.match(/.*\.action$/) && document.URL.indexOf('?') == -1) {
		var pagesVisitedCookie = jQuery.cookie('pagesVisited');
		var pageQueue = new Queue();

		if ((typeof(pagesVisitedCookie) != 'undefined') && (pagesVisitedCookie != '')) {
			pageQueue = rebuildQueue(eval(pagesVisitedCookie));
		}

		var keywords = "";
		try {
			keywords += jQuery('meta[name=keywords]').attr("content");
		} catch (keywordsE) {}

		var title = tmptitle;
		var currentPage = {
				title: title,
				url: document.URL,
				keywords: keywords
		};

		var alreadyTracked = false;
		var pages = pageQueue.toArray();
		
		for(var i = 0, l = pages.length; i < l; i++){
			if(pages[i].url == currentPage.url) alreadyTracked = true;
		}
		
		if (!alreadyTracked) {
			if (pageQueue.size() == 5) pageQueue.pop();
			pageQueue.push(currentPage);
			var serialized = serializeQueue(pageQueue);
			jQuery.cookie('pagesVisited', serialized, { 'path': '/'});
		}
	}
}