var g_ep_defaultPath = "";
var g_ep_ajaxMode = true;
var g_ep_useFckEditor = true;
var g_ep_numberOfImagesToDisplay = 10;
var g_ep_maximumAssignedImages = 20;
var g_ep_loadingImage = g_ep_defaultPath + "/system/img/loading.gif";
var g_brokenImage = g_ep_defaultPath + "/system/img/brokenimage.png"

var g_ep_waitDialog;

var g_ep_sessionID;
var g_ep_totalNumberOfUnusedImages;
var g_ep_deletedImages;
var g_ep_unusedImages;
var g_ep_assignedImages;
var g_ep_adjustStart;
var g_ep_nextItem;
var g_ep_dragging;
var g_ep_currentFirstUnusedImageIndex;
var g_ep_backwardControls;
var g_ep_forwardControls;
var g_ep_pageCounter;
var g_ep_outerImages;
var g_ep_editPropertyDialog;
var g_ep_alias;
var g_ep_assetCode;
var g_ep_propertyCode;
var g_ep_constrained;
var g_ep_propertyImageWarning;
var g_ep_deletionNotice;
var g_ep_preUnused;
var g_ep_postUnused;
var g_ep_srcArray;
var g_ep_imgHolderArray;
var g_ep_propertyTitle;
var g_ep_propertyPageTitle;
var g_ep_propertySummary;
var g_ep_propertyTitleDefault;
var g_ep_propertySummaryDefault;
var g_ep_revertPropertySummaryButton;
var g_ep_propertyDescription;
var g_ep_content;

var g_ip_previewImageDialog;
var g_ip_image;
var g_ip_imageWidth = null;
var g_ip_imageHeight = null;
var g_ip_dialogWidth = null;
var g_ip_dialogHeight = null;
var g_ep_imageBrowserDialog;
var g_pp_previewImageDialog;

// Preload AJAX loading image
jQuery("<img>").attr("src", g_ep_loadingImage);

function editProperty(sessionid, propertyCode, assetCode) {

	if (assetCode == "")
		assetCode = propertyCode;
    g_ep_loadingImage = g_ep_defaultPath + "/system/img/loading.gif";
    g_brokenImage = g_ep_defaultPath + "/system/img/brokenimage.png"
    if (!g_ep_ajaxMode) return;

    g_ep_propertyCode = propertyCode;
	g_ep_assetCode = assetCode;
    g_ep_sessionID = sessionid;

    g_ep_editPropertyDialog = $("<div id=\"editPropertyDialog\"></div>").appendTo($(document)).dialog({
        autoOpen: true,
        title: "Edit Property: " + propertyCode + (assetCode != propertyCode ? "("+assetCode+")" : ""),
        bgiframe: true,
        modal: true,
        height: 640,
        width: 848,
        resizable: false,
        draggable: false,
        close: function(event, ui) {
            g_ep_editPropertyDialog.dialog('destroy');
            g_ep_editPropertyDialog.remove();
            g_ep_outerImages = null;
            g_ep_nextItem = null;
            g_ep_unusedImages = null;
            g_ep_assignedImages = null;
            g_ep_backwardControls = null;
            g_ep_forwardControls = null;
            g_ep_pageCounter = null;
            g_ep_propertyImageWarning = null;
            g_ep_deletionNotice = null;
            g_ep_deletedImages = null;
            g_ep_preUnused = null;
            g_ep_postUnused = null;
            g_ep_srcArray = null;
            g_ep_imageBrowserDialog = null;
            g_pp_previewImageDialog = null;
            g_ep_imgHolderArray = null;
        },
        buttons: {
            "Cancel": function() { closeDialog(g_ep_editPropertyDialog); },
            "OK": function() { sendData(); }
        }
    });
    loadingStart(g_ep_editPropertyDialog);
    
    g_ep_editPropertyDialog.load(g_ep_defaultPath + "edit.asp", { "propertyCode": propertyCode, "assetCode": assetCode, "sessionid": g_ep_sessionID, "cacheGuid": newGuid(), "ajax": true },
        function(responseText, textStatus, XMLHttpRequest) {
            if (textStatus == "success") {
                editPropertyOnReady(propertyCode);
            } else {
                closeDialog(g_ep_editPropertyDialog)
                alert("Could not load property editor for property " + propertyCode);
            }
        })
}

function closeDialog(obj) {
    if (g_ep_ajaxMode) obj.dialog('close');
}

function loadingStart(obj) {
    obj.html("<div class=\"AjaxLoader\"><img src=\"" + g_ep_loadingImage + "\" title=\"Loading please wait\" alt=\"Loading please wait\" /></div>");
}

