// JavaScript Document

function containsDOM (container, containee) {
  var isParent = false;
  do {
    if ((isParent = container == containee))
      break;
    containee = containee.parentNode;
  }
  while (containee != null);
  return isParent;
}

function checkMouseEnter (element, evt) {
  if (element.contains && evt.fromElement) {
    return !element.contains(evt.fromElement);
  }
  else if (evt.relatedTarget) {
    return !containsDOM(element, evt.relatedTarget);
  }
}

function checkMouseLeave (element, evt) {
  if (element.contains && evt.toElement) {
    return !element.contains(evt.toElement);
  }
  else if (evt.relatedTarget) {
    return !containsDOM(element, evt.relatedTarget);
  }
}

var timer;

function DelayShowHideStart(div){

if (document.getElementById(div).style.visibility == 'visible'){
var timer = setTimeout("ShowHide('"+div+"','hide');",1000);
} else if (document.getElementById(div).style.visibility == 'hidden'){
var timer = setTimeout("ShowHide('"+div+"','show');",1000);
}

}

function DelayShowHideStop(div){
clearTimeout(timer);
}

function centerbox(id){
	var object = document.getElementById(id);
	//object.style.top = '50%';
	//object.style.left = '50%';
	object.style.marginLeft = '-' + parseInt(object.offsetWidth / 2) + 'px';
  	object.style.marginTop = '-' + parseInt(object.offsetHeight / 2) + 'px';
	object.style.display = 'block';
}

function getPageSize() {
	        
	     var xScroll, yScroll;
		
		if (window.innerHeight && window.scrollMaxY) {	
			xScroll = window.innerWidth + window.scrollMaxX;
			yScroll = window.innerHeight + window.scrollMaxY;
		} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
			xScroll = document.body.scrollWidth;
			yScroll = document.body.scrollHeight;
		} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
			xScroll = document.body.offsetWidth;
			yScroll = document.body.offsetHeight;
		}
		
		var windowWidth, windowHeight;
		
		if (self.innerHeight) {	// all except Explorer
			if(document.documentElement.clientWidth){
				windowWidth = document.documentElement.clientWidth; 
			} else {
				windowWidth = self.innerWidth;
			}
			windowHeight = self.innerHeight;
		} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
			windowWidth = document.documentElement.clientWidth;
			windowHeight = document.documentElement.clientHeight;
		} else if (document.body) { // other Explorers
			windowWidth = document.body.clientWidth;
			windowHeight = document.body.clientHeight;
		}	
		
		// for small pages with total height less then height of the viewport
		if(yScroll < windowHeight){
			pageHeight = windowHeight;
		} else { 
			pageHeight = yScroll;
		}
	
		// for small pages with total width less then width of the viewport
		if(xScroll < windowWidth){	
			pageWidth = xScroll;		
		} else {
			pageWidth = windowWidth;
		}

		return [pageWidth,pageHeight];
	}


function showdeadcenterdiv(divid,overlay) {
	// First, determine how much the visitor has scrolled
	
	var dimensions = $(divid).getDimensions();

	Xwidth = dimensions.width;
	Yheight = dimensions.height;
	
	var scrolledX, scrolledY;
	if( self.pageYOffset ) {
	scrolledX = self.pageXOffset;
	scrolledY = self.pageYOffset;
	} else if( document.documentElement && document.documentElement.scrollTop ) {
	scrolledX = document.documentElement.scrollLeft;
	scrolledY = document.documentElement.scrollTop;
	} else if( document.body ) {
	scrolledX = document.body.scrollLeft;
	scrolledY = document.body.scrollTop;
	}
	
	
	// Next, determine the coordinates of the center of browser's window
	
	var centerX, centerY;
	if( self.innerHeight ) {
	centerX = self.innerWidth;
	centerY = self.innerHeight;
	} else if( document.documentElement && document.documentElement.clientHeight ) {
	centerX = document.documentElement.clientWidth;
	centerY = document.documentElement.clientHeight;
	} else if( document.body ) {
	centerX = document.body.clientWidth;
	centerY = document.body.clientHeight;
	}
	
		// set the background overlay
	if (overlay){ 
		var backdrop = $(overlay);
		var arrayPageSize = getPageSize();
        backdrop.style.width = arrayPageSize[0] + 'px';
		backdrop.style.height = arrayPageSize[1] + 'px';
		//backdrop.style.top = scrolledY+'px';
		//backdrop.style.padding = scrolledY+'px';
		//backdrop.style.left = scrolledX+'px';
		Effect.Appear(overlay, { duration: 0.5, to: 0.4 });
		backdrop.onclick= function(){closedeadcenterdiv(divid,overlay)}
	}
	
	// Xwidth is the width of the div, Yheight is the height of the
	// div passed as arguments to the function:
	var leftOffset = scrolledX + (centerX - Xwidth) / 2;
	var topOffset = scrolledY + (centerY - Yheight) / 2;
	// The initial width and height of the div can be set in the
	// style sheet with display:none; divid is passed as an argument to // the function
	var o=$(divid);
	var r=o.style;
	r.position='absolute';
	r.top = topOffset + 'px';
	r.left = leftOffset + 'px';
	//r.display = "block";
	setTimeout("Effect.Appear('"+divid+"', { duration: 0.5 })", 1000);
}

