var addthis_config = {
    username: 'pbsteachers',
    ui_click: false,
    ui_offset_top: -19,
    ui_offset_left: 0
};

$(document).ready(function(){
    //============================================
    // Global functions
    //============================================
    //delay
    $.fn.delay = function(time, callback){
        // Empty function:
        jQuery.fx.step.delay = function(){};
        // Return meaningless animation, (will be added to queue)
        return this.animate({delay:1}, time, callback);
    }
    //setWidth
    $.fn.setWidth = function(size) { 
          var bodyWidth = $(window).width();
          var frameWidth = (parseInt(bodyWidth - size) + 'px');       
        return $(this).css("width",frameWidth).addClass("sized");
    };
    //setHeight
    $.fn.setHeight = function(size) { 
      var bodyHeight = $(window).height();
      var frameHeight = (parseInt(bodyHeight - size) + 'px');       
    return $(this).css("height",frameHeight);
    };
    //removeWidth
    $.fn.removeWidth = function(size) {     
        return $(this).removeClass("sized").css("width","100%");
    };


    //============================================
    // Mark share buttons.
    //============================================
    if (typeof(addthis) != 'undefined') {
        addthis.button(".btn-mini-share");
    }

        
    //============================================
    // Wrap the insides of blockquotes
    //============================================
    $("blockquote", $("#content")).wrapInner("<span class='blockquote-inner'></span>");
    
    //============================================
    // Input focus and blur
    //============================================
    $("input, textarea", $("form")).focus(function(){
        $(this).addClass("focus");
        $(this).parents(".form-field").addClass("cur");
    });
    $("input, textarea", $("form")).blur(function(){
        $(this).removeClass("focus");
        $(this).parents(".form-field").removeClass("cur");
    });
        
    //============================================
    // Promo carousel
    //============================================
    $('.promo-browse', $("#content .promo-carousel")).css('display','block');

    $('.col-main .promo-carousel-inner', $("#content")).before('<ul class="promo-nav">')
        .cycle({
        cleartype: 0,
        timeout: 0,
        speed: 500,
        pager: '.promo-nav',
        pagerEvent: 'click',
        next:   '.col-main .promo-next', 
    prev:   '.col-main .promo-prev',
        pagerAnchorBuilder: function(idx, slide) {
            return '<li class="promos-'+ (idx + 1) +'-nav"><a href="#">'  + (idx 
            + 1) + '</a></li>';
        }
    });
    
    $('.col-aside .promo-carousel-inner', $("#content"))
        .cycle({
        cleartype: 0,
        timeout: 0,
        speed: 500,
        pagerEvent: 'click',
        next:   '.col-aside .promo-next', 
    prev:   '.col-aside .promo-prev'
    });
        
    //============================================
    // Feature Well
    //============================================
    var featureNavImg = $("#feature-nav li img")
    $(featureNavImg).css({
        'left' : "0px"
        });
        
    $("#feature-nav a", $("#feature-well")).hover(function(){
          $(featureNavImg).stop(true,true).css("left","0px")
        }, function(){
          $(featureNavImg).stop(true,true).css("left","0px")
        });
    
    
    // Look further down the document for "DescriptionFadeIn" and "DescriptionFadeOut". 
    // Also, have a great day!
    $('#feature-well-features', $("#feature-well"))
        .cycle({
        cleartype: 1,
        timeout: 7500,
        speed: 250,
        pager: '#feature-nav',
        pagerEvent: 'mouseover',
        after: descriptionFadeIn,
        before: descriptionFadeOut,
        pagerAnchorBuilder: function(idx, slide) { // return sel string for existing anchor 
            return '#feature-nav li:eq(' + (idx) + ') a'; } 
    });
        
    //============================================
    // Tooltips
    //============================================
        $(".tooltip-object", $("#content")).hover(function(){
            $(this).find(".tooltip").stop(true,true).css("display","block").css("opacity","0.01").fadeTo(500,1);
        }, function(){
            $(this).find(".tooltip").stop(true,true).fadeTo(500,1).fadeTo(500,0.01);            
        });
        
        
    //============================================
    // Header Nav
    //============================================
    $("#nav > li, #jun09-nav > li, #nav-other-sites .dropdown, #jun09-nav-other-sites .dropdown").hover(
        function(){
            $("#nav ul:visible, #nav-other-sites ul:visible, #jun09-nav ul:visible, #jun09-nav-other-sites ul:visible").stop(true,true).hide();
            $("#nav .sfHover, #nav-other-sites .sfHover, #jun09-nav .sfHover, #jun09-nav-other-sites .sfHover").removeClass("sfHover")
            $(this).find("ul").fadeIn("fast");
            $(this).addClass("sfHover")
        }, function(){
            $(this).find("ul").stop(true,true).fadeTo(500,1).fadeOut("fast", function(){
                $("#nav .sfHover, #jun09-nav .sfHover").removeClass("sfHover");
                $("#nav-other-sites .sfHover, #jun09-nav-other-sites .sfHover").removeClass("sfHover");
            });
    });
            
            
    //============================================
    // TV Schedule expander
    //============================================
    $("#tvschedules .programlist, #tvschedules .backtotop").hide();
    var tabRule = $("#tvschedules .tabrule")
    $("#tvschedules .tabrule").addClass("closed");
    $(tabRule).click(function(){
        if ($(this).hasClass("closed")) {
            $(this).removeClass("closed").next(".programlist").fadeIn("fast").next(".backtotop").fadeIn("fast");
        } else {
            $(this).addClass("closed").next(".programlist").fadeOut("fast").next(".backtotop").fadeOut("fast");
        }
    })
    $("#tvschedules .nav a").click(function(){
        var thisTarget = $(this).html().toLowerCase();
        $(".closed a[name="+ thisTarget +"]").parents(".tabrule").removeClass("closed").next(".programlist").fadeIn("fast").next(".backtotop").fadeIn("fast");
    });


    //============================================
    // Resource iFrame controls
    //============================================
    var resourceFrame = $('iframe#resource-frame')

    $(resourceFrame).load(function(){
        $(this).setHeight(60);
   });

    $(window).resize(function(){ 
      $(resourceFrame).setHeight(60);
        $("#resource-comment:visible").setHeight(60);
      $("#resource-save:visible").setHeight(60);
    
      if ($(resourceFrame).hasClass("sized")) {
          $(resourceFrame).delay(1000, function(){
          if ($(resourceFrame).hasClass("sized")) {
                $(resourceFrame).setWidth(275);
              }
          }); }
    });
    $("#btn-save").click(function(){
        $("#resource-comment:visible").fadeOut();
        $("#resource-save:hidden").fadeIn();
        $(resourceFrame).setWidth(275);
        $("#resource-save").setHeight(60);
        return false;
    })
    $("#btn-comment").click(function(){
        $("#resource-save:visible").fadeOut();
        $("#resource-comment:hidden").fadeIn();
        $(resourceFrame).setWidth(275);
        $("#resource-comment").setHeight(60);
        return false;
    })
    $(".btn-close").click(function(){
        $(this).parents(".resource-side").fadeOut();
        $(resourceFrame).removeWidth();
        return false;
    })
    

    //============================================
    // Stars
    //============================================
    $(".stars a", $("#content")).click(function(){
        $(this).parents(".stars").find(".cur").removeClass("cur");
        $(this).addClass("cur");
        return false;
    });


    //============================================
    // Module collapse
    //============================================
    //$("div.module:not('.layout-home #module-dashboard')", $("#content .col-aside")).each(function(){
    $("div.module:not('.layout-home')", $("#content .col-aside")).each(function(){
          var moduleId = $(this).attr("id");
          if (moduleId == '' || moduleId == null) return;
          var cookieState = $.cookie(''+ moduleId +'')
          if (cookieState == "collapsed"){
              $(this).addClass("collapsed");
          }
    })


    //============================================
    // Collapsing action
    //============================================
    $(".collapsible .header h3", $("#content .col-aside")).click(function(){
        var parentModule = $(this).parents(".module");
        var moduleId = $(parentModule).attr("id");
        if ($(parentModule).hasClass("collapsed")){
          $(parentModule).removeClass("collapsed");
          var moduleId = $(this).parents(".module").attr("id");
          $.cookie(''+ moduleId +'', 'uncollapsed', { expires: 9999 });
        } else {
          $(parentModule).addClass("collapsed");
          $.cookie(''+ moduleId +'', 'collapsed', { expires: 9999 });
        }
    })


    //============================================
    // Resource Filters
    //
    // Filters the displayed resources on a
    // classroom page.
    //============================================
    $("form.form-filter-resources select, form.form-filter-discussions select").change(function() {
        var form = $(this).parents("form").get(0);
        form.submit();
    });


    //============================================
    // Clear On Focus
    //
    // Tie 'clear-on-focus' class to clear the
    // input element on focus if it is set to
    // a default value.
    //============================================
    $("form input.clear-on-focus").focus(function() {
        var val = $(this).val();
        if (val == 'Search within results') $(this).val('');
    });
    $("textarea.clear-on-focus").focus(function() {
        var val = $(this).html();
        if (val.indexOf('Enter your comment about ') != -1) $(this).html('');
    });
    $("form.resource-comment-form").submit(function() {
            var html = $(this).find("textarea[name=text]").val();
            if (html == '' || html.indexOf('Enter your comment about ') != -1) {
                alert("Please enter a comment.");
                return false;
            }
            return true;
    });


    //============================================
    // Rate a resource.
    //
    // AJAX action to rate a resource.
    //============================================
    $("a.rate-resource-link").click(function() {
            function _cb_rate_resource(ul) {
                var ul = ul;
                return function(data, textStatus) {
                    $("#get-average-rating").html(data.average_rating);
                    $("#get-ratings-count").html(data.ratings_count)
                    $("#get-average-rating").attr('class', 'stars ' + data.average_rating_css_class);
                    // update the ratings stars...
                    $(ul).attr('class', 'stars ' + data.user_rating_css_class);
                }
            }
            // grab the url
            var url = $(this).attr('href');
            var score = $(this).html();
            $.post(url, {score: score}, _cb_rate_resource($(this).parents('ul:eq(0)')), 'json');
            return false;
    });


    //============================================
    // Bookmark a Resource
    //============================================
    $("a.display-save-resource-login").click(function(eventObject) {
            alert("Sign up or log in to save this resource.");
            eventObject.preventDefault();
    });
    $(".login-to-rate-popup").click(function(eventObject) {
            alert("Sign up or log in to rate or comment on this resource.");
            eventObject.preventDefault();
        });
    $("a.display-save-resource").click(function(eventObject) {
            var dialog_options = {
                title: 'Save Resource',
                modal: true,
                width: 600
            };
            $(this).parent().find("div.save-resource").dialog(dialog_options);
            eventObject.preventDefault();
    });
    $(".save-resource input[type=button]").click(function(eventObject) {
            // close the dialog the button is in.
            $(this).parents(".save-resource").dialog("close");
    });

    // Use a closure to construct the save function for the supplied form.
    function make_save_resource_form_success(form_element, article_resource_element) {
        var form = form_element;
        var article_resource = article_resource_element;
        return function save_resource_form_success(json_response, status_text) {
            if (json_response.success) {
                $(form).children("div.error-message").css('display', 'none');
                $(form).find(".form-field p.help").html("").css('display', 'none');
                $(form).parents("div.save-resource").dialog("close");
                if (article_resource) {
                    $(article_resource).find("div.success-message").css('display', 'block');
                } else {
                    $("div.save-resource-success").css('display', 'block');
                }
            } else {
                // Form had errors, display them now.
                // clear out any existing error messages.
                $(form).find(".form-field p.help").html("").css('display', 'none');
                for (var i in json_response.errors) {
                    $(form).children("div.error-message").css('display', 'block');
                    $(form).find(".form-field label[for="+i+"]").siblings("p.help").html(json_response.errors[i]).css('display', 'block');
                }
            }
        };
    };

    $("div.save-resource form").each(function(index, dom_element) {
                // Construct a callback function as a closure containing
                // the current form, allowing control of form from the
                // callback.
                $(this).ajaxForm({
                        success: make_save_resource_form_success(dom_element, $(dom_element).parents("div.article-resource").get(0)),
                        dataType: 'json'
                });
    });

    function make_save_resource_iframe_callback(form_element) {
        var form = form_element;
        return function(json_response, status_text) {
            if (json_response.success) {
                $(form).children("div.error-message").css('display', 'none');
                $(form).find(".form-field p.help").html("").css('display', 'none');
                $("#resource-save div.save-resource-success").css('display', 'block');
            } else {
                // Form had errors, display them now.
                // clear out any existing error messages.
                $(form).find(".form-field p.help").html("").css('display', 'none');
                for (var i in json_response.errors) {
                    $(form).children("div.error-message").css('display', 'block');
                    $(form).find(".form-field label[for="+i+"]").siblings("p.help").html(json_response.errors[i]).css('display', 'block');
                }
            }
        };
    };
    $("#resource-save form").each(function(index, dom_element) {
            // Construct a callback for displaying the success message div.
            $(this).ajaxForm({
                    success: make_save_resource_iframe_callback(dom_element),
                    dataType: 'json'
            });
    });

    //============================================
    // ActivityLog Latest
    //============================================
    function _rename_link() {
        var display = $(this).css('display');
        var a = $(this).parents(".activitylog-latest").find(".activitylog-show-more");
        if (display == 'block') {
            $(a).html("&laquo;&nbsp;Hide");
        } else {
            $(a).html("Show more&nbsp;&raquo;");
        }
    }
    $(".activitylog-latest .activitylog-show-more").click(function(evt) {
            $(this).parents(".activitylog-latest").find(".activitylog-hidden").slideToggle('normal', _rename_link);
            evt.preventDefault();
    });
});

// These animations trigger when the feature-well is cycling.
function descriptionFadeIn(curr, next, opts) { 
  var index = opts.currSlide;
  $("#feature-nav li:eq("+ index +")").siblings().find("img").stop(true,true).css({
    'left' : "0px"
    });
  $("#feature-nav li:eq("+ index +") img").delay(50, function(){
      $(this).animate({
          left: '-10px'
        }, 200);
  });
}
function descriptionFadeOut(curr, next, opts) { 
      var index = opts.currSlide;
      $("#feature-nav li:eq("+ index +") img").css({
      'left' : "0px"
    });
}
