//
// Copyright (c) 2007-2008 Stardock Systems, Inc.
// Author: Andrew Powell, 10.30.07
// Version 1.0
// Version 1.1 ~ 11.20.07
// Version 1.1 ~ 04.14.08
//
// http://prototype.conio.net/

//var Class = {
//  create: function() {
//    return function() {
//      this.initialize.apply(this, arguments);
//    }
//  }
//}
//
//// Taken from protoype. magically copies properties over. 
//Object.extend = function(destination, source) {
//  for (var property in source) {
//    destination[property] = source[property];
//  }
//  return destination;
//}



/* Based on Alex Arnell's inheritance implementation. */
var Class = {
  create: function() {
    var parent = null, properties = $A(arguments);
    if (Object.isFunction(properties[0]))
      parent = properties.shift();

    function klass() {
      this.initialize.apply(this, arguments);
    }

    Object.extend(klass, Class.Methods);
    klass.superclass = parent;
    klass.subclasses = [];

    if (parent) {
      var subclass = function() { };
      subclass.prototype = parent.prototype;
      klass.prototype = new subclass;
      parent.subclasses.push(klass);
    }

    for (var i = 0; i < properties.length; i++)
      klass.addMethods(properties[i]);

    if (!klass.prototype.initialize)
      klass.prototype.initialize = function() { };

    klass.prototype.constructor = klass;

    return klass;
  }
};

Class.Methods = {
  addMethods: function(source) {
    var ancestor   = this.superclass && this.superclass.prototype;
    var properties = Object.keys(source);

    if (!Object.keys({ toString: true }).length)
      properties.push("toString", "valueOf");

    for (var i = 0, length = properties.length; i < length; i++) {
      var property = properties[i], value = source[property];
      if (ancestor && Object.isFunction(value) &&
          value.argumentNames().first() == "$base") {
        var method = value, value = Object.extend((function(m) {
          return function() { return ancestor[m].apply(this, arguments) };
        })(property).wrap(method), {
          valueOf:  function() { return method },
          toString: function() { return method.toString() }
        });
      }
      this.prototype[property] = value;
    }

    return this;
  }
};

var Abstract = { };

Object.extend = function(destination, source) {
  for (var property in source)
    destination[property] = source[property];
  return destination;
};

Object.extend(Object, {
  keys: function(object) {
    var keys = [];
    for (var property in object)
      keys.push(property);
    return keys;
  },

  values: function(object) {
    var values = [];
    for (var property in object)
      values.push(object[property]);
    return values;
  },

  isFunction: function(object) {
    return typeof object == "function";
  },

  isString: function(object) {
    return typeof object == "string";
  }
});

