//google analytics id
_uacct = "UA-486365-1";

function onLoad() {
  window.onresize = onResize;
  window.onscroll = onScroll;
  onResize();

  if (window.oobInit) {
    window.oobInit();
  }
}

function onResize() {
  resizeCoolWin();
  if (window.pageResize) {
    window.pageResize();
  }
}

function onScroll() {
  resizeCoolWin();
  if (window.pageScroll) {
    window.pageScroll();
  }
}

var coolWinOpen = false;
var coolWinSize = null;
var coolWinActivate = false;
var coolWinParameters = null;

var oldCoolWin = new Array();

function openCoolWin(url, w, h, waitForActivate, hideClose) {
  var bkg = Styles.getElement("coolWinBackground");
  var win = Styles.getElement("coolWinBox");
  var winClose = Styles.getElement("coolWinBoxClose");
  var loading = Styles.getElement("coolWinLoading");

	if (coolWinOpen) {
		oldCoolWin.push({"title":Styles.getElement("coolWinTitle").innerHTML, 
										 "content":Styles.getElement("coolWinContent").innerHTML, 
										 "close":Styles.setVisible(winClose), 
										 "control":Styles.getElement("coolWinControl").innerHTML, 
										 "menu":Styles.getElement("coolWinMenu").innerHTML, 
										 "size":coolWinSize});
	}

  Styles.setVisible(bkg, true);
  Styles.setVisible(win, true);
  if (hideClose) {
	  Styles.setVisible(winClose, false);
	} else {
	  Styles.setVisible(winClose, true);
	}
  Styles.setVisible(loading, true);
  Styles.setVisible("coolWinControl", false);
  Styles.setVisible("coolWinMenu", false);
  
  if (Styles.getElement("adDiv")) {
	  Styles.setVisible("adDiv", false);
	}
  if (Styles.getElement("adRectDiv")) {
	  Styles.setVisible("adRectDiv", false);
	}

  coolWinParameters = new Array();
  for (var i = 4; i < arguments.length; i++) {
    coolWinParameters.push(arguments[i]);
  }

  if (!w) { w = 400; }
  if (!h) { h = 400; }
  coolWinSize = {w:w, h:h};
  if (waitForActivate) {
    coolWinActivate = true;
  } else {
    coolWinActivate = false;
  }
  
  winClose.onclick = closeCoolWin;
  win.style.width = w+"px";
  win.style.height = h+"px";
  loading.style.width = win.style.width;
  loading.style.height = (h-42)+"px";

	if (SystemConfig.isIE6()) {
		hideAllSelects();
	}
  resetCoolWinContentSize();
  
  coolWinOpen = true;
  resizeCoolWin();

	if (url) {
	  loadCoolWinURL(url);
	}
}

function showAllSelects() {
  var e = document.getElementsByTagName("select");

	for (var i = 0; i < e.length; i++) {
		if (e[i].className != "searchHeaderSelect") {
			Styles.setVisible(e[i], true);
		}
	}
}

function hideAllSelects() {
  var e = document.getElementsByTagName("select");

	for (var i = 0; i < e.length; i++) {
		if (e[i].className != "searchHeaderSelect") {
			Styles.setVisible(e[i], false);
		}
	}
}

function activateCoolWin() {
  Styles.setVisible("coolWinLoading", false);  
}

function closeCoolWin() {
  coolWinOpen = false;

  Styles.setVisible("coolWinBackground", false);
  Styles.setVisible("coolWinBox", false);
  Styles.setVisible("coolWinBoxClose", false);
  Styles.setVisible("coolWinLoading", false);

  if (Styles.getElement("adDiv")) {
	  Styles.setVisible("adDiv", false);
	}
  if (Styles.getElement("adRectDiv")) {
	  Styles.setVisible("adRectDiv", false);
	}

	if (SystemConfig.isIE6()) {
		showAllSelects();
	}
	
	openPrevCoolWin();
}

