var selectedTab;

// shorthand to document.getElementById
function _$(id) { return document.getElementById(id); }

//preload images
var search_multisearch_images = [ 'search_whattodo.gif', 'search_wheretostay.gif', 'search_events.gif' ];
var search_multisearch_imgcache = {};
for (i = 0; i < search_multisearch_images.length; i++)
{
    img = search_multisearch_images[i];
    search_multisearch_imgcache[img] = new Image();
    search_multisearch_imgcache[img].src = 'images/widgets/search/multisearch/' + img;
}
var search_results_img_expand = 'images/widgets/myhawaii/search_results_expandlistin.gif';
var search_results_img_close  = 'images/widgets/myhawaii/search_results_closelist.gif';
var img1 = new Image(); img1.src = search_results_img_expand;
var img2 = new Image(); img2.src = search_results_img_close;

function search_multisearch_selectTab(tab)
{
    var all_fields = ['what_to_do', 'where_to_stay', 'events'];
    var config = {
        'what_to_do': {
            'img': 'search_whattodo.gif'
        },
        'where_to_stay': {
            'img': 'search_wheretostay.gif'
        },
        'events': {
            'img': 'search_events.gif'
        }
    };

    var img = config[tab].img;

    header_img = document.getElementById('tabs_img');
    header_img.src = search_multisearch_imgcache[img].src;

    for (f in all_fields)
    {
        f1 = document.getElementById('search-multisearch_' + all_fields[f]);
        f2 = document.getElementById('search-multisearch_' + all_fields[f]);
        if (f1) f1.style.display = 'none';
        if (f2) f2.style.display = 'none';
    }

    if (f1 = document.getElementById('search-multisearch_' + tab))
    {
        f1.style.display = '';
    }

    selectedTab = tab;
}


// submits a form if Enter key is detected
// use like: <input type="text" name="q" onkeypress="return search_multisearch_keypress(this.form, event);" />
function search_multisearch_keypress(theform, event)
{
    // For IE
    if (window.event && window.event.keyCode == 13)
    {
        search_multisearch_submitForm(theform);
    }
    // For Netscapish
    else if (event && event.which == 13)
    {
        search_multisearch_submitForm(theform);
    }

    return true;
}


function search_multisearch_selectCategory(id)
{
    if (id != "")
    {

        // put in a Loading message
        fld = document.getElementById('search-multisearch-sub_categories');
        fld.options.length = 0;
        fld.options[0] = new Option('- Loading -', '');

        doAjaxCall('GetSubCategoriesById', [id], search_multisearch_updateSubCategories);

    }
}

var categories;

function search_multisearch_updateSubCategories(response)
{
    try {eval('categories = '+response)} catch (e) {return false}

    fld = document.getElementById('search-multisearch-sub_categories');
    fld.options.length = 0;

    for (id in categories)
    {
        fld.options[fld.options.length] = new Option(categories[id], id);
    }
}

function search_multisearch_submitForm(which_form)
{
    if(which_form.q)
    {
        if (which_form.q.value == 'optional')
        {
            which_form.q.value = '';
        }
    }
    which_form.submit();

    return true;

}

function search_multisearch_toggleExpand()
{
    c  = document.getElementById('search-multisearch_content');
    b1 = document.getElementById('search-multisearch_base1');
    b2 = document.getElementById('search-multisearch_base2');
    collapsed = (c.style.display == 'none');

    c.style.display  = (collapsed ? '' : 'none');
    b1.style.display = (collapsed ? '' : 'none');
    b2.style.display = (collapsed ? 'none' : '');

    return true;
}

function search_results_expand(row_num)
{
    row = document.getElementById('search_results_row_' + row_num);
    row.style.display = (row.style.display == 'none' ? '' : 'none');

    img = document.getElementById('search_results_expand_' + row_num);
    if (null != img)
    {
        img.src = (row.style.display == 'none' ? search_results_img_expand : search_results_img_close);
    }
}

function searchresults_display(url_params)
{
    searchresults_reload(url_params, 0);
    search_modifyresults_reload(url_params, 250);
}

