﻿var SHTURMANN = SHTURMANN || {}; //namespace


SHTURMANN.Class = function () {
    var len = arguments.length;
    var P = arguments[0];
    var F = arguments[len - 1];

    var C = typeof F.initialize == "function" ?
        F.initialize :
        function () { P.prototype.initialize.apply(this, arguments); };

    if (len > 1) {
        var newArgs = [C, P].concat(
                Array.prototype.slice.call(arguments).slice(1, len - 1), F);
        SHTURMANN.inherit.apply(null, newArgs);
    } else {
        C.prototype = F;
    }
    return C;
};

SHTURMANN.inherit = function (C, P) {
    var F = function () { };
    F.prototype = P.prototype;
    C.prototype = new F;
    var i, l, o;
    for (i = 2, l = arguments.length; i < l; i++) {
        o = arguments[i];
        if (typeof o === "function") {
            o = o.prototype;
        }
        SHTURMANN.Util.extend(C.prototype, o);
    }
};

SHTURMANN.Util = SHTURMANN.Util || {};
SHTURMANN.Util.extend = function (destination, source) {
    destination = destination || {};
    if (source) {
        for (var property in source) {
            var value = source[property];
            if (value !== undefined) {
                destination[property] = value;
            }
        }

        var sourceIsEvt = typeof window.Event == "function"
                          && source instanceof window.Event;

        if (!sourceIsEvt
           && source.hasOwnProperty && source.hasOwnProperty("toString")) {
            destination.toString = source.toString;
        }
    }
    return destination;
};

SHTURMANN.Util.applyDefaults = function (to, from) {
    to = to || {};
    var fromIsEvt = typeof window.Event == "function"
                    && from instanceof window.Event;

    for (var key in from) {
        if (to[key] === undefined ||
            (!fromIsEvt && from.hasOwnProperty
             && from.hasOwnProperty(key) && !to.hasOwnProperty(key))) {
            to[key] = from[key];
        }
    }
    if (!fromIsEvt && from && from.hasOwnProperty
       && from.hasOwnProperty('toString') && !to.hasOwnProperty('toString')) {
        to.toString = from.toString;
    }
    return to;
};

function createErrorPopup() {
    jQuery('body').append('<div id="errorPopup" class="popup-error"><h3 id="errorTitle"></h3><p id="errorMessage"></p></div>');
}
function createCommonPopup() {
    jQuery('body').append('<div id="messagePopup"><div class="t">&nbsp;</div><div class="c"><div class="c1"><h2 id="messageTitle"></h2><div class="row add-row" id="messageMessage" style="padding-left:0;"></div><div style="text-align:center;"><input type="image" src="/images/btn_ok.png" id="messageYes" title="Ok" onmouseout=\'jQuery("#messageYes").attr("src", "/images/btn_ok.png")\' onmouseover=\'jQuery("#messageYes").attr("src", "/images/btn_ok_on.png")\' /></div><a class="close" id="messageClose" href="#">close</a></div></div><div class="b">&nbsp;</div></div>');
}
// показать сообщение на @timeout по окончании таймаута вызвать @onUnblock
function showMessage(title, message,timeout,onUnblock) {
    if (!jQuery('#messagePopup').length) {
        createCommonPopup();
    }
    timeout = typeof (timeout) == "undefined" ? 0 : timeout;

    jQuery('#messageYes').click(function() {
        jQuery.unblockUI();
        if (!(typeof (onUnblock) == "undefined"))
            onUnblock();
        return false;
    });
    jQuery('#messageClose').click(function() {
        jQuery.unblockUI();
        if (!(typeof (onUnblock) == "undefined"))
            onUnblock();
        return false;
    });
    if (timeout > 0) {
        jQuery('#messageYes').hide();
        jQuery('#messageClose').hide();
    }

    jQuery('#messageTitle').html(title);
    jQuery('#messageMessage').html(message);
    jQuery.blockUI({
        message: jQuery('#messagePopup'),
        fadeIn: 0,
        fadeOut: 0,
        timeout:timeout,
        showOverlay: true,
        focusInput: false,
        onUnblock:onUnblock,
        css: { width: jQuery('#messagePopup').width(), backgroundColor: 'transparent', border: 'none', cursor: 'auto', top: '30%' }
    });
}

function showErrorMessage(title, message, duration, onUnblock) {
    if (!jQuery('#errorPopup').length) {
        createErrorPopup();
    }
    jQuery('#errorTitle').html(title);
    jQuery('#errorMessage').html(message);
    jQuery.blockUI({
        message: jQuery('#errorPopup'),
        fadeIn: 700,
        fadeOut: 700,
        timeout: duration,
        showOverlay: false,
        onUnblock:onUnblock,
        css: {
            border: 'none',
            opacity: .9
        }
    });
}