function resetCoolWinContentSize() {
  var content = Styles.getElement("coolWinContent");
  var b = 42;//title plus border
  if (Styles.getVisible("coolWinControl")) {
    b += 41;
  }
  if (Styles.getVisible("coolWinMenu")) {
    b += 31;
  }
  content.style.height = (coolWinSize.h - b) + "px";
}

function setCoolWinTitle(str) {
  Styles.getElement("coolWinTitle").innerHTML = str;
}

function setCoolWinControls(str) {
  var controls = Styles.getElement("coolWinControl");
  controls.innerHTML = str;
  
  var toggled = !Styles.getVisible(controls);
  Styles.setVisible(controls, true);
  if (toggled) {
    resetCoolWinContentSize();
  }
}

function setCoolWinMenu(str) {
  var menu = Styles.getElement("coolWinMenu");
  menu.innerHTML = str;
  
  var toggled = !Styles.getVisible(menu);
  Styles.setVisible(menu, true);
  if (toggled) {
    resetCoolWinContentSize();
  }
}

function resizeCoolWin() {
  var bkg = Styles.getElement("coolWinBackground");
  bkg.style.top = "0px";
  bkg.style.left = "0px";
  if (coolWinOpen) {
    var win = Styles.getElement("coolWinBox");
    var winClose = Styles.getElement("coolWinBoxClose");
    var loading = Styles.getElement("coolWinLoading");
    
    var w = document.body.clientWidth;
    var h = getWinHeight();
    
    var scrolledV = 0;
    var scrolledH = getHScrollPos();
    if (h > coolWinSize.h) {
	    scrolledV = getVScrollPos();
	  }
    var scrolledH = getHScrollPos();
    var x = Math.round(((w/2) - (coolWinSize.w/2)) + scrolledH);
    var y = Math.round(((h/2) - (coolWinSize.h/2)) + scrolledV);

    if (x < 0) {
      x = 0;
    }
    if (y < 0) {
      y = 0;
    }

    win.style.left = x+"px";
    win.style.top = y+"px";

    loading.style.left = x+1+"px";
    loading.style.top = y+42+"px";
    
    winClose.style.left = (x+coolWinSize.w-25)+"px";
    winClose.style.top = y+12+"px";

    bkg.style.top = scrolledV+"px";
    bkg.style.left = scrolledH+"px";
    
//    if (document.body.clientHeight > h) {
//    	alert("using this height");
//      bkg.style.height = document.body.clientHeight+"px";
//    } else {
//      bkg.style.height = h+"px";
//    }
  }
}

function loadCoolWinURL(url) {
  try {
    var http = getHTTPRequest();

    if (url.indexOf("?") == -1) {
      url += "?bn="+window.buildNumber;
    } else {
      url += "&bn="+window.buildNumber;
    }
    http.open("GET", url, true);

    http.onreadystatechange = function() {
      if(http.readyState == 4) {
        http.onreadystatechange = function () {};
        handleCoolWinData(http);
      }
    };
    
    http.send(null);
  } catch(e) {
    alert(e.message);
  }
}

function handleCoolWinData(http) {
  try {
    if (http.status == "200") {
      data = http.responseText;
      var win = Styles.getElement("coolWinContent");
      
      win.innerHTML = "";
      var results = seperateScripts(data)
      win.innerHTML = results[0];
      
      var scripts = results[1];
      if (scripts != null) {
        for (var i = 0; i < scripts.length; i++) {
          globalEval(scripts[i]);
        }
      }
      
      if (!coolWinActivate) {
        activateCoolWin();
      }
    }
  } catch(e) {
    alert(e.message);
  }  
}

function seperateScripts(str) {
	var arry = str.split(new RegExp('<script.*?>|<\/script>', 'img'));
	var scripts = new Array();
	var html = "";
	for (var i = 0; i < arry.length; i++) {
		if (arry[i] != null && arry[i].length > 0) {
			if (i % 2 == 0) {
				html += arry[i];
			} else {
				scripts.push(arry[i]);
			}
		}
	}
	return [html, scripts];
}


