/**
 * teclan recently viewed functionality.
 *
 * @copyright teclan 2009
 */

var rvpCount = 0;
 
var $k = function(id) {
  return document.getElementById(id);
}; 

/**
 * Returns all elements of type 'nodeType' with class 'className'.
 */
var $$ter = function(nodeType, className) {
  var ret = new Array();
  var arr = document.getElementsByTagName(nodeType.toUpperCase());
  for (var i = 0; i < arr.length; i++) {
    if (arr[i].className) {
	  if (arr[i].className == className) {
	    ret.push(arr[i]);
	  }
	}
  }
  return ret;
};

function createRVP(html) {
  var total = 0;
  for (var i = 0; i < 4; i++) {
    var c = getCookie("RVP-" + i);
    if (c != null && c != "" && c != "undefined") {
	  if (c == html) return;
	  total++;
	}
  }
  if (total < 4) {
    setCookie("RVP-" + total, html);
  }
}

function destroyRecentlyViewed(rvID) {
  var rv = getCookie("RVP-" + rvID);
  var rvDiv = $k("RVP-" + rvID);
  if (rv) {
    //delete cookie
	setCookie("RVP-" + rvID, "");
	rvpCount--;
  }
  if (rvDiv) {
    //hide box
    rvDiv.style.display = "none";
  }
  if (rvpCount == 0) {
    $k('recently-viewed-items').style.display = 'none';
  }
}

function getRVPs(title) {
  var ret = "";
  for (var i = 0; i < 4; i++) {
    var c = getCookie("RVP-" + i);
    if (c != null && c != "" && c != "undefined") {
	  ret += c.replace(/<span/i, '<span onclick="destroyRecentlyViewed(' + i + ');"').replace(/RVPID/, 'RVP-' + i);
	  //if we're not in 'acatalog' then update the image
	  var path = "";
	  if (isCGIPage()) {
		path = "/acatalog/";
	  }
	  else if (isHomePage()) {
	    path = "acatalog/";  
		}
	  else if (isOffline()) {
	    path = "../";  
	  }
	  ret = ret.replace(/RVPIMG/, path);
	  rvpCount++;
	}
  }
  
  if (ret != "") {
    ret = '<div id="recently-viewed-items"><h2>' + title + '</h2>' + ret + '<div style="clear:left"></div></div>';
  }
  return ret;
}

function isHomePage() {
  var loc = window.location.toString();
  return loc.indexOf("acatalog") == -1 && !isOffline();
}
function isCGIPage() {
  var loc = window.location.toString();
  return loc.indexOf("cgi-bin") != -1 && !isOffline();
}

function isOffline() {
  var loc = window.location.toString();
  return loc.indexOf("file:") != -1;
}

function setRecentlyViewedItems() {
  //get all items created on the page
  var setups = $$ter('DIV', 'recently-viewed-creation');
  for (var i = 0; i < setups.length; i++) {
    createRVP(setups[i].innerHTML);
  }
}

function isIE() {
  return /msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent);
}

//attach the init function to the load event
if (window.attachEvent) { 
  window.attachEvent("onload", setRecentlyViewedItems); 
} 
else {  
  window.addEventListener("load", setRecentlyViewedItems, false); 
}
