var uploadUrl = '/ajax/upload-msg-image.html';

// Полезные штуки
if (!Array.prototype.some)
{
  Array.prototype.some = function(fun /*, thisp*/)
  {
    var i = 0,
        len = this.length >>> 0;

    if (typeof fun != "function")
      throw new TypeError();

    var thisp = arguments[1];
    for (; i < len; i++)
    {
      if (i in this &&
          fun.call(thisp, this[i], i, this))
        return true;
    }

    return false;
  };
}

String.prototype.printf = function (obj) {
  var useArguments = false;
  var _arguments = arguments;
  var i = -1;
  if (typeof _arguments[0] == "string") {
    useArguments = true;
  }
  if (obj instanceof Array || useArguments) {
    return this.replace(/\%s/g,
    function (a, b) {
      i++;
      if (useArguments) {
        if (typeof _arguments[i] == 'string') {
          return _arguments[i];
        }
        else {
          throw new Error("Arguments element is an invalid type");
        }
      }
      return obj[i];
    });
  }
  else {
    return this.replace(/{([^{}]*)}/g,
    function (a, b) {
      var r = obj[b];
      return typeof r === 'string' || typeof r === 'number' ? r : a;
    });
  }
};

// Заставить бы работать эту штуку ...
//function moveCaretToTheEnd(ed)
//{
//  var root = ed.dom.getRoot();
//  var lastnode = root.childNodes[root.childNodes.length - 1];
//
//  if (tinymce.isGecko)
//    lastnode = lastnode.childNodes[lastnode.childNodes.length - 1];
//
//  ed.selection.select(lastnode);
//  ed.selection.collapse(false);
//}

function initTinyMCELinkPopup(ed)
{
    var popup = $('#popup-1');

    popup.find('.close').click(function () {
        popup.fadeOut('fast');
        return false;
    });

    ed.addButton('insert-link', {
        title: 'Вставить ссылку',
        image: '/i/reg-sign.png',
        onclick: function() {
            popup.find("form").unbind();

            popup.find('input[name=url]').val('');
            popup.find('input[name=text]').val('');

            var offset = $('#new_msg_body').offset();
            popup.css({ 'left': offset.left + 250, 'top':offset.top }).fadeIn('fast');		

            popup.find('form').submit(function() {
                var url = popup.find('input[name=url]').val();
                var text = popup.find('input[name=text]').val() || ed.selection.getContent();
                var content = '<a href="%s" target="_blank">%s</a>'.printf(url, text);

                if (url) {
                    ed.focus(false);
                    ed.selection.setContent(content);

                    popup.fadeOut('fast');
                }
                else
                    popup.find('input[name=url]').focus();

                return false;
            });
        }
    });
}

function initTinyMCEImagePopup(ed)
{
    var popup = $('#popup-2');

    popup.find('.close').click(function () {
        popup.fadeOut('fast');
        return false;
    });

    ed.addButton('insert-img', {
        title: 'Вставить изображение',
        image: '/i/img-icon.gif',
        onclick: function() {
            popup.find("form").unbind();

            popup.find('input[name=url]').val('');
            popup.find('input[name=title]').val('');

            var offset = $('#new_msg_body').offset();
            popup.css({ 'left':offset.left + 300, 'top':offset.top }).fadeIn('fast');		

            popup.find('form').submit(function() {
                if (popup.find('input[type=file]').val()) {
                    $.ajaxFileUpload({
                        url: uploadUrl,
                        secureuri: false,
                        fileElementId: 'imageUploadMCE',
                        dataType: 'json',
                        success: function(data, status) {
                            if (data.error) 
                                alert(data.errorStr);
                            else {
                                var imgTitle = popup.find('input[name=title]').val() || '';
                                var imgUrl = data.imageUrl;
                                var content = '<img src="%s" title="%s"></img>'.printf(imgUrl, imgTitle);

                                ed.focus(false);
                                ed.selection.setContent(content);

                                popup.fadeOut('fast');
                            }
                        },
                        error: function(data, status, e) { alert(e) }
                    });
                }
                else {
                    var imgUrl = popup.find('input[name=url]').val();

                    if (imgUrl) {
                        var imgTitle = popup.find('input[name=title]').val() || '';
                        var content = '<img src="%s" title="%s"></img>'.printf(imgUrl, imgTitle);

                        ed.focus(false);
                        ed.selection.setContent(content);

                        popup.fadeOut('fast');
                    }
                    else
                        popup.find('input[name=url]').focus();
                }

                return false;
            });
        }
    });
}

