﻿/// <reference path="lib/jquery.js" />

//OnPageLoad += "setDisabledClass();";

//alert("PublishDate (onload)" +PublishDate);

(function () {
    var obj = this;
    obj._closeButton = undefined;
    obj._buttons = undefined;
    obj._progressBox = undefined;
    obj._progressText = undefined;
    obj.Attach = function () {

        obj._closeButton = $('#closeW');
        obj._buttons = $('.content-toolBox a');
        obj._progressBox = $('#actionBox');
        obj._progressText = $('#actionMessage');

        if (DocumentID == 0)
            obj.setDisabledClass();
        if (parent.finish || parent.closeWindow)
            obj._closeButton.show();

        obj.AddClick();
        obj.hideProgress();
    };

    obj.setDisabledClass = function () {
        if (IsCheckedOut) {
            $('.g1').removeClass('disabled');
            $('.g2').addClass('disabled');

        }
        else {
            $('.g1').addClass('disabled');
            $('.g2').removeClass('disabled');
        }

        return true;
    }

    obj.progress = function (msg) {
        obj.showProgress(msg)
        setTimeout(obj.hideProgress, 2000);
    }

    obj.showProgress = function (msg) {
        try {
            obj._progressText.innerHTML = msg;
            obj._progressBox.show();
        }
        catch (e) { alert("showProgress() " + e.name + ": " + e.Message); }
    }

    obj.hideProgress = function () {
        try {
            obj._progressBox.hide();
        }
        catch (e) { alert("hideProgress() " + e.name + ": " + e.Message); }
    }

    obj.AddClick = function () {
        obj._buttons.click(function (event) {
            event.preventDefault();
            if (window.event)
                window.returnValue = false;
            if ($(this).hasClass('disabled'))
                return false;

            var action = $(this).attr('rel');
            try {
                switch (action) {
                    case "save":
                        if (obj.saveIt() == false)
                            return false;
                        break;
                    case "publish":
                        if (obj.publishIt() == false)
                            return false;
                        break;
                    case "end":
                        if (checkInDocument() == false)
                            return false;
                        break;
                    case "edit":
                        if (checkOutDocument() == false)
                            return false;
                        break;
                    case "preview":
                        obj.preview();
                        break;
                    case "close":
                        if (DocumentID > 0) {
                            AutoCheckInIfModified = true;
                            AutoCheckInIfNotModified = true;
                            AskForSaveIfNoChanges = false;
                        }else{
                            AskForSaveChanges = false;
                            AskForSaveIfNoChanges = false;
                            AskForCheckInIfNotModified = false;
                        }                      
                       
                        if (window.event)
                            window.event.returnValue = false;
                        obj.closeEditForm(); 
                        return false;
                        break;
                }
            }
            catch (e) {
                alert("buttons.click " + e.name + ": " + e.message);
            }

            try {
                if (parent.doButtonState) {
                    parent.doButtonState();
                }
                obj.setDisabledClass();
            }
            catch (e) {
                alert("[2]" + e.name + ": " + e.message);
            }
            return false;
        });
    }

    obj.saveIt = function () {
        try {
            AutoSaveIfNoChanges = true;
            obj.progress("Sparar...");

            if (saveCompleteDocument() == false)
                return false;
        }
        catch (e) { alert("saveIt() " + e.name + ": " + e.Message); }
        return true;
    }

    obj.publishIt = function () {
        try {
            obj.progress("Sparar och publicerar...");
            if (saveCompleteDocument(true) == false)
                return false;
            if (approveDocument(true) == false)
                return false;
        }
        catch (e) {
            alert("publishIt() " + e.name + ": " + e.Message);
        }
        return true;
    }
    function GetCurrentDate() {
        var Dateobj = new Date();
        var iYear = Dateobj.getFullYear();
   
        var iMonth = (Dateobj.getMonth() + 1);
        var iDay = Dateobj.getDate();
        var iHouer = Dateobj.getHours();
        var iMinute = Dateobj.getMinutes();
        var iSec = Dateobj.getSeconds();
        if (iMonth < 10)
            iMonth = "0" + iMonth.toString();
        if (iDay < 10)
            iDay = "0" + iDay.toString();
        if (iHouer < 10)
            iHouer = "0" + iHouer.toString();
        if (iMinute < 10)
            iMinute = "0" + iMinute.toString();
        if (iSec < 10)
            iSec = "0" + iSec.toString();
        return iYear + "-" + iMonth + "-" + iDay + " " + iHouer + ":" + iMinute + ":" + iSec;
    }

    obj.closeEditForm = function () {
        try {
            var temp = getQueryString("doreturn", "false");    
            var doReturn = false;
            if (temp == "true")
                doReturn = true;
            if (doReturn) {
               
                if (DocumentID == 0)
                {
                    doReturn = false;
                }
                else if (InternalRevision == 0  && DocumentID != 0)
                {
                    doReturn = false;
                }
                else if (PublishDate == '' && DocumentID != 0) {
                    doReturn = false;
                }
                else if (PublishDate != '') {
                    if (GetCurrentDate() < PublishDate)
                      { 
                         doReturn = false;
                      }
                }
            }

            if (parent.finish)
                parent.finish(DocumentID);

            if (parent.closeWindow){
           
                parent.closeWindow(DocumentID, doReturn, VirtualPath);
            }else
                alert("parent.closeWindow == null");        
        }
        catch (e) { alert("closeEditForm() " + e.name + ": " + e.Message); }
        return false;
    }

    obj.preview = function () {
        var docTitlestr = "Förhandsgrandska.";
        var params = {
            categoryId: CategoryID,
            documentId: DocumentID,
            content: previewXML(true),
            fileExtension: '.xml',
            documentTitle: docTitlestr,
            headerProperties: '',
            bodyProperties: '',
            EtXml: '',
            ASCode: ''
        };

        PreviewHandler.createPreviewFile(params);
    
    }

    obj.setReviewInfo = function () {
        try {

            var user = getCookie("CS_UserData", "FullName")
            var currentTime = new Date()
            var month = currentTime.getMonth() + 1;
            var day = currentTime.getDate();
            var year = currentTime.getFullYear();
            var hours = currentTime.getHours();
            var minutes = currentTime.getMinutes()
            var seconds = currentTime.getSeconds()
            if (month < 10) {
                month = "0" + month;
            }

            if (minutes < 10) {
                minutes = "0" + minutes;
            }
            if (seconds < 10) {
                seconds = "0" + seconds;
            }
            var now = year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;

            $('.CS_reviewedDate').val(now);
            $('.CS_reviewedBy').val(user);
            $('.CS_reviewedDateLbl').text(now);
            $('.CS_reviewedByLbl').text(user);
        } catch (e) {
            alert("setReviewInfo: " + e.name + ": " + e.message)
        }
    }
    $(document).ready(obj.Attach);
    attachToCSEvent("pageload", obj.setDisabledClass);
})();

