function init() {
    $("textarea[maxlength]").keypress(function(event){
        var key = event.which;
        if (key >= 33 || key == 13) {
            var maxLength = $(this).attr("maxlength");
            var length = this.value.length;
            if (length >= maxLength) {
                event.preventDefault();
            }
        }
    });
}

function login() {
    var params = $("#login").serialize();
    $("#login_msg").text("");

    $.post(
        "/login",
        params,
        function(data){
            if (data.success) {
                refresh();
            }
            else {
                $("#login_msg").text("Invalid login.");
            }
        },
        "json"
    ); 
}

function register() {
    var params = $("#register").serialize();
    $("#register_msg").text("");

    $.post(
        "/register",
        params,
        function(data){
            if (data.success) {
                refresh();
            }
            else {
                $("#register_msg").text(data.msg);
            }
        },
        "json"
    ); 
}

function edit_account() {
    var params = $("#edit").serialize();
    $("#edit_msg").text("");

    $.post(
        "/account_edit",
        params,
        function(data){
            $("#edit_msg").text(data.msg);
        },
        "json"
    );
}

function delete_account() {
    if (confirm("Clicking OK will delete your account.")) {
        var params = $("#delete").serialize();

        $.post(
            "/account_delete",
            params,
            function(data){
                if (data.success) {
                    refresh();
                }
                else {
                    $("#delete_msg").text(data.msg);
                }
            },
            "json"
        );
    }
}

function add_fav(obj, pid) {
    var a = $(obj);
    a.text("Saving...").click(function(){});

    $.post(
        "/add_favorite",
        {"pid": pid},
        function(data){
            a.after(success_msg("Added to favorites")).remove();
        }
    ); 
}

function set_user_pic(obj, pid) {
    var a = $(obj);
    a.text("Saving...").click(function(){});

    $.post(
        "/set_user_pic",
        {"pid": pid},
        function(data){
            a.after(success_msg("Profile pic saved")).remove();
        }
    );
}

function like_photo(obj, pid, rating) {
    var a = $("#likebar" + pid);
    var num = parseInt($("#likenum" + pid).text());
    a.text("Saving...").click(function(){});

    if (rating != 1 && rating != -1) return;

    $.post(
        "/like_photo",
        {"pid": pid, "rating": rating},
        function(data){a
            if (rating > 0) {
                a.after(success_msg("You like this photo")).remove();
                num++;
            }
            else {
                a.after(success_msg("You dislike this photo")).remove();
                num--;
            }
            //$("#likemsg").html("<b>" + num + "</b> " + ((num == 1) ? "person" : "people") + " liked this photo.");
        }
    );
}

function delete_photo(obj, pid) {
    if (confirm("Delete this photo?")) {
        var a = $(obj);
        a.text("Deleting...").click(function(){});

        $.post(
            "/delete_photo",
            {"pid": pid},
            function(data){
                refresh();
            }
        );
    }
}

function remove_photo(obj, pid) {
    if (confirm("Remove this photo?")) {
        var a = $(obj);
        a.text("Removing...").click(function(){});

        $.post(
            "/remove_photo",
            {"pid": pid},
            function(data){
                refresh();
            }
        );
    }
}

function post_comment(obj, pid, uid) {
    var a = $(obj);
    var params = $("#comment_form").serialize();

    $.post(
        "/post_comment",
        params,
        function(data){
            $("#nocomment").hide();
            $("#comments").append(data);
            $(".new").fadeIn();
            $("#comment_form").after(success_msg("Comment posted.")).remove();
        }
    );
}

function create_thread() {
    var params = $("#thread_form").serialize();

    $.post(
        "/create_thread",
        params,
        function(data){
            if (data) go("/forum/" + data.fid + "/" + data.thid + "/");
        },
        "json"
    );
}

function create_post() {
    var params = $("#post_form").serialize();
    var parent_post_id = $("#parent_post_id").val();
    $.post(
        "/create_post",
        params,
        function(data){
            if (parent_post_id == 0) {
                $("#posts").prepend(data);
            }
            else {
                $("#post" + parent_post_id).after(data);
            }
            $("#post_form").hide();
            $(".new").fadeIn("slow");
        }
    );
}

