/**
 * Created by JetBrains PhpStorm.
 * User: Eugene
 * Date: 17.08.11
 * Time: 0:13
 * To change this template use File | Settings | File Templates.
 */

/* jQuery extension method */

jQuery.fn.center = function () {
    this.css("position", "absolute");
    this.css("top", (($(window).height() - this.outerHeight()) / 2) + $(window).scrollTop() + "px");
    this.css("left", (($(window).width() - this.outerWidth()) / 2) + $(window).scrollLeft() + "px");
    return this;
}

/* captcha */

function ReloadCaptcha() {
    RefreshCaptcha('imgCaptcha', 'imgName', 'imgCode');
}

function CheckCaptcha() {
    var dataObj = {};
    var imgname = $('#imgName').val();
    var imgcode = $('#imgCode').val();

    $.ajax({
        type: "POST",
        url: "/",
        data: "imgname=" + imgname + "&imgcode=" + imgcode + this._additionalRequest,
        context: window,
        success: function(msg) {
            if (msg != null) {
                var message = $.parseJSON(msg);
                if (message.isCaptchaValid === true) {
                    CloseCaptchaForm();
                    this._successCallback(message.processResult);
                } else {
                    ReloadCaptcha();
                    alert('Вы ввели неверный код');
                }
            } else {
                ReloadCaptcha();
                alert('Ошибка приема данных');
            }
        },
        error: function() {
            ReloadCaptcha();
            alert("Ошибка передачи данных");
        }
    });
}

function CaptchaInit() {
    $(window).resize(function() {
        $("#CaptchaForm").center();
    });

    $(window).scroll(function() {
        $("#CaptchaForm").center();
    });

    $("#CaptchaForm").center();
}

$(function() {
    CaptchaInit();
});

function OpenCaptchaForm(request, successCallback) {
    ReloadCaptcha();
    this._additionalRequest = request;
    this._successCallback = successCallback;
    $("#CaptchaForm").show();
}

function CloseCaptchaForm() {
    $("#CaptchaForm").hide();
}

