document.onclick = function(e){
	e = e||window.event
	var t = e.target||e.srcElement
	if (t.onclick) return;
	var r = true
	if(t.className){
		t.className.splitrim(' ').each(function(c){
			if(onclicks[c]) {
				onclicks[c].call(t, e)
				r = false
	}})}
	return r
}

function emptyFunc() {}

function setCookie(name, value, expires, path, domain, secure) 
{
  document.cookie= name + "=" + escape(value) +
      ((expires) ? "; expires=" + expires.toGMTString() : "") +
      ((path) ? "; path=" + path : "") +
      ((domain) ? "; domain=" + domain : "") +
      ((secure) ? "; secure" : "");
}

function getCookie(name) 
{
  var dc = document.cookie;
  var prefix = name + "=";
  var begin = dc.indexOf("; " + prefix);
  if (begin == -1) 
  {
    begin = dc.indexOf(prefix);
    if (begin != 0) return null;
  }
  else 
  {
		begin += 2;
  }
  var end = document.cookie.indexOf(";", begin);
  if (end == -1) 
  {
     end = dc.length;
  }
  return unescape(dc.substring(begin + prefix.length, end));
}
function deleteCookie(name, path, domain) 
{
	if (getCookie(name)) 
	{
  	document.cookie = name + "=" +
      ((path) ? "; path=" + path : "") +
      ((domain) ? "; domain=" + domain : "") +
      "; expires=Thu, 01-Jan-70 00:00:01 GMT";
	}
}

function getPostBody(tabName)
{
	var form = document.forms[tabName];
	var postBody = "";
	if (form)
	{
		for (var el in form.elements)
		{
			postBody += '&' + form.elements[el].name + '=' + encodeURIComponent(form.elements[el].value)
		}
	}
	return postBody;
}

function clearDefault(el)
{
	if (el.defaultValue==el.value) el.value = "";
}

function openPanel(){
	this.parentNode.className = 'closed_panel';
}

function switchToGuest()
{
	document.forms["energyRegister"].action="energyRegisterGuest.jsp?switch=Yes";
	document.forms["energyRegister"].submit();
	return false;
}

function busy(msg, doScroll)
{
	var message = $id('message');
	if (message)
	{
		if (msg == undefined)
		{
			msg = language.startSaving;
		}
		message.innerHTML = '<img src="/images/energy/icons/snake.gif" alt="" />' + msg;
		message.className = '';
	}
	if (doScroll)
	{
		scroll(0,0);
	}
}

function clearBusy()
{
	var message = $id('message');
	if (message)
	{
		message.innerHTML = '';
	}
}

// the following two functions ganked from prototype (http://prototype.conio.net)
// (c) 2005 sam stephenson
var Class = {
	create: function() {
		return function() { this.initialize.apply(this, arguments) }
}}
Function.prototype.bind = function(o) {
	var __method = this
	return function() { return __method.apply(o, arguments) }
}

function $id(id)
{
	if (typeof id == 'string') 
	{
		return document.getElementById(id);
	}
	return id;
}

Array.prototype.each = function(f){
	var l = this.length
	for(var i = 0; i < l; i++) f(this[i], i)
	return this
}

Array.prototype.clear=function() {
    this.length = 0;
};

function extend(dest, src){
	if(!src) return dest
	for(var k in src) dest[k] = src[k]
	return dest
}

extend( String.prototype, {
	include: function(t) { return this.indexOf(t) >= 0 ? true : false },
	trim: function(){ return this.replace(/^\s+|\s+$/g,'') },
	splitrim: function(t){ return this.trim().split(new RegExp('\\s*'+t+'\\s*')) },
	encodeTag: function() { return encodeURIComponent(this).replace(/%2F/g, '/') },
	unescHtml: function(){ var i,e={'&lt;':'<','&gt;':'>','&amp;':'&','&quot;':'"'},t=this; for(i in e) t=t.replace(new RegExp(i,'g'),e[i]); return t },
	escHtml: function(){ var i,e={'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'},t=this; for(i in e) t=t.replace(new RegExp(i,'g'),e[i]); return t },
	escRegExp: function(){ return this.replace(/[\\$*+?()=!|,{}\[\]\.^]/g,'\\$&') }
})

Ajax = Class.create();
Ajax.prototype = {
	initialize: function(options){
		this.transport = this.getTransport();
		this.postBody = options.postBody || '';
		this.method = options.method || 'POST';
		this.onComplete = options.onComplete || null;
		this.update = $id(options.update) || null;
		this.request(options.url);
	},
	request: function(url){
		this.transport.open(this.method, url, true)
		this.transport.onreadystatechange = this.onStateChange.bind(this)
		if (this.method != 'GET') {
			this.transport.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
			if (this.transport.overrideMimeType) this.transport.setRequestHeader('Connection', 'close')
		}
		this.transport.send(this.postBody)
	},
	onStateChange: function(){
		if (this.transport.readyState == 4 && this.transport.status == 200) {
			if (this.onComplete)
				setTimeout(function(){this.onComplete(this.transport)}.bind(this), 10)
			if (this.update)
				setTimeout(function(){this.update.innerHTML = this.transport.responseText}.bind(this), 10)
			this.transport.onreadystatechange = emptyFunc
	    }
    },
	getTransport: function(){
		if (window.ActiveXObject) return new ActiveXObject('Microsoft.XMLHTTP')
		else if (window.XMLHttpRequest) return new XMLHttpRequest()
		else return false
}}

