﻿/*
Watermark v3.0.5 (May 9, 2010) plugin for jQuery
http://jquery-watermark.googlecode.com/
Copyright (c) 2009-2010 Todd Northrop
*/
(function (a) { var k = "function", i = "password", c = "maxLength", e = "type", b = true, d = false, s = "watermark", t, m = s, h = "watermarkClass", p = "watermarkFocus", j = "watermarkSubmit", l = "watermarkMaxLength", g = "watermarkPassword", f = "watermarkText", r = ":data(" + m + ")", n = ":text,:password,:search,textarea", o = ["Page_ClientValidate"], q = d; a.extend(a.expr[":"], { search: function (a) { return "search" === a.type }, data: function (f, h, g) { var e, c = /^((?:[^=!^$*]|[!^$*](?!=))+)(?:([!^$*]?=)(.*))?$/.exec(g[3]); if (c) { e = a(f).data(c[1]); if (e !== t) { if (c[2]) { e = "" + e; switch (c[2]) { case "=": return e == c[3]; case "!=": return e != c[3]; case "^=": return e.slice(0, c[3].length) == c[3]; case "$=": return e.slice(-c[3].length) == c[3]; case "*=": return e.indexOf(c[3]) !== -1 } } return b } } return d } }); a.watermark = { version: "3.0.5", options: { className: s, useNative: b }, hide: function (b) { a(b).filter(r).each(function () { a.watermark._hide(a(this)) }) }, _hide: function (a, i) { if (a.val() == a.data(f)) { a.val(""); if (a.data(g)) if (a.attr(e) === "text") { var d = a.data(g), b = a.parent(); b[0].removeChild(a[0]); b[0].appendChild(d[0]); a = d } if (a.data(l)) { a.attr(c, a.data(l)); a.removeData(l) } if (i) { a.attr("autocomplete", "off"); window.setTimeout(function () { a.select() }, 0) } } a.removeClass(a.data(h)) }, show: function (b) { a(b).filter(r).each(function () { a.watermark._show(a(this)) }) }, _show: function (d) { var r = d.val(), j = d.data(f), m = d.attr(e); if ((r.length == 0 || r == j) && !d.data(p)) { q = b; if (d.data(g)) if (m === i) { var o = d.data(g), n = d.parent(); n[0].removeChild(d[0]); n[0].appendChild(o[0]); d = o; d.attr(c, j.length) } if (m === "text" || m === "search") { var k = d.attr(c); if (k > 0 && j.length > k) { d.data(l, k); d.attr(c, j.length) } } d.addClass(d.data(h)); d.val(j) } else a.watermark._hide(d) }, hideAll: function () { if (q) { a.watermark.hide(n); q = d } }, showAll: function () { a.watermark.show(n) } }; a.fn.watermark = function (q, l) { var o = "string", s = typeof q === o, r; if (typeof l === "object") { r = typeof l.className === o; l = a.extend({}, a.watermark.options, l) } else if (typeof l === o) { r = b; l = a.extend({}, a.watermark.options, { className: l }) } else l = a.watermark.options; if (typeof l.useNative !== k) l.useNative = l.useNative ? function () { return b } : function () { return d }; return this.each(function () { var u = "dragleave", t = "dragenter", w = this, d = a(w); if (!d.is(n)) return; if (d.data(m)) { if (s || r) { a.watermark._hide(d); s && d.data(f, q); r && d.data(h, l.className) } } else { if (l.useNative.call(w, d)) if (("" + d.css("-webkit-appearance")).replace("undefined", "") !== "" && d.attr("tagName") !== "TEXTAREA") { s && d.attr("placeholder", q); return } d.data(f, s ? q : ""); d.data(h, l.className); d.data(m, 1); if (d.attr(e) === i) { var x = d.wrap("<span>").parent(), k = a(x.html().replace(/type=["']?password["']?/i, 'type="text"')); k.data(f, d.data(f)); k.data(h, d.data(h)); k.data(m, 1); k.attr(c, q.length); k.focus(function () { a.watermark._hide(k, b) }).bind(t, function () { a.watermark._hide(k) }).bind("dragend", function () { window.setTimeout(function () { k.blur() }, 1) }); d.blur(function () { a.watermark._show(d) }).bind(u, function () { a.watermark._show(d) }); k.data(g, d); d.data(g, k) } else d.focus(function () { d.data(p, 1); a.watermark._hide(d, b) }).blur(function () { d.data(p, 0); a.watermark._show(d) }).bind(t, function () { a.watermark._hide(d) }).bind(u, function () { a.watermark._show(d) }).bind("dragend", function () { window.setTimeout(function () { a.watermark._show(d) }, 1) }).bind("drop", function (b) { var a = b.originalEvent.dataTransfer.getData("Text"); d.val().replace(a, "") === d.data(f) && d.val(a); d.focus() }); if (w.form) { var o = w.form, v = a(o); if (!v.data(j)) { v.submit(a.watermark.hideAll); if (o.submit) { v.data(j, o.submit); o.submit = function (c, b) { return function () { var d = b.data(j); a.watermark.hideAll(); if (d.apply) d.apply(c, Array.prototype.slice.call(arguments)); else d() } } (o, v) } else { v.data(j, 1); o.submit = function (b) { return function () { a.watermark.hideAll(); delete b.submit; b.submit() } } (o) } } } } a.watermark._show(d) }).end() }; o.length && a(function () { for (var b, c, d = o.length - 1; d >= 0; d--) { b = o[d]; c = window[b]; if (typeof c === k) window[b] = function (b) { return function () { a.watermark.hideAll(); return b.apply(null, Array.prototype.slice.call(arguments)) } } (c) } }) })(jQuery);

var isUserLogged = false;

$(function () {
    if ($('#userMessageBox').length > 0) { isUserLogged = true; }

    $.MessegerInit();

    $("input#email").watermark("логин(email)");
    $("input#password").watermark("пароль");

    $("#headerMenu li").hover(function () { $(this).addClass("hover"); }, function () { $(this).removeClass("hover"); });

    $.InitFreshNews();
    $.InitAdvertsLine();
    $.InitVoting();
});

// messeger
$.MessegerInit = function () {
    if ($('#userMessageBox').length > 0) {
        $.MessegerCheck();
        setInterval(function () { $.MessegerCheck(); }, 10000);
    }
}

$.MessegerCheck = function () {
    $.post('/site/user/message/check', null, function (data) {
        if (data.result == 'ok') {
            $.MessegerDisplayMessage(data.message);
        }
    });
}

$.MessegerDisplayMessage = function (message) {

    if (message == null) { return; }
    if ($.data($('#userMessageBox')[0], "id") == message.id) { return; }
    $.data($('#userMessageBox')[0], "id", message.id);

    $('#userMessageBox .body img').load().attr('src', message.photo).attr('alt', message.fromname).attr('title', message.fromname);

    $('#userMessageBox .body a').attr('href', '/user/info/' + message.from);
    $('#userMessageBox .body .sender').text(message.fromname);

    $('#userMessageBox .body .time').text(message.sent);
    $('#userMessageBox .body .text').html(message.text);

    $('#userMessageBox .buttons').empty();
    $('#userMessageBox .caption #close').show();

    var text = '';
    if (message.type == "friend") {

        var declineBtn = $('<div />').text('Отклонить').attr('class', 'button').attr('id', 'declineBtn');
        declineBtn.click(function () { $.MessegerDeclineFriend(message.from); });
        $('#userMessageBox .buttons').append(declineBtn);

        var approveBtn = $('<div />').text('Принять').attr('class', 'button').attr('id', 'approveBtn');
        approveBtn.click(function () { $.MessegerApproveFriend(message.from); });
        $('#userMessageBox .buttons').append(approveBtn);

        $('#userMessageBox .caption #close').hide();
    }
    else {
        if (message.type == "read") {
            var closeBtn = $('<div />').text('Закрыть').attr('class', 'button').attr('id', 'closeBtn');
            closeBtn.click(function () { $.MessegerClose(); });
            $('#userMessageBox .buttons').append(closeBtn);

        } else {
            var closeBtn = $('<div />').text('Закрыть').attr('class', 'button').attr('id', 'closeBtn');
            closeBtn.click(function () { $.MessegerClose(); });
            $('#userMessageBox .buttons').append(closeBtn);

            var replyBtn = $('<div />').text('Ответить').attr('class', 'button').attr('id', 'replyBtn');
            replyBtn.click(function () { $.MessegerReply(message.from, message.id); });
            $('#userMessageBox .buttons').append(replyBtn);

            $('#userMessageBox .caption #close').click(function () { $.MessegerClose(); });
        }
    }

    $('#userMessageBox').slideDown();
}

$.MessegerReply = function (userId, messageId) {
    $.MessegerClose();
    window.location.href = '/user/messages/dialog/' + userId;
}

$.MessegerClose = function () {
    $('#userMessageBox').slideUp();
    var messageId = $.data($('#userMessageBox')[0], "id");
    $.post('/site/user/message/read', { messageId: messageId }, function (data) {
        if (data.message != null) {
            $.MessegerDisplayMessage(data.message);
        }
    });
}

$.MessegerApproveFriend = function (id) {
    $('#userMessageBox').slideUp();
    var messageId = $.data($('#userMessageBox')[0], "id");
    $.post('/site/user/friend/approve', { messageId: messageId, friendId: id }, function (data) {
        document.location.reload();
/*        if (data.message != null) {
            $.MessegerDisplayMessage(data.message);
        }*/
    });
}

$.MessegerDeclineFriend = function (id) {
    $('#userMessageBox').slideUp();
    var messageId = $.data($('#userMessageBox')[0], "id");
    $.post('/site/user/friend/decline', { messageId: messageId, friendId: id }, function (data) {
        if (data.message != null) {
            $.MessegerDisplayMessage(data.message);
        }
    });
}
// end messeger

    var googleKey;
    var googleKeys = {
        'loc': 'ABQIAAAAM-exuWDPRyRrda2C45i5URQKEBQ-wZ8Kv97jsOkUbi6gWSv3jRSoBn20L6rz-Dkf0phQbRaA3eLRjw',
        'nesterov-city.ru': 'ABQIAAAAM-exuWDPRyRrda2C45i5URQKEBQ-wZ8Kv97jsOkUbi6gWSv3jRSoBn20L6rz-Dkf0phQbRaA3eLRjw'
    };

    $.getGoogleKey = function () {
        if (googleKey != undefined) return googleKey;
        var host = window.location.host.match(/\.loc$/) ? 'loc' : window.location.host.replace('www.', '');
        if (host.indexOf('.') == 2) host = host.substring(2); // remove language prefix
        googleKey = googleKeys[host];
        return googleKey;
    };


    // Watermark For Wysiwyg control
    $.WatermarkForWysiwyg = function (ctrlText, ctrlForm) {
        // Watermark init
        $(ctrlText).each(function () {
            var wysiwyg = $.data(this, 'wysiwyg');
            if (wysiwyg.editorDoc.body.innerHTML.length > 0) {
                return;
            }
            var watermark = '<span id="watermark">Your message...</span>';
            wysiwyg.editorDoc.body.innerHTML = watermark;
            $(wysiwyg.editorDoc.body).focus(function () {
                if (this.firstChild != null) {
                    if (this.firstChild.id == 'watermark') {
                        this.innerHTML = '';
                    }
                }
            });
            $(wysiwyg.editorDoc.body).blur(function () {
                if (this.firstChild == null) {
                    this.innerHTML = watermark;
                }
            });
        });

        // remove watermark while submit
        $(ctrlForm).submit(function () {
            $(ctrlText).each(function () {
                var wysiwyg = $.data(this, 'wysiwyg');
                var body = $(wysiwyg.editorDoc.body);
                if (body.length > 0) {
                    if (body[0].firstChild != null) {
                        if (body[0].firstChild.id == 'watermark') {
                            $(ctrlText).val('');
                        }
                    }
                }
            });
        });
    }
    // end Watermark For Wysiwyg control

    function onSilverlightError(sender, args) {
        var appSource = "";
        if (sender != null && sender != 0) {
            appSource = sender.getHost().Source;
        }

        var errorType = args.ErrorType;
        var iErrorCode = args.ErrorCode;

        if (errorType == "ImageError" || errorType == "MediaError") {
            return;
        }

        var errMsg = "Unhandled Error in Silverlight Application " + appSource + "\n";

        errMsg += "Code: " + iErrorCode + "    \n";
        errMsg += "Category: " + errorType + "       \n";
        errMsg += "Message: " + args.ErrorMessage + "     \n";

        if (errorType == "ParserError") {
            errMsg += "File: " + args.xamlFile + "     \n";
            errMsg += "Line: " + args.lineNumber + "     \n";
            errMsg += "Position: " + args.charPosition + "     \n";
        }
        else if (errorType == "RuntimeError") {
            if (args.lineNumber != 0) {
                errMsg += "Line: " + args.lineNumber + "     \n";
                errMsg += "Position: " + args.charPosition + "     \n";
            }
            errMsg += "MethodName: " + args.methodName + "     \n";
        }

        throw new Error(errMsg);
    }

    $.initAddComment = function () {

        $('#add-comment-form').submit(function (e) {
            e.preventDefault();

            $.post('/site/add-comment', $('#add-comment-form').serialize(),
            function (response) {
                if (response.status == 'ERR') {
                    $('#Message').text(response.error);
                }
                if (response.status == 'OK') {
                    $('#Message').text('Комментарий успешно добавлен.');
                    $('#guestsbook').show();
                    $(response.data).appendTo('#guestsbook');
                    $('#Text').each(function () { $.data(this, 'wysiwyg').editorDoc.body.innerHTML = ''; });
                    $('#DisplayName').val('');
                    $('#Email').val('');
                }

                $('#DisplayName').focus();
                $('#Email').focus();
                $('#Text').each(function () { $($.data(this, 'wysiwyg').editorDoc.body).focus(); });
            });
        });
    }

    $.initCommentSubscribing = function () {
        $('#SubscribeButton').click(function () {
            $('#SubscribeButton').slideUp('slow', function () {
                if (isUserLogged) {
                    $('№SubscribeProgess').slideDown('slow');
                    $.post('/site/subscribe-comments/' + $('#ObjectID').val() + '/true', null, function (data) {
                        $('№SubscribeProgess').slideUp('slow');
                        if (data.result = 'ok') {
                            $('#UnSubscribeArea').slideDown('slow');
                        } else {
                            $('<span style="float: right; color: Red;">' + data.errоr + '</span>').appendTo($('#SubscribeArea'));
                        }
                    });
                } else {
                    $('<span style="float: right; color: Red;">Подписка доступна только зарегистрированным пользователям</span>').appendTo($('#SubscribeArea'));
                }
            });
        });

        $('#UnSubscribeButton').click(function () {
            $('#UnSubscribeArea').slideUp('slow', function () {
                if (isUserLogged) {
                    $('№SubscribeProgess').slideDown('slow');
                    $.post('/site/subscribe-comments/' + $('#ObjectID').val() + '/false', null, function (data) {
                        $('№SubscribeProgess').slideUp('slow');
                        if (data.result = 'ok') {
                            $('#SubscribeButton').slideDown('slow');
                        } else {
                            $('<span style="float: right; color: Red;">' + data.errоr + '</span>').appendTo($('#SubscribeArea'));
                        }
                    });
                } else {
                    $('<span style="float: right; color: Red;">Подписка доступна только зарегистрированным пользователям</span>').appendTo($('#SubscribeArea'));
                }
            });
        });
    }

    $.InitAdvertsLine = function () {

        var currentPage = 1;
        var spacing = (226 + 17) * 4;

        $('div.advertisement > ul').css('width', spacing * 4);
        var adsList = $('div.advertisement > ul');
        var startAnimate = function () { adsList.animate({ 'left': spacing - currentPage * spacing }, 'slow'); };
        var stopAnimate = function () { adsList.stop() };

        $('.advertisement a.advertisementNext').click(function () {
            if (currentPage > 3) {
                currentPage = 1;
                adsList.css('left', spacing - currentPage * spacing);
            }
            stopAnimate();
            currentPage++;
            startAnimate();
        });

        $('.advertisement a.advertisementPrev').click(function () {
            if (currentPage < 2) {
                currentPage = 4;
                adsList.css('left', spacing - currentPage * spacing);
            }
            stopAnimate();
            currentPage--;
            startAnimate();
        });
    }

    var FreshNewsPage = 1;
    var FreshNewsIntervalId;
    $.FreshNewsClick = function (id) {
        $('.freshNews').fadeOut('slow');
        $('#freshNews' + id).fadeIn('slow');
        $('.freshNewsWrap').animate({ 'height': $('#freshNews' + id).height() }, 'slow');
    }

    $.InitFreshNews = function () {
        $('.freshNewsWrap').height($('#freshNews1').height());
        $('.phtoSlider ul li').click(function () {
            clearInterval(FreshNewsIntervalId);
            $.FreshNewsClick($(this).text());
        });

        FreshNewsIntervalId = setInterval(function () {
            FreshNewsPage++;
            if (FreshNewsPage > 5) { FreshNewsPage = 1; }
            $.FreshNewsClick(FreshNewsPage);
        }, 15000)
    }

    $.InitVoting = function () {
        $('#SurveyForm').submit(function (e) {
            $.Voting(true);
            return false;
        });

        $('#voteResults').click(function () {
            $.Voting(false);
        });

        $.Voting = function (vote) {
            var items = $('#SurveyForm fieldset > div.items');

            var answerId = $('input:radio[name=V]').val();
            if (vote == true) {
                answerId = $('input:radio[name=V]:checked').val();
                if (answerId == null) {
                    var old = items.css("color");
                    items.stop();
                    items.animate({ 'color': 'Red' }, 500, function () { items.animate({ 'color': old }, 500); });
                    return false;
                }
            }

            $('#SurveySubmit').fadeOut('slow');
            $('#voteResults').fadeOut('slow');
            $.post('/surveys/vote', { answerId: answerId, vote: vote }, function (response) {
                if (response.status == 'ERR') {
                    $('#SurveySubmit').fadeIn('slow');
                    $('#voteResults').fadeIn('slow');
                }
                if (response.status == 'OK') {
                    var answerHtml = '';
                    for (var i = 0; i < response.answers.length; i++) {
                        answerHtml += '<div class="items">';
                        answerHtml += '<span>' + response.answers[i].text + '</span>';
                        answerHtml += '<div class="oprosResults"><div class="oprosResultsPercentage"><div style="width:' + response.answers[i].percent + '%"></div></div>' + response.answers[i].percent + '%(' + response.answers[i].votes + ')</div></div>'

                    }
                    items.remove();
                    $(answerHtml).insertAfter('div.victoQuestion');
                }
            });
            return false;
        }
    }
