﻿//var logedIn = false;
var errorLoadAgain = "Der opstod en fejl. Vær venlig at genindlæse siden igen."
var userObj;

//init
$(document).ready(function() {
    //init formHighlighter
    $(".minSideCreate, .minSideEdit, .minSideContentLoginCreate").formHighlighter({
        classFocus: 'focus',
        classBlur: 'blur',
        classKeyDown: 'keydown'
    });

    //dim layer init
    $("#dim").css("height", $(document).height());
    $(".msgBoxClose").click(function() {
        $("#dim").fadeOut();
        return false;
    });

    //check for login errormessage
    AjaxMyPage.readCookie("errorLogin", function(res) {
        if (res.error != null) {
            $("#statusBox").msgbox({ msg: errorLoadAgain, type: "error", time: 3000 });
        } else {
            if (res.value != null && res.value != "") {
                $("#statusBox").msgbox({ msg: res.value, type: "warning", time: 3000 });
            }
        }
    });

    //autoopen tab on login
    AjaxMyPage.readCookie("tabOpen", function(res) {
        if (res.error != null) {
            $("#statusBox").msgbox({ msg: errorLoadAgain, type: "error", time: 3000 });
        } else {
            if (res.value == "true") {
                showHideContentBoxes();
            }
        }
    });

    //show/hide contentboxes
    $(".openContentBoxes").click(function() {
        location.href = "#";
        showHideContentBoxes();
    });

    //create userobj if user is loged in
    AjaxMyPage.isLogedIn(createUserObj_Callback);

    //Bind clickevents
    $(".showCreateProfile").click(function() {
        $(".minSideContent").removeClass("roundedCornerTopRight").removeClass("roundedCornerBottomRight").css("height", $(".minSideCreate").height() + 29 + "px");
        $(".minSideCreate").css("display", "block");
    });

    $(".showEditProfile").click(function() {
        var minSideContentHeight = $(".minSideContent").height() - 29;
        var minSideEditHeight = $(".minSideEdit").height();
        var diffInHeight = -1;

        if (minSideContentHeight > minSideEditHeight) {
            diffInHeight = minSideContentHeight - minSideEditHeight;
            $(".minSideContent").removeClass("roundedCornerTopRight").removeClass("roundedCornerBottomRight");
            $(".minSideEdit").css("height", $(".minSideEdit").height() + diffInHeight + "px");
        } else {
            diffInHeight = minSideEditHeight - minSideContentHeight;
            $(".minSideContent").removeClass("roundedCornerTopRight").removeClass("roundedCornerBottomRight").css("height", $(".minSideContent").height() + diffInHeight + "px");
        }
        $(".minSideEdit").css("display", "block");
    });

    $("#btnCreateProfile").click(function() {
        createProfile();
    });

    $("#btnUpdateProfile").click(function() {
        updateProfile();
    });

    $(".minSideDeleteProfile a").click(function() {
        deleteProfile();
    });

    $(".addToMyPage").click(function() {
    //åbn dialogboks. Valg: vil du abbonnere på sidens underliggende sider også?
        msgBoxAlert();
    });

    $("#btnSaveMyPage").click(function() {
        var saveSubPages = $("#addSubPages").is(':checked');

        AjaxMyPage.saveMyPage($("#userId").val(), $("#pageId").val(), saveSubPages, saveMyPage_Callback);
        return false;
    });

    $(".addToMyNews").click(function() {
        if ($("#newsCats") != null) {
            AjaxMyPage.saveMyNews($("#userId").val(), $("#newsCats").val(), function(res) {
                if (res.error != null) {
                    $("#statusBox").msgbox({ msg: res.error.Message, type: "warning", time: 3000 });
                } else {
                    $("#statusBox").msgbox({ msg: "Nyhederne er gemt", type: "success", time: 3000 });
                }
            });
        } else {
            $("#statusBox").msgbox({ msg: "Der er ingen nyhedskatergorier at tilføje", type: "info", time: 3000 });
        }
        return false;
    });

    //Bind enterkey to Create Profile fields
    $(".createLogin").keydown(function(e) {
        if (e.keyCode == 13) {
            createProfile();
            return false;
        }
    });

    //Bind enterkey to Update Profile fields
    $(".editLogin").keydown(function(e) {
        if (e.keyCode == 13) {
            updateProfile();
            return false;
        }
    });
});

