///////////////////////////////////////////////////
//
// these functions depend on:
// * utils.js
// * prototype.js
// * cookiejar.js
// * cookie.js
//
///////////////////////////////////////////////////

var site_url = 'http://www.localhelpwanted.net/cincinnati';

//
// create our cookie jar (cookiejar.js)
//

jar = new CookieJar({
    expires:3600,   // seconds
    path: '/'
});

//
// define vars
//

var MAX_RECENT_SEARCHES = 30;
var MAX_RECENT_SEARCHES_DISPLAY = 5;

var search_sortby = '';
var search_subsortby = '';
var search_subsortby_reversed = 0;
var search_filters = new Hash();
var search_filters_heads = new Hash();
var search_filters_values = new Hash();
var current_filters_display = new Hash();
var search_sortby_values = new Hash();

//
// initialise these from the query string
// 

search_filters.set('location', getQuerystring('location'));
search_filters.set('category', getQuerystring('category'));
search_filters.set('age', getQuerystring('age'));
search_filters.set('type', getQuerystring('type'));
search_filters.set('experience', getQuerystring('experience'));
search_filters.set('company', getQuerystring('company'));

//
// only elements defined above will be displayed in the 'current filters' area
//

search_filters.each(function(pair)
{
    current_filters_display.set(pair.key, 1);
});

//
// additionally these args will be passed to the ajax call
//

search_filters.set('display', getQuerystring('display'));
search_filters.set('offset', getQuerystring('offset'));
search_filters.set('perpage', getQuerystring('perpage'));
search_filters.set('what', getQuerystring('what'));
search_filters.set('where', getQuerystring('where'));
search_filters.set('titleonly', getQuerystring('titleonly'));
search_filters.set('wordmatch', getQuerystring('wordmatch'));
search_filters.set('radius', getQuerystring('radius'));

search_filters.set('company_name', getQuerystring('company_name'));    // from ByCompany tab
search_filters.set('location_type', getQuerystring('location_type'));  // from ByLocation tab
search_filters.set('location_id', getQuerystring('location_id'));      // from ByLocation tab
search_filters.set('category_type', getQuerystring('category_type'));  // from ByCategory tab
search_filters.set('category_id', getQuerystring('category_id'));      // from ByCategory tab
search_filters.set('search_name', getQuerystring('search_name'));      // from ByCompany+ByCategory+ByLocation tab

//
// define nice display names
// 

search_filters_heads.set('location', 'Location');
search_filters_heads.set('category', 'Category');
search_filters_heads.set('age', 'Updated');
search_filters_heads.set('type', 'Job Type');
search_filters_heads.set('experience', 'Experience');
search_filters_heads.set('company', 'Company');

//
// define nice display values
// 

search_filters_values.set('age', new Hash());
search_filters_values.get('age').set('0', 'Today');
search_filters_values.get('age').set('2', '&lt;2 days');
search_filters_values.get('age').set('7', '&lt;7 days');
search_filters_values.get('age').set('30', '&lt;30 days');
search_filters_values.get('age').set('60', '&lt;60 days');

//search_filters_values['type'] = new Hash();
//search_filters_values['type']['full'] = 'Full Time';
//search_filters_values['type']['part'] = 'Part Time';
//search_filters_values['type']['contract'] = 'Contract';
//search_filters_values['type']['project'] = 'Project';
//search_filters_values['type']['perday'] = 'Per Day';
//search_filters_values['type']['commission'] = 'Commision';
//search_filters_values['type']['shift'] = 'Shift Work';
//search_filters_values['type']['evening'] = 'Evenings';
//search_filters_values['type']['weekend'] = 'Weekends';

search_filters_values.set('experience', new Hash());
search_filters_values.get('experience').set('0', 'none');
search_filters_values.get('experience').set('1', '<1 years');
search_filters_values.get('experience').set('2', '<2 years');
search_filters_values.get('experience').set('3', '<3 years');
search_filters_values.get('experience').set('4', '<4 years');
search_filters_values.get('experience').set('5', '<5 years');
search_filters_values.get('experience').set('6', '<6 years');
search_filters_values.get('experience').set('7', '<7 years');
search_filters_values.get('experience').set('8', '<8 years');
search_filters_values.get('experience').set('9', '<9 years');

