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

var app_root = document.location.pathname;
if (app_root.match(/^\/td(\/.*)?$/)) {
    app_root = '/td';
} else {
    app_root = '';
}


// 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();
}

function showEmailThis() {
}

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

    // hide stuff
    $j("#popover").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_tab").click(
        function() {
        	var tab_id = $j(this).attr('id');
            $j(".t_tab").removeClass("on");
            $j("#" + tab_id).addClass("on");

			var content_id = tab_id.replace('t_', 'p_');
			$j(".p_content").hide();
			$j("#" + content_id).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;
    });
    
    
    // email subscribe buttons popup
    $j("#email_sub_tgl").toggle(function() {
    	var position = $j(this).position();
    	var parent_position = $j(this).parent().position();
    	$j("#email_sub_form").css('left', parent_position.left);
    	$j("#email_sub_form").css('top', position.top + 15);
    	$j("#email_sub_form").slideDown('fast');
        if ($j("#rss_sub_buttons").is(':visible')) {
            $j("#rss_sub_tgl").trigger('click');
        }
         _gaq.push(['_trackEvent', 'Follow Techdirt (' + etpg + ')', 'Click Link', 'Follow - Newsletter']);
        return false;
    }, function() {
    	$j("#email_sub_form").slideUp('fast');
    });

    // rss subscribe buttons popup
    $j("#rss_sub_tgl").toggle(function() {
    	var position = $j(this).position();
    	var parent_position = $j(this).parent().position();
    	$j("#rss_sub_buttons").css('left', parent_position.left);
    	$j("#rss_sub_buttons").css('top', position.top + 15);
    	$j("#rss_sub_buttons").slideDown('fast');
        if ($j("#email_sub_form").is(':visible')) {
            $j("#email_sub_tgl").trigger('click');
        }
         _gaq.push(['_trackEvent', 'Follow Techdirt (' + etpg + ')', 'Click Link', 'Follow - RSS']);
        return false;
    }, function() {
    	$j("#rss_sub_buttons").slideUp('fast');
    });

    // email this popup
    $j(".emailthis_button").live('click', function() {
    	var position = $j(this).position();
    	var sid = $j(this).attr('href').replace(/.*sid=/i, "").replace(/\&.*/, "");
    	$j("#et_sid").attr("value", sid);
    	$j("#et_popup").css('left', position.left - 135);
    	$j("#et_popup").css('top', position.top - 258);
    	$j("#et_popup").show();

        return false;
    });

    $j(".et_close").click(function () {
        $j("#et_popup").hide();
        return false;
    });

    // top promo close
    $j("#topclose").click(function () {
        $j("#toppromo").slideUp('slow');
        //alert($j("#toppromo").attr('name'));
        $j.cookie("toppromoclose", $j("#toppromo").attr('name'), { expires: 365 });
        return false;    
    })
    .css({cursor:"pointer"})
    ;
    
    // hide crystal ball
    $j('#crystalballhide').click(
    	function() {
            $j.get(base_path + '/ajax/json-set-user-preference.php?pn=cbCollapsed&pv=1');
            $j('#crystalball').slideUp('normal', function() {
	            $j('#crystalballhide').hide();
                $j('#crystalballhide').css({ background : 'url(\'http://cdn.techdirt.com/images/icons/min-arrow-dn.gif\') no-repeat center bottom' });
	            $j('#crystalballshow').show();
        	});
    	}
    ).hover(
        function () {$j(this).css({ 'background-color' : "#efefef" });},
        function () {$j(this).css({ 'background-color' : "" });}
    ).css({cursor:"pointer"});

    // show crystal ball
    $j('#crystalballshow').click(
    	function() {
            $j.get(base_path + '/ajax/json-set-user-preference.php?pn=cbCollapsed&pv=0');
    		$j('#crystalballshow').hide();
            $j('#crystalballhide').show(0,
            	function() {
		            $j('#crystalball').slideDown('normal', function() {
		                $j('#crystalballhide').css({ background : 'url(\'http://cdn.techdirt.com/images/icons/min-arrow-up.gif\') no-repeat center bottom' });
		            });
	            }
            );
    	}
    ).hover(
        function () {$j(this).css({ 'background-color' : "#efefef" });},
        function () {$j(this).css({ 'background-color' : "" });}
    ).css({cursor:"pointer"});

    
    // 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());
      }
    });
    
    
    // "what's this?" pop-up
    $j('.whatsthis').click(function() {

		// remove existing what's this div, if any
   		$j('#wt_ol').remove();

		// get the what's this link position
    	var position = $j(this).position();

    	// get the key
    	var key = $j(this).attr('class');
		key = key.replace('whatsthis ', '');

		// get the content
		$j.getJSON(app_root + '/ajax/json-whatsthis.php?key=' + key, '', function(data) {
            var whatsthis = data[key];

			$j('body').append('<div id="wt_ol"><p class="wt_head">What&apos;s this?</p><p class="wt_content">' + whatsthis + '</p>');
			
	    	$j('#wt_ol').css('left', position.left - 2);
	    	$j('#wt_ol').css('top', position.top - 18);
	    	$j('#wt_ol').fadeIn();
	    	$j('body').click(function() {
	    		$j('#wt_ol').fadeOut('slow', function() {
	    			$j('#wt_ol').remove();
	    		});
	    	});
        });
			
		return false;
    });
    
});


