/**
 *
 * global.js
 *
 */

try {
  document.execCommand('BackgroundImageCache', false, true);
} catch(e) {}

/* Code forking variables */
var browser_isopera = typeof window.opera != 'undefined';
var browser_isie = typeof document.all != 'undefined'
   	&& !browser_isopera && navigator.vendor != 'KDE';
var browser_issafari = navigator.vendor == 'Apple Computer, Inc.';

/* Universal information message when an error encountered while processing XML */
var global404ErrorMessage = "An error has occurred while trying to locate this data. Please refresh your browser to try locating the data again.";

/* globally assume PGA tour until different tour selected; use this var to store that selection */
var tournCode = "r";

var tcdacmd="dt";

/* Process initialize function on load */
Event.observe (window, "load", initialize);

/* Run this function on load globally; Test for conditions to drive functionality */
function initialize() {
/* check for tour selection var (TID) in url */
	var t = queryString("TID") ;
	if (t != "false") tournCode = t.toLowerCase();

/* use tournCode value to highlight selected tour in sub menu(s) */
	var tourMenu = $A(document.getElementsByClassName("lboard-nav"));
	if (t != "false" && tourMenu && tourMenu.length) {
		tourMenu.each ( function(menu) {
			var LIs = $A(menu.getElementsByTagName("li"))
			if (LIs && LIs.length) {
				LIs.each ( function(li) {
					Element.removeClassName(li, "selected");
					var link = li.getElementsByTagName("a")[0];
					if(link) {
						var href = link.href;
						href = href.substr(href.indexOf("?"));
						if (href && href.indexOf("#") == -1) {
							var s = new PageQuery(href).getValue("TID");
							if(s) {
								if (s.toLowerCase() == tournCode.toLowerCase()) {
									Element.addClassName(li, "selected");
								}
							}
						}
					}
				} );
			}
		} );
	}

/* Center article in-line image in 190 pixel container */
	var sidebar = $A(document.getElementsByClassName("article-sidebar"));
	if (sidebar && sidebar.length) {
		sidebar.each ( function(sb) {
			var div = sb.getElementsByTagName("div");
			if (div && div.length) {
				var container = div[0];
				var max = Element.getDimensions(container).width
				var img = $A(container.getElementsByTagName("img"));
				var link = $A(container.getElementsByTagName("a"));
				if (img && img.length && link && link.length) {
					var photo = img[0];
					var farRight = Position.positionedOffset(photo)[0] + Element.getDimensions(photo).width + 1;
					link[0].style.right = parseInt(max - farRight) + "px";
				}
			}
		} );
	}
}

/* Following two functions used to query browser url for ?var1=value1&var2=value2 */
function PageQuery(q) {
	if (q.length > 1) this.q = q.substring(1, q.length);
	else this.q = null;
	this.keyValuePairs = new Array();
	if (this.q) {
		for (var i=0; i < this.q.split("&").length; i++) {
			this.keyValuePairs[i] = this.q.split("&")[i];
		}
	}
	this.getKeyValuePairs = function() { return this.keyValuePairs; }
	this.getValue = function(s) {
		for(var j=0; j < this.keyValuePairs.length; j++) {
			if (this.keyValuePairs[j].split("=")[0] == s) return this.keyValuePairs[j].split("=")[1];
		}
		return false;
	}
	this.getParameters = function() {
		var a = new Array(this.getLength());
		for (var j=0; j < this.keyValuePairs.length; j++) {
			a[j] = this.keyValuePairs[j].split("=")[0];
		}
		return a;
	}
	this.getLength = function() { return this.keyValuePairs.length; }
}

function queryString(key) {
	var page = new PageQuery(window.location.search);
	return unescape(page.getValue(key));
}

/* Helper function to build DOM node */
function buildElem(type, className, attrs) {
	var el = document.createElement(type);
	if (className) el.className = className;
	return el;
}

/* Helper function to return string whether xml node exists with value or not */
function safeNodeValue(nodeTarget, defVal) {
	var val = "N/A";
	if (typeof defVal != typeof undefined) val = defVal;
	if (nodeTarget && nodeTarget.firstChild) {
		val = (nodeTarget.firstChild.nodeValue) ? (nodeTarget.firstChild.nodeValue) : val;
	}
	return val;
}

/* Helper function to return string whether attribute exists with value or not */
function safeAttrValue(node, attrTarget, defVal) {
	var val = "N/A";
	if (typeof defVal != typeof undefined) val = defVal;
	var test = node.getAttribute(attrTarget);
	val = (test) ? (test) : val;
	return val;
}

/* Helper function to find node with specific attribute value */
function getNodeWithAttr(pNode, nodeName, attrName, attrValue) {
	var nodes = pNode.getElementsByTagName(nodeName);
	if (nodes.length) {
		for (var i = 0; i < nodes.length; i++) {
			var n = nodes[i];
			var s = n.getAttribute(attrName);
			if (s && s == attrValue) { /*alert("Found: " + s);*/ return n; }
		}
	}
	return null;
}

