// ITEM INFORMATION SCRIPTS

// TEMPLATES
var item_message_template_string = "\n\
<div class='borderless_blue_box' id='{id}' style='display:none;'>\n\
  <span class='message_user_name'>{username}</span>\n\
  <span class='message_time'>({time_ago} ago)</span><br />\n\
  <div class='item_message'>{text}</div>\n\
</div>\n\
";
var item_message_template = jsontemplate.Template(item_message_template_string);

var not_bought_button_string = "\n\
<form class='button-to' action='/items/bought_one?item_user_id={id}&amp;take_it_back=true' method='post'>\n\
    <div>\n\
        <input type='submit' value=\"Oops, no I didn't.\" id='not_bought_button'/>\n\
    </div>\n\
</form>\n\
\n\
";
var not_bought_template = jsontemplate.Template(not_bought_button_string);

var json_append_message = function(data){
    var html = item_message_template.expand( data );
    $("#message_list").append(html);
    $("#" + data.id).fadeIn("slow");
};

var extract_action_from_button_to = function(button_jquery_element){
    var form = button_jquery_element.parent().parent();
    return form.attr("action");
};

function ItemInformation(total_quantity,my_quantity){
    if( total_quantity === "" ) total_quantity = 0;
    if( my_quantity === "" ) my_quantity = 0;
    
    this.total_quantity = parseInt(total_quantity);
    this.my_quantity = parseInt(my_quantity);
}

function update_quantities(amount){
    item_information.total_quantity += amount;
    item_information.my_quantity += amount;
    $("#total_given").text(item_information.total_quantity);
    $("#my_given").text(item_information.my_quantity);
}

function remove_not_bought_button(){
    $("#not_bought_container").empty();
}

function attach_not_bought_button_handler(){
    var not_bought = "not_bought_button";
    if( document.getElementById(not_bought) != null ){
        var not_bought_button = $("#" + not_bought);
        not_bought_button.click(function(){
            var action = extract_action_from_button_to(not_bought_button);
            $.post(action,
                null,
                null,
                "json");

            update_quantities(-1);
            if( item_information.my_quantity == 0 ){
                remove_not_bought_button();
            }
            return false;
        });
    }
}

function add_not_bought_button(id){
    var json = {
        'id' : id
    };
    var html = not_bought_template.expand(json);
    $("#not_bought_container").append(html);
    attach_not_bought_button_handler();
}

var item_information;
// BOUGHT AND NOT BOUGHT BUTTONS
$(document).ready(function(){
    var bought_one = "bought_one_button";
    var not_bought = "not_bought_button";
    
    if( document.getElementById(bought_one) != null ){
        var total = $("#total_given").text();
        var my_quantity = $("#my_given").text();
        item_information = new ItemInformation(total,my_quantity);

        var bought_button = $("#" + bought_one);
        bought_button.click(function(){
            var action = extract_action_from_button_to(bought_button);
            $.post(action,
                null,
                null,
                "json");

            update_quantities(1);

            // if there isn't a bought one button, add it
            if( document.getElementById(not_bought) == null ){
                var item_id = $("#item_information").attr('item_id');
                add_not_bought_button(item_id);
            }

            return false;
        });
    }

   
    attach_not_bought_button_handler();
});

// ADD MESSAGE BUTTON
$(document).ready(function(){
    if( document.getElementById("add_message_button") != null ){
        var target_button = $("#add_message_button");
        target_button.click(function(){
            var action = extract_action_from_button_to(target_button);

            var msg_area = $("#message_text_area");
            var value = msg_area.val();
            msg_area.val("");
            $.post(action,
            {
                'post': value
            },
            json_append_message,
            "json");

            return false;
        });
    }
});

// END ITEM INFORMATION SCRIPTS


// DO NOT WANT SCRIPTS
//on blur mark the thing as changed
$(document).ready(function(){
    $("#wmd-input").change(function(){
        $("#changed").val(false);
    });
});

// END DO NOT WANT SCRIPTS

