var last_band_row = 0;
var doc_ready_funcs = new Array();

// global on_load handler. Will also call any other specified handlers
$(document).ready(function(event){
    // jQuery-based form validation
    // Place the error message in the right spot
    jQuery.validator.setDefaults({
                errorPlacement: function(error, element)
                {
                    var elem = element.parent().next();
                    error.prependTo(elem);
                }
        });
    // Add rule for fields that must be currency
    jQuery.validator.addMethod("currency",
        function(value, element)
        {
            var regex = /^\s*(([1-9][0-9]*(\.([0-9]{2}))?)|[0])?\s*$/;
            return this.optional(element) || value.match(regex);
        }, 
        "Must be in Currency Format");
        
    // All inputs named "date" must be date-formatted
    $("input[name=date]").focusout(function(event){
        // user entered only the year
        if (this.value.match(/^\d{4}$/))
        {
            this.value = this.value + "-01-01";
        }
         
        // user entered year and month
        if (this.value.match(/^\d{4}-\d{1,2}$/))
        {
            this.value = this.value + "-01";
        }
        
        if (this.value != '' && !isDate(this.value, "yyyy-MM-dd"))
        {
            this.value = "";
            alert("Not a valid date format");
        }
    });
    
    // numeric-only fields
    $("input[name=quantity]").focusout(function(event){
        if (!this.value.match(/^\d*$/))
        {
            this.value = "";
            alert("Numeric values only");
        }
    });
    
    // float-only fields
    $("input[name=width], input[name=height], input[name=rpp]").focusout(function(event){
       if (!this.value.match(/^[0-9]*\.?[0-9]+$|^$/))
       {
           this.value = "";
           alert("Numeric values only");
       }
    });
    
    setup_currency_fields();
    
    // select-boxes with "other" fields
    $("select").live('change', function(event){
        show_hide_other_field(this);
    });
    
    // add/remove band buttons
    $("a[name=band_add]").click(function(event){
        event.preventDefault();
        add_new_band_row();
        show_hide_other_field($("select[name^=band]").last());
    });
    $("a[name=band_remove]").click(function(event){
        var bands = $("select[name^=band]");
        if (bands.length > 1)
        {   
            bands.last().parent().prev().remove();
            bands.last().parent().remove();
            last_band_row--;
        }
    });
    
    // hide non-visible sidebar menus
    $(".sidebar_menu").each(function()
    {
        if($(this).children("input:checked").size() == 0)
        {
            $(this).hide();
        }
    });
    
    // Change the icons on the filter list
    $(".sidebar_menu_root").click(function(event){
        $(this).next(".sidebar_menu").toggle(250);
        var oldText = $(this).text();
        if (oldText.indexOf('-') == -1)
        {
            $(this).html("-" + oldText.substring(oldText.indexOf('+')+1));
        }
        else
        {
            $(this).text("+" + oldText.substring(oldText.indexOf('-')+1));
        }
    });
    
    // clearing the selected options
    $("#clearsidebar").click(function(event){
        $("input[name=band]").attr("checked", false);
        $("input[name=artist]").attr("checked", false);
        $("input[name=type]").attr("checked", false);
        $("input[name=query]").attr("value", "");
        $("input[name=prev_search_text]").attr("value", "");
        
        filter_results("");
    });
    
    setup_toggle_fields();
    
    // Whenever the selection changes, refresh the list
    $(".filter, .namedFilter").change(function(event){
        filter_results($("input[name=prev_search_text]").attr("value"));
    });
    
    // Search button
    $("input[name=searchButton]").click(function(){
        filter_results($("input[name=query]").attr("value"));
    });
    
    // Dynamic search
    $("#dynSearch").keyup(function(event){
        if (!event.ctrlKey && !event.metaKey && !event.altKey && event.which != 20 &&
            !(event.which >= 44 && event.which <= 46))
            updateDynamicSearch();
    });
    
    $("#dynClear").click(function(event){
        event.preventDefault();
        $("#dynSearch").attr("value", "");
        updateDynamicSearch();
    });
    
    // Put confirmation boxes on delete links
    $("a[name=delete]").click(function(event){
        if (!confirm("Delete this listing? This cannot be undone"))
        {
            event.preventDefault();
        }
    });
    
    // changing the number of items per page
    $("input[name=rowsperpage]").click(function()
    {
        filter_results($("input[name=prev_search_text]").attr("value"));
    });
    
    // Any other elements
    var i;
    for(i = 0; i < doc_ready_funcs.length; i++)
    {
        doc_ready_funcs[i](event);
    }
});