search_sortby_values.set('newest', 'Newest');
search_sortby_values.set('oldest', 'Oldest');
search_sortby_values.set('viewed', 'Most Viewed');
search_sortby_values.set('applied', 'Most Applications');
search_sortby_values.set('saved', 'Most Saved');
search_sortby_values.set('closest', 'Closest Locations');
search_sortby_values.set('title', 'Title'); 
search_sortby_values.set('company', 'Company'); 
search_sortby_values.set('category', 'Category'); 
search_sortby_values.set('location', 'Location'); 
search_sortby_values.set('audio', 'Audio'); 
search_sortby_values.set('video', 'Video'); 
search_sortby_values.set('added', 'Added Date'); 
search_sortby_values.set('expiry', 'Expiry Date'); 

//
// the functions...
// 

function sortby(s)
{
    if (s == null) s = '';
    search_sortby = s;
    search_refresh();
}

function subsortby(s)
{
    if (s == null) s = '';

    //alert("s="+s+" search_subsortby="+search_subsortby+" search_subsortby_reversed="+search_subsortby_reversed);

    if (search_subsortby == s)
        search_subsortby_reversed = search_subsortby_reversed ? 0 : 1;
    else 
    {
        search_subsortby = s;
        search_subsortby_reversed = 0;
    }

    search_refresh();
}

function del_filter(f)
{
    search_filters.set(f, '');
    search_filters.set('offset', 0);
    search_refresh();
}

function add_filter(f, v)
{
    set_recent_searches();
    search_filters.set(f, v);
    search_filters.set('offset', 0);
    search_refresh();
}

function del_all_filters()
{
    search_sortby = '';
    search_subsortby = '';
    search_filters.set('location', '');
    search_filters.set('category', '');
    search_filters.set('age', '');
    search_filters.set('type', '');
    search_filters.set('experience', '');
    search_filters.set('company', '');
    search_filters.set('offset', 0);
    search_refresh();
}

function display_format(display)
{
    //
    // set the format and save it in our cookies
    //

    search_filters.set('display', display);
    save_attrib('display', display);

    //
    // ensure the user hasn't requested too many items for the new format
    //

    if (display == 'grid' && search_filters.get('perpage') == 10)
        search_filters.set('perpage', 50);

    if (display == 'browse' && search_filters.get('perpage') == 200)
        search_filters.set('perpage', 100);

    search_refresh(2);
}

function save_attrib(name, value)
{
    jar.put(name, value);
}

function get_attrib(name)
{
    var value = jar.get(name);
    if (value == null) return '';
    return value;
}

function display_perpage(count)
{
    search_filters.set('perpage', count);
    search_refresh(2);
}

function display_offset(offset)
{
    search_filters.set('offset', offset);
    search_refresh(2);
    scroll_page('search_main');
}

function set_category(category)
{
    search_filters.set('category', category);
    search_filters.set('offset', 0);
    search_refresh();
}

function set_location(str)
{
    search_filters.set('location', str);
    search_filters.set('offset', 0);
    search_refresh();
}

