(function($) {
	var interval = null;
	var checklist = [];

	$.elementReady = function(id, fn) {
		checklist.push({id: id, fn: fn});
		if (!interval) {interval = setInterval(check, $.elementReady.interval_ms);}
		return this;
	};
	
	// Plugin settings
	$.elementReady.interval_ms = 23; // polling interval in ms
	
	// Private function
	function check() {
		var docReady = $.isReady; // check doc ready first; thus ensure that check is made at least once _after_ doc is ready
		for (var i = checklist.length - 1; 0 <= i; --i) {
			var el = document.getElementById(checklist[i].id);
			if (el) {
				var fn = checklist[i].fn; // first remove from checklist, then call function
				checklist[i] = checklist[checklist.length - 1];
				checklist.pop();
				fn.apply(el, [$]);
			}
		} 
		if (docReady) {
			clearInterval(interval);
			interval = null;
		}
	}
})(jQuery);

/**
 * Use TIMEINC.GOLF namespace for the following See-Try-Buy module.
 * 
 * Update this manual namespacing if other namespacing functionality becomes available.
 */
var  TIMEINC = TIMEINC || {};
TIMEINC.GOLF = TIMEINC.GOLF || {};

/**
 * See-Try-Buy module 
 *
 * Implements branded footer links on See and Buy tabs
 *
 * Dependencies:
 * - jQuery for AJAX call
 */
