//For JSLint
/*global focusObject, $, ActiveXObject, DOMParser, GBrowserIsCompatible, GClientGeocoder, GEvent, GL_SITE_ROOT, GMap2, GMapTypeControl, GMarker, GSmallMapControl */

$(document).ready(function() {
	//bindImageCheckRadios("input[type=checkbox]", "jqCheckbox_checkBox");
	//bindImageCheckRadios("input[type=radio]", "jqCheckbox_radioBox");
});

//Global var to track which object has focus
var focusObject;

function bindImageCheckRadios(selector, className) {
	//Bind image checkboxes/radios
	$(selector).checkbox({
		cls: className,
		empty:  GL_SITE_ROOT + 'images/checkbox/empty.png'
	});
}

function setLastFocus(obj) {
	focusObject = obj;
}

function getLastFocus() {
	return focusObject;
}

function openWindow(url, windowName, width, height) {
	var winl, wint;
	
	var settings = '';
	
	if (screen.width) {
		winl = (screen.width - width) / 2;
		wint = (screen.height - height) / 2;
	} else {
		winl = 0;
		wint = 0;
	}
	
	if (winl < 0) { winl = 0; }
	if (wint < 0) { wint = 0; }
	
	settings += 'height=' + height + ',';
	settings += 'width=' + width + ',';
	settings += 'top=200,left=200,';
	settings += 'directories=no,location=no,menubar=no,scrollbars=yes,status=no,toolbar=no,resizable=yes';
	
	var win = window.open(url, windowName, settings);
	
	return win;
}

function trim(str) {
	if (str === "") {
		return str;
	}
	
	if (str.charAt) {
		while (str.charAt(0) == ' ') {
			str = str.substring(1);
		}
		
		while (str.charAt(str.length - 1) == ' ') {
			str = str.substring(0, str.length - 1);
		}
		
		return str;
	} else {
		return str;
	}
}

function isEmailValid(sEmail) {
	sEmail = trim(sEmail);
	
	if (sEmail === '') {
		return false;
	}
	
	//Define RegEx string
	var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	
	//Test email address
	if (filter.test(sEmail)) {
		return true;
	} else {
		return false;
	}
}

function isValidZipcode(sZip) {
	sZip = trim(sZip);
	
	//Valid formats:
	//  99999               (5)
	//  99999-9999         (10)
	//  99999 9999         (10)
	//  999999999           (9)
	//  AAAAAA (Canadian)   (6)
	//  AAA AAA (Canadian)  (7)
	
	//First, check length - must be 5, 10, 9, or 6 characters long
	if (sZip.length !== 5 && sZip.length !== 10 && sZip.length !== 9 && sZip.length !== 6 && sZip.length !== 7) {
		return false;
	}
	
	//If ZIP code is 5 or 9 characters, they must all be numbers
	if (sZip.length == 5 || sZip.length == 9) {
		if (isNaN(sZip)) {
			return false;
		}
	}
		
	//If ZIP code is 10 characters, must be 99999-9999 or 99999 9999
	if (sZip.length == 10) {
		//6th character must be a dash or space
		if(!sZip.indexOf('-') == 5 && !sZip.indexOf(' ') == 5) {
			return false;
		}
		
		//Check that first 5 characters and last 4 characters are all numbers
		var firstFive = sZip.substring(0, 5);
		var lastFour = sZip.substring(6, 10);
		
		if (isNaN(firstFive) || isNaN(lastFour)) {
			return false;
		}
	}
	
	//If ZIP code is 6 characters, it must be Canadian and must NOT be all numbers
	if (sZip.length == 6) {
		if (!isNaN(sZip)) {
			return false;
		}
		
		//First character cannot be a number
		var firstChar = sZip.substring(0, 1);
		
		if (!isNaN(firstChar)) {
			return false;
		}
	}
	
	
	//If ZIP code is 7 characters, it must be Canadian and must NOT be all numbers
	if (sZip.length == 7) {
		if (!isNaN(sZip)) {
			return false;
		}
		
		//First character cannot be a number
		firstChar = sZip.substring(0, 1);
		if (!isNaN(firstChar)) {
			return false;
		}
		
		//Fourth character must be a dash or space
		if(!sZip.indexOf('-') == 3 && !sZip.indexOf(' ') == 3) {
			return false;
		}
	}
	
	return true;
}


