﻿/**
* @idea Gunger [gunger.ru]
* @author Vladimir Yunev
* @desc Create semaphore on text or password input with jQuery
* @version 1.0
* @params
* regexp - regular expression to validate user input
* state - input state on start ('common', 'valid', 'error', 'important')
* @example
* $(any text or password input selector).semaphore();
* @license free
**/

// Helper-function for setting state to any input
function SemaphoreSetInputState(input, state) {
    if ($(input).data('curstate') != state) {
        $(input).removeClass('important valid common error').addClass(state);
        $(input).data('curstate', state);
    }
};

jQuery.fn.semaphore = function(params) {

    var options = {
        regexp: null,
        state: 'common'
    }
    op = jQuery.extend(options, params);

    function ValidateInput(input, reg) {
        if (reg == null) return;        
        var result = reg.test(input.value);
        if (!result) SemaphoreSetInputState(input, 'error');
        else SemaphoreSetInputState(input, 'valid');
        return result;
    }

    return this.each(function() {
        $(this).data('state', op.state);
        $(this).data('regexp', op.regexp);

        $(this).bind('blur', function() {
            var el = $(this)[0];
            if (el.value == '') {
                SemaphoreSetInputState(el, $(this).data('state'));
                return;
            }
            var lastcheck = $(this).data('lastcheck');
            if (lastcheck != el.value) {
                ValidateInput(el, $(this).data('regexp'));
                $(this).data('lastcheck', el.value);
            }
        });
        $(this).bind('keyup', function() {
            var el = $(this)[0];
            if (el.value == '') {
                SemaphoreSetInputState(el, $(this).data('state'));
                return;
            }
            ValidateInput(el, $(this).data('regexp'));
        });

        SemaphoreSetInputState(this, op.state);
    });
};