function editPropertyOnReady(propertyCode) {
    g_ep_propertyCode = propertyCode;
    g_ep_outerImages = $("#OuterImages");
    g_ep_propertyTitle = $("#PropertyTitle");
    g_ep_propertyPageTitle = $("#PropertyPageTitle");
    g_ep_propertySummary = $("#PropertySummary");
    g_ep_propertyTitleDefault = $("#PropertyTitle_Interface_Default");
    g_ep_propertySummaryDefault = $("#PropertySummary_Interface_Default");
    g_ep_revertPropertySummaryButton = $("#RevertSummary");
    g_ep_propertyDescription = $("#PropertyDescription");
    g_ep_content = $("#EditContent");

    // Correct IE box model
    if (!jQuery.support.boxModel)
        g_ep_content.css("width", $("#Content").width() - 15);

    editPropertyLoadImagesSection();

    if (g_ep_useFckEditor)
        g_ep_revertPropertySummaryButton.hide();
    else
        g_ep_revertPropertySummaryButton.click(function() { revertText(g_ep_propertySummary, g_ep_propertySummaryDefault); });

    var contentWidth = g_ep_content.width();

    g_ep_propertyTitle.css("width", contentWidth - 6);
    g_ep_propertyPageTitle.css("width", contentWidth - 6);
    g_ep_propertySummary.change(checkFields).css("width", contentWidth - 6);
    g_ep_propertyDescription.css("width", contentWidth - 6);

    checkFields();

    var summaryDiv = $("#Summary");
    var descriptionDiv = $("#Description");

    $("#Title input[name='OverrideTitle']").click(function() {
        var editOption = $(this).val();

        if (editOption == "true") {
            g_ep_propertyTitle.attr("disabled", false).val(g_ep_propertyTitle.data("overrideValue"));
        }
        else {
            g_ep_propertyTitle.data("overrideValue", g_ep_propertyTitle.val()).attr("disabled", true).val(g_ep_propertyTitleDefault.val());
        }
    });
    
    $("#EditOptions input[name='EditOptionsRadio']").click(function() {
        var editOption = $(this).val();

        if (editOption.indexOf("Summary") > -1 || editOption.indexOf("Both") > -1)
            summaryDiv.slideDown("slow");
        else
            summaryDiv.slideUp("slow");

        if (editOption.indexOf("Description") > -1 || editOption.indexOf("Both") > -1)
            descriptionDiv.slideDown("slow");
        else
            descriptionDiv.slideUp("slow");
    });

    // If fckEditor for EditProperty is true then we want to insert FCK Editors.
    if (g_ep_useFckEditor) {
        var oFCKeditor = new FCKeditor("FCKeditor_Summary");
        oFCKeditor.BasePath = g_ep_defaultPath + "system/fckeditor/";
        oFCKeditor.ToolbarSet = "EditProperty";
        oFCKeditor.Value = $("#PropertySummary").hide().val();
        oFCKeditor.Width = 815;
        oFCKeditor.Height = 120;
        var strHTML = oFCKeditor.CreateHtml();

        $("#PropertyDetailsContainer").html(strHTML);

        oFCKeditor = new FCKeditor("FCKeditor_Description");
        oFCKeditor.BasePath = g_ep_defaultPath + "system/fckeditor/";
        oFCKeditor.ToolbarSet = "EditProperty";
        oFCKeditor.Value = $("#PropertyDescription").hide().val();
        oFCKeditor.Width = 815;
        oFCKeditor.Height = 150;
        strHTML = oFCKeditor.CreateHtml();

        $("#PropertyDescriptionContainer").html(strHTML);
    }
}

function checkFields() {
    if (g_ep_propertySummary.val() == g_ep_propertySummaryDefault.val()) {
        g_ep_propertySummary.addClass("IsDefault");
        g_ep_revertPropertySummaryButton.hide();
    }
    else {
        g_ep_propertySummary.removeClass("IsDefault");
        g_ep_revertPropertySummaryButton.show();
    }
}

function editPropertyLoadImagesSection() {
    loadingStart(g_ep_outerImages);


    g_ep_outerImages.load(g_ep_defaultPath + "system/EditProperty/edit_images.asp", { "alias": g_ep_alias, "sessionid": g_ep_sessionID, "cacheGuid": newGuid(), "PropertyCode": g_ep_propertyCode, "assetCode": g_ep_assetCode },
        function(responseText, textStatus, XMLHttpRequest) {
            if (textStatus == "success") {
                editPropertyImagesOnReady();
            } else {
                if (g_ep_ajaxMode) closeDialog(g_ep_editPropertyDialog)
                alert("Could not load property image editor for property " + g_ep_propertyCode);
            }
        });
}