function searchresults_reload(url_params, delay)
{
  if(delay == null) { delay = 0; }

  var container = document.getElementById('search-results-block');
  if (container != null)
  {
    widget = '[[Search:Results ajax_mode"true" gmap_code="true"]]';
    options = {
      location: document.location.pathname + '?' + url_params,
      append_request: url_params,
      noprogressbar: (delay == 0 ? true : false)
      };
    delayGetWidget(delay, 'search-results', widget, container.parentNode, searchresults_done, options);
  }
}

function searchresults_done(response)
{
    roundCorners();

    if (progressbar_default != null)
    {
        progressbar_default.stop();
        progressbar_default.hideBar();
    }
}


function search_modifyresults_reload(url_params, delay)
{
  if(delay == null) { delay = 0; }

  var container = document.getElementById('search-modifyresults');
  if (container != null)
  {
    widget = '[[Search:ModifyResults ajax_mode"true"]]';
    options = {
      location: document.location.pathname,
      append_request: url_params,
      noprogressbar: true
      };
    delayGetWidget(delay, 'search-modifyresults', widget, container.parentNode, null, options);
  }
}

// This will take the inputs of the modify search form, and do an ajax call
function search_modifyresults(modifyform, ajax)
{
    if(ajax == null || ajax != true)
    {
        return true;
    }

    var queryString = 'types=' + encodeURIComponent(modifyform.types.value);

    if(modifyform.elements['location[]'] != null)
    {
        for (i = 0; i < modifyform.elements['location[]'].length; i++)
        {
            if(modifyform.elements['location[]'][i].checked == true)
            {
                queryString += '&location[]=' + modifyform.elements['location[]'][i].value;
            }
        }
    }
    if(modifyform.elements['category[]'] != null)
    {
        for (i = 0; i < modifyform.elements['category[]'].length; i++)
        {
            if(modifyform.elements['category[]'][i].checked == true)
            {
                queryString += '&category[]=' + modifyform.elements['category[]'][i].value;
            }
        }
    }
    if(modifyform.elements['subcategory[]'] != null)
    {
        for (i = 0; i < modifyform.elements['subcategory[]'].length; i++)
        {
            if(modifyform.elements['subcategory[]'][i].checked == true)
            {
                queryString += '&subcategory[]=' + modifyform.elements['subcategory[]'][i].value;
            }
        }
    }


    if (modifyform.date_begin != null && modifyform.date_begin != '')
    {
        queryString += '&date_begin=' + encodeURIComponent(modifyform.date_begin.value);
    }
    if (modifyform.date_end != null && modifyform.date_end != '')
    {
        queryString += '&date_end=' + encodeURIComponent(modifyform.date_end.value);
    }

    if (modifyform.sort != null && modifyform.sort != '')
    {
        queryString += '&sort=' + encodeURIComponent(modifyform.sort.value);
    }
    if (modifyform.letter != null && modifyform.letter != '')
    {
        queryString += '&letter=' + encodeURIComponent(modifyform.letter.value);
    }
    if (modifyform.hide_sellers != null && modifyform.hide_sellers.checked == true)
    {
        queryString += '&hide_sellers=' + encodeURIComponent(modifyform.hide_sellers.value);
    }

    if (modifyform.q != null && modifyform.q != '')
    {
        queryString += '&q=' + encodeURIComponent(modifyform.q.value);
    }

    search_modifyresults_reload(queryString, 1500);
    searchresults_reload(queryString, 2000);
}

function search_modifyresults_islands(modifyform, id)
{
    islands = modifyform.elements['location[]'];

    // If All Island was clicked on
    if(id == 0)
    {
        // uncheck the other islands
        if(islands[0].checked)
        {
            for (i = 1; i < islands.length; i++)
            {
                islands[i].checked = false;
            }
        }
    }
    // if any other island is checked, then uncheck All Islands
    else
    {
        var all = true;
        for (i = 1; i < islands.length; i++)
        {
            if(true == islands[i].checked)
            {
                all = false;
            }
        }

        if(all == true)
        {
            islands[0].checked = true;
        }
        else
        {
            islands[0].checked = false;
        }
    }
}

// synchronous multi-search widget

/**
 * Builds the sub category list
 * @param [selectBox] the calling select box
 */
