$(document).ready(function() {
    if (document.getElementById('nextSlide')) {
        twoPaneCarousel();
    }
    if (document.getElementById('trackPack')) {
        $('#trackList a').mouseover(trackPackModule);
        $('#trackPack h4').mouseover(defaultPacks);
    }

    if (document.getElementById("breakingNews")) {
        $(".layoutHome #mainContentColExtra").css("margin-top", "50px");
    }

    $("#siteNavMain>li:last").addClass("lastItem");

    $("#headerLinkBox>li:last").addClass("lastItem");

    $("#footerLinks>li:last").addClass("lastItem");
	
	$("#tabScroller>li:last").addClass("lastItem");
	
	$("#podcastLinks>li:last").addClass("lastItem");
	
	if(document.getElementById('tabScroller')) {
		$("#tabScroller li a span").each(function() {
			var spanHeight = $(this).height();
			if(spanHeight < 20) {
				$(this).addClass("oneLine");
			} else {
				$(this).addClass("twoLines");
			}
		});
	}
	
	$("#tabScroller2>li:last").addClass("lastItem");

    $("#calendarContent ul li:last").addClass("lastItem");

    $(".listModule .newsList li:last").addClass("lastItem");

    $(".jcorePoll label:last").css({ "border-bottom": "0px", "padding-bottom": "10px" });

    if ($(".newsletterInput").length > 0) {
        newsletterSignUp();
    }

    $("#nav_community, #nav_store, #nav_fantasy").next("UL").css({ "left": "auto", "right": "0" });

    // push Tripple Column Wrap down when the tirtiery nav is present
    if ($(".subNavModule ul li ul").length > 0) {
        if ($(".layoutM").length > 0) {
            $(".layoutM #mainTripleColWrap").css("margin-top", $(".subNavModule ul li ul").height() - 10);
            $(".subNavModule ul li ul").css("border-bottom", "0px");
            // if ie below version 8 use move amount for those versions
            if ($.browser.msie && $.browser.version < "8.0") {
                $(".layoutM #mainTripleColWrap").css("margin-top", $(".subNavModule ul li ul").height() + 20);
            }
        }
        if ($(".layoutAa").length > 0) {
            $(".layoutAa #mainContentColWrap").css("margin-top", $(".subNavModule ul li ul").height() + 10);
            $(".subNavModule ul li ul").css("border-bottom", "0px");
            // if ie below version 8 use move amount for those versions
            if ($.browser.msie && $.browser.version < "8.0") {
                $(".layoutAa #mainContentColWrap").css("margin-top", $(".subNavModule ul li ul").height());
            }
        }
    }
    if ($("#mainFooterPanel").length > 0) {
        $("#mainFooterPanel").append("<div class='clear'></div>");
    }
    $("#headerSearchField").each(function() {
        var resetValue = this.value;
        $(this).focus(function() {
            if (this.value == resetValue)
                this.value = "";
        });
        $(this).blur(function() {
            if (this.value == "")
                this.value = resetValue;
        });
    });

    $(".genericForm").each(function() {
        $(this).append("<div class='genericFormError'></div>");
    });

    /*$(".genericForm").submit(function() {
    return validateForm(this);
    });*/

    // add click functionality for generic dropdowns
    $(".genericDropDown").each(function(i) {
        var scope = $(this);
        $(".dropTrigger>a", scope).click(function() {
            var thisDropStyle = $(".dropContent", scope).css("display");
            if (thisDropStyle == "none") {
                $(".dropContent").hide();
                $(".dropContent", scope).show();
            } else {
                $(".dropContent").hide();
            }
            return false;
        });
    });
    // filter values temporary variables
    var filterAffiliateParameter = "";
    var filterStateParameter = "";
    // select affiliates program filter and store in variables
    $(".filterAffiliateProgram li a").click(function(e) {
        e.preventDefault();

        filterAffiliateParameter = unescape($(this).text());
        $(".dropContent").hide();
    });
    // select state filter and store in variables
    $(".filterState li a").click(function(e) {
        e.preventDefault();

        filterStateParameter = unescape($(this).text());
        $(".dropContent").hide();
    });
    // click search button and refresh browser with url and parameters
    $("#btnSearchAffiliate").click(function(e) {
        e.preventDefault();

        var currentPage = trimOffURLParameters(location.href);
        var parmStr = "";
		
        // if filterAffiliateParameter not empty, add to parameter string
        if (filterAffiliateParameter != "" && filterAffiliateParameter != "All") {
            parmStr += "t=" + filterAffiliateParameter;
        }
        // if filterStateParameter not empty, add to parameter string
        if (filterStateParameter != "" && filterStateParameter != "State") {
            // if parameter string not empty, add ampersand separater
            if (parmStr.length > 0) { parmStr += "&"; }
            // add q, filterStateParameter to string
            parmStr += "q=" + filterStateParameter;
        }
        // if parameter string not empty, add ?, parameter starter to parameter string
        if (parmStr.length > 0) { parmStr = "?" + parmStr; }
        // refresh browser url
		var ancstr = "#showFindStations";
		if(currentPage.indexOf("#") > 0 && currentPage.indexOf("#") < currentPage.length-1)
		{
			ancstr = currentPage.substring(currentPage.indexOf("#"), currentPage.length);
			currentPage = currentPage.replace(ancstr, "");
		}
		else if(currentPage.indexOf("#") == currentPage.length-1)
		{
			currentPage = currentPage.replace("#", "");
		}
		
        window.location = currentPage + parmStr + ancstr;
    });
    // click affiliate program dropdown and set its dropdown value
    $("ul.filterAffiliateProgram li a").click(function(e) {
        e.preventDefault();

        $("#affiliateProgram .affiliateProgramValue").text(unescape($(this).text()));
        filterAffiliateParameter = unescape($(this).text());
    });
    // if the affiliate program dropdown is present, set the dropdown value to the query value
    if (document.getElementById("affiliateProgram")) {
        var theValue = queryStr("t");
        // if the affiliate program dropdown value is empty, set the dropdown value to all
        if (theValue == "") {
            $("#affiliateProgram .affiliateProgramValue").text("All");
            filterAffiliateParameter = "";
        }
        // if the affiliate program dropdown value is not undefined, set the dropdown to the query value
        if (theValue !== undefined) {
            $("#affiliateProgram .affiliateProgramValue").text(unescape(theValue));
            filterAffiliateParameter = theValue;
        }
    };

    // click state dropdown and set its dropdown value
    $("ul.filterState li a").click(function(e) {
        e.preventDefault();
		
        $("#state .stateValue").text($(this).text());
        if ($(this).attr("sname") === undefined) {
            filterStateParameter = "";
        } else {
            filterStateParameter = $(this).attr("sname");
        }
    });
    function findNameThruKey(valStr, theSelector) {
        var findValue = "";
        $(theSelector).each(function() {
			//alert(valStr);
            if ($(this).attr("sname") == valStr.replace("%20", " ")) {
                findValue = $(this).text();
                return false;
            }
        });
        return findValue;
    }
    // if state dropdown is present, set the dropdown value to the query value
    if (document.getElementById("state")) {
        var theValue = queryStr("q");
        // if the state dropdown value is empty, set the dropdown value to state
        if (theValue == "") {
            $("#state .stateValue").text("State");
            filterStateParameter = "";
        }
        // if the state dropdown value is not undefined, set the dropdown to the query value
        if (theValue !== undefined) {
            //alert(findNameThruKey( theValue, "ul.filterState li a" ));
            $("#state .stateValue").text(unescape(findNameThruKey(theValue, "ul.filterState li a")));
            filterStateParameter = theValue;
        }
    };

    if (document.getElementById("experienceScoller")) {
        var expScroll = new experienceScroll();

        var urlparam = queryStr("i");
        if (urlparam) {
            var marker;
            $("#experienceScoller .scrollItem").each(function(i) {
                var testId = $(this).attr("id");
                if (testId == urlparam) {
                    marker = Math.floor(i / 5);
                    $(".scrollItem").removeClass("activeScrollItem");
                    $(this).addClass("activeScrollItem");
                }
            });
            expScroll.currentPane = marker;
            expScroll.scrollCarousel(marker * -1);
        }

    }

    if (document.getElementById("timelineVert")) {
        timelineScroll();
    }
	if(document.getElementById("tabScroller")) {
		tabScroller();
	}
	if(document.getElementById("tabScroller2")) {
		tabScroller2();
	}
    // preload loader icon
    expLoadIcon = new Image();
    expLoadIcon.src = "/media/big_loader.gif";

    function updateShareLinks(experienceID) {
        $("#shareBox").hide();
        var currentURL = window.location.toString();
        currentURL = currentURL.replace(/#/, "");
        if (currentURL.match(/\?i=/)) {
            var newURLTemp = currentURL.split("?");
            var newURL = newURLTemp[0] + "?i=" + experienceID; ;
        }
        else if (currentURL.match(/\?/))
            var newURL = currentURL + "&i=" + experienceID;

        else
            var newURL = currentURL + "?i=" + experienceID;

        var newShareSource = "<a id='diggLink' href='http://digg.com/submit?phase=2&url=" + newURL + "&title=Feel+The+Experience' target='_blank'><img height='22' width='21' src='/media/wgi/icons/digg_icon.gif' alt='Digg'/></a><a id='deliciousLink' href='http://del.icio.us/post?url=" + newURL + "' target='_blank'><img height='22' width='22' src='/media/wgi/icons/delicious_icon.gif' alt='Delicious'/></a><a id='newsvineLink' href='http://www.newsvine.com/_wine/save?u=" + newURL + "&h=Feel+The+Experience' target='_blank'><img height='22' width='21' src='/media/wgi/icons/newsvine_icon.gif' alt='Newsvine'/></a><a id='redditLink' href='http://reddit.com/submit?url=" + newURL + "&title=Feel+The+Experience' target='_blank'><img height='22' width='21' src='/media/wgi/icons/reddit_icon.gif' alt='Reddit'/></a><a id='stumbleLink' href='http://www.stumbleupon.com/submit?url=" + newURL + "&title=Feel+The+Experience' target='_blank'><img height='22' width='21' src='/media/wgi/icons/stumble_icon.gif' alt='Stumble'/></a><a id='technoratiLink' href='http://www.technorati.com/faves?add=" + newURL + "' target='_blank'><img height='22' width='21' src='/media/wgi/icons/technorati_icon.gif' alt='Technorati'/></a><a id='facebookLink' href='http://www.facebook.com/sharer.php?u=" + newURL + "&t=Feel+The+Experience' target='_blank'><img height='22' width='19' src='/media/wgi/icons/facebook_icon.gif' alt='Facebook'/></a>"
        $("#shareBox").html(newShareSource);
    }

    $(".scrollItem").click(function() {
        var scrollItemId = $(this).attr("id");
        updateShareLinks(scrollItemId);

        var ajaxUrl = $("a:first", this).attr("href");
        $("#experienceContent").html("<div id='expLoading'>loading</div>");
        $.ajax({
            type: "GET", url: ajaxUrl, cache: false, dataType: "html",
            success: function(newExperience) {
                $("#experienceContent").animate({ opacity: 'hide' }, "fast", function() {
                    $("#experienceContent").html(newExperience);
                    //$("#experienceContent").animate({opacity: 'show'}, "fast");
                    $("#experienceContent").show();
                    $('#feelTheExperienceWrapInner .ad728x90').hide();
                    $('#feelTheExperienceWrapInner .ad728x90').show();
                });
            }
        });
        $(".activeScrollItem").removeClass("activeScrollItem");
        $(this).addClass("activeScrollItem");
        return false;
    });

    $(".layoutHome .newsListModule").each(function(i) {
        var context = $(this);
        $(".genericTabs li a", context).click(function() {

            var ajaxUrl = $(this).attr("href");
            $(".homeNewsTabContent", context).html("<div id='expLoading'>loading</div>");
            $.ajax({
                type: "GET", url: ajaxUrl, cache: false,
                success: function(tabCOntent) {
                    $(".homeNewsTabContent").animate({ opacity: 'hide' }, "fast", function() {
                        $(".homeNewsTabContent").html(tabCOntent);
                        $(".homeNewsTabContent").animate({ opacity: 'show' }, "fast");
                    });
                }
            });
            $(".genericTabs li", context).removeClass("activeTab");
            $(this).parent().addClass("activeTab");
            return false;
        });
    });

    //$(".genericForm input:checkbox").addClass("genericCheckbox");
    //$(".genericForm input:radio").addClass("genericRadio");

    // event cal module filter
    $("#calFilter").each(function() {
        var eventFilters = new Filter("calFilter", "calendarFilterItem", "calendarContent", 1000, false);
    });


    // position track site box
    $("a#trackSitesLink").click(function() {
        var thisPos = findPos(this);
        toggleTrackBox(thisPos);
        return false;
    });
    $("#trackNav a").click(function(i) {
        $("#trackNav").hide();
    });
	
	// position track site box
	
	
    /*$(".dropTrigger a").click(function() {
		var thisPos = findPos(this);
        toggleDropBox(thisPos);
		$(".dropContent").show();
        return false;
    });
    $(".dropContent a").click(function(i) {
        $(".dropContent").hide();
    });*/


    // share box scripts
    /*$(".shareBarSocial a").click(function() {
    var thisPos = findPos(this);
    toggleShareBar(thisPos);
    return false;
    });*/

    // Unbind any clicks for .shareBarSocial a
    $(".shareBarSocial a, .mediaShareBtn").unbind("click");
    // Bind a new function that gets the screen position of the link
    // and toggles the share bar at that position
    var makeTwitterLink = true;
    $(".shareBarSocial a, .mediaShareBtn").bind("click", function() {
        if (makeTwitterLink == true) {
            $("#twitterLink").each(function() {
                scope = $(this);
                $.ajax({
                    url: "/Handlers/Bitly.ajax?url=" + document.location,
                    dataType: "json",
                    cache: false,
                    success: function(data) {
                        makeTwitterLink = false;
                        if (data.success == true)
                            scope.attr("href", $(scope).attr("href") + " " + data.url);
                    }
                });
            });
        }
        var thisPos = findPos(this);
        toggleShareBar(thisPos);
        return false;
    });

    /*$("#shareBox a").click(function(i) {
    $("#shareBox").hide();
    });*/
    $(window).bind('resize', function() {
        $("#shareBox").hide();
    });
    catchPromo();
    readPromo();

    if ($(".countdownClock").length > 0) {
        setClock();
    }
    if ($("#miniCalTitle").length > 0) {
        setProgramClock();
    }
    if ($(".calendarContentDuring").length > 0) {
        calendarTabs();
    }
    if ($(".newsTabsModule").length > 0) {
        newsTabs();
    }
    if ($(".vertTabsModule").length > 0) {
        vertTabs();
    }
    if ($(".campingModule").length > 0) {
        campingTabs();
    }
    if ($(".calLinks").length > 0) {
        $(".calLinks li:last-child").addClass("lastItem");
    }
    if ($(".wizardForm").length > 0) {
        wizard();
    }

    if ($(".quizForm").length > 0) {
        quiz();
    }

    /*if($(".ad728x90 object param").length > 0){
    $(".ad728x90 param[name*='wmode']").val("transparent");
    $(".ad728x90 embed").attr("wmode","transparent");
    }*/

    if (document.getElementById('breakingNews')) {
        breakingNewsBar();
    }
    if ($('.smlEventLinks').length > 0) {
        $(".smlEventLinks li:first-child").addClass("first");
    }
    $("#siteNavMain>li>a").bind("mouseover", function() {
        var scope = $(this).parent();
        var scopeAd = $(".subNavCol5 li", scope);
        if (typeof (scopeAd) != "undefined") {
            getRibbonAd(scopeAd);
        }
    });

});
/*************************************************
END OF DOC READY
*************************************************/
// strip parameters off url
function trimOffURLParameters( str ){
	if( str.indexOf("?") < 0 ){
		return str;
	}else{
		return str.substr( 0, str.indexOf("?") );
	}
};
// urlEncode spaces for url parameters
function urlEncodeSpace( theWords ) {
	return theWords.replace(" ", "%20");
};
// urlDecode spaces for url parameters
function urlDecodeSpace( theWords ) {
	return theWords.replace("%20", " ");
};
function toggleTrackBox(coords) {
	var boxHeight = $("#trackNav").height();
	$("#trackNav").css("left",coords[0] - 100);
	$("#trackNav").css("top",(coords[1] - (boxHeight + 8)));
	$("#trackNav").toggle();
}

function toggleDropBox(coords) {
	var boxHeight = $(".dropContent").height();
	$(".dropContent").css("left",coords[0]+5);
	$(".dropContent").css("top",(coords[1]+19));
	$(".dropContent").toggle();
}

function toggleShareBar(coords) {
	newCoord = coords[0] - 152;
	$("#shareBox").css("left",newCoord);
	$("#shareBox").css("top", coords[1]);
	$("#shareBox").toggle("display");
	//$("#shareBox").show();
}
function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		} while (obj = obj.offsetParent);
	return [curleft,curtop];
	}
}