(function(golf_ns, $, stb_module_name) {

    var tabs = 'see try buy'.split(' ');    //  See-Try-Buy Widget Tabs
        see_tab = tabs[0], 
		try_tab = tabs[1], 
		buy_tab = tabs[2],
    	stb_module_name = stb_module_name || tabs.join(''),

        // See-Try-Buy Brands
		no_brand = 0,
    	brands = {"0":{"brandname":"","code":"0","slug":""},"27":{"brandname":"TaylorMade","code":"27","slug":"taylor-made"},"47":{"brandname":"Adidas","code":"47","slug":"adidas"},"4":{"brandname":"Callaway","code":"4","slug":"callaway"},"16":{"brandname":"Nike","code":"16","slug":"nike"},"20":{"brandname":"Ping","code":"20","slug":"ping"},"29":{"brandname":"Titleist","code":"29","slug":"titleist"},"46":{"brandname":"FootJoy","code":"46","slug":"footjoy"},"6":{"brandname":"Cleveland","code":"6","slug":"cleveland"},"7":{"brandname":"Cobra","code":"7","slug":"cobra"},"13":{"brandname":"Mizuno","code":"13","slug":"mizuno"},"1":{"brandname":"Adams","code":"1","slug":"adams"},"305":{"brandname":"Bridgestone","code":"305","slug":"bridgestone"},"25":{"brandname":"Srixon","code":"25","slug":"srixon"},"31":{"brandname":"Tour Edge","code":"31","slug":"tour-edge","redirect":"touredge"},"32":{"brandname":"Wilson","code":"32","slug":"wilson"}},
        
        // See-Try-Buy Footer Labels
        labels = 'Balls Shoes Bags Apparel Accessories'.split(' '),
        
		/**
		 * brandedLink object:
		 *
		 * Encapsulates the business rules for creating components of
		 * branded or default links for the See-Try-Buy footer menu.
		 */
		brandedLink = {	
			/**
			 * The brandedLink.shop type corresponds primarily to
			 * links on the BUY-tab and points to shop.golf.com
			 */
			shop: {
				/**
				 * Get default or branded filename for this link
				 *
				 * @param {Number} brand_id The brand code number
				 * @param {Number} label_idx The footer item index
				 * @return {String} The filename string
				 */
				parseFilename: function(brand_id, label_idx) {
					var brandprefix = 'g_bid-',
					extension = '.aspx',
					filename = [];
	
					if (brand_id) {
						filename.push(brandprefix)
						filename.push(brand_id);
					} else {
						filename.push(labels[label_idx].toLowerCase());
					}
					filename.push(extension);
					return filename.join('');
				},
				/**
				 * Get default or branded path for this link
				 *
				 * @param {Number} brand_id The brand code number
				 * @param {Number} label_idx The footer item index
				 * @return {String} The path string
				 */
				parsePath: function(brand_id, label_idx) {
					var path = [];
					if (brand_id) {
						path.push(labels[label_idx].toLowerCase());
						path.push(brands[brand_id].slug + (label_idx === 0 ? 'balls' : ''));
					}
					return path.join('/');
				},
				/**
				 * Get server for this link
				 *
				 * @return {String} The server string
				 */
				server: 'shop.golf.com'
			},
			
			/**
			 * The brandedLink.browse type corresponds primarily to
			 * links on the SEE-tab and points to equipment.golf.com
			 */
			browse: {
				/**
				 * Get default or branded filename for this link
				 *
				 * @param {Number} brand_id The brand code number
				 * @param {Number} label_idx The footer item index
				 * @return {String} The filename string
				 */
				parseFilename: function(brand_id, label_idx) {
					var fileprefix = 'g_pt-',
					browseCodes = {
                        Balls: 3, Shoes: 7, Bags: 6, Apparel: undefined, Accessories: 2
                    },
					brandprefix = '_b-',
					extension = '.aspx',
					filename = [];
	
					filename.push(fileprefix);
					filename.push(browseCodes[labels[label_idx]]);
					if (brand_id) {
						filename.push(brandprefix);
						filename.push(brand_id);
					}
					filename.push(extension);
					return filename.join('');
				},
				/**
				 * Get default or branded path for this link
				 *
				 * @param {Number} brand_id The brand code number
				 * @param {Number} label_idx The footer item index
				 * @return {String} The path string
				 */
				parsePath: function(brand_id, label_idx) {
					var pathprefix = 'golf',
					brandprefix = 'men',
					path = [];
	                
	                //path.push(''); // leading slash placeholder
					path.push(pathprefix);
					path.push(labels[label_idx].toLowerCase());
					if (brand_id) {
						path.push(brandprefix);
						path.push(brands[brand_id].slug);
					}
					//path.push(''); // trailing slash placeholder
					return path.join('/');
				},
				/**
				 * Get server for this link
				 *
				 * @return {String} The server string
				 */
				server: 'equipment.golf.com'
			}
		}, // End brandedLink object
		
		/**
		 * brandedFooter object
		 * 
		 * Encapsulates higher-level functions of the See-Try-Buy footer
		 * - getData() fetches JSON data
		 * - applyBusinessRules(linktype, brand_id, label_idx) 
		 * - parseUrl(linktype, brand_id, label_idx)
		 */
        brandedFooter = {
            json_dir: '/golf/static/json/seetrybuy/',
            json_filename: 'stb_BrandedFooterLinks.json',
            json_data: {},

            /**
             * Apply certain business rules and switch link type if necessary.
             * Rules are here instead of in each brandedLink type to maintain
             * loose coupling, otherwise the link types would have to know about 
             * each other.
             *
             * @param {String} linktype The link type
             * @param {Number} brand_id The brand code number
             * @param {Number} label_idx The footer item index
             * @return {String} The updated link type if any rules apply, otherwise returns type unchanged
             */
            applyBusinessRules: function(linktype, brand_id, label_idx) {
                var browse = 'browse',
                    shop = 'shop',
                    namesMap = {browse: [browse, see_tab], shop: [shop, buy_tab] },
                    titleist = 29, footjoy = 46,
                    apparelIndex = labels.indexOf('Apparel'),
                    accessoriesIndex = labels.indexOf('Accessories'),
                    
                    isType = function(type, name) {
                        var regexStr = namesMap[type].join('|');
                        return new RegExp(regexStr, 'i').test(name);
                    },
                    isBrowse = function() { return isType(browse, linktype); },
                    isShop = function() { return isType(shop, linktype); },
                    isTitleist = function() { 
                        return brand_id === titleist || brand_id === footjoy; 
                    }, 
                    isApparel = function() { 
                        return label_idx === apparelIndex; 
                    },
                    isAccessories = function() { 
                        return label_idx === accessoriesIndex; 
                    },
                    getType = function() { return isBrowse() ? browse : shop; },
                    
                    switchType = function() { return isBrowse() ? shop : browse; 
                    },
                    rules = [
                    //  All browse apparel links should be shop apparel links
                        function() { 
                            return isApparel() && isBrowse();
                        },
                        
                    //  Certain Titleist-related shop links should be browse
                        function() { 
                            return isTitleist() && isShop() && !isApparel() && !isAccessories(); 
                        }
                    ],
                    r = 0; // End var 
    
                for (r = 0; r < rules.length; r += 1) {
                    if (rules[r]()) { 
                        return switchType();
                    } 
                }
                // return linktype unchanged if no rules apply
                return getType();
            },
            /**
             * Return the branded or default See-Try-Buy footer URL built from
             * the required components.
             *
             * @param {String} stb_tab The STB tab type
             * @param {Number} brand_id The brand code
             * @param {Number} label_idx The footer item index
             * @return {String} The url string
             */
            parseUrl: function(stb_tab, brand_id, label_idx) {
                var url = [],
                    protocol = 'http:',
                    linktype = this.applyBusinessRules(stb_tab, +brand_id, label_idx),
                    link = brandedLink[linktype],
                    path = link.parsePath(brand_id, label_idx);

                url.push(protocol);
                url.push(''); // Second forward slash
                url.push(link.server);
                
            //  Add path only if not empty
                if (path) { url.push(path); }
                
                url.push(link.parseFilename(brand_id, label_idx));
                return url.join('/');
            },
	
            /**
             * Fetch branded footer links JSON data via AJAX call.
             */
            getData: function() {
                var url = this.json_dir + this.json_filename,
					footer = this;
     			$.getJSON(url, function(data) {
    				footer.json_data = data;
   				});
            },
            
            /**
             * Build HTML for the See-Try-Buy footer with branded links.
             * Works for 'see' and 'buy' tabs
             *
             * @param {String} stb_tab The desired tab name for which to get footer HTML.
             * @param {Number} stb_brand_id The desired brand ID to customize footer links for.
             * @return {String} html The footer HTML with branded links.
             */
            getFooterHtml: function(stb_tab, stb_brand_id) {
                var footer = brandedFooter,
                    label_idx = 0,
                    label_len = labels.length,
                    html = [],
                    validateBrandId = function(id) {
                        return id in brands ? id : no_brand;
                    },

                    buildFooterHtml = function(label_idx) {
                        var data_id = 0,
                            href = ''
                            writeTag = function(href, text) {
                                return ['<a href="', href, '">', text, '</a>'].join('');
                            };
                    //  fetch data ID from JSON for this tab, brand, and index
                        data_id = +footer.json_data[stb_tab][stb_brand_id][label_idx];
            
                    //  get branded URL
                        href = footer.parseUrl(stb_tab, data_id, label_idx);
            
                    //  add link HTML
                        return writeTag(href, labels[label_idx]);
                    };
        
            //  Confirm the page's brand is valid, if not, use no-brand value
                stb_brand_id = validateBrandId(stb_brand_id);	
                
            //  For each footer item in the See-Try-Buy footer, build link tag
                for (label_idx = 0; label_idx < label_len; label_idx += 1) {
                    html.push(buildFooterHtml(label_idx));
                }
                return html.join('');
            }
	    }, // End brandedFooter object	
		/**
		 * Return index of desired value in an array
		 *
		 * @param {String} value The desired value
		 * @return{Number} If found, the index of key-value pair, otherwise -1
		 */
        indexOf = function(value) {
            var result = -1, index = 0,
                len = this.length;
                
            if (!len) { return result; }
            for (index = 0; index < len; index += 1) {
                if (this[index] === value) {
                    result = index;
                    break;
                }
            }
            return result;
        },
        /**
         * Initialize labels.indexOf and JSON data
         */
        init = function() {
            labels['indexOf'] = indexOf;
            brandedFooter.getData();
        }; // end var statement

    // Initialization call
    init();

    // Set public API and assign to golf namespace
    golf_ns[stb_module_name] = {
        getFooterHtml: brandedFooter.getFooterHtml,
		footer: brandedFooter
    };

})(TIMEINC.GOLF, jQuery);


