﻿$(document).ready(function () {

    var rootUrl = '';
    var relative = '';

    var scripts = document.getElementsByTagName('link');
    $.each(scripts, function (index, element) {
        var idx = element.href.indexOf('athCms/css/athCmsCss.css', 0);
        if (idx != -1) {
            rootUrl = element.href.substring(0, idx);
            $('body').data('rootUrl', rootUrl);
            return false;
        };
    });

    function checkAdmin() {
        var retval = false;
        $.ajax({ type: "GET", url: rootUrl + 'athCms/ajax/AthCms.asmx/IsAdmin', async: false, dataType: "json", cache: false, contentType: "application/json; charset=utf-8;", data: '{}',
            success: function (data) {
                if (data !== null && data.d !== null && data.d == true) {
                    retval = true;
                }
            }
        });
        return retval;
    }

    var isAdmin = checkAdmin();

    if (isAdmin) {

        if (!jQuery().validate) {
            $.ajax({ type: "GET", url: rootUrl + 'athCms/js/jquery.validate.js', async: false, type: 'script' });
        };
        if (!jQuery().form) {
            $.ajax({ type: "GET", url: rootUrl + 'athCms/js/jquery.form.js', async: false, type: 'script' });
        };
        if (!jQuery().blockUI) {
            $.ajax({ type: "GET", url: rootUrl + 'athCms/js/jquery.blockUI.js', async: false, type: 'script' });
        };
        $.ajax({ type: "GET", url: rootUrl + 'athCms/js/athI18nButton.js', async: false, type: 'script' });

        setTimeout(function () {
            var cmsAreas = $(".athCmsArea");
            $.each(cmsAreas, function (index, area) {
                var id = $(this).attr('id');

                if ($(this).data('id') != null) {
                    $(this).data('id').refresh();
                }
                else {
                    var cms = new athCmsArea($(this));
                    cms.refresh();
                }
            });
            $(document).trigger('cmsLoadComplete');
        }, 50);

        function utilities() {
            var create = false;
            if (isAdmin) {
                $.ajax({ type: "GET", url: rootUrl + "athCms/ajax/AthCms.asmx/CanCreateElements", async: false, dataType: "json", contentType: "application/json; charset=utf-8", data: '{}',
                    success: function (data) {
                        if (data.d == true) {
                            create = true;
                        }
                    }
                });
                $.ajax({ url: rootUrl + "athCms/js/selectCmsType.js", async: false, dataType: "script", cache: true });
            }
            this.canCreateElements = function () {
                return create;
            }
        };

        var utils = new utilities();

        $('body').append('<div id="athHeadingEditor" style="display:none"><input type="text" id="athHeading" name="heading"/></div>');
        $('body').append('<div id="fileUploadDialog" style="display:none;"><form id="uploadFileForm" name="uploadFileForm" method="post" action="' + rootUrl + 'athCms/ajax/AthCms.asmx/UploadFile"><input type="hidden" id="cmsElementName" name="cmsElementName"/><input type="hidden" id="fileId" name="fileId"/><input type="hidden" id="cmsEntryId" name="cmsEntryId"/><input type="hidden" id="cmsSiteName" name="cmsSiteName"/><input type="hidden" id="cmsElementType" name="cmsElementType"/><table><tr><td class="formLabel"><label for="fileDescription">Description:</label></td><td><input type="text" id="fileDescription" name="fileDescription"/><br/></td></tr><tr><td class="formLabel"><label for="fileToUpload">File</label></td><td><input type="file" id="fileToUpload" name="fileToUpload"/><br/></td></tr></table></form></div>');
        $('body').append('<div id="busyIcon" style="position: absolute; z-index: 5000; top: 50%; left: 50%; background: url(' + rootUrl + 'athCms/images/ajax-loader.gif) no-repeat; width: 50px; height: 50px;display:none"></div>');
        $('body').append('<div id="createLink" style="display:none"><form id="createLinkForm"><table cellpadding="0" cellspacing="0" width="100%"><tr><td><strong>Url:</strong><br/><br/></td><td><input type="textArea" id="linkUrl" name="linkUrl"/><br/><br/></td></tr><tr><td><strong>Target:</strong><br/><br/></td><td><select id="linkTarget" name="linkTarget"><option value="0">Opens in same window</option><option value="1">Opens in new window</option></select><br/><br/></td></tr><tr><td><strong>Title:</strong></td><td><input type="text" id="linkTitle" name="linkTitle"/></td></tr></table></form></div>');

        $.ajax({ type: "GET", async: false, url: rootUrl + "athCms/html/athEditorDialog.html",
            success: function (data) {
                $('body').append(data);
            }
        });
        $.ajax({ type: "GET", async: false, url: rootUrl + "athCms/html/athImageUploadDialog.html",
            success: function (data) {
                $('#uploadImageForm').attr('action', rootUrl + 'athCms/ajax/upload_image.aspx');
                $('body').append(data);
            }
        });
        $.ajax({ type: "GET", async: false, url: rootUrl + "athCms/html/athUpdateImageDialog.html",
            success: function (data) {
                $('#imageEditForm').attr('action', rootUrl + 'athCms/ajax/AthCms.asmx/UpdateImage');
                $('body').append(data);
            }
        });
        $.ajax({ type: "GET", async: false, url: rootUrl + "athCms/html/athBannerEditor.html",
            success: function (data) {
                $('#editBannerForm').attr('action', rootUrl + 'athCms/ajax/AthCms.asmx/AddBannerImage');
                $('body').append(data);
            }
        });
        $.ajax({ type: "GET", async: false, url: rootUrl + "athCms/html/athManageImages.html",
            success: function (data) {
                $('body').append(data);
                //$('#uploadImageForm').attr('action', rootUrl + 'athCms/ajax/upload_image.aspx');
            }
        });

        if (!jQuery().tinymce) {
            $.ajax({ type: "GET", url: rootUrl + 'athCms/js/jquery.tinymce.js', async: false, type: 'script',
                success: function () {
                    $('#athEditor').tinymce({
                        script_url: rootUrl + 'athCms/js/tiny_mce.js',
                        theme: 'advanced',
                        plugins: 'table,paste',
                        dialog_type: 'modal',
                        theme_advanced_toolbar_location: 'top',
                        theme_advanced_buttons1: 'bold,italic,underline,bullist,link,unlink,hr,|,undo,redo',
                        theme_advanced_buttons2: '',
                        theme_advanced_buttons3: '',
                        theme_advanced_resizing: true,
                        paste_auto_cleanup_on_paste: true,
                        paste_remove_styles: true,
                        paste_remove_styles_if_webkit: true,
                        paste_strip_class_attributes: true,
                        table_inline_editing: true,
                        valid_elements: 'underline[class|style],strong/b,em/i,span[class|style],br,hr,a[href|target|title],-ul,-li',
                        valid_styles: { '*': 'text-decoration' },
                        inline_styles: true,
                        force_br_newlines: true,
                        forced_root_block: '',
                        width: 816,
                        height: 240,
                        setup: function (ed) {
                            ed.addCommand("mceLink", function (ui, v) {
                                var linkElm = ed.selection.getContent({ format: 'text' });
                                $('#createLinkForm').resetForm();
                                $('#createLink').dialog({
                                    title: "Create link",
                                    buttons: {
                                        "OK": function () {
                                            if ($('#createLinkForm').validate().form()) {
                                                var theUrl = $('#linkUrl').val();
                                                var theTitle = $('#linkTitle').val();
                                                ed.execCommand("createlink", false, theUrl);
                                                var body = $(ed.getBody());
                                                var a = body.find('a');
                                                var link = $(ed.getBody()).find('a[href="' + theUrl + '"]');
                                                link.attr('title', theTitle);
                                                if ($('#linkTarget').val() == 1) {
                                                    link.attr('target', '_blank');
                                                }
                                                $('#createLink').dialog('close');
                                            }
                                        },
                                        "Cancel": function () {
                                            $('#createLink').dialog('close');
                                        }
                                    }
                                });
                                $('#createLink').dialog('open');
                                return false;
                            });
                        }
                    });
                }
            });
        };

        $('#athEditorDialog').dialog({
            autoOpen: false,
            modal: true,
            width: 850,
            height: 610
        });

        $('#athHeadingEditor').dialog({
            autoOpen: false,
            modal: true,
            width: 400,
            height: 170
        });

        $('#athImageUploadDialog').dialog({
            autoOpen: false,
            modal: true
        });

        $('#imageEditDialog').dialog({
            autoOpen: false,
            modal: true
        });

        $('#createLink').dialog({
            autoOpen: false,
            modal: true
        });

        $('#athCmsManageImagesDialog').dialog({
            autoOpen: false,
            modal: true
        });

        $('#uploadImageForm').attr('action', rootUrl + 'athCms/ajax/upload_image.aspx');
        $('#imageEditForm').attr('action', rootUrl + 'athCms/ajax/AthCms.asmx/UpdateImage');
        $('#athDeleteImage').attr('src', rootUrl + 'athCms/images/delete.png');
        $('#athDeleteFile').attr('src', rootUrl + 'athCms/images/delete.png');

        $('#imageUploadDialog').dialog({
            autoOpen: false,
            modal: true
        });

        $('#fileUploadDialog').dialog({
            autoOpen: false,
            modal: true
        });

        $('#bannerEditor').dialog({
            autoOpen: false,
            modal: true
        });

        $('#createLinkForm').validate({
            rules: {
                linkUrl: { required: true },
                linkTitle: { required: true }
            },
            messages: {
                linkUrl: "<br/>This field is required.",
                linkTitle: "<br/>This field is required."
            }
        });

        $('#editBannerForm').validate({
            rules: {
                bannerLinkUrl: { required: true },
                bannerImageUrl: { required: true }
            },
            messages: {
                bannerLinkUrl: "<br/>This field is required.",
                bannerImageUrl: "<br/>This field is required"
            }
        });

        $('#imageEditForm').validate({
            rules: {
                updateImageToUpload: {
                    accept: "jpg|jpeg|png|gif"
                }
            },
            errorPlacement: function (error, element) {
                error.appendTo(element.parent("td"));
            }
        });

        $('#uploadImageForm').validate({
            rules: {
                imageDescription: {
                    required: true
                },
                imageToUpload: {
                    required: true,
                    accept: "jpg|jpeg|png|gif"
                }
            },
            errorPlacement: function (error, element) {
                error.appendTo(element.parent("td"));
            }
        });

        $('#uploadFileForm').validate({
            rules: {
                fileDescription: {
                    required: true
                },
                fileToUpload: {
                    required: true,
                    accept: "doc|xls|pdf|zip"
                }
            },
            errorPlacement: function (error, element) {
                error.appendTo(element.parent("td"));
            }
        });

        $('#athCmsDisplayDate, #athCmsDateFrom, #athCmsDateTo').datepicker({
            showOn: 'both',
            dateFormat: 'dd/mm/yy',
            changeMonth: true,
            changeYear: true,
            buttonImage: rootUrl + "athCms/images/calendar.png"
        });

        function refreshCmsArea(name) {
            var areas = $('#' + name + '.athCmsArea'); // get all the cms areas with the specified name, there could be more than one
            if (areas.length > 0) {
                $.each(areas, function (index, area) {
                    $(area).data(name).refresh();
                });
                $(document).trigger('cmsLoadComplete');
            };
        };

        function resetAllForms() {
            $('#uploadImageForm').resetForm();
            $('#uploadFileForm').resetForm();
            $('#athHeading').val('');
        };

        $('#athCmsDeleteImage').click(function (ev) {
            ev.preventDefault();
            var imageId = 0;
            var entryId = 0;
            var data = $('#athEditorDialog').data('cms');
            entryId = $('#athEditorDialog').data('entryId');
            var entry = data.entryById(entryId);
            if (entry != undefined) {
                if (entry.images().length > 0) {
                    imageId = entry.images()[0].id();
                }
                $.ajax({ type: "POST", url: rootUrl + 'athCms/ajax/AthCms.asmx/DeleteImage', data: { operation: "delete", imageId: imageId },
                    success: function () {
                        refreshCmsArea(data.name());
                    }
                });
            }
        });

        // open manage images dialog
        $('#athCmsManageImages').click(function (e) {
            e.preventDefault();
            var entryId = 0;
            var data = $('#athEditorDialog').data('cms');
            $.each(data, function (index, element) {
            });
            $('#athCmsManageImagesDialog').dialog({
                title: 'Manage Images',
                buttons: {
                    "Add": function () {
                    },
                    "Done": function () {
                        $('#athCmsManageImagesDialog').dialog('close');
                    }
                }
            });
            $('#athCmsManageImagesDialog').dialog('open');
        });

        $('#athCmsDeleteFile').click(function (ev) {
            ev.preventDefault();
            var fileId = 0;
            var entryId = 0;
            var data = $('#athEditorDialog').data('cms');
            entryId = $('#athEditorDialog').data('entryId');
            var entry = data.entryById(entryId);
            if (entry != undefined) {
                if (entry.files().length > 0) {
                    fileId = entry.files()[0].id();
                }
                $.ajax({ type: "POST", url: rootUrl + "athCms/ajax/AthCms.asmx/DeleteFile", dataType: "json", contentType: "application/json; charset=utf-8", data: '{"fileId":"' + fileId + '","cmsEntryId":"' + entryId + '"}',
                    success: function () {
                        refreshCmsArea(data.name());
                    }
                });
            }
        });

        $('.athCmsAddButton, .athCmsEditButton, .athCmsAddImageButton').live('click', function (ev) {
            ev.preventDefault();
            $('#athCmsDisplayDate').val('');
            $('#athCmsDateFrom').val('');
            $('#athCmsDateTo').val('');
            if (!checkAdmin()) {
                alert('Your session has been inactive for too long and has expired.');
                window.location.reload();
            }
            else {
                var entryId = $(this).attr('id');
                var area = $(this).parents('.athCmsArea');
                var id = area.attr('id');
                var data = area.data(id);
                var type = data.type();
                if (type == '' || type == undefined && area.find('cmsType') != undefined) {
                    type = area.find('cmsType').val();
                }
                resetAllForms();
                $('#cmsElementName').val(id);
                $('#cmsSiteName').val(data.site());
                $('#cmsEntryId').val(entryId);
                $('#cmsElementType').val(data.type());
                $('#athEditorDialog').data('cms', data);
                $('#athEditorDialog').data('entryId', entryId);
                if (type == 'text' || type == 'blog') {
                    doHtmlEdit(data, entryId);
                }
                else if (type == 'image') {
                    doImageEdit(data, entryId);
                }
                else if (type == 'header') {
                    doPlainEdit(data, entryId);
                }
                else if (type == 'gallery') {
                    doImageEdit(data, entryId);
                }
                else if (type == 'banner') {
                    doBannerEdit(data, entryId);
                }
                else if (type == 'page') {
                    doPageEdit(data, entryId);
                }
            }
        });

        $('#athCmsUploadImage').click(function (ev) {
            ev.preventDefault();
            $('#imageUploadDialog').dialog({
                title: 'Choose Image',
                buttons: {
                    "OK": function () {
                        if ($('#uploadImageForm').validate().form()) {
                            $(this).dialog('close');
                        }
                    },
                    "Cancel": function () {
                        $(this).dialog('close');
                    }
                }
            });
            $('#uploadImageForm').resetForm();
            $('#imageUploadDialog').dialog('open');
        });

        $('#athCmsUploadFile').click(function (ev) {
            ev.preventDefault();
            $('#fileUploadDialog').dialog({
                title: 'Choose File',
                buttons: {
                    "OK": function () {
                        if ($('#uploadFileForm').validate().form()) {
                            $(this).dialog('close');
                        }
                    },
                    "Cancel": function () {
                        $(this).dialog('close');
                    }
                }
            });
            $('#uploadFileForm').resetForm();
            $('#fileUploadDialog').dialog('open');
        });

        function doImageEdit(cms, entryId) {
            $('#imageUploadDialog').dialog({
                title: 'Upload Image',
                buttons: {
                    "OK": function () {
                        if (!checkAdmin()) {
                            alert('Your session has been inactive for too long and has expired, content has not been uploaded.');
                        }
                        else {
                            if ($('#uploadImageForm').validate().form()) {
                                $('#uploadImageForm').ajaxSubmit({ async: false,
                                    success: function () {
                                        refreshCmsArea(cms.name());
                                    }
                                });
                                $(this).dialog('close');
                            }
                        }
                    },
                    "Cancel": function () {
                        $(this).dialog('close');
                    }
                }
            });
            $('#uploadImageForm').resetForm();
            $('#imageUploadDialog').dialog('open');
        }

        function doHtmlEdit(cms, entryId) {
            var retval = false;
            var editor = tinymce.getInstanceById('athEditor');
            tinymce.execCommand('mceFocus', false, 'athEditor');
            if (entryId > 0) {
                var entry = cms.entryById(entryId);
                editor.setContent(entry.content());
                $('#athCmsTitle').val(entry.title());
                $('#athCmsDisplayDate').val(entry.displayDate());
                $('#athCmsDateFrom').val(entry.dateFrom());
                $('#athCmsDateTo').val(entry.dateTo());
                $('#uploadImageForm').find('#cmsEntryId').val(entry.id());
                $('#uploadFileForm').find('#cmsEntryId').val(entry.id());
            }
            else {
                $('#athCmsTitle').val('');
                editor.setContent('');
                $('#athCmsDisplayDate').val('');
            }
            if (cms.type() == 'blog') {
                tinymce.activeEditor.theme.resizeTo(816, 240);
                $('#fileUpload').show();
                $('#athTitle').show();
            }
            else {
                tinymce.activeEditor.theme.resizeTo(816, 430);
                $('#fileUpload').hide();
                $('#athTitle').hide();
            }
            $('#athEditorDialog').dialog({
                title: 'Edit Content<img src="' + rootUrl + 'athCms/images/ath_logo.png" alt="ATH Breeze" class="athCmsLogo" align="right" />',
                buttons: {
                    "OK": function () {
                        if (!checkAdmin()) {
                            alert('Your session has been inactive for too long and has expired, content has not been uploaded');
                        }
                        else {
                            $('.ui-dialog').block({ message: null });
                            $('#busyIcon').show();
                            var newContent = '';
                            try {
                                newContent = editor.getContent();
                                newContent = newContent.replace(/&lt;!--(.*?)--&gt;/g, '');
                                newContent = escape(newContent);
                            }
                            catch (e) {
                            }
                            $.ajax({ type: "POST", async: false, url: $('body').data('rootUrl') + 'athCms/ajax/AthCms.asmx/UpdateCmsEntry', data: { cmsElementName: cms.name(), cmsEntryId: entryId, cmsContent: newContent, cmsSiteName: cms.site(), cmsElementType: cms.type(), cmsDateDisplay: $('#athCmsDisplayDate').val(), cmsDateFrom: $('#athCmsDateFrom').val(), cmsDateTo: $('#athCmsDateTo').val(), athCmsTitle: $('#athCmsTitle').val() },
                                success: function (data) {
                                    refreshCmsArea(cms.name());
                                }
                            });
                            if (cms.type() == "blog") {
                                if (entryId == cms.name()) { // indicates we clicked on add a new entry rather than an edit button
                                    var data = $('#athEditorDialog').data('cms');
                                    var entry = data.lastEntry();
                                    if (entry != undefined) {
                                        $('#uploadImageForm').find('#cmsEntryId').val(entry.id());
                                        $('#uploadFileForm').find('#cmsEntryId').val(entry.id());
                                    }
                                }
                                // uploaded entry so we can be sure it exists, now upload files
                                var imageName = $('#imageToUpload').val();
                                var fName = $('#fileToUpload').val();
                                if (imageName != undefined && imageName != '') {
                                    $('#uploadImageForm').ajaxSubmit({ async: false,
                                        success: function () {
                                            refreshCmsArea(cms.name());
                                        }
                                    });
                                };
                                if (fName != undefined && fName != '') {
                                    $('#uploadFileForm').ajaxSubmit({ async: false,
                                        success: function () {
                                            refreshCmsArea(cms.name());
                                        }
                                    });
                                }
                            };
                            $('#busyIcon').hide();
                            $('.ui-dialog').unblock();
                            $(this).dialog('close');
                            retval = true;
                        }
                    },
                    "Cancel": function () {
                        $(this).dialog('close');
                    },
                    "Delete": function () {
                        var data = $('#athEditorDialog').data('cms');
                        entryId = $('#athEditorDialog').data('entryId');
                        if (confirm('Delete this entry?')) {
                            if (entryId > 0) {
                                $.ajax({ type: "POST", url: rootUrl + "athCms/ajax/AthCms.asmx/DeleteEntry", dataType: "json", contentType: "application/json; charset=utf-8",
                                    data: '{"entryId":"' + entryId + '"}',
                                    success: function () {
                                        $('#athEditorDialog').dialog('close');
                                        refreshCmsArea(data.name());
                                    }
                                });
                            }
                        }
                        $(this).dialog('close');
                    }
                }
            });
            $('#athEditorDialog').dialog('open');
            tinymce.execCommand('mceFocus', false, 'athEditor');
        };

        function doPlainEdit(cms, entryId) {
            if (typeof (cms.entries()) != undefined && cms.entries().length > 0) {
                $('#athHeading').val(cms.entries()[0].content);
            }
            $('#athHeadingEditor').dialog({
                title: 'Edit Heading<img src="' + rootUrl + 'athCms/images/ath_logo.png" alt="ATH Breeze" class="athCmsLogo" align="right"/>',
                buttons: {
                    "OK": function () {
                        var theText = escape($('#athHeading').val());
                        $.ajax({ type: "POST", url: rootUrl + "athCms/ajax/AthCms.asmx/UpdateCmsEntry", async: false, data: { cmsElementName: cms.name(), cmsSiteName: cms.site(), cmsElementType: cms.type(), cmsEntryId: entryId, cmsContent: theText },
                            success: function () {
                                refreshCmsArea(cms.name());
                            }
                        });
                        $('#athHeadingEditor').dialog('close');
                    },
                    "Cancel": function () {
                        $('#athHeadingEditor').dialog('close');
                    }
                }
            });
            $('#athHeadingEditor').dialog('open');
        };

        function doBannerEdit(cms, entryId) {
            $('#editBannerForm').resetForm();
            if (typeof (cms.entries()) != undefined && cms.entries().length > 0) {
                $('#bannerLinkUrl').val(cms.entries()[0].link());
                $('#bannerTitle').val(cms.entries()[0].title());
                $('#bannerTarget').val(cms.entries()[0].content());
            }
            $('#bannerEditor').dialog({
                title: 'Edit Banner<img src="' + rootUrl + 'athCms/images/ath_logo.png" alt="ATH Breeze" class="athCmsLogo" align="right"/>',
                buttons: {
                    "OK": function () {
                        if ($('#editBannerForm').validate().form()) {
                            $('#editBannerForm').ajaxSubmit({ async: false, url: rootUrl + 'athCms/ajax/AthCms.asmx/AddBannerImage', dataType: "json", data: { elementName: cms.name(), siteName: cms.site() },
                                success: function () {
                                    refreshCmsArea(cms.name());
                                }
                            });
                            $('#bannerEditor').dialog('close');
                        }
                    },
                    "Cancel": function () {
                        $(this).dialog('close');
                    }
                }
            });
            $('#bannerEditor').dialog('open');
        };

    };

    function getCmsElement(elementName, cmsSite) {
        var retval = null;
        $.ajax({ type: "POST", url: rootUrl + 'athCms/ajax/AthCms.asmx/GetCmsElement', async: false, dataType: "json", contentType: "application/json; charset=utf-8",
            data: '{"elementName": "' + elementName + '", "siteName": "' + cmsSite + '"}',
            success: function (data) {
                if (data != null && data.d != null) {
                    retval = data.d;
                }
            }
        });
        return retval;
    };


    function athCmsArea(cms) {

        var getProperty = function (name) {
            var retval = '';
            var element = cms.find(name);
            if (element.length > 0) {
                retval = element.val();
            }
            return retval;
        };

        var self = this;
        var cmsArea = cms;
        var cmsName = cms.attr('id');
        var cmsSite = getProperty('#siteName');
        var cmsType = '';
        var cmsLimitChars = getProperty('#limitCharacters');
        var cmsLimitArticles = getProperty('#limitArticles');
        var cmsReadMoreLink = getProperty('#readMoreLink');
        var cmsReadMoreText = getProperty("#readMoreText");
        var cmsDisplay = getProperty('#display');
        var cmsEntries = new Array();

        this.refresh = function () {
            cmsEntries = new Array();
            cmsArea.empty();
            cmsArea.append('<img id="athWaitingImage" src="' + rootUrl + 'athCms/images/ajax-loader.gif"/>');
            var element = getCmsElement(cmsName, cmsSite);
            if (element == null && isAdmin && utils.canCreateElements()) {
                var button = $('<a href="#" id="' + cmsName + '" class="athCmsAddArea">Set cms type</a>');
                button.bind('click', function (e) {
                    e.preventDefault();
                    var t = new cmsTypeSet();
                    t.setCmsType(self);
                });
                cmsArea.append(button);
            }
            if (element != null) {
                cmsType = element.Type.Name; // override anything set in the div
                if (typeof (element.Entries) != undefined && element.Entries.length > 0) {
                    $.each(element.Entries, function (index, entry) {
                        cmsEntries.push(new cmsEntry(entry, self));
                    });
                };
                cmsArea.empty();
                $.each(cmsEntries, function (index, element) {
                    if (cmsLimitArticles != '' && cmsLimitArticles <= index) {
                        return false;
                    }
                    cmsArea.append('<a name="' + element.id() + '"></a>');
                    cmsArea.append(element.html());
                });
                if (isAdmin) {
                    var button;
                    if (cmsType == 'blog') {
                        button = $('<a href="#" id="' + cmsName + '" class="athCmsAddButton">+ Add</a>');
                        //button.bind('click', function (e) {
                        //self.addBlogEntry();
                        //});
                    }
                    else if (cmsType == 'gallery') {
                        if (cmsLimitArticles == '') {
                            cmsArea.append('<br />');
                            var button = $('<div class="athCmsAddGalleryBox"></div>');
                            var href = $('<a href="#" id="' + cmsName + '" class="athCmsAddGalleryButton"><img src="' + rootUrl + 'athCms/images/photo.png" alt="Add photo" width="14" height="16" align="absmiddle" /> Add photo</a>');
                            href.bind('click', function (e) {
                                e.preventDefault();
                                self.addGalleryImage(e);
                            });
                            button.append(href);
                        }
                        else {
                            var div = $('<div class="athCmsReadMoreBox"></div>');
                            if (cmsReadMoreLink !== '') {
                                if (cmsReadMoreText !== '') {
                                    div.append('<a href="' + rootUrl + decodeURIComponent(cmsReadMoreLink.replace(/\+/g, ' ')) + '" class="athCmsReadMoreLink">' + decodeURIComponent(cmsReadMoreText.replace(/\+/g, ' ')) + '</a>');
                                }
                                else {
                                    div.append('<a href="' + rootUrl + decodeURIComponent(cmsReadMoreLink.replace(/\+/g, ' ')) + '" class="athCmsReadMoreLink">Read More &gt;&gt;</a>');
                                }
                            }
                            cmsArea.append(div);
                        }
                    }
                    else if (cmsType == 'image') {
                        cmsArea.append('<br />');
                        if (cmsEntries.length == 0) {
                            button = $('<a href="#" id="' + cmsName + '" class="athCmsAddImageButton"><img src="' + rootUrl + 'athCms/images/photo.png" alt="Add photo" width="14" height="16" align="absmiddle" /> Add photo</a>');
                        }
                        //button.bind('click', function (e) {
                        //});
                    }
                    else if (cmsEntries.length == 0) {
                        button = $('<a href="#" id="0" class="athCmsAddButton">+ Add</a>');
                        //button.bind('click', function (e) {
                        //});
                    }
                    cmsArea.prepend(button);
                }
            }
            if (cmsSite != '') {
                cmsArea.append('<input type="hidden" id="siteName" value="' + cmsSite + '"/>');
            };
            if (cmsLimitChars != '') {
                cmsArea.append('<input type="hidden" id="limitCharacters" value="' + cmsLimitChars + '"/>');
            }
            if (cmsLimitArticles != '') {
                cmsArea.append('<input type="hidden" id="limitArticles" value="' + cmsLimitArticles + '"/>');
            }
            if (cmsReadMoreLink != '') {
                cmsArea.append('<input type="hidden" id="readMoreLink" value="' + cmsReadMoreLink + '"/>');
            }
            if (cmsReadMoreText !== '') {
                cmsArea.append('<input type="hidden" id="readMoreText" value="' + cmsReadMoreText + '"/>');
            }
            cmsArea.trigger('loadComplete');
            $('#athWaitingImage').remove();
        }

        this.name = function () {
            return cmsName;
        };

        this.type = function () {
            return cmsType;
        };

        this.entries = function () {
            return cmsEntries;
        };

        this.site = function () {
            return cmsSite;
        }

        this.limitCharacters = function () {
            return cmsLimitChars;
        };

        this.limitArticles = function () {
            return cmsLimitArticles;
        }

        this.readMoreLink = function () {
            return cmsReadMoreLink;
        };

        this.readMoreText = function () {
            return cmsReadMoreText;
        };

        this.addBlogEntry = function () {
            $.ajax({ type: "POST", async: false, url: rootUrl + 'athCms/ajax/AthCms.asmx/AddBlogEntry', data: '{"elementName": "' + cmsName + '", siteName: "' + cmsSite + '", "dateFrom": ""}',
                success: function (data) {
                    self.refresh();
                }
            });
        };

        this.addGalleryImage = function () {
            $('#imageUploadDialog').dialog({
                title: 'Upload Image',
                buttons: {
                    "OK": function () {
                        if ($('#uploadImageForm').validate().form()) {
                            var imageDescription = $('#imageDescription').val();
                            $('#imageDescription').val('');
                            $('#uploadImageForm').ajaxSubmit({ async: false, url: rootUrl + 'athCms/ajax/AthCms.asmx/AddGalleryImage', dataType: "json", contentType: "application/json; charset=utf-8", data: { elementName: cmsName, siteName: cmsSite },
                                success: function (data) {
                                    if (data != null) {
                                        var imageId = $.parseJSON(data).imageId;
                                        $.ajax({ type: "POST", async: false, url: rootUrl + 'athCms/ajax/AthCms.asmx/UpdateImageDescription', dataType: 'json', contentType: "application/json; charset=utf-8", data: '{"imageId":"' + imageId + '", "description": "' + imageDescription + '"}',
                                            success: function () {
                                                self.refresh();
                                            }
                                        });
                                    }
                                },
                                error: function (jqXHR, textStatus, errorThrown) {
                                    alert(textStatus);
                                }
                            });
                            $('#imageUploadDialog').dialog('close');
                        }
                    },
                    "Cancel": function () {
                        $('#imageUploadDialog').dialog('close');
                    }
                }
            });
            $('#uploadImageForm').resetForm();
            $('#imageUploadDialog').dialog('open');
        };

        this.entryById = function (id) {
            var retval = null;
            $.each(cmsEntries, function (index, element) {
                if (element.id() == id) {
                    retval = element;
                    return false;
                }
            });
            return retval;
        };

        this.firstEntry = function () {
            var retval = undefined;
            if (cmsEntries.length > 0) {
                retval = cmsEntries[0];
            }
            return retval;
        };

        this.lastEntry = function () {
            var retval = undefined;
            if (cmsEntries.length > 0) {
                retval = cmsEntries[cmsEntries.length - 1];
            };
            return retval;
        };

        $(cmsArea).data(cmsName, self);
    };

    function cmsEntry(entry, parent) {

        var self = this;
        var entryId = entry.Id;
        var entryContent = unescape(entry.Content).replace(/&lt;!--(.*?)--&gt;/g, '');
        var dateDisplay = entry.DateDisplay;
        var entryTitle = entry.Title;
        var dateFrom = entry.DateFrom;
        var dateTo = entry.DateTo;
        var linkUrl = entry.Link;
        var language = '';
        var entryImages = new Array();
        var entryFiles = new Array();

        if (entry.Language != null && entry.Language != undefined) {
            language = entry.Language.Code;
        };

        if (typeof (entry.Images) != undefined && entry.Images.length > 0) {
            $.each(entry.Images, function (index, element) {
                entryImages.push(new cmsImage(element));
            });
        };

        if (typeof (entry.Files) != undefined && entry.Files.length > 0) {
            $.each(entry.Files, function (index, element) {
                entryFiles.push(new cmsFile(element));
            });
        };

        this.id = function () {
            return entryId;
        };

        this.displayDate = function () {
            return dateDisplay;
        };

        this.title = function () {
            return entryTitle;
        };

        this.dateFrom = function () {
            return dateFrom;
        };

        this.dateTo = function () {
            return dateTo;
        };

        this.content = function () {
            return entryContent;
        }

        this.images = function () {
            return entryImages;
        };

        this.files = function () {
            return entryFiles;
        };

        this.link = function () {
            return linkUrl;
        };

        this.languageCode = function () {
            return language;
        };

        this.moveUp = function (e) {
            e.preventDefault();
            $.ajax({ type: "POST", url: rootUrl + "athCms/ajax/AthCms.asmx/DecreaseEntryWeight", dataType: "json", contentType: "application/json; charset=utf-8", data: '{"entryId":"' + entryId + '"}',
                success: function (data) {
                    parent.refresh();
                }
            });
        };

        this.moveDown = function (e) {
            e.preventDefault();
            $.ajax({ type: "POST", url: rootUrl + "athCms/ajax/AthCms.asmx/IncreaseEntryWeight", dataType: "json", contentType: "application/json; charset=utf-8", data: '{"entryId":"' + entryId + '"}',
                success: function (data) {
                    parent.refresh();
                }
            });
        };

        this.deleteGalleryImage = function (imageId) {
            if (confirm('Delete this image?')) {
                $.ajax({ type: "POST", url: rootUrl + "athCms/ajax/AthCms.asmx/DeleteImage", dataType: "json", contentType: "application/json; charset=utf-8", data: '{"imageId": "' + imageId + '"}',
                    success: function (data) {
                        parent.refresh();
                    }
                });
            }
        };

        this.moveImageUp = function (imageId) {
            $.ajax({ type: "POST", url: rootUrl + "athCms/ajax/AthCms.asmx/DecreaseImageWeight", dataType: "json", contentType: "application/json; charset=utf-8", data: '{"imageId": "' + imageId + '"}',
                success: function (data) {
                    parent.refresh();
                }
            });
        };

        this.moveImageDown = function (imageId) {
            $.ajax({ type: "POST", url: rootUrl + "athCms/ajax/AthCms.asmx/IncreaseImageWeight", dataType: "json", contentType: "application/json; charset=utf-8", data: '{"imageId": "' + imageId + '"}',
                success: function (data) {
                    parent.refresh();
                }
            });
        };

        this.editImage = function (imageId, imageName) {
            $('#updateImageDescription').val(imageName);
            $('#updateImageId').val(imageId);
            $('#imageEditDialog').dialog({
                title: 'Edit Image',
                buttons: {
                    "OK": function () {
                        if ($('#imageEditForm').validate().form()) {
                            //newContent = newContent.replace(/&lt;!--(.*?)--&gt;/g, '');
                            //newContent = escape(newContent);
                            var imageDescription = encodeURIComponent($('#updateImageDescription').val());
                            $.ajax({ type: "POST", async: false, url: rootUrl + "athCms/ajax/AthCms.asmx/UpdateImageDescription", dataType: "json", contentType: "application/json; charset=utf-8", data: '{"imageId": "' + imageId + '", "description":"' + $('#updateImageDescription').val() + '"}',
                                success: function () {
                                    $('#updateImageDescription').val('');
                                    $('#imageEditForm').ajaxSubmit({ async: false, dataType: "json", contentType: "application/json; charset=utf-8", data: { updateImageDescription: imageDescription },
                                        success: function () {
                                            parent.refresh();
                                        }
                                    });
                                }
                            });
                            $('#imageEditDialog').dialog('close');
                        }
                    },
                    "Cancel": function () {
                        $(this).dialog('close');
                    }
                }
            });
            $('#imageEditDialog').dialog('open');
        };

        this.html = function () {
            var div = $('<div id="' + self.id() + '" class="athCmsSubArea"></div>');
            if (parent.type() == 'gallery') {
                if (entryImages != null && entryImages.length > 0) {
                    var articleLimit = parent.limitArticles();
                    $.each(entryImages, function (index, image) {
                        if (articleLimit != '' && articleLimit <= index) {
                            return false;
                        }
                        var subDiv = $('<div id="' + image.id() + '" class="athCmsGalleryBox"></div>');
                        var html = '<div class="athCmsImageBox"><a href="' + rootUrl + image.url() + '" class="athCmsImageLink" title="' + image.name() + '"><img id="' + image.id() + '" src="' + rootUrl + image.url() + '" alt="' + image.name() + '" class="athCmsGalleryImage"/></a></div><span class="athCmsImageGalleryCaption">' + image.name() + '</span>';
                        if (articleLimit != '') {
                            subDiv = $('<div id="' + image.id() + '" class="athCmsSmallGalleryBox"></div>');
                            html = '<div class="athCmsImageBox"><a href="' + rootUrl + image.url() + '" class="athCmsImageLink" title="' + image.name() + '"><img id="' + image.id() + '" src="' + rootUrl + image.url() + '" alt="' + image.name() + '" class="athCmsGalleryImage"/></a></div><span class="athCmsImageSmallGalleryCaption">' + image.name() + '</span>';
                        }
                        if (isAdmin && articleLimit == '') {
                            var del = $('<a href="#" id="athDeleteGalleryImage" class="athCmsDeleteGalleryImage"><img src="' + rootUrl + 'athCms/images/delete.png" id="athDeleteImage" alt="Delete image" width="14" height="19" align="absmiddle" /></a>');
                            del.bind('click', function (e) {
                                e.preventDefault();
                                self.deleteGalleryImage(image.id());
                            });
                            subDiv.append(del);
                            var up = $('<a href="#" id="athGalleryImageUp" class="athIncreaseEntryWeight"><img src="' + rootUrl + 'athCms/images/increase.png" alt="Increase weighting" width="11" height="16" align="absmiddle" /></a>');
                            var down = $('<a href="#" id="athGalleryImageDown" class="athDecreaseEntryWeight"><img src="' + rootUrl + 'athCms/images/decrease.png" alt="Decrease weighting" width="11" height="16" align="absmiddle" /></a>');
                            var edit = $('<a href="#" id="' + self.id() + '" class="athCmsEditImageButton"><img src="' + rootUrl + 'athCms/images/edit.png" alt="Edit" width="16" height="16" align="absmiddle" /></a>');
                            up.bind('click', function (e) {
                                e.preventDefault();
                                self.moveImageUp(image.id());
                            });
                            down.bind('click', function (e) {
                                e.preventDefault();
                                self.moveImageDown(image.id());
                            });
                            edit.bind('click', function (e) {
                                e.preventDefault();
                                self.editImage(image.id(), image.name());
                            });
                            subDiv.append(up);
                            subDiv.append(down);
                            subDiv.append(edit);
                        }
                        subDiv.append(html);
                        div.append(subDiv);
                    });
                }
            }
            else if (parent.type() == 'banner') {
                if (entryImages != undefined && entryImages.length > 0) {
                    div.append('<a href="' + linkUrl + '" target="' + entryContent + '" title="' + entryTitle + '"><div class="athCmsBannerBox"><img class="athCmsBannerImage" src="' + rootUrl + entryImages[0].url() + '"/></div></a>');
                    if (isAdmin) {
                        div.append('<a href="#" id="' + self.id() + '" class="athCmsEditButton"><img src="' + rootUrl + 'athCms/images/edit.png" alt="Edit" width="16" height="16" align="absmiddle" /> Edit</a>');
                    }
                }
            }
            else {
                var imageHtml = '';
                var theContent = entryContent;
                if (entryImages != null && entryImages.length > 0) {
                    if (entryImages.length == 1) {
                        var image = entryImages[0];
                        var html = '<div class="athCmsImageBox"><img id="' + image.id() + '" src="' + rootUrl + image.url() + '" align="right" alt="' + image.name() + '" class="';
                        if (parent.limitCharacters() == 0) {
                            html = html + 'cmsImage"/></div>';
                        }
                        else {
                            html = html + 'cmsImageSmall"/></div>';
                        };
                        imageHtml = imageHtml + html;
                    }
                    else if (entryImages.length > 1 && parent.limitArticles() == '') {
                        $.each(entryImages, function (index, image) {
                            var html = '<div class="athCmsImagesBox"><img id="' + image.id() + '" src="' + rootUrl + image.url() + '" align="right" alt="' + image.name() + '" class="';
                            html = html + 'cmsImage"/></div>';
                            imageHtml = imageHtml + html;
                        });
                    };
                }
                if (dateDisplay != undefined && dateDisplay != '') {
                    div.append('<span class="athCmsEntryDate">' + dateDisplay + '</span><br />');
                }
                if (entryTitle != undefined && entryTitle != '') {
                    div.append('<span class="athCmsEntryTitle">' + entryTitle + '</span>');
                }

                if ((dateDisplay != undefined && dateDisplay != '') || (entryTitle != undefined && entryTitle != '')) {
                    div.append('<br/>');
                }

                if (parent.limitCharacters() != '') {
                    if (parent.limitCharacters() == '0') {
                        theContent = '';
                    }
                    else if (theContent.length > parent.limitCharacters()) {
                        theContent = theContent.substring(0, parent.limitCharacters());
                        theContent = theContent + " ...";
                    }
                }
                if (entryImages != null && entryImages.length > 1) {
                    div.append(theContent + imageHtml);
                }
                else {
                    div.append(imageHtml + theContent);
                }

                if (entryFiles != null && entryFiles.length > 0) {
                    $.each(entryFiles, function (index, file) {
                        div.append(file.html());
                    });
                };
                /*
                if (parent.readMoreLink() != '') {
                var url = parent.readMoreLink();
                if (url.match('http') == null) {
                url = rootUrl + url + '#' + self.id();
                }
                if (parent.readMoreText() != '') {
                div.append('<br/><a href="' + url + '">' + parent.readMoreText() + '</a>');
                }
                else {
                div.append('<br/><a href="' + url + '">Read More &gt;&gt;</a>');
                }
                };
                */
                if (isAdmin) {
                    if (parent.type() == 'blog') {
                        var up = $('<br clear="right" /><a href="#" id="' + self.id() + '" class="athIncreaseEntryWeight"><img src="' + rootUrl + 'athCms/images/increase.png" alt="Increase weighting" width="11" height="16" align="absmiddle" /></a>');
                        var down = $('<a href="#" id="' + self.id() + '" class="athDecreaseEntryWeight"><img src="' + rootUrl + 'athCms/images/decrease.png" alt="Decrease weighting" width="11" height="16" align="absmiddle" /></a>');
                        up.bind('click', function (e) {
                            self.moveUp(e);
                        });
                        down.bind('click', function (e) {
                            self.moveDown(e);
                        });
                        div.append(up);
                        div.append(down);
                    }
                    if (parent.type() == 'image') {
                        div.append('<a href="#" id="' + self.id() + '" class="athCmsEditButton"><img src="' + rootUrl + 'athCms/images/photo.png" alt="Edit" width="16" height="16" align="absmiddle" /> Edit</a>');
                    }
                    else {
                        div.append('<a href="#" id="' + self.id() + '" class="athCmsEditButton"><img src="' + rootUrl + 'athCms/images/edit.png" alt="Edit" width="16" height="16" align="absmiddle" /> Edit</a>');
                    }
                }
            }
            return div;
        };

    };

    function cmsImage(image) {

        var imageId = image.Id;
        var imageUrl = image.Url;
        var imageName = image.Name;
        var imageType = image.Type;

        this.id = function () {
            return imageId;
        };

        this.url = function () {
            return imageUrl;
        }

        this.name = function () {
            return imageName;
        };

        this.type = function () {
            return imageType;
        };

    };

    function cmsFile(file) {

        var self = this;
        var fileId = file.Id;
        var fileName = file.Name;
        var fileUrl = file.Url;
        var fileType = file.FileType;

        this.id = function () {
            return fileId;
        };

        this.name = function () {
            return fileName;
        };

        this.url = function () {
            return fileUrl;
        };

        this.type = function () {
            return fileType;
        };

        this.downloadDocument = function () {
            window.open(rootUrl + fileUrl);
        };

        this.html = function () {
            var retval = $('<a href="#" id="' + fileId + '" class="athCmsDocument"></a>');
            var img = '';
            if (fileType == 'application/pdf') {
                img = '<img src="' + rootUrl + 'athCms/images/pdf.png" alt="download pdf" class="athCmsDocumentImage" align="left"/>';
            }
            else if (fileType == 'application/msword') {
                img = '<img src="' + rootUrl + 'athCms/images/word.jpg" alt="download document" class="athCmsDocumentImage" align="left"/>';
            }
            else if (fileType == 'application/ms-excel') {
                img = '<img src="' + rootUrl + 'athCms/images/excel.jpg" alt="download document" class="athCmsDocumentImage" align="left"/>';
            }
            else if (fileType == 'application/zip') {
                img = '<img src="' + rootUrl + 'athCms/images/zip.jpg" alt="download zip file" class="athCmsDocumentImage" align="left"/>';
            }
            img = img + fileName;
            retval.html(img);
            retval.bind('click', function (e) {
                e.preventDefault();
                self.downloadDocument();
            });
            return retval;
        };

    };

});