function queryStr(parameter) 
{
    hu = window.location.search.substring(1);
    gy = hu.split("&");
    for (i=0;i<gy.length;i++) 
    {
        ft = gy[i].split("=");
        if (ft[0] == parameter)
        {return ft[1];}
    }
}

function experienceScroll() {
	this.scrollWidth = $("#experienceScollHide").width();
	this.currentPane = 1;
	this.totalScrollPanes = $("#experienceScollHide .scrollItem").length;
	this.paneWidth = 170;
	this.totalScrollPanes = parseInt(this.totalScrollPanes) * this.paneWidth;
	
	this.paneCount = Math.ceil(this.totalScrollPanes / this.scrollWidth);
	
	this.scrollHide = $("#experienceScollHide");
	this.scrollWrap = $("#experienceScollHide #experienceScollWrap");
	$(this.scrollWrap).width(this.totalScrollPanes+"px");
	
	this.okToScroll = true;
	this.scrollLeftButton = $("#experienceScoller #scrollLeft");
	this.scrollRightButton = $("#experienceScoller #scrollRight");
	var self= this;
	$(this.scrollLeftButton).click(function() {
		self.scrollCarousel(1);
		return false;
	});
	$(this.scrollRightButton).click(function() {
		self.scrollCarousel(-1);
		return false;
	});
	
	if(this.paneCount > 1)
		$(this.scrollRightButton).show();
}
experienceScroll.prototype = {
	scrollCarousel: function(dir) {
		var cssDir= (dir<0) ? 'right':'left';
		var scrollWidth = this.scrollWidth;
		var scrollSpeed = this.scrollWidth;
		var scrollWrapLeft = $(this.scrollWrap).css("left");

		if(this.okToScroll == false) {
			return;
		}
		var newScrollWrapLeft = (parseInt(scrollWrapLeft) + (dir * scrollWidth));
		if(cssDir == "left") {
			if(this.currentPane <= 1) {
				return;
			} else {
				$(this.scrollRightButton).css("visibility","visible");
				var self = this;
				this.okToScroll = false;
				$(this.scrollWrap).animate({left: newScrollWrapLeft+"px"}, "slow", function() {
					self.okToScroll = true;
				});
				this.currentPane--;
			}
		}
		if(cssDir == "right") {
			if(this.currentPane >= this.paneCount) {
				return;
			} else {
				$(this.scrollLeftButton).css("visibility","visible");
				this.okToScroll = false;
				var self = this;
				$(this.scrollWrap).animate({left: newScrollWrapLeft+"px"}, "slow", function() {
					self.okToScroll = true;
				});
				this.currentPane++;
			}
		}
		
		this.checkCurrentPane(this.currentPane, this.paneCount);
	},
	checkCurrentPane: function(currentPane, paneCount) {
		if(currentPane == 1) {
			$(this.scrollLeftButton).css("visibility","hidden");
		} else if(currentPane == paneCount) {
			$(this.scrollRightButton).css("visibility","hidden");
		}
	}
	
}
sfHover = function() {
	var sfEls = document.getElementById("siteNavMain").getElementsByTagName("LI");
	for (var i=0; i<sfEls.length; i++) {
		sfEls[i].onmouseover=function() {
			this.className+=" sfhover";
		}
		sfEls[i].onmouseout=function() {
			this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
		}
	}
}
if (window.attachEvent) window.attachEvent("onload", sfHover);

