/*
 * 
 * Static Dreamweaver Pages from Creative
 * 
 */
function MM_showHideLayers() { //v6.0
  var i,p,v,obj,args=MM_showHideLayers.arguments;
  for (i=0; i<(args.length-2); i+=3) if ((obj=MM_findObj(args[i]))!=null) {v=args[i+2];
    if (obj.style) {obj=obj.style;v=(v=='show')?'block':(v=='hide')?'none':v;}
    obj.display=v;}
}

function MM_preloadImages() { //v3.0
  var d=document;if(d.images){if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments;for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){d.MM_p[j]=new Image;d.MM_p[j++].src=a[i];}}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr;for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;if(!d) d=document;if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document;n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n];for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n);return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments;document.MM_sr=new Array;for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x;if(!x.oSrc) x.oSrc=x.src;x.src=a[i+2];}
}

function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}


/*
 * 
 * Prototype Gems
 * 
 */

var Browser = {
	IE:     !!(window.attachEvent && !window.opera),
	Opera:  !!window.opera,
	WebKit: navigator.userAgent.indexOf('AppleWebKit/') > -1,
	Gecko:  navigator.userAgent.indexOf('Gecko') > -1 && navigator.userAgent.indexOf('KHTML') == -1,
	MobileSafari: !!navigator.userAgent.match(/Apple.*Mobile.*Safari/)
};
 
var $ = function(id) {
 	return typeof id === 'string' ? document.getElementById(id) : id;
}

Object.extend = function(destination, source) {
  for (var property in source)
    destination[property] = source[property];
  return destination;
};

Object.extend(Function.prototype, {
  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)));
    }
  },
	
  bindAsEventListener: function() {
    var __method = this, args = $A(arguments), object = args.shift();
    return function(event) {
      return __method.apply(object, [event || window.event].concat(args));
    }
  },	

  curry: function() {
    if (!arguments.length) return this;
    var __method = this, args = $A(arguments);
    return function() {
      return __method.apply(this, 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);
  }
});

var $break = { };

Object.extend(Array.prototype, {
	each: function(iterator) {	
	  try {
	    for (var i = 0, len = this.length; i < len; i++)
	      iterator(this[i], i);
	  } catch (e) {
	    if (e != $break) throw e;
	  }
	  return this;
	},
	
  include: function(object) {
    return this.indexOf(object) != -1;
  }	
});

if (!Array.prototype.indexOf) Array.prototype.indexOf = function(item, i) {
  i || (i = 0);
  var length = this.length;
  if (i < 0) i = length + i;
  for (; i < length; i++)
    if (this[i] === item) return i;
  return -1;
};

function $A(iterable) {
  if (!iterable) return [];
  var length = iterable.length, results = new Array(length);
  while (length--) results[length] = iterable[length];
  return results;
}

/** DOM Events **/
(function() {
	var order = {};
	var add = document.attachEvent ?
	  function(element, type, handler) {
	    element.attachEvent("on" + type, handler);
	  }
	: function(element, type, handler) {
	    element.addEventListener(type, handler, false);
	  }
	;
	
	var remove = document.detachEvent ?
	  function(element, type, handler) {
	    element.detachEvent("on" + type, handler);
	  }
	: function(element, type, handler) {
	    element.removeEventListener(type, handler, false);
	  }
	;
  var idCounter = 0;
  
  var identify = function(el) {
		if (el === document) {
			return '<document>';
		} else if (el === window) {
			return '<window>';
		}
		el = $(el);
		if (typeof el.id !== 'string' && (typeof el.tagName !== 'string' || el.tagName.toUpperCase() == 'FORM')) {
      // form with child with name "id"
			var clone = el.cloneNode(false);
      var id = clone.id;
		}	else {
      var id = el.id;
    }
    if (!id) {
      id = 'anonymous_element_' + (++idCounter);
      el.setAttribute('id', id);
    }
    return id;
  };
	
	window.addListener = function(el, ev, fn) {
		el = $(el);
		var id = identify(el);	
		if (!order[id]) order[id] = {};
		if (!order[id][ev]) {
			order[id][ev] = [];
			var obs = function(event) {
				event = event || window.event;
				var fns = order[id][ev];
				for (var i = 0, len = fns.length; i < len; i++) {
					fns[i](event);
					if (event.stopped) break;
				}
			};
			order[id][ev].obs = obs;
			add(el, ev, obs);
		}		
		order[id][ev].push(fn);
	};
	window.removeListener = function(el, ev, fn) {
		el = $(el);
		var id = identify(el);
		try {
			var fns = order[id][ev];
			for (var i = 0, len = fns.length; i < len; i++) {
				if (fns[i] == fn) {
					fns.splice(i, 1);
					break;
				}
			}
			if (fns.length == 0) {
				remove(el, ev, order[id][ev].obs);
				delete order[id][ev];
			}
			for (var ev in order[id]) return;
			delete order[id];
		}	catch(e) {}	
	};	
})();