function msgBoxAlert() {
    $("#dim").fadeIn();
    return false;
    
}

function createUserObj_Callback(res) {
    // create userobj
    if (res.error != null) {
        //user not loged in (disable formfields)
        $(".notLoggedInMsg").show();
        if ($("#comment_name").length > 0) {
            $("#comment_name").attr("disabled", "disabled")
        }
        if ($("#comment_email").length > 0) {
            $("#comment_email").attr("disabled", "disabled")
        }
        if ($("#comment_comment").length > 0) {
            $("#comment_comment").attr("disabled", "disabled")
        }

    } else {
        userObj = res.value;

        $(".minSideUser").html(userObj.Userrealname + "´s menu:");
        
        // if commentbox is show, add name and e-mail to textboxes
        if ($("#comment_name").length > 0) {
            $("#comment_name").val(userObj.Userrealname);
        }
        if ($("#comment_email").length > 0) {
            $("#comment_email").val(userObj.Email);
        }
    }
    
}

function createProfile() {
    //validation
    if ($("#createNavn").val() == "navn" || $("#createNavn").val() == "") {
        $("#statusBox").msgbox({ msg: "Navn skal udfyldes", type: "warning", time: 3000 });
        return false;
    }
    if ($("#createEmail").val() == "e-mailadresse" || $("#createEmail").val() == "") {
        $("#statusBox").msgbox({ msg: "E-mailadresse skal udfyldes", type: "warning", time: 3000 });
        return false;
    }
    if (!isValidEmailAddress($("#createEmail").val())) {
        $("#statusBox").msgbox({ msg: "E-mailadresse skal være gyldig", type: "warning", time: 3000 });
    }
    if ($("#createPassword").val() == "adgangskode" || $("#createPassword").val() == "") {
        $("#statusBox").msgbox({ msg: "Adganskoden skal udfyldes", type: "warning", time: 3000 });
        return false;
    }
    if ($("#createPasswordRepeat").val() == "gentag adgangskode" || $("#createPasswordRepeat").val() == "") {
        $("#statusBox").msgbox({ msg: "Gentag adganskoden skal udfyldes", type: "warning", time: 3000 });
        return false;
    }
    if ($("#createPassword").val() != $("#createPasswordRepeat").val()) {
        $("#statusBox").msgbox({ msg: "Felterne adgangskode og gentag adgangskode skal være ens", type: "warning", time: 3000 });
        return false;
    }

    //track click in GA
    pageTracker._trackEvent('Min Side', 'Opret profil');

    //call ajaxmethod
    AjaxMyPage.CreateProfile($("#createNavn").val(), $("#createEmail").val(), $("#createPassword").val(), createProfile_Callback);
}

function createProfile_Callback(res) {
    if (res.error != null) {
        $("#statusBox").msgbox({ msg: res.error.Message, type: "warning", time: 3000 });
    } else {
        clearCreateProfileForm();
        $("#statusBox").msgbox({ msg: "Din bruger er oprettet. Du får tilsendt en godkendelsesmail inden længe.", type: "success", time: 5000 });
    }
}

function updateProfile() {
    var password = "";
    
    if ($("#editNavn").val() == "navn" || $("#editNavn").val() == "") {
        $("#statusBox").msgbox({ msg: "Navn skal udfyldes", type: "warning", time: 3000 });
        return false;
    }

    if ($("#editPassword").val() != "adgangskode") {
        if ($("#editPassword").val() != $("#editPasswordRepeat").val()) {
            $("#statusBox").msgbox({ msg: "Felterne adgangskode og gentag adgangskode skal være ens", type: "warning", time: 3000 });
            return false;
        } else {
            password = $("#editPassword").val();
        }
    }


    //call akaxmethod
    AjaxMyPage.UpdateProfile($("#editNavn").val(), userObj.Email, password, updateProfile_Callback);
}

function updateProfile_Callback(res) {
    if (res.error != null) {
        $("#statusBox").msgbox({ msg: res.error.Message, type: "warning", time: 3000 });
    } else {
        if (res.value) {
            $("#statusBox").msgbox({ msg: "Dine data er rettet.", type: "success", time: 5000 });
        } else {
            $("#statusBox").msgbox({ msg: "Ingen data blev ændret.", type: "info", time: 5000 });
        }

        showHideContentBoxes();
        AjaxMyPage.isLogedIn(createUserObj_Callback);
    }
}