function delete_thread(thid) {
    if (confirm("Delete this thread?")) {
        $.post(
            "/delete_thread",
            {"thid":thid},
            function(data){
                $("#thread" + thid).fadeOut();
            }
        );
    }
}

function success_msg(msg) {
    return '<img src="/images/check.gif"/> ' + msg;
}

function load_obj(id, attr, s) {
    $("#" + id).attr(attr, Base64.decode(s));
}

function refresh() {
    location.reload(false);
}

function go(url) {
    location.href = url;
}

function move_photo(obj, pid) {
    var a = $(obj);
    a.text("Moving...").click(function(){});

    $.post(
        "/move_photo",
        {"pid": pid},
        function(data){
            if (data.success) {
                a.html('<b>Photo moved.</b>');
            }
        },
        "json"
    );
}

function edit_favs(obj) {
    $(obj).hide();
    $("#editfav").slideDown();
    $("#favorites").addClass("editing");
    $("#favorites .thumbs a").each(function(){
        var a = $(this);
        //a.prepend('<div class="delete"><img src="/images/delete.gif" /></div>');
        a.attr("xhref", a.attr("href")).attr("href", "#").click(function(){
            delete_fav(a, a.attr("pid"));
        });
    });
}

function reset_favs() {
    //$("#favorites .delete").remove();
    $("#editfav").slideUp();
    $("#editfavlink").show();
}

function done_edit_favs() {
    reset_favs();
    $("#favorites .thumbs a").each(function(){
        var a = $(this);
        a.attr("href", a.attr("xhref")).unbind("click");
    });
    $("#favorites").removeClass("editing");
}

function delete_fav(a, pid) {
    if (confirm("Remove this photo?")) {
        $.post(
            "/remove_favorite",
            {"pid": pid},
            function(data){
                if (data.success) {
                    a.find("img").fadeOut("slow");
                }
                else {
                    alert("Delete failed.");
                }
            },
            "json"
        );
    }
}

function ask_login() {
    alert("You must be logged in to do that.");
}

var Base64 = {
	// private property
	_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

	// public method for encoding
	encode : function (input) {
		var output = "";
		var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
		var i = 0;

		input = Base64._utf8_encode(input);

		while (i < input.length) {

			chr1 = input.charCodeAt(i++);
			chr2 = input.charCodeAt(i++);
			chr3 = input.charCodeAt(i++);

			enc1 = chr1 >> 2;
			enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
			enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
			enc4 = chr3 & 63;

			if (isNaN(chr2)) {
				enc3 = enc4 = 64;
			} else if (isNaN(chr3)) {
				enc4 = 64;
			}

			output = output +
			this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
			this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);

		}

		return output;
	},

	// public method for decoding
	decode : function (input) {
		var output = "";
		var chr1, chr2, chr3;
		var enc1, enc2, enc3, enc4;
		var i = 0;

		input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

		while (i < input.length) {

			enc1 = this._keyStr.indexOf(input.charAt(i++));
			enc2 = this._keyStr.indexOf(input.charAt(i++));
			enc3 = this._keyStr.indexOf(input.charAt(i++));
			enc4 = this._keyStr.indexOf(input.charAt(i++));

			chr1 = (enc1 << 2) | (enc2 >> 4);
			chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
			chr3 = ((enc3 & 3) << 6) | enc4;

			output = output + String.fromCharCode(chr1);

			if (enc3 != 64) {
				output = output + String.fromCharCode(chr2);
			}
			if (enc4 != 64) {
				output = output + String.fromCharCode(chr3);
			}

		}

		output = Base64._utf8_decode(output);

		return output;

	},

	// private method for UTF-8 encoding
	_utf8_encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";

		for (var n = 0; n < string.length; n++) {

			var c = string.charCodeAt(n);

			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}

		}

		return utftext;
	},

	// private method for UTF-8 decoding
	_utf8_decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;

		while ( i < utftext.length ) {

			c = utftext.charCodeAt(i);

			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}

		}

		return string;
	}
}