function editPropertyImagesOnReady() {
    g_ep_adjustStart = false;
    g_ep_nextItem = null;
    g_ep_dragging = false;
    g_ep_constrained = false;
    g_ep_currentFirstUnusedImageIndex = 0;
    g_ep_unusedImages = $("#UnusedImageList");
    g_ep_assignedImages = $("#AssignedImageList");
    g_ep_backwardControls = $("#BackwardControls");
    g_ep_forwardControls = $("#ForwardControls");
    g_ep_pageCounter = $("#PageCounter");
    g_ep_propertyImageWarning = $("#PropertyImageWarning");
    g_ep_deletionNotice = $("#DeletionNotice");
    g_ep_deletedImages = $("#DeletedImages");
    g_ep_preUnused = $("#PreUnused");
    g_ep_postUnused = $("#PostUnused");
    g_ep_srcArray = [];
    g_ep_imgHolderArray = [];

    // Correct IE box model
    if (!jQuery.support.boxModel)
        $("#Assigned, #Unused").css("width", g_ep_assignedImages.width() - 9);

    var imageArea = $("#Images");

    var imageContainers = $("#AssignedImageList,#UnusedImageList,#PostUnused");
    var visibleImageContainers = imageContainers.filter("#AssignedImageList,#UnusedImageList");
    visibleImageContainers.sortable({
        cancel: ".Add, .Remove, .Delete, .Preview",
        connectWith: visibleImageContainers,
        containment: imageArea,
        receive: function(event, ui) { imageReceive(event, ui); },
        sort: function(event, ui) { imageSort(event, ui); },
        start: function(event, ui) { imageStart(event, ui); },
        stop: function(event, ui) { imageStop(event, ui); },
        zIndex: 3,
        revert: true
    }).disableSelection(); ;

    // Attach double click event to run preview, and place img sources into an array for quick search.
    var imageHolders = imageContainers.children("li.ImageHolder").dblclick(function() {
        previewImage($(this));
    }).each(function(i) {
        g_ep_srcArray[i] = $(this).attr("imgsrc");
        g_ep_imgHolderArray[i] = $(this);
    });

    // Attach constraint events
    imageHolders.filter(".External,.UsedElsewhere").mouseover(function() {
        if (g_ep_constrained == true) return;
        g_ep_constrained = true;
        visibleImageContainers.sortable("option", "connectWith", "");
        visibleImageContainers.sortable("option", "containment", g_ep_assignedImages);
    });
    imageHolders.filter(":not(.External,.UsedElsewhere)").mouseover(function() {
        if (g_ep_constrained == false) return;
        g_ep_constrained = false;
        visibleImageContainers.sortable("option", "connectWith", visibleImageContainers);
        visibleImageContainers.sortable("option", "containment", imageArea);
    });

    var unusedImages = g_ep_postUnused.find("li.ImageHolder");
    g_ep_totalNumberOfUnusedImages = unusedImages.size();

    // Move first ten unused images into sorter.
    if (g_ep_totalNumberOfUnusedImages > 0)
        unusedImages.slice(0, g_ep_numberOfImagesToDisplay).each(function(i) { moveImage($(this), g_ep_unusedImages); });

    // Load assigned images
    g_ep_assignedImages.children("li.ImageHolder").each(function(i) { loadImage($(this)); });

    $("#AddImageButton,#RevertImagesButton").mouseover(function() { $(this).addClass("ButtonHover"); })
        .mouseout(function() { $(this).removeClass("ButtonHover"); });

    $("#AddImageButton").click(startImageBrowser);


    $("#RevertImagesButton").click(revertImages);

    $("#SkipToFirst").click(function() { navigateTo(true); });
    $("#SkipBackTen").click(function() { navigatePage(-g_ep_numberOfImagesToDisplay); });
    $("#SkipBackOne").click(function() { navigatePage(-1); });
    $("#SkipForwardOne").click(function() { navigatePage(1); });
    $("#SkipForwardTen").click(function() { navigatePage(g_ep_numberOfImagesToDisplay); });
    $("#SkipToLast").click(function() { navigateTo(false); });

    checkCounts();
    updatePageControls();
}


function receiveSelectedImageDialogFiles() {
    var iframe = $("div#g_ep_imageBrowserDialog #JQueryDialogIFrame");
    var domiframe = iframe.get(0);

    //returns a selector
    var selector = domiframe.contentWindow.getSelectedChecks();

    var freeSlots = g_ep_maximumAssignedImages - g_ep_assignedImages.children().size();

    var addImage = new Array();

    selector.each(function(i) {
        if (i < freeSlots) {
            var imgSrc = UrlEncoder.decode($(this).find("img").attr("src"));
            var existingLocationArr = findImage(imgSrc);

            // Not found.
            if (existingLocationArr[0] == "") {
                // We need to add a new image
                addImage.push(imgSrc);
            }
            else if (existingLocationArr[0] != "Assigned")
                moveImage(existingLocationArr[1], g_ep_assignedImages, false);
        }
    });

    closeDialog(g_ep_imageBrowserDialog);

    // Retrieve image html for specified sources
    if (addImage.length > 0) {
        showWait("Adding...");
        var strAddImage = addImage.join("?");

        $.ajax({
            type: "POST",
            url: g_ep_defaultPath + "system/EditProperty/getImages.asp",
            dataType: "html",
            cache: false,
            data: {
                "alias": g_ep_alias,
                "sessionid": g_ep_sessionID,
                "propertyCode": g_ep_propertyCode,
                "imageUrls": strAddImage
            },
            success: function(data, textStatus) {
                closeDialog(g_ep_waitDialog);

                // Load the UL into a container.
                var loadedHtml = $("<div></div>").html(data);

                // Iterate through each child, adding it to the  assigned images.
                var vacantSpaces = g_ep_maximumAssignedImages - g_ep_assignedImages.children().size();
                loadedHtml.children("ul").children("li").each(function(i) {
                    if (i < vacantSpaces) {
                        // Correct instances used.
                        var instanceUsed = $(this).attr("instances");
                        if (instanceUsed != undefined && !isNaN(instanceUsed)) {
                            instanceUsed = parseInt(instanceUsed) + 1;
                            $(this).attr("instances", instanceUsed);
                            if(instanceUsed > 1)
                                $(this).addClass("UsedElsewhere");
                        }
                        else
                            $(this).attr("instances", "1");

                        g_ep_assignedImages.append($(this));
                        loadImage($(this));
                    }
                });
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                closeDialog(g_ep_waitDialog);
                alert("Could not add images: " + errorThrown);
            }
        });

        closeDialog(g_ep_waitDialog);
    }
}

function findImage(imgSrc) {
    var stringLocation = "";
    var image;
    var returnArr = new Array();

    g_ep_assignedImages.children().each(function() {
        if ($(this).attr("imgsrc") == imgSrc)
        {
            stringLocation = "Assigned";
            image = $(this);
        }
    });

    if(stringLocation == "")
        g_ep_preUnused.children().each(function() {
            if ($(this).attr("imgsrc") == imgSrc)
            {
                stringLocation = "PreUnused";
                image = $(this);
            }
        });


    if (stringLocation == "")
        g_ep_postUnused.children().each(function() {
            if ($(this).attr("imgsrc") == imgSrc)
            {
                stringLocation = "PostUnused";
                image = $(this);
            }
        });


        if (stringLocation == "")
            g_ep_unusedImages.children().each(function() {
                if ($(this).attr("imgsrc") == imgSrc) {
                    stringLocation = "Unused";
                    image = $(this);
                }
            });


    if (stringLocation == "")
        g_ep_deletedImages.children().each(function() {
            if ($(this).attr("imgsrc") == imgSrc)
            {
                stringLocation = "Deleted";
                image = $(this);
            }
        });
     
     
    returnArr.push(stringLocation);
    returnArr.push(image);

    return returnArr;
}