function search_refresh(which_div)
{
    //
    // provide the option of just refreshing the filters
    // div or the results div. default is both
    //

    var refresh_filters = 1;
    var refresh_results = 1;

    if (which_div == 1) refresh_results = 0;
    if (which_div == 2) refresh_filters = 0;

    //
    // first send the ajax request to refresh the main content
    // the div 'search_results' is defined in 'search_results.html'
    // 
    
    var url = 'search.cgi?htmlpartial=1';
    var current_filters = '';
    var num_filters = 0;
    
    //
    // add sorting to the display
    //

    if (search_sortby != '')
    {
        url += '&sortby=' + search_sortby;

        current_filters = '<font color="gray">' + search_sortby_values.get(search_sortby) + '</font>' +
            ' <a style="text-decoration: none;" href="javascript:sortby();"><font color=red><b>x</b></font></a>' +
            '<br/>';

        num_filters++;
    }

    if (search_subsortby != '')
    {
        url += '&subsortby=' + search_subsortby + '&subsortby_reversed=' + search_subsortby_reversed;

        current_filters = '<font color="gray">Sort: ' + search_sortby_values.get(search_subsortby) + '</font>' +
            ' <a style="text-decoration: none;" href="javascript:subsortby();"><font color=red><b>x</b></font></a>' +
            '<br/>';

        num_filters++;
    }

    //
    // add filters to the display
    //

    search_filters.each(function(pair)
    {
        //
        // add any non-null values to the ajax url
        //

        if (pair.value != '') url += '&' + pair.key + '=' + escape(pair.value);

        //
        // build our string for the list of currently applied filters
        //

        if (pair.value != '' && current_filters_display.get(pair.key) != null)
        {
            var niceval = unescape(pair.value);

            if (search_filters_values.get(pair.key) != null && search_filters_values.get(pair.key).get(pair.value) != '')
            {
                niceval = search_filters_values.get(pair.key).get(pair.value);
            }

            current_filters +=  
                            '<font color="gray">' +
                            search_filters_heads.get(pair.key) + '</font> <i>' + 
                            niceval + '</i>' +
                            ' <a style="text-decoration: none;" href="javascript:del_filter(\'' + pair.key + '\');"><font color=red><b>x</b></font></a>' +
                            '<br/>';

            num_filters++;
        }
    });

    if (num_filters != 0)
    {
        current_filters = 'You have refined by:<br/>' + current_filters;

        if (num_filters > 1) 
            current_filters += '<a style="text-decoration: none;"href="javascript:del_all_filters();">Remove All <font color=red><b>x</b></font></a>';
    }
    else
        current_filters = '<font color=gray><i>No filters applied</i></font>';

    //
    // set_div_from_url() is defined in utils.js but this could be
    // be changed to use the prototype one, etc
    //

    if (refresh_results) set_div_from_url('search_results', url);

    //
    // now update the current filters list
    // the div 'current_filters' is defined in 'search_filters.html'
    // 

    if (refresh_filters)
    {
        set_div_from_str('current_filters', current_filters);
        set_div_from_str('recent_searches', get_recent_searches());
        set_div_from_str('save_search', get_save_search_html());
    }
}

///////////////////////////////////////////////////
// to reload a new search

function new_search(options)
{
    // this way would be nicer...
    //var url = 'search.cgi?mode=browse&format=nohdrs&' + options;
    //set_div_from_url('search_main', url);
    

    var url = 'search.cgi?mode=browse&' + options;
    open_waiting_page();
    document.location = url;
}

function open_page(url)
{
    //
    // this will break if the url doesn't already have a '?' in it somewhere...
    // 
    
    var referer = escape('search.cgi?' + get_save_search_url());
    open_waiting_page();
    document.location = url + '&http_referer=' + referer;
}

///////////////////////////////////////////////////
// by-company tab
//

function show_company_logo(id)
{
    show('company_logo_' + id);

    //var id = document.getElementById('company_logo');
    //id.style.top = "100px";
    //id.style.left = "100px";
    //id.style.display = 'block';
}

function hide_company_logo(id)
{
    hide('company_logo_'+id);
}

///////////////////////////////////////////////////
//
// these functions just handle the dynamnic items in
// the mysearch/further-flters column

//
// saved searches included
//

function show_saved_closed()
{
	hide('saved_open');
	show('saved_closed');
}

function show_saved_open()
{
	hide('saved_closed');
	show('saved_open');
}

//
// recent searches included
//

function show_recent_closed()
{
	hide('recent_open');
	show('recent_closed');
}

function show_recent_open()
{
	hide('recent_closed');
	show('recent_open');
}

//
// rss feed included
//

function show_rss_closed()
{
	hide('rss_open');
	show('rss_closed');
}

function show_rss_open()
{
	hide('rss_closed');
	show('rss_open');
}