Object.extend(Function.prototype, {
  argumentNames: function() {
    var names = this.toString().match(/^[\s\(]*function[^(]*\((.*?)\)/)[1].split(",").invoke("strip");
    return names.length == 1 && !names[0] ? [] : names;
  },

  bind: function() {
    if (arguments.length < 2 && arguments[0] === undefined) return this;
    var __method = this, args = $A(arguments), object = args.shift();
    return function() {
      return __method.apply(object, args.concat($A(arguments)));
    }
  },

  delay: function() {
    var __method = this, args = $A(arguments), timeout = args.shift() * 1000;
    return window.setTimeout(function() {
      return __method.apply(__method, args);
    }, timeout);
  },

  wrap: function(wrapper) {
    var __method = this;
    return function() {
      return wrapper.apply(this, [__method.bind(this)].concat($A(arguments)));
    }
  }
});

Object.extend(String.prototype, {
  strip: function() {
    return this.replace(/^\s+/, '').replace(/\s+$/, '');
  }
});

var $break = { };

Object.extend(Array.prototype, 
{
  _each: function(iterator) {
    for (var i = 0, length = this.length; i < length; i++)
      iterator(this[i]);
  },
  clear: function() {
    this.length = 0;
    return this;
  },
  first: function() {
    return this[0];
  },
  last: function() {
    return this[this.length - 1];
  },
  clone: function() {
    return [].concat(this);
  },
  invoke: function(method) {
    var args = $A(arguments).slice(1);
    return this.map(function(value) {
      return value[method].apply(value, args);
    });
  },
  each: function(iterator, context) {
    var index = 0;
    iterator = iterator.bind(context);
    try {
      this._each(function(value) {
        iterator(value, index++);
      });
    } catch (e) {
      if (e != $break) throw e;
    }
    return this;
  },  
  map: function(iterator, context) {
    iterator = iterator ? iterator.bind(context) : function(x) { return x };
    var results = [];
    this.each(function(value, index) {
      results.push(iterator(value, index));
    });
    return results;
  },
  contains: function(what)
  {
		for (var i = 0, length = this.length; i < length; i++)
			if(this[i] == what) return true;
		return false;
  }    
});

Function.prototype.bind = function() {
  var __method = this, args = $A(arguments), object = args.shift();
  return function() {
    return __method.apply(object, args.concat($A(arguments)));
  }
};

Boolean.prototype.parse = function(value)
{
  if (typeof(value)=='string')
  {
    return (value.toLowerCase()=='true');
  }
  return value ?true :false;
};

String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); };
String.prototype.endsWith = function(s){ var reg = new RegExp(s + "$"); return reg.test(this); };
String.prototype.removeHtml = function(replaceBrackets)
{
	 var text = new String(this);
   // This line is optional, it replaces escaped brackets with real ones, i.e. < is replaced with < and > is replaced with >
   if(replaceBrackets && replaceBrackets == true) text = text.replace(/&(lt|gt);/g, function (strMatch, p1){ return (p1 == "lt")? "<" : ">"; });
   text = text.replace(/<\/?[^>]+(>|$)/g, '');
   return text;
};
String.prototype.replaceBreaks = function()
{
   text = this.replace(/\r\n/gi, '<br/>');
   text = text.replace(/\r\n/gi, '<br/>');
   return text;
};
String.prototype.replaceNewLines = function()
{
   var text = this.replace(/\r\n/gi, '<br>');
   text = text.replace(/\n/gi, '<br>');
   text = text.replace(/\r/gi, '<br>');
   text = text.replace(/\r\n/gi, '<br/>');
   text = text.replace(/\n/gi, '<br/>');
   text = text.replace(/\r/gi, '<br/>');
   return text;
};


RegExp.prototype.escape = function(s)
{
	var specials = ['/', '.', '*', '+', '?', '|','(', ')', '[', ']', '{', '}', '\\'];
  var r = new RegExp('(\\' + specials.join('|\\') + ')', 'g');
  return s.replace(r, '\\$1');
};

Date.prototype.MonthNames = new Array('January','February','March','April','May','June','July','August','September','October','November','December');
Date.prototype.DayNames = new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');
Date.prototype.format = function(f)
{
  if (!this.valueOf())
      return 'n.a.';// 

  var d = this;
  return f.replace(/(yyyy|yy|y|MMMM|MMM|MM|M|dddd|ddd|dd|d|HH|H|hh|h|mm|m|ss|s|t|x)/gi,
    function($1)
    {
      switch ($1)
      {
        case 'yyyy': return d.getFullYear();
        case 'yy':   return (d.getFullYear()%100).zf(2);
        case 'y':    return (d.getFullYear()%100);
        case 'MMMM': return Date.MonthNames[d.getMonth()];
        case 'MMM':  return Date.MonthNames[d.getMonth()].substr(0, 3);
        case 'MM':   return (d.getMonth() + 1).zf(2);
        case 'M':    return (d.getMonth() + 1);
        case 'dddd': return Date.DayNames[d.getDay()];
        case 'ddd':  return Date.DayNames[d.getDay()].substr(0, 3);
        case 'dd':   return d.getDate().zf(2);
        case 'd':     return d.getDate();
        case 'HH':   return d.getHours().zf(2);
        case 'H':    return d.getHours();
        case 'hh':   return ((h = d.getHours() % 12) ? h : 12).zf(2);
        case 'h':    return ((h = d.getHours() % 12) ? h : 12);
        case 'mm':   return d.getMinutes().zf(2);
        case 'm':    return d.getMinutes();
        case 'll':   return (d.getSeconds() / 1000);
        case 'ss':   return d.getSeconds().zf(2);
        case 's':    return d.getSeconds();
        case 't':     return d.getHours() < 12 ? 'am' : 'pm';
        case 'x':
		 			switch (d.getDate())
		      {
			      case 1:
			      case 21:
			      case 31:
			          return "st";
			      case 2:
			      case 22:
			          return "nd";
			      case 3:
			      case 23:
			          return "rd";
			      default:
			          return "th";
		      }                    
    	}            
		}
  );
};
Date.prototype.ticks = function()
{
	 var date = this;
   this.day = date.getDate();
   this.month = date.getMonth() + 1;
   this.year = date.getFullYear();
   this.hour = date.getHours();
   this.minute = date.getMinutes();
   this.second = date.getSeconds();
   this.ms = date.getMilliseconds();
   
   this.monthToDays = function(year, month)
   {
      var add = 0;
      var result = 0;
	    if((year % 4 == 0) && ((year % 100  != 0) || ((year % 100 == 0) && (year % 400 == 0)))) add++;
         
      switch(month)
      {
         case 0: return 0;
         case 1: result = 31; break;
         case 2: result = 59; break;
         case 3: result = 90; break;
         case 4: result = 120; break;
         case 5: result = 151; break;
         case 6: result = 181; break;
         case 7: result = 212; break;
         case 8: result = 243; break;
         case 9: result = 273; break;
         case 10: result = 304; break;
         case 11: result = 334; break;
         case 12: result = 365; break;
      }
      if(month > 1) result += add;
      return result;      
   };

   this.dateToTicks = function(year, month, day)
   {
      var a = parseInt((year - 1) * 365);
      var b = parseInt((year - 1) / 4);
      var c = parseInt((year - 1) / 100);
      var d = parseInt((a + b) - c);
      var e = parseInt((year - 1) / 400);
      var f = parseInt(d + e);
      var monthDays = this.monthToDays(year, month - 1);
      var g = parseInt((f + monthDays) + day);
      var h = parseInt(g - 1);
      return h * 864000000000;
   };

   this.timeToTicks = function(hour, minute, second)
   {
      return (((hour * 3600) + minute * 60) + second) * 10000000;
   };
   
   return this.dateToTicks(this.year, this.month, this.day) + this.timeToTicks(this.hour, this.minute, this.second) + (this.ms * 10000);
};