function addDays(myDate, days) {
    return new Date(myDate + (days * 24 * 60 * 60 * 1000));
}

function FormatNumber(expr, decplaces) {
	if (isNaN(expr) || isNaN(parseFloat(expr, 10))) {
		return expr;
	}
	
	var str = "" + Math.round(eval(expr) * Math.pow(10, decplaces));
	
	while (str.length <= decplaces) {
		str = "0" + str;
	}
	
	var decpoint = str.length - decplaces;
	
	return str.substring(0,decpoint) + "." + str.substring(decpoint, str.length);
}

//Required by daysInMonth()
function isLeapYear(yr) {
	if (yr % 4 !== 0) { return false; }
	else if (yr % 400 === 0) { return true; }
	else if (yr % 100 === 0) { return false; }
	else { return true; }
}

//Required by isValidDate()
function daysInMonth(mn, yr) {
	var mDay;
	
	if ((mn === 4) || (mn === 6) || (mn === 9) || (mn === 11)) { 
		mDay = 30;
	} else if (mn === 2) {
		//calling leap year function 
		mDay = isLeapYear(yr) ? 29 : 28;    
	} else {
		mDay = 31;
	}
	
	return mDay; 
}

function isValidDate(sDate) {
	sDate = trim(sDate);
	
	var dateSplit = sDate.split("/");
	
	if (dateSplit.length !== 3) {
		return false;
	}
	
	var month = trim(dateSplit[0]);
	var day = trim(dateSplit[1]);
	var year = trim(dateSplit[2]);

	month = parseInt(month, 10);
	day = parseInt(day, 10);
	year = parseInt(year, 10);
	
	if (isNaN(month) || isNaN(day) || isNaN(year)) {
		return false;
	}

	//All parts must be numbers
	if (isNaN(month) || isNaN(day) || isNaN(year)) {
		return false;
	}
	
	//Check month (must be between 1 and 12)
	if (month < 1 || month > 12) {
		return false;
	}
	
	//Check day (must be between 1 and 31)
	if (day < 1 || day > 31) {
		return false;
	}
	
	//Check year -- make into 4-digit year if needed
	if (year.length === 2) {
		if (year < 70) {
			year = 2000 + year;
		} else {
			year = 1900 + year;
		}
	} else if (year.length === 3) {
		return false;
	}
	
	//Make sure the day entered is valid based on the month & year entered
	if (day > daysInMonth(month, year)) {
		return false;
	}
	
	return true;
}

function isValidTime(sTime) {
	sTime = trim(sTime);
	
	if (sTime === '') {
		return true;
	}
	
	if (sTime.indexOf(":") < 0) {
		return false;
	}
	
	var timeSplit = sTime.split(":");
	timeSplit[0] = trim(timeSplit[0]);
	timeSplit[1] = trim(timeSplit[1]);
	
	if (isNaN(timeSplit[0]) || isNaN(timeSplit[1])) {
		return false;
	}

	//Check first part (must be between 1 and 12)
	if (parseInt(timeSplit[0], 10) < 1 || parseInt(timeSplit[0], 10) > 12) {
		return false;
	}
	
	//Check last part (must be between 00 and 59 and must be 2 digits)
	if (parseInt(timeSplit[1], 10) < 0 || parseInt(timeSplit[1], 10) > 59 || timeSplit[1].length !== 2) {
		return false;
	}
	
	return true;
}

function getRadioValue(objRadio) {
	var itemChecked = false;
	
	//Only consider returning a value if the radio object is valid
	if (objRadio) {
		for (var i=0; i < objRadio.length; i++) {
			if (objRadio[i].checked) {
				itemChecked = true;
				return objRadio[i].value;
			}
		}
		
		if (itemChecked === false) {
			return '';
		}
	} else {
		return '';
	}
}

function setRadioValue(objRadio, sValue) {
	//Only take action if the radio object is valid
	if (objRadio) {
		for (var i=0; i < objRadio.length; i++) {
			if (objRadio[i].value === sValue) {
				objRadio[i].checked = true;
			}
		}
	}
}

function changeHoverMode(element, mode) {
	if (element.getAttribute('borderState') === 'on') {
		return;
	}
	
	if (mode === 'on') {
		element.style.backgroundColor = '#eeeeee';
	} else {
		element.style.backgroundColor = '#ffffff';
	}
}