function updateDynamicSearch()
{
    // Get the text in the search box - it's the one with id dynSearch
    var searchText = $("#dynSearch").attr("value");
    
    // Go through every item of type dynSearchResult, and hide it if it doesn't match
    $(".dynSearchResult").each(function(){
       var itemValue = $(this).attr("searchCriteria");
       if (itemValue.toUpperCase().indexOf(searchText.toUpperCase()) == -1)
       {
           $(this).hide();
       }
       else
       {
           $(this).show();
       }
    });
}

function setup_currency_fields()
{
    // currency-only fields
    $("input[name=price],input.currency").focusout(function(event){
        var regex = /^\s*(([1-9][0-9]*(\.([0-9]{2}))?)|[0])?\s*$/;
        if (!this.value.match(regex))
        {
            this.value = "";
            alert("Invalid currency format");
        }
    });
}

function setup_toggle_fields()
{
    // radio boxes for toggling which input field to use
    $("input[name^=toggle]").change(function(event)
        {
            toggle_form_items();
        });
    // And we need to do it at the start too
    toggle_form_items();
}

function filter_results(query)
{
    var bands = "";
    $("input[name=band]:checked").each(function()
    {
        bands += this.value + ",";
    });
    bands = bands.substring(0, bands.length - 1);
    
    var artists = "";
    $("input[name=artist]:checked").each(function()
    {
        artists += this.value + ",";
    });
    artists = artists.substring(0, artists.length - 1);
    
    var types = "";
    $("input[name=type]:checked").each(function()
    {
        types += this.value + ",";
    });
    types = types.substring(0, types.length - 1);
    
    filterstr = "";
    if (bands != "")
    {
        filterstr += "&bands=" + bands;
    }
    
    if (artists != "")
    {
        filterstr += "&artists=" + artists;
    }
    
    if (types != "")
    {
        filterstr += "&types=" + types;
    }
    
    $("input.filter:checked").each(function()
    {
        filterstr += "&"+this.name;
    });
    
    if (parseInt($("input[name=rpp]:first").val()) != 10)
    {
        filterstr += "&perpage=" + $("input[name=rpp]:first").val();
    }
    
    if (query.length > 0)
    {
        filterstr = "&query=" + escape(query) + filterstr;
    }
    
    window.location = document.URL.split("?")[0] + "?action=main" + filterstr;
}

// If form items are controlled by a toggle disable the unselected ones
function toggle_form_items()
{
    $("input[name^=toggle]:not(:checked)").next().attr("disabled", "disabled");
    $("input[name^=toggle]:not(:checked)").next().attr("value", "");
    // Enable items next to the checked item
    $("input[name^=toggle]:checked").next().attr("disabled", "");
}

function edit_item_setup()
{
    last_band_row = $("select[name^=band]").length - 1;
    // Make sure other boxes are either shown or hidden
    $("select").each(function(){
        if (this.length == 1 || this.selectedIndex == this.length - 1)
        {
            $("input[name='"+this.name+"_other']").show();
        }
        else
        {
            $("input[name='"+this.name+"_other']").hide();
        }
    });
    
    setup_related_browser();
    
    // When we submit the page, save any changes to the related items
    $("input[name=item\\_edit\\_submit]").click(function(event){
        if (!confirm("Edit item details? This cannot be undone"))
        {
            event.preventDefault();
            return false;
        }
        
        copy_selected_items();
    });
}


