﻿var gServiceSelectorHidden;
var gTimeoutHide;

var gContainerCustomerType;
var gContainerLocationState;
var gContainerLocationRegion;
var gContainerSeek;
var gContainerNoSeek;
var gSearchButtonDisabled;

$(function() {
    gContainerCustomerType = $('div#service-selector .column2');
    gContainerLocationState = $('div#service-selector select#selIAmLocated');
    gContainerLocationRegion = $('div#service-selector select#selRegion');
    gContainerSeek = $('div#service-selector .column4 > div.visible');
    gContainerNoSeek = $('div#service-selector .column4 > div.hidden');

    AjaxUpdateCustomerTypes(true, gSelectedCustomerTypeIds);
    AjaxUpdateStates(true, gSelectedCustomerTypeIds, gSelectedStateId);
    AjaxUpdateRegions(true, gSelectedCustomerTypeIds, gSelectedStateId, gSelectedRegionId);
    AjaxUpdateSeeks(true, gSelectedCustomerTypeIds, gSelectedStateId, gSelectedRegionId, gSelectedSeekIds);

    gServiceSelectorHidden = true;

    if (gForceOpenClose == 1) {
        // OPEN
        ServiceSelectorForceOpen();
        gTimeoutHide = setTimeout(ServiceSelectorShowHide, 4000);
    } else if (gForceOpenClose == 2) {
        // CLOSE
        ServiceSelectorForceHide();
    } else {
        // DEFAULT - Demo if user doesn't have cookie

        // -------- uncomment this conditional statement to auto-show the service selector ------
        //if (!readCookie('serviceselectordemoed')) {
        //    gServiceSelectorHidden = true;
        //    ServiceSelectorShowHide();
        //    gTimeoutHide = setTimeout(ServiceSelectorShowHide, 4000);
        //    createCookie('serviceselectordemoed', true);
        //} else {
            gServiceSelectorHidden = true;
        //}
    }

    $('a#btnServiceSelector').click(function() {
        ServiceSelectorShowHide();
        return false;
    });

    $('div#service-selector .column2 > ul > li > input').live("click", function(e) {
        UpdateCustomerTypes();
    });

    $('div#service-selector select#selIAmLocated').change(function(e) {
        UpdateLocationState();
    });

    $('div#service-selector select#selRegion').change(function(e) {
        UpdateLocationRegion();
    });

    // Search
    $('div.column5 > a.search').click(function(e) {
        if (!gSearchButtonDisabled) {
            DoSearch();
        }
        return false;
    });

    // Reset
    $('div.column5 > a.reset').click(function(e) {
        DoReset();
        return false;
    });
});

function ServiceSelectorShowHide() {
    clearTimeout(gTimeoutHide);     // If timer for hide is still running
    
    if (gServiceSelectorHidden) {
        // Show
        gServiceSelectorHidden = false;
        $('div#service-selector div.services-content').show();
        $('div#service-selector').animate({ top: '141px' }, 400, function() { $('div#service-selector').effect("bounce", { times: 1, distance: 5, mode: "effect", direction: "down" }, 300); });
        //$('div#service-selector').animate({ top: '120px' }, { queue: false, duration: 600, easing: "bounceEaseOut" });
        $('a#btnServiceSelector').addClass('open');
    } else {
        // Hide
        gServiceSelectorHidden = true;
        $('div#service-selector').effect("bounce", { times: 1, distance: 5, mode: "effect" }, 300, function() { $('div#service-selector').animate({ top: '-25px' }, 400, function() { $('div#service-selector div.services-content').hide(); }); });
        //$('div#service-selector').animate({ top: '-25px' }, { queue: false, duration: 600, easing: "bounceEaseIn" });
        $('a#btnServiceSelector').removeClass('open');
    }
}