function crop(img_id, crop_id, x, y, width, height, oWidth, oHeight, url, alt) { 
	/* ***
	* To use crop, provide: 
	* crop([img src], [the div id that crops the img], [crop coordinate from left], [crop coordinate from top], [ % smaller width-wise],[% smaller height-wise], [original width], [original height])
	* Original width and height are necessary or irregularity of display of image thumbnail will take place with uses with AJAX.
	* 'oWidth', and 'oHeight' refer to original (JSON supplied) width and height.
	*** */

	if(isIE){var cimg = '<a href="'+url+'"><img id="' + crop_id + '_img" src="' + img_id + '" alt="' + alt + '" style="display:none" /></a>';}
	else {var cimg = '<img id="' + crop_id + '_img" src="' + img_id + '" alt="' + alt + '" style="display:none" />';}
	
	jQuery("#"+crop_id).html(cimg);
	
	var scale_x = 80 / width;
	var scale_y = 80 / height;
	
	jQuery("#"+crop_id).css({"position": "relative","overflow": "hidden"});
	jQuery("#"+ crop_id + '_img').css({"position": "absolute","display": "block","left": (-x * scale_x) + "px", "top": (-y * scale_y) + "px","width": (oWidth * scale_x) + "px","height": (oHeight * scale_y) + "px"});
}

var isMacFF = function () {
	if(navigator.userAgent.indexOf('Mozilla') > -1 && navigator.userAgent.indexOf('Macintosh') > -1){return true;}
	return false;
};
var isMacSafari = function () {
	if(navigator.userAgent.indexOf('Safari') > -1 && navigator.userAgent.indexOf('Macintosh') > -1){return true;}
	return false;
};
var isSafari = function () {
	if(navigator.userAgent.indexOf('Safari') > -1){return true;}
	return false;
};
var isIE6 = function () {
	if(navigator.userAgent.indexOf('MSIE 6') > -1){return true;}
	return false;
};
var isIE = function () {
	if(navigator.userAgent.indexOf('MSIE') > -1){return true;}
	return false;
};


var isMacSafariLT5 = function(){
	if(isMacSafari()){
		var ugent = navigator.userAgent;				
		var regex = /Version\/([0-9].)/;
		var matches = ugent.match(regex); 
		var getMajorVer = parseInt(matches[1]);
		if (getMajorVer < 5){ return true}
		else if (getMajorVer >= 5){	return false;}		
				
	}	
}


jQuery('#carousel').find('.galleryOpen').live('click', function(e){
	if(window.opener && !window.opener.closed){
		window.opener.location.href = jQuery(this).attr('href');
	}
	else {
		var pw = window.open(jQuery(this).attr('href'),'galWin');
		pw.focus();
	}
	return false
});	

/**
* Item html creation helper.
*/
function mycarousel_getItemHTML(item, addtitle, int) {
	var sectionTitle = (addtitle) ? '<h3>' + it_carousel_title_single + '</h3>' : '';
	return '<a href="' + item.link + '" title="' + item.img.iAlt + '"><img src="' + item.img.ipath + '" width="78" height="67" border="0" alt="' + item.img.iAlt + '" style="text-decoration:none" />' + sectionTitle +'<span>' + item.title + '</span></a>';
}
function nervecenter_getItemHTML(item, addtitle, int) {
	return '<a href="'+ item.link +'" class="galleryOpen" title="' + item.img.iAlt + '"><img src="' + item.img.ipath + '" width="78" height="67" border="0" alt="' + item.img.iAlt + '" style="text-decoration:none" /> <span>' + item.title + '</span></a>';
}
function gallerycarousel_getItemHTML(item, i, len) {	
	var highlighted = pageNum - 1;
	highlighted = (highlighted == i) ? "border-color:#D80101" : "";
	var displayCounter = (highlighted !== "") ? "showCounter" : "";
	jQuery('span.currentSlide').html(pageNum + ' of ' + len);
	return '<a href="' + item.link + '" title="' + item.img.iAlt + '"><div class="croppedIMG" id="crop' + (i+1) + '" style="width:80px; height:80px; margin-bottom:5px;'+highlighted+'"></div><span class="'+displayCounter+'">'+ (i+1) +' of '+len+'</span></a>';
	
}