function getVScrollPos() {
  if (document.documentElement && document.documentElement.scrollTop) {
	  return document.documentElement.scrollTop;
  } else if (document.body) {
	  return document.body.scrollTop
  } else {
    return window.pageYOffset;
  }
}

function getHScrollPos() {
  if (document.documentElement && document.documentElement.scrollLeft) {
	  return document.documentElement.scrollLeft;
  } else if (document.body) {
	  return document.body.scrollLeft
  } else {
    return window.pageXOffset;
  }
}

function getWinHeight() {
  if (window.innerHeight) {
    return window.innerHeight;
  } else if (document.documentElement && document.documentElement.clientHeight) {
	  return document.documentElement.clientHeight;
  } else if (document.body) {
	  return document.body.clientHeight;
  }
  return 0;
}

onLoginRefresh = false;
function openLogin(refresh) {
  if (refresh) {
    onLoginRefresh = true;
  }
  openCoolWin("/golfers/login.html", 300, 320);
}

function starMouseOver(rateId, clubId, starId) {
  var color = "blue";
  
  for (var i = 0; i < 5; i++) {
    if (i > starId) {
      color = "grey";
    }
    Styles.changeImage("star_"+i+"_"+rateId, "/images/icons/16x16/w_star_"+color+".png");
  }
}

function starMouseOut(rateId, clubId, starId) {
  var rating = parseInt(Styles.getElement("rating_" + rateId).value);

  var color = "yellow";
  if (rating < 0) {
    color = "blue";
    rating = rating * -1;
  }
  
  for (var i = 0; i < 5; i++) {
    if (i >= rating) {
      color = "grey";
    }
    Styles.changeImage("star_"+i+"_"+rateId, "/images/icons/16x16/w_star_"+color+".png");
  }
}

function starClick(rateId, clubId, starId, rType, objType) {
  var rating = starId + 1;
  try {
    if (objType && objType == 2) {
      authenticatedJSONRequest("equipment.rateEquipment", starClickSaved, clubId, rType, rating);
    } else {
      authenticatedJSONRequest("courses.rateCourse", starClickSaved, clubId, rType, rating);
    }
  } catch (e) {}
  Styles.getElement("rating_" + rateId).value = -1 * rating;
}

function starClickSaved() {
  if (!window.authenticated) {
    window.location.reload();
  }
}

var queuedRequest = null;
function authenticatedJSONRequest() {
  if (!window.authenticated) {
    openLogin();
    queuedRequest = arguments;
    return;
  }
  try {
    var client = getJSONRPCClient();
    client.callRemote.apply(client, arguments);
  } catch (e) {
    if (e.code == 1) {
      openLogin();
      queuedRequest = arguments;
    } else {
      throw e;
    }
  }
}

function checkEnter(e) {
  var characterCode = null;
  if (e && e.which) {
    characterCode = e.which;
  } else{
    characterCode = e.keyCode
  }
  if (characterCode == 13){
    return true; 
  }
  return false;
}

var currentSubMenu = null;
var currentMenu = null;
var subMenuTimeout = 250;
var subMenuInterval = null;

function displaySubMenu(i, event) {

  if (window.event) window.event.cancelBubble = true;
  else if (event.stopPropagation) event.stopPropagation();
  
  clearHideSubMenu();
  
  if (currentSubMenu != null && currentSubMenu != i) {
    justHideSubMenu(currentSubMenu);
  }
  currentSubMenu = i;
  var pos = Styles.findPosition('menu_'+i);

  var sub = Styles.getElement('submenu_'+i);
  Styles.setVisible(sub, true);
  if (SystemConfig.isIE()) {
	  sub.style.top = (pos.y+31)+'px';
	} else {
	  sub.style.top = (pos.y+30)+'px';
	}
  sub.style.left = (pos.x)+'px';

  Styles.getElement('menu_b_'+i).className = "menu menuover";
}