function showHideElement(elementId, action) {
	var oElement = document.getElementById(elementId);
	
	if (oElement) {
		if (action === 'show') {
			oElement.style.display = '';
		} else if (action === 'hide') {
			oElement.style.display = 'none';
		} else if (action === 'toggle') {
			if (oElement.style.display === '') {
				oElement.style.display = 'none';
			} else {
				oElement.style.display = '';
			}
		}
		
		return oElement;
	}
}

function setClass(elementId, className) {
	var oElement = document.getElementById(elementId);
	
	if (oElement) {
		oElement.className = className;
	}
}

function showHideExpandIcon(elementId, iconId, action, root) {
	var oElement = showHideElement(elementId, action);
	var oIcon = document.getElementById(iconId);
	
	//If element is not showing, change plus/minus to "plus"
	if (oElement.style.display === 'none') {
		oIcon.src = root + 'images/icons/arrow-right.gif';
	} else {
		oIcon.src = root + 'images/icons/arrow-down.gif';
	}
}

function toggleExpandIcon(iconId, action, root) {
	var oIcon = document.getElementById(iconId);
	
	if (oIcon) {
		if (action == 'toggle') {
			if (oIcon.src.indexOf('arrow-right') >= 0) {
				oIcon.src = root + 'images/icons/arrow-down.gif';
			} else {
				oIcon.src = root + 'images/icons/arrow-right.gif';
			}
		} else if (action == 'show') {
			oIcon.src = root + 'images/icons/arrow-down.gif';
		} else if (action == 'hide') {
			oIcon.src = root + 'images/icons/arrow-right.gif';
		}
	}
}

function jqShowHideExpandIcon(elementId, iconId, action, root, callback) {
	var oElement = document.getElementById(elementId);
	
	$(document).ready(function () {
		toggleExpandIcon(iconId, action, root);
		
		if (callback == null) {
			callback = function() { };
		}
		
		if (action == 'show') {
			$(oElement).slideDown("fast", callback);
		} else if (action == 'hide') {
			$(oElement).slideUp("fast", callback);
		} else {
			$(oElement).slideToggle("fast", callback);
		}
	});
}

//Required by sortSelectBox()
function sortSelectOptions(a, b) {
	if ((a.text.toLowerCase() + "") < (b.text.toLowerCase() + "")) { return -1; }
	if ((a.text.toLowerCase() + "") > (b.text.toLowerCase() + "")) { return 1; }
	return 0;
}

function sortSelectBox(obj) {
	var o = [];
	
	if (!obj.options) {
		return;
	}
	
	//Add all select box options to an array
	for (var i=0; i < obj.options.length; i++) {
		o[o.length] = new Option(obj.options[i].text, obj.options[i].value, obj.options[i].defaultSelected, obj.options[i].selected) ;
	}
	
	if (o.length === 0) {
		return;
	}
	
	//Sort the array based on the option texts
	o = o.sort(sortSelectOptions);

	//Add contents of array back to select box in newly-sorted order
	for (i=0; i < o.length; i++) {
		obj.options[i] = new Option(o[i].text, o[i].value, o[i].defaultSelected, o[i].selected);
	}
}

function getCursorPosition(e) {
    e = e || window.event;
    var cursor = {x:0, y:0};
	
    if (e.pageX || e.pageY) {
        cursor.x = e.pageX;
        cursor.y = e.pageY;
    } else {
        cursor.x = e.clientX + 
            (document.documentElement.scrollLeft || 
            document.body.scrollLeft) - 
            document.documentElement.clientLeft;
        cursor.y = e.clientY + 
            (document.documentElement.scrollTop || 
            document.body.scrollTop) - 
            document.documentElement.clientTop;
    }
	
    return cursor;
}

//Required by various
function f_filterResults(n_win, n_docel, n_body) {
	var n_result;
	
	if (n_win) {
		n_result = n_win;
	} else {
		n_result = 0;
	}
	
	if (n_docel && (!n_result || (n_result > n_docel))) {
		n_result = n_docel;
	}
	
	var retValue;
	
	if (n_body && (!n_result || (n_result > n_body))) {
		retValue = n_body;
	} else {
		retValue = n_result;
	}
	
	return retValue;
}

//Required by getWindowSize()
function f_clientWidth() {
	var param1, param2, param3;
	
	if (window.innerWidth) { param1 = window.innerWidth; } else { param1 = 0; }
	if (document.documentElement) { param2 = document.documentElement.clientWidth; } else { param2 = 0; }
	if (document.body) { param3 = document.body.clientWidth; } else { param3 = 0; }

	return f_filterResults (param1, param2, param3);
}

