﻿var firstView = true;
var loading = true;
var preLoadTimer;

$(function() {
    //   $("#tabs").hide();      //not sure if this will fix the problem of showing the tabs unformatted
    //   $("#tabs").tabs();

    $('.blink').focus(function() {
        if ($(this).val() == $(this).attr('title')) {
            $(this).val('');
        }
    });
    $('.blink').blur(function() {
        if ($(this).val() == '') {
            $(this).val($(this).attr('title'));
        }
    });

    //add autocomplete
    $('#locationTB').autocomplete(locData, {
        minChars: 0,
        //    max: 12,
        width: 500,
        autoFill: false,
        mustMatch: false,
        matchContains: true,
        scrollHeight: 150,
        scroll: true,
        multiple: false,
        formatItem: function(data, i, total) {
            return "<td style = \"width:350px\">" + data.areaOne + "</td> <td>" + data.areaTwo + "</td>";
            //    return "<div style = \"width:300px\";>" + data.areaOne + "</div>" + data.areaTwo;

        },
        formatMatch: function(data, i, max) {
            return data.areaOne + ", " + data.areaTwo;
        },
        formatResult: function(data, i, total) {
            if (data.areaOne != data.areaTwo)
                return data.areaOne + ", " + data.areaTwo;
            else return data.areaOne;
        }
    });

    //check if this is the first time typing or blur in location TB and replace backgrounf
    $('#locationTB').keydown(function() {
        if (firstView) {
            $(this).removeClass('text-field-no-loc')
                       .addClass('text-field');
            firstView = false;
        }
    })
    .blur(function() {  //remove help background image
        if (firstView) {
            $(this).removeClass('text-field-no-loc')
                   .addClass('text-field');
            firstView = false;
        }
        search_onchange();
    })
    //add result event to move id to hidden control
    .result(function(event, data, formatted) {
        $('#locationId').val(data.id);
        sucessfullyFoundMatch();
    })
    //set locationId to -1 if not a valid input
    .change(function() {
        if ($(this).val() == $(this).attr('title') || $(this).val() == '') {
            $('#locationId').val('-1');
            $(this).val('City, State, or Country...');
            $('.feedback-tab .inner').slideUp('slow');
        }
    })
    //select all contents on click
    .click(function() {
        $(this).select();
    });

    $('#searchTB').keydown(function() {
        //load feedback tab on 1 second idle state
        //clear prior timeout, if any
        window.clearTimeout(preLoadTimer);

        //create new timeout.
        preLoadTimer = window.setTimeout("TextBoxChange()", 800); //$(this).trigger('change'), 2000);
    });


    swap_select($('#for-sale-select'));
    swap_select($('#jobs-select'));
    swap_select($('#housing-select'));
    swap_select($('#price-select'), 100);
    swap_select($('#services-select'));
    swap_select($('#gigs-select'));
    swap_select($('#community-select'));
    swap_select($('#personals-select'));
    //swap_select($('#resumes-select'));

    swap_radio($('.radio-wrap'));
    swap_checkbox($('.checkbox-wrap'));
    $("#tabs").show();      //part of above

    //select all gigs as default   
    $('#gigs ul:eq(1) a:eq(1)').addClass('radio');


    //select instantly as default and add xml tags to instant alert text
    $('.alert a').eq(1).addClass('radio');
    /*
    
    //.prepend("<div id='instant-alert-help'><img src='css/images/question.png'/></div>&nbsp;")
    //                   .append("<div id='instant-alert-time'></div>")
    .qtip(  //tooltip for questionmark
    {
    content: {
    prerender: true,
    text: '"INSTANTLY" alerts you as soon as a new listing is posted.<div id="instant-help-time"><\div>'
    },
    position: {
    corner: {
    target: 'leftMiddle',
    tooltip: 'rightMiddle'
    }
    },
    style: {
    width: 250,
    padding: 6,
    background: '#e7e7e8',
    color: 'black',
    textAlign: 'center',
    border: {
    width: 3,
    radius: 0,
    color: '#947FC1'
    },
    tip: 'rightMiddle',
    name: 'dark' // Inherit the rest of the attributes from the preset dark style
    }
    });
    */
    //add onChange event to email TB to remove error border if valid email
    $('#emailTB').change(function() {
        removeErrorIfEmailValid();
    });

    //add click event to tabs
    $('#tabs').bind('tabsselect', function(event, ui) {
        if (!$(this).hasClass('.ui-tabs-selected'))
            search_onchange(ui.index);
    });

    //show page after load
    $('.shell').show();

    //put focus on textbox
    if ($('#locationId').val() == -1)
        $('#locationTB').focus();
    else
        $('#searchTB').focus();

    loading = false;
});