// JavaScript Document
/* Promo COOKIES */
var Cookies = {
    init: function() {
        var allCookies = document.cookie.split('; ');
        for (var i = 0; i < allCookies.length; i++) {
            var cookiePair = allCookies[i].split('=');
            this[cookiePair[0]] = cookiePair[1];
        }
    },
    create: function(name, value, days) {
        if (days) {
            var date = new Date();
            date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
            var expires = "; expires=" + date.toGMTString();
        }
        else var expires = "";
        document.cookie = name + "=" + value + expires + "; path=/";
        this[name] = value;
    },
    erase: function(name) {
        this.create(name, '', -1);
        this[name] = undefined;
    }
};
function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

function eraseIt(name) {
    Cookies.erase(name);
}

function catchPromo() {
    var promoCode = window.location.search.substring(1);
    var matchvar = promoCode.search(/PromotionCode/);
    if (matchvar != -1) {
        Cookies.create('promocookie', promoCode, 1);
    }
}
//Use read cookie to verify the cookie
function readPromo() {
    //Check for cookie
    var promoValue = readCookie('promocookie');
    if (promoValue) {
        //If cookie is there add promo to buy links
        var promoLinks = $('.acceptPromo');
        for (i = 0; i < promoLinks.length; i++) {
            var currentLink = promoLinks[i].getAttribute('href');
			var matchPromo = currentLink.search(/PromotionCode/);
			//check to see if we already have a promotion code attached to the URL if we do skip checking for a cookie
			if (matchPromo == -1) {
				var matchvar = currentLink.search(/\?/);
				if (matchvar == -1) {
					var modifiedLink = currentLink + '?' + promoValue;
					promoLinks[i].setAttribute('href', modifiedLink);
				}
				else {
					var modifiedLink = currentLink + '&' + promoValue;
					promoLinks[i].setAttribute('href', modifiedLink);
				}
			}
        }
    }
}
//Trackpack Clocks and Ajax calls
function trackPackModule(){
	var thisRel = this.getAttribute('rel');
	$.get(thisRel, function(data){writePack(data)});
	return false;
}
function writePack(data){
	$('#trackFeature').html(data);
	$('#trackFeature').fadeIn('fast');
	setClock();
}
function defaultPacks(){
	$('#trackFeature').fadeOut('fast');
}
//Set event clock function
function setClock(){
	$(".countdownClock").each(function(i) {
		var dayUnit= $(".dayUnit:eq(0)", this).html();
		var hourUnit= $(".hourUnit:eq(0)", this).html();
		var minuteUnit= $(".minuteUnit:eq(0)", this).html();
		var secondUnit= $(".secondUnit:eq(0)", this).html();
		var d = (dayUnit)?dayUnit:'D';
		var h = (hourUnit)?hourUnit:'H';
		var m = (minuteUnit)?minuteUnit:'M';
		var s = (secondUnit)?secondUnit:'S';
				
		countdown($(this), i, d, h, m, s);
	});
}
function setProgramClock(){
	$("#miniCalTitle").each(function(i) {
		var dayUnit= $(".dayUnit:eq(0)", this).html();
		var hourUnit= $(".hourUnit:eq(0)", this).html();
		var minuteUnit= $(".minuteUnit:eq(0)", this).html();
		var secondUnit= $(".secondUnit:eq(0)", this).html();
		var d = (dayUnit)?dayUnit:'D';
		var h = (hourUnit)?hourUnit:'H';
		var m = (minuteUnit)?minuteUnit:'M';
		var s = (secondUnit)?secondUnit:'S';		
		
		programCountdown($(this), i, d, h, m, s);
	});
}
function calendarTabs(){
	$(".calendarContentDuring").each(function(i) {
		var context = $(this);		
		$(".genericTabs li a", context).click(function() {
			var ajaxUrl = $(this).attr("href");
			$(".calendarContentMain", context).html("<div id='expLoading'>loading</div>");
			$.ajax({
				type: "GET",url:ajaxUrl,cache:false,
				success: function(newSchedule){
					$(".calendarContentMain", context).animate({opacity: 'hide'}, "fast", function() {
						$(".calendarContentMain", context).html(newSchedule); 
						$(".calendarContentMain", context).animate({opacity: 'show'}, "fast");
					});
				}
			});
			$(".genericTabs li", context).removeClass("activeTab");
			$(this).parent().addClass("activeTab");
			return false;
		});
	});
}
function newsTabs(){
	$(".newsTabsModule").each(function(i) {
		var context = $(this);
		$(".genericTabs li a", context).click(function() {
			var ajaxUrl = $(this).attr("href");
			$(".newsTabsContentMain", context).html("<div id='expLoading'>loading</div>");
			$.ajax({
				type: "GET",url:ajaxUrl,cache:false,
				success: function(newSchedule){
					$(".newsTabsContentMain", context).animate({opacity: 'hide'}, "fast", function() {
						$(".newsTabsContentMain", context).html(newSchedule);
						$(".newsTabsContentMain", context).animate({opacity: 'show'}, "fast");
					});
				}
			});
			$(".genericTabs li", context).removeClass("activeTab");
			$(this).parent().addClass("activeTab");
			return false;
		});
	});
}
function vertTabs(){
	$(".vertTabsModule").each(function(i) {
		var context = $(this);
		$(".vertTabs li a", context).click(function() {
			var ajaxUrl = $(this).attr("href");
			$(".vertTabContentMain", context).html("<div class='expLoading'>loading</div>");
			$.ajax({
				type: "GET",url:ajaxUrl,cache:false,
				success: function(newVert){
					$(".vertTabContentMain", context).animate({opacity: 'hide'}, "fast", function() {
						$(".vertTabContentMain", context).html(newVert);
						$(".vertTabContentMain", context).animate({opacity: 'show'}, "fast");
					});
				}
			});
			$(".vertTabs li", context).removeClass("activeTab");
			$(this).parent().addClass("activeTab");
			return false;
		});
	});
}
function campingTabs(cont,writeTo){
	$(".campingModule").each(function(i) {
		var context = $(this);
		$(".genericTabs li a", context).click(function() {
			var ajaxUrl = $(this).attr("href");
			$(".campingMain", context).html("<div id='expLoading'>loading</div>");
			$.ajax({
				type: "GET",url:ajaxUrl,cache:false,
				success: function(newSchedule){
					$(".campingMain", context).animate({opacity: 'hide'}, "fast", function() {
						$(".campingMain", context).html(newSchedule);
						$(".campingMain", context).animate({opacity: 'show'}, "fast");
					});
				}
			});
			$(".genericTabs li", context).removeClass("activeTab");
			$(this).parent().addClass("activeTab");
			return false;
		});
	});
}
function newsletterSignUp() {
	$(".newsletterInput").each(function() {
		var parentForm = $(this).parent();
		var myId = this.getAttribute('id');
		$(parentForm).submit(function() {
			var newsletterField = document.getElementById(myId);
			var validateEmail = new RegExp(/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/);
			if(!validateEmail.test(newsletterField.value)) {
				alert("Please enter a valid email address");
				return false;
			}
		});
		var newsletterResetValue = this.value;
		$(this).focus(function() {
			if(this.value == newsletterResetValue)
				this.value="";
		});
		$(this).blur(function() {
			if(this.value == "")
				this.value=newsletterResetValue;
		});
	});
}
function twoPaneCarousel(){
	$("#prevSlide").click(function(){
	  $("#newscarousel ul").animate( { left:"0"}, 1000 )
	  document.getElementById('nextSlide').className = '';
	  document.getElementById('prevSlide').className = 'active';
	  return false;
    });
	$("#nextSlide").click(function(){
	  $("#newscarousel ul").animate( { left:"-636px"}, 1000 )
	  document.getElementById('prevSlide').className = '';
	  document.getElementById('nextSlide').className = 'active';
	  return false;
    });
}
function breakingNewsBar(){
	var wrapper = document.getElementById('wrapper');
	var newsHeight = $('#breakingNews').height();
	var wrapperHeight = $('#wrapper').height();
	var combinedHeight = (newsHeight + wrapperHeight + 20) + 'px';
	wrapper.style.height = combinedHeight;
}
/**
 * Loads a ribbon ad in to the .adHolder within the element passed.
 * Gets the url from the title attribute of the noscript within the element.
 * @returns {void}
 * @param {element} el The element we're performing all of the actions upon.
 * @see $(document).ready (called by)
 * @author Richard Rudzinski
 */
