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

 	UI WIDGETS

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

function PopupWindow( window_content ) {

	
	var POPUP_DEFAULT_WIDTH = '300px';

	
	var container = document.createElement('div');
	container.className = 'PopupWindow';
	container.style.visibility = 'hidden';
	
	
	var close_control = document.createElement('a');
	close_control.className = 'windowClose';	
	close_control.setAttribute( 'title', 'Close' );
	close_control.href = '#';
	close_control.innerHTML = '<span class="label">Close</span>';
	
	
	container.appendChild( close_control );
		
	
	var window_instance = {};
	window_instance.labels = [];
	
	window_instance.content = container.insertBefore( document.createElement('div'), close_control );
	
	window_instance.close = function() {
	
		container.style.visibility = 'hidden';
		// container.style.display = 'none';
		
		if ( typeof this.onclose == 'function' ) {
		
			return this.onclose();
		
		}
	
	}
	
	window_instance.isOpen = function() {
	
		return container.style.visibility == 'hidden' ? false : true;
		
	}
	
	window_instance.open = function( ) {

		container.style.visibility = '';
		// container.style.display = '';
		
		this.focusFirstFocusable();
		
	}
	
	window_instance.move = function( x, y ) {
	
		container.style.left = ( x ) + 'px';
		container.style.top = ( y ) + 'px';		
	
	}

	
	window_instance.setWidth = function( width ) {
	
		container.style.width = width;
	
	}
	
	
	window_instance.getWidth = function() { 
		
		return container.offsetWidth;
		
	}
	
	window_instance.setHeight = function( height ) {
	
		container.style.height = height;
	
	}
	
	window_instance.toggle = function() {
	
		if ( !this.isOpen() ) {
		
			return this.open();
		
		}
		
		return this.close();
	}
	
	window_instance.setContent = function( content ) {
		
		if ( content.parentNode != window_instance.content ) {
			
			 window_instance.content.appendChild( content );
			 content.style.display = '';
			
		}
		
	}
	
	
	
	window_instance.focusFirstLink = function() {
	
		var anchors = window_instance.content.getElementsByTagName('a');
		
		if ( anchors.length > 0 ) { anchors[0].focus(); return true; }
		
		return false;
	
	}
	
	window_instance.focusFirstInput = function() {
		
		var inputs = window_instance.content.getElementsByTagName('input');		
		
		for ( var i = 0; i < inputs.length; i++ ) {
		
			if ( inputs[i].type.toLowerCase() != 'hidden' ) {
			
				inputs[i].focus(); 
				return true; 
			}
		
		}
			
		
		return false;
	
	}
	
	
	window_instance.focusFirstFocusable = function() {
	
		if ( !this.focusFirstInput() ) {
		
			if ( !this.focusFirstLink() ) {
			
				close_control.focus();
			
			}
		
		}
	}
	
	
	
	window_instance.onclose = null;
	
	close_control.onclick = function () { window_instance.close(); return false; }
	
	window_instance.setWidth( POPUP_DEFAULT_WIDTH );
	
	if ( window_content ) { window_instance.setContent( window_content ); }
	
	
	document.body.insertBefore( container, document.body.lastChild );
	
	return window_instance;

}