function startImageBrowser()
{
    var browserurl = g_ep_defaultPath + "/system/fckeditor/editor/filemanager/browser/default/imagebrowser.asp?Type=Image&mode=jquerydialog&"+newGuid();

    g_ep_imageBrowserDialog = $("<div id=\"g_ep_imageBrowserDialog\"><iframe id=\"JQueryDialogIFrame\" style=\"display: none; height: auto; width: auto; margin: 0px;\" frameborder=\"0\"></iframe></div>").appendTo($(document)).dialog({
        autoOpen: true,
        title: "Image Browser",
        bgiframe: true,
        modal: true,
        height: 760,
        width: 848,
        resizable: false,
        draggable: false,
        close: function(event, ui) {         
            g_ep_imageBrowserDialog.dialog('destroy');
            g_ep_imageBrowserDialog.remove();
        },
        buttons: {
            "Cancel": function() { closeDialog(g_ep_imageBrowserDialog); },
            "OK": function() { receiveSelectedImageDialogFiles(); }   
        }
    });

    $("#JQueryDialogIFrame").show().css({
        "height": $("#g_ep_imageBrowserDialog").height(),
        "width": $("#g_ep_imageBrowserDialog").width()
    }).attr("src", browserurl);
}


function revertImages() {
    if (confirm("Are you sure you want to revert the image state?")) {
        g_ep_outerImages.empty();
        editPropertyLoadImagesSection();
    }
}

function buttonAction(button) {
    if (g_ep_dragging)
        return;

    var strAction = button.attr("class");
    var image = button.parent();
    if (strAction == "Preview")
        previewImage(image);
    else if (strAction == "Add")
        addImage(image);
    else if (strAction == "Remove")
        removeImage(image);
    else if (strAction == "Delete")
        deleteImage(image);
}

function previewImage(image) {
    displayPreviewImage(image);
}

function addImage(image) {
    moveImage(image, g_ep_assignedImages, false);
}

function removeImage(image) {
    if (image.hasClass("UsedElsewhere")) 
        image.remove();
    else if (image.hasClass("External"))
        moveImage(image, g_ep_deletedImages, false);
    else {
        if (g_ep_currentFirstUnusedImageIndex > 0)
            navigateTo(true);
        moveImage(image, g_ep_unusedImages, true);
    }
}

function deleteImage(image) {
    moveImage(image, g_ep_deletedImages, false);
}

function moveImage(image, target, start) {
    var from = image.parent()[0];
    var to = target[0];

    var fromVisibleUnused = (from == g_ep_unusedImages[0]);
    var fromUnused = (fromVisibleUnused || (from == g_ep_preUnused[0]) || (from == g_ep_postUnused[0]));
    var toVisibleUnused = (target[0] == g_ep_unusedImages[0]);
    var toUnused = (toVisibleUnused || (to == g_ep_preUnused[0]) || (to == g_ep_postUnused[0]));

    if (fromUnused && !fromVisibleUnused)
        loadImage(image);

    if (fromVisibleUnused) {
        if (start)
            target.prepend(image);
        else
            target.append(image);
    }


    if (toVisibleUnused) {
        var visibleElements = g_ep_unusedImages.children("li.ImageHolder:not(.ui-sortable-placeholder)");
        if (visibleElements.size() >= g_ep_numberOfImagesToDisplay) {
            if (start)
                g_ep_postUnused.prepend(visibleElements.slice(-1));
            else
                g_ep_preUnused.append(visibleElements.eq(0));
        }
    }
    else if (fromVisibleUnused) {
        // Show hidden item
        var newImage;
        var postImages = g_ep_postUnused.children("li.ImageHolder");
        if (postImages.size() < 1) {
            var preImages = g_ep_preUnused.children("li.ImageHolder");
            if (preImages.size() > 0) {
                newImage = preImages.slice(-1);
                loadImage(newImage);
                g_ep_unusedImages.prepend(newImage);
                g_ep_currentFirstUnusedImageIndex--;
            }
        }
        else {
            newImage = postImages.eq(0);
            loadImage(newImage);
            g_ep_unusedImages.append(newImage);
        }
    }

    if (!fromVisibleUnused) {
        if (start)
            target.prepend(image);
        else
            target.append(image);
    }

    if (fromUnused != toUnused) {
        if (fromUnused)
            g_ep_totalNumberOfUnusedImages--;
        else if (toUnused)
            g_ep_totalNumberOfUnusedImages++;
    }
    updatePageControls();
    checkCounts();
}