var PreviewDialog = {
    box: null,
    body: null,
    close_button: null,
    revision_button: null,
    iframe: null,
    show_revision_toolbar: null,
    curent_scroll: 0,
    curent_version: 0,

    Init: function () {
        this.body = $('body');
        this.box = $('#preview-dialog');
        this.revision_toolbar = $('#preview-versions-bar');
        this.close_button = $('.close-button', this.box);


        this.show_revision_button = $('.show-revision-button', this.box);
        this.iframe = $('.preview-iframe', this.box);

        this.close_button.on('click', this.Close.bind(this));
        this.show_revision_button.on('click', this.OpenRevisionToolbar.bind(this));
    },
    Open: function (src) {
        this.curent_scroll = this.body.scrollTop();
        this.body.addClass('preview-mode');
        this.iframe.prop('src', src);
        this.box.addClass('open');
        $('.content-toolBox.buttons').addClass('disable');

    },
    Close: function () {
        this.iframe.prop('src', this.iframe.data('src'));
        this.box.removeClass('open');
        this.revision_toolbar.removeClass('open');
        this.body.removeClass('preview-mode').scrollTop(this.curent_scroll);
        $('.content-toolBox.buttons').removeClass('disable');

    },
    OpenRevisionToolbar: function () {
        this.revision_toolbar.toggleClass('open');

        if (this.revision_toolbar.hasClass('open'))
            RevisionHandler.GetAll();

    }
}