//Required by getWindowSize()
function f_clientHeight() {
	var param1, param2, param3;
	
	if (window.innerHeight) { param1 = window.innerHeight; } else { param1 = 0; }
	if (document.documentElement) { param2 = document.documentElement.clientHeight; } else { param2 = 0; }
	if (document.body) { param3 = document.body.clientHeight; } else { param3 = 0; }

	return f_filterResults (param1, param2, param3);
}

//Required by getWindowSize()
function f_scrollLeft() {
	var param1, param2, param3;
	
	if (window.pageXOffset) { param1 = window.pageXOffset; } else { param1 = 0; }
	if (document.documentElement) { param2 = document.documentElement.scrollLeft; } else { param2 = 0; }
	if (document.body) { param3 = document.body.scrollLeft; } else { param3 = 0; }
	
	return f_filterResults (param1, param2, param3);
}

//Required by getWindowSize()
function f_scrollTop() {
	var param1, param2, param3;
	
	if (window.pageYOffset) { param1 = window.pageYOffset; } else { param1 = 0; }
	if (document.documentElement) { param2 = document.documentElement.scrollTop; } else { param2 = 0; }
	if (document.body) { param3 = document.body.scrollTop; } else { param3 = 0; }
	
	return f_filterResults (param1, param2, param3);
}

//Functions to determine window size
function getWindowSize() {
	var windowSize = {width:0, height:0, scrollLeft:0, scrollTop:0, top:0, left:0};
	
	windowSize.width = f_clientWidth();
	windowSize.height = f_clientHeight();
	windowSize.scrollLeft = f_scrollLeft();
	windowSize.scrollTop = f_scrollTop();
	windowSize.top = windowSize.scrollTop;
	windowSize.bottom = windowSize.top + windowSize.height;
	windowSize.left = windowSize.scrollLeft;
	windowSize.right = windowSize.left + windowSize.width;
	
	return windowSize;
}

function getObjectSize(objId) {
	var size = {width:0, height:0};
	var obj = document.getElementById(objId);
	
    if (document.layers) {
		size.height = obj.document.height;
		size.width = obj.document.width;
	} else if (document.all) {
		size.height = obj.offsetHeight;
		size.width = obj.offsetWidth;
	}
	
	return size;
}

function tabExists(tabIdsArray, tabId) {
	if (!tabIdsArray) {
		return false;
	}
	
	var tabPresent = false;
	var contentDivId, tabElementId;
	
	for(var i=0; i < tabIdsArray.length; i++) {
		if (tabIdsArray[i] !== tabId) {
			continue;
		}
		
		eval('contentDivId = \'tabContent_' + tabIdsArray[i] + '\'');
		eval('tabElementId = \'tab_' + tabIdsArray[i] + '\'');
		
		if (document.getElementById(contentDivId) && document.getElementById(tabElementId)) {
			tabPresent = true;
			break;
		}
	}
	
	return tabPresent;
}

function showTab(tabIdsArray, tabId, callback) {
	var contentDivId, tabElementId;
	
	//Verify that the requested tab is part of the tabIdsArray...
	if (!tabExists(tabIdsArray, tabId)) {
		//Default to first tab
		tabId = tabIdsArray[0];
	}
	
	//First, hide content for all tabs & set tab class to "off" state
	for(var i=0; i < tabIdsArray.length; i++) {
		eval('contentDivId = \'tabContent_' + tabIdsArray[i] + '\'');
		eval('tabElementId = \'tab_' + tabIdsArray[i] + '\'');
		showHideElement(contentDivId, 'hide');
		setClass(tabElementId, 'contentBoxTab_off');
	}
	
	//Show the content for the requested tab and set tab class ot "on" state
	eval('contentDivId = \'tabContent_' + tabId + '\'');
	eval('tabElementId = \'tab_' + tabId + '\'');
	showHideElement(contentDivId, 'show');
	//$("#" + contentDivId).fadeIn(100, callback);
	
	if (callback != null) {
		callback();
	}
	
	setClass(tabElementId, 'contentBoxTab_on');
}

