//-------------------------------------------------------------------------
// This source code is confidential proprietary information which is
// Copyright (c) 1999, 2010 by Great Hill Corporation.
// All Rights Reserved.
//-------------------------------------------------------------------------
// A collection of utility functions for read, writing and removing
// cookies and generating HTML code

//=====================
// COOKIE LIBRARY
//=====================

//--------------------------------
//-- Return the actual value of the cookie
function getCookieValue(offset)
{
	var endstr = document.cookie.indexOf(";", offset);
	if (endstr == -1)
		endstr = document.cookie.length;

	return unescape(document.cookie.substring(offset, endstr));
}

//--------------------------------
//-- Find and return the value of the given cookie or null if not found
function GetCookie(name)
{
	var arg  = name + "=";
	var alen = arg.length;
	var clen = document.cookie.length;

	var i = 0;
	while (i < clen)
	{
		var j = i + alen;
		if (document.cookie.substring(i, j) == arg) 
		{
			return getCookieValue(j);
		}
		i = document.cookie.indexOf(" ", i) + 1;
		if (i == 0)
			break;
	}

	return null;
}

//--------------------------------
//-- Set the value of the 'name' cookie
function SetCookie(name, value)
{
	var argv    = SetCookie.arguments;
	var argc    = SetCookie.arguments.length;
	var expires = (argc > 2) ? argv[2] : null;
	var path    = (argc > 3) ? argv[3] : null;
	var domain  = (argc > 4) ? argv[4] : null;
	var secure  = (argc > 5) ? argv[5] : false;

	document.cookie = name + "=" + escape (value) +
										((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
										((path == null) ? "" : ("; path=" + path)) +
										((domain == null) ? "" : ("; domain=" + domain)) +
										((secure == true) ? "; secure" : "");
}

//--------------------------------
//-- Write a cookie including expiration date
function WriteCookie(name, value, nMonths)
{
	// Make it five years from now
	var expires = new Date();
	var mon = expires.getMonth();
	mon += nMonths;
	if (mon > 12)
	{
		expires.setMonth(mon-12);
		expires.setFullYear(expires.getFullYear() + 1);
	} else
	{
		expires.setMonth(mon);
	}
	SetCookie(name, value, expires, "/");
}

//--------------------------------
//-- Remove a cookie
function ExpireCookie(name)
{
	var expdate = new Date();
	expdate.setFullYear(expdate.getFullYear() - 1);
	SetCookie(name, "", expdate, "/");
}

//--------------------------------
function setDisabled(itemName, state)
{
	for (j=0;j<document.dialogForm.elements.length;j++)
	{
		if (document.dialogForm.elements[j].name == itemName)
		{
			document.dialogForm.elements[j].disabled = state;
			return;
		}
	}
}

//--------------------------------
function setDisabled_scan(itemName, state) // does not stop short since there are more than one with same name
{
	for (j=0;j<document.dialogForm.elements.length;j++)
		if (document.dialogForm.elements[j].name == itemName)
			document.dialogForm.elements[j].disabled = state;
}

//--------------------------------
function enableAll()
{
	if (document.dialogForm && document.dialogForm.elements)
		for (j=0;j<document.dialogForm.elements.length;j++)
			document.dialogForm.elements[j].disabled = false;
}

//--------------------------------
function setCheck(itemName, state)
{
	for (j=0;j<document.dialogForm.elements.length;j++)
	{
		if (document.dialogForm.elements[j].name == itemName)
		{
			document.dialogForm.elements[j].checked = state;
			return;
		}
	}
}

//--------------------------------
function setFormFocus(focusName)
{
	for (i=0;i<document.forms.length;i++)
	{
		for (j=0;j<document.forms[i].elements.length;j++)
		{
			if (document.forms[i].elements[j].name == focusName)
			{
				if (document.forms[i].elements[j].type != "hidden")
					document.forms[i].elements[j].focus();
				return;
			}
		}
	}
}

//--------------------------------
function setImageSource(itemName, image)
{
	for (j=0;j<document.images.length;j++)
	{
		if (document.images[j].name == itemName)
		{
			document.images[j].src = image;
			return;
		}
	}
}

//--------------------------------
function setLinkURL(itemName, newURL)
{
	for (j=0;j<document.links.length;j++)
	{
		if (document.links[j].name == itemName)
		{
			document.links[j].href = newURL;
			return;
		}
	}
}

//--------------------------------
var colorArray =
[
	"default",              "black",          "navy",         "darkblue",        "mediumblue",       "blue",
	"darkgreen",            "green",          "teal",         "darkcyan",        "deepskyblue",      "darkturquoise",
	"mediumspringgreen",    "lime",           "springgreen",  "aqua",            "cyan",             "midnightblue",
	"dodgerblue",           "lightseagreen",  "forestgreen",  "seagreen",        "darkslategray",    "limegreen",
	"mediumseagreen",       "turquoise",      "royalblue",    "steelblue",       "darkslateblue",    "mediumturquoise",
	"indigo",               "darkolivegreen", "cadetblue",    "cornflowerblue",  "mediumaquamarine", "dimgray",
	"slateblue",            "olivedrab",      "slategray",    "lightslategray",  "mediumslateblue",  "lawngreen",
	"chartreuse",           "aquamarine",     "maroon",       "purple",          "olive",            "gray",
	"skyblue",              "lightskyblue",   "blueviolet",   "darkred",         "darkmagenta",      "saddlebrown",
	"darkseagreen",         "lightgreen",     "mediumpurple", "darkviolet",      "palegreen",        "darkorchid",
	"yellowgreen",          "sienna",         "brown",        "darkgray",        "lightblue",        "greenyellow",
	"paleturquoise",        "lightsteelblue", "powderblue",   "firebrick",       "darkgoldenrod",    "mediumorchid",
	"rosybrown",            "darkkhaki",      "silver",       "mediumvioletred", "indianred",        "peru",
	"chocolate",            "tan",            "lightgrey",    "thistle",         "orchid",           "goldenrod",
	"palevioletred",        "crimson",        "gainsboro",    "plum",            "burlywood",        "lightcyan",
	"lavender",             "darksalmon",     "violet",       "palegoldenrod",   "lightcoral",       "khaki",
	"aliceblue",            "honeydew",       "azure",        "sandybrown",      "wheat",            "beige",
	"whitesmoke",           "mintcream",      "ghostwhite",   "salmon",          "antiquewhite",     "linen",
	"lightgoldenrodyellow", "oldlace",        "red",          "fuchsia",         "magenta",          "deeppink",
	"orangered",            "tomato",         "hotpink",      "coral",           "darkorange",       "lightsalmon",
	"orange",               "lightpink",      "pink",         "gold",            "peachpuff",        "navajowhite",
	"moccasin",             "bisque",         "mistyrose",    "blanchedalmond",  "papayawhip",       "lavenderblush",
	"seashell",             "cornsilk",       "lemonchiffon", "floralwhite",     "snow",             "yellow",
	"lightyellow",          "white",          "white"
];

//--------------------------------
function getColorOptions(selected)
{
	for (i=0;i<141;i++)
	{
		document.write("<option value=\"" + i + "\"");
		if (i == selected)
			document.write(" selected");
		document.write(">");
		document.write(colorArray[i]);
	}
}

//--------------------------------
function getColorNameAt(index)
{
	if (index == 0)
		return "default";

	if (index > 0 && index < 141)
		return colorArray[index];
	
	return "";
}

//--------------------------------
function popWindow(url)
{
	page = window.open(url, "Review", 'width=635,height=400,scrollbars=1,resizable=1,toolbars=0,location=0,statusbars=0,menubars=0');
}

//--------------------------------
function strrev(str)
{
   if (!str)
		return '';

   var revstr='';
   for (i = str.length-1; i>=0; i--)
       revstr+=str.charAt(i);

   return revstr;
}

//--------------------------------
function getFilename(str)
{
	var ret = strrev(str);
	var find = ret.indexOf("/");
	if (find == -1)
		return str;

	ret = ret.substring(0, find);
	ret = strrev(ret);
	return ret;
}

//--------------------------------
function makeDate(y, m, d)
{
	var ret = new Date();

	ret.setFullYear(y);
	ret.setMonth   (m-1);
	ret.setDate    (d);

	return ret;
}

//--------------------------------
function addEvent( obj, type, fn )
{
	if (obj.addEventListener)
	{
		obj.addEventListener( type, fn, false );
		EventCache.add(obj, type, fn);
	} else if (obj.attachEvent)
	{
		obj["e"+type+fn] = fn;
		obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
		obj.attachEvent( "on"+type, obj[type+fn] );
		EventCache.add(obj, type, fn);
	} else
	{
		obj["on"+type] = obj["e"+type+fn];
	}
}

//--------------------------------
var EventCache = function(){
	var listEvents = [];
	return {
		listEvents : listEvents,
		add : function(node, sEventName, fHandler){
			listEvents.push(arguments);
		},
		flush : function(){
			var i, item;
			for(i = listEvents.length - 1; i >= 0; i = i - 1){
				item = listEvents[i];
				if(item[0].removeEventListener){
					item[0].removeEventListener(item[1], item[2], item[3]);
				};
				if(item[1].substring(0, 2) != "on"){
					item[1] = "on" + item[1];
				};
				if(item[0].detachEvent){
					item[0].detachEvent(item[1], item[2]);
				};
				item[0][item[1]] = null;
			};
		}
	};
}();

//--------------------------------
function toggleHints(onOff)
{
	WriteCookie('hints', '<hints>' + onOff + '</hints>;', 3);
	var sp = document.getElementById('hint_span1');
	if (sp)
	{
		if (onOff)
		{
			sp.innerHTML = spanOn;

		} else
		{
			sp.innerHTML = spanOff;
		}
		sp.align='middle';
	}
}

//--------------------------------
addEvent(window,   'unload', EventCache.flush);

//--------------------------------
function JSWindow(title, divName, windowID)
{
	// define variables
	this.title    = title;
	this.oContent = document.getElementById(divName);
	this.moveable = false;
	
	// create the table window and define CSS properties
	this.oTable                = document.createElement("table");
	this.oTable.id             = windowID;
	this.oTable.style.width    = "12px"; // content forces width
	this.oTable.style.border   = "1px solid black";
	this.oTable.cellSpacing    = 0;
	this.oTable.cellPadding    = 2;
	this.oTable.border         = 0;
	this.oTable.style.backgroundColor = "#FFFFFF";
	this.oTable.style.position = "absolute";
	this.oTable.className      = "cw_css_popupbody";

	// link from the table to the JSWindow object
	this.oTable.jsWindow = this;

	// if the table is clicked anywhere, show the table in front of other open windows
	this.oTable.onmousedown = JSWindow.prototype.onBringToFront;

	// append to document body
	document.body.appendChild(this.oTable);

	// add a row for the titlebar
	var oTR = this.oTable.insertRow(0);
	oTR.className = "cw_css_popuphead";
	
	// Title: add the title to the titlebar	
	oTD = oTR.insertCell(0);
	oTD.innerHTML = title;
	oTD.jsWindow = this;
	oTD.onmousedown = JSWindow.prototype.tdOnMouseDown;
	oTD.style.borderBottom = "1px solid #000000";
	oTD.height = "20";
	oTD.width = "98%";
	
	// Close: add the close button to the titlebar
	oTD = oTR.insertCell(1); 
	oTD.innerHTML = "<a href=#><img border=0 width=18 src=" + baseRoot + "cw_images/error.gif align=absmiddle></a>";
	oTD.jsWindow = this;
	oTD.style.align = "right";
	oTD.onmousedown = JSWindow.prototype.onClose;
	oTD.style.color = "black";
	oTD.style.borderBottom = "1px solid #000000";
	oTD.width = "2%";
	oTD.style.paddingLeft = "1px";
	
	// add a row for the window's content
	oTR = this.oTable.insertRow(1);
	
	this.oContentTD = oTR.insertCell(0);
	this.oContentTD.colSpan = 2;
	this.oContentTD.style.backgroundColor = this.bgcolor;
	this.oContentTD.className = "cw_css_popupbody";
 
	// use the content from the referenced div as the content for the window
	var thisDiv = document.getElementById(divName);
	if (thisDiv)
		this.oContentTD.innerHTML = thisDiv.innerHTML;
}

JSWindow.prototype.onBringToFront = function()
{
	this.jsWindow.bringToFront();
}

JSWindow.prototype.bringToFront = function()
{
	// if not already the last child of the document.body, make it so
	if ( document.body.childNodes[document.body.childNodes.length-1] !== this.oTable )
	{
		// move to bottom of document
		document.body.appendChild(this.oTable);
	}
}

JSWindow.prototype.tdOnMouseDown = function()
{
	this.jsWindow.onMouseDown();
}

JSWindow.prototype.onMouseDown = function()
{
	if (this.moveable)
	{
		// record that an onmousedown has just occurred
		this.bDown = true;

		// link from body to this JSWindow object
		document.body.jsWindow = this;

		// save body mouse handlers
		this.saveMouseMove = document.body.onmousemove;
		this.saveMouseUp = document.body.onmouseup;

		// set new handlers.
		document.body.onmousemove = JSWindow.prototype.bodyOnMouseMove;
		document.body.onmouseup = JSWindow.prototype.bodyOnMouseUp;
	}
}

JSWindow.prototype.bodyOnMouseMove = function(evt)
{
	var e = window.event ? window.event : evt;
	this.jsWindow.onMouseMove(e);
}

JSWindow.prototype.onMouseMove = function(evt)
{
	if (this.moveable)
	{
		// if mouse not down, stop the move (for IE only)
		if ( (document.all) && !(evt.button & 1) )
		{
			this.onMouseUp();
			return;
		}
		if ( this.bDown )
		{
			this.dx = parseInt(this.oTable.style.left, 10) - evt.clientX;
			this.dy = parseInt(this.oTable.style.top, 10) - evt.clientY;
			this.bDown = false;
		}
		else
		{
			this.oTable.style.left = Math.max((this.dx + evt.clientX),0) + "px";
			this.oTable.style.top = Math.max((this.dy + evt.clientY),0) + "px";
		}
	}
}

JSWindow.prototype.bodyOnMouseUp = function()
{
	this.jsWindow.onMouseUp();
}

JSWindow.prototype.onMouseUp = function()
{
	if (this.moveable)
	{
		document.body.onmouseup = this.saveMouseUp;
		document.body.onmousemove = this.saveMouseMove;
		document.body.jsWindow = null;
	}
}

JSWindow.prototype.close = function()
{	
	// remove from browser document
	this.oTable.parentNode.removeChild(this.oTable);
}

JSWindow.prototype.onClose = function()
{
	this.jsWindow.close();
}

function createWindow(title, controlName)
{
	closeAllPopups();

	var divName    = controlName + "Div";
	var windowID   = controlName + "Window";
	var buttonName = controlName + "Button";

	var item = document.getElementById(windowID);
	if (item)
	{
		item.parentNode.removeChild(item);

	} else
	{
		item = new JSWindow(title, divName, windowID); 

		// the window is not showing so move it to the proper place
		var left = 0;
		var top  = 0;

		// travel up the chain to the body tag accumulating the offests all the way up
		// so we can position the popup window
		var button = document.getElementById(buttonName);
		for (var p = button; p && p.tagName != 'BODY'; p = p.offsetParent)
		{
			left += p.offsetLeft;
			top  += p.offsetTop;
		}

		var buttonHeight = button.offsetHeight;
		var windowHeight = (12*32)+(12*6);
		var scrollTop    = document.body.scrollTop;

		var tl = left + 34;
		var tt = top  + buttonHeight - 21;

		if (tt + item.oTable.clientHeight - scrollTop > document.body.clientHeight)
			tt = document.body.clientHeight - item.oTable.clientHeight + scrollTop;

		if (tl + item.oTable.clientWidth - document.body.scrollLeft > document.body.clientWidth)
			tl -= (item.oTable.clientWidth + 34);

		item.oTable.style.left = tl + "px";
		item.oTable.style.top = tt + "px";
	}
}

function closeOnePopup(name)
{
	var win = document.getElementById(name);
	if (win)
		win.parentNode.removeChild(win);
}

function popupClicked(controlName, valueSelected)
{
	var item = document.getElementById(controlName);
	if (item)
		item.value = valueSelected;
	closeOnePopup(controlName + 'Window');
}

function makePopupHeadFoot(controlName, isHead)
{
	if (isHead)
	{
		document.write("<div id=" + controlName + "Div style=display:none>");
		document.write("<table cellpadding=0 cellspacing=1 width=100%><tr>");
	} else
	{
		document.write("</tr></table>");
		document.write("</div>");
	}
}

function makePopupFromArray(controlName, nValues, values, renderFunc)
{
	makePopupHeadFoot(controlName, true);

	for (index = 0; index < nValues; index++)
	{
		renderFunc(controlName, values[index], index);
	}

	makePopupHeadFoot(controlName, false);
}

function makePopupFromSelect(controlName, renderFunc)
{
	makePopupHeadFoot(controlName, true);

	var selector = document.getElementById(controlName);
	if (selector)
	{
		for (index = 0;index < selector.options.length ; index++)
			renderFunc(controlName, selector.options[index].value, index);
	}

	makePopupHeadFoot(controlName, false);
}

function makePopupButton(title, controlName, buttonImg)
{
	var code = "";
	code += "<a onclick=\"createWindow('<b>" + title + "</b>', '" + controlName + "');\">";
	code += "<img align=absmiddle style=position:relative id=" + controlName + "Button border=0 src=" + buttonImg + ">";
	code += "</a>";
	document.write(code);
}

function makePopupArray(title, controlName, buttonImg, renderFunc, nValues, values)
{
	makePopupFromArray(controlName, nValues, values, renderFunc);
	makePopupButton(title, controlName, buttonImg);
}

function makePopupSelect(title, controlName, buttonImg, renderFunc)
{
	makePopupFromSelect(controlName, renderFunc);
	makePopupButton(title, controlName, buttonImg);
}

function closeAllPopups()
{
	closeOnePopup('artworkWindow');
	closeOnePopup('nameWindow');
	closeOnePopup('name2Window');
	closeOnePopup('textcolorWindow');
	closeOnePopup('bgcolorWindow');
}

function iconRenderFunc(controlName, value, index)
{
	var code = "<td ";

	if (index == 0) return;

	code += "class=cw_css_popupitem>";
	code += "<a href=\"javascript:popupClicked('" + controlName + "', '" + value + "')\" >";
	code += "<img ";
	code += "alt=\"" + value + "\" ";
	code += "title=\"" + value + "\" ";
	code += "src=\"" + baseRoot + value + "\"";
	code += "></a></td>";
	if (!((index) % 12))
		code += "</tr><tr>";

	document.write(code);
}

function contactClicked(controlName, valueSelected)
{
	var item = document.getElementById(controlName);
	if (item)
		item.value = valueSelected;
	closeOnePopup(controlName + 'Window');
}

function contactRenderFunc(controlName, value, index)
{
	var code;

	code  = "<td nowrap class=cw_css_popupitem>&nbsp;&nbsp;";
	code += "<a ";
	code += "href=# ";
	code += "onClick=\"javascript:contactClicked('" + controlName + "', '" + value + "')\" ";
	code += ">";
	code += value;
	code += "</a>";
	code += "&nbsp;&nbsp;</td>";
	if (!((index+1) % 2))
		code += "</tr><tr>";
	
	document.write(code);
}

function colorRenderFunc(controlName, value, index)
{
	if (index==0)
		return;

	var colorName = getColorNameAt(value);

	var code;

	code  = "<td class=cw_css_popupitem width=15>";
	code += "<a style='height:10px;width:15px;' ";
	code += "title=" + colorName + " onClick=\"javascript:popupClicked('" + controlName + "', '" + value + "')\"";
	code += "><img style='background:"+colorName+";height:10px;width:15px;border:0' src=" + baseRoot + "cw_templates/blank.gif></a>";
	code += "</td>";
	if (!((index) % 14))
		code += "</tr><tr>";

	document.write(code);
}

function AddFavorite(url, title)
{
	if (window.sidebar)
	{
		window.sidebar.addPanel( title, url, "");

	} else if (window.external)
	{
		window.external.AddFavorite( url, title );

	} else if (window.opera && window.print)
	{
		return true;
	}
}

