// prevent firebug errors
if (!window.console || !console.firebug) {
    var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml", "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];
    window.console = {};
    for (var i = 0; i < names.length; ++i)
        window.console[names[i]] = function() {}
}

// Allow for IE version detection
Prototype.Browser.IE6 = Prototype.Browser.IE && parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5)) == 6;
Prototype.Browser.IE7 = Prototype.Browser.IE && parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5)) == 7;
Prototype.Browser.IE8 = Prototype.Browser.IE && !Prototype.Browser.IE6 && !Prototype.Browser.IE7;

function show_gdialog(title, content) {
	window.gDialog = new goog.ui.Dialog(null, true);
	window.gDialog.setDisposeOnHide(true);
	window.gDialog.setTitle(title);
	window.gDialog.setButtonSet(null);
	window.gDialog.setDraggable(false);
	window.gDialog.setContent(content);
	window.gDialog.setBackgroundElementOpacity(0.7);
	window.gDialog.setVisible(true);
	window.gDialog.reposition();
	$$('.modal-dialog-bg')[0].setStyle('position: fixed; height: 100%; width: 100%;');
}

function show_gdialog_on_image(title, content, imageload) {
	window.loader = new goog.net.ImageLoader();
	window.imageLoaded = function() { show_gdialog(title, content) }
	goog.events.listen(this.loader, [goog.events.EventType.LOAD,goog.net.EventType.ERROR,goog.net.EventType.ABORT,goog.net.EventType.READY_STATE_CHANGE], this.imageLoaded, false, this);
	window.loader.addImage('loaderimg', imageload);
	window.loader.start();
}

function scrollToEl(e) {
	var el = $(e);
	Effect.ScrollTo(el, {
		afterFinish: function() { new Effect.Highlight(el); }
	});
}

function hide_subnav(except) {
	$$('.primarynav').each(function(pn) {
		if (pn.id != ('primarynav_' + except)) {
			pn.removeClassName('active');
		}
	});
	$$('.navsub_item').each(function(nsi) {
		var ns = nsi.up('.navsubOuter');
		if (ns) {
			if (nsi.id != ('navsub_' + except)) {
				ns.style.display = 'none'; // Hide the subnav menu
			}
		} else {
			var nss = nsi.up('.navsubSpecial');
			if (nss) {
				if (nsi.id != ('navsub_' + except)) {
					nss.style.display = 'none';
				}
			}	
		}
	});
}

function subnav_slide(e) {
	// Fix (i.e., lock) left/right position of submenus relative to the viewport.
	var sn = $(window.activeSubmenu);
	if (sn && sn.viewportOffset()[0] > 0) {
		var lvl = sn.id.split('_').pop(); // "sn" is the subnav item targeted by the click.
		var m = $('primarynav_' + lvl); // "m" is the corresponding main nav item
		var leftpos = m.positionedOffset()[0];
		var rightSide = leftpos + sn.getWidth();
		var leftval = m.positionedOffset()[0];
		if (rightSide > 963) {
			leftval = 963 - sn.getWidth();
		}
		sn.setStyle('left: ' + leftval + 'px;');
	}
}