function hideSubMenu(i, event) {
  var sub = Styles.getElement('submenu_'+i);
  var men = Styles.getElement('menu_b_'+i);

  if (Styles.checkMouseLeave(men, event) &&
      Styles.checkMouseLeave(sub, event)) {
    subMenuInterval = setTimeout("justHideSubMenu()", subMenuTimeout);
  }
}

function justHideSubMenu(i) {
  if (i == null) {
    var i = currentSubMenu;
  }
  if (i == null) {
    return;
  }
  Styles.setVisible('submenu_'+i, false);
  if (i == currentMenu) {
	  Styles.getElement('menu_b_'+i).className = "menu currentmenu";
	} else {
	  Styles.getElement('menu_b_'+i).className = "menu";
	}
  currentSubMenu = null;
}


function clearHideSubMenu() {
  if (subMenuInterval != null) {
    clearTimeout(subMenuInterval);
  }
}

var FIRST_FOCUS = [];
function onFirstFocus(el) {
  for (var i = 0; i < FIRST_FOCUS.length; i++) {
    if (FIRST_FOCUS[i] == el) {
      return;
    }
  }
  el.value = "";
  el.style.color = "#333333";
  FIRST_FOCUS.push(el);
}


function onSearchKeyword() {
  var form = document.forms.searchKeywordForm.elements;

  var q = form.q.value;
  
  if (!q) {
    alert('You must provide a keyword.');
    return false;
  }
  
  form.q.value = q;
  
  var t = form.t.options[form.t.selectedIndex].value;
  if (t == "2") {
    document.forms.searchKeywordForm.action = "/courses/finder/index.php";
  } else if (t == "1") {
    document.forms.searchKeywordForm.action = "/golfers/search.php";
    form.n.value = q;
  } else if (t == "3") {
    document.forms.searchKeywordForm.action = "/equipment/";
    form.k.value = q;
  } else if (t == "4") {
    document.forms.searchKeywordForm.action = "/groups/search.php";
    form.k.value = q;
  }
  
  return true;
}

function addShortStates(el, st) {
  var i = el.options.length;
  el.options.length = el.options.length + 63;
  el.options[i++] = new Option("AL", "AL"); 
  el.options[i++] = new Option("AB", "AB"); 
  el.options[i++] = new Option("AK", "AK"); 
  el.options[i++] = new Option("AZ", "AZ"); 
  el.options[i++] = new Option("AR", "AR"); 
  el.options[i++] = new Option("BC", "BC"); 
  el.options[i++] = new Option("CA", "CA"); 
  el.options[i++] = new Option("CO", "CO"); 
  el.options[i++] = new Option("CT", "CT"); 
  el.options[i++] = new Option("DE", "DE"); 
  el.options[i++] = new Option("DC", "DC"); 
  el.options[i++] = new Option("FL", "FL"); 
  el.options[i++] = new Option("GA", "GA"); 
  el.options[i++] = new Option("HI", "HI"); 
  el.options[i++] = new Option("ID", "ID"); 
  el.options[i++] = new Option("IL", "IL"); 
  el.options[i++] = new Option("IN", "IN"); 
  el.options[i++] = new Option("IA", "IA"); 
  el.options[i++] = new Option("KS", "KS"); 
  el.options[i++] = new Option("KY", "KY"); 
  el.options[i++] = new Option("LA", "LA"); 
  el.options[i++] = new Option("MB", "MB"); 
  el.options[i++] = new Option("ME", "ME"); 
  el.options[i++] = new Option("MD", "MD"); 
  el.options[i++] = new Option("MA", "MA"); 
  el.options[i++] = new Option("MI", "MI"); 
  el.options[i++] = new Option("MN", "MN"); 
  el.options[i++] = new Option("MS", "MS"); 
  el.options[i++] = new Option("MO", "MO"); 
  el.options[i++] = new Option("MT", "MT"); 
  el.options[i++] = new Option("NB", "NB"); 
  el.options[i++] = new Option("NE", "NE"); 
  el.options[i++] = new Option("NV", "NV"); 
  el.options[i++] = new Option("NH", "NH"); 
  el.options[i++] = new Option("NJ", "NJ"); 
  el.options[i++] = new Option("NL", "NL"); 
  el.options[i++] = new Option("NM", "NM"); 
  el.options[i++] = new Option("NT", "NT"); 
  el.options[i++] = new Option("NU", "NU"); 
  el.options[i++] = new Option("NS", "NS"); 
  el.options[i++] = new Option("NY", "NY"); 
  el.options[i++] = new Option("NC", "NC"); 
  el.options[i++] = new Option("ND", "ND"); 
  el.options[i++] = new Option("OH", "OH"); 
  el.options[i++] = new Option("OK", "OK"); 
  el.options[i++] = new Option("ON", "ON"); 
  el.options[i++] = new Option("OR", "OR"); 
  el.options[i++] = new Option("PA", "PA"); 
  el.options[i++] = new Option("PE", "PE"); 
  el.options[i++] = new Option("QC", "QC"); 
  el.options[i++] = new Option("RI", "RI"); 
  el.options[i++] = new Option("SC", "SC"); 
  el.options[i++] = new Option("SK", "SK"); 
  el.options[i++] = new Option("SD", "SD"); 
  el.options[i++] = new Option("TN", "TN"); 
  el.options[i++] = new Option("TX", "TX"); 
  el.options[i++] = new Option("UT", "UT"); 
  el.options[i++] = new Option("VT", "VT"); 
  el.options[i++] = new Option("VA", "VA"); 
  el.options[i++] = new Option("WA", "WA"); 
  el.options[i++] = new Option("WV", "WV"); 
  el.options[i++] = new Option("WI", "WI"); 
  el.options[i++] = new Option("WY", "WY");
  el.options[i++] = new Option("YT", "YT");
}