function trapKeypress(e, theKey) {
	var iKeyCode = 0;
	
	if (window.event) {
		iKeyCode = window.event.keyCode;
	} else if (e) {
		iKeyCode = e.which;
	}
	
	return (iKeyCode !== theKey);
}

function enterPressed(event) {
	var result = trapKeypress(event, 13);
	
	if (result === true) {
		//Enter key was NOT pressed
		return false;
	} else {
		return true;
	}
}

function trapEnter(event) {
	return trapKeypress(event, 13);
}

function selectOption(selectBoxId, method, matchText) {
	//Get ref to object
	var oSelect = document.getElementById(selectBoxId);
	var optionValue = '';
	var optionText = '';
	
	if (oSelect && oSelect.options) {
		//Loop through select options
		for (var i=0; i < oSelect.options.length; i++) {
			optionValue = oSelect.options[i].value;
			optionText = oSelect.options[i].text;
			
			if (method === 'value' && matchText === optionValue) {
				oSelect.options[i].selected = true;
				return;
			} else if (method === 'text' && matchText === optionText) {
				oSelect.options[i].selected = true;
				return;
			}
		}
	}
}

function getBrowserInfo() {
	var userAgentString = navigator.userAgent.toLowerCase();
	var browser, version, os;

	//Determine browser & version
	if (userAgentString.indexOf('msie') >= 0) {
		browser = 'msie';
		version = userAgentString.charAt(userAgentString.indexOf(browser) + browser.length + 1);
	} else if (userAgentString.indexOf('safari') >= 0) {
		browser = 'safari';
		version = userAgentString.charAt(userAgentString.indexOf(browser) + browser.length + 1);
	} else if (userAgentString.indexOf('firefox') >= 0) {
		browser = 'firefox';
		version = userAgentString.charAt(userAgentString.indexOf(browser) + browser.length + 1);
	} else if (userAgentString.indexOf('opera') >= 0) {
		browser = 'opera';
		version = userAgentString.charAt(userAgentString.indexOf(browser) + browser.length + 1);
	} else if (!userAgentString.indexOf('compatible')) {
		browser = 'netscape';
		version = userAgentString.charAt(8);
	}
	
	//Determine Operating System
	if (userAgentString.indexOf('linux') >= 0) {
		os = 'linux';
	} else if (userAgentString.indexOf('x11') >= 0) {
		os = 'unix';
	} else if (userAgentString.indexOf('mac') >= 0) {
		os = 'mac';
	} else if (userAgentString.indexOf('win') >= 0) {
		os = 'windows';
	} else {
		os = 'other';
	}
}

function SelectAllListboxItems(oListbox) {
	if (!oListbox) {
		return;
	}
	
	for(var i=0; i < oListbox.options.length; i++) {
		oListbox.options[i].selected = true;
	}
}

function SetupJSCalendar(Calendar, inputField, triggerButton, yearRange) {
	Calendar.setup({
		inputField: inputField,
		button: triggerButton,
		ifFormat: "%m/%e/%Y",
		daFormat: "%A, %B %d, %Y",
		align: "Br",
		range: yearRange.split(","),
		weekNumbers: false,
		cache: true
	});
}

function doFade(id, opacStart, opacEnd, millisec, delayBeforeFade) {
	var speed = Math.round(millisec / 100); 
	var timer = 0; 
	
	if (delayBeforeFade > 0) {
		setTimeout('doFade(\'' + id + '\', ' + opacStart + ', ' + opacEnd + ', ' + millisec + ', 0);', delayBeforeFade);
		return;
	}
	
	var i;
	
	if (opacStart > opacEnd) {
		//Fade out
		for (i = opacStart; i >= opacEnd; i--) { 
			setTimeout('changeOpac(\'' + id + '\', ' + i + ', true)', (timer * speed)); 
			timer++; 
		} 
	} else if (opacStart < opacEnd) { 
		//Fade in
		for(i = opacStart; i <= opacEnd; i++) { 
			setTimeout('changeOpac(\'' + id + '\', ' + i + ', true)', (timer * speed)); 
			timer++; 
		} 
	}
}

//change the opacity for different browsers 
function changeOpac(id, opacity, hideWhenZero) { 
	var objectStyle = document.getElementById(id).style;
	
	objectStyle.opacity = (opacity / 100); 
	objectStyle.MozOpacity = (opacity / 100); 
	objectStyle.KhtmlOpacity = (opacity / 100); 
	objectStyle.filter = "alpha(opacity=" + opacity + ")";
	
	if (hideWhenZero === true && opacity === 0) {
		objectStyle.display = 'none';
	}
}