function getRibbonAd(el) {
	var adURL = $("noscript", el).attr("title");
	
	if(adURL == "" || typeof(adURL) == "undefined") {
		return;	
	}
	
	var tempData;
	document.writeln = function(data){
		tempData = data;
	};
	
	var adContainer = $(el);
	
	$.ajax({
		type: "GET",
		url: adURL,
		dataType: "script",
		success: function(){
			$(".adHolder",adContainer).html(tempData);
			tempData = "";
		}
	});

}
/*-- Wizard --*/
function wizard(){	
	//Reinit the radio buttons after load
	initWizAnswers();
	
	//$('.wizardForm').submit(
	$('.wizardForm').bind("submit",function(){
			var wizardForm = $(this).attr('id');
			var contentUrl = $('#'+wizardForm).attr('action');
			
			//Grab current page
			var currentPage = $('#'+wizardForm).attr('action');
			if(currentPage == '#' || currentPage == ''){
				//do nothing
			} else {
				//Append the last page
				$('#'+wizardForm).append('<input class="backValues" type="hidden" value="' + currentPage + '" />');
			}
			wizardParser(contentUrl,wizardForm);			
			return false;
	});
}
function initWizAnswers(){
	$('input', this).unbind('focus');
	
	$('input', this).bind("click",function(){
		var newAction = this.getAttribute('value');
		var wizForm = this.form.getAttribute('id');
		$('#'+wizForm).attr('action',newAction);
	});
}
function wizardReset(){
	$(".resetWizButton").bind("click", function(e){
      	//Grab variables
		var contentUrl = $(this).attr('href');
		var wizardForm = $(this).attr('rel');
		
		//Run Parser
		wizardParser(contentUrl,wizardForm);
		
		//Remove last pages
		//$('.backValues','#'+wizardForm).remove();
		
		//Kill the default action
		return false;
    });
}
function wizardBack(){
	$(".wizBackButton").bind("click", function(e){
      	//Grab variables
		//var contentUrl = $(this).attr('href');
		var wizardForm = $(this).attr('rel');
		
		//Remove last pages
		$('.backValues:last','#'+wizardForm).remove();

		if($('.backValues').length > 0){
			//Grab the last hidden field
			var contentUrl = $('.backValues:last').attr('value');
		} else {
			var contentUrl = $('.defaultWiz').attr('value');
		}

		//Run Parser
		wizardParser(contentUrl,wizardForm);
		
		//Kill the default action
		return false;
    });
}
function wizardParser(contentUrl,wizardForm){
		//alert(contentUrl + ' - ' + wizardForm);
		
		var qCount = $('#'+wizardForm).children('.backValues').length + 1;
		
		if(contentUrl == '#' || contentUrl == ''){
			alert('Please select an answer.'); 
		} 
		else { 
			$.getJSON(contentUrl, function(data){
			
			//Clear contents							   
			$('#'+wizardForm).children('.wizardWrite').empty();	
			
			//Clear the action for the validation
			$('#'+wizardForm).attr('action','#');
			
			//Text Answer Parse
			if(data.type == 'textAnswer'){
				//Start Array
				var tempArray = new Array();
					
				//Insert Question
				tempArray.push('<h5 class="wizardQ"><span>' + qCount + '.</span> ' + data.question + '</h5>');
				
				//Loop through to get answers and the answerValues
				$.each(data.answer,function(i){		 
					tempArray.push('<div class="questionRow">');
					tempArray.push('<input value="' + data.answerValue[i] + '" type="radio" name="answer" />');
					tempArray.push('<label>' + data.answer[i] + '</label>');
					tempArray.push('</div>');
				});
				
				//Place controls
				tempArray.push('<div class="wizardControls">');
				tempArray.push('<a class="wizBackButton" href="' + contentUrl + '" rel="' + wizardForm + '">Back</a>');
				tempArray.push('<button class="wizNextButton" type="submit">Next</button>');
				tempArray.push('</div>');
				
				//Insert Array into page
				$('#'+wizardForm).children('.wizardWrite').append(tempArray.join(""));
				
				//Reinit after load
				initWizAnswers();
				wizardBack();
			}
			// Result Parse
			if(data.type == 'result'){
				//Start Array and place result header in it.
				var tempArray = new Array();
				tempArray.push('<h5 class="resultsHdr">Results</h5>');
				
				//Place Result Chunk
				tempArray.push('<div class="resultBlock">');
				tempArray.push(data.result);
				tempArray.push('</div>');
				
				//Result links
				tempArray.push(data.resultLinks);
			
				//Place controls
				tempArray.push('<div class="wizardControls">');
				tempArray.push('<a class="resetWizButton" href="' + data.resetValue + '" rel="' + wizardForm + '">Take It Again</a>');
				tempArray.push('</div>');
			
				//Insert Array into page
				$('#'+wizardForm).children('.wizardWrite').append(tempArray.join(""));
				
				//Remove last pages
				$('.backValues','#'+wizardForm).remove();
				
				//Attach reset function
				wizardReset();
			}
			// Image Parse
			if(data.type == 'image'){
				var tempArray = new Array();
				
				//Insert Question
				tempArray.push('<h5 class="wizardQ"><span>' + qCount + '.</span> ' + data.question + '</h5>');
				
				//Loop through to get answers and the answerValues
				$.each(data.answer,function(i){		 
					tempArray.push('<div class="imgRadio">');
					tempArray.push(data.answer[i]);
					tempArray.push('<input value="' + data.answerValue[i] + '" type="radio" name="answer" />');
					tempArray.push('</div>');
				});
				
				//Place controls
				tempArray.push('<div class="wizardControls">');
				tempArray.push('<button class="btnSubmit" type="submit">Submit</button>');
				tempArray.push('</div>');
				
				$('#'+wizardForm).children('.wizardWrite').append(tempArray.join(""));
				
				//Reinit the radio buttons after load
				initWizAnswers();
			}
		});
	}
}

