var email_regexp  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

$(function() {

    $('#userEmail').blur(function() {
        if (email_regexp.test($(this).val())) {
            $.getJSON('/gsmx.Users/captureEmail.json',{e : $(this).val()});
        }
    });

    $('#formRegistration').submit(function () {
        //return true;
        errorsClean(this);
        var required = $(this).find('.fieldRequired');
        var missing = 0;

        for (var i=0; i < required.length; i++) {
            var el = $(required[i]);
            if (el.attr('tagName')=='INPUT' && (el.attr('type')=='radio' || el.attr('type')=='checkbox') && $('INPUT[@name='+el.attr('name')+']:checked').length==0) {
                errorInputRadio(el);
                missing++;
            } else if (el.val()=='') {
                errorInput(el);
                missing++;
            }
        }
        if (missing != 0) {
            return errorForm(this, 'reg_please_fill_in');
        }

        if (!email_regexp.test($('#userEmail').val())) {
            errorInput($('#userEmail'));
            return errorForm(this, 'reg_valid_email');
        }

        if ($('#userPhone').val().length < 8) {
            errorInput($('#userPhone'));
            return errorForm(this, 'reg_valid_phone');
        }

        return true;
    });

    if ($('#homeFooterTestimonials').length > 0) {
        $('#homeFooterTestimonials .testimonial:hidden').removeClass('hide').hide();
        $.timer(7000, changeTestimonial);
    }

});

function changeTestimonial(timer) {
    timer.stop();
    $('#homeFooterTestimonials .testimonial:visible').each(function() {
        $(this).fadeOut("fast", function() {
            $(this).addClass('hide');
            var nxt;
            if ($(this).next().length > 0) {
                nxt = $(this).next();
            } else {
                nxt = $(this).parent().children('.testimonial:first');
            }
            nxt.removeClass('hide');
            nxt.fadeIn("slow", function() {
                $.timer(7000, changeTestimonial);
            });
        });
    });
}

function errorInputRadio(el)
{
    el.parents('LABEL').addClass('fieldError');
}

function errorInput(el)
{
    $('LABEL[@for='+el.attr('id')+']').addClass('labelError');
    el.addClass('fieldError');
}

function errorForm(frm, msg)
{
    $('<div class="updError">'+gsmx_lang[msg]+'</div>').hide().prependTo($(frm)).fadeIn();
    return false;
}

function errorsClean(frm)
{
    $(frm).find('.updError').remove();
    $(frm).find('.fieldError').removeClass('fieldError');
    $(frm).find('.labelError').removeClass('labelError');
}

function pingServer()
{
}