function $id(id, element, type)
{
    /// <param name="id" type="String"></param>
    /// <param name="element" domElement="true" optional="true" mayBeNull="true"></param>

		if(type) return $partial(id, element, type);
    if (!element)
    {
    	var ele = document.getElementById(id);
    	if(ele) Sd.Proto.extend(ele);
    	return ele;
   	}
   	
    if (element.getElementById)
    {
    	var ele = element.getElementById(id);
    	if(ele) Sd.Proto.extend(ele);
    	return ele;    	
   	}

    var nodeQueue = [];
    var childNodes = element.childNodes;
    if(!childNodes) return null;
    for (var i = 0; i < childNodes.length; i++)
    {
        var node = childNodes[i];
        if (node.nodeType == 1)
        {
            nodeQueue[nodeQueue.length] = node;
        }
    }

    while (nodeQueue.length)
    {
        node = nodeQueue.shift();

        if (node.id == id)
        {
        		Sd.Proto.extend(node);
            return node;
        }
        childNodes = node.childNodes;
        for (i = 0; i < childNodes.length; i++)
        {
            node = childNodes[i];
            if (node.nodeType == 1)
            {
                nodeQueue[nodeQueue.length] = node;
            }
        }
    }

    return null;
};

function $partial(id, element, type)
{
	var childs;
	if(element)
	{
		if(!element._next) Sd.Proto.extend(element);	
		childs = element._tags(type);
	}
	else
	{
		childs = document.getElementsByTagName(type);
	}
	
	for(var i=0; i < childs.length; i++)
	{
		if(childs[i].id.indexOf(id)!=-1)
		{
			var ele = childs[i];
			if(!ele._next) Sd.Proto.extend(ele);
			return ele;
		}
	}	
	
	
//   var Collection = document.getElementsByTagName(type);
//   for(var i=0; i < Collection.length; i++)
//   {
//      if(Collection[i].id.indexOf(id)!=-1)
//      {
//         var ele = Collection[i];
//         Sd.Proto.extend(ele);
//         return ele;
//      }
//   }
//   
//   return null;
};

/*
 * Returns an array of elements from the page of type with the given server id.
 * Optional third parameter is an element that the search will be conducted in.
 * NAQ 07-18-07
 */
function $col(id,type,lookin)
{
	var Collection;
	if( typeof(lookin) != "undefined" && lookin != null ) {
	  Collection = lookin.getElementsByTagName(type);
	} else {
	  Collection = document.getElementsByTagName(type);
	}
	
	var retCol = [];
	for(var i=0; i < Collection.length; i++)
	{
	  if(Collection[i].id.indexOf(id) == Collection[i].id.length - id.length) {
	     retCol[retCol.length] = Collection[i];
	  }
	}
   
	for(var i = 0; i < retCol.length; i++)
		Sd.Proto.extend(retCol[i]);
	
	return retCol;
};

