function delete_comment(id){
	if(confirm("Вы действительно хотите удалить коментарий?")){
		location.replace("/php/delete-idea-comment.php?comment_id="+id);
	}
}

function showWindow() {
	$(".modal_window").css({display: "block"});
	$(".modal_window").animate({opacity: '1.0'}, 500);
}

$.fn.fireEvent = function(eventType) {
  return this.each(function() {
    if (document.createEvent) {
      var event = document.createEvent("HTMLEvents");
      event.initEvent(eventType, true, true);
      return !this.dispatchEvent(event);
    } else {
      var event = document.createEventObject();
      return this.fireEvent("on" + eventType, event)
    }
  });
};

function validate_email(str)
{
	apos=str.indexOf("@");
	dotpos=str.lastIndexOf(".");
	if (apos<1||dotpos-apos<2) 
	 {return false;}
	else {return true;}
}

$(document).ready(function () {

	$(".users_type").click(function() {
		var id = $(this).attr("id");
		var name = "#u"+id;
		var display;
		if($(name).css("display") == "block")
			display = 'none';
		else
			display = 'block';
		$(name).css("display", display);
	});
	
	$(".close_access").click(function() {
        if(!confirm("Действительно закрыть доступ?")) {
            return false;
        } else {
            $(this).parent().append("&nbsp;Проверка данных...");

            var idea_id = $(this).parents("div.idea_block").attr("id");
			var user_id = $(this).attr("id");
			
            $.ajax({
                type: "POST",
                url: "/php/close_access.php",
                cache: false,
                data: "idea_id=" + idea_id + "&user_id=" + user_id,
                dataType: "json",
                timeout: 5000,
                success: function (data) {
                    if(data.status == '0') {
                        $(this).parent().append(data.message);
                    } else if (data.status == '1') {
                        $("#" + idea_id).remove();
                    }
                },
                error: function () {
                    $(this).parent().append("Ошибка соединения. Попробуйте позже.");
                }
            });
        }
        return false;
    });

    $(".delete_idea").click(function() {
        if(!confirm("Действительно удалить идею?")) {
            return false;
        } else {
            $(this).parent().append("&nbsp;Проверка данных...");

            var idea_id = $(this).parents("div.idea_block").attr("id");

            $.ajax({
                type: "POST",
                url: "/php/delete-idea.php",
                cache: false,
                data: "idea_id=" + idea_id,
                dataType: "json",
                timeout: 5000,
                success: function (data) {
                    if(data.status == '0') {
                        $(this).parent().append(data.message);
                    } else if (data.status == '1') {
                        $("#" + idea_id).remove();
                    }
                },
                error: function () {
                    $(this).parent().append("Ошибка соединения. Попробуйте позже.");
                }
            });
        }
        return false;
    });
	
	$(".delete_friend_idea").click(function() {
        if(!confirm("Действительно удалить идею?")) {
            return false;
        } else {
            $(this).parent().append("&nbsp;Проверка данных...");

            var idea_id = $(this).parents("div.idea_block").attr("id");
			

            $.ajax({
                type: "POST",
                url: "/php/delete-friend-idea.php",
                cache: false,
                data: "idea_id=" + idea_id,
                dataType: "json",
                timeout: 5000,
                success: function (data) {
                    if(data.status == '0') {
                        $(this).parent().append(data.message);
                    } else if (data.status == '1') {
						$(this).parent().append(data.message);
                    }
					else if (data.status == '2') {
                        $("#" + idea_id).remove();
						//$(this).parent().append("sss");
                    }
                },
                error: function (jXHR, textStatus, errorThrow) {
                    $(this).parent().append("Ошибка соединения. Попробуйте позже.");
                }
            });
        }
        return false;
    });

    $("#login_form").submit(function() {
        var form_data = $(this).serialize();
        $("#login_status").text("Проверка данных...");

        $.ajax({
            type: "POST",
            url: "/login.php",
            cache: false,
            data: form_data + "&js=1",
            dataType: "json",
            timeout: 5000,
            success: function (data) {
                if(data.status == '0') {
                    $("#login_status").text(data.message);
                } else if (data.status == '1') {
                    window.location.reload();
                }
            },
            error: function () {
                $("#login_status").text("Ошибка соединения. Попробуйте позже.");
            }
        });

        return false;
    });

    $("#change_pass_link").click(function () {
        $(".new_password").toggle();

        return false;
    });

    $("#add_cv_block").click(function () {
        var count = $(this).parent().parent().siblings().length;
        $(this).parent().parent().before('<tr><td><input type="text" name="' + (count + 1) + '_title_new" maxlength="500" size="50" /><br /><textarea name="' + (count + 1) + '_contents_new" cols="40" rows="7"></textarea></td></tr>');
        $("textarea[name='" + (count + 1) + "_contents_new']").tinymce({
            script_url : "/scripts/tiny_mce_jquery/tiny_mce.js",
        width : "373",
        language : "ru",
        theme : "advanced",
        theme_advanced_buttons1 : "bold,italic,underline,strikethrough,separator,undo,redo,separator,link,unlink,separator,bullist,numlist,separator,code",
        theme_advanced_buttons2 : "",
        theme_advanced_buttons3 : ""
        });

        return false;
    });

    $("#add_idea_block").click(function () {
        var count = $(this).parent().parent().siblings().length;
        $(this).parent().parent().before('<tr><td><input type="text" name="' + (count + 1) + '_title_new" maxlength="500" size="50" /><br /><textarea name="' + (count + 1) + '_abstract_new" cols="40" rows="3"></textarea><br /><textarea name="' + (count + 1) + '_contents_new" cols="40" rows="7"></textarea><input type="file" name="' + (count + 1) + '_file_new" /><br /><select name="' + (count + 1) + '_visibility_new"><option value="0">черновик</option><option value="1">со-авторам</option><option value="2">всем</option></select></td></tr>');
        $("textarea[name='" + (count + 1) + "_contents_new'], textarea[name='" + (count + 1) + "_abstract_new']").tinymce({
            script_url : "/scripts/tiny_mce_jquery/tiny_mce.js",
        width : "373",
        height: "100",
        language : "ru",
        theme : "advanced",
        theme_advanced_buttons1 : "bold,italic,underline,strikethrough,separator,undo,redo,separator,link,unlink,separator,bullist,numlist,separator,code",
        theme_advanced_buttons2 : "",
        theme_advanced_buttons3 : ""
        });

        return false;
    });

    $("#cv_table_edit").tableDnD({dragHandle: "drag-handle"});

    $('#cv_table textarea, .mce').tinymce({
        script_url : "/scripts/tiny_mce_jquery/tiny_mce.js",
        content_css : "/css/tinymce_jquery.css",
        width : "373",
        height: "100",
        language : "ru",
        theme : "advanced",
        theme_advanced_blockformats : "p,h2,h3,h4,h5",
        theme_advanced_buttons1 : "bold,italic,underline,strikethrough,separator,formatselect,separator,undo,redo,separator,link,unlink,separator,bullist,numlist,separator,code",
        theme_advanced_buttons2 : "",
        theme_advanced_buttons3 : ""
    });

    $('#cv_table tr').mouseenter(function () {
        $(this).find(".delete_cv_block").show();
        $(this).find(".delete_idea_block").show();
    });

    $('#cv_table tr').mouseleave(function () {
        $(this).find(".delete_cv_block").hide();
        $(this).find(".delete_idea_block").hide();
    });

    $(".delete_cv_block").click(function () {
        var id = $(this).attr("name");
        id = id.replace(/_delete/, '');
        var link = $(this);

        if(confirm("Удалить параграф резюме?")) {
            $.ajax({
                type: "POST",
                url: "/php/cvblock-delete.php",
                data: "id=" + id + "&user=" + $("input[name='user']").attr("value"),
                success: function(msg){
                    if(msg == '1') {
                        link.parent().parent().remove();
                    } else {
                        alert(msg);
                    }
               }
             });
        }

        return false;
    });

    $(".delete_idea_block").click(function () {
        var id = $(this).attr("name");
        id = id.replace(/_delete/, '');
        var link = $(this);

        if(confirm("Удалить параграф Идеи?")) {
            $.ajax({
                type: "POST",
                url: "/php/ideablock-delete.php",
                data: "id=" + id + "&user=" + $("input[name='user']").attr("value"),
                success: function(msg){
                    if(msg == '1') {
                        link.parent().parent().remove();
                    } else {
                        alert(msg);
                    }
               }
             });
        }

        return false;
    });

    $(".delete_ideaparagraph_file").click(function () {
        var id = $(this).attr("rel");

        if(confirm("Удалить файл из параграфа?")) {
            $.ajax({
                type: "POST",
                url: "/php/delete-ideaparagraph-file.php",
                data: "entry_id=" + id,
                dataType: "json",
                timeout: 5000,
                success: function(data){
                    if(data.status == '1') {
                        $(this).parents(".idea_paragraph_file").remove();
                    } else {
                        alert(data.message);
                    }
               }
             });
        }

        return false;
    });

    $(".idea_paragraph_actions .action_multiple a").click(function() {
        $(".action_multiple ul").not($(this).siblings("ul")).hide();
        $(this).siblings("ul").toggle();
        return false;
    });

    $(".idea_paragraph_actions .action_multiple ul li a").click(function() {
        $("form input[type='hidden'][name='" + $(this).attr("rel") +"']").attr("value", $(this).parent().attr("name"));
        $(this).parents(".action_multiple").children("#current_" + $(this).attr("rel")).text($(this).text());
        $(this).parent().parent().hide();
        if($(this).attr("rel") == 'contents_type' && $(this).parent().attr("name") != '0') {
            $(".idea_paragraph_file").show();
        } else if ($(this).parent().attr("name") == '0') {
            $(".idea_paragraph_file").hide();
        }
    });

    $('.idea_paragraph_abstract textarea, .idea_paragraph_contents textarea').each(function() {
        var width = $(this).width() + 11;
        var height = $(this).height();
        
        $(this).tinymce({
            script_url : "/scripts/tiny_mce_jquery/tiny_mce.js",
            content_css : "/css/tinymce_jquery.css",
            width: width,
            height: height,
            language : "ru",
            theme : "advanced",
            theme_advanced_blockformats : "p,h2,h3,h4,h5",
            theme_advanced_buttons1 : "bold,italic,underline,separator,formatselect,separator,link,unlink,separator,bullist,numlist,separator,code",
            theme_advanced_buttons2 : "",
            theme_advanced_buttons3 : ""
        });
    });

    $(".idea_paragraph_actions a#save").click(function() {
        $("form").fireEvent("submit");
        return false;
    });

    $(".idea_paragraph_actions a#delete").click(function() {
        var id = $(this).attr("rel");

        if(confirm("Удалить параграф?")) {
            $.ajax({
                type: "POST",
                url: "/php/delete-ideaparagraph.php",
                data: "entry_id=" + id,
                dataType: "json",
                timeout: 5000,
                success: function(data){
                    if(data.status == '1') {
                        window.location.href = '/my-ideas/' + data.message + '/';
                    } else {
                        alert(data.message);
                    }
               }
             });
        }

        return false;
    });

    $(".invite_user").click(function() {
        $(this).next().slideToggle();
        return false;
    });

    $("ul.star-rating li a").one('click', function () {
		var rating = $(this).attr("id");
		var entry_id = $(this).parents("ul").attr("id");

		$(this).siblings().each(function () { $(this).unbind('click'); $(this).click(function () { return false; }); });

		$.ajax({
		url: "/rate.php?entry_id=" + entry_id + "&mark=" + rating,
		cache: false,
		success: function(html){
			$("p#vote_result").slideDown();
			$("p#vote_result").append(html);
			setTimeout('$("p#vote_result").animate({opacity: "0.0"}, 1000)', 1500);
			setTimeout('$("p#vote_result").text("")', 2500);
		}
        });

        return false;
    });

    $(".invite_submit").click(function() {
        $(this).siblings("form").submit();
        return false;
    });

    $(".show_comments").click(function() {
        $(this).nextAll(".comments").slideToggle();
        return false;
    });

    $(".show_comment_form").click(function() {
        $(this).nextAll(".form").slideToggle();
        return false;
    });
});