function stopEvent(event) {
	event = event || {};
	if (event.preventDefault) {	
  	event.preventDefault();
  	event.stopPropagation();
  } else {
		event.returnValue = false;
  	event.cancelBubble = true;
	} 
	event.stopped = true;
}

/** GP Functions **/
var FocusHighlighter = function(form, focusColor, blurColor) {
	var focus = function(event) {
		getTarget(event).style.backgroundColor = focusColor;
	};
	var blur = function(event) {
		getTarget(event).style.backgroundColor = blurColor;
	};	
	var fields = $(form).elements;
	for (var i = 0, len = fields.length; i < len; i++) {	
		if (fields[i].type == 'text' || 
			fields[i].type == 'password' || 
			fields[i].tagName.toLowerCase() == 'select' ||
			fields[i].tagName.toLowerCase() == 'textarea'
		) {
			addListener(fields[i], 'focus', focus);
			addListener(fields[i], 'blur', blur);
			fields[i].style.backgroundColor = blurColor;
		}
	}
}

var AutoTabber = function(/* id1[, id2][, idN...] */) {
//console.log('AutoTabber');
	var focusAndSelect = function(input) {
		input.focus();
		if (input.value.length) {
			// we have a value already so highlight it
			input.select();				
		}		
	};
	var doTab = function(event, prevInput, nextInput) {
		var ascii = (event.charCode || event.keyCode);
		if (nextInput && this.value.length + 1 == this.maxLength && ascii > 31 && ascii < 127) {
			this.value += String.fromCharCode(ascii);
			focusAndSelect(nextInput);
			stopEvent(event);
			
		} else if (prevInput && this.value.length == 0 && ascii == 8) {
			// focus to last field and delete
			if (prevInput.value.length)
				prevInput.value = prevInput.value.substring(0, prevInput.value.length - 1);		
			prevInput.focus();
			stopEvent(event);
		} else if (Browser.Gecko && ascii == 9) {
			// gecko doesn't handle tab properly in this situation
			if (event.shiftKey && prevInput) {
				focusAndSelect(prevInput);
				stopEvent(event);
				stopEvent(event);
				stopEvent(event);
			} else if (nextInput) {
				focusAndSelect(nextInput);
				stopEvent(event);
				stopEvent(event);
				stopEvent(event);
			}
		}
	};
	var prevInput = undefined, thisInput = $(arguments[0]), nextInput;
	for (var i = 1, len = arguments.length; i <= len; i++) {
  	nextInput = $(arguments[i]);
		addListener(thisInput, 'keypress', doTab.bindAsEventListener(thisInput, prevInput, nextInput));
		prevInput = thisInput;
		thisInput = nextInput;
  }
}

function doAutoTab(evt, iMaxLen, fldCurr, fldNext, iIndex) {
  if (fldCurr.value.length >= iMaxLen) {
    if ((evt.keyCode || evt.which) > 47)  {
      if (!fldNext.focus) {fldNext = fldNext[iIndex]}
      fldNext.focus();
      if (fldNext.select) {fldNext.select();}
    }
  }
}

function changeFreq(freq){
	if(freq != 'O'){
		document.getElementById('dt').style.display = "";
	}else{
		document.getElementById('dt').style.display = "none";
	}
}

