var insertVar = function(val){
    return function(){tinyMCE.activeEditor.execCommand('mceInsertContent',false,val); tinyMCE.activeEditor.focus();}
};

function init_mce()
{
	tinymce.create('tinymce.plugins.objsAlbum', {
    createControl: function(n, cm) {
        switch (n) {
            case 'albumsbutton':
                var c = cm.createSplitButton('albumsbutton', {
                    title : 'Вставить альбом',
                    image : '/img/icon_album.gif',
                    onclick: function() { return true; }
                });

                c.onRenderMenu.add(function(c, m) {
                    m.add({title : 'Список альбомов', 'class' : 'mceMenuItemTitle'}).setDisabled(1);
                    
                    tt = m.add({title : 'Идет загрузка...', onclick : function() {
                        return false;
                    }});
                    
                    $.post("/utils/albums_list/", 
					false,
			        function(data)
			        {
			        	tt.remove();
			        	try { data = eval("("+data+")"); parsed = true; } catch(e) { alert(data); parsed = false; }
						if (parsed)
						{
							for (i in data)
							{
								var cbk_func = insertVar('[album_id='+data[i].id+']');
								
								m.add({title : data[i].title, onclick : cbk_func});
							}
						}
					});
                });
                return c;
        }

        return null;
    }
});

tinymce.PluginManager.add('album', tinymce.plugins.objsAlbum);
	
  tinyMCE.init({
                // General options
                mode : "specific_textareas",
        		editor_selector : "mceEditor",
                theme : "advanced",
                skin : "o2k7",
        		skin_variant : "silver",
                plugins : "-album,embed,safari,pagebreak,style,layer,table,save,advhr,advimage,advlink,iespell,inlinepopups,imagemanager,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",
				
                theme_advanced_blockformats : "p,h3,h4,h5,h6",
                // Theme options
                theme_advanced_buttons1 : "bold,italic,justifyleft,justifycenter,justifyright,justifyfull,bullist,numlist,table,formatselect,|,link,unlink,image,albumsbutton,removeformat,|,undo,redo,|,code,embed",
                theme_advanced_buttons2 : "",
                theme_advanced_buttons3 : "",
                theme_advanced_toolbar_location : "top",
                theme_advanced_toolbar_align : "left",
                theme_advanced_statusbar_location : "bottom",
                theme_advanced_resizing : true,
				theme_advanced_resize_horizontal : false,
                content_css : "/css/main.css"
        });
}        

function slidetabs_init()
{
  $(".slidetabs a").click(function(){ popup_photo(this); return false; });
}

function popup_photo(h)
{
	$(".slidetabs.current").removeClass("current");
	$(h).parent().addClass("current");
	$(h).parent().find("a.current").removeClass("current");
	$(h).addClass("current");
	
	img_path = $(h).attr("href");

	popup = $(".popup-window");
	popup_reset();
	popup.attr("id", "popup-img");
	popup.css("margin-top", -(32+20)/2); // loader 32x32
    popup.css("margin-left", -(32+20)/2);
	popup.find(".popup-content").html('<img id="tmp_img" src="/img/ajax-loading.gif" />');
	
	var pre_img = new Image();
	pre_img.src = img_path;

	$(pre_img).load(function()
	{
		img_w = pre_img.width; 
	  	img_h = pre_img.height;
	  	
	  	popup.find(".popup-content").prepend('<a class="backward" href="javascript:void(0);" onclick="popup_photo_next(this,-1);"><img width="100%" height="100%" src="/img/zero.png" /><span></span></a><a class="forward" href="javascript:void(0);" onclick="popup_photo_next(this,1);"><img width="100%" height="100%" src="/img/zero.png" /><span></span></a>');
		$("#tmp_img").attr("src", img_path);
	  	popup.css("margin-top", -(img_h+20)/2);
	  	popup.css("margin-left", -(img_w+20)/2);
	  	
	  	popup_photo_preload();
	})
	.error(function() {
			alert('Ошибка при загрузке изображения: ' + img_path);
	});

	popup_show();  
}

function popup_photo_preload()
{
	cur_slidetab = $(".slidetabs.current");
	cur = cur_slidetab.find("a.current");
	
	next_a = cur.next();
	if (next_a.find("img").length == 0) next_a = cur_slidetab.find("a:first");
	prev_a = cur.prev();
	if (prev_a.length == 0) prev_a = cur_slidetab.find("a:last");
	
	imgs = [next_a.attr("href"), prev_a.attr("href")];
	for (i in imgs)
	{
		img_path = imgs[i];
		var pre_img = new Image();
		pre_img.src = img_path;
		$(pre_img).load();
		delete pre_img;
	}
}