function closedeadcenterdiv(divid, overlay){
	Effect.Fade(divid, { duration: 0.5 });
	if (overlay){
		setTimeout("Effect.Fade('"+overlay+"', { duration: 1.0, from: 0.4 })",500);
	}
	
}

function hoverbox(html,width,height){
    
    var popup = document.getElementById('popup');
    if (width){ popup.style.width = width+'px'; }
    if (height){ popup.style.height = height+'px'; }
    popup.innerHTML = html;
    
    showdeadcenterdiv('popup','overlay');

    
}

function showlogin(redirect){
	showdeadcenterdiv(450,300,'loginbox','overlay');
	setTimeout("document.getElementById('loginemail').focus()",2000);
	document.getElementById('loginredirect').value = redirect;
}


function processform(formid,file,button,keepwaiting){

	var url = '/?ajaxrequest='+file;
	var formid = formid;
	if (button){
	var buttontext = button.innerHTML;


	if (button.className == 'button wait'){
		alert ('already processing');
		return false;
	}
	}


	new Ajax.Request(url, {
	  method: 'post',
	  parameters: $(formid).serialize(true),
	  onCreate: function(){
    if (button){
		button.className = 'button wait';
                button.innerHTML = '<span style="visibility:hidden">'+buttontext+'</span>';
		
	}
  },
  onComplete: function(){
    if (button && !keepwaiting){
		button.className = 'button submit';
		button.innerHTML = buttontext;
	}
  }
	});

}

function testform(formid,file,button,keepwaiting){
	var url = '/?ajaxrequest='+file;
	var formid = formid;
	if (button){
	var buttontext = button.innerHTML;
	if (button.className == 'button wait'){
		alert ('already processing');
		return false;
	}
	}
	
	$(formid).method = 'POST';
	$(formid).action = url;
	$(formid).submit();
}

function ajaxupdater(objectid,file,param){
	new Ajax.Updater(objectid, '/?ajaxrequest='+file, {
		method: 'post',
  		parameters: { ajaxparams: param, ajaxtemplate: template_zone }
	});
}

function ajaxupdaterfade(objectid,file,param,evalcode){
	new Ajax.Updater(objectid, '/?ajaxrequest='+file, {
		onSuccess: function(response) {
			new Effect.Opacity(objectid, { from: 0, to: 1.0, duration: 0.5 });
			setTimeout("prepareInputsForHints();",500);
			if (evalcode){
				setTimeout(unescape(evalcode),500);
			}
		  },
		method: 'post',
  		parameters: { ajaxparams: param, ajaxtemplate: template_zone }
	});
}


function ajaxprinter(objectid,file,param){
	ajaxupdater(objectid,'templateprinter','template:'+file+',data:'+param);
}

function ajaxrequester(file,param){
	new Ajax.Request('/?ajaxrequest='+file, {
		method: 'post',
  		parameters: { ajaxparams: param, ajaxtemplate: template_zone }
	});
}