function $new(tagName, id, className)
{
	var ele = document.createElement(tagName);
	if(id) ele.id = id;
	if(className) ele.className = className;
	Sd.Proto.extend(ele);
	return ele;
};

var $A = Array.from = function(iterable) {
  if (!iterable) return [];
  if (iterable.toArray) {
    return iterable.toArray();
  } else {
    var results = [];
    for (var i = 0; i < iterable.length; i++)
      results.push(iterable[i]);
    return results;
  }
};

var Sd = Class.create();

Sd.Browser = { agent: navigator.userAgent.toLowerCase() };
Sd.Browser =
{
	agent: navigator.userAgent.toLowerCase(),
	ver: (Sd.Browser.agent.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/) || [])[1],
	verNum: parseFloat((Sd.Browser.agent.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/) || [])[1]),
	iphone: /iphone/.test(Sd.Browser.agent),
	safari: /webkit/.test(Sd.Browser.agent),
	opera: /opera/.test(Sd.Browser.agent),
	ie: /msie/.test(Sd.Browser.agent) && !/opera/.test(Sd.Browser.agent),
	moz: /mozilla/.test(Sd.Browser.agent) && !/(compatible|webkit)/.test(Sd.Browser.agent)
};


//
//
//		Sd.Common
//
//

Sd.Common = Class.create();
Sd.Common.prototype = { };
Sd.Common.Browser = Sd.Browser; //deprecated. keeping this around for older scripts.

	 Sd.Common.events = [];

   Sd.Common.cancelEvent = function(e)
   {
      var e = e || window.event;
      if(!e) return false;

      e.cancelBubble = true; // for IE
      if (typeof e.stopPropagation == 'function')
         e.stopPropagation();

      e.returnValue = false; // for IE
      if (typeof e.preventDefault == 'function')
         e.preventDefault();

      return false;
   };

   //Modified from http://weblogs.asp.net/asmith/archive/2003/10/06/30744.aspx
   Sd.Common.addEvent = function(target, eventName, func, handlerName)
   {
      if (target.addEventListener)
      {
         target.addEventListener(eventName, func, false);
         Sd.Common.events[handlerName] = func;
      }
      else if (target.attachEvent)
      {
         Sd.Common.events[handlerName] = func.bind(target);
         target.attachEvent('on' + eventName, Sd.Common.events[handlerName], false);
      }
   };

   Sd.Common.removeEvent = function(target, eventName, handlerName)
   {
      if (target.addEventListener)
      {
         target.removeEventListener(eventName, Sd.Common.events[handlerName], false);
      }
      else if (target.detachEvent)
      {
         target.detachEvent('on' + eventName, Sd.Common.events[handlerName]);
      }
   };

  Sd.Common.addDocumentReadyEvent = function(func)
  {
    if(Sd.Browser.moz || Sd.Browser.opera)
    {
    	document.addEventListener("DOMContentLoaded", func, false);
    	return;
    }
    
    if(Sd.Browser.ie)
    {
      var deferScript = $id('__init_script');

      if(!deferScript)
      {
      	document.write('<script id="__init_script" defer="true" src="//Loading..."><\/script>');
      	deferScript = $id('__init_script');
			}

      if (deferScript)
      {
        deferScript.onreadystatechange = function()
        {
          if (this.readyState == 'complete')
          {
          	if(!func.called && !func.called == true)
            {
							func.called = true;
              func();
            }
          }
        };

        deferScript.onreadystatechange();

        // clear reference to prevent leaks in IE
        deferScript = null;
        
        return;
      }
    }

		// for other browsers
   	window.onload = func;
  
  };

  Sd.Common.addDocumentReadyEventEx = function(func)
  {
		if(!Sd.Common.readyEventAdded) Sd.Common.readyEventAdded = false;
		if(!Sd.Common.readyEvents) Sd.Common.readyEvents = [];
		
		Sd.Common.readyEvents.push(func);
		
    if(Sd.Browser.moz || Sd.Browser.opera)
    {
    	if(Sd.Common.readyEventAdded == false)
    	{
    		Sd.Common.readyEventAdded = true;
    		document.addEventListener("DOMContentLoaded", Sd.Common.executeReadyEvents, false);
    	}
    	return;
    }
    
    if(Sd.Browser.ie)
    {
      var ieScript = $id('__init_scriptEx');

      if(!ieScript)
      {
      	document.write('<script id="__init_scriptEx" defer="true" src="//Loading..."><\/script>');
      	ieScript = $id('__init_scriptEx');
			}

      if (ieScript) 
      {
      	if(!ieScript.onreadystatechange)
      	{
	        ieScript.onreadystatechange = function()
	        {
	          if (this.readyState == 'complete')
	          {
	          	Sd.Common.executeReadyEvents();
	          }
	        };
      	}

        ieScript.onreadystatechange();

        // clear reference to prevent leaks in IE
        ieScript = null;
        
        return;
      }
    }

		// for other browsers
   	window.onload = Sd.Common.executeReadyEvents;
  
  };
  
  Sd.Common.executeReadyEvents = function()
  {
   	for(var i = 0; i < Sd.Common.readyEvents.length; i++)
  	{
  		var func = Sd.Common.readyEvents[i];
    	if(!func.called && !func.called == true)
      {
				func.called = true;
        func();
      }
  	}
  };

	Sd.Common.getObjectByPartialID = function(id,type)
	{
	   return $partial(id, type);
	};

	Sd.Common.strDup = function(number,str)
	{
	   var result = '';
	   for(var i=0; i < number; i++)
	   {
	      result += str;
	   }

	   return result;
	};

	Sd.Common.isNumeric = function(value)
	{
		for (var i=0; i < value.length; i++)
		{
			a = parseInt(value.charAt(i));
			if (isNaN(a))
			{
			 return false;
			 break;
			}
		}
 		return true;
	};

	Sd.Common.getElementPos = function(el)
	{
		//return an element absolute position
		var elmnt=el;
		if(!elmnt) return;

		var pos = new Object;

		//get width and height
		pos.width=elmnt.offsetWidth;
		pos.height=elmnt.offsetHeight;

		//get left and top
		pos.left = 0;
		pos.top = 0;

		// ie 5.0 counts the body as well with the full win width, so we need to stop on body
		while(elmnt != null && elmnt.nodeName != "BODY")
		{
			pos.left += elmnt.offsetLeft;
			pos.top += elmnt.offsetTop;
			elmnt=elmnt.offsetParent;
		}

		//right and bottom
		pos.right = (pos.left + pos.width);
		pos.bottom = (pos.top + pos.height);

		pos.x = pos.left;
		pos.y = pos.top;

		return pos;
	};

	Sd.Common.getDocumentRect = function()
	{
		var w = window;
		var d = w.document, m = d.compatMode == 'CSS1Compat', b = d.body, de = d.documentElement;

		var rect = new Object();
		rect.left = w.pageXOffset || (m ? de.scrollLeft : b.scrollLeft);
		rect.top = w.pageYOffset || (m ? de.scrollTop : b.scrollTop);
		rect.width = w.innerWidth || (m ? de.clientWidth : b.clientWidth);
		rect.height = w.innerHeight || (m ? de.clientHeight : b.clientHeight);

		return rect;

//		return {
//			left : w.pageXOffset || (m ? de.scrollLeft : b.scrollLeft),
//			top : w.pageYOffset || (m ? de.scrollTop : b.scrollTop),
//			width : w.innerWidth || (m ? de.clientWidth : b.clientWidth),
//			height : w.innerHeight || (m ? de.clientHeight : b.clientHeight)
//		};
	};

	Sd.Common.formatMoney = function(num)
	{
		num = num.toString().replace(/\$|\,/g,'');
		if(isNaN(num))
		num = "0";
		sign = (num == (num = Math.abs(num)));
		num = Math.floor(num*100+0.50000000001);
		cents = num%100;
		num = Math.floor(num/100).toString();
		if(cents<10)
		cents = "0" + cents;
		for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
		num = num.substring(0,num.length-(4*i+3))+','+
		num.substring(num.length-(4*i+3));
		return (((sign)?'':'-') + '$' + num + '.' + cents);
	};

	Sd.Common.hideElement = function(ele)
	{
	  //if(ele.className.indexOf(' Hide') < 0) ele.className += ' Hide';
	  if(ele.style.display) ele.style.prevdisplay = ele.style.display;
	  ele.style.display = 'none';
	};

	Sd.Common.showElement = function(ele)
	{
	  //Let's kill the class name too, so we can use both.
//	  var className = ele.className;
//	  className = className.replace(/Hide/, '');
//	  className = className.replace(/ Hide/, '');
//	  className = className.replace(/hide/, '');
	  ele.className = ele.className.replace(/ hide/i, '');
	  ele.className = ele.className.replace(/^hide$/i, '');
//	  className = className.replace(/invisible/, '');
//	  className = className.replace(/ invisible/, '');
//	  ele.className = className;
	  
		if(ele.style.prevdisplay)
			 ele.style.display = ele.style.prevdisplay;
		else
			 ele.style.display = '';
	};

	Sd.Common.removeChildren = function(node)
	{
		while (node.hasChildNodes())
		{
		  node.removeChild(node.firstChild);
		}
  };
  
	Sd.Common.UrlEncode = function(value)
	{
		// The Javascript escape and unescape functions do not correspond
		// with what browsers actually do...
		var SAFECHARS = "0123456789" +					// Numeric
						"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
						"abcdefghijklmnopqrstuvwxyz" +
						"-_.!~*'()";					// RFC2396 Mark characters
		var HEX = "0123456789ABCDEF";
	
		var plaintext = value;
		var encoded = "";
		for (var i = 0; i < plaintext.length; i++ ) {
			var ch = plaintext.charAt(i);
		    if (ch == " ") {
			    encoded += "+";				// x-www-urlencoded, rather than %20
			} else if (SAFECHARS.indexOf(ch) != -1) {
			    encoded += ch;
			} else {
			    var charCode = ch.charCodeAt(0);
				if (charCode > 255) {
				    alert( "Unicode Character '" 
	                        + ch 
	                        + "' cannot be encoded using standard URL encoding.\n" +
					          "(URL encoding only supports 8-bit characters.)\n" +
							  "A space (+) will be substituted." );
					encoded += "+";
				} else {
					encoded += "%";
					encoded += HEX.charAt((charCode >> 4) & 0xF);
					encoded += HEX.charAt(charCode & 0xF);
				}
			}
		} // for
	
		return encoded;
	};

	Sd.Common.UrlDecode = function(value)
	{
	   // Replace + with ' '
	   // Replace %xx with equivalent character
	   // Put [ERROR] in output if %xx is invalid.
	   var hexchars = "0123456789ABCDEFabcdef"; 
	   var encoded = value;
	   var plaintext = "";
	   var i = 0;
	   while (i < encoded.length) {
	       var ch = encoded.charAt(i);
		   if (ch == "+") {
		       plaintext += " ";
			   i++;
		   } else if (ch == "%") {
				if (i < (encoded.length-2) 
						&& hexchars.indexOf(encoded.charAt(i+1)) != -1 
						&& hexchars.indexOf(encoded.charAt(i+2)) != -1 ) {
					plaintext += unescape( encoded.substr(i,3) );
					i += 3;
				} else {
					alert( 'Bad escape combination near ...' + encoded.substr(i) );
					plaintext += "%[ERROR]";
					i++;
				}
			} else {
			   plaintext += ch;
			   i++;
			}
		} // while
	   return plaintext;
	};  

	Sd.Common.catchEnter = function(e)
	{
	   var key;
	
	   if(!e || window.event) e = window.event;
	
	   if(window.event)
	        key = e.keyCode;     //IE
	   else
	        key = e.which;     //firefox, others
	
	   var result = key != 13;
	
	   //Yay. Firefox does something non-standard now. Firefox needs to go away.
	   if(!result) Sd.Common.cancelEvent(e);
	
	   return result;
	};


