$(document).ready(function () {
    //initOpenClose();

    BindWatermarks();

    var CurrentUrl = window.location.pathname.toLowerCase();
    if (CurrentUrl != "/") {
        $("#nav a, .top-nav a").each(function () {
            if ($(this).attr("href").toLowerCase().indexOf(CurrentUrl) > -1) {
                $(this).parent().addClass("active");
            }
        });
    }

    //hook up all video / podcast links
    $(".btn-video a, .btn-audio a, .banner .v, .banner .a").click(function (e) {
        e.preventDefault();
        var AssetID = $(this).attr("href").replace("#", "");

        //if asset is widescreen
        var Widescreen = "";
        if ($(this).hasClass("wsTrue")) {
            Widescreen = "Lg";
            $(".media-popup").addClass("media-popup-ws");
        }
        else {
            $(".media-popup").removeClass("media-popup-ws");
        }

        $(".media-popup").append("<iframe id='container_media' src='/ajaxcontent/" + Widescreen + "MediaAsset.aspx?ID=" + AssetID + "' scrolling='no' frameborder='0'></iframe>");

        InitPopup(".media-popup", ".btn-close2 a");
    });

    $("#subscribe-txt")
        .keypress(function (e) {
            if (e.which == 13) {
                $("#subscribe-btn").trigger("click");
                return false;
            }
        })
        .focus(function () {
            $("#subscribe-t").html("tok15!");
        });

    $("#subscribe-btn").click(function (e) {
        e.preventDefault();
        var val = $("#subscribe-txt").val();
        if (IsValidEmail(val)) {
            $.ajax({
                type: "POST",
                url: "/csg-ws.asmx/InsertSubscriber",
                data: "{'Email' : '" + val + "', " +
                        "'t' : '" + $("#subscribe-t").html() + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (result) {
                    //pageTracker._trackPageview("Order Form - Form Submitted");
                    InitPopup(".popup", ".btn-close a");
                }
            });
        }
    });

    //check for asset in querystring..
    var qval = GetQueryStringValue("asset");
    if (qval != "") {
        $(".media-popup").append("<iframe id='container_media' src='/ajaxcontent/MediaAsset.aspx?ID=" + qval + "' scrolling='no' frameborder='0'></iframe>");

        InitPopup(".media-popup", ".btn-close2 a");
    }


    // Track poll submissions in Google Analytics
    $(".pds-votebutton").each(function () {
        $(this).bind("click", function () {
            if ($(".pds-radiobutton:checked").length > 0) {
                // Get parent poll ID
                var parentPollDivs = $(this).parents().filter(".PDS_Poll");
                if (parentPollDivs.length > 0) {
                    // Track a poll event in GA
                    pageTracker._trackPageview("/pollsubmitted/" + $(parentPollDivs[0]).attr("id"));
                    return true;
                }
            }
            return false;
        });
    });

    $("a").each(function () {
        var href = $(this).attr("href");
        if (href != null) {
            href = href.toLowerCase();
            if (href.indexOf(".mp3") > -1 || href.indexOf(".pdf") > -1) {
                var DownloadType = ".mp3";
                if (href.indexOf(".pdf") > -1) {
                    DownloadType = ".pdf";
                }
                $(this).click(function () {
                    _gaq.push(['_trackEvent', 'Downloads', DownloadType, href]);
                });
            }
        }
    });


    //hover events for ie6
    var IE6 = (navigator.appVersion.indexOf("MSIE 6") > 0) ? true : false;
    if (IE6) {
        $("#nav > li").hover(
            function () {
                $(this).find("ul").show();
            },
            function () {
                $(this).find("ul").hide();
            });
    }

});

// Open-Close init
function initOpenClose() {
    $('div.box-text').OpenClose({
        activeClass: 'active',
        opener: 'a.opener',
        slider: 'div.slide',
        slideSpeed: 400
    });
    $('.list-quest li').OpenClose({
        activeClass: 'active',
        opener: '.more a',
        slider: 'div.slide',
        slideSpeed: 400
    });
}

function InitPopup(PopupSelectorStr, CloseButtonSelectorStr) {
    $(window).resize(function () {
        LightPlace();
    });
    $(window).scroll(function () {
        LightPlace();
    });
    var _duration = 400;
    var _light = $(PopupSelectorStr);
    if (!$.browser.msie) {
        _light.css({ opacity: 0 }).hide();
    }
    var _lay = $('<div class="overlay"></div>').css({ opacity: 0 }).appendTo($('body')).hide();
    var _close = $(CloseButtonSelectorStr);

	//position modal...
    var WindowScroll = $(window).scrollTop();
    $(PopupSelectorStr).css("top", (WindowScroll + 50));
    LightPlace();
    if ($.browser.msie) {
        _light.show();
    }
    else {
        _light.show().animate({ opacity: 1 }, { queue: false, duration: _duration });
    }
    _lay.show().animate({ opacity: 0.5 }, { queue: false, duration: _duration });
    _lay.click(function () {
        $("#container_media").remove();
        if ($.browser.msie) {
            _light.hide();
        }
        else {
            _light.animate({ opacity: 0 }, { queue: false, duration: _duration, complete: function () { $(this).hide(); } });
        }
        _lay.animate({ opacity: 0 }, { queue: false, duration: _duration, complete: function () { $(this).hide(); } });
        return false;
    });
    _close.click(function () {
        $("#container_media").remove();
        if ($.browser.msie) {
            //_light.hide();
			_light.animate({ opacity: 0 }, { queue: false, duration: _duration, complete: function () { $(this).hide(); } });
        }
        else {
            _light.animate({ opacity: 0 }, { queue: false, duration: _duration, complete: function () { $(this).hide(); } });
        }
        _lay.hide();
        return false;
    });

};

