﻿//CONFIGURATION
var stackCMSEditImg = "<img class=\"cmsedit\" src=\"/App_PlugIns/StackCMS/IMG/Tool.png\">";
var postCMSURL = "/App_PlugIns/StackCMS/PostCMS.aspx";
var authenticationURL = "/CMS/AuthenticateCMS.aspx";
var loginRedirectURL = "/Secure/Logon.aspx?ReturnUrl=";
var mustAuthenticate = true;
var cmsFadeIDTag = "#page";  //this should be the div that wraps the content area.
var currentCMSBlock;
//END CONFIGURATION

//GLOBAL VARS
var areEditing = false;
//END GLOBAL VARS

$(document).ready(function() {

    //don't bother with cms if it's not in the url
    if (!(document.location.toString().indexOf("cms") > 0))
        return;
    //we'll ping the cms authentication page to be sure the
    //user is loggin for cms editing.
    if (mustAuthenticate) {
        checkForAuthentication();
    } else {
        enableCMS();
    }

});
function checkForAuthentication() {
    var temp;
    //if the user has cms access, enable it, otherwise redirect to login.

    var result = "";

    //ping the authentication to see if the user is able to work with the cms.
    result = $.ajax({
        url: authenticationURL,
        type: "GET",
        success: function(msg) {
            if (msg == "True") {
                enableCMS();
            }
            else {
                //if not autenticated, we'll redirect them here.
                window.location = loginRedirectURL + window.location.href;
            }

        },
        error: function(msg) {
            alert(msg);
        }
    });
}
function enableCMS() {

    //hook into cms content areas
    addCMSTags();
    //make sure page links have the ?cms query variable so that subsequent pages
    //are automatically wired up.
    wireCMSLinks();
    $(".cmsedit").click(function(event) {

        areEditing = true;

        //fadeout the background.        
        $(cmsFadeIDTag).fadeTo("slow", 0.33, showCMSEditor);

        //clear any content in the cms system.
        ResetCMS();

        //pass the document url to the form
        var theUrl = document.location.href;
        $("#stack-cms-url").val(theUrl);
        $("#stack-cms-id").val($(this).next().attr("id"));

        //trick to get the outerhtml
        //$('<div>').append( this.eq(0).clone() ).html();
        //this makes a clone of the html to copy it into the editcontent var.
        //this breaks in IE because it does not work for custom cmscontent tags
        //and forces tag names to uppercase.
        var editContent = $('<div>').append($(this).next().clone()).html();

        //currentCMSBlock = $(this).next().remove();
        //var editContent = currentCMSBlock.text();
        //alert(editContent);
        //alert($(this).next().contents());
        $("#content-test").text("'" + editContent + "'");
        //alert($(this).next().innerHTML);

        //update all of the cms areas with the editable cotntent
        updateTextContent(editContent);
        updateFrameContent(editContent);
        updateOriginalContent(editContent);

    });
    $("#stack-button-cancel").click(function() {
        updateFrameContent("");
        updateTextContent("");
        updateOriginalContent("");
        hideCMSEditor();
        areEditing = false;
    });
    $(window).scroll(function() {
        centerCMSEditor();
    });
    $(window).resize(function() {
        centerCMSEditor();
    });

}
//function GetExactHtml(objID)
//{
    //target_node = document.getElementById("dom_xhtml_text");
    //var page_XHTML = "";
    //page_XHTML = parseNode(target_node);
//}
function ResetCMS() {
    updateFrameContent("");
    updateTextContent("");
    updateOriginalContent("");
}
function wireCMSLinks() {
    var links = $("a");    
    for (i = 0; i < links.length; i++) {
        var link = links[i];
        var href = $(link).attr("href");
        if (href) {
            if (href.indexOf('?') > 0) {
                $(link).attr("href", href + "&cms=1");
            }
            else {
                $(link).attr("href", href + "?cms=1");
            }
        }
    }

}
function addCMSTags() {    
    $("CMSCONTENT,cmscontent").before(stackCMSEditImg);
    $(".cmscontent").before(stackCMSEditImg);
}
function showCMSEditor() {

    centerCMSEditor();
    $("#stack-cms-editor-container").css({
        "display": "block"
    });
}
function centerCMSEditor() {

    if (!areEditing) return;
    
    var windowWidth = document.documentElement.clientWidth;
    var windowHeight = document.documentElement.clientHeight;
    var popupHeight = $("#stack-cms-editor-container").height();
    var popupWidth = $("#stack-cms-editor-container").width();
    ///scrolltop of body does not work in ie and ff.
    var scrollTop = $(window).scrollTop();

    var adjustedTop = scrollTop + (popupHeight / 2);
    var adjustedLeft = (windowWidth / 2) - (popupWidth / 2);


    $("#stack-cms-editor-container").css({
        "position": "absolute",
        "top": adjustedTop,
        "left": adjustedLeft
    });
}
function hideCMSEditor() {
    $("#page").fadeTo("slow", 1.00);
    $("#stack-cms-editor-container").css("display", "none");
    updateFrameContent("");
    updateTextContent("");
    updateOriginalContent("");
}
function updateOriginalContent(content) {
    $("#stack-cms-original").val(content);
}
function updateFrameContent(content) {
    $("#stack-cms-editorWidgIframe").contents().find("body").html(content);
}
function updateTextContent(content) {
    $("#stack-cms-editor").val(content);
}
function submitCMS() {
    //submit in this function so the widgeditor has time
    //to do it's pre-submit actions.
    var f = $("#stack-cms-form");
    
    var serializedForm = f.serialize();

    var content = $("#stack-cms-editor").val();
    var originalContent = $("#stack-cms-original").val();

    var url = $("#stack-cms-url").val();

    //$("#test-output").html(serializedForm);
        
    try {
        var result = "";

        result = $.ajax({
            url: postCMSURL,
            type: "POST",
            data: serializedForm,
            success: function(msg) {
                if (msg.match("^error") == "error") {
                    alert(msg);
                }
                else {
                    hideCMSEditor();
                    areEditing = false;
                    $("#" + $("#stack-cms-id").val()).replaceWith(content);
                }
            },
            error: function(msg) {
                alert("failure" + msg);
            }
        });

    }
    catch (err) {
        alert(err.description);
    }
    return false;
}