var PreviewHandler = {
    current_args: null,
    previewFile: {
        categoryId: 0, tempFilename: "", previewFilename: "", reset: function () {
            this.categoryId = 0;
            this.tempFilename = "";
            this.previewFilename = "";
        }
    },
    presentationTemplateCache:{},
    deletePreviewFile: function(async) {

        if (!this.previewFile.tempFilename) {
            return null;
        }

        //alert("this.previewFile.tempFilename: " + this.previewFile.tempFilename)
        //alert("this.previewFile.categoryId: " + this.previewFile.categoryId)

        return $.ajax({
            url: "cs/WebAPI/ContentStudio_Document_PreviewManager.ashx?Action=PreviewDispose",
            dataType: "json",
            async: async,
            data: { tempFileName: this.previewFile.tempFilename, categoryId: this.previewFile.categoryId },
            type: "GET"
        }).done(this.deletePreviewFileDone.bind(this)).fail(this.previewAjaxFail.bind(this));
    },
    deletePreviewFileDone: function(){
        this.previewFile.reset();
        //this.current_args = null;
    },
    LoadTemplateDone: function(templateList){
        for (var index in templateList) {
            var template = templateList[index];
            if (template.isDefault) {
                this.presentationTemplateCache[this.current_args.categoryId] = template;
                this.previewDone(template.id, this.previewFile.previewFilename);
                break;
            }
        }
    },
   
    createPreviewFileDone: function (jsonBlob)
    {
            this.previewFile.previewFilename = jsonBlob.previewFilename;
            this.previewFile.tempFilename = jsonBlob.tempFilename;
            this.previewFile.categoryId = this.current_args.categoryId;

            var template = this.presentationTemplateCache[this.current_args.categoryId];

            if (template) {
                this.previewDone(template.id, this.previewFile.previewFilename);
            } else {
                $.ajax({
                    url: "cs/WebAPI/ContentStudio_Document_EPT.ashx?Action=GetCurrentTemplates",
                    dataType: "json",
                    data: { categoryId: this.current_args.categoryId },
                    type: "GET"

                }).done(this.LoadTemplateDone.bind(this)).fail(this.previewAjaxFail.bind(this));
            }       
    },

    //  1. //cs/WebAPI/ContentStudio_Document_DocumentReader.ashx?action=getdetails&requestedVersionNumber=1&id=1069
    // 2 //cs/WebAPI/ContentStudio_Document_PreviewManager.ashx?Action=PreviewHandler
    createPreviewFile: function (args) {

        this.current_args = args;

        this.deletePreviewFile(false);

        return $.ajax({
            url: "cs/WebAPI/ContentStudio_Document_PreviewManager.ashx?Action=Preview",
            dataType: "json",
            data: JSON.stringify(this.current_args),
            contentType: "application/json; charset=utf8;",
            type: "POST"
        })
        .done(this.createPreviewFileDone.bind(this))
        .fail(this.previewAjaxFail.bind(this));

    },
    previewDone: function (presentationTemplateId, previewFilename) {
        var href = 'default.aspx?ptid=' + presentationTemplateId + '&CS_XMLFileName=' + previewFilename;
        PreviewDialog.Open(href);
    },

    previewAjaxFail: function (e) {
        // removeLoader();
        console.log('previewAjaxFail', e);
    }    
}