function ajaxtester(file, param, method) {
    method = method || "post"; // Set method to post by default, if not specified.

    // The rest of this code assumes you are not using a library.
    // It can be made less wordy if you use one.
    var form = document.createElement("testform");
    form.setAttribute("method", method);
    form.setAttribute("action", file);

    params = new Array();
    params['ajaxparams']=param;
    params['ajaxtemplate']=template_zone;
    for(var key in params) {
        var hiddenField = document.createElement("input");
        hiddenField.setAttribute("type", "hidden");
        hiddenField.setAttribute("name", key);
        hiddenField.setAttribute("value", params[key]);

        form.appendChild(hiddenField);
    }

    document.body.appendChild(form);
    form.submit();
    //document.body.removeChild(form);

}


function linker(objectid,file,param,evalcode){
	new Effect.Opacity(objectid, { from: 1.0, to: 0, duration: 0.5 });
	setTimeout("ajaxupdaterfade('','"+objectid+"','templateprinter','template:"+file+",data:"+param+"', '"+escape(evalcode)+"');",500);
}

function reloadPage(redirect){
	if (redirect){
		//alert ('location: '+redirect);
		setTimeout('location.href = \''+redirect+'\';', 1000);
	} else {
		setTimeout('location.reload(true);', 1000);
	}
}

function postCheckout(){
	var form = $('sessionTransferForm');
	form.action = checkoutURL;
	form.method = 'post';
	form.submit();
}


function popup(file,param){
	ajaxprinter('popup',file,param);
	showdeadcenterdiv('popup','overlay');
}


function setCookie( name, value, expires, path, domain, secure ){
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );
	
	/*
	if the expires variable is set, make the correct 
	expires time, the current script below will set 
	it for x number of days, to make it for hours, 
	delete * 24, for minutes, delete * 60 * 24
	*/
	if ( expires ){
		expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );
	
	document.cookie = name + "=" +escape( value ) +
	( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + 
	( ( path ) ? ";path=" + path : "" ) + 
	( ( domain ) ? ";domain=" + domain : "" ) +
	( ( secure ) ? ";secure" : "" );
}

function getCookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f
	
	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );
		
		
		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
	
		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
}