//
// locations included
//

function show_locations_closed()
{
	hide('locations_open');
	show('locations_closed');
}

function show_locations_open()
{
	hide('locations_closed');
	show('locations_open');
}

function show_locations_part()
{
	hide('locations_full');
	show('locations_part');
}

function show_locations_full()
{
	hide('locations_part');
	show('locations_full');
}

//
// my search included
//

function show_mysearch_closed()
{
	hide('mysearch_open');
	show('mysearch_closed');
}

function show_mysearch_open()
{
	hide('mysearch_closed');
	show('mysearch_open');
}

//
// locations included
//

function show_locations_closed()
{
	hide('locations_open');
	show('locations_closed');
}

function show_locations_open()
{
	hide('locations_closed');
	show('locations_open');
}

function show_locations_part()
{
	hide('locations_full');
	show('locations_part');
}

function show_locations_full()
{
	hide('locations_part');
	show('locations_full');
}

//
// job categories
//

function show_categories_closed()
{
	hide('categories_open');
	show('categories_closed');
}

function show_categories_open()
{
	hide('categories_closed');
	show('categories_open');
}

function show_categories_part()
{
	hide('categories_full');
	show('categories_part');
}

function show_categories_full()
{
	hide('categories_part');
	show('categories_full');
}

//
// last updated
//

function show_updated_closed()
{
	hide('updated_open');
	show('updated_closed');
}

function show_updated_open()
{
	hide('updated_closed');
	show('updated_open');
}

//
// job type
//

function show_type_closed()
{
	hide('type_open');
	show('type_closed');
}

function show_type_open()
{
	hide('type_closed');
	show('type_open');
}

//
// experience
//

function show_experience_closed()
{
	hide('experience_open');
	show('experience_closed');
}

function show_experience_open()
{
	hide('experience_closed');
	show('experience_open');
}

//
// company
//

function show_company_closed()
{
	hide('company_open');
	show('company_closed');
}

function show_company_open()
{
	hide('company_closed');
	show('company_open');
}

//
// relevance
//

function show_relevance_closed()
{
	hide('relevance_open');
	show('relevance_closed');
}

function show_relevance_open()
{
	hide('relevance_closed');
	show('relevance_open');
}

//
// complete panel
//

function show_filters_panel()
{
	hide('filters_panel_closed');
	show('filters_panel_open');
}

function hide_filters_panel()
{
	hide('filters_panel_open');
	show('filters_panel_closed');
}

/////////////////////////////////////////////////////////
// provide two functions
// * set_recent_searches() - add current page to the list
// * get_recent_searches() - list as html
/////////////////////////////////////////////////////////

//
// add the current url as a recent search
// 
 
function set_recent_searches()
{
    if (getQuerystring('action') != '') return;

    var rs = jar.get('rs');
    if (rs == null) rs = new Array();

    //
    // try and work out a title for this search
    // 

    var title = '';

    //
    // if we have what/where the name is easy
    // 

    var what = getQuerystring('what');
    var where = getQuerystring('where');
    var search_name = getQuerystring('search_name');

    if (what != '') title = what;

    if (where != '')
    {
        if (title != '') title += ' - ';
        title += where;
    }

    //
    // if still blank need to do something more clever
    // 

    if (title == '')
    {
        if (search_name != '')
        {
            title = search_name;
        }
    }

    if (title == '') return;
    
    //
    // first check to see if it is already in the list
    //

    for (i=0; i<rs.size(); i++)
    {
        if (rs[i].title == title) return;
    }

    var index = rs.size();

    //
    // shuffle down up 1 to make a free slot if full
    //

    if (index >= MAX_RECENT_SEARCHES)
    {
        for (i=0; i<MAX_RECENT_SEARCHES; i++)
        {
            rs[i] = rs[i+1];
        }

        index = MAX_RECENT_SEARCHES;
    }

    //
    // add our new entry
    //

    rs[index] = { title: title, url: location.href };

    //
    // save our array back to the cookie jar
    //

    jar.put('rs', rs);
}

