        function modalWindow(cfg){
            this._width  = cfg.width;
            this._height = cfg.height;
            this._func = cfg.namefunc;
        };

        modalWindow.prototype = {
            createWindow: function(){
                var self = this;
                this._overlay = $('<div id="modal-overlay"></div>')
                    .hide()
                    .appendTo("body")
                    .fadeTo('fast', 0.9);

                this._window = $('<div id="modal-window"></div>')
                    .hide()
                    .css({
                        top: ($(window).height() - this._height) / 2 - 15,
                        left: ($(window).width() - this._width) / 2 - 15,
                        width: this._width,
                        height: this._height
                    })
                    .appendTo("body")
                    .fadeIn('fast');

                this._close = $('<a href="#" id="modal-close"></a>')
                    .click(function(){
                        self.closeWindow();
                    })
                    .appendTo(this._window);
                this._header = $('<div class="modal-header"></div>')
                    .appendTo(this._window);

                this._body = $('<div id="modal_ajax"></div>')
                    .appendTo(this._window);

                this._footer = $('<div class="modal-footer"></div>')
                    .appendTo(this._window);

            },
            closeWindow: function(){
                var self = this;
                this._window.fadeOut('fast', function(){
                    self._window.remove();
                });
                this._overlay.fadeOut('fast', function(){
                    self._overlay.remove();
                });

            },
            fillWindow: function(){
                if (this._func == "reg")
                    this.createRegForm();
                else if (this._func == "reginfo")
                    this.showRegInfo();
                else if (this._func == "wait")
                    this.showWait();

            },
            createRegForm: function(){
                this._header.html("<h1>Вход и регистрация</h1>");

                this._body.html("<div class='modal-entry'><h3>Я уже зарегистрирован</h3><br/><form id='login-form' action='auth/login' method='post'><div class='entry-row'><input name='username' value='логин'/></div><div class='entry-row'><input name='password' type='password' value='пароль'/><small> <a href='/auth/forgot_password'>забыли?</a></small></div><div class='entry-row'><input name='alien_comp' id='remember-login' type='checkbox' value='1'/> Чужой компьютер </div></form><a class='btn-entry' href='#'></a></div><div id='modal-reg'><h3>Я новый пользователь</h3><p>Я хочу список созданных сайтов, свою фотку на аватар и возможности расширенного управления.</p><a href='auth/register' class='reg-entry pic1'><ins></ins></a></div>");
                $("input[name='username']").one('focus', function(){
				    $("input[name='username']").val("");
			    });
			    $("input[name='password']").one('focus', function(){
				    $("input[name='password']").val("");
			    });
		        $('.btn-entry').click( function() {
			        $('#login-form').submit();
			        return false;
		        });

                this._footer.html("");
            },
            showRegInfo: function(){
	            this._header.html("<h1>Вы не авторизованы</h1>");
	            this._body.html("Пользователи без регистрации не могут:<ol><li>загружать фото на аватар</li><li>получать список созданных сайтов</li><li>пролучить возможности расширенного управления</li><li>и др.</li></ol><br/>Пройти регистрацию можно <a href='auth/register'>здесь</a>");
	            this._footer.html("<a href='create_site' class='action-button'>Подарить без регистрации</a>");
            },
            showWait: function(){
                this._close.hide();
                this._body.html('<div style="text-align: center">Пожалуйста, подождите...<br/><img src="../img/loading.gif"/></div>');
            }
        }

        function showModalWindow(n) {
            var cfg = {};
            if (n == "reg"){
                cfg = {
                    width: 530,
                    height: 230,
                    namefunc: n
                }
            } else if (n == "reginfo"){
                cfg = {
                    width: 500,
                    height: 240,
                    namefunc: n
                }
            } else if (n == "wait"){
                cfg = {
                    width: 400,
                    height: 100,
                    namefunc: n
                }
            }
            var modal = new modalWindow(cfg);
            modal.createWindow();
            modal.fillWindow();
            return modal;
        }


	function slide_accord(block1, block2, after_slide) {
		var cur = $("#accordion").children(".selected");
		var next = cur.next();
		cur.animate({width: "62px"});
		next.animate({width: "700px"});
		cur.removeClass("selected");
		next.addClass("selected");
		cur.children("h2").fadeOut('fast');
		block1.fadeOut('fast', function() {
			block1.hide();
			block2.fadeIn('fast', after_slide);
		});
	}
	