function deleteCookie( name, path, domain ) {
	if ( getCookie( name ) ) document.cookie = name + "=" +
	( ( path ) ? ";path=" + path : "") +
	( ( domain ) ? ";domain=" + domain : "" ) +
	";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

function checkBoxes(field, selected){
	var selectedarray = selected.split(',');
	for (i = 0; i < field.length; i++){
		if (selectedarray.any(function(n) { if (field[i].value==n){ return true; } else { return false; } })){
			field[i].checked = true;
		} else {
			field[i].checked = false;
		}
	}
}

function checkEnter(e){ //e is event object passed from function invocation
	var characterCode; //literal character code will be stored in this variable
	
	if(e && e.which){ //if which property of event object is supported (NN4)
		e = e;
		characterCode = e.which; //character code is contained in NN4's which property
	} else {
		e = event;
		characterCode = e.keyCode; //character code is contained in IE's keyCode property
	}
	
	if(characterCode == 13){ //if generated character code is equal to ascii 13 (if enter key)
		return true;
	} else {
		return false;
	}

}


var noticeoptions = {
	header: 			'&nbsp;'
	,speedin: 			0.3
	,speedout: 			0.5
	,outDirection: 		{ y: -20 }
	,life: 				10
	,sticky: 			false
	,className: 		"notice"
	};

function removenotice(n, o){
	o = o || noticeoptions;
	new Effect.Parallel([
		new Effect.Move(n, Object.extend({ sync: true, mode: 'relative' }, o.outDirection)),
		new Effect.Opacity(n, { sync: true, to: 0 }) 
	], {
		duration: o.speedout
	});
}

function insertnotice(msg, options){
	
	if (!$('noticebox')){
		noticebox = new Element("div", { "id": "noticebox" });
		noticebox.wrap( document.body );
	}
	
	var opt = Object.clone(noticeoptions);
	options = options || {};
	Object.extend(opt, options);
	var notice;
	notice = new Element('div', {'class': opt.className}).setStyle({display: 'block', opacity: 0});
	if (opt.sticky){
		var noticeExit = new Element('div', {'class': 'notice-exit'}).update('&times;');
		noticeExit.observe('click', function(){ removenotice(notice, opt); });
		notice.insert(noticeExit);
	}
	notice.insert(new Element("div", {"class": "notice-head"}).update(opt.header));
	notice.insert(new Element("div", {"class": "notice-body"}).update(msg));
	$('noticebox').insert(notice);
	new Effect.Opacity(notice, { to: 0.85, duration: opt.speedin });

	if (!opt.sticky){
		removenotice.delay(opt.life, notice, opt);
	}

}




function prepareInputsForHints() {
    var tags = ['input', 'select', 'textarea' ];
    for(var t = 0; t < tags.length; t++) {
        var inputs = document.getElementsByTagName(tags[t]);
        for (var i=0; i<inputs.length; i++){
            connectInputHint(inputs[i]);
        }
    }
}
 
function connectInputHint(input) {
    var span = input.parentNode.getElementsByTagName("dfn")[0];
    if(span) {
        // Add pointer
        var pointer = document.createElement('span');
        pointer.className = 'hint-pointer';
        pointer.innerHTML = ' ';
        span.appendChild(pointer);
 
        // Hook up events
        input.onfocus = function () {
            span.style.display = "inline";
        }
        input.onblur = function () {
            span.style.display = "none";
        }
    }
}



/* 
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Title :		charcount.js
Author : 		Terri Ann Swallow
URL : 		http://www.ninedays.org/
Project : 		Ninedays Blog
Copyright:		(c) 2008 Sam Stephenson
			This script is is freely distributable under the terms of an MIT-style license.

Description :	Functions in relation to limiting and displaying the number of characters allowed in a textarea
Version:		2.1
Changes:		Added overage override.  Read blog for updates: http://blog.ninedays.org/2008/01/17/limit-characters-in-a-textarea-with-prototype/

Created : 		1/17/2008 - January 17, 2008
Modified : 		5/20/2008 - May 20, 2008

Functions:		init()						Function called when the window loads to initiate and apply character counting capabilities to select textareas
			charCounter(id, maxlimit, limited)	Function that counts the number of characters, alters the display number and the calss applied to the display number
			makeItCount(id, maxsize, limited)	Function called in the init() function, sets the listeners on teh textarea nd instantiates the feedback display number if it does not exist
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
*/
/*	Event.observe(window, 'load', init);

	function init(){
		makeItCount('description', 300, false);
		makeItCount('comments',100);
	}
*/	
	function charCounter(id, maxlimit, limited){
		if (!$('counter-'+id)){
			$(id).insert({after: '<div id="counter-'+id+'"></div>'});
		}
		if($F(id).length >= maxlimit){
			if(limited){	$(id).value = $F(id).substring(0, maxlimit); }
			$('counter-'+id).addClassName('charcount-limit');
			$('counter-'+id).removeClassName('charcount-safe');
		} else {	
			$('counter-'+id).removeClassName('charcount-limit');
			$('counter-'+id).addClassName('charcount-safe');
		}
		$('counter-'+id).update( $F(id).length + '/' + maxlimit );	
			
	}
	
	function makeItCount(id, maxsize, limited){
		if(limited == null) limited = true;
		if ($(id)){
			Event.observe($(id), 'keyup', function(){charCounter(id, maxsize, limited);}, false);
			Event.observe($(id), 'keydown', function(){charCounter(id, maxsize, limited);}, false);
			charCounter(id,maxsize,limited);
		} else {
			alert('could not find '+id);	
		}
	}
	
function listhighlighter(selectrow) {
     items = selectrow.parentNode.getElementsByTagName("li");
	 for(var i = 0; i < items.length; i++) {
          items[i].removeClassName('selected');
     }
	 selectrow.addClassName('selected');
}

window.onload=function(){
	prepareInputsForHints();
}

function AddSelectOption(selectObj, text, value, isSelected) 
{
	if (selectObj != null && selectObj.options != null)
	{
		selectObj.options[selectObj.options.length] = 
			new Option(text, value, false, isSelected);
	}
}