var onloadEvents = new Array();

function addToOnload(event){
	onloadEvents.push(event);
	window.onload = function() { 
		for (var x = 0; x < onloadEvents.length; x ++) {
			eval(onloadEvents[x]);
		}
	}
}
sfHover = function() {
	var sfEls = document.getElementById("navigation").getElementsByTagName("LI");
	for (var i=0; i<sfEls.length; i++) {

		var className = this.className;
		if(className == 'first' || className == 'last' || className == '') continue;
	
		sfEls[i].onmouseover=function() {
			var className = this.className;
			if(className.indexOf(' ') != -1) {
				var className = className.substr(0, className.indexOf(' '));
			}
			this.className+=" "+className+"-sfhover";
			hideSelects(this, true);
		}
		sfEls[i].onmouseout=function() {
			var className = this.className;
		
			if(className.indexOf(' ') != false) {
				var className = className.substr(0, className.indexOf(' '));
			}
			this.className=this.className.replace(new RegExp(" "+className+"-sfhover\\b"), "");
			hideSelects(this, false);
		}
	}
}

function hideSelects(element, hide) {
//	if(hide) {
//		visibility = 'hidden';
//	} else {
//		visibility = 'visible';
//	}
//	// are we on the home page.
//
//	if(document.getElementById('home')) {
//		var selects = document.getElementsByTagName('select');
//		for(var i = 0; i < selects.length; i++) {
//			selects[i].style.visibility = visibility;
//		}
//	}
//	return;
//	var shimID = 'shim-'+element.className.substr(4);
//	//var selects = document.getElementsByTagName('select');
//	//for(var i = 0; i < selects.length; i++) {
//		if(!hide) {
//
//			if(document.getElementById(shimID) == null) {
//				var tmp = document.createElement('iframe');
//				tmp.id = shimID;
//				tmp.style.background = 'red';
//				tmp.style.position = 'absolute';
//				tmp.style.top = '30px';
//				tmp.style.left = '0';
//				tmp.style.width = '310px';
//				tmp.style.zIndex = '9998';
//				tmp.style.filter = 'progidXImageTransform.Microsoft.Alpha(style=0,op acity=0)';
//				tmp.frameBorder = 0;
//
//				element.appendChild(tmp);
//
//				/*var iframeShim = new Element('div', {
//					id: 'shim',
//					src: 'javascript: false; document.write("");',
//					frameBorder: 0,
//					style: {
//						'z-index': 9998
//					}
//				});*/
//			} else {
//				document.getElementById(shimID).style.display = 'block';
//			}
//		} else {
//			window.status = document.getElementById(shimID);
//			if(document.getElementById(shimID) != null) {
//				//alert('asdf');
//				document.getElementById(shimID).style.display = 'none';
//			}
//		}
//
//	
		//selects[i].style.visibility = visibility;
	//}
}

// only attach for ie
if (window.attachEvent) window.attachEvent("onload", sfHover);
addToOnload('pageControl.init()');
addToOnload('searchBar.init()');
addToOnload('textControl.init()');
//addToOnload('tableControl.init()');

// round a float to precision dec
function roundNumber(num, dec) {
	var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
	return result;
}

var textControl = {
	currentSize: 1.00,
	emModifier: .10,
	cookieExpires: 365 * 5, // 5 years
	init: function() {
		this._attachEvents();
		var cookieVal = roundNumber(parseFloat(Cookie.read('emSize')), 1);
		if(cookieVal != null) {
			if(cookieVal >= 1 && cookieVal <= 1.5) {
				this.currentSize = cookieVal;
				//this._changeTextSizeEM(cookieVal);
			} else {
				Cookie.dispose('emSize');
			}
		}
	},
	printPage: function() {
		window.print();
	},
	increaseText: function() {
		if(this.currentSize < 1.5) {
			this.currentSize += this.emModifier;
			this._changeTextSizeEM(this.currentSize);
		}
	},
	decreaseText: function() {
		if(this.currentSize > 1) {
			this.currentSize -= this.emModifier;
			this._changeTextSizeEM(this.currentSize);
		}
	},
	_changeTextSizeEM: function(emSize) {
		var area = $$('#column-left-content,#column-left, #column-middle, #mymia-home, #loginContainer');
		var area2 = $$('#column-full');
		
		Cookie.write('emSize', roundNumber(emSize,2), {path: '/', duration: textControl.cookieExpires});
		// make sure the content area exists
		if(area && area != null && area != '') {
			area.setStyle('font-size', emSize+'em').setStyle('line-height', 'normal');
		} else if(area2 && area2 != null) {
			area2.setStyle('font-size', emSize+'em').setStyle('line-height', 'normal');
			var labels = $$('#column-full li>label');
			for(var i = 0; i < labels.length; i++) {
				if(emSize == 1) {
					labels[i].setStyle('line-height', '16px');
				} else {
					labels[i].setStyle('line-height', '1em');
				}
				var h = parseInt(labels[i].getHeight());
				if(h == 0) {
					// (lines) * (16px * emSize)
					h = parseInt((labels[i].get('text').length / 14) * (16 * (emSize + .1)));
				}
				labels[i].getParent().setStyle('min-height', (h)+'px');
			}
		}
	},
	_attachEvents: function() {
		$$('#contentControl>button.print').addEvent('click', function() {
			textControl.printPage();
		});
		$$('#contentControl>button.decrease').addEvent('click', function() {
			textControl.decreaseText();
		});
		$$('#contentControl>button.increase').addEvent('click', function() {
			textControl.increaseText();
		});
	}
}