// LOGIN PAGE SCRIPTS
$(document).ready(function(){
    var login_exists = $("#login").length === 1;

    if( login_exists ){
        // Event Handlers
        $("#login").focus(function(){
            document.getElementById("login").className = "login_input_user";
            current_username = $("#login").val();
            if( current_username == "Username" ) $("#login").val("");
        });

        $("#login").blur(function(){
            current_username = $("#login").val();
            if( current_username == "" ){
                $("#login").val("Username");
                document.getElementById("login").className = "login_input_default";
            }
        });

        $("#password_placeholder").focus( function() {
            $("#password_placeholder").hide();
            $("#password").show().focus();
        });

        $("#password").blur( function() {
            current_password = $("#password").val();
            if( current_password == "" ) {
                $("#password").hide();
                $("#password_placeholder").show();
            }
        });

        // Initialize Things

        //replace the password box with a textbox, so we can render some
        //visible text into it. Swap with textbox on focus
        $("#password").hide();
        $("#password_placeholder").show();

        //if the browser has 'remembered' some value, then switch the class
        if( $("#login").val() != "Username" ) {
            document.getElementById("login").className = "login_input_user";
        }
    }
});
// END LOGIN PAGE SCRIPTS

// VIEW AS OWNER SCRIPTS
$(document).ready( function() {
    //On load actions
    var on_page = $("#my_wishlist").length === 1;
    if( on_page ){
        var hide_remove_panel = function(){
            $("#mask").fadeOut(250);
            $("#remove_panel").fadeOut(250);
        };

        //hide the submit buttons and show the input buttons
        $(".remove_submit_button").each( function () {
            var id = $(this).attr("id");
            $(this).hide();
            $(this).after("<input type='button' id='" + id + "' class='remove_button' value='Take this off my list' />");
            $(this).remove();
        });

        // Remove button should popup the panel on click
        $(".remove_button").bind("click", function(){
            var maskHeight = $(document).height() - 2;
            var maskWidth = $(window).width() - 2;

            $("#mask").css({
                'width':maskWidth,
                'height':maskHeight
            });

            var panel_left = (maskWidth/2) - 205;
            $("#remove_panel").css({
                'top':200,
                'left':panel_left
            });

            //setup the panel
            var id = $(this).attr("id");
            $("#remove_item_panel_id").attr("value", id);

            var edit_id = "#edit_link_" + id;
            var title = $(edit_id).text();
            $("#remove_item_name").text(title);

            //show the panel
            $("#mask").fadeIn(500);
            $("#remove_panel").fadeIn(500);

        });

        // Close popup link, make not a link and fade the panel on click
        $(".back_to_my_list").replaceWith("<label class='link_like_label back_to_my_list'>Back to my list</label>");
        $(".back_to_my_list").click( function() {
            hide_remove_panel();
        });
        $("#cancel_removal").click(function(){
            hide_remove_panel();
        });
    }

});
// END VIEW AS OWNER SCRIPTS

// ITEM FORM SCRIPTS
function item_form_on_submit(){
    $("#item_tags").attr("value",current_tags.join(","));
}

$(document).ready(function(){
    var on_item_form = $("#item_form").length === 1;

    if( on_item_form ){

        var setup = function(){
            $(".remove_tag").click(function(){
                $(this).fadeOut(500, function() {
                    $(this).remove();
                });
                var to_remove = $(this).text();
                for( i = 0; i < current_tags.length; i++ ){
                    if( current_tags[i] == to_remove) current_tags[i] = "";
                }
            });
        }
        setup();

        var in_second_not_first = function( array1, array2 ){
            results = new Array();

            for(var i = 0; i < array2.length; i++ ){
                var item = array2[i];
                if( item.length < 1 ) continue;
                var found = false;
                for( var j = 0; j < array1.length; j++ ){
                    var compare_with = array1[j];
                    if( compare_with == item ) {
                        found = true;
                    }
                }
                if( !found ) {
                    results.push(item);
                    array1.push(item);
                }
            }
            return results;
        }

        var sanitize_tags = function( tag_string ){
            tag_string = tag_string.replace(/\s/g, "");
            tag_string = tag_string.toLowerCase();
            tag_string = tag_string.replace(/[^a-z0-9]/,"");
            return tag_string;
        }


        $("#item_tags").blur(function(){
            var contents = $(this).val();
            $(this).attr("value","");
            var split_result = contents.split(",");
            jQuery.each( split_result, function(index) {
                split_result[index] = sanitize_tags(this);
            });
            var new_tags = in_second_not_first( current_tags, split_result );

            for( var i = 0; i < new_tags.length; i++ ){
                var item = new_tags[i];
                $("#dynamic_tags").append('<span id="tag_' + item + '"class="remove_tag">' +item + '</span>');
                $("#tag_" + item).hide().fadeIn(500);
            }
            setup();
        });
    }
});

// END ITEM FORM SCRIPTS