//
//
//		Sd.Common.UI
//
//

Sd.Common.UI = Class.create();
Sd.Common.UI.prototype =
{
   initialize: function()
   {
   }
};

	Sd.Common.UI.setSelectValue = function(select, value)
	{
		for(var index = 0; index < select.length; index++)
		{
			if(select[index].value == value)
		 		select.selectedIndex = index;
		}
	};
	
	//QueryString Parsing Functions
	Sd.Common.PageQuery = function(q)
	{
	
		if(String(this.q) == 'undefined') this.q = '';
	
		if(q.length > 1) 
			this.q = q.substring(1, q.length);
		else
			this.q = null;
	
		this.keyValuePairs = new Array();
	
		if(q)
		{
			if(this.q)
			{
				for(var i=0; i < this.q.split("&").length; i++)
				{
					this.keyValuePairs[i] = this.q.split("&")[i];
				}
			}
		}
	
		this.getKeyValuePairs = function() { return this.keyValuePairs; };
		
		this.getValue = function(s)
		{
			for(var j=0; j < this.keyValuePairs.length; j++)
			{
				if(this.keyValuePairs[j].split("=")[0] == s)
					return this.keyValuePairs[j].split("=")[1];
			}
			
			return '';
		};
		
		this.getParameters = function() 
		{
			var a = new Array(this.getLength());
			
			for(var j=0; j < this.keyValuePairs.length; j++) 
			{
				a[j] = this.keyValuePairs[j].split("=")[0];
			}
		
			return a;
		};
	
		this.getLength = function() { return this.keyValuePairs.length; };
	};

	Sd.Common.QueryString = function(key)
	{
	   var search = window.location.search;
	   
	   if(search == null) search = '';
	   if(key == null) key = '';
	   
	   var page = new Sd.Common.PageQuery(search.toLowerCase()); 
	   return unescape(page.getValue(key.toLowerCase())); 
	};	