function thumbnail(result, cdiv){
	if(result.resize == 'Y'){
		crop(result.img.ipath, cdiv, 40, 40, 280, 280, result.img.iWidth, result.img.iHeight, result.link, result.img.iAlt );
	}
	else {
		var cimg = (isIE) ? '<a href="'+result.link+'"><img src="' + result.img.ipath + '" alt="' + result.img.iAlt + '" /></a>' : '<img src="' + result.img.ipath + '" alt="' + result.img.iAlt + '" />';
		jQuery("#"+cdiv).html(cimg);
	}
}


function mycarousel_itemAddCallback(carousel, first, last, data, addTitle, isGallery) {
	var results, cdiv, img;
	if(isGallery){
		results = data.photogalleries;
		for (i = 0; i < results.length; i++) {
			carousel.add(i, gallerycarousel_getItemHTML(results[i], i, results.length));			
			cdiv = 'crop' + (i+1);
			thumbnail(results[i], cdiv);
		}
		/*for (i = 0; i < results.length; i++) {
			carousel.add(i, gallerycarousel_getItemHTML(results[i], i, results.length));			
		}
		for (i = 0; i < results.length; i++){
			cdiv = 'crop' + (i+1);
			crop(results[i].img.ipath, cdiv, 40, 40, 280, 280, results[i].img.iWidth, results[i].img.iHeight, results[i].link, results[i].img.iAlt );
		}*/
	} else {
		results = (addTitle)? data.leaderboardphotoandvideo : data.photoandvideo;
		for (i = 0; i < results.length; i++) {
			carousel.add(i, mycarousel_getItemHTML(results[i], addTitle, i));
		}
	}
	carousel.size(results.length);
}

/*See Try Buy*/

function stbcarousel_getItemHTML(item, addtitle, int,tabtype) {
	var str="";	
	for(var i= 0; i<item.images.length; i++){		
		var getItem = item.images[i];						
		for(var key in getItem)	{	
				var getTabUrl;				
				if(tabtype=='see'){ getTabUrl = getItem[key].seeUrl;}
				else if (tabtype=='try'){ getTabUrl = getItem[key].tryUrl;}
				else { getTabUrl = getItem[key].buyUrl;}				
				str+='<a href="'+getTabUrl+'"><img  src="'+getItem[key].src+'" width="'+getItem[key].width +'" height="'+getItem[key].height +'" alt="'+getItem[key].alt +'" /></a>';				
		 }
	}
	return str;	
}


function stbcarousel_itemAddCallback(carousel, first, last, data, addTitle,tabtype) {
	var results, cdiv, img;
	results = data.seetrybuy;
	for (i = 0; i < results.length; i++) {
			carousel.add(i, stbcarousel_getItemHTML(results[i], addTitle, i,tabtype));
	}
	
	carousel.size(results.length);
}

function nervecenter_itemAddCallback(carousel, first, last, data, addTitle, isGallery) {
	var results, cdiv;
	if(isGallery){
		results = data.photogalleries;
		for (i = 0; i < results.length; i++) {
			carousel.add(i, gallerycarousel_getItemHTML(results[i], i, results.length));			
			cdiv = 'crop' + (i+1);
			thumbnail(results[i], cdiv);
		}
		/*for (i = 0; i < results.length; i++) {
			carousel.add(i, gallerycarousel_getItemHTML(results[i], i, results.length));			
		}
		for (i = 0; i < results.length; i++){
			cdiv = 'crop' + (i+1);
			crop(results[i].img.ipath, cdiv, 40, 40, 280, 280, results[i].img.iWidth, results[i].img.iHeight, results[i].link, results[i].img.iAlt );
		}*/
	} else {
		results = (addTitle)? data.leaderboardphotoandvideo : data.photoandvideo;
		jQuery("#container3").prepend('<h3>' + results[0].header + '</h3>');		
		for (i = 0; i < results.length; i++) {
			carousel.add(i, nervecenter_getItemHTML(results[i], addTitle, i));
		}
	}		
	
	var thisOne = jQuery("#container3").find("div");
	for (var k=0; k<thisOne.length; k++) {
		if (thisOne[k].className.match('jcarousel-next') == 'jcarousel-next') { 			
			thisOne[k].onclick = function() {
				//console.log(this.className);
				var daUls = document.getElementById("carousel");
				var daLis = daUls.getElementsByTagName("li");	
				//console.log("0: " + daLis.length + " : " + results.length);
				if (daLis.length > results.length) {			
					//console.log("1: " + daLis.length + " : " + results.length);
					daUls.removeChild(daLis[daLis.length-1]);					
					//console.log("2: " + daLis.length + " : " + results.length);
				} 
				//console.log(daUls.style.left);				
			}
		}		
	}
	
	carousel.size(results.length);
}