/*-- Quiz --*/
function quiz() {
    initQuizAnswers();

    $('.quizForm').unbind('submit');
    $('.quizForm').bind('submit', function() {
        var quizForm = $(this).attr('id');
        var contentUrl = $('#' + quizForm).attr('action');

        quizParser(contentUrl, quizForm);
        return false;
    });
}
function initQuizAnswers(){
	$('input', this).unbind('focus');
	
	$('input', this).bind("click",function(){
		var newAction = this.getAttribute('value');
		var quizForm = this.form.getAttribute('id');
		$('#'+quizForm).attr('action',newAction);
	});
}
function quizParser(contentUrl, quizForm) {

    //var qCount = $('#'+quizForm).children('.answered').length + 1;

    if (contentUrl == '#' || contentUrl == '') {
        alert('Please select an answer.');
    } else {
        // get data for next question
    $.getJSON(contentUrl, function(data) {

        // clear the current question
        $('#' + quizForm).children('.quizWrite').empty();

        if (data.type == 'textAnswer') {
            // parse JSON data and turn into HTML
            var tempArray = new Array();

            //Inform whether last question was answered correctly or not
            tempArray.push(data.lastAnswerCorrect);

            // write question
            tempArray.push('<h5 class="quizQ">' + data.question + '</h5>');

            // write answers
            $.each(data.answer, function(i) {
                tempArray.push('<div class="questionRow">');
                tempArray.push('<input value="' + data.answerValue[i] + '" type="radio" name="answer" />');
                tempArray.push('<label>' + data.answer[i] + '</label>');
                tempArray.push('</div>');
            });

            // write controls
            tempArray.push('<div class="quizControls">');
            tempArray.push('<button class="quizNextButton" type="submit">Submit</button>');
            tempArray.push('</div>');

            $('#' + quizForm).children('.quizWrite').append(tempArray.join(""));

            initQuizAnswers();
        }

        if (data.type == 'image') {
            var tempArray = new Array();

            //Inform whether last question was answered correctly or not
            tempArray.push(data.lastAnswerCorrect);

            //Insert Question
            tempArray.push('<h5 class="quizQ">' + data.question + '</h5>');

            //Loop through to get answers and the answerValues
            $.each(data.answer, function(i) {
                tempArray.push('<div class="imgRadio">');
                tempArray.push(data.answer[i]);
                tempArray.push('<input value="' + data.answerValue[i] + '" type="radio" name="answer" />');
                tempArray.push('</div>');
            });

            //Place controls
            tempArray.push('<div class="quizControls">');
            tempArray.push('<button class="btnSubmit" type="submit">Submit</button>');
            tempArray.push('</div>');

            $('#' + quizForm).children('.quizWrite').append(tempArray.join(""));

            //Reinit the radio buttons after load
            initQuizAnswers();
        }
        if (data.type == 'result') {
            var tempArray = new Array();

            //Inform whether last question was answered correctly or not
            tempArray.push(data.lastAnswerCorrect);

            tempArray.push('<h5>Results</h5>');
            tempArray.push('You answered ' + data.correct + ' of ' + data.possible + ' questions correctly.<br><br>');

            // formUrl is empty if the user didn't reach Minimum To Win
            tempArray.push(data.winOrLoseText);
            if (data.win != 'True') {
                $("#" + quizForm).attr("action", data.resetValue);
                tempArray.push('<button class="btnSubmit" type="submit">Try Again</button>');
            }

            //$('.answered', '#'+quizForm).remove();

            $('#' + quizForm).children('.quizWrite').append(tempArray.join(""));
        }
    });
    }
}