function refreshPage() {
  var r = "ran="+Math.floor(Math.random()*10000000);
  if (window.location.href.indexOf("?") != -1) {
    r = "&"+r;
  } else {
    r = "?"+r;
  }
  window.location.href = window.location.href+r;
}


function getQueryString() {
    var urlStr = document.location.href;
    var i = urlStr.indexOf("?");
    if (i != -1) {
        return urlStr.substring(i, urlStr.length);
    }
    
    return null;
}

function getParameter(name, defaultValue) {
    if (defaultValue == null) {
        defaultValue = null;
    }
    var url = document.location.href;
    var i = url.indexOf(name + "=");
    if (i != -1) {
        var valuestart = i+name.length+1;
        var valueend = url.length;
        i = url.indexOf("&", valuestart)
        if (i != -1) {
            valueend = i;
        }
        return unescape(url.substring(valuestart, valueend));
    }
    return defaultValue;
}

function getCookie( name ) {
        var start = document.cookie.indexOf( name + "=" );
        var len = start + name.length + 1;
        if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
                return null;
        }
        if ( start == -1 ) return null;
        var end = document.cookie.indexOf( ";", len );
        if ( end == -1 ) end = document.cookie.length;
        return unescape( document.cookie.substring( len, end ) );
}
function setCookie( name, value, expires, path, domain, secure ) {
        var today = new Date();
        today.setTime( today.getTime() );
        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() : "" ) + //expires.toGMTString()
                ( ( path ) ? ";path=" + path : "" ) +
                ( ( domain ) ? ";domain=" + domain : "" ) +
                ( ( secure ) ? ";secure" : "" );
}
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";
}

var coolWaitTime = 0;
function openCoolWait(title, message) {
	if (title == null) {
		title = "One Moment";
	}
	if (message == null) {
		message = "Just a few more seconds...";
	}
	openCoolWin(null, 350, 175, true, false);
  var win = Styles.getElement("coolWinContent");
  win.innerHTML = '<div style="margin:20px;text-align:center;" class="smallText">'+message+'<br/><br/><img src="/images/icons/24x24/w_recycle.png"/></div>';
  setCoolWinTitle(title);

	coolWaitTime = (new Date()).getTime();
	activateCoolWin();
}