function SF(form, element) {
	try {
		return document.forms[form].elements[element];
	} catch(e) {return null}
}

function submitOnce(button, processingMsg) {
	button = $(button);
	addListener(button.form, 'submit', function(event) {
		var submitter = event.explicitOriginalTarget || document.activeElement;
		if (submitter.type != 'submit' || submitter == button) {
			button.disabled = true;
			var hidden = Node.create('input', {
				type: 'hidden',
				name: button.name,
				value: button.value
			});
			button.form.appendChild(hidden);
			if (processingMsg) {
				button.value = processingMsg;
			}
		}
	}.bindAsEventListener());
}

var SelectFromTo = function(from, to) {
	this.from = $(from);
	this.to = $(to);
	var opts = this.from.options;
	if (this.from.options && this.to.options && opts.length) {
		addListener(this.from, 'change', this.reset.bind(this, this.from, this.to));
		addListener(this.to, 'change', this.reset.bind(this, this.to, this.from));
		this.reset(this.from, this.to);
	} else {
		throw new Error('SelectFromTo unable to find both drop downs with 2+ options');
	}
};
Object.extend(SelectFromTo.prototype, {
	reset: function(changed, other) {
		var changedSelValue = changed.options[changed.selectedIndex].value;
		var otherSelValue = other.options[other.selectedIndex].value;
		if (changedSelValue == otherSelValue) {
			for (var i = 0; i < other.length; i++) {
				if (changedSelValue != other.options[i].value) {
					break;
				}						
			}
			other.selectedIndex = i;
		}
	}
});	
document.viewportWidth = function() {
	return self['innerWidth'] || (document.documentElement.clientWidth, document.body.clientWidth);
}
document.viewportHeight = function() {
	return self['innerHeight'] || (document.documentElement.clientHeight, document.body.clientHeight);
}
document.windowWidth = function() {
	return self.innerWidth || screen.availWidth;
}
document.windowHeight = function() {
	return self.innerHeight || screen.availHeight;
}
function popHref(a, width, height) {
	return popWindow($(a).href, width, height);
}
var popWindow = function(url, width, height) {	
	var left = Math.floor(document.windowWidth() / 2);
	var top = Math.floor(document.windowHeight() / 2);
	var popup = window.open(url, 'popup' + popWindow.guid, 'height=' + height + ',width=' + width + ',resizable=1,scrollbars=1,left=' + left + ',top=' + top);
	popup.focus();
	popWindow.guid++;
	return popup;
}
popWindow.guid = 0;


var Imager = {
	preload: function() {
		for (var i = 0, len = arguments.length; i < len; i++)
			new Image().src = arguments[i];
	},
	DropDownSwapper: function(select, img) {
		var select = $(select), img = $(img);
	
		for (var i = 0, len = select.options.length; i < len; i++) {
			var imgPath =select.options[i].title;
			if (imgPath) {
	  		// preload image path contained in the title
				new Image().src = imgPath;
				// store path to image
				select.options[i]._src = imgPath;
				// remove title
				select.options[i].title = "";
			}
		}
				
		var setImg = function() {
			var idx = select.selectedIndex == -1 ? 0 : select.selectedIndex;
			var selected = select.options[idx];
			var imgPath = selected._src;
			if (imgPath) {
		  	img.style.visibility = 'visible';
		  	img.src = imgPath;
				img.alt = selected.text;
		  } else {
				img.style.visibility = 'hidden';
			}
		};
		setImg();

		addListener(select, 'change', setImg);
	}
};

function getTarget(event) {
	return event.target || event.srcElement;
}