function deleteProfile() {
    var confirmBox = confirm("Er du sikker på, at du vil slette din profil?");
    if (confirmBox) {
        AjaxMyPage.DeleteProfile(userObj.Email, deleteProfile_Callback);
    } else {}
}

function deleteProfile_Callback(res) {
    if (res.error != null) {
        $("#statusBox").msgbox({ msg: res.error.Message, type: "warning", time: 3000 });
    } else {
        if (res.value) {
            location.href = "?action=logoff";
        } else {
            $("#statusBox").msgbox({ msg: "Kunne ikke slette din profil.", type: "info", time: 5000 });
        }
    }    
}

//checks if user is loged on
function isLogedIn() {
    AjaxMyPage.isLogedIn(isLogedIn_Callback);
}

//id logedin show data else show loginbox
function isLogedIn_Callback(res) {
    if (res.error != null) {
        $(".minSideContentLoginCreate").css("display", "block");

    } else {
        //userObj = res.value;
        if ($(".minSideContentData").html().length == 0) {
            showTabLoading();
            $(".minSideUser").html(userObj.Userrealname + "´s menu:");
            $("#editNavn").val(userObj.Userrealname);
            $(".minSideLinkAdmin").css("display", "block");
            AjaxMyPage.getDomains(getDomains_Callback)
        }
    }    
}

//loads domain(s)
function getDomains_Callback(res) {
    hideTabLoading();
    if (res.error != null) {
        $("#statusBox").msgbox({ msg: errorLoadAgain, type: "error", time: 3000 });
    } else {
        obj = res.value;
        if (obj) {
            $(".minSideContentData").css("display", "block");
            for (var i = 0; i < obj.Rows.length; i++) {
                //show domain
                var domain = obj.Rows[i].domain;
                $(".minSideContentData")
                .append(
                    $("<div>")
                    .addClass("bottomMargin")
                    .attr("domain", domain)
                    .append(
                        $("<div>")
                        .addClass("minSideHeadline")
                        .addClass("minSideItemBox")
                        .html(domain)
                        .bind("click", function() {
                            var content = $("[domain=" + $(this).html() + "]").html()
                            //tjekker om der er indhold, så det ikke indlæses flere gange
                            if (content.indexOf("minSideType") == -1) {
                                //AjaxPro.queue.abort();
                                showTabLoading();
                                AjaxMyPage.getTypes($(this).html(), getTypes_Callback);
                            }
                        })
                    )
                )
            }
            $("div.bottomMargin div.minSideHeadline",".minSideContentData").click();
        } else { 
            //
        }
    }
}

function getTypes_Callback(res) {
    hideTabLoading();
    if (res.error != null) {
        $("#statusBox").msgbox({ msg: errorLoadAgain, type: "error", time: 3000 });
    } else {
    var obj = res.value;
        for (var i = 0; i < obj.Rows.length; i++) {
            //news
            if (obj.Rows[i].type == 0) {
                $("[domain=" + obj.Rows[i].domain + "]")
                .append(
                    $("<div>")
                    .addClass("minSideType")
                    .addClass("minSideNews")
                    .addClass("minSideItemBox")
                    .append(
                        $("<div>")
                        .html("Nyheder")
                        .bind("click", function() {
                            AjaxPro.queue.abort();
                            showTabLoading();
                            $("[domain=" + $(this).parent().parent().attr("domain") + "] .minSideNews").addClass("openArrow");
                            AjaxMyPage.getData($(this).parent().parent().attr("domain"), 0, getData_Callback);
                        })
                    )
                ).append(
                    $("<div>")
                    .addClass("newsDataContainer")
                )
            } 
            //pages
            else if (obj.Rows[i].type == 1) {
            $("[domain=" + obj.Rows[i].domain + "]")
                .append(
                    $("<div>")
                    .addClass("minSideType")
                    .addClass("minSidePage")
                    .addClass("minSideItemBox")
                    .append(
                        $("<div>")
                        .html("Sider")
                        .bind("click", function() {
                            AjaxPro.queue.abort();
                            showTabLoading();
                            $("[domain=" + $(this).parent().parent().attr("domain") + "] .minSidePage").addClass("openArrow");
                            AjaxMyPage.getData($(this).parent().parent().attr("domain"), 1, getData_Callback);
                        })
                    )
                ).append(
                    $("<div>")
                    .addClass("pageDataContainer")
                )
            }   
        }
    }
}