function PopupLabel( element ) {

	var POPUP_OFFSET_X = 5;
	var POPUP_OFFSET_Y = 10;
	
	var obj_instance = {};	

	obj_instance.element = element;
	obj_instance.popup =  new PopupWindow();
	
	
	obj_instance.open = function( e ) {
		
		var content = document.getElementById(  element.href.slice( element.href.lastIndexOf('#') + 1 ) );
				
		if ( content ) {
		
			this.popup.setContent( content );
		
			var geometry = new WindowGeometry( window );
			
			var clientX = element.offsetLeft;
			var clientY = element.offsetTop + element.offsetHeight;
						
			
			
			var totalX = 0;
			var totalY = element.offsetHeight;
			
			for ( var source = element; source.offsetParent; source = source.offsetParent ) {
			
				// alert( source.tagName + ":" + source.offsetLeft );
				totalX += source.offsetLeft;
				totalY += source.offsetTop;
			}
			
			// alert( "total x/y: " + totalX + '/' + totalY );
			
			clientX = totalX;
			clientY = totalY;

			// alert( 'getVerticalScroll: ' +  geometry.getVerticalScroll() );
			
			if ( ( clientX + geometry.getHorizontalScroll() + POPUP_OFFSET_X + this.popup.getWidth() ) > geometry.getViewportWidth() )  { // right align popup
				
				this.popup.move( clientX + element.offsetWidth + geometry.getHorizontalScroll() - POPUP_OFFSET_X - this.popup.getWidth(), clientY  /* + geometry.getVerticalScroll() */ + POPUP_OFFSET_Y );	
			
			}
			
			else { // left align popup

				this.popup.move( clientX + geometry.getHorizontalScroll() + POPUP_OFFSET_X, clientY /* + geometry.getVerticalScroll() */ + POPUP_OFFSET_Y );
				
			}
			
			this.popup.onclose = function ( ) { obj_instance.element.focus(); };
			
			this.popup.open();
		
		}
	
	}
	
	
	obj_instance.close = function() {
		
		this.popup.close();
	
	}
	
	obj_instance.toggle = function ( e ) {
	
		if ( this.popup.isOpen() ) { return this.close(); }
		
		return this.open( e );
	
	}
	
	
	function onclick_function( e ) {
		
		obj_instance.toggle( e );
		
		if ( e.returnValue != undefined ) { e.returnValue = false; }
		if ( e.preventDefault != undefined ) { e.preventDefault(); }
		// if ( element.blur ) { element.blur(); }
		
		return false;
	
	}
	
	function watchKeyPress( e ) {
		
		if ( e.keyCode == 13 ) { window.setTimeout( function() { obj_instance.popup.focusFirstLink(); }, 10 );  }
	
	}
	
	function onfocus_function( e ) {
		
		addEvent( element, 'keypress', watchKeyPress, true );
		
	}
	
	function onblur_function( e ) {
	
		removeEvent( element, 'keypress', watchKeyPress, true );
	
	}
		
	addEvent( element, 'click', onclick_function, true );
	addEvent( element, 'focus', onfocus_function, true );
	addEvent( element, 'blur', onblur_function, true );
	
	return obj_instance;

}



function tabbedInterface( element ) {

	var selected_index;

	var tabs = getElementsByTagNameAndClassName( 'a', 'tab', element );
	var tab_display_area = getElementsByTagNameAndClassName( 'div', 'tab_display_area', element )[0];
	
	function hideContent( element ) { element.style.display = 'none'; }
	
	function showContent( element ) { element.style.display = 'block'; }
	
	
	function deselectTab( element ) {
	
		removeClass( element, 'selected' ); 
		hideContent( document.getElementById( element.hash.slice( 1 ) ) );	
	
	}
	
	
	function selectTab( element ) {
			
		addClass( element, 'selected' );
		showContent( document.getElementById( element.hash.slice( 1 ) ) );
	
	}
	
	
	function selectItem( index ) {
	
		if ( tabs[selected_index] ) { 
		
			deselectTab( tabs[selected_index] );
		
		}
		
		selectTab( tabs[index] );
		tabs[index].focus();
		selected_index = index;
		
	}
	
	element.selectItem = selectItem;
	
	
	for ( var i = 0; i < tabs.length; i++ ) {
	
		tabs[i].index = i;
				
		tabs[i].onclick = function() {
		
			selectItem( this.index );
			return false;
		
		}
		
		if ( hasClass( tabs[i], 'selected' ) ) { selectItem( i ); }
		
		else { deselectTab( tabs[i] ); }
			
	}
	
	
	// Override selected tab if hash present in url
	if ( window.location.hash ) {
	
		for ( var i = 0; i < tabs.length; i++ ) {
		
			if (  window.location.hash.slice( 1 )  == tabs[i].hash.slice( 1 ) ) {
			
				selectItem( i );
				break;
			}		
			
		}
	
	}

	
	// if no selected tab, select the first tab
	if ( !selected_index && tabs.length > 0) { selectItem( 0 ); }
	
	tab_display_area.style.display = 'block';

}