function setup_related_browser()
{
    // don't show the related item browser to start
    $("div[name=relatedbrowser]").hide();
    // Show it when the button is clicked
    $("a[name=editrelated]").click(function(event){
        event.preventDefault();
        $("div[name=relatedbrowser]").show(400);
        $("a[name=editrelated]").hide(400);
    });
    
    $("button[name=closesave]").click(function(event){
        event.preventDefault();
        close_related_box(function() {
        
                // clear all of the items in the related items area
                $("table[name='rel\\_table']").hide(400, function(){
                        $("table[name='rel\\_table']").children().remove();
                        // and replace them with ones from the list
                        copy_selected_items();
                
                        $("table[name='rel\\_table']").show(400);
                    });
            });
    });
    $("button[name=closecancel]").click(function(event){
        event.preventDefault();
        close_related_box(function() {
                // clear the status
                $("input[name^=id][name$=selected]").attr("checked", false);
                // set only those we have as related
                set_related_status();
            });
    });
    
    // In the related item browser, don't show any page past the first originally
    current_page = 1;
    for(i = 2; i <= pages; i++)
    {
        $("tr[name='page"+i+"']").hide();
    }
    
    // Scrolling forward through pages
    $("a[name=nextpage]").click(function(event){
        event.preventDefault();
        if(current_page < pages)
        {
            $("tr[name='page"+(current_page++)+"']").hide();
            $("tr[name='page"+(current_page)+"']").show();
            $("span[name=page]").html(current_page);
        }
    });
    
    // scrolling backwards through pages
    $("a[name=prevpage]").click(function(event){
        event.preventDefault();
        if(current_page > 1)
        {
            $("tr[name='page"+(current_page--)+"']").hide();
            $("tr[name='page"+(current_page)+"']").show();
            $("span[name=page]").html(current_page);
        }
    });
    
    /*
     * Set up the mapping between selected items in the browser and
     * listed related items.
     */
    // On load, set the selected state of the items in the browser to be whether or
    // not they are already related
    set_related_status();
}

function copy_selected_items()
{
    var ids = "";
    
    var checkedItems = $("input[name^=id][name$=selected]:checked");
    if(checkedItems.length > 0)
    {
        checkedItems.each(function()
            {
                var name = $(this).attr('name').split("_")[0];
                var title = $(this).parents("tr").children("[name=title]").text();
                var img_path = $(this).parents("tr").find("img").attr('src');
                
                ids += name.substring(2) + " ";
                
                // now create a table row for this item
                var row = $(document.createElement("tr"));
                row.attr('name', name);
                
                var imgcell = $(document.createElement("td"));
                if(img_path == undefined)
                {
                    imgcell.html("<div style='height:100px; min-width:80px' class='nopic'><b style='position:relative; top:43px'>No Picture</b></div>");
                }
                else
                {
                    imgcell.html("<img style='height:100px' src='"+img_path+"' />");
                }
                
                var titlecell = $(document.createElement("td"));
                titlecell.text(title);
                
                row.append(imgcell);
                row.append(titlecell);
                
                $("table[name='rel\\_table']").append(row);
            });
    }
    else
    {
        var row = $(document.createElement("tr"));
        row.html("<td><div style='height:100px; min-width:80px' class='nopic'><b style='position:relative; top:43px'>No Items</b></div>");
        $("table[name='rel\\_table']").append(row);
    }
    
    $("input[name='related\\_items']").val(ids);
}

function set_related_status()
{
    $("tr[name^=id]").each(function(){
        $("input[name='"+$(this).attr('name')+"_selected']").attr("checked", true);
    });
}

// Closing the related item browser
function close_related_box(callback)
{
    $("div[name=relatedbrowser]").hide(400, callback);
    $("a[name=editrelated]").show(400);
}

function add_new_band_row()
{    
    var bands = $("select[name^=band]");
    
    var new_select = $($("select[name^=band]:last").get(0).cloneNode(true));
    new_select.attr('name', "band"+bands.length);
    
    var new_other = $($("input[name^=band][name$=other]:last").get(0).cloneNode(true));
    new_other.attr('name', "band"+bands.length+"_other");
    
    var new_div = $(document.createElement('div'));
    new_div.addClass('data');
    new_div.append(new_select);
    new_div.append($(document.createTextNode("\n")));
    new_div.append(new_other);
    
    $("select[name^=band]:last").parent().after('<div class=\'label\'></div>');
    new_div.insertAfter($("select[name^=band]:last").parent().next())
}

function show_calendar(target, anchor) {
    var cal = new CalendarPopup("calendar");
    cal.showYearNavigation();
    cal.showYearNavigationInput();
    cal.select(target, anchor, 'yyyy-MM-dd');
}

function confirm_remove(type) {
    return confirm("Remove this item from your " + type + "?");
}

function confirm_image_picked()
{
    var image = document.getElementById("new_image");
    if (image.value == "")
    {
        alert("Must choose an image to upload");
        return false;
    }
    return true;
}

function show_hide_other_field(sel)
{
    if (sel.length == 1 || sel.selectedIndex == sel.length - 1)
    {
        $("input[name='"+sel.name+"_other']").show();
    }
    else
    {
        $("input[name='"+sel.name+"_other']").hide();
    }
}