function showResponseError(title, message, alert_durations) {
    alert_durations = typeof (alert_durations) == "undefined" ? 3000 : alert_durations;
    if (message) {
        showErrorMessage(title, message, alert_durations);
    }
    else {
        showErrorMessage(title, common_alert, alert_durations);
    }
}

var loginUrl = "/";

function showLoginPopup(link) {
    loginUrl = link;
    jQuery('#logonPopupMessage').html("");
    jQuery('#password').html("");
    jQuery('#popupCancel').click(function() {
        jQuery.unblockUI();
        return false;
    });

    jQuery('#popupLogon').click(function() {
        jQuery.ajax({
            type: "POST",
            url: "/Popup",
            data: jQuery('#popupLoginForm').serialize(),
            success: clojure_logonPopup(link),
            error: function(jqXHR, textStatus, errorThrown) { jQuery('#logonPopupMessage').html(ConnectionErrorMessage); }, // TODO удалить строку после тестирования
            complete: function(XMLHttpRequest, textStatus) { },
            dataType: "json"
        });
        return false;
    });
    jQuery('#popupClose').click(function() {
        jQuery.unblockUI();
        return false;
    });

    jQuery.blockUI({
        message: jQuery('#popup'),
        fadeIn: 0,
        fadeOut: 0,
        showOverlay: true,
        focusInput: false,
        css: { width: jQuery('#popup').width(), backgroundColor: 'transparent', border: 'none', cursor: 'auto', top:'30%' }
    });
    return false;

}



function clojure_logonPopup(link) {
    return function setReceiving(result, textStatus, jqXHR) {
        if (result) {
            if (result.Result) {
                document.location = link.href;
            }
            else {
                jQuery('#logonPopupMessage').html(result.ErrorMessage);
            }
        }
        else {
            jQuery('#logonPopupMessage').html(ErrorMessage);
        }
    }
}


function ParseJson(text, reviver) {

    // Копикаст с http: //www.JSON.org/json2.js с одним именением:
    // Метод Json() контроллера в asp.NET mvc сериализует дату в специальный формат (), поэтому необходимо сделать замену. Сложность в том, что замену нужно
    //     сделать до оценки, но после валидации.
    // Подробнее: http://weblogs.asp.net/bleroy/archive/2008/01/18/dates-and-json.aspx
    // The new format is "\/Date(1198908717056)\/" where the number is again the number of milliseconds since January 1st 1970 UTC.
    // Notice how a simple eval-based parser will just return the exact same string in both cases, but if you run a simple search 
    //    for "\\/Date\((\d+)\)\\/" and replace with "new Date($1)" before the eval (but after validation), you'll get the dates right in the final object graph.             


    // The parse method takes a text and an optional reviver function, and returns
    // a JavaScript value if the text is a valid JSON text.

    var j;

    function walk(holder, key) {

        // The walk method is used to recursively walk the resulting structure so
        // that modifications can be made.

        var k, v, value = holder[key];
        if (value && typeof value === 'object') {
            for (k in value) {
                if (Object.hasOwnProperty.call(value, k)) {
                    v = walk(value, k);
                    if (v !== undefined) {
                        value[k] = v;
                    } else {
                        delete value[k];
                    }
                }
            }
        }
        return reviver.call(holder, key, value);
    }


    // Parsing happens in four stages. In the first stage, we replace certain
    // Unicode characters with escape sequences. JavaScript handles many characters
    // incorrectly, either silently deleting them, or treating them as line endings.

    var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;

    text = String(text);
    cx.lastIndex = 0;
    if (cx.test(text)) {
        text = text.replace(cx, function(a) {
            return '\\u' +
                        ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
        });
    }

    // In the second stage, we run the text against regular expressions that look
    // for non-JSON patterns. We are especially concerned with '()' and 'new'
    // because they can cause invocation, and '=' because it can cause mutation.
    // But just to be safe, we want to reject all unexpected forms.

    // We split the second stage into 4 regexp operations in order to work around
    // crippling inefficiencies in IE's and Safari's regexp engines. First we
    // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
    // replace all simple value tokens with ']' characters. Third, we delete all
    // open brackets that follow a colon or comma or that begin the text. Finally,
    // we look to see that the remaining characters are only whitespace or ']' or
    // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.

    if (/^[\],:{}\s]*$/
.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
.replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {

        // In the third stage we use the eval function to compile the text into a
        // JavaScript structure. The '{' operator is subject to a syntactic ambiguity
        // in JavaScript: it can begin a block or an object literal. We wrap the text
        // in parens to eliminate the ambiguity.

        // Находим и заменяем даты.
        text = text.replace(/"\\\/Date\(([0-9-]+)\)\\\/"/gi, "new Date($1)");

        j = eval('(' + text + ')');

        // In the optional fourth stage, we recursively walk the new structure, passing
        // each name/value pair to a reviver function for possible transformation.

        return typeof reviver === 'function' ?
                    walk({ '': j }, '') : j;
    }

    // If the text is not JSON parseable, then a SyntaxError is thrown.

    throw new SyntaxError('JSON.parse');
};