function loadImage(imageHolder) {
    if (imageHolder.attr("loaded") == undefined) {
        var instances = parseInt(imageHolder.attr("instances"));
        var external = imageHolder.hasClass("External");

        // Add buttons
        imageHolder.append("<div class=\"ImageToolbar\">&nbsp;</div><div class=\"Instances\" title=\"This image is used " + instances + " time" + (instances != 1 ? "s" : "") + " on your site\">" + instances + "</div>")
            .append($("<div class=\"Preview\" title=\"Preview this image\">&nbsp;</div>").click(function() { buttonAction($(this)); }))
            .append($("<div class=\"Remove\" title=\"Remove from property images\">&nbsp;</div>").click(function() { buttonAction($(this)); }))
            .append($("<div class=\"Add\" title=\"Add to property images\">&nbsp;</div>").click(function() { buttonAction($(this)); }))
            .append($("<div class=\"Delete\" title=\"Delete this image from the server\">&nbsp;</div>").click(function() { buttonAction($(this)); }));

        if (external)
            imageHolder.append("<div class=\"External\" title=\"This image is hosted externally\">&nbsp;</div>");

        // Create actual image holder
        var imgHolderDiv = $("<div class=\"ImageHolderDiv\" />");
        imageHolder.prepend(imgHolderDiv);

        var img = $("<img src=\"" + g_ep_loadingImage + "\" title=\"Loading image, please wait...\" alt=\"Loading image, please wait...\" />");
        imgHolderDiv.append(img);

        // Create new image to load image in.
        var newImg = new Image();
        $(newImg).error(function() {
            $(newImg).unbind("error").attr("src", g_brokenImage);
            }).load(function() {
            var i = $(this);
            var i2 = i[0];
            var imageWidth = i2.width;
            var imageHeight = i2.height;

            if (i2.width > 75) {
                i2.height = imageHeight = imageHeight * 75 / imageWidth;
                i2.width = imageWidth = 75;
            }

            var title = external ? "No title has been set for this image." : imageHolder.attr("title");
            i.attr("title", title).attr("alt", title);

            img.fadeOut("slow", function() {
                img.replaceWith(i);

                if (imageHeight < 56)
                    imgHolderDiv.css("padding-top", (56 - imageHeight) / 2);
                i.fadeIn("slow");
            });

        }).attr("src", imageHolder.attr("imgsrc")+"?width=75");

        imageHolder.attr("loaded", true);
    }
}

function navigateTo(goToStart) {
    if (goToStart) {
        if (g_ep_currentFirstUnusedImageIndex > 0)
        navigatePage(0 - g_ep_currentFirstUnusedImageIndex);
    } else {
        var lastIndex = g_ep_totalNumberOfUnusedImages - g_ep_numberOfImagesToDisplay;
        if (g_ep_currentFirstUnusedImageIndex + 1 < lastIndex)
            navigatePage(lastIndex - g_ep_currentFirstUnusedImageIndex);
}
}

function navigatePage(shift) {
    // TODO sanity check jump length

    if (Math.abs(shift) <= g_ep_numberOfImagesToDisplay) {
        // We're jumping a page or less
    while (shift != 0) {
        var nextItem;
        if (shift > 0) {
            nextItem = g_ep_postUnused.children("li.ImageHolder").eq(0);
            if (nextItem.size() == 1) {
                g_ep_currentFirstUnusedImageIndex++;
                shift--;
                moveImage(nextItem, g_ep_unusedImages, false);
            } else
                shift = 0;
        } else {
            nextItem = g_ep_preUnused.children("li.ImageHolder").slice(-1);
            if (nextItem.size() == 1) {
                g_ep_currentFirstUnusedImageIndex--;
                shift++;
                moveImage(nextItem, g_ep_unusedImages, true);
            } else
                shift = 0;
        }
    }
    } else {
        g_ep_currentFirstUnusedImageIndex += shift;
        // We're jumping more than a page
        if (shift > 0) {
            // Dump all the visible items and skipped images into the preUnused div
            g_ep_preUnused.append(g_ep_unusedImages.children("li.ImageHolder:not(.ui-sortable-placeholder)"))
                .append(g_ep_postUnused.children("li.ImageHolder").slice(0, shift - g_ep_numberOfImagesToDisplay));
            // Load and display a new page
            g_ep_unusedImages.append(g_ep_postUnused.children("li.ImageHolder").slice(0, g_ep_numberOfImagesToDisplay).each(function() { loadImage($(this)); }));
        } else {
            // Dump all the visible items and skipped images into the preUnused div
            g_ep_postUnused.prepend(g_ep_unusedImages.children("li.ImageHolder:not(.ui-sortable-placeholder)"))
                .prepend(g_ep_preUnused.children("li.ImageHolder").slice(shift + g_ep_numberOfImagesToDisplay));
            // Load and display a new page
            g_ep_unusedImages.prepend(g_ep_preUnused.children("li.ImageHolder").slice(-g_ep_numberOfImagesToDisplay).each(function() { loadImage($(this)); }));
        }
    }

    updatePageControls();
}

function updatePageControls() {
    var startIndex = g_ep_currentFirstUnusedImageIndex + 1;
    var endIndex = startIndex + 9;

    if (g_ep_currentFirstUnusedImageIndex < 1)
        g_ep_backwardControls.addClass("Disabled");
    else
        g_ep_backwardControls.removeClass("Disabled");

    if (endIndex >= g_ep_totalNumberOfUnusedImages) {
        g_ep_forwardControls.addClass("Disabled");
        endIndex = g_ep_totalNumberOfUnusedImages;
    } else
        g_ep_forwardControls.removeClass("Disabled");

    if (g_ep_totalNumberOfUnusedImages > 10) {
        g_ep_pageCounter.text("Images " + startIndex + " to " + endIndex + " of " + g_ep_totalNumberOfUnusedImages + " unused images");
    } else {
        g_ep_pageCounter.text(g_ep_totalNumberOfUnusedImages + " unused image" + (g_ep_totalNumberOfUnusedImages != 1 ? "s" : ""));
    }
}