function getImageLink(element)
{
	return (element.href) ? element.href : element.parentNode.href;
}

function popupWindow()
{
	var element = this;
	var re = new RegExp("P([0-9]+)x([0-9]+)");
	var m = re.exec(element.className);
	if (m)
	{
		winName = (element.name) ? element.name : 'console';
		_lastPopupWindow = window.open(this.href,winName,'width='+m[1]+',height='+m[2]+',scrollbars=yes');
		return false;
	}
	return true;
}

function favouriteLink(element)
{
	var url = "favouriteController.jsp?";
	
	var re = new RegExp("FAV_([0-9:]+)$");
	var m = re.exec(element.id);
	if (m)
	{
		if (element.className == "rmRemove removeFavourite hilite")
		{
			url += "direction=remove&id=" + m[1];
		}
		else
		{
			url += "direction=add&id=" + m[1];
		}
	}
	return url;
}

function rmAdd()
{
	var element = this;
	busy();
	new Ajax({
			url	: favouriteLink(this),
			method: 'get',
			onComplete: function(transport){
				element.className = "rmRemove removeFavourite hilite";
				element.innerHTML = language.rmFavourite;
				clearBusy();
			}
	});
}

function rmRemove()
{
	var element = this;
	busy();
	new Ajax({
			url	: favouriteLink(this),
			method: 'get',
			onComplete: function(transport){
				element.className = "rmAdd addFavourite hilite";
				element.innerHTML = language.addFavourite;
				clearBusy();
			}
	});
}

function rmRemoveFavourite()
{
	new Ajax({
			url	: getImageLink(this),
			method: 'get'
	});
	var lc = $id("epc");
	if (lc && lc.childNodes.length <= 2)
	{
		$id("sortList").style.display = "none";
	}
	new fx.FadeSize(this.parentNode.parentNode.parentNode, {
		 duration: 1500, 
		 onComplete: function() 
		 { 
		 		remove(this.el);
		 		var lc = $id("epc");
				if (lc && lc.childNodes.length == 0)
				{
					$id("noFavourites").style.display = "";
				}		
		 } 
	}).toggle('height');
}

function rmReminder()
{
	new Ajax({
			url	: this.parentNode.href + '?confirm=Yes',
			method: 'get'
	});	
	;(new fx.FadeSize(this.parentNode.parentNode.parentNode.parentNode, {
			 duration: 500, onComplete: function() {remove(this.el)} 
		})).toggle('height');
}

function niceExtend(dest, src){
	if(!src) return dest
	if(src.html) { dest.innerHTML = src.html; delete src.html }
	if(src.css) { dest.className = src.css; delete src.css }
	if(src.attr) {
		var s = src.attr
		for(var k in s) dest.setAttribute(k, s[k])
		delete src.attr
	}
	if(src.style) {
		var d = dest.style, s = src.style
		for(var k in s) d[k] = s[k]
		delete src.style
	}
	for(var k in src) dest[k] = src[k]
	return dest
}

function remove()
{
	for (var i=0, o; o=arguments[i]; i++)
	{
		if (o && o.parentNode)
		{
			o.parentNode.removeChild(o);
		}
	}
}

function create(o,t)
{
	if (o == 'text')
	{
		return document.createTextNode(t||'')
	}
	else 
	{
		var e = document.createElement(o)
		if (t) 
		{
			if (typeof t == 'string')
			{
				e.innerHTML = t;
			}
			else
			{
				niceExtend(e, t);
			}
		}
		return e
	}
}

var _cachedHTML = "";

function showSortList()
{
	var productList = $id("epc");
	var sortList = $id("sortList");
	
	if (sortList && productList)
	{
		if (productList.style.display == "")
		{
			var elements = document.getElementsByTagName("span");
			var pSort = $id("productSort");
			var re = new RegExp("PEN_([0-9]+)");
			if (pSort)
			{
				pSort.options.length = 0;
				for (var i = 0; i < elements.length; i++)
				{
					var m = re.exec(elements[i].id);
					if (m)
					{
						var opt = create('option', {'html':elements[i].innerHTML,'attr':{'value':m[1]}});
						pSort.appendChild(opt);
					}
				}
			}
			sortList.style.display = "";
			productList.style.display = "none";
		}
		else
		{
			sortList.style.display = "none";
			productList.style.display = "";
		}
	}
}

function updateProductList()
{
	var productList = $id("epc");
	var pSort = $id("productSort");
	if (productList && pSort)
	{
		var elementList = [];
		for (var i = 0; i < pSort.length; i++)
		{
			var product = $id("p" + pSort[i].value);
			if (product)
			{
				elementList[i] = $id("p" + pSort[i].value);
				productList.removeChild(elementList[i]);
			}
		}
		for (var x = 0; x < elementList.length; x++)
		{
			productList.appendChild(elementList[x]);
		}	
	}
}