function tabScroller2() {
	$('#tabScroller2 li a').bind('click',function(e){
		$('#tabScroller2 li a').removeClass('currentTab');
		$(this).addClass('currentTab');
		var timelineContent = $(this).attr('href');
		var tabsContent = $('#tabScroller2').html();
		$('#tabScroller2 li a').removeAttr('href');
		$.get(timelineContent, function(data){
			$('#timelineContent').empty();
			$('#timelineContent').append('<ul id=\"tabScroller2\" class=\"genericTabs\">' + tabsContent + '</ul>');
			$('#timelineContent').append(data);
			if(document.getElementById('podcastLinks')) {
				$("#podcastLinks>li:last").addClass("lastItem");
			}
			tabScroller2();
		});
	});
}

function mycarousel_initCallback(carousel) {
	var startPos = $('#tabScroller .activeTab').attr('jcarouselindex');
	if (startPos > 6) {
		carousel.options.start = startPos;
	}
	return false;
}

function tabScroller() {
	
	jQuery('#tabScroller').jcarousel({
		scroll: 6,
		initCallback: mycarousel_initCallback
	});
	
	$('.genericTabs345345 li a').bind('click',function(e){
		var timelineContent = $(this).attr('href');
		$.get(timelineContent, function(data){
		  $('#timelineContent').fadeOut("slow",function(){
				$('body').empty();
		  		$('body').append(data);
			});
		  
		  $('#tabScroller').fadeIn("slow");
		  //.append(data);
		});
		
		//$('#genericTabs .active').removeClass('active');
		//$(this).addClass('active');
		
		if($('#shareBox').is(':visible')){
			//$('#shareBox').hidden();
			$("#shareBox").toggle("display");
		}
		
		return false;
	});
}

