﻿function IsVisible(e) {
    var isVisible = true;
    $(e).parents().each(function(i) {
        if ($(this).css('display') == 'none' || $(this).css('visibility') == 'hidden') {
            isVisible = false;
            return false;
        }
    });
    return isVisible;
}

function IsSameInput(e1, e2) {
    var id1 = $(e1).attr('id'), id2 = $(e2).attr('id');
    if (id1 == id2)
        return true;

    var name1 = $(e1).attr('name'), name2 = $(e2).attr('name');
    if (name1 == name2)
        return true;

    return false;
}

function GetSiblingInputs(e) { return $(e).closest('form').find(':input'); }

function GetInputIndex(e, inputs) {
    if (!inputs) inputs = GetSiblingInputs(e);
    var index = 0;
    inputs.each(function(i, ee) {
        if (IsSameInput(e, ee)) {
            index = i;
            return false;
        }
    });
    return index;
}

function NextInput(e, inputs) {
    if (!inputs) inputs = GetSiblingInputs(e);
    var index = 0;
    inputs.each(function(i, ee) {
        if (IsSameInput(e, ee)) {
            index = i;
            return false;
        }
    });

    index++;
    return inputs.length > index ? inputs.eq(index) : e;
}


function OnTextInputChange(input, mask, maxLength, exclusions, handler) {

	if (input == null) return;

    input.maxLength = maxLength;
    $(input).mask(mask);
    var lastValue = input.value;
    

    function onKeyUp(e) {
        var pos = $(this).getSelection().end;
        if (pos == maxLength) {
            $(input).change();
        }
    }

    function onChange()
    {
        if (input.value != lastValue) {

            if (input.value.match(/\d{5}/)) {
                lastValue = input.value;
                LastPostalCodeValue = lastValue; // Hacked Global
                handler(input, lastValue);
            }
        }
    };

    $(input).keyup(onKeyUp);
    $(input).change(onChange);
}

function SkipInput(input, exclusions) {

    var skip = false;
    for (var i = 0; i < exclusions.length; i++) {
        if (CurrentInput && CurrentInput.name && CurrentInput.name == exclusions[i]) {
            skip = true;
            break;
        }
    }

    if (!skip)
    return;

    var inputs = GetSiblingInputs(input);
    var nextIndex = GetInputIndex(input, inputs) + 1;
    var next = inputs.eq(nextIndex);

    var length = inputs.length;

    if (exclusions && exclusions.length) {
        while (nextIndex < length) {
            if (IsVisible(next)) {

                var isValid = true;
                $(exclusions).each(function(i, o) {
                    if ($(next).attr('name') == exclusions[i]) {
                        isValid = false;
                        return false;
                    }
                });

                if (isValid) {
                    break;
                }
            }
            nextIndex++;
            next = inputs.eq(nextIndex);
        }
    }
    else {
        while (nextIndex < length) {
            if (IsVisible(next))
                break;

            nextIndex++;
            next = inputs.eq(nextIndex);
        }
    }

    if (next) $(next).focus();
}

function PostalCode_OnKeyUpCallback(data) {
    var p = eval('(' + data + ')');
    if (p.ServiceResponse.response != 'True') return;
    var zipCodeInfo = p.ServiceResponse.ZipCodeInfo;


    if (LastPostalCodeValue != zipCodeInfo['@PostalCode'])
        return;
    
    var postalCode = document.getElementById('POSTALCODE');
    postalCode.value = zipCodeInfo['@PostalCode'];
    
    var item = document.getElementById('CITY');
    item.value = zipCodeInfo['@CityName'];
    
    var newStateValue = zipCodeInfo['@StateAbbr'];

    var ddl = document.getElementById('STATE');
    for (var x = 0; x < ddl.options.length; x++) {
        if (ddl.options[x].value == newStateValue) {
            ddl.options[x].selected = true;
            break;
        }
    }

    
    SkipInput(postalCode, ['POSTALCODE', 'STATE', 'CITY']);
}

var CurrentInput;
var LastPostalCodeValue;

$(document).ready(function () {

    $('input').focus(function () {
        CurrentInput = this;
    });

    $('select').focus(function () {
        CurrentInput = this;
    });

    var postalCode = document.getElementById('POSTALCODE');

    if (typeof loadCityState != 'undefined' && loadCityState === true) {
        OnTextInputChange(postalCode, '99999', 5, ['STATE', 'CITY'], function (input, lastValue) {
            WrapServiceExecute('Zipcode_Get', PostalCode_OnKeyUpCallback, postalCode.value, '', '');
        });
    }
});

