function recepty() {
}

recepty.pin = function(id) {
	var article_id = id.substring(3);
	$('#'+id).unbind("click").click(function(){
		$.post(
			"/recepty/pin/article_id/"+article_id,
			function(ret) {
				$('#'+id+" img").attr('src', '/images/unpin.gif');
				$('#'+id+" img").attr('title', 'Убрать с главной');
				var newid = 'unpin'+article_id;
				$('#'+id).attr('id', newid);
				$.jGrowl(ret['message']);
				recepty.unpin(newid);
			},
			"json"
		);		
	});
}

recepty.unpin = function(id) {
	var article_id = id.substring(5);
	$('#'+id).unbind("click").click(function(){
		$.post(
			"/recepty/unpin/article_id/"+article_id,
			function(ret) {
				$('#'+id+" img").attr('src', '/images/pin.gif');
				$('#'+id+" img").attr('title', 'Прикрепить на главную');
				var newid = 'pin'+article_id;
				$('#'+id).attr('id', newid);
				$.jGrowl(ret['message']);
				recepty.pin(newid);
			},
			"json"
		);		
	});
}



recepty.move_to_public = function(id) {
	var article_id = id.substring(3);
	$('#'+id).unbind("click").click(function(){
		$.post(
			"/recepty/changeokay/article_id/"+article_id,
			function(ret) {
				$('#'+id+" img").attr('src', '/images/remove_from_mainpage.gif');
				$('#'+id+" img").attr('title', 'Больше не одобряю');
				var newid = 'okay'+article_id;
				$('#'+id).attr('id', newid);
				$.jGrowl(ret['message']);
				recepty.remove_from_public(newid);
			},
			"json"
		);		
	});
}

recepty.remove_from_public = function(id) {
	var article_id = id.substring(4);
	$('#'+id).unbind("click").click(function(){
		$.post(
			"/recepty/changeokay/article_id/"+article_id,
			function(ret) {
				$('#'+id+" img").attr('src', '/images/to_mainpage.gif');
				$('#'+id+" img").attr('title', 'Одобряю');
				var newid = 'all'+article_id;
				$('#'+id).attr('id', newid);
				$.jGrowl(ret['message']);
				recepty.move_to_public(newid);
			},
			"json"
		);		
	});
}


recepty.delete_recept = function(id) {
	var article_id = id.substring(6);
	$('#'+id).unbind("click").click(function(){
        if (confirm("Вы уверены?")) {
            location.href = '/recepty/delete/article_id/'+article_id;
            return false;
        }
    });
}

recepty.move_to_favorite = function(id) {
	var article_id = id.substring(12);
	$('#'+id).unbind("click").click(function(){
		$.post(
			"/recepty/addtofavorite/article_id/"+article_id,
			function(ret) {
				var growl = {};
				if (ret['res']) {
					$('#'+id).attr('title', 'Удалить рецепт из своей кулинарной книги');
					$('#'+id)[0].innerHTML = '<img src="/images/remove_from_favorites.png" alt="Удалить рецепт из своей кулинарной книги" /> Удалить из кулинарной книги';
					var newid = 'is_favorite'+article_id;
					$('#'+id).attr('id', newid);
					recepty.remove_from_favorite(newid);
				} else {
					growl.theme = 'error';
				}

				$.jGrowl(ret['message'], growl);
			},
			"json"
		);		
	});

}

recepty.remove_from_favorite = function(id) {
	
	var article_id = id.substring(11);
	$('#'+id).unbind("click").click(function(){
		$.post(
			"/recepty/removefromfavorite/article_id/"+article_id,
			function(ret) {
				$('#'+id).attr('title', 'Добавить рецепт в свою кулинарную книгу');
				$('#'+id)[0].innerHTML = '<img src="/images/add_to_favorite.png" alt="Добавить рецепт в свою кулинарную книгу" /> В кулинарную книгу';
				var newid = 'not_favorite'+article_id;
				$('#'+id).attr('id', newid);
				$.jGrowl(ret['message']);
				recepty.move_to_favorite(newid);
			},
			"json"
		);		
	});

}

recepty.rating_enabled = function(id) {
	
	var article_id = id.split('_')[1];
	var article_rating = id.split('_')[2];
	//var article_id = id.substring(id.indexOf('_'), id.lastIndexOf()("_") - id.indexOf('_'));
	//var article_rating = id.substring(id.lastIndexOf()('_'));
	$(document).ready(function() {
		$('#rate_'+article_id+'_'+article_rating).rating('/recepty/voting/' + article_id + '/' + article_rating, {maxvalue:5,increment:1,id:'_'+article_id+'_'+article_rating});
	});
};