function togglePanel(){
	var el = $id(this.id.substring(0, this.id.length-5));
	if (el)
	{
		if (el.className == 'open_panel')
		{
			el.className = 'closed_panel';
		}
		else
		{
			el.className = 'open_panel';
		}
		setCookie(el.id + "_toggle", el.className);
	}
}

function showProducts()
{
	var u = $id("unentitled_prods");
	var e = $id("entitled_prods");
	var sp = $id("showProducts");
	switch (parseInt(sp.value))
	{
		case 0:
			if (u) u.className = 'open_panel';
			if (e) e.className = 'open_panel';
			break;
		case 1:
			if (u) u.className = 'closed_panel';
			if (e) e.className = 'open_panel';
			break;
		case 2:
			if (u) { u.className = 'open_panel'; }
			if (e) { e.className = 'closed_panel'; }
			break;
	}
}

function moveUp()
{
	var obj = $id("productSort");
	var current;
	var reverse;
	var icurrentID;
	var ireverseID;
	
	if(obj && obj.options[obj.options.selectedIndex].index > 0)
	{
		current = obj.options[obj.options.selectedIndex].text;
		reverse = obj.options[obj.options[obj.options.selectedIndex].index-1].text;
		icurrentID = obj.options[obj.options.selectedIndex].value;
		ireverseID = obj.options[obj.options[obj.options.selectedIndex].index-1].value;
		obj.options[obj.options.selectedIndex].text = reverse;
		obj.options[obj.options[obj.options.selectedIndex].index-1].text = current;
		obj.options[obj.options.selectedIndex].value = ireverseID;
		obj.options[obj.options[obj.options.selectedIndex].index-1].value = icurrentID;
		self.focus();
		obj.options.selectedIndex--;
	}
}

function moveDown()
{
	var obj = $id("productSort");
	var current;
	var next;
	var icurrentID;
	var inextID;
	if(obj && obj.options[obj.options.selectedIndex].index != obj.length-1)
	{
		current = obj.options[obj.options.selectedIndex].text;
		next = obj.options[obj.options[obj.options.selectedIndex].index+1].text;
		icurrentID = obj.options[obj.options.selectedIndex].value;
		inextID = obj.options[obj.options[obj.options.selectedIndex].index+1].value;
		
		obj.options[obj.options.selectedIndex].text =  next;
		obj.options[obj.options[obj.options.selectedIndex].index+1].text = current;
		obj.options[obj.options.selectedIndex].value =  inextID;
		obj.options[obj.options[obj.options.selectedIndex].index+1].value = icurrentID;
		
		self.focus();
		obj.options.selectedIndex++;
	}
}

function saveSortOrder()
{
	var postBody = "";
	
	var productList = $id("productSort");
	if (productList)
	{
		var postBody = "";
		
		var isf = $id("isf");
		if (isf)
		{
			postBody += 'favourites=' + isf.value + '&';
		}
		
		postBody += 'productList=';
		
		if (productList.tagName.toLowerCase() != "select")
		{
			return;
		}
		
		for (var i = 0; i < productList.length; i++)
		{
			postBody = postBody + productList[i].value + '|';
		}

		postBody = postBody.substring(0,postBody.length -1);
		busy();
		new Ajax({
				url	: 'saveSortedProducts.jsp',
				postBody: postBody,
				method: 'post',
				onComplete: function(transport){
					clearBusy();
					updateProductList();
					showSortList();
				}
		});
	}
}

function setTabSeen(tab)
{
	new Ajax({
			url	: 'profileUpdatedController.jsp?tab=' + tab,
			method: 'get'
	});
}

var onclicks = {
	'rmAdd': rmAdd,
	'rmRemove': rmRemove,
	'rmRemoveFavourite': rmRemoveFavourite,
	'openPanel': togglePanel,
	'closedPanel': togglePanel,
	'rmReminder':	rmReminder,
	'popup': popupWindow,
	'switchToGuest': switchToGuest,
	'sortProducts': showSortList,
	'mu': moveUp,
	'md': moveDown,
	'saveSort': saveSortOrder,
	'showProducts': showProducts
}

var language = {
	"addFavourite"		: "Add to Favourites",
	"rmFavourite"			: "Remove from Favourites",
	"startSaving"			: "Saving...",
	"unsavedChanges"	: "You are navigating away from the page without saving your changes. Do you want to abandon the changes?"
}

function epSystemLoad()
{
	var className = "";
	var elements = {0:$id("unentitled_prods"), 1:$id("entitled_prods")};
	for (var x in elements)
	{
		if (elements[x])
		{
			className = getCookie(elements[x].id + "_toggle");
			if (className)
			{
				elements[x].className = className;
			}
		}
	}
}

function epSystemOnLoad()
{
  var oldOnLoad;
  oldOnLoad = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = function() {
      epSystemLoad();
    };
  } else {
    window.onload = function() {
      oldOnLoad();
      epSystemLoad();
    };
  }
}

epSystemOnLoad();