function getData_Callback(res) {
    hideTabLoading();
    if (res.error != null) {
        $("#statusBox").msgbox({ msg: errorLoadAgain, type: "error", time: 3000 });
    } else {
        var obj = res.value;

        if (obj[0].Type == 0) {
            //news
            //reset content
            $("[domain=" + obj[0].Domain + "] .newsDataContainer").html("");
            
            for (var i = 0; i < obj.length; i++) {
                $("[domain=" + obj[i].Domain + "] .newsDataContainer")
                .append(
                    $("<div>")
                    .html(obj[i].News.NewsHtml)
                )
            }
        } else if (obj[0].Type == 1) {
            //pages
            //reset content
            $("[domain=" + obj[0].Domain + "] .pageDataContainer").html("");
            
            for (var i = 0; i < obj.length; i++) {
                $("[domain=" + obj[i].Domain + "] .pageDataContainer")
                    .append(
                        $("<div>")
                        .html("<a href=\"http://" + obj[i].Domain + "/page" + obj[i].Page.PageId + ".aspx\" class=\"dataLink\"><i>" + obj[i].Page.ModifiedFormatted + "</i> " + obj[i].Page.PageTitle + "</a>")
                    )
            }
        }
    
    }
}

function saveMyPage_Callback(res) {
    $("#dim").fadeOut();
    if (res.error != null) {
        $("#statusBox").msgbox({ msg: res.error.Message, type: "warning", time: 3000 });
    } else {
        $("#statusBox").msgbox({ msg: "Siden er gemt", type: "success", time: 3000 });
    }
}

//utilities
function removeChar(text, character) {
    return text.replace(/\./g, '');
}

function isValidEmailAddress(emailAddress) {
    var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
    return pattern.test(emailAddress);
}

function showTabLoading() {
    $(".minSideUser").addClass("loadingStatus");
}

function hideTabLoading() {
    $(".minSideUser").removeClass("loadingStatus");
}

function showBigLoading(msg) {
    $("#statusBox").show().addClass("loading").html(msg);
}

function hideBigLoading() {
    $("#statusBox").hide().removeClass("loading").html();
}

function showHideContentBoxes() {
    if ($(".minSideCreate").css("display") == "block") {
        $(".minSideCreate").toggle();
        $(".minSideContent").addClass("roundedCornerTopRight").addClass("roundedCornerBottomRight");
    }
    if ($(".minSideEdit").css("display") == "block") {
        $(".minSideEdit").toggle();
        $(".minSideContent").addClass("roundedCornerTopRight").addClass("roundedCornerBottomRight");
    }

    if ($(".minSideContent").css("display") == "block") {
        $(".minSideTab").removeClass("minSideTabClose");
    } else {
        $(".minSideTab").addClass("minSideTabClose");
    }

    $(".minSideContent").toggle();
    AjaxMyPage.setCookie("tabOpen", "false");

    if ($(".minSideContent").css("display") == "block") {
        isLogedIn();
    } 
}

function clearCreateProfileForm() {
    $("#createNavn").val("navn");
    $("#createEmail").val("e-mailadresse");
    $("#createPassword").val("adgangskode");
    $("#createPasswordRepeat").val("gentag adgangskode");
}

//plugin til statusbox
(function($) {
    jQuery.fn.msgbox = function(options) {
        var obj = $(this);
        var opts = $.extend({}, $.fn.msgbox.defaults, options || {});

        showBigStatus(opts, obj);

        function showBigStatus(opts, $obj) {
            $obj.addClass(opts.type);
            $obj.html(opts.msg);
            $obj.slideDown();
            setTimeout(function() { hideBigStatus($obj) }, opts.time);
        };

        function hideBigStatus($obj) {
            $obj.slideUp(function(){
                $obj.removeClass();
                $obj.html("");
            });                  
        };
    };

    $.fn.msgbox.defaults = {
        msg: "",
        time: 2000,
        type: "success"
    };
})(jQuery);