var RevisionHandler = {

    wrapper: null,
    current_version: 0,
    GetAll: function () {
        
        this.wrapper = $('#preview-versions-bar');
        this.wrapper.html('');

        var itemModel = {
            'ID': DocumentID
        }

        $.ajax({
            url: 'cs/WebAPI/ContentStudio_Document_VersionHistory.ashx?Action=getVersionHistory&docId=' + DocumentID,
            type: 'GET',
            dataType: "json",
            contentType: 'application/json'
        })
        .done(this.AddVersionsToList.bind(this))
        .fail(function (jqXHR, textStatus, errorThrown) {
            console.log("RevisionHandler.GetAll", textStatus)
            alert("error")
            alert("fail")
        }
       )
    },
    RestoreToCurrentVersion: function () {
        if (IsCheckedOut)
            this.RestoreVersion(this.current_version);
    },
    RestoreVersion: function(version){

        if (!confirm("Vill du återskapa version nummer: %? Nuvarande utkast kommer att skrivas över. ".replace(/\%/, version)))
            return false;

        PreviewHandler.deletePreviewFile(false);

        $.ajax({
            url: 'cs/WebAPI/ContentStudio_Document_VersionHistory.ashx',
            data: { action: "restoreVersion", revision: version, docId: DocumentID },
            type: 'GET',
            dataType: "json",
            contentType: 'application/json'
        })
          .done(this.RestoreVersionDone.bind(this))
          .fail(function (jqXHR, textStatus, errorThrown) {
              alert("RevisionHandler.GetRevision: " + textStatus);             
          });

        return true;
    },
    RestoreVersionDone: function(data){        
        console.log(data);
        if (IsCheckedOut) {
            AskForCheckInIfModified = false;
            AutoCheckInIfModified = false;

            AskForCheckInIfNotModified = false;
            AutoCheckInIfNotModified = false;
            AskForSaveChanges = false;
        }

        setTimeout(function () {
            window.location.href = window.location.href;
        }, 200);
        // 
    },
    GetRevision: function (version) {
        this.current_version = version;
        $.ajax({
            url: 'cs/WebAPI/ContentStudio_Document_DocumentReader.ashx',
            data: { action: "getdetails", requestedVersionNumber: version, id: DocumentID },
            type: 'GET',
            dataType: "json",
            contentType: 'application/json'
        })
        .done(this.GetRevisionDone.bind(this)).fail(function (jqXHR, textStatus, errorThrown) {
            console.log("RevisionHandler.GetRevision", textStatus)
            alert("error")
            alert("fail")
        });

        //cs/WebAPI/ContentStudio_Document_DocumentReader.ashx?action=getdetails&requestedVersionNumber=1&id=1069   
    },
    GetRevisionDone: function(data){

        //this.wrapper.removeClass('open');
        var docTitlestr = data.name;
        var params = {
            categoryId: CategoryID,
            documentId: DocumentID,
            content: data.content,
            fileExtension: '.xml',
            documentTitle: docTitlestr,
            headerProperties: '',
            bodyProperties: '',
            EtXml: '',
            ASCode: ''
        };

        PreviewHandler.createPreviewFile(params);
    },

    AddVersionsToList: function(data){
        try {
            if (data == null)
                return;            

             var ul = $('<ul/>', { 'class': 'version-list' });
            $.each(data, function (index, item) {
                if (item.version) {
                    var li = $('<li/>', { 'title': 'Skapad av ' + item.revisedby })
                    var preview_button = $('<a/>', { 'data-id': item.version, 'class': 'preview-button' }).on('click', function(){
                        RevisionHandler.GetRevision(item.version);
                        $(this).parent().siblings().removeClass('active');
                        $(this).parent().addClass('active');
                    })

                    var version = $('<span />', { 'class': 'version' }).text(item.version);
                    var date = $('<span />', { 'class': 'date' }).text(item.createddatedisplay);
                    preview_button.append(version).append(date);

                    var restore_button = $('<a/>', { 'data-id': item.version, 'class': 'retore-button', 'title': 'Återskapa version' }).on('click', function () {
                        RevisionHandler.RestoreVersion(item.version);
                    });

                    li.append(preview_button);
                    li.append(restore_button);
                    ul.append(li);
                }
            });

            //for (var id in data) {
            //    item = data[id];
            //    if (item.version) {
            //        var li = $('<li/>', { 'title': 'Skapad av ' + item.revisedby })
            //        var a = $('<a/>', { 'data-id': item.version });
            //        var version = $('<span />', { 'class': 'version' }).text(item.version);
            //        var date = $('<span />', { 'class': 'date' }).text(item.createddatedisplay);
            //        a.append(version).append(date);

            //        li.append(a);
            //        ul.append(li);
            //    }
            //}

           this.wrapper.append(ul);

        } catch (e) {
            console.log("RevisionHandler.AddVersionsToList", e)
            alert("fel");
        }
    }
}

$(document).ready(PreviewDialog.Init.bind(PreviewDialog));