//
// get the recent searches in html
//

function get_recent_searches()
{
    var html = '';
    var rs = jar.get('rs');

    if (rs == null || rs.size() == 0) return '';

    var count = MAX_RECENT_SEARCHES_DISPLAY;

    for (i=rs.size()-1; i>=0 && count>=0; i--, count--)
    {
        html += '<a href="' + rs[i].url + '">' + unescape(rs[i].title) + '</a><br/>';
    }

    html += '<a href="javascript:clear_recent_searches();">Remove All <font color=red><b>x</b></font></a>';

    return html;
}

//
// remove a search from our cookies
//

function rmsearch(id)
{
    var rs = jar.get('rs');

    for (i=id; i<rs.size(); i++)
    {
        rs[i] = rs[i+1];
    }

    jar.put('rs', rs);
    document.location = 'search.cgi?&mode=mysearches';
}

//
// create the link to save this search
// 

function get_save_search_url()
{
    var url = '';

    if (search_sortby != '') url += '&sortby=' + search_sortby;
    if (search_subsortby != '') url += '&subsortby=' + search_subsortby + '&subsortby_reversed=' + search_subsortby_reversed;

    search_filters.each(function(pair)
    {
        if (pair.value != '') 
        {
            url += '&' + pair.key + '=' + escape(pair.value);
        }
    });

    return url;
}

function get_save_search_html()
{
    var url = '';
    var rss = '';

    if (search_sortby != '') url += '&sortby=' + search_sortby;
    if (search_subsortby != '') url += '&subsortby=' + search_subsortby + '&subsortby_reversed=' + search_subsortby_reversed;

    search_filters.each(function(pair)
    {
        if (pair.value != '') 
        {
            url += '&' + pair.key + '=' + escape(pair.value);
            if (pair.key != 'offset' && pair.key != 'perpage')
                rss += '&' + pair.key + '=' + escape(pair.value);
        }
    });

    rss += '&perpage=500';

    if (url == '') return '';

    var html = '';
    var username = get_cookie('mojousn');

    if (username == null || username == '')
    {
        var rs = jar.get('rs');
        var id = rs.size() - 1;

        return '<a href="javascript:login_to_save_search(' + id + ');">Saved Search</a><br>' +
               '<a href="javascript:login_to_create_alert(' + id + ');">Active Alert</a><br>' +
               '<a href="javascript:show_bookmarks(\'' + escape(rss) + '\');">Bookmark</a>';
    }
    else {
        return '<a href="search.cgi?'+ url + '&action=mksearch">Saved Search</a><br>' +
               '<a href="search.cgi?'+ url + '&action=mkalert">Active Alert</a><br>' +
               '<a href="javascript:show_bookmarks(\'' + escape(rss) + '\');">Bookmark</a>';
    }
}

//
// set+get convenience function
//

function update_recent_searches()
{
    set_recent_searches();
    return get_recent_searches();
}

//
// just clear the search list and refresh
//

function clear_recent_searches()
{
    jar.put('rs', null);
    search_refresh(1);
}

//
// various ajax functions
//

function show_company_video(id)
{
    http_request(show_company_video_aux, 'search.cgi?mode=company_video&id='+id, 0);
}

function show_company_video_aux(video_html)
{
    jQuery.blockUI({ message: video_html, centerY: 0, css: { top: '50px', left: (jQuery(window).width() - 620) /2 + 'px', background: '#ccc', color: '#4D741A', border: 'solid', width: '600px', padding: '10px', '-webkit-border-radius': '10px', '-moz-border-radius': '10px' } });
}

function close_company_video()
{
    jQuery.unblockUI();
}

function show_company_video_page(id)
{
    http_request(show_company_video_page_aux, 'search.cgi?mode=company_video_link&id='+id, 0);
}

function show_company_video_page_aux(video_html)
{
    jQuery.blockUI({ message: video_html, centerY: 0, css: { top: (jQuery(window).height() - 570) /2 + 'px', left: (jQuery(window).width() - 870) /2 + 'px', width: '850px', height: '550px', background: '#ccc', color: '#4D741A', border: 'solid', padding: '10px', '-webkit-border-radius': '10px', '-moz-border-radius': '10px' } });
}