var initial_select_top = '24px';

//submit bitton actions
$('#submit-btn').live('mousedown', function() { $(this).addClass('submit-button-down'); })
                .live('mouseup', function() { $(this).removeClass('submit-button-down'); })
                .live('mouseout', function() { $(this).removeClass('submit-button-down'); })
                ;
                
//setup event for clicking on a dropdown area
$('.drop-down .current_val').live('click', function() {
    var ul = $(this).parent().find('ul:first');
    if ($(ul).is(':visible')) {             //if the dropdown is open and clicked on again, make it disapear
        $(ul).hide();
        $(ul).css('top', initial_select_top);
    } else {
        var doc_height = $('body').height() - 10;
        $(ul).show();
        var li = $(ul).find('li:last');
        if ($(li).offset().top + $(li).height() > doc_height) {     //if the list in dropdown is longer then page
            $(ul).css('top', (-$(ul).height() - 2).toString() + 'px');
            $(ul).hide();
            setTimeout(function() {
                $(ul).show();
            }, 1);
        } else {
            $(ul).css('top', initial_select_top);
        }
    }
});

//drop down click events
$('.drop-down a').live('click', function() {
    $('.drop-down a.current').removeClass('current');
    $(this).addClass('current');
    $(this).parents('.drop-down').find('.current_val div').html($(this).html());
    $(this).parents('.drop-down').find('ul').css('top', initial_select_top).hide();
    $('#' + $(this).parents('.drop-down:eq(0)').attr('fallback')).val($(this).attr('value'));
    search_onchange();
    return false;
});  

//if drop-down is open, allows you to click anywhere on site to hide it.
$('body').live('click', function(e) {
    var el = e.target || e.srcElement;

    var obj = $(el);
    if (obj.parents('.drop-down').length) {
        var this_ul = obj.parents('.drop-down').find('ul:eq(0)');
        $(this_ul).addClass('keep');
        $('.drop-down ul').not('.keep').hide();
        $('.drop-down ul').not('.keep').css('top', initial_select_top);
        $(this_ul).removeClass('keep');
        return;
    };
    $('.drop-down ul').hide();
    $('.drop-down ul').css('top', initial_select_top);
});

$('.bullet').live('click', function() {
    if (!$(this).hasClass('radio')) {               //if not selected
        var name = $(this).attr('fallback');
        if ($(this).hasClass('radiobox')) {        //if is a radio button, uncheck current selection
            $('.bullet[fallback="' + name + '"]').removeClass('radio');
        }
        $('input[name="' + name + '"]').removeAttr('checked');

        $('input[name="' + name + '"][value="' + $(this).attr('value') + '"]').attr('checked', 'checked');
        $(this).addClass('radio');
        if ($(this).parent().attr('class') != 'alert')  //if not an alert control
            search_onchange();
    }
    else if ($(this).hasClass('checkbox')) {       //uncheck for checkbox
        $(this).removeClass('radio');
        if ($(this).parent().attr('class') != 'alert')  //if not an alert control
            search_onchange();
    }

    return false;
});

function verifyLocationIsValid() {
    var locId = $('#locationId').val();

    if ((locId == -1) && ($('#locationTB').val() != 'City, State, or Country...')) {
        failedToFindMatch(false);
        return false;
    }
    
    var locInput = $('#locationTB').val();
    var idx = 0;
    for (var i = 0; i < locData.length; i++) {
        if (locData[i].id == locId) {
            idx = i;
            break;
        }
    }
    var formatLoc;
    if (locData[idx].areaOne != locData[idx].areaTwo)
        formatLoc = locData[idx].areaOne + ", " + locData[idx].areaTwo;
    else formatLoc = locData[idx].areaOne;

    if (formatLoc == locInput)
        return true
    else {
        $('#locationTB').val(formatLoc);
        return false;
    }
}

function sucessfullyFoundMatch() {
    $('#locationTB').removeClass('text-field-no-result');
    $('#locationTB').removeClass('text-field-error');
    $('#bad-location-feedback').hide();
}

function failedToFindMatch(fromKeyChange) {
    $('#locationId').val('-1');
    $('#locationTB').addClass('text-field-no-result');
    $('#bad-location-feedback').show();
    if (!fromKeyChange)
        $('.feedback-tab .inner').slideUp('slow');
}