function mycarousel_itemLoadCallback(carousel, state) {
	if (state != 'init') { return; }
	jQuery.getJSON(it_carousel_url, function(data) {
	   mycarousel_itemAddCallback(carousel, carousel.first, carousel.last, data);
	});
}
function mycarousel_itemLoadCallback2(carousel, state) {	
	if (state != 'init') { return; }
	jQuery.getJSON(it_carousel_url2, function(data) {
	   mycarousel_itemAddCallback(carousel, carousel.first, carousel.last, data);
	});
}
function mycarousel_itemLoadCallback_single(carousel, state) {
	if (state != 'init') { return; }
	jQuery.getJSON(it_carousel_url_single, function(data) {
	   mycarousel_itemAddCallback(carousel, carousel.first, carousel.last, data, true);
	});
}
function gallerycarousel_itemLoadCallback(carousel, state) {
	if (state != 'init') { return; }
	jQuery.getJSON(it_carousel_url, function(data) {
	   mycarousel_itemAddCallback(carousel, carousel.first, carousel.last, data, false, true);
	});
}
function nervecenter_itemLoadCallback(carousel, state) {
	if (state != 'init') { return; }
	jQuery.getJSON(it_carousel_url, function(data) {		
	   nervecenter_itemAddCallback(carousel, carousel.first, carousel.last, data);
	});
}

function mycarousel_itemLoadCallback_stb_see(carousel, state) { 
	if (state != 'init') { return; }
	carousel.buttonNext.bind('click', function() {
        carousel.startAuto(0);
    });
     carousel.buttonPrev.bind('click', function() {
        carousel.startAuto(0);
    });
     // Pause autoscrolling if the user moves with the cursor over the clip.
    carousel.clip.hover(function() {
        carousel.stopAuto();
    }, function() {
        carousel.startAuto();
    });	
	   jQuery.getJSON(it_carousel_url_stb, function(data) {	
	   stbcarousel_itemAddCallback(carousel, carousel.first, carousel.last, data, true,'see');
	});
}

function mycarousel_itemLoadCallback_stb_try(carousel, state) { 
	if (state != 'init') { return; }
	carousel.buttonNext.bind('click', function() {
        carousel.startAuto(0);
    });
     carousel.buttonPrev.bind('click', function() {
        carousel.startAuto(0);
    });
     // Pause autoscrolling if the user moves with the cursor over the clip.
    carousel.clip.hover(function() {
        carousel.stopAuto();
    }, function() {
        carousel.startAuto();
    });		
		
		jQuery.getJSON(it_carousel_url_stb, function(data) {
		   stbcarousel_itemAddCallback(carousel, carousel.first, carousel.last, data, true,'try');
	});
}

function mycarousel_itemLoadCallback_stb_buy(carousel, state) {
	if (state != 'init') { return; }	
	carousel.buttonNext.bind('click', function() {
        carousel.startAuto(0);
    });
     carousel.buttonPrev.bind('click', function() {
        carousel.startAuto(0);
    });
     // Pause autoscrolling if the user moves with the cursor over the clip.
    carousel.clip.hover(function() {
        carousel.stopAuto();
    }, function() {
        carousel.startAuto();
    });	
	
	jQuery.getJSON(it_carousel_url_stb, function(data) {	
	   stbcarousel_itemAddCallback(carousel, carousel.first, carousel.last, data, true,'buy');
	});
}

function stb_getFooterMenu(){	
	jQuery.getJSON('/golf/static/json/seetrybuy/stb_footerMenu.js', function(data) {	
	var results = data.stbFooterMenu;	
	var footerStr="";	
		 for(var i = 0; i<results.length;i++){			
			if(i== results.length-1){
					footerStr+="<a style='border:0;' href='"+results[i].link+"'>"+results[i].title+"</a>";		
				} 
				else footerStr+="<a href='"+results[i].link+"'>"+results[i].title+"</a>";
		}
		jQuery(".tabFooter").html(footerStr);	
													
	});												
}


/*	 Start code for top navigation. Build ont he elementReady function that waits for the DOM element *
*	to be built instead of the usually full DOM tree method the rest of the code falls into. */
jQuery.elementReady('nav-container', function() {
	jQuery('#topnav > ul li a span').bind("click", function(){
		var url = jQuery(this).attr("href");
		if(window.name == 'diggiFrame'){window.document.location = url;} 
		else {parent.window.document.location = url;}
	});
	var setNavTab = smap['default'];
	var $tabs = jQuery('#topnav > ul').tabs({event: 'mouseover', selected: setTabNav});
	if (typeof(sectionNavName) != 'undefined') {
		if (typeof(smap[sectionNavName]) != 'undefined') {setNavTab = smap[sectionNavName];}	
	}	
	var selected = jQuery('#topnav > ul').tabs('option', 'selected'); // Sets the page default
	jQuery('#topnav').mouseleave(function(){ // Returns the nav to the page default
		jQuery('#topnav > ul').tabs('option', 'selected', setTabNav);
	});
	jQuery('#topnav li:first a').css('background-image','none');
	jQuery('#topnav #fragment-1 li:first, #topnav #fragment-2 li:first, #topnav #fragment-3 li:first, #topnav #fragment-4 li:first, #topnav #fragment-5 li:first, #topnav #fragment-16 li:first, #topnav #fragment-7 li:first, #topnav #fragment-8 li:first').css({'border':'0px', 'padding-left':'2px'});
	jQuery('#topnav').css('display', 'block');
	jQuery('#topnav .ui-tabs-panel a.popup').click(function(evt){
		evt.preventDefault();
		evt.stopPropagation();
		var url = jQuery(this).attr('href');
		if(!window.tnavPop){
			var win = window.open(url, "tnavPop");
			window.tnavPop.focus();
		}
		else {
			window.tnavPop.location.href = url;	
			window.tnavPop.focus();
		}			
	})
});
/* End code for top navigation */