recepty.add_comment = function(id) {
	
	$('#'+id).unbind("click").click(function() {
		
		var article_id = id.split('_')[2];
		var parent_id = id.split('_')[3];
		if (!parent_id) {
			parent_id = '0';
		}
		var level = id.split('_')[4];
		if (!level) {
			level = '0';
		}
		
		var the_form = "<span style=\"color: #D0D0D0;\">Добавить комментарий:</span><br/>";
		the_form += "<form name='answer_form' method='post' id='answer_form_" + article_id + "_" + parent_id + "' action=''  >" +
						"<textarea id='comment_"+ article_id +"_" + parent_id + "' class='comment_mceEditor' name=com_body rows=2 style='width:90%'>" +
						"</textarea>" +
						//"<br><input type=submit value='добавить'>" +
						"<div class='actions'><input type='button' onclick='recepty.comm_insert(" + article_id +", " + parent_id + ", " + level + ");' value='Сохранить изменения'> или <a href='#' onclick='recepty.comm_exit(" + article_id +", " + parent_id + ", " + level + "); return false;'>Отмена</a></div>" +						
					"</form>";
		if ($('#'+id+"_form").css('display') == "none") {
			$('#'+id+"_form").html(the_form);
			$('#'+id+"_form").slideDown('slow'); 
			//document.answer_form.com_body.focus();
			$('#'+id+"_form").ready(function () {
				tinyMCE.execCommand("mceAddControl", false, "comment_"+ article_id +"_" + parent_id);
//				tinyMCE.settings.theme_advanced_buttons1 = "myinserttable, row_after, row_before, separator, simpleuploader, separator, bold, italic, underline, strikethrough, separator, justifyleft, justifycenter, justifyright, justifyfull, separator, bullist, numlist, separator, outdent, indent, separator, undo, redo, separator, link, unlink, separator, code";		
			});
		} else {
			recepty.comm_exit(article_id, parent_id, level);
			//$('#'+id+"_form").slideUp('slow');
			//tinyMCE.execCommand("mceRemoveControl", false, "comment_"+ article_id +"_" + parent_id);
			//the_element.innerHTML = "";
		}
	});
};



recepty.delete_comment = function(id) {

	$('#'+id).unbind("click").click(function(){
		var found_parent_comment = 0;
		var comment_id = id.split('_')[2];
        if (confirm("Вы уверены?")) {
        	$.post(
        		   	"/recepty/deletecomment/comment_id/"+comment_id,
        			{
        			},
        			function(ret){
        				if (ret['res'] == false) {
        					$.jGrowl(ret['message'], {theme: 'error'});
        					return;
        				}        				
						// Deleting comment and childs
        				$.each(ret['deleted_comments'], function(index, value){
        					//alert(value);
        					//$('#main_comment_'+value).remove();
        					//$('#main_comment_' + value).effect("highlight", {}, 3000);
        					$('#main_comment_' + value).effect("drop", {}, 500, function() {$(this).remove();});
        					//$('#main_comment_'+value).slideUp(200, this.remove);
        					//$("p").remove(":contains('Hello')");
        					
        				});

						$.jGrowl(ret['message']);
        			},
        			"json"
        	);
        }
    });
}

recepty.update_comment = function(id) {
	
	$('#'+id).unbind("click").click(function() {
		var article_id = id.split('_')[2];
		var comment_id = id.split('_')[3];
		var level = id.split('_')[4];
		if (!level) {
			level = '0';
		}

		var element_id = id.replace('update', 'add')+"_form";
		if ($('#'+element_id).css('display') == "none") {

                    $.get(
                        "/recepty/loadcomment/id/"+comment_id,
                        function(ret){

                            var the_form = "<span style=\"color: #D0D0D0;\">Изменить комментарий:</span><br/>";
                            the_form += "<form name='edit_form' method='post' id='edit_form_" + comment_id + "' action='' >" +
                                           "<textarea id='comment_"+ article_id +"_" + comment_id + "' class='comment_mceEditor' name=com_body rows=4 style='width:90%'>" +
                                               ret +
                                           "</textarea>" +
                                           "<div class='actions'><input type='button' onclick='recepty.comm_save(" + article_id +", " + comment_id + ", " + level + ");' value='Сохранить изменения'> или <a href='#' onclick='recepty.comm_exit(" + article_id +", " + comment_id + ", " + level + "); return false;'>Отмена</a></div>" +						
                                         "</form>";
                                     
                            $('#'+element_id).html(the_form);
                            $('#'+element_id).slideDown('slow');
                            
                            tinyMCE.execCommand("mceAddControl", false, "comment_"+ article_id +"_" + comment_id);

                        }
                    );
		} else {
                    recepty.comm_exit(article_id, comment_id, level);
		}                
		
	});
}