function AjaxUpdateCustomerTypes(asynchronous, selectCustomerTypeIds) {
    if (gServiceSelectorWebServicePath == '') {
        alert('Search Web-service path is not set');
        return;
    }

    if (gServiceSelectorFullPath == '') {
        alert('Search Full path is not set');
        return;
    }

    // Get list of checked boxes (in this case only from the function params)
    var currentVal;
    if (selectCustomerTypeIds != null)
        currentVal = selectCustomerTypeIds;
    else
        currentVal = new Array();
    
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: gServiceSelectorWebServicePath + "/GetServiceCustomerTypes",
        data: '{ }',
        dataType: "json",
        success: function(data, status) {
            var resultHtml = '<ul>';
            var recordCount = 0;

            jQuery.each(data.d, function() {
                resultHtml += "<li class='clear'>";
                resultHtml += "<input type='checkbox' value='" + this.Id + "' name='type_" + this.Id + "' id='type_" + this.Id + "' /><label for='type_" + this.Id + "'>" + this.Title + "</label>";
                resultHtml += "</li>";
                recordCount++;
            });
            resultHtml += '</ul>';

            // Remove the old UL
            gContainerCustomerType.remove('ul');
            
            // Append the new UL
            gContainerCustomerType.append(resultHtml);

            // Recheck any checkboxes
            jQuery.each(currentVal, function() {
                gContainerCustomerType.find('[value="' + this + '"]').attr('checked', 'checked');
            });
        },
        error: function(obj, status, error) {
            //alert("ERROR attempting to load 'Customer Type's");
        },
        complete: function(obj, status) {
            // Update Display
            UpdateDisplay();
        }
    });
}

function AjaxUpdateStates(asynchronous, customerTypeIds, selectStateId) {
    if (gServiceSelectorWebServicePath == '') {
        alert('Search Web-service path is not set');
        return;
    }

    if (gServiceSelectorFullPath == '') {
        alert('Search Full path is not set');
        return;
    }

    if (!isArray(customerTypeIds)) {
        customerTypeIds = new Array();
    }


    var currentVal;
    if (selectStateId != null)
        currentVal = selectStateId;
    else
        currentVal = gContainerLocationState.val();

    // Load new values
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: gServiceSelectorWebServicePath + "/GetServiceStates",
        data: '{ "customerTypes": ' + JSON.stringify(customerTypeIds) + ' }',
        dataType: "json",
        success: function(data, status) {
            var resultHtml = '';
            var recordCount = 0;

            jQuery.each(data.d, function() {
                resultHtml += "<option value='" + this.Id + "'>" + this.Title + "</option>";
                recordCount++;
            });

            // Add a "please select" to top
            if (recordCount > 0) {
                resultHtml = "<option value='-1'>Select State</option>" + resultHtml;
            }

            // Insert the returned HTML into the <select>.
            gContainerLocationState.html(resultHtml);

            // Select previous value
            gContainerLocationState.val(currentVal);

            if (gContainerLocationState.attr("selectedIndex") < 0)
                gContainerLocationState.attr("selectedIndex", 0);
        },
        error: function(obj, status, error) {
            //alert("ERROR attempting to load 'State's");
        },
        complete: function(obj, status) {
            // Update Display
            UpdateDisplay();
        }
    });
}

function AjaxUpdateRegions(asynchronous, customerTypeIds, stateId, selectRegionId) {
    if (gServiceSelectorWebServicePath == '') {
        alert('Search Web-service path is not set');
        return;
    }

    if (gServiceSelectorFullPath == '') {
        alert('Search Full path is not set');
        return;
    }

    if (!isArray(customerTypeIds)) {
        customerTypeIds = new Array();
    }

    if (isNull(stateId)) {
        stateId = -1;
    }

    var currentVal;
    if (selectRegionId != null)
        currentVal= selectRegionId;
    else
        currentVal = gContainerLocationRegion.val();
    
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: gServiceSelectorWebServicePath + "/GetServiceRegions",
        data: '{  "customerTypes": ' + JSON.stringify(customerTypeIds) + ', stateId:"' + stateId + '"}',
        dataType: "json",
        success: function(data, status) {
            var resultHtml = '';
            var recordCount = 0;

            jQuery.each(data.d, function() {
                resultHtml += "<option value='" + this.Id + "'>" + this.Title + "</option>";
                recordCount++;
            });

            // Add a "please select" to top
            if (recordCount > 0) {
                resultHtml = "<option value='-1'>Select Region</option>" + resultHtml;
            }

            // Insert the returned HTML into the <select>.
            gContainerLocationRegion.html(resultHtml);

            // Select previous value
            gContainerLocationRegion.val(currentVal);

            if (gContainerLocationRegion.attr("selectedIndex") < 0)
                gContainerLocationRegion.attr("selectedIndex", 0);
        },
        error: function(obj, status, error) {
            //alert("ERROR attempting to load 'Region's");
        },
        complete: function(obj, status) {
            // Update Display
            UpdateDisplay();
        }
    });
}