function mainnav_clicked(e) {
	var navitem = e.findElement('.primarynav');
	var id = navitem.id.split('_').pop();
	var sn = $('navsubOuter_' + id);
	hide_subnav(id);
	if (navitem.hasClassName('active')) {
		if (sn && (sn.getStyle('display') == 'block')) {
			// Hide the submenu
			navitem.removeClassName('active');
			if (sn) { 
				//sn.setStyle('display: none;');
				new Effect.SlideUp(sn, { duration: 0.3});
			}
		} else {
			// Show the submenu.
			if (sn) {
				var leftpos = navitem.positionedOffset()[0];
				var rightSide = leftpos + sn.getWidth();
				var leftval = navitem.positionedOffset()[0];
				if (rightSide > 963) {
					// Don't let sub-menus extend beyond the right border of the site.
					leftval = 963 - sn.getWidth();
				}
				//sn.setStyle('display: block; visibility: visible; position: absolute; left: ' + leftval + 'px;');
				sn.setStyle('visibility: visible; position: absolute; left: ' + leftval + 'px;');
				new Effect.SlideDown(sn, { duration: 0.3});
				window.activeSubmenu = sn.id;
				Event.observe(window, 'resize', subnav_slide);			
			}
		}
	} else {
		// Show the submenu
		navitem.addClassName('active');
		if (sn) {
			var leftpos = navitem.positionedOffset()[0];
			var rightSide = leftpos + sn.getWidth();
			var leftval = navitem.positionedOffset()[0];
			if (rightSide > 963) {
				// Don't let sub-menus extend beyond the right border of the site.
				leftval = 963 - sn.getWidth();
			}
			//sn.setStyle('display: block; visibility: visible; position: absolute; left: ' + leftval + 'px;');
			sn.setStyle('visibility: visible; position: absolute; left: ' + leftval + 'px;');
			new Effect.SlideDown(sn, { duration: 0.3});
			window.activeSubmenu = sn.id;
			Event.observe(window, 'resize', subnav_slide);			
		}
	}
}

function clear_all_menuTimers() {
	var timercount = window.menuTimers.size();
	var i;
	for (i=0; i<timercount; i++) {
		if ((typeof window.menuTimers[i]) != 'undefined') {
			clearTimeout(window.menuTimers[i]);
		}
	}
}

function nav_mouseover(e) {
	var navitem = e.findElement('.primarynav');
	var id = navitem.id.split('_').pop();
	clear_all_menuTimers();
	showSubnav(id);
}

function nav_mouseout(e) {
	var navitem = e.findElement('.primarynav');
	var id = navitem.id.split('_').pop();
	window.menuTimers[id] = setTimeout("hideSubnav("+id+")", window.menuTimeout);	
}

function subnav_mouseover(e) {
	var el = e.findElement('.navsubOuter, .navsubSpecial');
	var id = el.id.split('_').pop();
	clearTimeout(window.menuTimers[id]);
}

function subnav_mouseout(e) {
	var el = e.findElement('.navsubOuter, .navsubSpecial');
	var id = el.id.split('_').pop();
	window.menuTimers[id] = setTimeout("hideSubnav("+id+")", window.menuTimeout);	
}

function hideSubnav(sid) {
	var sn = $('navsubOuter_' + sid);
	var navitem = $('primarynav_' + sid);
	hide_subnav(sid);
	if (sn) {
		navitem.removeClassName('active');
		sn.setStyle('display: none; visibility: hidden;');
	}
}

function showSubnav(sid) {
	var sn = $('navsubOuter_' + sid);
	var navitem = $('primarynav_' + sid);
	var nmi = $('navmain-inner');
	hide_subnav(sid);
	navitem.addClassName('active');
	if (sn) {
		var nmi_left = nmi.cumulativeOffset()[0];
		var nmi_width = nmi.getWidth();
		var nmi_right = nmi_left + nmi_width;
		var leftpos = navitem.cumulativeOffset()[0];
		var rightSide = leftpos + sn.getWidth();
		var leftval = leftpos;
		if (rightSide > nmi_right) {
			// Don't let sub-menus extend beyond the right border of the site.
			leftval = nmi_right - sn.getWidth();
		}
		sn.setStyle('display: block; visibility: visible; position: absolute; left: ' + leftval + 'px;');
		
		// Fix display bug in IE
		if (Prototype.Browser.IE === true) {
			sn.descendants().each(function(snd) {
				snd.setStyle('z-index: 8000');
			});
		}
		
		window.activeSubmenu = sn.id;
		Event.observe(window, 'resize', subnav_slide);
	}
}

function init_submenus_clickable() {
	$$('.primarynav').each(function(p) {
		p.observe('click', mainnav_clicked);
	});
}

function init_submenus() {
	window.menuTimeout = 200; // in milliseconds
	window.menuTimers = [];
	$$('.primarynav').each(function(p) {
		p.observe('mouseover', nav_mouseover);
		p.observe('mouseout', nav_mouseout);
	});
	$$('.navsubOuter, .navsubSpecial').each(function(s) {
		s.observe('mouseover', subnav_mouseover);
		s.observe('mouseout', subnav_mouseout);
	});
}