/* --- BEGIN MODAL WINDOW INTEGRATION --- */


function setTransparency( element, transparency ) {
	
	element.style.opacity = transparency;
	element.style['-moz-opacity'] = transparency;
	
	if ( element.style.filter ) {
		element.style.filter =  'alpha( opacity=' + (transparency * 100) + ')';
	}

}



function centerInWindow( element ) { 
	
	element.style.position = 'absolute';
	
	var geometry = new WindowGeometry( window );
	
	var vp_width = geometry.getViewportWidth();
	var vp_height = geometry.getViewportHeight();
	
	var el_width = element.scrollWidth;
	var el_height = element.scrollHeight;
	
	var top = Math.floor( ( vp_height - el_height ) / 2 ) + geometry.getVerticalScroll();
	var left = Math.floor( ( vp_width - el_width ) / 2 ) + geometry.getHorizontalScroll();
	
	// alert( 'Math.floor( ( ' + vp_width + ' - ' +  el_width + ' ) / 2 ) + ' + geometry.getHorizontalScroll() + ' = ' + left );
	
	element.style.top = top > 0 ? top + 'px' : '0px';
	element.style.left = left > 0 ? left + 'px' : '0px';

}


function fillViewport( element ) {
		
	var geometry = new WindowGeometry( window );
	
	element.style.width = document.getElementsByTagName('body')[0].offsetWidth + 'px';
	element.style.top = document.getElementsByTagName('body')[0].offsetTop + 'px';
	element.style.left = document.getElementsByTagName('body')[0].offsetLeft + 'px';
			
	var element_height = document.getElementsByTagName('html')[0].scrollHeight > geometry.getViewportHeight() ? document.getElementsByTagName('html')[0].scrollHeight : geometry.getViewportHeight();
	element.style.height = element_height  + 'px';
	
	return;
		
}


function focusInput( input ) {
	
	// Do things twice for IE...
	if ( input.type.toLowerCase().match(/^text|textarea|password$/) && ( input.value.length > 0 ) && input.select ) {
		
		input.select(); 
		input.select(); 
		
	} else if ( input.focus ) {
		
		input.focus(); 
		input.focus(); 
	}

}


function getIdFromURL( url ) {
	
	var hash_pos = url.indexOf('#');
	
	if (  hash_pos > 0 ) {
	
		return url.slice( hash_pos + 1 );
	
	}
	
	return '';

}


QueryString = function( queryString ) {

	this.props = [];
	this.propLookup = [];
	
	if ( queryString ) { this.parse( queryString ); }

}


QueryString.prototype.parse = function( queryString ) {
		
	var args = queryString.replace(/^\?/, '').split('&');
	
	for ( var i = 0; i < args.length; i++ ) {
	
		var arg = args[i].split('=');
		
		this.set( arg[0], decodeURIComponent( String( arg[1] ).replace(/\+/, ' ') ) );
			
	}
	
}

QueryString.prototype.set = function( prop_name, prop_value ) {

	var value = { name: prop_name, value: prop_value };
	
	var ns_prop = this.nsProp( prop_name );
		
	if ( this.get( prop_name ) != null ) { // key exists, overwrite value
		
		this.props[this.propLookup[ns_prop]] = value;
	
	}
	
	else {
	
		this.props.push( value );
		this.propLookup[ns_prop] = ( this.props.length - 1 );
	
	}

}

QueryString.prototype.nsProp = function( property_name ) {

	return 'indeed_' + property_name;

}


QueryString.prototype.get = function( prop_name ) {

	// we add a string to the beginning of the name so it does not overwrite or conflict
	// with any existing methods/properties (like sort, length, etc.)
	var ns_prop = this.nsProp( prop_name );
	
	if ( this.propLookup[ns_prop] != null ) {
	
		return this.props[this.propLookup[ns_prop]].value;
	
	}
	
	return null;

}