function buildSubCategoryList(selectBox,sub_id)
{
    // get the sub category select box
    if(sub_id)
    {
        var subSelectBox = _$(sub_id);
    }
    else
    {
        var subSelectBox = _$("search-multisearch-sub_categories");
    }
    var selValue = selectBox.options[selectBox.selectedIndex].value;
    // get all child nodes of the selected category
    var subNodes = _$("cat_"+selValue).getElementsByTagName("span");

    // clear the previous list
    subSelectBox.options.length = 0;
    for (var i = 0 ; i < subNodes.length; ++i)
    {
        var subNode = subNodes[i];
        var text = subNode.getAttribute("sub_name");
        var value = subNode.getAttribute("sub_id");
        // add the new options
        subSelectBox.options[subSelectBox.options.length] = // below
            new Option(text, value);
    }
}


//  new categories functions utilizing Ajax

// pull the categories from /shared/search_categories.php
var req = '';
var sel_loc = '';
function GetCategories(location,updateElement,cat,section,table)
{
    if (location != '') {
        $('location').value = location;
        sel_loc = location;
    }

    // cancel request if selection changes
    if (req != '' && req != null)
    {
        req.transport.abort();
    }

    //console.log('first_location ', location);

    // make sure that if it s a sub_category is being searched on, the location is passed along.
    if (location == '' && updateElement == 'search-multisearch-sub_categories_what_to_do')    {
        if (sel_loc == 0) {
            location = '';
        } else {
            location = sel_loc;
        }
    }
    else if (location == 0)
    {
        location = '';
    }

    //console.log('third location ',location);

    // exit if missing these two items
    if (updateElement=='' || section=='')    {
        alert('missing items: \n ' + "location:" + location + "\n element = " + updateElement + "\n section = " + section);
        return false;
    }

    // setup url variables
    cat = (cat == "" || cat == "undefined") ? "" : cat;
    table = (table == '' || table == 'undefined') ? "listing" : table;
    isSubCat = (selected_subcategory) ? 'true' : "false";

    var url = base_href_js +"/shared/search_categories.php?section="+section+"&cat_id="+cat+"&location="+location+"&table="+table+"&subcat="+isSubCat;
    var callback = UpdateCategories;
    var queryString = "";

    // clone first item of the selected element to add back in later
    var theList = $(updateElement);
    var first_item = theList.options[0];


    //clear out sub cat element
    if (updateElement == 'what_to_do_cat') {
        $('search-multisearch-sub_categories_what_to_do').length=0;
        AddSelectOption(theList,'','',true);
    }


    // if changing the category back to "all categories", don't update the type dropdown
    if(updateElement == 'search-multisearch-sub_categories_what_to_do' && cat=='')
    {

        $('search-multisearch-sub_categories_what_to_do').length=0;
        AddSelectOption(theList,'','',true);
        return;
    }

    theList.length = 0; // clear out old list

    // add "loading" message as the first dropdown item
    AddSelectOption(theList,'Loading...','',true);

    // send the request
    req = new Ajax.Request(url, {
        method: 'get',
        parameters: queryString,
        asynchronous:false,
        onComplete: function(req)
        {
            theList.length = 0; // clear out old list
            var text = req.responseText;
            callback(text,updateElement);

        },
        onFailure: function(request) { alert('Error Retrieving Categories'); }

    });


}

// update the the select box with the new categories.
function UpdateCategories(response,updateElement)
{
    var response_ob = eval("(" + response + ")");
    var theList = $(updateElement);

    for(i=0; i<response_ob.length; i++)
    {
        var item = response_ob[i];
        //var selected = (item.id == selected_cat || item.id == selected_subcategory) ? true : false;
        AddSelectOption(theList, item.name + " ("+item.count+")", item.id, false);
    }

    req = null;


}


// actually add the new options to the select field (mainly for IE support)
function AddSelectOption(selectObj, text, value, isSelected)
{
    if (selectObj != null && selectObj.options != null)
    {
        selectObj.options[selectObj.options.length] =
            new Option(text, value, false, isSelected);
    }
}

//set selected if exists
function SetSelected(selectElement,value)
{
    var select = document.getElementById(selectElement);
    if (value != '' && value != null)
    {
        for (i=0; i<select.length; i++)
        {
            if (select.options[i].value == value)
            {
                select.value = value;
            }
        }
    }
}