function fix_cols() {
	var cw = $('content-wrap');
	var f = $('footer');
	if (cw && f) {
		var cwtop = cw.cumulativeOffset().top;
		var cwbottom = cwtop + cw.getHeight();
		var ftop = f.cumulativeOffset().top - 1;
		if (cwbottom < ftop) {
			cw.setStyle('height: ' + (ftop - cwtop + 1) + 'px');
		}
	}
}

function morenews() {
	// Can't press the button twice in quick succession...
	if (window.moreNewsDisabled === true) { return false; }
	window.moreNewsDisabled = true;
	$('news_spinner').style.visibility = 'visible';
	
	// Bring the next batch of stories into the page.	
	xajax_morenews(window.storiesInPage, window.newscat);
}

function moreevents() {
	// Can't press the button twice in quick succession...
	if (window.moreNewsDisabled === true) { return false; }
	window.moreNewsDisabled = true;
	$('news_spinner').style.visibility = 'visible';
	
	// Bring the next batch of stories into the page.	
	xajax_moreevents(window.storiesInPage);
}

function check_prompt(fld) {
	if (fld.value == window.init_fields.text_prompts[fld.id]) {
		fld.removeClassName('filled_field');
		fld.addClassName('unfilled_field');
	} else {
		fld.removeClassName('unfilled_field');
		fld.addClassName('filled_field');
	}
}

window.init_imageSwaps = function() {
	window.init_imageSwaps.sources = {
		fontdown : {
			over: 'minus_over.png',
			up: 'minus.png'
		},
		fontup : {
			over: 'plus_over.png', 
			up: 'plus.png'
		}
	};
	this.image_hover = function(e) {
		e.target.src = window.BASE_URL + 'images/' + window.init_imageSwaps.sources[e.target.id].over;
	};
	this.image_unhover = function(e) {
		e.target.src = window.BASE_URL + 'images/' + window.init_imageSwaps.sources[e.target.id].up;
	}
	var fontup = $('fontup');
	var fontdown = $('fontdown');
	var imagesToWatch = [fontup, fontdown];
	imagesToWatch.each(function(im) {
		if (im) {
			im.observe('mouseover', this.image_hover);
			im.observe('mouseout', this.image_unhover);
		}
	});
}

window.init_fields = function() {
	window.init_fields.text_prompts = {
		first_name : 'First', 
		last_name : 'Last', 
		email : 'name@email.com', 
		phone : '123-456-7890', 
		address1 : '10 Main St', 
		city : 'Anywhere', 
		state : 'State', 
		zip : '00000', 
		datetimes : 'Thursday mornings', 
		message : 'Type message'
	};
	this.prompt_focused = function(e) {
		if (e.target.value == window.init_fields.text_prompts[e.target.id]) { e.target.value = ''; }
		check_prompt(e.target);
	};
	this.prompt_blur = function(e) {
		if (e.target.value.blank() === true) { e.target.value = window.init_fields.text_prompts[e.target.id]; }
		check_prompt(e.target);
	};
	var first_name = $('first_name');
	var last_name = $('last_name');
	var email = $('email');
	var phone = $('phone');
	var address1 = $('address1');
	var city = $('city');
	var state = $('state');
	var zip = $('zip');
	var datetimes = $('datetimes');
	var message = $('message');
	var fieldsToWatch = [first_name, last_name, email, phone, message, address1, city, state, zip, datetimes];
	fieldsToWatch.each(function(field) {
		if (field) {
			field.observe('focus', this.prompt_focused); 
			field.observe('blur', this.prompt_blur); 
			check_prompt(field); // Turn it gray if unfilled, blue if filled.	
		}
	});	
}

function global_init() {
	init_submenus();
	fix_cols();
	window.init_fields();
	window.init_imageSwaps();
}
Event.observe(window, 'load', global_init);
