﻿/// <reference path="jquery-1.2.6.min.js" />
/// <reference path="model.js" />
/// <reference path="jquery.jgrowl_minimized.js" />

/// <reference path="jquery.tooltip.min.js" />
/// <reference path="jquery.jgrowl_minimized.js" />


function Nizzote()
{ 


	$("#link").click(function()
	{
		var txt = $(this).text();
		if (window.clipboardData)
		{
			window.clipboardData.setData('Text', t);
			$.jGrowl("Copied '" + txt + "' to clip board!");
		}
		else
		{ 
			$.copy(txt);
		}

	});
	if (!window.clipboardData)
	{
		$("#clickcopy").hide();
	}

	$(".tip").tooltip({ 
		track: true, 
		delay: 0, 
		showURL: false, 
		showBody: " - ", 
		fade: 250 
	});
 
    function Login(setting)
    {
        isLoggedIn = setting;
        if (!isLoggedIn)
        {
            $("#DivImmortal").show();
            $("#logout").hide();
        }
        else
        {
            $("#logout").show();
        }

        $("#logout").unbind().click(function()
        {
            Login(false);
            jax(null, "/a/login.asmx/Logout", true, function(msg)
            {
                $.jGrowl($("string", msg).text());
            });
            return false;
        });
    } Login(isLoggedIn);

    if (!isOwner)
    {

        $("#Immortal").click(function() { $.jGrowl("You must be registered / logged in to endow imortality"); LoginSignUp(); $("#DivImmortal").slideUp(); });
    }

    if (!isOwned)
    {
        $("#DivOwn").show();
    }

    $("#tools").slideDown();

    var postdata = { newNote: $("#noteTextShow").text(),
        isPrivate: $("#isPrivate")[0].checked,
        WritePrivilage: $("#WritePrivilage")[0].checked,
        isLocked: $("#isLocked")[0].checked,
        SharedKey: $("#SharedKey")[0].checked,
        url: url
    };

    function Ownership()
    {
        $("#MakePublic").click(function()
        {
            jax({ url: url }, "/a/layout.asmx/MakePublic", false, function(msg)
            {
                if (eval($("success", msg).text()))
                {
                    $("#DivOwn").slideUp();
                    isOwned = true;
                    $.jGrowl("Nizzote Is Now Public Domain");
                }
                else
                {
                    $.jGrowl($("msg", msg).text());
                }
            });
        });

        $("#TakeOwnership").click(function()
        {
            jax({ url: url }, "/a/layout.asmx/TakeOwnership", false, function(msg)
            {
                if (eval($("success", msg).text()))
                {
                    $("#DivOwn").slideUp();
                    isOwned = true;
                    $.jGrowl("This Nizzote Is Now Yours.");
                }
                else
                {
                    $.jGrowl($("msg", msg).text());
                    LoginSignUp();
                }
            });
        });

    } Ownership();


    function LoginSignUp()
    {
        $("#LoginSignUp").slideDown();

        $("#email").click(function()
        {
            if ($(this).val() == "email") $(this).val('');
        });
        $("#password").click(function()
        {
            if ($(this).val() == "email") $(this).val('');
        });

        $("#btnLogin").unbind().click(function()
        {
            var password = $("#password").val();
            var email = $("#email").val();
            $("#btnLogin").attr('disabled', 'disabled');
            jax({ email: email, password: password }, "/a/login.asmx/LoginAttempt", false, function(msg)
            {
                $("#btnLogin").removeAttr('disabled');
                if (eval($("success", msg).text()))
                {
                    $.jGrowl('You are logged in');
                    $("#LoginSignUp, #DivImmortal").slideUp();
                    Login(true);
                }
                else
                {
                    $("#LoginMsg").text($("msg", msg).text());
                }
            });
        });

        $("#Forgot").unbind().click(function()
        {
            var email = $("#email").val();
            jax({ email: email, password: password }, "/a/login.asmx/Forgot", false, function(msg)
            {
                $("#LoginMsg").text($("msg", msg).text());
            });
        });


        $("#btnSignUp").unbind().click(function()
        {
            var password = $("#password").val();
            var email = $("#email").val();
            $("#btnSignUp").attr('disabled', 'disabled');
            jax({ email: email, password: password }, "/a/login.asmx/SignUp", false, function(msg)
            {
                $("#btnSignUp").removeAttr('disabled');
                if (eval($("success", msg).text()))
                {
                    $.jGrowl('You are logged in');
                    $("#LoginSignUp, #DivImmortal").slideUp();
                    Login(true);
                }
                else
                {
                    $("#LoginMsg").text($("msg", msg).text());
                }
            });
        });
    }

    function SubPages()
    {
        $("#newSubPage").keyup(function(e)
        {
            if (e.keyCode == 13)
            {
                $.jGrowl("just type the url that you want in the browser");
            }
        });

        jax({ url: url }, "/a/layout.asmx/GetSubPages", false, function(msg)
        {
        	$("string", msg).each(function()
        	{
        		var subpage = $(this).text(); 
        		$("#SubPages").append(subpage);
        	});
        	$("#SubPages a").tooltip({
        			track: true,
        			delay: 0,
        			showURL: false,
        			showBody: " - ",
        			fade: 250
        		});
        });
    } SubPages();




    var Logs = {
    	InsertLog:
                function(date, justOne)
                {
                	$("#log").prepend(date)
                	if (justOne)
                	{
                		Logs.ClickLogs();
                		$.jGrowl("Saved.");
                		$("#log a:first").tooltip({
                			track: true,
                			delay: 0,
                			showURL: false,
                			showBody: " - ",
                			fade: 250
                		}); 
                	} 
                },
    	ClickLogs:
                function()
                {
                	$("#log a:first").hide().slideDown();

                	$("#log a").unbind('click').click(function()
                	{
                		getHTML(null, $(this).attr('href'), true, function(data)
                		{
                			$("#ghost #content").html($("#noteTextShow", data).html());
                			$("#ghost").slideDown('fast');
                			$("#close").unbind().click(function()
                			{
                				$("#ghost").slideUp('fast');
                			});

                		});
                		return false;
                	})


                },

    	GetLogs:
                function()
                {
                	jax({ url: url }, "/a/layout.asmx/GetLogs", false, function(msg)
                	{
                		$("string", msg).each(function()
                		{
                			var date = $(this).text();
                			Logs.InsertLog(date, false);
                		});
                		Logs.ClickLogs();
                		$("#log a").tooltip({
                			track: true,
                			delay: 0,
                			showURL: false,
                			showBody: " - ",
                			fade: 250
                		});
                	});
                }
    }
    Logs.GetLogs();

    function Locks()
    {
        $("#isLocked").click(function()
        {
            if (!isOwner)
            {
                $.jGrowl("You must own this page to lock it");
            }
            else
            {
                //write lock
                jax({ isLocked: $("#isLocked")[0].checked }, "/a/layout.asmx/Lock", true, function(msg)
                {
                    var date = $("msg", msg).text();
                    if (eval($("success", msg).text()))
                    {
                        Logs.InsertLog(date, true);
                    }
                    else
                    {
                        $.jGrowl(date);
                        $("#isLocked")[0].checked = !($("#isLocked")[0].checked);
                    }
                });
            }
        });
    } Locks();

    function SharedKey()
    {

        function ShowHide()
        {
            $("#ChecksharedKey").click(function()
            {
                if (!$(this)[0].checked)
                {
                    $("#sharedKeyBox").slideUp();
                    $("#SharedKey").val('');
                    $("#SaveKey").click();
                }
                else $("#sharedKeyBox").slideDown();
            });

            if ($("#ChecksharedKey")[0].checked) $("#sharedKeyBox").slideDown();
        } ShowHide();

        $("#SaveKey").click(function()
        {
            //update key
            jax({ Key: $("#SharedKey").val() }, "/a/layout.asmx/SaveKey", true, function(msg)
            {
                var date = $("msg", msg).text();
                if (eval($("success", msg).text()))
                {
                    Logs.InsertLog(date, true);
                }
                else
                {
                    $.jGrowl(date);
                }
            });
        });

        $("#WritePrivilage").click(function()
        {
            //update Write
            jax({ WritePrivilage: $("#WritePrivilage")[0].checked }, "/a/layout.asmx/Privilage", true, function(msg)
            {
                var date = $("msg", msg).text();
                if (eval($("success", msg).text()))
                {

                    Logs.InsertLog(date, true);
                }
                else
                {
                    $.jGrowl(date);
                    $("#WritePrivilage")[0].checked = !($("#WritePrivilage")[0].checked);
                }
            });
        });

    } SharedKey();

    function Privacy()
    {
        var isPrivate = $("#isPrivate")[0].checked;

        function ShowHide()
        {
            if (!isLoggedIn)
            {
                $("#isPrivate")[0].checked = isPrivate;
            }
            if (isPrivate)
                $("#DivSharedKey").slideDown();
            else
                $("#DivSharedKey").slideUp();
        } ShowHide();

        $("#isPrivate").unbind().click(function()
        {
        	isPrivate = $("#isPrivate")[0].checked;
        	if (isLoggedIn)
        	{
        		//write privacy
        		jax({ isPrivate: $("#isPrivate")[0].checked }, "/a/layout.asmx/Private", true, function(msg)
        		{
        			var date = $("msg", msg).text();
        			if (eval($("success", msg).text()))
        			{
        				Logs.InsertLog(date, true);
        				ShowHide();
        			}
        			else
        			{
        				$.jGrowl(date);
        				$("#isPrivate")[0].checked = !($("#isPrivate")[0].checked);
        			}
        		});
        	}
        	else
        	{
        		$(this)[0].checked = false;
        		$.jGrowl("You must be logged in to do this.");
        		LoginSignUp();
        		return false;
        	}

        });

    } Privacy();

	function replaceURLWithHTMLLinks(text) {
		var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gi;
		return text.replace(exp,"<a target=\"_blank\" href='$1'>$1</a>"); 
	}


    function replaceURLs(re, newText)
    {
		var matches = newText.match(re);
        if (matches != null)
        {
            if (matches.length > 0)
            {
                for (var i = 0; i < matches.length; i++)
                {
                    var protocol = "http://";
                    if (matches[i].indexOf(":") != -1)
                    { protocol = ""; }
                    var link = "<a target=\"_blank\" href=\"" + protocol + matches[i] + "\">" + matches[i] + "</a>";

                    newText = newText.replace(matches[i], link);
                }
            }
        }

        return newText;
    }

    function Delete()
    {
		//delete nizzotes - for now i will actually delete them, maybe in the future i'll just "flag" them as deleted
    	$("#delete").click(function()
    	{
    		$(this).slideUp();
    		$("#confirmDelete").slideDown(); 
    	});

    	$("#yesDelete").click(function()
    	{
    		//do delete
    		jax(null, "/a/layout.asmx/Delete", true, function(msg)
    		{
    			if (eval($("success", msg).text()))
    			{
    				$.jGrowl("Page Deleted");
    				$("#controlForm").attr('action', '/a').submit();
    			}
    			else
    			{
    				$.jGrowl("Error:" + $("msg", msg).text()); 
    			}
    		});
    	});
    	$("#cancelDelete").click(function() { 
    		$(this).slideUp();
    		$("#delete").slideDown();
    	});
    }Delete();
	
    function WebNote()
    {
        //parse and update links then update Show with new edit

        var item = $("#noteTextShow");

        var newText = item.html().replace(/<br>/gi, "\n");
        //var re = /([^ \n]+)(\.com)([^ \n]+)/ig;
        //newText = replaceURLs(re, newText);
        //re = /([^ \n]+)(\.com)/ig;
        //newText = replaceURLs(re, newText);

        newText = replaceURLWithHTMLLinks(newText);

        newText = newText.replace(/\n/gi, "<br />").replace(/  /g, "");

        if (newText == '' | newText == ' ') { newText = "Click here, then type here." }

        $("#noteTextShow").html(newText);
    }

    function EditorToShow()
    {
        var safehtml = $("#noteTextEdit").val();
        safehtml = safehtml.replace(/</gi, "&lt;").replace(/>/gi, "&gt;").replace(/\n /gi, "\n&nbsp;").replace(/\n/gi, "<br>").replace(/  /gi, "&nbsp; ");
        if (safehtml.charAt(0) == ' ')
            safehtml = safehtml.replace(" ", "&nbsp;");
        $("#noteTextShow").html(safehtml);
    }

    function ShowToEditor()
    {
        var showbox = $("#noteTextShow");
        if (showbox.text() == 'Click here, then type here.') { showbox.text(''); }
        $("#noteTextEdit").height(showbox.height());

        //put whats was shown into the editor - escape line breaks manually so that they don't get lost in translation
        var re = new RegExp("<br/>", "gi");
        var escaped = showbox.html().replace(/<br>/gi, "&lt;br/&gt;").replace(re, "&lt;br/&gt;").replace(RegExp("<br />", "gi"), "&lt;br/&gt;"); //.replace(/<b>/gi, "&lt;b&gt;").replace(/<\/b>/gi, "&lt;/b&gt;");
        showbox.html(escaped);
        $("#noteTextEdit").val(showbox.text().replace(re, "\n"));
    }

    function Editor()
    {

        //auto size text box
        $("#noteTextEdit").keyup(function()
        {
            isDirty = true;
            EditorToShow();
            $(this).height($("#noteTextShow").height());
        });

        $("#noteTextShow").click(function()
        {
            ShowToEditor();
            $("#noteTextShow").hide();
            $("#noteTextEdit").show().focus();
        });

        $("#noteTextEdit").blur(function()
        {

            EditorToShow();
            WebNote(); //turn urls into links
            $("#noteTextShow").show();
            $("#noteTextEdit").hide();

            //save then append to log
            if (isDirty)
            {
                jax({ newNote: $("#noteTextEdit").val() }, "/a/layout.asmx/Save", true, function(msg)
                {
                    if (eval($("success", msg).text()))
                    {
                        var date = $("msg", msg).text();
                        isDirty = false;
                        Logs.InsertLog(date, true);
                    }
                    else
                    {
                        $.jGrowl($("msg", msg).text());
                        LoginSignUp();
                    }
                });
            }
        });

    }

    Editor();
    ShowToEditor();
    EditorToShow();
    WebNote();
}

$().ready(Nizzote);