/* Email to a Friend JS function */
function openEmail() {
        var pageURL   	= document.URL;
        var pageURLPre  = pageURL;
        var pageIDPre   = pageURLPre.substring(pageURLPre.lastIndexOf("/"));
        var pageIDs     = pageIDPre.split(",");
        var pageID      = pageIDs[2];

        if (pageURL.substring(pageURL.length-1)=="#") {
                pageURL = pageURL.substring(0, pageURL.length-1);
        }
        var pageTitle = self.document.title;
        if (pageTitle.indexOf('|') > 0) {
                pageTitle = pageTitle.substring(0, pageTitle.indexOf('|'));
        }
        var urlSeparate = "%3F";
        if(pageURL.indexOf("?")!=-1){
                urlSeparate = "%26"
        }
        var formURL     = "/cgi-bin/mail/mailurl2friend.cgi?path=/golf/static/email&url="  + pageURL + urlSeparate + 
"cid=staf-email-" + pageID + "&group=golf&title="+pageTitle
        showCenteredPopup('emailpop', formURL, 'scrollbars=1', 460, 470);
        return false;
}

/* Function to create a centered popup on the site */
function showCenteredPopup(name, url, features, width, height) {
        var top = (screen.height / 2) - height / 2;
        var left = (screen.width / 2) - width / 2;
		if(url.indexOf("/video/article") > -1 && url.indexOf("/mail/mailurl2friend") === -1){
			window.open(url, name);
			return
		}
        if (features == null || features == '') {
                features =" scrollbars=yes,toolbar=no,menubar=no,status=no,location=no";
        }
        window.open(url, name, features + ",top=" + top + ",left=" + left + ",width=" + width + ",height=" + height);
}

/* Function to attach popup behavior to an anchor unobtrusively */
function setAnchorPopup (anchorId, windowName, windowFeatures, windowWidth, windowHeight, openFromParent)
{
	if (!anchorId)
	{
		return false;
	}
	var anchor = document.getElementById (anchorId);
	if (!anchor || !anchor.href)
	{
		return false;
	}
	function openPopup (event)
	{
		tii_stopDefaultAction (event);
		if (!openFromParent)
		{
			showCenteredPopup (windowName, anchor.href, windowFeatures, windowWidth, windowHeight);
		}
		else
		{
			window.open (anchor.href, windowName, windowFeatures + (windowFeatures? ',' : '') + 'width=' + width + ',height=' + height);
		}
	}	
	tii_addEventHandler (anchor, 'click', function (event) { openPopup (event); }, false);
	var keyevent = browser_issafari || browser_isie ? 'keydown' : 'keypress';
	tii_addEventHandler (anchor, keyevent, function (event) { openPopup (event); }, false);
}

/* Stops the default action for the event, such as jumping to an anchor when clicking on a hyperlink */
function tii_stopDefaultAction (event)
{
	event.returnValue = false;
	if (typeof event.preventDefault != 'undefined')
	{
		event.preventDefault ();
	}
}

/* Generic show/hide for a layer */
function showHide (layername) {
        if (document.getElementById(layername).style.display == "none") {
                document.getElementById(layername).style.display = "block";
        } else {
                document.getElementById(layername).style.display = "none";
        }
}

/* Hide or show the various elements on the Equipment Finder based on selection */
function equipShowHide (stringList,thisForm) {
        var opt_layers  = new Array("shaft_type","shaft_flex","loft","subtypes","bounces","length");
        for (x = 0; x < opt_layers.length; x++) {
		 var exists = new RegExp(opt_layers[x]).test(stringList); 
	         if (exists) {
                 	document.getElementById(opt_layers[x] + "_div").style.display = "block";
		} else {
                 	document.getElementById(opt_layers[x] + "_div").style.display = "none";
			resetEquipmentForm(thisForm,opt_layers[x]);
       		} 
	}
}

/* Reset the select lists for the Equipment Finder page */
function resetEquipmentForm(f,e) {
   if ( (typeof(f)).match(/^(STRING|NUMBER)$/i) ) {
      if ( undefined != document.getElementById(f) ) {
         f = document.getElementById(f);
      } else {
         if ( document.getElementsByName &&
              undefined != document.getElementsByName(f) ) {
            f = document.getElementsByName(f)[0];
         }
      }
   }
   if (! f.getElementsByTagName) {
     return true;
   }
   var elle = f.getElementsByTagName('select');
   for (var i=0; elle != undefined && i < elle.length; i++) {
        // if our form has any selects reset 
	if ( elle[i].name == e &&
             elle[i].type.match(/^SELECT/i) ) { 
	     elle[i].selectedIndex = 0;
        }
   }
   return false;
}

/* Only submit if value is not blank */
function isListValid (val) {
        if (val != "") return true;
        return false;
}

//For DFP ad tag 
var adConfig = new TiiAdConfig("3475.golf");
adConfig.setCmSitename("cm.golf");
adConfig.setRevSciTracking(true);

function openUrlInWindow(url) {
  window.open(url);
}

function redirectToFormValue(formId, valueId) {
	window.location = document.forms[formId].elements[valueId].value;
}

function contrib_select_change(selObj) {
	var selectedValue = selObj.options[selObj.selectedIndex].value;
    if(isListValid(selectedValue)) {
    	location.href = selectedValue;
    }          
    return false;
}

//Copyright year gets updated automatically id="copyYear"
// Samuel Shin

function copyYear() { var cy = new Date(); document.getElementById("copyYear").innerHTML = cy.getFullYear(); }

if (window.addEventListener)
window.addEventListener("load", copyYear, false);
if (window.attachEvent)
window.attachEvent("onload", copyYear); 