function getSelectValue(id) {
	var oSelect = document.getElementById(id);
	
	if (oSelect) {
		return oSelect.options[oSelect.selectedIndex].value;
	}
}

function getXMLParser(xmlSource) {
	var doc;
	
	if (window.ActiveXObject) {
		// code for IE
		doc = new ActiveXObject("Microsoft.XMLDOM");
		doc.async = "false";
		doc.loadXML(xmlSource);
	} else {
		// code for Mozilla, Firefox, Opera, etc.
		var parser = new DOMParser();
		doc = parser.parseFromString(xmlSource, "text/xml");
	}
	
	return doc;
}

function reloadCaptcha(root) {
	var captchaImage = document.getElementById('captcha');
	var captchaInput = document.getElementById('captchaCode');
	
	captchaImage.src = root + 'inc/securimage/show.php?t=' + Math.random();
	captchaInput.value = '';
	captchaInput.focus();
	
	return false;
}

function getElement(e, mouseEventType) {
	if (!e) {
		e = window.event;
	}
	
	if (!e) {
		return null;
	}
	
	if (mouseEventType === 'onmouseover') {
		//Returns the element the mouse came FROM
		return e.fromElement || e.relatedTarget;  //IE || Other browsers
	} else if (mouseEventType === 'onmouseout') {
		//Returns the element is going TO
		return e.toElement || e.relatedTarget;  //IE || Other browsers
	}
}

//Clears jQuery animation queue for an object
function jqClearQueue(obj) {
	$(obj).stop({clearQueue: true});
}

function stopBubble(event) {
	event.cancelBubble = true;
	
	if (event.stopPropagation) {
		event.stopPropagation();
	}
}

//jQuery helper function to define & display Dialog with dynamic height based on content
function jqDefineDialog(dialogId, dialogTitle, dialogWidth, dialogHeight, dialogResizable, dialogModal) {
	var dialogMinHeight = 150;
	
	var divDialog = document.getElementById(dialogId);
	
	if (!divDialog) {
		return;
	}
	
	$(divDialog).dialog("close");
	
	if (dialogHeight > dialogMinHeight) {
		dialogMinHeight = dialogHeight;
	} else if (dialogHeight < dialogMinHeight) {
		dialogHeight = dialogMinHeight;
	}
	
	if (dialogTitle === '') {
		dialogTitle = 'Team Cowboy';
	}
	
	dialogTitle = '<img src="' + GL_SITE_ROOT + 'images/icons/tcDialogEmblem.gif" alt="" width="19" height="19" border="0" class="valign"> ' + dialogTitle;
	
	$(divDialog).dialog({ 
	    autoOpen: false,
		draggable: true,
		position: "center",
		width: dialogWidth,
		minWidth: dialogWidth,
		height: dialogHeight,
		minHeight: dialogMinHeight,
		title: dialogTitle,
		resizable: dialogResizable,
		modal: dialogModal,
		overlay: { 
	        opacity: 0.08, 
	        background: "black" 
	    } 
	});
	
	$(divDialog).dialog("open");
}

function jqShowDialog(dialogId, dialogTitle, dialogWidth, dialogResizable, dialogModal) {
	var dialogHeight, wrapperHeight;
	
	jqDefineDialog(dialogId, '', 400, 0, true);
	
	var divContentWrapper = document.getElementById(dialogId + '_content');
	
	if (!divContentWrapper) {
		return;
	}
	
	wrapperHeight = $(divContentWrapper).height();
	
	if (isNaN(wrapperHeight)) {
		dialogHeight = 200;
	} else {
		dialogHeight = wrapperHeight + 53;
	}
	
	jqDefineDialog(dialogId, dialogTitle, dialogWidth, dialogHeight, dialogResizable, dialogModal);
}

function jqHideDialog(dialogId) {
	var divDialog = document.getElementById(dialogId);
		
	if (!divDialog) {
		return;
	}
		
	$(divDialog).dialog("close");
}

//Just calls display() to refresh the dialog size
function refreshDialog(contentDivId, resetPosition) {
	var oDialog = eval('dialog_' + contentDivId);
	
	if (oDialog) {
		if (oDialog.isVisible == true) {
			oDialog.resetPosition = resetPosition;
			//oDialog.setAutoCenter(autoCenter);
			oDialog.display();
			oDialog.adjustPosition();
		}
	}
}