var SelfLabeler = function(form) {
	var form = $(form), inputs = [];
	var passwordFocus = function(event) {
		var text = getTarget(event);
 		removeListener(text, 'focus', arguments.callee);
		text.parentNode.replaceChild(text._password, text);
		text._password._changed = true;
		text._password.focus();		
		text._password.select();		
	};
	var textFocus = function(event) {
		var input = getTarget(event);
  	if (input.value == input.title) {			
  		input.value = '';
  		removeListener(input, 'focus', arguments.callee);
			input._changed = true;
  	}		
	};
	for (var i = 0, len = form.elements.length; i < len; i++) {
		var input = form.elements[i];
		if (input.type == 'text' || input.type == 'password' || input.tagName.toLowerCase() == 'textarea') {
			inputs.push(input);
	  	if (input.value == '' || input.value == input.title) {
				if (input.type == 'password') {
					var text = Node.create('input', {
						type: 'text',
						size: input.size,
						className: input.className,
						name: input.name,
						_password: input,
						value: input.title
					});
					text.style.backgroundColor = input.style.backgroundColor;
					input.parentNode.replaceChild(text, input);
			  	addListener(text, 'focus', passwordFocus);
				} else {
					input.value = input.title;
					addListener(input, 'focus', textFocus);
				}
		  }
		}
	} 
	addListener(form, 'submit', function() {
		for (var i = 0, len = inputs.length; i < len; i++)
			if (!inputs[i]._changed && inputs[i].value == inputs[i].title)
				inputs[i].value = '';
	});
};

var fieldHasValue = function(field) {
	if (!field) return true;

	try {
		if (field.length && String(field[0].tagName).toUpperCase() == 'INPUT') {
			var type = 'CHECKABLE_GROUP';
			
		} else if (field.type) { 
			var type = String(field.type).toUpperCase();
			
		} else {
			var type = String(field.tagName).toUpperCase();
		}
		switch (type) {
			case 'CHECKABLE_GROUP':
				for (var i = 0, len = field.length; i < len; i++) {
					if (field[i].checked) {
						return true;
					}
				}
				return false;
				
			case 'SELECT':
				return !!field.options[field.selectedIndex].value;
				
			case 'TEXT':
			case 'PASSWORD':
			case 'TEXTAREA':
			case 'FILE':
				return field.value != '';
				
			case 'CHECKBOX':
			case 'RADIO':
				return !!field.checked;
				
			default:
				return true;
		}
	} catch (e) {
		logValue(e);
		return true;
	}
};

var RequiredInputList = function(form, required, callback) {
	form = $(form);
	addListener(form, 'submit', function(event) {
		var msg = '';
		for (var fieldName in required) {
			if (!fieldHasValue(form.elements[fieldName])) {
				msg += required[fieldName] + '\n';
			}
		}
		if (msg.length) {
			stopEvent(event);
			alert(msg);
			if (typeof callback == 'function') callback(event, msg);
		}
	});
};

var logValue = function() {
	if (console && (typeof console.log == 'function')) {
		if (arguments.length > 1) {
			var value = [], i = arguments.length;
			while (i--) value[i] = arguments[i];
		} else {
			var value = arguments[0];
		}		
  	console.log(value);
  } 
};