jQuery(document).ready(function() {
	/* CSS helper function that removes text-decorations from links with img children */
	jQuery('a:has(img)').css("textDecoration","none");
	/* End helper */
	
	/* See Try Buy */
	if (document.getElementById("tabbed-toolbarSTB") !== null) {
		jQuery('#tabbed-toolbarSTB > ul').tabs({event: 'click', selected : stbActiveTab});	
		jQuery('#tabbed-toolbarSTB').css('display','block');
		jQuery('#carousel_see').jcarousel({wrap: "last",  auto: 3, scroll: 1, visible: 1, itemLoadCallback: mycarousel_itemLoadCallback_stb_see});
		jQuery('#carousel_try').jcarousel({wrap: "last",  auto: 3, scroll: 1, visible: 1, itemLoadCallback: mycarousel_itemLoadCallback_stb_try});
		jQuery('#carousel_buy').jcarousel({wrap: "last",  auto: 3, scroll: 1, visible: 1, itemLoadCallback: mycarousel_itemLoadCallback_stb_buy});
		
		// Updated call to build SeeTryBuy footer links, uses TIMEINC.GOLF.seetrybuy module
		// Previous call was: stb_getFooterMenu(); which remains in this file
		var stb = TIMEINC.GOLF.seetrybuy,
			seeFooterHtml = stb.getFooterHtml('see', golf_stb_brandid),
			buyFooterHtml = stb.getFooterHtml('buy', golf_stb_brandid);	
	
		// Build footer menus
		jQuery('#tab_see .tabFooter').html(seeFooterHtml);
		jQuery('#tab_buy .tabFooter').html(buyFooterHtml);

		// Remove right border from last element in footer menus
        jQuery('.tabFooter').find('a:last').css({'border-width': '0'});
		
		// Hide red arrows on Buy-tab image captions if empty
		// Implemented here because Buy-tab HTML generated from an unmodifiable SSI
		jQuery('#tab_buy .topProds > a').each(function() {
			var caption = jQuery(this);
			if (!(jQuery.trim(caption.text()))) {
				caption.hide();	
			}
		});
		
		if(displayGTechform == false){
			jQuery('#golftec').css('display','none');
		}
	}
	
	/* Leaderboard template carousels */
	if(typeof(LBPrimaryColor) !== "undefined"){
		jQuery('#carousel_1').jcarousel({wrap: "both", scroll: 1, visible: 1, itemLoadCallback: mycarousel_itemLoadCallback_single});
		jQuery('#carousel_2').jcarousel({wrap: "both", scroll: 3, visible: 3, itemLoadCallback: mycarousel_itemLoadCallback });
		jQuery('#container2').prepend("<h3>" + it_carousel_title + "</h3>");
	}
	
	/* Photo Gallery template carousel */
	else if(typeof(contentType) !== "undefined" && contentType === "gallery"){
		if(isIE6){jQuery('#footer li:first-child').css('border','0');}	
		if(typeof(moregalleriesurl) !== "undefined"){
			
			/* The following getJSON function manages the content of the most popular galleries pulldown on the gallery pages */
			jQuery.getJSON(moregalleriesurl, function(data) {
			var MAXIMUM = 8,
				index, link = '',
				//articleID = articleID || '1234567890',
				galleries = data.moregalleries,
				thisGallery, nextGallery, galleryItem,
				validGalleries = [],
				uniqueGalleries = [],
				
				// Compare galleries based on link url string
				compareLinks = function(a,b) {
					if (a.link > b.link) {
						return 1;
					} else if (a.link < b.link) {
						return -1;
					} else {
						return 0;
					}
				},
				
				// standard shuffle functionality
				shuffle = function(array) {
					var i = array.length;
					if (i === 0) {
						return;
					}
					while(--i) {
						var j = Math.floor(Math.random() * (i + 1));
						var temp = array[i];
						array[i] = array[j];
						array[j] = temp;
					}
				
				};
					
			// Walk through JSON and remove empty links and self-referencing galleries
			for(index = 0; index < galleries.length; index += 1) {
				galleryItem = galleries[index];
				link = galleryItem.link;
		
				// if there is a link string
				if (link && typeof link === 'string') {
		
					// if the link does NOT include the current article's ID
					if (link.indexOf(articleID) === -1) {
		
						// add to valid list
						validGalleries.push(galleryItem);
					}
				}
			}
			
			// If no galleries, return the empty array
			if (!validGalleries.length) {
				return validGalleries;
			}
			// Sort galleries
			validGalleries.sort(compareLinks);
		
			// Check for and remove duplicates on sorted array.
			// This algorithm requires a sorted array to work
			uniqueGalleries.push(validGalleries[0]);
			for (index = 0; index < validGalleries.length - 1; index += 1) {
				thisGallery = validGalleries[index];
				nextGallery = validGalleries[index + 1];
				
				// If next link is different add it, otherwise it's a duplicate.
				if (compareLinks(thisGallery, nextGallery) !== 0) {
					uniqueGalleries.push(nextGallery);
				}
			}
			
			// Shuffle galleries order
			shuffle(uniqueGalleries);
			
			// Enforce maximum 8 galleries
			if (uniqueGalleries.length > MAXIMUM) {
				uniqueGalleries.length = MAXIMUM;
			}	
									
			// Inject HTML
			for (var k = 0; k < uniqueGalleries.length; k++){
				galleryItem = uniqueGalleries[k];
				var mdiv = 'crop' + (k+1);
				jQuery('#more-galleries-div p').append('<a href="' + galleryItem.link + '" title="' + galleryItem.img.iAlt + '"><img src="' + galleryItem.img.ipath + '" width="78" height="67" border="0" alt="' + galleryItem.img.iAlt + '" /><span>' + galleryItem.title + '</span></a>');
				if	(k ===0) {
					jQuery('#more-galleries a img').replaceWith('<img src="' + galleryItem.img.ipath + '" width="78" height="67" border="0" alt="' + galleryItem.img.iAlt + '" />')
				}
			}
		});
			/* Changed to reflect new ad slide -- RH 5/3/10 */
			if(jQuery('div.adContent').length > 0){
				jQuery('#right-rail #advance-btns').width('66.6%').css('left', '100px');				
			}
			else {
				jQuery('#right-rail #advance-btns').width(jQuery('div#gallery img').width()).css('left', ((600 - jQuery('div#gallery img').width())/2));				
			}
			
			/* Photo Gallery Advancing buttons */			
			jQuery('div#gallery')
				.mouseover(function(){jQuery('#right-rail #advance-btns').show();})
				.mouseout(function(){jQuery('#right-rail #advance-btns').hide();});
				
			/*BA: update the click thru functionality on galleries. Clicking on 1/3rd of image takes user to previous slide and clicking on 2/3 right section takes user to next slide */			
			var prevSectionWidth = jQuery('div#gallery img').width()/3;
			var nextSectionWidth = jQuery('div#gallery img').width() *2/3 -3 ;		
			var imgHeight = jQuery('div#gallery img').height();
			
			jQuery('span#prev-btn').css({'height':imgHeight,'width':prevSectionWidth});
			jQuery('span#next-btn').css({'height':imgHeight,'width':nextSectionWidth});
						
						
			function closeMoreGalleries(closebtn){
			  jQuery('#more-galleries-div').hide("normal", function(){jQuery('#more-galleries-div p').empty();});	
			}
			
			/* This portion manages the carousel content */
			pageNum = parseInt(pageNum);
			pageNumDiv = parseInt(pageNum / 4);
			pageNumRem = pageNum % 4;		
			
			// Set the start image of carousel based on page number 
			if ((pageNum %4) ==0 ){	pageNumResult = pageNum-3 ;	}
			else {pageNumResult= (pageNumDiv*4)+1;}			
						
			jQuery('#more-galleries, #more-galleries-div #close-btn').click(function(){jQuery('#more-galleries-div').toggle("normal");});
			jQuery('#carousel').jcarousel({
				wrap: "both", 
				start: pageNumResult,
				scroll: 4,
				itemLoadCallback: gallerycarousel_itemLoadCallback,
				itemVisibleInCallback: {
  					onBeforeAnimation: function(carousel, item, i, state, evt){
						if(i < 5){jQuery('.jcarousel-prev').hide();	}
						else {jQuery('.jcarousel-prev').show();}
						if(galleryTotal === i || galleryTotal < 5){jQuery('.jcarousel-next').hide();	}
						else {jQuery('.jcarousel-next').show();}
					}
				}
			});
		}
	}
	
	/* Homepage and Section Front template carousel */
	else if(typeof(contentType) !== "undefined" && contentType === "channel"){
		if(jQuery('#tabbed-toolbar > ul').length > 0){
			jQuery('#tabbed-toolbar > ul').tabs({event: 'click', selected : it_ttb_default});
		}
		// ******* Omniture clicking functionality Start ********
		var fireOmniClick = function(path){
			s_time.linkTrackVars = 'prop28,prop29';
			s_time.linkTrackEvents = 'None';				
			s_time.prop28 = 'widget|'+sectionNavName;
			s_time.prop29 = path;
			void(s_time.tl(this,'o','Widget Actions'));
		}
		function cleanArray(items) {
			var len = items.length;
			var newArray = [];
			for(var i=0; i<len; i++){
				if(items[i].search(/[a-zA-Z0-9]/) < 0){
					newArray.push('x');
				}
				else {
					newArray.push(items[i]);
				}
			}
			return newArray;
		}
		function getTab (){
			return jQuery('#tabbed-toolbar > ul ').find('li.ui-tabs-selected').text();
		}
		var sTab, val, tree, href;
		jQuery('#tabbed-toolbar').find('a').click(function(){
			sTab = getTab();
			val = jQuery(this).text();
			if (sTab.toLowerCase().indexOf('equipment') > -1 && val == ""){
				href = jQuery(this).find('img').attr('src');
				switch(true){
					case href.indexOf('club') > -1:
						val = "find clubs";
						break;
					case href.indexOf('balls') > -1:
						val = "find balls";
						break;
					case href.indexOf('shoes') > -1:
						val = "find shoes";
						break;
					case href.indexOf('bags') > -1:
						val = "find bags";
						break;
					case href.indexOf('acc') > -1:
						val = "find accessories";
						break;
				}
			}
			else if (jQuery(this).attr('href').indexOf('egolfcertificates') > -1 && val == ""){
				val = "ad|"+jQuery(this).attr('href').match(/\d+$/);				
			}			
			var temp1 = sTab.slice(sTab.length-1,sTab.length);
			sTab = (temp1 == ' ') ? sTab.substr(0, sTab.length-1) : sTab;
			tree = (sTab.toLowerCase() === val.toLowerCase()) ? sTab.toLowerCase() : sTab.toLowerCase()+"|"+val.toLowerCase();
			fireOmniClick("widget|"+tree.toLowerCase());
		});
		jQuery('#tabbed-toolbar').find('form').submit(function(){
			var arr = [];
			sTab = getTab();
			
			jQuery(this).find("input, select").each(function(i){arr.push(this.value);});
			
			arr.pop();
			val = cleanArray(arr);
			val = val.join('|');
			var temp2 = sTab.slice(sTab.length-1,sTab.length);
			sTab = (temp2 == ' ') ? sTab.substr(0, sTab.length-1) : sTab;
			if(val.indexOf('Equipment Finder') > -1){fireOmniClick("widget|"+sTab.toLowerCase()+"|search|search|"+val.toLowerCase());}
			else {fireOmniClick("widget|"+sTab.toLowerCase()+"|search|"+val.toLowerCase());}
		});
		// ******* Omniture clicking functionality End ********

		jQuery('#tabbed-toolbar').css('display', 'block');
		jQuery('#tabbed-toolbar ul:first').css({'background':'#fff'});
				
		if(isMacFF() || isMacSafari()){						
			jQuery('#right-rail #tabbed-toolbar #toolbar-2 form').css({'width':'278px !important'});
			jQuery('.right-banner #tabbed-toolbar #toolbar-2 form').css({'width':'278px !important'});
			
		}
		/*if(isMacSafari()){			
			jQuery('#right-rail #tabbed-toolbar #toolbar-2 form').css({'width':'278px !important'});
			jQuery('.right-banner #tabbed-toolbar #toolbar-2 form').css({'width':'278px !important'});	
		}*/
		
		if(isIE6()) {
			jQuery('#tabbed-toolbar .ui-tabs-nav li').css('width', '72px');
		}
		jQuery('#carousel').jcarousel({
			wrap: "both", 
			scroll: 4,
			itemLoadCallback: mycarousel_itemLoadCallback
		});
		it_carousel_title = (typeof(it_carousel_title) !== "undefined") ? it_carousel_title : "";
		jQuery('#container .jcarousel-container').prepend("<h3>" + it_carousel_title + "</h3>"); 		
		jQuery('#carousel_equipment').jcarousel({wrap: "last",  auto: 3, scroll: 1, visible: 1, itemLoadCallback: mycarousel_itemLoadCallback_stb_see});
		
		/* Handles the tout search boxes in center of page of HP and Section Front templates. */
		jQuery('#s_courses_travel, #s_equipment, #s_instruction').bind("focus", function() {
				var defaultValue = jQuery(this).val();
				var def = ["search instruction","search equipment","search courses & travel"];
				var len = def.length;				
				for (var i=0; i<len;i++){
					if(jQuery(this).val().length < 1 || jQuery(this).val() === def[i]){
						jQuery(this).removeClass().addClass("editBlack").val("");
						break;
					}
				}					
				function resetF(e) {
					for (var i=0; i<len;i++){
						if(jQuery(this).val() === def[i] || jQuery(this).val().length < 1){
							jQuery(this).removeClass().addClass("editGrey").val(txt);
							break;
						}
					}
					jQuery(this).unbind("blur");
				}
				return jQuery(this).bind("blur", resetF); 
		});
	}
	/* Article template carousels */
	else if(typeof(contentType) !== "undefined" && contentType === "article") {
		jQuery('#carousel').jcarousel({ wrap: "both",  scroll: 4, itemLoadCallback: mycarousel_itemLoadCallback });		
		jQuery('#carousel_2').jcarousel({ wrap: "both",  scroll: 3, itemLoadCallback: mycarousel_itemLoadCallback2 });
	}
	/* Nerve Center template carousel */
	else if(typeof(contentType) !== "undefined" && contentType === "nervecenter") {
		jQuery('#carousel').jcarousel({ wrap: "both",  scroll: 4, visible: 4, itemLoadCallback: nervecenter_itemLoadCallback });
	}
	/* Generic template carousels */
	else {
		jQuery('#carousel').jcarousel({
			wrap: "both", 
			scroll: 4,
			itemLoadCallback: mycarousel_itemLoadCallback
		});
	}
	
	jQuery('#tabbed-scorecard > ul').tabs({event: 'click', selected : '0'});
	jQuery('#tabbed-scorecard').css('display', 'block');
	jQuery('#tabbed-scorecard ul li:last span').css('border','0');
	jQuery('#toggle9 a:first').click(function(){
		jQuery('.course-scorecard:eq(0) div:eq(1), .course-scorecard:eq(1) div:eq(1), .course-scorecard:eq(2) div:eq(1), .course-scorecard:eq(3) div:eq(1), .course-scorecard:eq(4) div:eq(1)')
			.removeClass("box_shown")
			.addClass("box_hidden");
		jQuery('.course-scorecard:eq(0) div:eq(0), .course-scorecard:eq(1) div:eq(0), .course-scorecard:eq(2) div:eq(0), .course-scorecard:eq(3) div:eq(0), .course-scorecard:eq(4) div:eq(0)')
			.removeClass("box_hidden")
			.addClass("box_shown");
	})		
	jQuery('#toggle9 a:last').click(function(){
		jQuery('.course-scorecard:eq(0) div:eq(0), .course-scorecard:eq(1) div:eq(0), .course-scorecard:eq(2) div:eq(0), .course-scorecard:eq(3) div:eq(0), .course-scorecard:eq(4) div:eq(0)')
			.removeClass("box_shown")
			.addClass("box_hidden");
		jQuery('.course-scorecard:eq(0) div:eq(1), .course-scorecard:eq(1) div:eq(1), .course-scorecard:eq(2) div:eq(1), .course-scorecard:eq(3) div:eq(1), .course-scorecard:eq(4) div:eq(1)')
			.removeClass("box_hidden")
			.addClass("box_shown");
	})
});