function AjaxUpdateSeeks(asynchronous, customerTypeIds, stateId, regionId, selectSeekIds) {
    if (gServiceSelectorWebServicePath == '') {
        alert('Search Web-service path is not set');
        return;
    }

    if (gServiceSelectorFullPath == '') {
        alert('Search Full path is not set');
        return;
    }

    if (!isArray(customerTypeIds)) {
        customerTypeIds = new Array();
    }

    if (isNull(stateId)) {
        stateId = -1;
    }

    if (isNull(regionId)) {
        regionId = -1;
    }

    // Get list of checked boxes
    var currentVal;
    if (selectSeekIds != null)
        currentVal = selectSeekIds;
    else
        currentVal = GetCheckboxCheckedArrayValues(gContainerSeek);

    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: gServiceSelectorWebServicePath + "/GetServiceSeeks",
        data: '{ "customerTypes": ' + JSON.stringify(customerTypeIds) + ', stateId:"' + stateId + '", regionId:"' + regionId + '"}',
        dataType: "json",
        success: function(data, status) {
            var resultHtml = '';
            var recordCount = 0;

            jQuery.each(data.d, function() {
                resultHtml += "<li class='clear'>";
                resultHtml += "<input type='checkbox' value='" + this.Id + "' name='seek_" + this.Id + "' id='seek_" + this.Id + "' /><label for='seek_" + this.Id + "'>" + this.Title + "</label>";
                resultHtml += "</li>";
                recordCount++;
            });

            // Add UL if any records
            if (recordCount > 0) {
                resultHtml = '<ul>' + resultHtml + '</ul>';
            }

            // remove old UL
            gContainerSeek.children('ul').remove();

            // Append the new UL (if any records)
            gContainerSeek.append(resultHtml);

            // Recheck any checkboxes
            jQuery.each(currentVal, function() {
                gContainerSeek.find('[value="' + this + '"]').attr('checked', 'checked');
            });

            // Show hide Seeks/NoServices based on if any where found
            if (recordCount > 0 || regionId <= 0) {
                gContainerSeek.show();
                gContainerNoSeek.hide();
            }
            else {
                gContainerSeek.hide();
                gContainerNoSeek.show();
            }
        },
        error: function(obj, status, error) {
            //alert("ERROR attempting to load 'Seeks'");
        },
        complete: function(obj, status) {
            // Update Display
            UpdateDisplay();
        }
    });
}

function ServiceSelectorForceHide() {
    clearTimeout(gTimeoutHide);     // If timer for hide is still running
    gServiceSelectorHidden = true;
    $('div#service-selector').animate({ top: '-25px' }, 0);
    $('a#btnServiceSelector').removeClass('open');
}

function ServiceSelectorForceOpen() {
    clearTimeout(gTimeoutHide);     // If timer for hide is still running
    gServiceSelectorHidden = false;
    $('div#service-selector').animate({ top: '120px' }, 0);
    $('a#btnServiceSelector').addClass('open');
}

// Cookie functions from http://www.quirksmode.org/js/cookies.html
function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name, "", -1);
}

function GetCheckboxCheckedArrayValues(objContainer) {
    var ret = new Array();
    objContainer.find('input[type="checkbox"]:checked').each(function(i) {
        ret[i] = $(this).attr('value');
    });
    return ret;
}

function ClearCheckboxes(objContainer) {
    objContainer.find('input[type="checkbox"]:checked').each(function(i) {
        $(this).attr('checked', false);
    });
}