function LightPlace() {
    var _light = $('.popup');
    var _lay = $('div.overlay');
    var _w = _light.width();
    var _h = _light.height();

    if (window.innerHeight) { var _wx = window.innerWidth; var _wy = window.innerHeight; }
    else { _wx = document.documentElement.clientWidth; _wy = document.documentElement.clientHeight; };
    if ($('body').height() < _wy) {
        _lay.css({ height: _wy })
    }
    else {
        _lay.css({ height: $('body').height() });
    };
    _lay.css('width', $('body').outerWidth());
    _light.css({ left: (_wx - _w) / 2, top: (_wy - _h) / 2 + $(document).scrollTop() });
};



// Open-Close plugin
jQuery.fn.OpenClose = function (_options) {
    // default options
    var _options = jQuery.extend({
        activeClass: 'active',
        opener: '.opener',
        slider: '.slide',
        slideSpeed: 400,
        animStart: false,
        animEnd: false,
        event: 'click'
    }, _options);

    return this.each(function () {
        // options

        var _holder = jQuery(this);
        var _slideSpeed = _options.slideSpeed;
        var _activeClass = _options.activeClass;
        var _opener = jQuery(_options.opener, _holder);
        var _slider = jQuery(_options.slider, _holder);
        var _animStart = _options.animStart;
        var _animEnd = _options.animEnd;
        var _event = _options.event;

        if (_slider.length) {

            if (_holder.hasClass(_activeClass)) _slider.css({ display: 'block' });
            else _slider.css({ display: 'none' });

            _opener.bind(_event, function () {
                if (!_slider.is(':animated')) {
                    if (typeof _animStart === 'function') _animStart();
                    if (_holder.hasClass(_activeClass)) {
                        _holder.removeClass(_activeClass);
                        _slider.slideUp(_slideSpeed, function () {
                            if (typeof _animEnd === 'function') _animEnd();
                        });
                    }
                    else {
                        _holder.addClass(_activeClass);
                        _slider.slideDown(_slideSpeed, function () {
                            if (typeof _animEnd === 'function') _animEnd();
                        });
                    }
                }
                return false;
            });
        }
    });
}

function BindWatermarks() {
    $(".watermark").each(function () {
        $(this).focus(function () {
            if (this.value == this.title) {
                this.value = "";
            }
        });
        $(this).blur(function () {
            if (this.value == "") {
                this.value = this.title;
            }
        });
    });
}

function IsValidEmail(str) {
    if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(str)) {
        return (true);
    }
    return (false);
}

function GetQueryStringValue(Key) {
    var QStrArray = document.location.search.substring(1).split("&");
    for (var i = 0; i < QStrArray.length; i++) {
        var tempArray = QStrArray[i].split("=");
        if (tempArray[0] == Key) {
            return tempArray[1];
        }
    }

    return "";
}

function setCookie(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=/";
}

function getCookie(c_name) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) c_end = document.cookie.length;
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return "";
}


function TrackEvent(Category, Val1, Val2) {
    //_gaq.push(['_trackEvent', Category, Val1, Val2]);
} 

/*** PROGRAM & RESOURCES ***/
program_resources_docready = function () {
    $(".ddlcategory").change(function () {
        var val = $(this).val();
        FilterList(val);
        ChangeTab(val);
    });
    $("#tab-nav a").click(function (e) {
        e.preventDefault();
        this.blur();
        if (!$(this).parent().hasClass("on")) {
            $("#tab-nav .on").removeClass("on");
            $(this).parent().addClass("on");
            var val = this.className;
            FilterList(val);
            $(".ddlcategory").val(val);
        }
    });
    var Category = GetQueryStringValue("c");
    if (Category != "") {
        $("." + Category).trigger("click");
    }
    $("#askKGroupSideBox .ask-btn").click(function (e) {
        this.blur();
        e.preventDefault();
        var val = $("#askKGroupSideBox textarea").val();
        if (val != "") {
            $("#askKGroupSideBox .errorMsg").hide();
            $(this).fadeTo(200, 0.5);
            $.ajax({
                type: "POST",
                url: "/csg-ws.asmx/InsertQuestion",
                data: "{'Question' : '" + val + "', " +
"'Category' : '', " +
"'t' : 'tok25!'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (result) {
                    $("#askKGroupSideBox .ask-btn").fadeTo(200, 1);
                    $("#askKGroupSideBox textarea").val("");
                    InitPopup(".popup", ".btn-close a");
                }
            });
        }
        else {
            $("#askKGroupSideBox .errorMsg").show();
        }
    });
}




function FilterList(val) {
    $(".programs-promotions-assets .NotFound").slideUp(300);
    console.log(val);
    if (val == "") {
        $(".asset-item").slideDown(300);
        $(".box-title").show();
        TrackEvent("Program & Resources Tab Change", "all", "");
    }
    else {
        $(".box-title").hide();
        var Items = $(".programs-promotions-assets ." + val);
        if (Items.length > 0) {
            Items.slideDown(300);
            $(".asset-item:not(." + val + ")").slideUp(300);
        }
        else {
            $(".asset-item").slideUp(300);
            $(".programs-promotions-assets .NotFound").slideDown(300);
        }
        TrackEvent("Program & Resources Tab Change", val, "");
    }
}
function ChangeTab(val) {
    $("#tab-nav .on").removeClass("on");
    if (val == "") {
        $(".All").parent().addClass("on");
    }
    else {
        $("#tab-nav ." + val).parent().addClass("on");
    }
} 