function showDialog(contentDivId, options) {
	//Get context to div and the associated dialog object
	var oDiv = document.getElementById('dialog_' + contentDivId + '_wrapper');
	var oDialog = eval('dialog_' + contentDivId);
	
	//Define option variables & defaults
	var option_width = 400;
	var option_height = null;
	var option_autoCenter = true;
	var option_top = null;
	var option_left = null;
	var option_borderStyle = 'border';
	var option_borderSize = 9;
	var option_borderOpacity = 0.4;
	var option_borderVisible = true;
	var option_modal = true;
	var option_draggable = true;
	var option_fadeOut = true;
	
	//Parse options
	var optionsArray = options.split(",");
	var tempOption;
	
	for(var i=0; i < optionsArray.length; i++) {
		tempOption = trim(optionsArray[i]).split('=');
		
		eval('option_' + trim(tempOption[0]) + ' = ' + trim(tempOption[1]) + ';');
	}
	
	//Turn autoCenter off if a top or left is provided
	var setPosition = false;
	
	if (option_top !== null || option_left !== null) {
		option_autoCenter = false;
		setPosition = true;
	}
	
	if (oDialog && oDiv) {
		oDialog.setDivId('dialog_' + contentDivId + '_wrapper');
		oDialog.setSize(option_width, option_height);
		if (setPosition === true) {
			oDialog.setPosition(option_top, option_left);
		}
		oDialog.setBorderStyle(option_borderStyle, option_borderSize, option_borderOpacity, option_borderVisible);
		oDialog.setIsModal(option_modal);
		oDialog.autoCenter = option_autoCenter;
		oDialog.resetPosition = true;
		oDialog.display();
		
		$(document).ready(function () {
			//Start by un-binding the event. This avoids multiple instances of the event
			//from getting bound to our title bar
			$('#dialog_' + contentDivId + '_titleBar').unbind("dblclick");
			
			$('#dialog_' + contentDivId + '_titleBar').dblclick(function() {
				var contentDisplay = $('#dialog_' + contentDivId + '_content').css("display");
				
				//use fade (scrollup/down causes display issues in IE)
				if (contentDisplay === 'block') {
					$('#dialog_' + contentDivId + '_content').fadeOut("fast", function() { refreshDialog(contentDivId, false); });
				} else {
					$('#dialog_' + contentDivId + '_content').fadeIn("fast", function() { refreshDialog(contentDivId, false); });
				}
			});
		});
		
		//Make it draggable (jquery)
		if (option_draggable === true) {
			$(document).ready(function () {
				//Remove draggable first, otherwise it gets assigned twice and events are bound multiple times
				$(oDiv).draggable("destroy");
				
				$("#dialog_" + contentDivId + "_titleBar").css("cursor", "move");
				$(oDiv).draggable({
					cancel: "#dialog_" + contentDivId + "_content",
					opacity: 1.00,
					delay: 0,
					start: function() { oDialog.startDrag(); },
					stop: function() { oDialog.endDrag(); }
				});
			});
		}
	}
}

function closeDialog(contentDivId) {
	var oDialog = eval('dialog_' + contentDivId);
	
	if (oDialog) {
		oDialog.close();
	}
}

function setupTeamMenu() {
	//Setup animation for switch teams menu
	//Hover on method is setting width of container to the content width to fix display glitch with IE
	$(document).ready(function () {
		$(".st_menu").click(function() { $(".st_items").slideToggle("fast"); });

		var hoverConfig = {
			sensitivity: 7,
			interval: 125,
			over: function() { $(".st_items").slideDown("fast", function() { jqClearQueue($(this)); }); },
			timeout: 0,
			out: function() { return; $(".st_items").slideUp("fast"); }
		};
		
		var hoverConfig2 = {
			sensitivity: 7,
			interval: 125,
			over: function() { return; },
			timeout: 0,
			out: function() { $(".st_items").slideUp("fast"); }
		};
		
		$(".st_menu").hoverIntent(hoverConfig);
		$(".st_container").hoverIntent(hoverConfig2);
		//$(".st_item_content").click(function() { $(".st_items").slideUp("fast"); });
		$(".st_item_container").click(function(e) {
			var a = $(e.target).find(".st_item_link");
			
			if (a) {
				a.click();
				$(".st_items").slideUp("fast");
			}
		});
	});
}