//swap the dropdown (select) with custom dropdown
function swap_select(obj, width_cutout) {
    if (typeof width_cutout == 'undefined') {
        width_cutout = 0;
    }
    var default_width = 173;
    var html = '<div class="drop-down" fallback="' + $(obj).attr('id') + '"><div class="current_val"><div></div></div><ul>';
    var options = $(obj).find('option');
    for (var i = 0; i < options.length; i++) {
        html += '<li><a href="" value="' + $(options[i]).attr('value') + '">' + $(options[i]).html() + '</a></li>';
    };
    html += '</ul></div>';
    $(obj).before(html);
    $(obj).addClass('swapped');
    var dd = $('.drop-down[fallback="' + $(obj).attr('id') + '"]');
    $(dd).css('width', (default_width - width_cutout).toString() + 'px').find('ul, .current_val, .current_val div, a').each(function() {
        $(this).css('width', (parseInt($(this).css('width')) - width_cutout).toString() + 'px');
    });
    $(dd).find('a[value="' + $(obj).val() + '"]').click();      //select first element in dropwdown
    $(obj).hide();
}

//switch out the radio controls with custom ones
function swap_radio(objects) {
    for (var i = 0; i < objects.length; i++) {
        var wrap = objects[i];
        var checked = ($(wrap).find('input[checked]').length > 0) ? 'radio' : '';
        var html = '<a class="bullet radiobox ' + checked + '" href="" value="' + $(wrap).find('input').val() + '" fallback=' + $(wrap).find('input').attr('name') + '>' + $(wrap).find('label').html() + '</a>';
        $(wrap).before(html);
        $(wrap).hide();
    };
}

//switch out the checkbox controls with custom ones
function swap_checkbox(objects) {
    for (var i = 0; i < objects.length; i++) {
        var wrap = objects[i];
        var checked = ($(wrap).find('input[checked]').length > 0) ? 'radio' : '';
        var html = '<a class="bullet checkbox ' + checked + '" href="" value="' + $(wrap).find('input').val() + '" fallback=' + $(wrap).find('input').attr('name') + '>' + $(wrap).find('label').html() + '</a>';
        $(wrap).before(html);
        $(wrap).hide();
    };
}

function submit_onclick() {
    //validate controls
    if (!validateControls())
        return false;    
    //move data to hidden controls
    moveDataToHiddenControls();            
    return true;
}

function validateControls() {
    var valid = true;

    //verify query control
    var queryStr = $('#searchTB').val();
    if (queryStr.indexOf("&") != -1){
        $('#searchTB').addClass('text-field-error');
        valid = false;
    }
    else
        $('#searchTB').removeClass('text-field-error');
        
    //verify valid email
    var email = $('#emailTB').val();
    var filter = /^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
    if ((!filter.test(email)) || (email == "notifinder@gmail.com")) {
        $('#emailTB').addClass('text-field-error');
        valid = false;
    }
    else
        $('#emailTB').removeClass('text-field-error');

    //validate location control
    //var location = $('#locationDD').val();
    //if (location == -1) {
    //    $('#locationDD').addClass('drop-down-loc-error');
    var locationid = $('#locationId').val();
    if (locationid == '-1' || locationid == '') {
        $('#locationTB').addClass('text-field-error');    
        valid = false;
    }
    else
        $('#locationTB').removeClass('text-field-error');
    return valid;
}

function removeErrorIfEmailValid() {
    var email = $('#emailTB').val();
    var filter = /^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
    if ((filter.test(email)) && (email != "notifinder@gmail.com")) 
        $('#emailTB').removeClass('text-field-error');
}

function moveDataToHiddenControls() {  
    //type
    var $tabs = $('#tabs').tabs();
    var searchtype = $tabs.tabs('option', 'selected');
    $('#search-type').val(searchtype);

    //notify every
    $('#notify-every').val($('.alert a[class~=radio]').attr('value'));
    switch (searchtype) {
        case 1:     //jobs
            $('#search-attributes').val(getAttributes($("#jobs a[class~='radio']")));
            break;
        case 2:     //housing
            $('#search-attributes').val(getAttributes($("#housing a[class~='radio']")));
            break;
        case 4: //gigs
            $('#search-attributes').val(getAttributes($("#gigs a[class~='radio']")));
            break;
    }
}

//gets checkbox or radio controll attributes
function getAttributes(obj) {
    var optionsStr = '';
    var size = $(obj).size();
    if (size > 0)
        optionsStr += "*";
    for (var i = 0; i < size; i++) {
        optionsStr += $(obj).eq(i).attr('value');
        if (i+1 != size)
            optionsStr += '*';
    }            
    return optionsStr;
}

function TextBoxChange() {
    $('.feedback-tab .inner').slideUp('slow');
    search_onchange();
}