(function($){

$.fn.autoGrowInput = function(o) {

    o = $.extend({
        maxWidth: 1000,
        minWidth: 0,
        comfortZone: 70
    }, o);

    this.filter('input:text').each(function(){

        var minWidth = o.minWidth || $(this).width(),
            val = '',
            input = $(this),
            testSubject = $('<tester/>').css({
                position: 'absolute',
                top: -9999,
                left: -9999,
                width: 'auto',
                fontSize: input.css('fontSize'),
                fontFamily: input.css('fontFamily'),
                fontWeight: input.css('fontWeight'),
                letterSpacing: input.css('letterSpacing'),
                whiteSpace: 'nowrap'
            }),
            check = function() {

                if (val === (val = input.val())) {return;}

                // Enter new content into testSubject
                var escaped = val.replace(/&/g, '&amp;').replace(/\s/g,' ').replace(/</g, '&lt;').replace(/>/g, '&gt;');
                testSubject.html(escaped);

                // Calculate new width + whether to change
                var testerWidth = testSubject.width(),
                    newWidth = (testerWidth + o.comfortZone) >= minWidth ? testerWidth + o.comfortZone : minWidth,
                    currentWidth = input.width(),
                    isValidWidthChange = (newWidth < currentWidth && newWidth >= minWidth)
                                         || (newWidth > minWidth && newWidth < o.maxWidth);

                // Animate width
                if (isValidWidthChange) {
                    input.width(newWidth);
                }

            };

        testSubject.insertAfter(input);

        $(this).bind('keyup keydown blur update', check);

    });

    return this;

};

})(jQuery);	
	
	
	
	new function($) {
  $.fn.setCursorPosition = function(pos) {
    if ($(this).get(0).setSelectionRange) {
      $(this).get(0).setSelectionRange(pos, pos);
    } else if ($(this).get(0).createTextRange) {
      var range = $(this).get(0).createTextRange();
      range.collapse(true);
      range.moveEnd('character', pos);
      range.moveStart('character', pos);
      range.select();
    }
  }
}(jQuery);

function onGiveSiteFinish(){
		if (select_domain == 0 || select_theme == 0) {
			alert("Создание сайта невозможно");
			return;
		}
		var hide_id = $('#is_hide_id').is(':checked') ? '4'+select_domain+'7' : '2'+select_theme+'3',
			name = $.trim($('#sitename').val()),
			pname = name.toLowerCase().replace(/ /g, "-");
		if (name == "" || name == "Имя"){
			$('#create_error').html('Пожалуйста, введите имя').show();
			return false;
		}
		var isRus = (/^([ієїа-я\-\ ]+)$/i).test(name);
		var isEng = (/^([a-z\-\ ]+)$/i).test(name);
		if ( !isRus && !isEng ) {
			$('#sitename_rule').addClass('error_rule');
			$('#create_error').html('Пожалуйста, введите другое имя').show();
			return false;
		}
        var modal = showModalWindow('wait');
		$.ajax({
			url:"create_site/createcheck",
			data:"domainid="+select_domain+"&themeid="+select_theme+"&hideid="+hide_id+"&name="+name+"&pname="+pname,
			type:"POST",
			cache:false,
			success:function (msg){
				if (msg.substring(0, 3) == "OK:") 
					document.location.href = msg.substring(3);
				else {
					modal.closeWindow()
					$('#create_error').html('Произошла непредвиденная ошибка. Обновите страницу.').show();
				}
			},
			error:function (){
                modal.closeWindow()
				$('#create_error').html('Сервер перегружен. Попробуйте подарить сайт чуточку позднее.').show();
			}	
		});
	return false;
};