var pageControl = {
	init : function() {
		// TEMPORARY! trap links to #
		this.trapLinks();
		
		var findMigrationAgent = $('find-migration-agent');
		if(findMigrationAgent) {
			findMigrationAgent.getElements('input').each(function(e){
				if(e.name == 'memberName' || e.name == 'memberLocation') {
					if(e.value == '') {
						e.value = 'Please enter...';
					}
				
					e.addEvent('click', function(){
						if(e.value == 'Please enter...') {
							e.value = '';
						}
					});
					
					e.addEvent('blur', function(){
						if(e.value == '') {
							e.value = 'Please enter...';
						}
					});
				}
			});
			// fix images not being clickable
			$$('div.search-result-item>a img').addEvent('click', function() {
				var tmp = Element(arguments[0].target);
				document.location.href = tmp.getParent('a'); 
			});
		}
		
		var miaSearch = $('mia-search');
		if(miaSearch) {
			miaSearch.getElements('input').each(function(e){
				if(e.name == 'searchTerm') {
					if(e.value == '') {
						e.value = 'Please enter...';
					}
				
					e.addEvent('click', function(){
						if(e.value == 'Please enter...') {
							e.value = '';
						}
					});
					
					e.addEvent('blur', function(){
						if(e.value == '') {
							e.value = 'Please enter...';
						}
					});
				}
			});
		}
		
		var cpdSearch = $('cpd-search');
		if(cpdSearch) {
			cpdSearch.getElements('input').each(function(e){
				if(e.name == 'subject') {
					if(e.value == '') {
						e.value = 'Enter search term';
					}
					e.addEvents({
						'click': function() {
							if(e.value == 'Enter search term') {
								e.value = '';
							}
						},
						'blur': function() {
							if(e.value == '') {
								e.value = 'Enter search term';
							}
						}
					});
				}
			});
		}

		var eventEducationSearch = $('event-education-search');
		if(eventEducationSearch) {
			eventEducationSearch.getElements('input').each(function(e){
				if(e.get('id') == 'eeSubject') {
					if(e.get('value') == '') {
						e.set('value', 'Enter search term');
					}
					e.addEvents({
						'click': function() {
							if(e.get('value') == 'Enter search term') {
								e.set('value', '');
							}
						},
						'blur': function() {
							if(e.get('value') == '') {
								e.set('value', 'Enter search term');
							}
						}
					});
				}
			});
		}
	},
	
	trapLinks: function() {
		var $links = $$('a[href=#]');
		for(var i = 0; i < $links.length; i++) {
			$links[i].addEvent('click', function() {
				return false;
			});
		}
	}
}

var searchBar = {
	created: false,
	bar: null,
	displayStatus: 'hidden',
	// public
	init: function() {
		this.attachEvents();
	},
	// private
	attachEvents: function() {
		$$('li.search>a').addEvent('click', function() {
			searchBar.toggle();
			return false;
		});
	},
	// public
	toggle: function() {
		if(this.displayStatus == 'hidden') {
			this.show();
		} else {
			this.hide();
		}
	},
	// public
	show: function() {
		if(!this.created) {
			this.createBar();
		}
		this.bar.setStyle('display', 'block');
		$$('body').setStyle('background-position', 'left 54px');
		//$('search-bar').setStyle('display', 'block');
		this.displayStatus = 'visible';
	},
	// public
	hide: function() {
		this.bar.setStyle('display', 'none');
		$$('body').setStyle('background-position', 'left top');
		this.displayStatus = 'hidden';
	},
	// private
	createBar: function() {
		var defaultValue = 'Search the MIA';
		var sb = new Element('div', {
			'id': 'search-bar',
			'html': '<form method="get" action="/search/"><input class="search-box" type="text" name="searchTerm" value="'+defaultValue+'" /><button class="yellow"><span><em class="search-bar">Search</em></span></button><span class="errors"></span></form>'
		});
		sb.inject('container', 'before');
		$$('#search-bar input').addEvent('focus', function() {
			if(this.value == defaultValue) {
				//this.value = '';
			}
		})[0].select();
		// fix button position in ie6/7
		if(Browser.Engine.trident && Browser.Engine.version <= 5) { // IE7 or lower
			$$('#search-bar button').setStyle('margin-bottom', '7px');
		}

		$$('#search-bar form').addEvent('submit', function() {
			inp = $$('#search-bar input')[0];
			if(inp.value == '' || inp.value == defaultValue) {
				inp.select();
				return false;
			}
		});
		this.bar = $$('#search-bar');
		this.created = true;
	}
}