function imageSort(event, ui) {
    var overUnassigned = ui.placeholder.parent()[0] == g_ep_unusedImages[0];
    if (g_ep_nextItem == null) {
        // Unused box is not full, so handle page counter only
        if (overUnassigned != g_ep_adjustStart) {
            g_ep_totalNumberOfUnusedImages += overUnassigned ? 1 : -1;
            g_ep_adjustStart = overUnassigned;
            updatePageControls();
        }
    } else {
        // Unused box is full so manipulate contents if necessary
        var nextHidden = g_ep_nextItem.parent()[0] != g_ep_unusedImages[0];
        if (overUnassigned != nextHidden) {
            g_ep_totalNumberOfUnusedImages += overUnassigned ? 1 : -1;
            if (g_ep_adjustStart) {
                g_ep_currentFirstUnusedImageIndex += overUnassigned ? 1 : -1;
                if (overUnassigned)
                    g_ep_preUnused.append(g_ep_nextItem);
                else
                    g_ep_unusedImages.prepend(g_ep_nextItem);
            } else {
                if (overUnassigned)
                    g_ep_postUnused.prepend(g_ep_nextItem);
                else
                    g_ep_unusedImages.append(g_ep_nextItem);
            }
            updatePageControls();
        }
    }
}

function imageStart(event, ui) {
    g_ep_dragging = true;
    g_ep_nextItem = null;
    g_ep_adjustStart = false;

    if (ui.item.parent()[0] == g_ep_unusedImages[0]) {
        var postImages = g_ep_postUnused.children("li.ImageHolder");
        if (postImages.size() > 0) {
            g_ep_nextItem = postImages.eq(0);
        } else {
            var preImages = g_ep_preUnused.children("li.ImageHolder");
            g_ep_adjustStart = true;
            if (preImages.size() > 0)
                g_ep_nextItem = preImages.slice(-1);
        }
    }
    else {
        var visibleElements = g_ep_unusedImages.children("li.ImageHolder:not(.ui-sortable-placeholder)");
        if (visibleElements.size() >= g_ep_numberOfImagesToDisplay)
            g_ep_nextItem = visibleElements.slice(-1);
    }

    if (g_ep_nextItem != null)
        loadImage(g_ep_nextItem);
}

function imageReceive(event, ui) {
    checkCounts();
}

function imageStop(event, ui) {
    g_ep_dragging = false;
}

function checkCounts() {
	
	
    if (g_ep_assignedImages.children("li.ImageHolder:not(.ui-sortable-placeholder)").size() > (g_ep_maximumAssignedImages - 1)) {
        // Contain unused images to its own UL.
        g_ep_unusedImages.sortable("option", "containment", g_ep_unusedImages);

        // Hide all add divs in the unused image UL.
        g_ep_unusedImages.children().find("div.Add").addClass("Hidden");

        g_ep_propertyImageWarning.show();
    }
    else {
        // Contain unused images to the id image div.
        g_ep_unusedImages.sortable("option", "containment", "#Images");

        // Show all add divs in the unused image UL.
        g_ep_unusedImages.children().find("div.Add").removeClass("Hidden");

        g_ep_propertyImageWarning.hide();
    }

    var deletionText = "";
    var deletedImageList = g_ep_deletedImages.children();
    var numberOfDeletedImages = deletedImageList.size();

    if (numberOfDeletedImages > 0) {
        var externalDeleted = deletedImageList.filter(".External").size()
        var serverDeleted = numberOfDeletedImages - externalDeleted;

        deletionText = "You have " +
            (serverDeleted > 0 ? serverDeleted + " server image" + (serverDeleted > 1 ? "s " : " ") : "") +
            ((serverDeleted > 0) && (externalDeleted > 0) ? "and " : "") +
            (externalDeleted > 0 ? externalDeleted + " external image" + (externalDeleted > 1 ? "s " : " ") : "") +
            "marked for deletion.";
    }

    g_ep_deletionNotice.text(deletionText);
}