recepty.comm_insert = function(article_id, parent_id, level) {
	
	var ed = tinyMCE.get("comment_"+ article_id +"_" + parent_id);
	if (!ed.getContent()) {
		$.jGrowl("Комментарий не может быть пустым", {
			theme: 'error'
		});
		return false;
	} else {
		$("#empty_comment" + parent_id).remove();	
	}

	ed.setProgressState(1);
	$.post(
	   	"/recepty/insertcomment/article_id/"+article_id,
		{
			"parent_id": parent_id,
			"level": level + 1,
			"com_body": ed.getContent()//$("#comment_" + article_id +"_" + parent_id).attr("value")			
		},
		function (ret) {
			
			if (ret['res'] == false) {
				ed.setProgressState(0);
				$.jGrowl(ret['message'], {theme: 'error'});
				return;
			}
			var insert_after = ret['insertAfter'];
			var body = ret['body'];
			var id = ret['id'];
			
			ed.setProgressState(0); 	
			if (insert_after > 0){
				$("#main_comment_" + insert_after).after(body);
			} else {
				$("#comments_div").append(body);
			}
			$.jGrowl(ret['message']);
			recepty.comm_exit(article_id, parent_id, level);
			$.scrollTo('#main_comment_' + id);
			$('#main_comment_' + id).effect("highlight", {}, 3000);
			//adding actions for comunity buttons
			recepty.add_comment("comm_add_" + article_id +"_" + id + "_" + (level+1));
			recepty.update_comment("comm_update_" + article_id +"_" + id + "_" + (level+1));
			recepty.delete_comment("comm_delete_" + id);
		},
		"json"
	);
}

recepty.comm_save = function(article_id, comment_id, level) {

	var ed = tinyMCE.get("comment_"+ article_id +"_" + comment_id);
	if (!ed.getContent()) {
            $.jGrowl("Комментарий не может быть пустым", {
                    theme: 'error'
            });
            return false;
	}
        
	//alert(ed.getContent());
	ed.setProgressState(1);
	$.post(
		   	"/recepty/savecomment/article_id/"+article_id,
			{
				"id": comment_id,
				"level": level,
				"com_body": ed.getContent()//$("#comment_" + article_id +"_" + comment_id).attr("value")			
			},
			function(ret){
				
				if (ret['res'] == false) {
					ed.setProgressState(0);
					$.jGrowl(ret['message'], {theme: 'error'});
					return;
				}
				
				ed.setProgressState(0); 
				//alert(ret);
				// замена целого комента $("#main_comment_" + comment_id).replaceWith(ret['body']);
				$("#edit_comment_" + comment_id).replaceWith("<div id=edit_comment_" + comment_id + ">" + ret['body'] + "</div>");
				$.jGrowl(ret['message']);				
				recepty.comm_exit(article_id, comment_id, level);
				//tinyMCE.execCommand("mceRemoveControl", false, "comment_"+ article_id +"_" + comment_id);
				//alert("comm_add_" + article_id +"_" + comment_id + "_" + level);
				recepty.add_comment("comm_add_" + article_id +"_" + comment_id + "_" + level);
				recepty.update_comment("comm_update_" + article_id +"_" + comment_id + "_" + level);
				recepty.delete_comment("comm_delete_" + comment_id);
			},
			"json"
		);
}

recepty.comm_exit = function(article_id, parent_id, level){
	
	//var article_id = id.split('_')[2];
	//var parent_id = id.split('_')[3];
//	var the_element = document.getElementById(id.replace('update', 'add')+"_form");
	$("#empty_comment" + parent_id).remove();	
	tinyMCE.execCommand("mceRemoveControl", false, "comment_"+ article_id +"_" + parent_id);
	if (parent_id == '0') {
		$("#comm_add_" + article_id + "_" + level + "_form").hide();
		//$("#comm_add_"+ article_id + "_" + level + "_form").slideUp('slow');
	}else{
		$("#comm_add_" + article_id + "_" + parent_id + "_" + level + "_form").hide();
		//$("#comm_add_"+ article_id + "_" + parent_id + "_" + level + "_form").slideUp('slow');
	}
	
//	the_element.innerHTML = "";
}