/*var tableControl = {
	init: function() {
		$$('table tbody tr').addEvent('mouseover', function(element) {
			var targetElement = element.target.getParent();
			while(targetElement != 'td') {
				targetElement = targetElement.getParent();
			}
			
			/*if(element.target == 'a') {
				
			}
			
			targetElement.setStyle('background', 'red');
			
			
			//tmp = new Element(element.target);
			//tmp.setStyle('background', 'red');
			
			element.addEvent('mouseover', function(ele) {
			});
		});
	}
}*/

/* start table roll over js (legacy) */
function dom_by_tag(tag, obj) {
	return obj.getElementsByTagName(tag);
}
var c_on_colour = '#F3F8FB';
var c_off_colour = '';
function attach_rollovers()
{
	var t = document.getElementsByTagName("table");
	for(var i = 0; i < t.length; i++) {
		var table = t[i];
		if(table.className.indexOf('list-results') == -1) continue;
		
		var trs = table.getElementsByTagName("tr");
		
		for (var e = 0; e < trs.length; e ++) {
			trs[e].onmouseover = function() {
				this.style.cursor = "pointer";
				var tds = dom_by_tag("td", this);
				for (var m = 0; m < tds.length; m ++) {
					tds[m].style.backgroundColor = c_on_colour;
				}
			}
			trs[e].onmouseout = function() {
				this.style.cursor = "default";
				var tds = dom_by_tag("td", this);
				for (var m = 0; m < tds.length; m ++) {
					tds[m].style.backgroundColor = c_off_colour;
				}
			}
			trs[e].onclick = function() {
				
				var anchors = dom_by_tag("a", this);
				if(anchors.length > 0) {
					this.style.cursor = "wait";
					document.location.href = anchors[0].href;
				} else {
					this.style.cursor = 'default';
				}
			}
		}
	}
}

addToOnload("attach_rollovers()");
/* end table roll over js (legacy) */

/* start google maps popup */
var siteBaseUrl = '/';
popupKeyListener();
function attachOnClickMap(){//id, dealershipId, addressType){
	//alert('asdf');
	//element = document.getElementById(id);
	//element.style.cursor = 'pointer';
	var divWidth = 600;
	var divHeight = 450;		
	//element.onclick = function (){
		//check if this element exists.
		
	e = document.getElementById('map-display');
	
	if (!e){
		myDimensions = getWindowDimensions();
		myWidth = myDimensions[0];
		
		if (document.all && !window.opera){
			var spinner = document.createElement("DIV");
			spinner.id = "spinner";
			spinner.className = 'busySignal';
			spinner.style.zIndex = '10000';
			spinner.style.width = '628px';
			spinner.style.position = 'absolute';
			spinner.style.top = (window.getScrollTop() + 80)+'px';
			spinner.style.left = (myWidth / 2) - (divWidth / 2) + "px";
			spinner.style.height =  '460px';
			document.body.appendChild(spinner);		
		}
		
		var myDiv = document.createElement("DIV");
		myDiv.id = "map-display";
		myIframe = document.createElement('iframe');
		myIframe.src = siteBaseUrl+'map.php';//?dealerId='+dealershipId+'&type='+addressType;	
		myIframe.style.zIndex = '100';
		myIframe.scrolling = 'no';
		myIframe.width = divWidth;
		myIframe.height = divHeight+40;					
		myIframe.frameBorder = "0";
		
		//Append
		myDiv.appendChild(myIframe);
		myDiv.style.position = 'absolute';
		myDiv.style.width = divWidth+'px';
		myDiv.style.top = (window.getScrollTop() + 50)+'px';
		myDiv.style.left = (myWidth / 2) - (divWidth / 2) + "px";
		document.body.appendChild(myDiv);
		
	}
		
		return false;
	//}
}

function processKeyPress(e){
	var e = window.event  || e;
	
	try {
		var key = e.keyCode || e.which;
	} catch (e){
		var key = 0;
	}
	//Esc or x (lowercase)
	if (key == 27 || key == 120) closePopup();
	
}

function closePopup() {
	e = document.getElementById('map-display');
	if (e){
		e.parentNode.removeChild(e);
	} 
}



function popupKeyListener() {document.onkeypress = processKeyPress;}


function getWindowDimensions(){
	
	var myWidth = 0, myHeight = 0;
	if( typeof( window.innerWidth ) == 'number' ) {
		//Non-IE
		myWidth = window.innerWidth;
		myHeight = window.innerHeight;
	} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
		//IE 6+ in 'standards compliant mode'
		myWidth = document.documentElement.clientWidth;
		myHeight = document.documentElement.clientHeight;
	} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
		//IE 4 compatible
		myWidth = document.body.clientWidth;
		myHeight = document.body.clientHeight;
	}
	return [myWidth, myHeight];
}
/* end google maps popup */

/** some mootools selectors*/
// :heading
Selectors.Pseudo.heading = function() {
	return (
			'h1' == Element.get(this, 'tag') ||
			'h2' == Element.get(this, 'tag') ||
			'h3' == Element.get(this, 'tag') ||
			'h4' == Element.get(this, 'tag') ||
			'h5' == Element.get(this, 'tag') ||
			'h6' == Element.get(this, 'tag')
	);
}