function openPopupWindow(height, width, href) {

    var windowFeatures = 'toolbar=0,scrollbars=yes,status=0,resizable=1,location=0,menuBar=0,height=' + height + ',width=' + width;
    
    var centeredY = (screen.height - height) / 2;
    var centeredX = (screen.width - width) / 2;
    window.open(href, 'name', windowFeatures + ',left=' + centeredX + ',top=' + centeredY).focus();
}

function socialComplete(result) {

    if (result.Result) {
        if (result.Data.IsRegisterNeed) {
            showPopupEmail(result.Data.Type, result.Data.TokenKey, result.Data.Email, result.Data.Username);
        }
        else {
            socialLogin();
        }
    }
    else {
        showErrorMessage(ErrorTitle, result.ErrorMessage, 3000);
    }
}

function socialLogin() {
    document.location = loginUrl;
}

function showPopupEmail(type, tokenKey, email, username) {

    jQuery("#socialusername").html(username);
    jQuery("#social-image").attr("src", "/images/btn_" + type + ".png");
    jQuery("#social-login-button").hide();
    jQuery('#popupEmailMessage').html('');
    jQuery('#socialemail').val('');
    jQuery('#socialemaillabel').html(EnterEmail);
    jQuery('#socialpassword').val('');
    jQuery('.social-register-login').hide();
    jQuery(".social-register-register").hide();
    jQuery('input[name="group"]').removeAttr("checked");
    jQuery('#IsAcceptEULA').removeAttr("checked");


    jQuery('input[name="group"]').change(function () {
        jQuery("#social-login-button").show();
        if (jQuery('input[name="group"]:checked').val() == "old_user") {
            jQuery('#IsAcceptEULA').removeAttr("checked");
            jQuery(".social-register-register").hide();
            jQuery(".social-register-login").show();

            jQuery('#popupEmailMessage').html('');
            jQuery('#popupEmailMessage').hide();
            jQuery('#socialemaillabel').html(LoginOrEmail);
            if (email != null && email != 'undefined' && email != '') {
                jQuery(".email-row").show();
                jQuery("#socialemail").val('');
            }
        }
        else {
            jQuery(".social-register-login").hide();
            jQuery(".social-register-register").show();
            jQuery('#popupEmailMessage').html('');
            jQuery('#popupEmailMessage').hide();
            jQuery('#socialemaillabel').html(EnterEmail);
            if (email != null && email != 'undefined' && email != '') {
                jQuery(".email-row").hide();
                jQuery("#socialemail").val(email);
            }
        }
    });
    
    
    if (email != null && email != 'undefined' && email != '') {
        jQuery(".email-row").hide();
        jQuery("#socialemail").val(email);
    }
    
    jQuery.blockUI({
        message: jQuery("#popupEmail"),
        fadeIn: 0,
        fadeOut: 0,
        showOverlay: true,
        focusInput: false,
        css: { width: jQuery('#popupEmail').width(), backgroundColor: 'transparent', border: 'none', cursor: 'auto', top: '30%' }
    });

    var registerHandler = function () {

        var data;
        var url;
        if (jQuery('input[name="group"]:checked').val() == "old_user") {
            data = { tokenKey: tokenKey, email: jQuery("#socialemail").val(), password: jQuery('#socialpassword').val() };
            url = '/Social/RegisterLogin/' + type;
        }
        else {
            data = { tokenKey: tokenKey, email: jQuery("#socialemail").val(), isAcceptEULA: jQuery('#IsAcceptEULA').is(':checked') };
            url = '/Social/Register/' + type;
            if (loginUrl == '/') {
                loginUrl = '/editProfile';
            }
        }

        jQuery.ajax(
            {
                type: "POST",
                url: url,
                data: data,
                dataType: 'json',
                success: function (result) {

                    if (result.Result) {
                        socialLogin();
                    }
                    else {

                        jQuery('#popupEmailMessage').html(result.ErrorMessage);
                        jQuery('#popupEmailMessage').show();
                        //showErrorMessage("Ошибка", result.Error, 3000, function () { window.location = '/login'; });
                    }


                },
                error: function (jqXHR, textStatus, errorThrown) {

                    jQuery('#popupEmailMessage').html(ConnectionErrorMessage);
                }, // TODO удалить строку после тестирования
                complete: function () { }

            });
    };
        jQuery("#popupEmail #popupRegister").click(registerHandler);

        var closeHandler = function () { jQuery.unblockUI(); jQuery("#popupEmail #popupRegister").unbind('click', registerHandler); };

        jQuery("#popupEmail #popupEmailClose").click(closeHandler);
        jQuery("#popupEmail #popupRegisterCancel").click(closeHandler);

    }

    function  hideAutocompleteProgressBar(input) {
        jQuery(input).removeClass("valid").removeClass("ui-autocomplete-loading");
    }