//
//
//		Sd.Validate
//
//

Sd.Validate = Class.create();
Sd.Validate.prototype =
{
   initialize: function()
   {
   }
};

	// require fields to match
	Sd.Validate.isMatch = function(fld,confirmfld)
	{
	if(!fld || !confirmfld) return false;
	  if(fld.disabled) return true;
	  if(fld.value != confirmfld.value) return false;
	  return true;
	};

	// simple email check
	Sd.Validate.isEmail = function(fld)
	{
		if(!fld) return false;
	  if(fld.disabled) return true; // blank fields are the domain of requireValue
	  var phony= /@(\w+\.)*example\.(com|net|org)$/i;
	  if(phony.test(fld.value))
	  { return false; }
	  var emailfmt= /^\w+([.-]\w+)*@\w+([.-]\w+)*\.\w{2,8}$/;
	  if(!emailfmt.test(fld.value))
	  { return false; }
	  return true;
	};

	// tenacious phone # correction
	Sd.Validate.fixPhone = function(fld,defaultAreaCode,sep,noext)
	{
		if(!fld) return false;
	  if(fld.disabled) return true; // blank fields are the domain of requireValue
	  if(typeof(sep)=='undefined') sep= '-';
	  if(typeof(defaultAreaCode)!='undefined') defaultAreaCode= defaultAreaCode + sep;
	  var ext= '', val= fld.value.toLowerCase();
	  if(val.indexOf('x') > 0)
	  {
	    if(!noext) ext= ' x'+val.substr(val.indexOf('x')).replace(/\D/g,'');
	    val= val.substr(0,val.indexOf('x'));
	  }
	  val= val.replace(/\D/g,'');
	  if(val.length == 7)
	  {
	    fld.value= defaultAreaCode + val.substring(0,3) + sep + val.substring(3,20) + ext;
	    return true;
	  }
	  if(val.length == 10)
	  {
	    fld.value= val.substring(0,3) + sep + val.substring(3,6) + sep + val.substring(6,20) + ext;
	    return true;
	  }
	  if(val.length < 7) return false;
	  if(val.length > 10) return false;

	  //status= 'The phone number you supplied for the '+fieldname(fld)+' field was wrong.';
	  return false;
	};

	// tenacious credit card correction; fieldname isn't a big consideration, probably only one card per form
	Sd.Validate.fixCreditCard = function(fld)
	{
		if(!fld) return false;
	  if(fld.disabled) return true; // blank fields are the domain of requireValue
	  var val= fld.value, ctype= 'credit card';
	  val= val.replace(/\D/g,'');
	  var prefix2= parseInt(val.substr(0,2));
	  if( val.substr(0,1) == '4' )
	  { // Visa
	    ctype= 'Visa\xae';
	    if( val.length == 16 );
	    else if( val.length == 13 ); // very old #, should be reassigned
	    else if( val.length < 13 )
	    { status= 'The Visa\xae number you provided is not long enough.'; return false; }
	    else if( val.length > 16 )
	    { status= 'The Visa\xae number you provided is too long.'; return false; }
	    else
	    { status= 'The Visa\xae number you provided is either not long enough, or too long.'; return false; }
	  }
	  else if( prefix2 >= 51 && prefix2 <= 55 )
	  { // MC
	    ctype= 'MasterCard\xae';
	    if( val.length < 16 )
	    { status= 'The MasterCard\xae number you provided is not long enough.'; return false; }
	    else if( val.length > 16 )
	    { status= 'The MasterCard\xae number you provided is too long.'; return false; }
	  }
	  else if( (prefix2 == 34) || (prefix2 == 37) )
	  { // AmEx
	    ctype= 'American Express\xae card';
	    if( val.length < 15 )
	    { status= 'The American Express\xae card number you provided is not long enough.'; return false; }
	    else if( val.length > 15 )
	    { status= 'The American Express\xae card number you provided is too long.'; return false; }
	  }
	  else if( val.substr(0,4) == '6011' )
	  { // Novus/Discover
	    ctype= 'Discover\xae card';
	    if( val.length < 16 )
	    { status= 'The Discover\xae card number you provided is not long enough.'; return false; }
	    else if( val.length > 16 )
	    { status= 'The Discover\xae card number you provided is too long.'; return false; }
	  }
	  else
	  { // other
	    if( val.length < 13 )
	    { status= 'The credit card number you provided is not long enough.'; return false; }
	    if( val.length > 19 )
	    { status= 'The credit card number you provided is too long.'; return false; }
	  }
	  var sum= 0, dbl= false;
	  for(var i= val.length-1; i >= 0; i--)
	  {
	    var digit= parseInt(val.charAt(i))*((dbl=!dbl)?1:2);
	    sum+= ( digit > 9 ? (digit%10)+1 : digit );
	  }
	  if(sum%10)
	  {
	    status= 'The '+ctype+' number you provided is not valid.\nPlease double-check it and try again.';
	    return false;
	  }
	  fld.value= val;
	  return true;
	};

	// set minimum and/or maximum field lengths
	Sd.Validate.isValidLength = function(fld, min, max)
	{
		if(!fld) return false;
	  if(fld.tagName.toLowerCase() == 'select'){ return fld.selectedIndex >= 0; }
	  if(fld.disabled) return true; // blank fields are the domain of requireValue
	  var len= fld.value.length;
	  if(min > -1 && len < min)
	  { return false; }

	  if(max)
	  {
		  if(max > -1 && len > max)
		  { return false; }
		}
	  return true;
	};

	// disallow a blank field
	Sd.Validate.requireValue = function(fld)
	{
		if(!fld) return false;
		if(fld.tagName.toLowerCase() == 'select')
		{
				if(fld.selectedIndex < 0) return false;

				var value = fld.options[fld.selectedIndex].value;
				if(value.trim() == '') return false;
				return true;
		}

	  if(fld.disabled) return true;
	  if(fld.value.trim() == '') return false;
	  if(!fld.value.length) return false;
	  return true;
	};

	Sd.Validate.addError = function(ele, message)
	{
		Sd.Validate.inputError(ele);
		Sd.Validate.inputErrorMessage(ele, message);
	};
	
	Sd.Validate.remError = function(ele)
	{
		Sd.Validate.inputNoError(ele);
		Sd.Validate.inputNoErrorMessage(ele);		
	};

	Sd.Validate.inputError = function(ele)
	{
	  ele.className += ' Input_Error';
	};
	
	Sd.Validate.inputNoError = function(ele)
	{
	  var className = ele.className;
	  className = className.replace(/Input\_Error/, '');
	  ele.className = className;
	};

	Sd.Validate.inputErrorMessage = function(ele, message)
	{
	  var id = ele.id + '_Error';
	  var pos = Sd.Common.getElementPos(ele);
	  var parent = ele.parentNode;
	  var parentPos = Sd.Common.getElementPos(parent);
	        
	  if($id(id)) ele.parentNode.removeChild($id(id));
	  
	  var div = document.createElement('div');
	  div.className = 'Input_ErrorMessage';
	  div.innerHTML = message;
	  div.id = id;
	
	  parent.appendChild(div);
	
	  var divPos = Sd.Common.getElementPos(div);
	  if(!parent.prevError)
	  {
	     parent.style.height = (parentPos.height + divPos.height) + 'px';
	     parent.prevError = true;
	  }
	};  
	
	Sd.Validate.inputNoErrorMessage = function(ele)
	{
	  var div = $id(ele.id + '_Error');
	  if(div) ele.parentNode.removeChild(div);
	  if(parent.prevError) ele.parentNode.prevError = null;
	};



document.write('<script type="text/javascript" src="http://scripts.stardock.com/Stardock.Proto.js"></script>\n');