function loadGMap(mapId, locationName, locationAddressBare, locationAddressEncoded, locationCity, dialogId) {
	var mapDiv = document.getElementById(mapId);
	var oMap;
	
	$(document).ready(function () {
		if (mapDiv && GBrowserIsCompatible()) {
			oMap = new GMap2(mapDiv);
			
			var markerHtml = '<div style="white-space: normal;"><h3>' + locationName + '</h3><a href="http://maps.google.com/maps?z=13&saddr=&daddr=' + locationAddressEncoded + '" target="_blank"><b>Get directions/view larger map</b></a> <img src="' + GL_SITE_ROOT + 'images/icons/external.png" alt="" width="10" height="10" border="0" class="valign"></div>';
			
			var geocoder = new GClientGeocoder();
			geocoder.getLatLng(locationAddressBare, function(point) { 
					if (point === null) {
						//Set default center of map using city/state
						geocoder.getLatLng(locationCity, function(point) { 
								if (point === null) {
									
								} else {
									oMap.setCenter(point, 13);
								}
						});
					} else {
						oMap.setCenter(point, 13);
						var marker = new GMarker(point);
						oMap.addOverlay(marker);
						//marker.openInfoWindowHtml(markerHtml);
						
						//onclick for marker
						GEvent.addListener(marker, "click", function() {
							marker.openInfoWindowHtml(markerHtml);
						});
					}
			});

			oMap.addControl(new GSmallMapControl());
			oMap.addControl(new GMapTypeControl());
			
			//Hide button & show map
			//var mapButton = document.getElementById(mapId + '_button');
			//$(mapButton).slideUp("fast");
			//$(mapDiv).slideDown("fast", function() { refreshDialog(dialogId); } );
		}
	});
}

function setOnBeforeUnloadEvent(msg) {
	window.onbeforeunload = function () {
		return msg;
	}
}

function clearOnBeforeUnloadEvent() {
	window.onbeforeunload = function () {
		
	}
}

function jqToggleCheckboxes(className, action) {
	$(document).ready(function() {
		if (action == "check") {
			$("." + className).attr("checked", "true");
		} else {
			$("." + className).attr("checked", "");
		}
	});
}

/**
 * Shorthand function to escape strings in jScript for use in URLs. Native escape() 
 * function does not escape plus signs (and possibly other things) but the 
 * encodeURIComponent() function does.
 *
 * @param string The string that needs to be encoded.
 *
 * @return string The encoded string, ready for use in a URL
 */
function jsEscape(string) {
	return encodeURIComponent(string);
}

function switchTournament() {
	var tournamentId = $("#tournamentId").val();
	
	if (tournamentId == '') {
		return;
	}
	
	var url = GL_SITE_ROOT + 'schedule/?tournamentId=';
	window.location = url + tournamentId;
}

function viewScheduleByDate() {
	var scheduleDate = $("#scheduleDate").val();
	
	if (scheduleDate == '') {
		return;
	}
	
	var url = GL_SITE_ROOT + 'schedule/dates/';
	window.location = url + scheduleDate;
}

function viewScheduleByTeam(dropdownId) {
	var scheduleTeam = $("#" + dropdownId).val();
	
	if (scheduleTeam == '') {
		return;
	}
	
	var url = GL_SITE_ROOT + 'schedule/teams/';
	window.location = url + scheduleTeam;
}

function saveEventLineItem(eventId) {
	//Get values
	var team1score = $.trim($("#eventId_" + eventId + "_team1score").val());
	var team2score = $.trim($("#eventId_" + eventId + "_team2score").val());
	var comments = $.trim($("#eventId_" + eventId + "_comments").val());
	
	if ((team1score == "" && team2score != "") || (team2score == "" && team1score != "")) {
		alert("Please enter scores for both teams.");
		return false;
	}
	
	//Build redirect URL to do save
	var url = GL_SITE_ROOT + "saveEvent.php?eventId=" + jsEscape(eventId) + 
		"&team1score=" + jsEscape(team1score) + 
		"&team2score=" + jsEscape(team2score) + 
		"&comments=" + jsEscape(comments) + 
		"&redirectUrl=" + jsEscape(currentPage);
		
	if (confirm("Are you sure you want to save this info?")) {
		//Reload page
		window.location = url;
	} else {
		return;
	}
}