function timelineScroll() {
    jQuery('#timelineVert').jcarousel({
        vertical: true,
        scroll: 6
    });

	tooltip('#timelineVert li a');
	
	$('#timelineVert li a').bind('click',function(e){
		var timelineContent = $(this).attr('href');
		$.get(timelineContent, function(data){
		  $('#timelineContent').fadeOut("slow",function(){
				$('#timelineContent').empty();
		  		$('#timelineContent').append(data);										
			});
		  
		  $('#timelineContent').fadeIn("slow");
		  //.append(data);
		});
		
		$('#timelineVert .active').removeClass('active');
		$(this).addClass('active');
		
		if($('#shareBox').is(':visible')){
			//$('#shareBox').hidden();
			$("#shareBox").toggle("display");
		}
		
		return false;
	});

}
this.tooltip = function(attachTo){	
	/* CONFIG */		
		xOffset = 80;
		yOffset = 80;		
		// these 2 variable determine popup's distance from the cursor
		// you might want to adjust to get the right result		
	/* END CONFIG */
	
	$(attachTo).hover(function(e){											  
		this.t = this.title;
		this.title = "";
		//this.offset = $(e).offset();
		var posArray = findPos(this);
		$("body").append("<p id='tooltip'>"+ this.t +"</p>");
		$("#tooltip")
			.css("top",(posArray[1] - yOffset) + "px")
			.css("left",(posArray[0] + xOffset) + "px")
			.fadeIn("fast");		
    },
	function(){
		this.title = this.t;		
		$("#tooltip").remove();
    });	
	$("a.tooltip").mousemove(function(e){
		$("#tooltip")
			.css("top",(posArray[1] - yOffset) + "px")
			.css("left",(posArray[0] + xOffset) + "px")
	});			
};

var marqueeOffsetWidth;
var marquee; 
var bnewsw = $("#breakingNews").width();
var titlew = $("#bnewsTitle").width();
var marqueew = bnewsw - (titlew + 5);
$("#marqueeHolder").width(marqueew);
$("#marqueeHolder").css("margin-left", titlew+5 + "px");

function setupTicker() {
	if(document.getElementById("marquee")) {
		marquee = document.getElementById("marquee");
		marquee.style.left = 0;
	}
	if(document.getElementById("marqueeText")) {
		marqueeOffsetWidth = document.getElementById("marqueeText").offsetWidth;
		}
	if(document.getElementById("marquee")) {
		setTimeout("startTicker()",3000);
	}
} 

function startTicker() {
	lefttime=setInterval("scrollTicker()", 50);
}

function scrollTicker() {
	if(marquee) {
		marquee.style.left = (parseInt(marquee.style.left) > (-10 - marqueeOffsetWidth)) ? parseInt(marquee.style.left) - 3 + "px" : marqueew + 10 + "px";
	}
} 

window.onload=function(){
	
	if(document.getElementById("marqueeText")){
		if(document.getElementById("marqueeText").offsetWidth > 725) {
			
			setupTicker();
		}
	}
}