var tinymce_opts = {
    mode: 'none',
    theme: 'advanced',
    skin: 'o2k7',
    skin_variant: 'silver',
    plugins: '-smileys',
    language: 'ru',
    theme_advanced_buttons1: 'bold,italic,underline,strikethrough,|,fontselect,fontsizeselect,forecolor,|,bullist,numlist,smileys,blockquote,insert-img,insert-link',
    entity_encoding: 'named',
    theme_advanced_buttons2: '',
    theme_advanced_buttons3: '',
    theme_advanced_toolbar_location: 'top',
    theme_advanced_toolbar_align: 'left',
    remove_linebreaks: true,
    inline_styles: true,
    convert_urls: false,
    setup: function(ed) {
        initTinyMCELinkPopup(ed);
        initTinyMCEImagePopup(ed);
    }
};

var lightbox_opts = {
	imageLoading: '/i/lightbox-ico-loading.gif',
	imageBtnClose: '/i/lightbox-btn-close.png',
	imageBtnPrev: '/i/lightbox-btn-prev.png',
	imageBtnNext: '/i/lightbox-btn-next.png',
	txtImage: 'Фото',
	txtOf: 'из'
};

function deleteMessage(msg_id)
{
	if (!window.confirm("Вы уверены, что хотите удалить сообщение?")) return;

	$.getJSON("/ajax/account.html", { cmd:"delete-message", msg_id:msg_id }, function() {
		window.location.href = window.location.href;
	});
}

function deleteWallMessage(msg_id)
{
	if (!window.confirm("Вы уверены, что хотите удалить сообщение?")) return;

	$.getJSON("/ajax/account.html", { cmd:"delete-wall-message", msg_id:msg_id }, function() {
		window.location.href = window.location.href;
	});
}

function deleteConversation(conv_id)
{
	if (!window.confirm("Вы уверены, что хотите удалить переписку?")) return;

	$.getJSON("/ajax/account.html", { cmd:"delete-conversation", conv_id:conv_id }, function() {
		window.location.href = window.location.href;
	});
}

$(document).ready(function() {
    // Блок авторизации
    var email_input    = $("div.login input[name=email]");
    var password_input = $("div.login input:password");
    var password_stub  = $("div.login input[name=password_stub]");

	var password = password_input.val();

    if (password) {
        password_stub.css({ display:"none" });
		password_input.css({ display:"inline" });
    } else {
		password_input.css({ display:"none" });
		password_stub.css({ display:"inline" });
    }

	password_input.css({ color:"#000" });
    if (email_input.val() != "email") email_input.css({ color:"#000" });

	email_input.focus(function() {
		if ($(this).val() == "email") $(this).val("");
        $(this).css({ color:"#000" });
	});

	email_input.blur(function() {
		if ($(this).val() != "") return;
        $(this).val("email").css({ color:"#666" });
	});

	password_stub.focus(function() {
		$(this).css({ display:"none" });
		password_input.css({ display:"inline" }).focus();
	});

	password_input.blur(function() {
		password = $(this).val();
        if (password != "") return;

        $(this).css({ display:"none" });
        password_stub.css({ display:"inline" });
	});

    // Попап в календаре
	$("div.calendar a").hover(
		function() { 
			$(this).parent().children("div.helper").show(); 

			//var dx = "-" + ($(this).parent().find("div.helper ul").width() -
            //    $(this).parent().find("div.helper").position().left) + "px";

			//$(this).parent().find("div.helper ul").css("right", dx);
		},
		function() { $(this).parent().children("div.helper").hide(); }
	);

	$("div.calendar div.helper").hover(
		function() { $(this).show(); },
		function() { $(this).hide(); }
	); 
});

// vim: fileencoding=utf-8