function edit_activealert(id)
{
    http_request(edit_activealert_aux, 'search.cgi?action=chalert_popup&id=' + id, 0);
}

function edit_activealert_aux(html)
{
    jQuery.blockUI({ message: html, centerY: 0, css: { top: '5px', left: (jQuery(window).width() - 720) /2 + 'px', background: '#fff', color: '#4D741A', border: 'solid', width: '700px', padding: '5px', '-webkit-border-radius': '5px', '-moz-border-radius': '5px'} });
}

function login_to_save_search(i)
{
    var rs = jar.get('rs');
    var referer = rs[i].url + '&action=mksearch';
    var url = 'psp.cgi/site_login_popup.html?message=You must login to Save Your Search&referer=' + escape(referer);

    http_request(login_to_save_search_aux, url, 0);
}

function login_to_save_search_aux(html)
{
    jQuery.blockUI({ message: html, centerY: 0, css: { top: '50px', left: (jQuery(window).width() - 400) /2 + 'px', background: '#fff', color: '#4D741A', border: 'solid', width: '400px', padding: '10px', '-webkit-border-radius': '10px', '-moz-border-radius': '10px' } });
}

function login_to_create_alert(i)
{
    var rs = jar.get('rs');
    var referer = rs[i].url + '&action=mkalert';
    var url = 'psp.cgi/site_login_popup.html?message=You must login to create your Active Alert&referer=' + escape(referer);

    http_request(login_to_create_alert_aux, url, 0);
}

function login_to_create_alert_aux(html)
{
    jQuery.blockUI({ message: html, centerY: 0, css: { top: '50px', left: (jQuery(window).width() - 420) /2 + 'px', background: '#fff', color: '#4D741A', border: 'solid', width: '400px', padding: '10px', '-webkit-border-radius': '10px', '-moz-border-radius': '10px' } });
}

function show_bookmarks(url)
{
    var params = unescape(url);
    var full_url = site_url + '/cgi-bin/search.cgi?tmpl_flavor=rss' + url;

    full_url = escape(full_url);

    http_request(show_bookmarks_aux, 'psp.cgi/search_rss_feeds.html?RSS_URL=' + full_url, 0);
}

function show_bookmarks_aux(html)
{
    jQuery.blockUI({ message: html, centerY: 0, css: { top: '200px', left: (jQuery(window).width() - 720) /2 + 'px', background: '#fff', color: '#4D741A', border: 'solid', width: '700px', padding: '10px', '-webkit-border-radius': '10px', '-moz-border-radius': '10px' } });
}

function edit_hotlist_notes(id)
{
    var date= new Date();
    var url = 'search.cgi?&mode=edit_hotlist_notes&id=' + id + '&epoch=' + date.getTime();
    http_request(edit_hotlist_notes_aux, url, 0);
}

function edit_hotlist_notes_aux(html)
{
    jQuery.blockUI({ message: html, centerY: 0, css: { top: '50px', left: (jQuery(window).width() - 520) /2 + 'px', background: '#fff', color: '#4D741A', border: 'solid', width: '500px', padding: '10px', '-webkit-border-radius': '10px', '-moz-border-radius': '10px' } });
}

function view_job(job_id)
{
    //var url = 'Jobs.cgi?action=view&type=ad&subtype=print&id=' + job_id;
    //var url = 'psp.cgi/site_login_popup.html?message=You must login to Save Your Search&referer=';
    var url = 'Jobs.cgi';
    http_request(view_job_aux, url, 0);
}

function view_job_aux(html)
{
    jQuery.blockUI({ message: html, centerY: 0, css: { top: '50px', left: (jQuery(window).width() - 520) /2 + 'px', background: '#fff', color: '#4D741A', border: 'solid', width: '500px', padding: '10px', '-webkit-border-radius': '10px', '-moz-border-radius': '10px' } });
}