function displayPreviewImage(image) {
    var windowHeight = $(document).height();
    var windowWidth = $(document).width();

    if (windowWidth < 1024)
        windowWidth = 1024;
    if (windowHeight < 768)
        windowHeight = 768;

    var maxHeight = windowHeight - 120;
    var maxWidth = windowWidth - 80;
    
    var minHeight = 420;
    var minWidth = 370;
    var adjustHeight = 210;
    var adjustWidth = 340;

    g_ip_image = image;
    
    var widthAttributeValue = image.attr("imageWidth");
    var heightAttributeValue = image.attr("imageWidth");
    
    if( widthAttributeValue != undefined && widthAttributeValue != "" && !isNaN(widthAttributeValue) )
        g_ip_imageWidth = parseInt(image.attr("imageWidth"));
    if( heightAttributeValue != undefined && heightAttributeValue != "" && !isNaN(heightAttributeValue) )
        g_ip_imageHeight = parseInt(image.attr("imageHeight"));

    var dialogWidth = (widthAttributeValue != null ? g_ip_imageWidth + adjustWidth : maxWidth);
    var dialogHeight = (heightAttributeValue != null ? g_ip_imageHeight + adjustHeight : maxHeight);
    
    // Constrain dialog dimensions between are predefined min/max values.
    if (dialogWidth > maxWidth)
        dialogWidth = maxWidth;
    else if (dialogWidth < minWidth)
        dialogWidth = minWidth;

    if (dialogHeight > maxHeight)
        dialogHeight = maxHeight;
    else if (dialogHeight < minHeight)
        dialogHeight = minHeight;

    g_ip_dialogHeight = dialogHeight;
    g_ip_dialogWidth = dialogWidth;

    g_ip_previewImageDialog = $("<div id=\"previewImageDialog\"></div>").appendTo($(document)).dialog({
        autoOpen: true,
        title: "Preview Image",
        bgiframe: true,
        modal: true,
        height: g_ip_dialogHeight,
        width: g_ip_dialogWidth,
        resizable: false,
        draggable: false,
        close: function(event, ui) {
            g_ip_previewImageDialog.dialog('destroy');
            g_ip_previewImageDialog.remove();
            g_ip_image = null;
            g_ip_imageWidth = null;
            g_ip_imageHeight = null;
            g_ip_dialogWidth = null;
            g_ip_dialogHeight = null;
        },
        buttons: {
            "Cancel": function() { closeDialog(g_ip_previewImageDialog); },
            "OK": function() {
                var title = $("#Preview_ImageTitleField").val();
                var oldTitle = g_ip_image.attr("title");
                if( oldTitle == undefined || oldTitle != title )
                    g_ip_image.addClass("TitleUpdated");
                g_ip_image.attr("title", title);
                if (title == "") {
                    g_ip_image.addClass("TitleWarning");
                    g_ip_image.find("img").attr("title", "No title has been set for this image.");
                }
                else {
                    g_ip_image.removeClass("TitleWarning");
                    g_ip_image.find("img").attr("title", title);
                }
                closeDialog(g_ip_previewImageDialog);
            }
        },
        zIndex: 2000
    });
    loadingStart(g_ip_previewImageDialog);

    g_ip_previewImageDialog.load(g_ep_defaultPath + "/system/EditProperty/preview_image.asp", { "alias": g_ep_alias, "propertyCode": g_ep_propertyCode, "sessionid": g_ep_sessionID, "cacheGuid": newGuid(), "ajax": true },
        function(responseText, textStatus, XMLHttpRequest) {
            if (textStatus == "success") {
                previewImageReady(g_ip_image);
            } else {
                closeDialog(g_ep_editPropertyDialog)
                alert("Could not load image preview for image.");
            }
        })
    }

    function previewImageReady(image) {
        var blnIsExternal = image.hasClass("External");
        var blnInUse = (image.parent().attr("id") == g_ep_assignedImages.attr("id"));
        var blnUsedElsewhere;
        var blnHasTitle = image.hasClass("TitleWarning");
        var intInstances;
        var strUploadedOn;
        var strUnusedSince;
        var infoDivHeight = $("#Preview_Info").height();
        var strFileSize = image.attr("fileSize");
        
        var imageAreaWidth = $("#Preview_Content").width() - $("#Preview_Info").width() - 35;
        var imageAreaHeight = g_ip_dialogHeight - 200;
        var imageAdded = image.attr("addedDate");
        var imageUnUsedSince = image.attr("unusedSince");
        var imageURL = image.attr("imgsrc");
        var imagePreview = $("#Preview_Image");

        // On image load error, display the broken image.
        imagePreview.error(function() {
            imagePreview.unbind("error").attr("src", g_brokenImage);
        });
        
        imagePreview.attr("src", imageURL);
        $("#ImageURLLink").attr("href", imageURL).text(imageURL);

        if (blnInUse)
            $("#Preview_NotUsedSince").hide();
        else {
            $("#Preview_UsedOnTitle,#Preview_UsedOn").hide();
            $("#Preview_ImageUnusedSinceText").text(imageUnUsedSince == undefined || imageUnUsedSince == "" ? "Unknown" : imageUnUsedSince);
        }

        if (!blnHasTitle)
            $("#Preview_ImageTitleField").val(image.attr("title"));

        $("#Preview_ImageAddedText").text(imageAdded == undefined || imageAdded == "" ? "Unknown" : imageAdded);
        
        if (blnIsExternal) {
            $("#Preview_LocationIcon").attr("src", "/system/img/link_16x16.gif");
            $("#Preview_LocationText").text("Stored Externally");
        }

        $("#Preview_FileSizeText").text((strFileSize != undefined
            && strFileSize != ""
            && !isNaN(strFileSize)
            && parseFloat(strFileSize) > 0 ? strFileSize+"KB":"Unknown"));

        if ((g_ip_imageWidth == null || g_ip_imageWidth <= 0)
        && (g_ip_imageHeight == undefined || g_ip_imageHeight <= 0))
            $("#Preview_ImageDimensionsText").text("Dimensions Unknown");
        else {
            $("#Preview_ImageDimensionsText").text("w: " + (g_ip_imageWidth == null ? "?" : g_ip_imageWidth)
            + "px, h: " + (g_ip_imageHeight == null ? "?" : g_ip_imageHeight) + "px");


            //"height": (infoDivHeight > g_ip_imageHeight ? infoDivHeight : g_ip_imageHeight),
            $("#Preview_MainImageArea").css({
                "height": imageAreaHeight,
                "width": imageAreaWidth,
                "overflow-x": (g_ip_imageWidth > imageAreaWidth ? "scroll" : "hidden"),
                "overflow-y": (g_ip_imageHeight > imageAreaHeight ? "scroll" : "hidden")
            });
        }
        
        // For external images remove default path, SQL will do the rest.
        var dbImageURL = imageURL;

        if (!blnIsExternal)
            dbImageURL = dbImageURL.replace(g_ep_defaultPath, "");

        $("#Preview_UsedOnList").load(g_ep_defaultPath + "system/EditProperty/preview_image_info.asp", { "alias": g_ep_alias, "sessionid": g_ep_sessionID, "propertyCode": g_ep_propertyCode, "ImageURL": dbImageURL, "External": (blnIsExternal ? 1 : 0), "cacheGuid": newGuid() },
        function(responseText, textStatus, XMLHttpRequest) {
            $("#Preview_UsedOnLoading").hide();
            var usedOnList = $("#Preview_UsedOnList");
            var usedOnListHeight = imageAreaHeight - $("#Preview_InformationContentFields").height() - 20;

            usedOnList.css("height", usedOnListHeight < 20 ? 20 : usedOnListHeight);
            usedOnList.fadeIn(750);
        });

    }

    function revertText(field, textField) {
        field.val(textField.val());
        checkFields();
    }

    function sendData() {
        // Display wait dialog, as we dont want double clicks.
        showWait("Updating Property...");
        
        // Get Property Title/Overview
        var title = g_ep_propertyTitle.val();
        var overview = g_ep_propertySummary.val();
        var description = g_ep_propertyDescription.val();
        var pageTitle = g_ep_propertyPageTitle.val();

        var blnOverideBoth = $("#EORadio_Both").attr("checked") != "";

        var blnOverrideTitle = $("#Title input#OverrideTitle").attr("checked") != "";
        
        var blnOverrideSummary = blnOverideBoth || $("#EORadio_Summary").attr("checked") != "";
        var blnOverrideDescription = blnOverideBoth || $("#EORadio_Description").attr("checked") != "";

        if (!blnOverrideTitle)
            title = "";

        if (!blnOverrideSummary)
            overview = "";
        else if (g_ep_useFckEditor)
            overview = FCKeditorAPI.GetInstance('FCKeditor_Summary').GetHTML();

        if (!blnOverrideDescription)
            description = "";
        else if (g_ep_useFckEditor) 
            description = FCKeditorAPI.GetInstance('FCKeditor_Description').GetHTML();

        // Generate photo information.
        var arrAssigned = new Array();
        var arrDeleted = new Array();
        var arrUnassignedTitleUpdated = new Array();

        // Loop through all unusued image lists and retrieve any children with the TitleUpdated class.
        g_ep_preUnused.children(".TitleUpdated").each(function() {
            arrUnassignedTitleUpdated.push($(this).attr("imgsrc") + "|" + $(this).attr("title")); 
        });
        g_ep_postUnused.children(".TitleUpdated").each(function() {
            arrUnassignedTitleUpdated.push($(this).attr("imgsrc") + "|" + $(this).attr("title")); 
        });
        g_ep_unusedImages.children(".TitleUpdated").each(function() {
            arrUnassignedTitleUpdated.push($(this).attr("imgsrc") + "|" + $(this).attr("title"));
        });
        
        // Loop through all assigned images.
        g_ep_assignedImages.children().each(function(i) {
            arrAssigned.push($(this).attr("imgsrc") + "|" + $(this).attr("title") + "|" + i); 
        });

        // Loop through all deleted images.
        g_ep_deletedImages.children().each(function() {
            arrDeleted.push($(this).attr("imgsrc"));
        });

        var assignedImages = arrAssigned.join("?");
        var deletedImages = arrDeleted.join("?");
        var unassignedUpdatedImages = arrUnassignedTitleUpdated.join("?");

        // Send ajax request.
        $.ajax({
            type: "POST",
            url: g_ep_defaultPath + "system/EditProperty/update_property.asp",
            dataType: "text",
            cache: false,
            data: {
                "alias": g_ep_alias,
                "sessionid": g_ep_sessionID,
                "propertyCode": g_ep_propertyCode,
				"assetCode": g_ep_assetCode,
                "PropertyTitle": title,
                "PropertySummary": overview,
                "assignedImages": assignedImages,
                "deletedImages": deletedImages,
                "unassignedImageUpdates": unassignedUpdatedImages,
                "pageTitle": pageTitle,
                "overrideTitle": blnOverrideTitle ? "1" : "0",
                "overrideSummary": blnOverrideSummary || blnOverideBoth ? "1" : "0",
                "overrideDescription": blnOverrideDescription || blnOverideBoth ? "1" : "0",
                "propertyDescription": description
            },
            success: function(data, textStatus) {
                closeDialog(g_ep_waitDialog);
                if (data == "") {
                    closeDialog(g_ep_editPropertyDialog);
                    if( document.forms["reload"] != undefined )
                        document.forms["reload"].submit();
                }
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                closeDialog(g_ep_waitDialog);
                alert("Could not save property details: " + errorThrown);
            }
        });
    }

    function showWait(strMessage) {
        g_ep_waitDialog = $("<div id=\"waitDialog\"><img src=\"" + g_ep_loadingImage + "\"/><br/>"+strMessage+"</div>").appendTo($(document)).dialog({
            autoOpen: true,
            bgiframe: true,
            modal: true,
            height: 120,
            width: 150,
            resizable: false,
            draggable: false,
            zIndex: 3000,
            close: function(event, ui) {
                g_ep_waitDialog.dialog('destroy');
                g_ep_waitDialog.remove();
            }
        });

        // hide the waiting dialog title.
        g_ep_waitDialog.parent().children(".ui-dialog-titlebar").hide();
    }


function newGuid() {
    var g = "";
    for (var i = 0; i < 32; i++)
        g += Math.floor(Math.random() * 0xF).toString(0xF) + (i == 8 || i == 12 || i == 16 || i == 20 ? "-" : "")
    return g;
}

/**
*
*  URL encode / decode
*  http://www.webtoolkit.info/
*
**/

var UrlEncoder = {

    // public method for url encoding
    encode: function(string) {
        return escape(this._utf8_encode(string));
    },

    // public method for url decoding
    decode: function(string) {
        return this._utf8_decode(unescape(string));
    },

    // private method for UTF-8 encoding
    _utf8_encode: function(string) {
        string = string.replace(/\r\n/g, "\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if ((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode: function(utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while (i < utftext.length) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if ((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i + 1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i + 1);
                c3 = utftext.charCodeAt(i + 2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }

}