function closeCoolWait(ms) {
	var t = (new Date()).getTime() - coolWaitTime;
	if (t >= ms) {
		closeCoolWin();
	} else {
		setTimeout("closeCoolWin()", ms-t);
	}
}

var coolInfoCallback = null;
function openCoolInfo(title, message, callback) {
	coolInfoCallback = callback;
	openCoolWin(null, 350, 175, true, false);
  var win = Styles.getElement("coolWinContent");
  win.innerHTML = '<div style="margin:20px;text-align:center;" class="smallText">'+message+'</div>';
  setCoolWinTitle(title);
  setCoolWinControls("<"+"input id='loginButton' type='submit' value='OK' onclick='closeCoolInfo();'/>");
	activateCoolWin();
}

function closeCoolInfo() {
	closeCoolWin();
	if (coolInfoCallback) {
		coolInfoCallback.apply(this.window);
	}
}

function openPrevCoolWin() {
	if (oldCoolWin.length > 0) {
		var obj = oldCoolWin.pop();
		openCoolWin(null, obj.size.w, obj.size.h, true, obj.close);
	  var win = Styles.getElement("coolWinContent");
	  win.innerHTML = obj.content;
	  setCoolWinTitle(obj.title);
	  if (obj.control != null) {
	  	setCoolWinControls(obj.control);
	  }
	  if (obj.menu != null) {
	  	setCoolWinMenu(obj.menu);
	  }
		activateCoolWin();
	}
}

String.prototype._$$split = String.prototype._$$split || String.prototype.split;
String.prototype.split = function (s /* separator */, limit) {
	// if separator is not a regex, use the native split method
	if (!(s instanceof RegExp))
		return String.prototype._$$split.apply(this, arguments);

	var	flags = (s.global ? "g" : "") + (s.ignoreCase ? "i" : "") + (s.multiline ? "m" : ""),
		s2 = new RegExp("^" + s.source + "$", flags),
		output = [],
		origLastIndex = s.lastIndex,
		lastLastIndex = 0,
		i = 0, match, lastLength;

	/* behavior for limit: if it's...
	- undefined: no limit
	- NaN or zero: return an empty array
	- a positive number: use limit after dropping any decimal
	- a negative number: no limit
	- other: type-convert, then use the above rules
	*/
	if (limit === undefined || +limit < 0) {
		limit = false;
	} else {
		limit = Math.floor(+limit);
		if (!limit)
			return [];
	}

	if (s.global)
		s.lastIndex = 0;
	else
		s = new RegExp(s.source, "g" + flags);

	while ((!limit || i++ <= limit) && (match = s.exec(this))) {
		var emptyMatch = !match[0].length;

		// Fix IE's infinite-loop-resistant but incorrect lastIndex
		if (emptyMatch && s.lastIndex > match.index)
			s.lastIndex--;

		if (s.lastIndex > lastLastIndex) {
			// Fix browsers whose exec methods don't consistently return undefined for non-participating capturing groups
			if (match.length > 1) {
				match[0].replace(s2, function () {
					for (var j = 1; j < arguments.length - 2; j++) {
						if (arguments[j] === undefined)
							match[j] = undefined;
					}
				});
			}

			output = output.concat(this.slice(lastLastIndex, match.index));
			if (1 < match.length && match.index < this.length)
				output = output.concat(match.slice(1));
			lastLength = match[0].length; // only needed if s.lastIndex === this.length
			lastLastIndex = s.lastIndex;
		}

		if (emptyMatch)
			s.lastIndex++; // avoid an infinite loop
	}

	// since this uses test(), output must be generated before restoring lastIndex
	output = lastLastIndex === this.length ?
		(s.test("") && !lastLength ? output : output.concat("")) :
		(limit ? output : output.concat(this.slice(lastLastIndex)));
	s.lastIndex = origLastIndex; // only needed if s.global, else we're working with a copy of the regex
	return output;
};