var tab_state = new Object;
tab_state.selected = '';

//Set up filter strings
get_string_array = window.location.search.substr(1).split("&");
tab_state.filter_l = '';
tab_state.filter_g = '';
tab_state.filter_r = '';
tab_state.filter_y = '';
tab_state.filter_as = '';
//Split up the get string, then cycle through each value, storing the ones used in the filter
for(i = 0; i < get_string_array.length; i++)
{
    prefix = get_string_array[i].substr(0, 3);
    if (prefix == 'fl=')
        tab_state.filter_l = get_string_array[i].substr(3);
    else if (prefix == 'fg=')
        tab_state.filter_g = get_string_array[i].substr(3);
    else if (prefix == 'fr=')
        tab_state.filter_r = get_string_array[i].substr(3);
    else if (prefix == 'fy=')
        tab_state.filter_y = get_string_array[i].substr(3);
    else if (prefix == 'as=')
        tab_state.filter_as = get_string_array[i].substr(3);
}

//Build the base URL that has none of the filters in it
tab_state.URL_start=window.location.href.replace(/(fl=|fg=|fr=|fy=|as=|y1=|y2=|pn=|ob=|#)+.*?(&|$)/g, "");
//Replace the .html page with 'index.html'
tab_state.URL_start=tab_state.URL_start.replace(/(\/.+\/).*?(html)/, "$1index.html");
if (tab_state.URL_start.substr(tab_state.URL_start.length - 1, 1) == "?" || tab_state.URL_start.substr(tab_state.URL_start.length - 1, 1) == "&")
    tab_state.URL_start = tab_state.URL_start.substr(0, tab_state.URL_start.length - 1);
    
    
jQuery(document).ready(function() {
    //Check if type was auto-forced, if it was then it needs added in the URL
    type_div = jQuery("#attribute_type_forced");
    if (type_div.length > 0 && tab_state.URL_start.indexOf("tf=") == -1)
    {
        if (tab_state.URL_start.indexOf("?") > 0)
            tab_state.URL_start += "&tf=" + type_div.val();
        else
            tab_state.URL_start += "?tf=" + type_div.val();
    }
    
    //When someone clicks a title link or 'all options' link, show the attributes window, also fired when a tab is clicked
    jQuery("a[id^='filter_link'],div[id^='attribute_tab_header']").click(function(event) {
        //Pull the id of which link was clicked
        tab_id = jQuery(this).attr("id");
        tab_id = tab_id.substr(tab_id.lastIndexOf("_")  + 1);
        
        jQuery('#attribute_search').show();
        select_tab(tab_id);
        return false;
    });
    
    //When someone clicks a checkbox attribute filter, the filter query string needs re-generated
    jQuery("[id^='chkl_'],[id^='chkg_'],[id^='chkgl_'],[id^='chkr_'],[id^='chky_']").click(function(event) { 
        //Split up the id, and use the parts to determine which function calls
        id_array = jQuery(this).attr("id").split("_");
        if (id_array[0] == 'chkl') //Listitems
        {
            if (id_array[1] == 0)
                attribute_item_select(1, "0_" + id_array[2]);
            else
                attribute_item_select(1, id_array[1]);
        }
        else if (id_array[0] == 'chkg') //Groups
        {
            attribute_item_select(2, id_array[1]);
            attribute_group_select(id_array[1]);
        }
        else if (id_array[0] == 'chkgl') //Group listitems
            attribute_item_select(4, id_array[3], id_array[1]);
        else if (id_array[0] == 'chkr') //Ranges
            attribute_item_select(3, id_array[1]);
        else if (id_array[0] == 'chky') //Years
            attribute_item_select(5, id_array[1]);
    }); 
    
    //Make 'show all/hide' group links work
    jQuery("[id^='link_']").click(function(event) {
        link_id = jQuery(this).attr("id").split("_");
        attribute_group_toggle_items(link_id[1]);
        return false;
    });
    
    //When someone clicks the close button, hide the attributes window
    jQuery('#attribute_search_close').click(function(event) {
        jQuery('#attribute_search').hide();
        return false;
    });
    
    //When someone presses enter in the year freeform box, submit the attributes form
    jQuery('#year1box,#year2box').keypress(function(event) {
        if (event.keyCode == 13)
        {
            attribute_search_submit();
            if (event.preventDefault)
                event.preventDefault();
            return false;
        }
    });

    //Toggle display of the second year textbox (with 'specific' year checkbox)
    jQuery('#year_specific').click(function(event) {
        jQuery('#year_extra').toggle();
        if (this.checked)
            jQuery('#year2box').val("");
    });
    
    //Main attribute select button
    jQuery('#attribute_submit').click(function(event) {
        return attribute_search_submit();
    });
});

//Selects a given tab, fires when a tab is clicked on
function select_tab(tab_id)
{
    var tab_data;
    var previous_tab_data = jQuery('#attribute_tab_data_' + tab_state.selected);
    var tab_controls = jQuery('#attribute_search_tab_div');
    //Only select a tab if the tab state object exists, and there are tab controls
    if (tab_controls.length && tab_state)
    {
        //If no previous selection, then initialize tabs
        if (tab_state.selected == "")
        {
            tab_state.first_tab = tab_controls.find("div:first").attr("id").replace(/attribute_tab_header_/g, "");
            initialize_tabs(tab_controls);
        }
        //Previous selection is present, disable previous and enable new tab
        else
            var previous_tab = jQuery('#attribute_tab_header_' + tab_state.selected);

        //No tab selected, set the current tab to the first tab
        if (tab_id == -1)
            tab_id = tab_state.first_tab;
        //Select the provided tab
        tab_state.selected = tab_id;
        current_tab = jQuery('#attribute_tab_header_' + tab_id);
        tab_data = jQuery('#attribute_tab_data_' + tab_id);
        //If a previous tab was set, then change the style back to normal
        if (previous_tab)
        {
            previous_tab.find("div:first").css("background-image", "url(static/css/images/usedprice-attribute_tab_background.gif)");
            previous_tab.find("div:first").css("top", 2);
        }
        //Change style to make it display like it's selected
        current_tab.find("div:first").css("background-image", "url(static/css/images/usedprice-attribute_tab_gradient.gif)");
        current_tab.find("div:first").css("top", 0);

        if (previous_tab_data)
            previous_tab_data.hide();
        tab_data.css("display", "block");
    }
}

//Adds an attribute filter selection to the generated url
function attribute_item_select(selection_type, selection_value, selection_group)
{
    if (selection_type == 1) //Listitem
        tab_state.filter_l = toggle_filter_value(tab_state.filter_l, selection_value, jQuery('#chkl_' + selection_value));
    else if (selection_type == 2) //Group 
        tab_state.filter_g = toggle_filter_value(tab_state.filter_g, selection_value, jQuery('#chkg_' + selection_value));
    else if (selection_type == 3) //Range
        tab_state.filter_r = toggle_filter_value(tab_state.filter_r, selection_value, jQuery('#chkr_' + selection_value));
    else if (selection_type == 4) //Group listitem
    {
        var group_item = jQuery('#chkgl_' + selection_group + '_l_' + selection_value);
        var normal_item = jQuery('#chkl_' + selection_value);
        //Check/uncheck the group list item, if unchecked then uncheck the normal list item as well
        tab_state.filter_l = toggle_filter_value(tab_state.filter_l, selection_value, group_item);
        if (normal_item.length && group_item.attr("checked") == false)
            normal_item.attr("checked", false);
        
        var group_div_items = jQuery('#div_' + selection_group).find('input');
        var group_box = jQuery('#chkg_' + selection_group);
        var group_item_value;
        if (group_div_items.length && group_box.length)
        {
            //If the group is checked
            if (group_box.attr("checked"))
            {
                //Toggle each individual item that's checked, since group will not be selected anymore
                group_div_items.each(function () {
                    if (jQuery(this).attr("checked"))
                    {
                        group_item_value = jQuery(this).attr("id").substr(jQuery(this).attr("id").indexOf('_l_') + 3);
                        tab_state.filter_l = toggle_filter_value(tab_state.filter_l, group_item_value, jQuery(this));
                    }
                });
               
                //Uncheck group and remove from list
                group_box.attr("checked", false);
                tab_state.filter_g = toggle_filter_value(tab_state.filter_g, selection_group, group_box);
            }
            //If the group is not checked
            else
            {
                var all_checked = true;
                //Loop through each item, determine if all items are checked
                group_div_items.each(function () {
                    if (jQuery(this).attr("checked") == false)
                    {
                        all_checked = false;
                        return false;
                    }
                });
                //If all items are checked, re-check the group and add it to the list
                if (all_checked)
                {
                    group_box.attr("checked", true);
                    tab_state.filter_g = toggle_filter_value(tab_state.filter_g, selection_group, group_box);
                    //Remove items from the list since group is selected now
                    group_div_items.each(function () {
                        group_item_value = jQuery(this).attr("id").substr(jQuery(this).attr("id").indexOf('_l_') + 3);
                        tab_state.filter_l = toggle_filter_value(tab_state.filter_l, group_item_value, jQuery(this), true);
                    });
                }
            }
        }
    }
    else if (selection_type == 5) //Year listitem
        tab_state.filter_y = toggle_filter_value(tab_state.filter_y, selection_value, jQuery('#chky_' + selection_value));
}

//Adds/removes an item from a filter, clear parameter is used by group items to clear their listitems
function toggle_filter_value(filter_variable, selection_value, box, clear)
{
    //If box is checked, and group isn't clearing items
    if (box.length && box.attr("checked") && !clear)
    {
        if ((('-' + filter_variable + '-').indexOf('-' + selection_value + '-') == -1))
        {
            if (filter_variable != "")
                filter_variable += '-';
            filter_variable += selection_value;
        }
    }
    //If box is unchecked, or group is clearing items
    else if (box.length)
    {
        filter_variable = ('-' + filter_variable + '-').replace('-' + selection_value + '-', '-');
        if (filter_variable == "-")
            filter_variable = "";
        if (filter_variable != "")
            filter_variable = filter_variable.substr(1, filter_variable.length - 2)
    }
    return filter_variable;
}

//Selects group items when a group is selected
function attribute_group_select(group_id)
{
    var group_div_items = jQuery('#div_' + group_id).find('input');
    var group_checkbox = jQuery('#chkg_' + group_id);
    var selection_value, normal_item;
    group_div_items.each(function () {
        if (!group_checkbox.attr("checked"))
        {
            normal_item = jQuery('#chkl_' + selection_value);
            if (normal_item.length)
                normal_item.attr("checked", false);
        }
        jQuery(this).attr("checked", group_checkbox.attr("checked"));
        selection_value = jQuery(this).attr("id").substr(jQuery(this).attr("id").indexOf('_l_') + 3);
        tab_state.filter_l = toggle_filter_value(tab_state.filter_l, selection_value, jQuery(this), true);
    });
}

//Shows/hides group items
function attribute_group_toggle_items(group_id)
{
    var group_div = jQuery('#div_' + group_id);
    var group_link = jQuery('#link_' + group_id);
    
    if (group_div.css("display") == 'none')
    {
        group_div.css("display", "");
        if (group_link.length)
            group_link.html("(hide)");
    }
    else
    {
        group_div.css("display", "none");
        if (group_link.length)
            group_link.html("(show all)");
    }
}

//Submits the current filters, directs to the newly generated URL
function attribute_search_submit()
{
    var new_URL = '';
    if (tab_state.filter_l != "")
        new_URL += '&fl=' + tab_state.filter_l;
    if (tab_state.filter_g != "")
        new_URL += '&fg=' + tab_state.filter_g;
    if (tab_state.filter_r != "")
        new_URL += '&fr=' + tab_state.filter_r;
    if (tab_state.filter_y != "")
        new_URL += '&fy=' + tab_state.filter_y;
        
    var attribute_tabs = jQuery('#attribute_search_tab_div').children();
    var tab_id, tab_controls, selected_box;
    //Build the attr_sel string by going through each tab and seeing if any boxes were checked
    for (i = 0; i < attribute_tabs.length; i++)
    {
        if (!attribute_tabs[i].innerHTML || attribute_tabs[i].id == 'attribute_tab0')
            continue;
        tab_id = attribute_tabs[i].id.replace(/attribute_tab/g, "");
        tab_controls = jQuery('#attribute_tab_data' + tab_id).find("input");
        selected_box = false;
        tab_controls.each(function () {
            if (jQuery(this).attr("type") == "checkbox" && jQuery(this).attr("checked"))
                selected_box = true;
        });
        //Checkbox was selected, add to attr_sel filter, otherwise remove from attr_sel filter
        if (selected_box)
        {
            if ((('-' + tab_state.filter_as + '-').indexOf('-' + tab_id + '-') == -1))
            {
                if (tab_state.filter_as != "")
                    tab_state.filter_as += '-';
                tab_state.filter_as += tab_id;
            }
        }
        else 
        {
            if ((('-' + tab_state.filter_as + '-').indexOf('-' + tab_id + '-') > -1))
            {
                tab_state.filter_as = ('-' + tab_state.filter_as + '-').replace('-' + tab_state.filter_as + '-', '-');
                if (tab_state.filter_as == "-")
                    tab_state.filter_as = "";
                if (tab_state.filter_as != "")
                    tab_state.filter_as = tab_state.filter_as.substr(1, tab_state.filter_as.length - 2)
            }
        }
    }
    if (tab_state.filter_as != "")
        new_URL += '&as=' + tab_state.filter_as;
    
    year1 = jQuery('#year1box');
    if (year1.length)
        new_URL += '&y1=' + year1.val();
    else if (jQuery('#year1_val').length)
        new_URL += '&y1=';
        
    //This is named differently (specific_year instead of year_specific) because for some RANDOM reason, IE 7 (and possibly other IE versions)
    //don't like it when it's named year_specific, and throw an error.. (wtf indeed)
    specific_year = jQuery('#year_specific');
    
    year2 = jQuery('#year2box');
    if (year1 && year1.val() != '' && ((specific_year.length && specific_year.attr("checked")) || (year2.length && year2.val() == year1.val())))
        new_URL += 's';
    else
    {
        if (year2.length && (!year1.length || year2.val() != year1.val()))
            new_URL += '&y2=' + year2.val();
        else if (jQuery('#year2_val').length)
            new_URL += '&y2=';
    }
    if (year1.length && year2.length && year1.val() && year2.val() && year1.val() > year2.val())
    {
        alert("Starting year must be earlier than ending year!");
        return false;
    }
    
    //Trim off the starting ampersand and replace it with a question mark, if there is a querystring
    if (new_URL != "" && tab_state.URL_start.indexOf("?") == -1)
        new_URL = "?" + new_URL.substr(1);
    document.location.href = tab_state.URL_start + new_URL;
}

//Initializes attribute search tab order
function initialize_tabs(tab_controls)
{
    var tab_nodes = tab_controls.children();
    var rows = new Array(), previous_row_width = 0, current_row_width = 0, current_row_height = -1;
    //Loop through each div and calculate the length of each row of tabs
    for (i = 0; i < tab_nodes.length; i++)
    {
        if (tab_nodes[i].innerHTML)
        {
            if (current_row_height == -1)
                current_row_height = tab_nodes[i].offsetTop;
            else if (tab_nodes[i].offsetTop > current_row_height)
            {
                 previous_row_width = current_row_width;
                 current_row_width = 0;
                 current_row_height = tab_nodes[i].offsetTop;
                 rows[rows.length] = tab_nodes[i].id;
            }
            current_row_width += tab_nodes[i].offsetWidth;
        }
    }
    if (rows.length > 0) //If there's more than one row, reposition tabs
    {
        var temp_tab;
        //Loop through each row, position the tabs in backwards row order
        //I.E. second row is stacked on top of the first row, third row is stacked on top of the second
        for (i = 0, current_row = 0, current_pos = -1; i < tab_nodes.length; i++)
        {
            if (tab_nodes[i].innerHTML)
            {
                //If this is the beginning of a row, then reset the current position
                if (tab_nodes[i].id == rows[current_row])
                {
                    current_row++;
                    current_pos = -1;
                }
                if (current_row > 0)
                {
                    //Take the current tab, remove it, change some styling, then re-insert it either at the very beginning, or after the previously inserted tab
                    temp_tab = tab_controls.find("#" + tab_nodes[i].id);
                    //temp_tab.remove();
                    temp_tab.css("z-index", (5 - current_row));
                    temp_tab.css("top", (4 * current_row));
                    temp_tab.css("position", "relative");
                    if (current_pos == -1)
                        tab_controls.prepend(temp_tab);
                    else
                        temp_tab.insertAfter("#" + current_pos);
                   //Track the newly inserted tab (the next insert will go after this one)
                   current_pos = temp_tab.attr("id");
                }
            }
        }
        //Add in a spacer tab if the last row is smaller than the previous
        if (previous_row_width > current_row_width + 5)
            temp_tab.append("<div style='width: " + (jQuery("#attribute_search_control_div").attr("offsetWidth") - current_row_width - 5) + "px; height: 21px; float: left;' id='spacer_div'>&nbsp;</div>")
    }
}

