// change jQuery to use $j so as to not conflict with prototype
var $j = jQuery.noConflict();

// cookie plugin
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};
// end-cookie plugin


function hideInsight(insightId) {
    //alert(insightId);
    $j("#iid" + insightId).hide();
    $j("#piid" + insightId).show();
}

$j(document).ready(function() {

    // hide stuff
    $j("#popover").hide();
    $j("#share_form").hide();
    $j("#share_email").hide();

    $j(".loadpop").click(function() {

        //get the url
        var thisUrl = $j(this).attr('href');

        // get the topOffset
        var popTopOffset = $j(this).offset().top + 5;
        var popLeftOffset = $j(this).offset().left;

        // get the JSON data
        $j.getJSON("ajax/json-" + thisUrl,
            function(data){

              var pophtml = "<div style='float:right;cursor:pointer;'>[x]</div>";
              pophtml += data.pophtml;
              popwidth = data.width;
              // show the popover
              $j("#popover").html(pophtml)
              .css({"background": "#eeeeee","border": "2px solid #aec6e0", "margin":"10px", "padding":"10px"})
              .css({"top":popTopOffset})
              .css({"left":popLeftOffset})
              .css({"width":popwidth})
              ;
            });

        // toggle the popover
        $j("#popover")
        .toggle()
        ;

        this.blur();
        return false;
    })
    .css({cursor:"pointer"})
    ;

    // if they click on the popover itself, it will toggle
    $j("#popover").click(function() {
        $j("#popover").toggle();
    })
    ;

    // collapse/expand ALL insights
    $j("#c_insights").toggle(
        function() {
            $j(".insight").slideUp();
            $j(".h_insight").children().attr("src","images/arrow-orange-rt.gif");
            return false;
        }
        ,
        function() {
            $j(".insight").slideDown();
            $j(".h_insight").children().attr("src","images/arrow-orange-dn.gif");
            return false;
        }
    )
    .css({cursor:"pointer"})
    ;

    // toggle insight when you click on the header
    $j(".h_insight").click(
        function() {
            var insightid = "#insight" + $j(this).attr("insightid");
            $j(insightid).slideToggle();

            if ($j(this).children().attr("src") == "images/arrow-orange-dn.gif") {
                $j(this).children().attr("src","images/arrow-orange-rt.gif");
            } else {
                $j(this).children().attr("src","images/arrow-orange-dn.gif");
            }
            return false;
        }
    )
    .css({cursor:"pointer"})
    ;

    // "add your comment" if you're not logged in
    $j(".lc2").click(
        function() {

            var insightid = $j(this).attr("insightid");  // get the insight id to apply this comment to.
            var icurl = $j(this).attr("href");

            var url = window.location.pathname + window.location.search; // can't just use window.location cuz then we get the hash
            url += "#lc" + insightid; // get this url to pass to comment_submit

            // get the topOffset
            var popTopOffset = $j(this).offset().top + 15;
            var popLeftOffset = $j(this).offset().left - 350;

            var pophtml = "<p style='padding: 15px 10px;font-size:18px;'>Please <a href='" + icurl + "'>visit the Insight Community</a> to add your comment.</p>";

            // build the form
            $j("#popover")
            .html(pophtml)
            ;

            // show the popover
            $j("#popover")
            .show()
            .css({"background": "#ffffbb","border": "2px solid #aec6e0", "margin":"10px", "padding":"10px", "width":"500px"})
            .css({"top":popTopOffset})
            .css({"left":popLeftOffset})
            ;

            this.blur();
            return false;
        }
    )
    .css({cursor:"pointer"})
    ;

    // profile tabs
    $j("#t_comments").click(
        function() {
            $j("#t_comments").addClass("on");
            $j("#t_submitted").removeClass("on");
            $j("#t_written").removeClass("on");

            $j("#p_comments").show();
            $j("#p_submitted").hide();
            $j("#p_written").hide();
            return false;
        }
    )
    .css({cursor:"pointer"})
    ;

    $j("#t_submitted").click(
        function() {
            $j("#t_comments").removeClass("on");
            $j("#t_submitted").addClass("on");
            $j("#t_written").removeClass("on");

            $j("#p_comments").hide();
            $j("#p_submitted").show();
            $j("#p_written").hide();

            return false;
        }
    )
    .css({cursor:"pointer"})
    ;

    $j("#t_written").click(
        function() {
            $j("#t_comments").removeClass("on");
            $j("#t_submitted").removeClass("on");
            $j("#t_written").addClass("on");

            $j("#p_comments").hide();
            $j("#p_submitted").hide();
            $j("#p_written").show();
            return false;
        }
    )
    .css({cursor:"pointer"})
    ;

    // tiers check for size selected
    $j("#tiersform").submit(function() {
        if ($j("#tiersize").val() == "") {
            alert ("Please choose a Size before clicking on the Buy button.");
            return false;
        }
        return true;
    });
    
    // techdirt reply-comment popup
    $j(".cmtrp").click(function () {
        $j("#replycid").attr("value", $j(this).attr("cid"));
        $j("#replysubject").attr("value", "Re: " + $j(this).attr("subject")); 
        
        // disable the regular comment form
        $j(".new_comment_input").attr("disabled", "disabled");

        var position = $j(this).position();
        $j("#cmmt_form").css('left', position.left);
        $j("#cmmt_form").css('top', position.top + 23);
        $j("#cmmt_form").show();

        return false;
    });
    
    $j(".cmmt_close").click(function () {
        $j("#cmmt_form").hide();
        // enable the regular comment form
        $j(".new_comment_input").removeAttr("disabled");
        return false;
    });
    
    // sharethis popup
    $j(".share_link").click(function () {        
    
        $j("#share_delicious").attr("href", "http://del.icio.us/post?url=" + $j(this).attr("ddurl") + "&title=" + $j(this).attr("ddurl"));
        $j("#share_digg").attr("href", "http://digg.com/submit?phase=2&url=" + $j(this).attr("ddurl") + "&title=" + $j(this).attr("ddurl"));
        $j("#share_facebook").attr("href", "http://www.new.facebook.com/share.php?u=" + $j(this).attr("ddurl"));
        $j("#share_reddit").attr("href", "http://reddit.com/submit?url=" + $j(this).attr("ddurl") + "&title=" + $j(this).attr("ddurl"));
        $j("#share_stumbleupon").attr("href", "http://www.stumbleupon.com/submit?url=" + $j(this).attr("ddurl") + "&title=" + $j(this).attr("ddurl"));
        
        $j("#share_post_id").attr("value", $j(this).attr("sid"));
        
        var position = $j(this).position();
        $j("#share_form").css('left', position.left);
        $j("#share_form").css('top', position.top + 23);
        $j("#share_form").show();

        return false;
    });    
    
    $j(".share_close").click(function () {
        $j("#share_form").hide();
        return false;
    });
    
    $j("#share_tab1").click(function () {
        $j("#share_tab1").addClass("selected");
        $j("#share_tab2").removeClass("selected");
        $j("#share_email").hide();
        $j("#share_social").show();
    });    
    
    $j("#share_tab2").click(function () {
        $j("#share_tab1").removeClass("selected");   
        $j("#share_tab2").addClass("selected"); 
        $j("#share_social").hide();
        $j("#share_email").show();
    });
    
    // top promo close
    $j("#topclose").click(function () {
        $j("#toppromo").hide();
        $j("#top").css({margin:0});
        //alert($j("#toppromo").attr('name'));
        $j.cookie("toppromoclose", $j("#toppromo").attr('name'), { expires: 14 });
        return false;    
    })
    .css({cursor:"pointer"})
    ;
    
    // close the top promo if the cookie matches the promo name
    if ($j.cookie("toppromoclose") == $j("#toppromo").attr('name')) { 
        $j("#toppromo").hide();
        $j("#top").css({margin:0});    
    }
    
    // abusive comment stuff
    $j(".abusivecomment").hide();
    $j(".abusiveflag").click(function() {
        showid = "#" + $j(this).attr('cid');
        $j(showid).toggle();
    })
    .toggle(function() {
                $j(this).html("This comment has been flagged by the community. Click to re-hide it.");        
            }, function() {
                $j(this).html("This comment has been flagged by the community. Click to show it.");                
        })
    .css({cursor:"pointer"})
    ;
    
    // show comment selector
    $j('#showcomments').change(function() {
      switch($j('#showcomments option:selected').text().toLowerCase())
      {
        case "show all comments":
            $j('.cmt').show();
        break;
        case "show insightful comments":
            $j('.cmt').hide();
            $j('.insightfulcomment').show();
        break;   
        case "show funny comments":
            $j('.cmt').hide();
            $j('.funnycomment').show();
        break;     
        default:
            // alert($j('#showcomments option:selected').text().toLowerCase());
      }
    });
    
});