QueryString.prototype.toString = function() {
	
	for ( var i = 0, return_value = []; i <  this.props.length; i++ ) {
	
		return_value[i] = this.props[i].name + "=" + encodeURIComponent( this.props[i].value ).replace(/\%20/, '+');

	}
	
	return "?" + return_value.join('&');
}


function WindowShade( element, target ) {

	var self = this;
	
	this.label = element;
	
	if ( typeof target == 'function' ) {
	
		this.target = target();
	
	}
	
	else {
	
		this.target = target;
	
	}
	this.isOpen = this.target.style.display == 'none' ? false : true;

	addClass( element, 'windowshade_label');
	
	if ( this.isOpen ) { this.open(); }
	
	else { this.close(); }
	
	addEvent( element, 'click', function( e ) { self.toggle(); element.blur(); killEvent(e); return false; }, false );
	
}


WindowShade.prototype.close = function() {
	
	this.target.style.display = 'none';
	removeClass( this.label, 'windowshade_open');
	this.isOpen = false;
	
	if ( typeof this.onclose == 'function' ) { this.onclose(); }

}

WindowShade.prototype.open = function() {

	this.target.style.display = '';
	addClass( this.label, 'windowshade_open');
	this.isOpen = true;
	
	if ( typeof this.onopen == 'function' ) { this.onopen(); }

}

WindowShade.prototype.toggle = function() {
	
	if ( !this.isOpen ) { this.open(); }
	else { this.close(); }

	
}



// Remove once this function is defined in global.js

function killEvent( e ) {

	if ( window.event ) { 

		window.event.returnValue = false; 
		window.event.cancelBubble = true; 
	} 
	
	else if ( e ) { 	
		e.preventDefault(); 
		e.stopPropagation(); 
	}
	
}