recepty.comm_rating_enabled = function (id, rate) {

	$('#'+id).unbind("click").click(function(){
		var comment_id = id.split('_')[4];
		$.post(
			   	"/recepty/ratecomment/id/"+comment_id,
				{
					"rate": rate
				},
				function(ret){
					if (ret['res'] == false) {
						$.jGrowl(ret['message'], {theme: 'error'});
						return;
					}					
					$.jGrowl(ret['message']);	
					$("#comm_rating_" + comment_id).replaceWith(ret['body']);	
				},
				"json"
			);
	});	
}


recepty.setup_comment_mceEditor = function () {
	
	tinyMCE.init({
		mode : "none",
		theme : "advanced",
		language : "ru",
		relative_urls : false,
		plugins : "emotions,simpleuploader",
		
		theme_advanced_buttons1 : "emotions,simpleuploader",
		theme_advanced_buttons2 : "",
		theme_advanced_buttons3 : "",
		theme_advanced_toolbar_location : "top",
		theme_advanced_toolbar_align : "left",
		theme_advanced_resizing : true,
		theme_advanced_resize_horizontal : false,

		//valid_elements : "p,a,img"
		valid_elements : "a[href|title],p,img[src|width|height|alt|title],br"
//		file_browser_callback : 'myFileBrowser'
			
/*		theme_advanced_statusbar_location : "bottom",
		force_br_newlines : true,
		
		paste_use_dialog : false,
		theme_advanced_link_targets : "_something=My somthing;_something2=My somthing2;_something3=My somthing3;",
		paste_auto_cleanup_on_paste : true,
		paste_convert_headers_to_strong : false,
		paste_strip_class_attributes : "all",
		paste_remove_spans : false,
		paste_remove_styles : false		
*/	});	
}


function getTagActionName(form) {
	var url = '/recepty/tag/';
	var isEmpty = true;
	var tag = $('#tagname').val();
	if (tag != '') {
		url += tag + '/';
		isEmpty = false;
	}
	if (isEmpty == false) { 
		window.location.href = url; 
		return false;
	}
	return false;
} 

recepty.setup_top = function () {
	
	if (location.href.indexOf('#blog_') != -1) {
		pos = location.href.substring(location.href.indexOf('#blog_')+6, location.href.length);
		display_articles('blogdiv_'+pos);
	}
}


function display_articles(id) {
	
	top_art = document.getElementById(id);
	
	if (top_art) {
		
		if (top_art.style.display == 'none')
			top_art.style.display = 'block';
		else
			top_art.style.display = 'none';
	}
}

var addthis_config = {
	services_custom: [{
	              name: "Мой мир",
	              url: "http://connect.mail.ru/share?share_url={{url}}&title={{title}}",
	              icon: "/images/button_micro_moimir.gif"
	              }],
	ui_language: "ru",
	data_track_clickback: true
}


$(document).ready(function() {
	
	// MakeOk
	$('a[id^="okay"]').each(function() {
		recepty.remove_from_public(this.id)
	});
	
	$('a[id^="all"]').each(function() {
		recepty.move_to_public(this.id)
	});

	$('a[id^="pin"]').each(function() {
		recepty.pin(this.id)
	});

	$('a[id^="unpin"]').each(function() {
		recepty.unpin(this.id)
	});
	
	
	// Delete recept
	$('a[id^="delete"]').each(function() {
		recepty.delete_recept(this.id)
	});

	//Make favorite
	$('a[id^="is_favorite"]').each(function() {
		recepty.remove_from_favorite(this.id)
	});
	
	$('a[id^="not_favorite"]').each(function() {
		recepty.move_to_favorite(this.id)
	});

	//Rating recept
	$('div[id^="rate_"]').each(function() {
		recepty.rating_enabled(this.id)
	});

	$.getScript( "http://s7.addthis.com/js/250/addthis_widget.js#username=chefcomua");

	// Add comment
	$('a[id^="comm_add"]').each(function() {
		recepty.add_comment(this.id)
	});

	// Delete comment
	$('a[id^="comm_delete"]').each(function() {
		recepty.delete_comment(this.id)
	});
	
	// Edit comment
	$('a[id^="comm_update"]').each(function() {
		recepty.update_comment(this.id)
	});

	//Rating comment up
	$('a[id^="comm_rating_up"]').each(function() {
		recepty.comm_rating_enabled(this.id, 1)
	});

	//Rating comment down
	$('a[id^="comm_rating_down"]').each(function() {
		recepty.comm_rating_enabled(this.id, 0)
	});

	//Setup for tiniMCE
	$('div[id^="comments_div"]').each(function() {
		recepty.setup_comment_mceEditor()
	});
	
	//Setup for TOP
	$('div[id^="top_div"]').each(function() {
		recepty.setup_top()
	});

	
	
});