function popup_photo_next(h, dir)
{
	cur_slidetab = $(".slidetabs.current");
	cur_a = cur_slidetab.find("a.current");
	
	if (dir == -1)
	{
		next_a = cur_a.prev();
		if (next_a.length == 0) next_a = cur_slidetab.find("a:last");
	}
	else if (dir == 1)
	{
		next_a = cur_a.next();
		if (next_a.find("img").length == 0) next_a = cur_slidetab.find("a:first");
	}

	popup = $(".popup-window");
	popup_content = popup.find(".popup-content");
	popup_content.css("opacity", "0.4");

	img_path = next_a.attr("href");	
	var pre_img = new Image();
	pre_img.src = img_path + '?rnd=' + (new Date()).getTime();
	$(pre_img).load(function()
	{
		img_w = pre_img.width; 
	  	img_h = pre_img.height;

		$("#tmp_img").attr("src", img_path);
	  	popup.css("margin-top", -(img_h+20)/2);
	  	popup.css("margin-left", -(img_w+20)/2);
	  	popup_content.css("opacity", "1");
	  	
	  	popup_photo_preload();
	})
	.error(function() {
			alert('Ошибка при загрузке изображения: ' + img_path);
	});
	
	$(".slidetabs.current").removeClass("current");
	next_a.parent().addClass("current");
	next_a.parent().find("a.current").removeClass("current");
	next_a.addClass("current");
	
	$(h).blur();
}

function popup_show(_popup_name)
{
	if (typeof(_popup_name) === "undefined") _popup_name = ".popup-window";
	$(_popup_name).show();
	popup_name = _popup_name;
	if ( $.browser.msie ) $(".popup-bg").show();
	else $(".popup-bg").fadeIn('fast');

	popup_status = 1;
}
function popup_reset()
{
	popup = $(".popup-window");
	if (popup.attr("id") != "")
	{
		popup.find(".popup-slider").css("margin-left", 0).empty();
	}
}

	// close popup when you click anywhere
	function popup_close()
	{
		if (popup_status == 1)
		{
			if (popup_name == ".popup-crop")
			{
				if (sm_js.jcrop_api) sm_js.jcrop_api.destroy();
			}
			$(popup_name).hide();
			if ( $.browser.msie ) $(".popup-bg").hide();
			else $(".popup-bg").fadeOut("fast");
			popup_status = 0;
		}
		return false;
	}

function block_btn(_obj) 
{
		if (typeof(_obj.attr) === "undefined") _obj = $(_obj);
		_obj.attr("disabled", "disabled");
		_obj.addClass("disable");
}
function unblock_btn(_obj) 
{
		if (typeof(_obj.removeAttr) === "undefined") _obj = $(_obj);
		_obj.removeAttr("disabled");
		_obj.removeClass("disable");
}	

function reg_err(data)
{
	inp = $("input[name='data["+data.field+"]']");
	desc = inp.parent().find("h6:first");
	
	inp.removeClass("input-loading");
	if (data.err == 0)
	{
		inp.addClass("form-ok");
		res = 1;
	}
	else if (data.err > 0)
	{
		inp.addClass("form-fail");
		desc.html(data.err_desc);
		res = 0;
	}
	
	reg_frm = $("form[name='reg_form']");
	if (reg_frm.find(".form-fail").length > 0)
	{
		reg_frm.find("input[type='submit']").attr("disabled", "disabled").addClass("disable");
	}
	else
	{
		reg_frm.find("input[type='submit']").removeAttr("disabled").removeClass("disable");
	}
	
	return res;
}

function reg_validate(field)
{
	if (typeof(field) === 'undefined')
	{
		reg_frm = $("form[name='reg_form']");
		return (reg_frm.find(".form-fail").length == 0);
	}
	else
	{
		inp = $("input[name='data["+field+"]']");
		desc = inp.parent().find("h6:first");
		val = inp.val();
		
		inp.removeClass("form-fail").removeClass("form-ok").addClass("input-loading");
		desc.html("&nbsp;");
		if (field == 'pass2')
		{
			pass1 = $("input[name='data[pass1]']");
			if (pass1.val().length == 0 || pass1.hasClass("form-fail")) return false;
			
			data = {field: field, err: 0};
			if (val != pass1.val())
			{
				data.err = 1;
				data.err_desc = 'Введенные пароли не совпадают';
			}
			res = reg_err(data);
		}
		else
		{
			$.post("/utils/reg_validate/", 
			{
				'data[field]': field,
				'data[val]': val
			},
			function(data)
			{
				try { data = eval("("+data+")"); parsed = true; } catch(e) { alert(data); parsed = false; }
				if (parsed)
				{
					res = reg_err(data);
				}
			});
		}
	}
}