function Container( element, href, method, width, height ) {
	
	var self = this;
	this.history = [];
	
	var default_width = width ? width :  450;
	var default_height = height ? height :  300;
	
	var mod_window = element;
	
	var abort = false;
	
	function wait() {

		var current_width = mod_window.offsetWidth;
		var current_height = mod_window.offsetHeight;
		
		var table = document.createElement('table');
		table.style.width =  current_width+ 'px';
		table.style.height = current_height + 'px';
		var tbody = document.createElement('tbody');
		var row = document.createElement('tr');

		var cell = document.createElement('td');
		cell.style.textAlign = 'center';
		
		cell.appendChild( document.createTextNode('Loading...') );
		
		row.appendChild( cell );
		tbody.appendChild( row )
		table.appendChild( tbody );		
		
		var wrapper = document.createElement('div');
		wrapper.appendChild( table );
		
		var string = wrapper.innerHTML;
		
		self.setContent( string );
	
	}
	
	
	function loadExternalContent( href, method ) {
	
		if ( !method ) { method = 'GET'; }
				
		// window.setTimeout( function() { // simulating slow response times...
		
			sendRequest( href,  method, function( result ) {
				
				if ( result.readyState != 4 || result.responseText == '' ) { return; }
				
				if ( abort ) { abort = false; return; }
				
				self.setContent( result.responseText );
				
				if ( typeof self.onload == 'function' ) { self.onload(); }
				
				evaluateScriptsInElement( mod_window );				
		
				self.history.push( { href: href, method: method } );
				

			} );
		
		// }, 2000 );
		
	}
	
	this.onload = null;
	
	this.load = function( href, method, callback ) {
		
		// wait();
		loadExternalContent( href, method, callback );
	
	}
	
	this.sizeToContent = function() {
	
		if ( mod_window.childNodes[0] ) {	
			var current_width = mod_window.childNodes[0].offsetWidth;
			var current_height = mod_window.childNodes[0].offsetHeight;
		}
		
		else {
		
			var current_width = default_width;
			var current_height = default_height;
		
		}
		
		mod_window.style.width = current_width + 'px';
		mod_window.style.height = current_height + 'px';
			
	}
	
	
	this.back = function() {
		
		if ( ( this.history.length - 1 ) > 0 ) {
		
			this.history.pop(); // current page
			var previous = this.history.pop(); // previous page, removing so there aren't dupes
			
			this.load( previous.href, previous.method );			
		
		}
	
	}
	
	
	this.abort = function( ) {
	
		abort = true;
	
	}
	
	
	function evaluateScriptsInElement( element ) {
	
		var scripts = element.getElementsByTagName('script');
		
		for ( var i = 0; i < scripts.length; i++ ) {
			
			var js_string = scripts[i].innerHTML;
			
			// Remove comment indicator before, after script contents....
			// automatically injected into response by Symantec
			js_string = js_string.replace( /^\s*\<\!\-\-/, '' );
			js_string =js_string.replace( /\/\/\s*\-\-\>\s*$/, '' );
			
			eval( js_string );
			
		}
		
	}
	
	this.setContent = function( content ) {
		
		// Trim leading/trailing whitespace, causes FF not to correctly resize box
		content = content.replace( /^\s*/, '' );
		content = content.replace( /\s*$/, '' );

		if ( mod_window ) { mod_window.innerHTML = content; }
		
		var anchors = mod_window.getElementsByTagName('a');
		
		for ( var i = 0; i < anchors.length; i++ ) { 
			
			if ( !anchors[i].getAttribute( 'href' ).match( /\#$/ ) ) { // javascripted
				
				addEvent( anchors[i], 'click', function( e ) {
				
					var target = window.event ? window.event.srcElement : e.target;

					killEvent( e );
					self.load( target.href );
				
				}, false );
			}
		}
		
		var forms = mod_window.getElementsByTagName('form');
		
		for ( var i = 0; i < forms.length; i++ ) { 
		
			addEvent( forms[i], 'submit', function( e ) {
			
				var target = window.event ? window.event.srcElement : e.target;
				
				var form = target;
				
				if ( target.tagName.toLowerCase() == 'input' ) { form = target.form; }
				
				killEvent( e );
				
				self.load( form.action + createPostQuery( form ), form.method.toUpperCase() );
			
			}, false );
		}
		
		this.sizeToContent();
										
	}
		
	if ( href ) {
	
		this.load( href, method );
	}
		

}



function ModalWindow( href, method, width, height ) {
	
	var self = this;
	
	var close_label = document.createElement('a');
	close_label.appendChild( document.createTextNode( 'Close' ) );
	close_label.href = '#';
	close_label.className = 'modalWindowClose';
	close_label.title = 'Close';
	
	var mod_window = document.createElement('div');
	mod_window.className = 'modalWindowContent';
	
	// new...
	var content = new Container( mod_window, null, null ,width, height );
	
	var container = document.createElement('div');
	container.className = 'modalWindow';
	container.appendChild( mod_window );
	container.appendChild( close_label );
	
	document.body.appendChild( container );	
	
	
	function positionModalWindow( ) {
			
		centerInWindow( container );
		
	}
	
	this.isOpen = false;
	
	content.onload = function() { container.style.visibility = 'hidden'; content.sizeToContent(); positionModalWindow( ); addClass( document.body, 'hideEmbed'); container.style.visibility = ''; }
	
	this.open = function( href, method ) {
				
		addEvent( window, 'resize', positionModalWindow, true );
		
		this.isOpen = true;
		
		var default_width = width ? width :  450;
		var default_height = height ? height :  300;
		
		// initially display a placeholder just to size the window...
		// content.setContent('<div style="width:' + default_width +'px;height:' + default_height +'px"></div>' );
		content.setContent('<table style="width:' + default_width +'px;height:' + default_height +'px"><tr><td align="center" valign="middle">Loading...</td></tr></table>' );
		content.sizeToContent(); 
		positionModalWindow( );
		
		this.load( href, method );
		
	}	
	
	
	this.load = function( href, method ) {
	
		content.load( href, method );
	}
	
	
	this.back = function() {
	
		content.back();
	
	}
	
	
	this.setContent = function( content ) {
			
		content.setContent( content );
		
	}
	
	
	this.setTransparency = function( amount ) {
	
		return setTransparency( container, amount );
	
	}
	
	this.close = function() {
		
		removeClass( document.body, 'hideEmbed'); 
		removeEvent( window, 'resize', positionModalWindow, true );
				
		// stop any previously requested content from being parsed...
		content.abort();
		container.parentNode.removeChild( container );
		
		this.isOpen = false;
		
		if ( typeof this.onclose == 'function' ) { return this.onclose(); }
	}
	
	this.onclose = null;
	
	close_label.onclick = function() { ModalWindow.close(); return false; }
	
	if ( href ) {
	
		this.open( href, method );
	}
		
}


ModalWindow.windows = [];
ModalWindow.current = null;
ModalWindow.backdrop = null;


ModalWindow.createBackdrop = function() {

	var backdrop = document.createElement('table');
	var tbody = document.createElement('tbody');
	var row = document.createElement('tr');
	var cell = document.createElement('td');
	row.appendChild( cell );
	tbody.appendChild( row );
	backdrop.appendChild( tbody );
	backdrop.id = 'modalWindowBackdrop';
	
	return backdrop;

}

ModalWindow.resizeBackdrop = function() {

	fillViewport( ModalWindow.backdrop );

}

ModalWindow.watchKeyPress = function ( e ) {
		
	var e = e ? e : window.event;
	
	if ( e.keyCode == 27 ) { 
			
		ModalWindow.close();
		
	}

}

ModalWindow.open = function( href, method, width, height ) { 
	
	if ( this.windows.length == 0 ) {
	
		if ( this.backdrop == null ) { this.backdrop = this.createBackdrop(); }
	
		var backdrop = this.backdrop;
		
		document.body.appendChild( backdrop );
		fillViewport( this.backdrop );
		
		addEvent( window, 'resize', ModalWindow.resizeBackdrop, true );
	
	}
	
	else {
	
		this.current.setTransparency( 0.5 );
	
	}
	
	var modal_window = new ModalWindow( href, method, width, height );
	this.windows.push( modal_window );
	this.current = modal_window;
	
	
		
	addEvent( document.body, 'keypress', this.watchKeyPress, true );
	

	return modal_window;

}


ModalWindow.load = function( href, method ) { 

	if ( this.current ) {
	
		return this.current.load( href, method );
	}
	
	return false;

}

ModalWindow.back = function( ) {

	if ( this.current ) {
	
		return this.current.back();
	
	}
	
	return false;

}


ModalWindow.close = function() { 
		
	if ( this.current ) {
	
		this.current.close();
		this.windows.pop();
	
	}
	
	if ( this.windows.length >= 1 ) {
	
		this.current = this.windows[this.windows.length - 1];
		this.current.setTransparency( 1 );
	
	}
	
	else {
	
		var backdrop = this.backdrop;
		
		backdrop.parentNode.removeChild( backdrop );
		removeEvent( window, 'resize', ModalWindow.resizeBackdrop, true );
		
		removeEvent( document.body, 'keypress', this.watchKeyPress, true );
		
	}
	
}




function createPostQuery( form ) {

	var query = new QueryString();

	 for ( var i = 0; i < form.elements.length; i++ ) {
	 
		input = form.elements[i];
		
		switch (input.type) {
			
			case 'text':
			case 'hidden':
			case 'password':
			case 'textarea':
			case 'submit':
			case 'file':
				query.set( input.name, input.value );
				break;

			case 'select-one':
				query.set( input.name, input.options[input.selectedIndex].value );
				break;
	
			case 'select-multiple':
				for ( var j = 0; j < input.options.length; j++ ) {
				
					if ( input.options[j].selected ) {
					
						query.set( input.name, input.options[j].value );
					
					}
				
				}
				
				break
			
			case 'radio':
			case 'checkbox':
				if ( input.checked ) { 
					query.set( input.name, input.value );
				}
				break;
				
		}
	}
	
	return query.toString();
}