function DoSearch() {
    var custTypeVals = GetCheckboxCheckedArrayValues(gContainerCustomerType);
    var stateVal = gContainerLocationState.val();
    var regionVal = gContainerLocationRegion.val();
    var seekVals = GetCheckboxCheckedArrayValues(gContainerSeek);
    var i;

    if (gServiceSelectorFullPath == '') {
        alert('Search Full path is not set');
        return;
    }

    var url = gServiceSelectorFullPath;
    url += "?";

    // Customer Types
    i = 0;
    jQuery.each(custTypeVals, function() {
        if (i > 0) {
            url += "&";    
        }
        url += "ct_" + i + "=" + this;
        i++
    });

    // Customer State / Region
    url += "&cls=" + stateVal;
    url += "&clr=" + regionVal;

    // Customer Seeks
    i = 0;
    jQuery.each(seekVals, function() {
        url += "&cs_" + i + "=" + this;
        i++
    });

    // Redirect
    window.location = url;
}

function isArray(obj) {
    if (obj instanceof Array) {
        return true;
    } else {
        return false;
    }
}

//-------------------------------------------------------------------
// isNull(value)
//   Returns true if value is null
//-------------------------------------------------------------------
function isNull(val) { return (val == null); }

function UpdateDisplay() {
    //gContainerCustomerType;
    var showButtons = true;
    
    // State
    if (gContainerLocationState.children().size() > 0) {
        gContainerLocationState.parent().show();
    } else {
        gContainerLocationState.parent().hide();
        showButtons = false;
    }
    
    // Region
    if (gContainerLocationRegion.children().size() > 0) {
        gContainerLocationRegion.parent().show();
    }
    else {
        gContainerLocationRegion.parent().hide();
        showButtons = false;
    }

    // Seeks
    if (gContainerSeek.children('ul').size() > 0) {
        gContainerSeek.show();
    }
    else {
        gContainerSeek.hide();
        showButtons = false;
    }

    if (showButtons) {
        ButtonsEnable();
    } else {
        ButtonsDisable();
    }
}

function ButtonsDisable() {
    gSearchButtonDisabled = true;
    $('div.column5 > a.search > img').attr(
        'src',
        $('div.column5 > a.search > img').attr('src').replace('btn-find.png', 'btn-find-disabled.png')
    );
    $('div.column5 > a.reset').hide();
}

function ButtonsEnable() {
    gSearchButtonDisabled = false;
    $('div.column5 > a.search > img').attr(
        'src',
        $('div.column5 > a.search > img').attr('src').replace('btn-find-disabled.png', 'btn-find.png')
    );
    $('div.column5 > a.reset').show();
}

function DoReset() {
    ClearCheckboxes(gContainerCustomerType);
    UpdateCustomerTypes();
}

function UpdateCustomerTypes() {
    var custTypeVals = GetCheckboxCheckedArrayValues(gContainerCustomerType);
    var stateVal = gContainerLocationState.val();
    var regionVal = gContainerLocationRegion.val();

    clearTimeout(gTimeoutHide);     // If timer for hide is still running

    AjaxUpdateStates(true, custTypeVals, null);
    AjaxUpdateRegions(true, custTypeVals, stateVal, null);
    AjaxUpdateSeeks(true, custTypeVals, stateVal, regionVal, null);
}

function UpdateLocationState() {
    var custTypeVals = GetCheckboxCheckedArrayValues(gContainerCustomerType);
    var stateVal = gContainerLocationState.val();
    var regionVal = gContainerLocationRegion.val();

    clearTimeout(gTimeoutHide);     // If timer for hide is still running

    AjaxUpdateRegions(true, custTypeVals, stateVal, null);
    AjaxUpdateSeeks(true, custTypeVals, stateVal, regionVal, null);
}

function UpdateLocationRegion() {
    var custTypeVals = GetCheckboxCheckedArrayValues(gContainerCustomerType);
    var stateVal = gContainerLocationState.val();
    var regionVal = gContainerLocationRegion.val();

    clearTimeout(gTimeoutHide);     // If timer for hide is still running

    AjaxUpdateSeeks(true, custTypeVals, stateVal, regionVal, null);
}