function av_change()
{
	$("#av_change_div").slideUp('fast');
	$("#av_upload_div").slideDown('fast');
}

function loading_overlay_add(elem)
{
	if (typeof(elem) === "string") elem = $(elem);

	overlay = $('<div class="loading-overlay"></div>');
	$(elem).after(overlay);
	
	overlay_img = $('<img src="/img/ajax-loading.gif" title="Идет загрузка..." />');
	overlay.append(overlay_img);
	
	overlay.fadeIn('fast');
}

function loading_overlay_del(elem)
{
	$(".loading-overlay").hide().remove();
}

/* comments */
function comments_init()
{
	unblock_btn($("form[name='new_comment'] .form-button"));
}
function comments_add()
{
	txt_inp = $("textarea[name='data[comment]']");
	comment_txt = txt_inp.val();
	if (comment_txt.length <= 3) 
	{
		alert('Ваш комментарий слишком короткий, введите больше 3 символов.');
		txt_inp.focus();
		return false;
	}
	
	block_btn($("form[name='new_comment'] .form-button"));
	
	return true;
}
function comments_reply(comment_id)
{
	comment_div = $("#comment-div-"+comment_id);
	username = comment_div.find(".comment-body h6:first a:first").text();
	txt_inp = $("textarea[name='data[comment]']");
	new_val = txt_inp.val();
	if (new_val.length > 0) new_val += "\n";
	new_val += username + ", ";
	txt_inp.val(new_val);
	txt_inp.focus();
}
function comments_edit(comment_id)
{
	$("#comment-edit-form").remove();
	$(".comment-edit-hidden").removeClass("comment-edit-hidden").show();
	
	comment_div = $("#comment-div-"+comment_id);
	prev = comment_div.find(".comment-body p:first");
	prev_val = prev.html();
	prev_val = prev_val.replace(/<br>/g, "");
	prev.after('<div id="comment-edit-form"><textarea class="form-input" rows="5" cols="45">'+prev_val+'</textarea> <input type="button" onclick="comments_edit_do('+comment_id+');" class="form-button" value="Изменить"></div>');
	prev.hide();
	prev.addClass("comment-edit-hidden");
}
function comments_edit_do(comment_id)
{
	edit_form = $("#comment-edit-form");
	new_comment_txt = edit_form.find("textarea").val();
	if (new_comment_txt.length <= 3) 
	{
		alert('Ваш комментарий слишком короткий, введите больше 3 символов.');
		edit_form.find("textarea").focus();
		return false;
	}
	
	block_btn(edit_form.find(".form-button"));
	$.post("/comments/edit/"+comment_id+"/",
	{
		'data[new_comment]': new_comment_txt
	},
	function(data)
	{
		unblock_btn(edit_form.find(".form-button"));
		try { data = eval("("+data+")"); parsed = true; } catch(e) { alert(data); parsed = false; }
		if (parsed)
		{
			if (data.errs) alert(data.errs);
			else
			{
				$(".comment-edit-hidden").html(data.new_comment).removeClass("comment-edit-hidden").show();
				$("#comment-edit-form").remove();		
			}
		}
	});
}
function comments_del(comment_id, del_topic)
{
	if (typeof(del_topic) === "undefined") del_topic = 0;
	if (del_topic)
	{
		conf_txt = "Вы действительно хотите удалить эту тему?\nВсе ответы будут удалены без возможности восстановления.";
	}
	else
	{
		conf_txt = "Вы действительно хотите удалить комментарий?\nВосстановить его будет невозможно.";
	}
	if (!confirm(conf_txt)) return false;
	
	if (del_topic) return true;
	
	comment_div = $("#comment-div-"+comment_id);
	if (comment_div.length > 0)
	{
		comment_div.fadeOut('slow', function(){ $(this).remove() });
		$.post("/comments/del/"+comment_id+"/",
		false,
		function(data)
		{
			try { data = eval("("+data+")"); parsed = true; } catch(e) { alert(data); parsed = false; }
			if (parsed)
			{
				if (data.errs) alert(data.errs);	
			}
		});
	}
	
	return false;
}