String.prototype.unescapeHtml = function() {
	return this.replace(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>');
};

String.prototype.stripTags = function () {
	return this.replace(/<\/?[^>]+>/g, '');
}

function trim(string) {
	return String(string).replace(/^\s+/, '').replace(/\s+$/, '');
}

var Node = {
	create: function(tag, properties) {
		var node = document.createElement(tag);	
		Object.extend(node, properties || {});
		return node;
	},	
	text: function(contents) {
		return document.createTextNode(contents);
	},
	setStyle: function(node, styles) {
		node = $(node);
		if (typeof arguments[1] == 'string') {
			node.style[arguments[1]] = arguments[2];
			
		}	else {
			for (var prop in styles) 
				node.style[prop] = styles[prop];
		}
		return node;
	},
	hasClass: function(node, className) {
		node = $(node);
		return new RegExp('\\b' + className + '\\b').test(node.className);
	},
	addClass: function(node, className) {
		if (!Node.hasClass(node, className)) {
			node = $(node);
			node.className += (node.className == '' ? '' : ' ') + className;
		}
	},
	removeClass: function(node, className) {
		node = $(node);
		node.className = trim(node.className.replace(new RegExp('(^|\\s+)' + className + '(\\s+|$)'), ' '));
	},
	getChildren: function(node, criteria) {
		node = $(node);
		var children = node.getElementsByTagName('*');
		if (criteria)
			return Node.filterList(children, criteria || {});	
		else
			return $A(children);
	},
	filterList: function(nodeList, criteria) {
		var elements = [], prop;
		if (typeof criteria == 'function') {
			for (var i = 0, len = nodeList.length; i < len; i++) {
				if (criteria(nodeList[i], i)) 
					elements.push(nodeList[i]);
			}
		}	else {
			for (var i = 0, len = nodeList.length; i < len; i++) {
				for (prop in criteria) {
					if (nodeList[i][prop] == criteria[prop] || (criteria[prop].test && criteria[prop].test(nodeList[i][prop])))
						elements.push(nodeList[i]);
				}
			}
		}
		return elements;	
	}
};


var ModalWindow = function(content, options) {
	options = options || {};
	// create cover
	this.cover = Node.create('div');
	Node.setStyle(this.cover, {
		position: 'absolute',
		top: '0',
		left: '0',
		height: '100%',
		width: '100%',
		backgroundColor: options.color || '#ffffff',
		opacity: options.opacity || 0.75,
		filter: 'alpha(opacity=' + ((options.opacity || 0.75) * 100) + ')'/*,
		zIndex: '1000'*/
	});
	// create wrapper
	this.wrapper = Node.create('div');
	this.wrapper.style.zIndex = '1001';
	// set wrapper contents
	if (content.nodeType == 1) {
  	this.wrapper.appendChild(content);
  } else {
  	this.wrapper.innerHTML = content;
  }
	if (options.parentNode) {
		this.parentNode = options.parentNode;
	}
//console.log(this.wrapper.innerHTML);
	// set wrapper position from options if given
	if (options.positionTop || options.positionLeft) {
  	this.wrapper.style.position = 'absolute';
  	if (options.positionTop) {
  		this.wrapper.style.top = options.positionTop;
  	}
  	if (options.positionLeft) {
  		this.wrapper.style.left = options.positionLeft;
  	}
  }
//alert(this.wrapper);	
	// save options
	this.options = options;
};
Object.extend(ModalWindow.prototype, {
	getParent: function() {
		// get the specified parent node or the body
		return this.options.parentNode ? $(this.options.parentNode) : document.getElementsByTagName('body')[0];
	},
	observeClose: function() {
		if (!this.isCloseObserved) {
			// observe any close buttons
			if (this.options.close) {
				var boundClose = this.close.bind(this);	
				addListener(this.cover, 'click', boundClose);
				addListener(this.wrapper, 'click', function(event) {
					if (this.options.close.indexOf(getTarget(event).id) != -1) {
						boundClose(event);
					}
				}.bind(this));
			}
			this.isCloseObserved = true;
		}
	},
	close: function(event) {
		// get body node
		var body = document.getElementsByTagName('body')[0];
		// remove cover
		body.removeChild(this.cover);
		// allow document scrolling
		Node.setStyle(body, {
			height: '',
			overflow: ''
		});
		// remove modal
		this.getParent().removeChild(this.wrapper);
		// prevent default
		stopEvent(event || window.event);
	},
	open: function(event) {
		// get body node
		var body = document.getElementsByTagName('body')[0];
		// add cover
		body.appendChild(this.cover);
		// prevent document scrolling
		Node.setStyle(body, {
			height: '100%',
			overflow: 'hidden'
		});
		// add wrapper
		this.getParent().appendChild(this.wrapper);
		// set close observers
		this.observeClose();
		// prevent default
		stopEvent(event || window.event);
	}
});
/* Gives us a way to style buttons with a consistant class called button */
var addSubmitClass = function () {
	var inputTags = document.getElementsByTagName("input");
	for (var i = 0; inputTags[i]; i++) {
		if (inputTags[i].type == "submit" || inputTags[i].type == "button" || inputTags[i].type == "reset"){
			if (inputTags[i].className && inputTags[i].className.indexOf("button") < 0) {
				inputTags[i].className = inputTags[i].className + " button";
			} else if (!inputTags[i].className) {
				inputTags[i].className = "button";
			}
		}
	}
}
addListener(window, 'load', addSubmitClass);
