function URLEncode(e){
	var SAFECHARS="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_.!~*'()";
	var HEX="0123456789ABCDEF";

	var plaintext = e.split('');
	var encoded = "";
	for (var i = 0; i < plaintext.length; i++ ){
		var ch = plaintext[i];
	    if (ch == " "){
		    encoded += "+";
		} else if (SAFECHARS.indexOf(ch) != -1){
		    encoded += ch;
		} else {
		    var charCode = ch.charCodeAt(0);
			if (charCode > 255) {
				encoded += "+";
			} else {
				encoded += "%"+HEX.charAt((charCode >> 4) & 0xF)+HEX.charAt(charCode & 0xF);
			}
		}
	}
	return encoded;
};

function URLDecode(e){
   var HEXCHARS = "0123456789ABCDEFabcdef"; 
   var encoded = e;
   var plaintext = "";
   var i = 0;
   while (i < encoded.length) {
       var ch = encoded.charAt(i);
	   if (ch == "+") {
	       plaintext += " ";
		   i++;
	   } else if (ch == "%") {
			if (i < (encoded.length-2) 
					&& HEXCHARS.indexOf(encoded.charAt(i+1)) != -1 
					&& HEXCHARS.indexOf(encoded.charAt(i+2)) != -1 ) {
				plaintext += unescape( encoded.substr(i,3) );
				i += 3;
			} else {
				i++;
			}
		} else {
		   plaintext += ch;
		   i++;
		}
	}
   return plaintext;
};

function get_rating(pagex) {
	 var curleft = curtop = 0;
    obj = $("#left_sidebar .rating_container")[0];
//    obj = $(".rating_container")[0]
    if (obj.offsetParent) {
        do {
			   curleft += obj.offsetLeft;
//			   curtop += obj.offsetTop;
        } while (obj = obj.offsetParent);
    };
    rating = Math.floor((pagex - curleft)/14) + 1;
    if (rating > 5) {
        rating = 5;
    };
    return rating;
};

function are_you_ie() {
    var sBrowser = navigator.userAgent;
    if (sBrowser.toLowerCase().indexOf('msie') > -1) return true;
    else return false;
}

$(document).ready(function() {
	 if(_c != ""){
		$("#post_comment textarea").html(URLDecode(_c));
	 }

	 $("#overlay_login a.register").click(function(e){
		e.preventDefault();
		window.open($(this).attr("href"));
	 });

    $(".new_rating .rating_container").mousemove(function(e) {
        $(".new_rating .rating").removeClass().addClass("rating rating_blue_" + get_rating(e.pageX) + "_0");
    }).mouseleave(function(e) {
        $(".new_rating .rating").removeClass().addClass("rating rating_blue_0_0");
    });

    $(".new_rating a").click(function(e) {
        e.preventDefault();
        e.stopPropagation();

        if (logged_in) {
            var node_rating = get_rating(e.pageX);
            $.post($(this).attr("href"), { rating: node_rating }, function(data) {
                window.location.reload();
            });
        }
        else {
            open_login_overlay("Rate this article", "Please login below to rate this article");
        }
    });

    $("#faves_form").submit(function(e) {
        if (!logged_in) {
            open_login_overlay("Save to Faves", "Please login below to save this article");
            e.preventDefault();
        }
    });
    
    $("#email_content").click(function(e) {
        e.preventDefault();
        e.stopPropagation();
        if (!logged_in) {
            open_login_overlay("Email", "Please login below to email this article");
        }
        else {
            open_overlay($("#overlay_email"));
        }
    });

    $("#post_comment").submit(function(e) {
        if (!are_you_ie()) {
            e.stopPropagation();
            e.preventDefault();
            var comment_value = $("#id_comment").val();
            if (!logged_in) {
					 var next = $("#overlay_login form fieldset #next");
					 $(next).val($(next).val() + "?comment=" + URLEncode(comment_value));
                open_login_overlay("Comment", "Please login below to comment on this article");
            }
            else if (!comment_value) {
                $(".error").show();
            }
            else {
                url = $(this).attr("action");

				    var form_data = {};
				    $("#post_comment input").each(function() {
					     form_data[$(this).attr("name")] = $(this).val();
				    });
				    form_data['ajax'] = 'True';
                form_data['comment'] = comment_value;

                $.post(url, form_data, function(data) {
                    username = data.username;
                    comment = data.comment;
                    link = data.link;
                    picture = data.picture;
                    comment_html = '<div class="comment new_comment"><a href="' + link + '"><img src="' + picture + '" width="44" height="44" /></a><a href="' + link + '">' + username + '</a>' + comment + '</div>'
                    $("#comment_list").append(comment_html);
                    $(".new_comment").hide();
                    $("#comment_list").show();
                    $(".new_comment").fadeIn("slow", function() {
                        $(".new_comment").removeClass("new_comment");
                    });
                    $("#id_comment").val("");
                }, "json");
            }
        }
    });

    $("form#post_form").submit(function(e) {
        e.stopPropagation();
        if (!logged_in) {
            open_login_overlay("Comment on this Discussion", "Please login below to comment on this discussion");
            e.preventDefault();
        }
    });
        

    $(".comment_link").show();
    $("#comment_list").hide();
    $("#add_comment").css("display","block");

	 if(_c == "") {
	    $("#post_comment").hide();
	 }

    $("#add_comment").click(function(e) {
        e.preventDefault();
		  if(are_you_ie() && !logged_in){
			  window.location = _login+"?next="+_curl;
		  } else {
	        $("#post_comment").toggle();
		  }
    });

    $(".comment_link").click(function(e) {
        e.preventDefault();
        $("#comment_list").slideToggle("fast");
        if (!$(this).hasClass("hide_comment_link")) {
            $(this).addClass("hide_comment_link")
        }
        else {
            $(this).removeClass("hide_comment_link")
        }
    });

    $("#markdown_link").click(function(e) {
        e.preventDefault();
        $("#markdown_content").load($(this).attr("href") + " #flatpage_content");
        $("#markdown_content").slideToggle();
    });
});

