﻿var PHAUser = {
    shortlists: [],
    id: null,
    fullRights: false,
    newSLID: "00000000000000000000000000000000",
    findShortlist: function(sid) { for (var i = 0; i < this.shortlists.length; i++) if (this.shortlists[i].id == sid) return this.shortlists[i]; return null; }
};

var Shortlist = function(id, title, lastModified, pictureCount) {
    this.id = id;
    this.title = title;
    this.lastModified = lastModified;
    this.pictureCount = pictureCount;
    this.pictures = Array();
    this.includesCurrentTarget = false;
    this.findPicture = function(pid) { for (var i = 0; i < this.pictures.length; i++) if (this.pictures[i].id == pid) return this.pictures[i]; return null; }
    this.isDirty = false;
    this.saveUI = null;
    this.dirty = function() { this.isDirty = true; $(this.saveUI).show(); }
    this.save = function() {
        var del = "";
        for (var i = 0; i < this.pictures.length; i++) if (this.pictures[i].deleted) del += this.pictures[i].id + ",";
        var url = "/resource/services/shortlists/update.ashx?id=" + encodeURIComponent(this.id) + "&title=" + encodeURIComponent(this.title) + "&del=" + encodeURIComponent(del.substring(0, del.length - 1));
        jQuery.get(url, this.saveComplete);
    }
    this.saveComplete = function(data, textStatus) {
        if (data == "OK") {
            activeShortlist.isDirty = false;
            $(activeShortlist.saveUI).hide();
        }
        else {
            alert("Sorry, we were unable to update your shortlist at this time. Please try again in a few moments or contact us if the problem persists.\n\n[" + data + "]");
        }
    }
}

var ShortlistPicture = function(id, ownerType, ownerId, small, med, large, jumbo, profileUrl, name, gender, dob) {
    this.id = id;
    this.ownerType = ownerType;
    this.ownerId = ownerId;
    this.thumbUrl = med;
    this.smallUrl = small;
    this.medUrl = med;
    this.jumboUrl = jumbo;
    this.largeUrl = large;
    this.profileUrl = profileUrl;
    this.name = name;
    this.gender = gender;
    this.dob = dob;
    this.deleted = false;
}

var ShortlistPictureGroup = function(title)
{
    this.title = title;
    this.pictures = new Array();
}

var ShortlistView = function(mode, shortlist) {
    this.mode = mode;
    this.groups = new Array();
    var p, base = this;

    switch (mode) {
        case "age":
            base.groups.push(new ShortlistPictureGroup(""));
            base.groups[0].pictures = shortlist.pictures.slice();
            base.groups[0].pictures.sort(function(a, b) { return b.dob - a.dob; });
            break;
        case "name":
            base.groups.push(new ShortlistPictureGroup(""));
            base.groups[0].pictures = shortlist.pictures.slice();
            base.groups[0].pictures.sort(function(a, b) { return a.name > b.name ? 1 : -1; });
            break;
        case "agegender":
        case "namegender":
            base.groups.push(new ShortlistPictureGroup("Women"), new ShortlistPictureGroup("Men"), new ShortlistPictureGroup("Other"));
            for (var i = 0; i < shortlist.pictures.length; i++) {
                p = shortlist.pictures[i];
                switch (p.gender) {
                    case "M": base.groups[1].pictures.push(p); break;
                    case "F": base.groups[0].pictures.push(p); break;
                    default: base.groups[2].pictures.push(p);
                }
            }
            if (mode == "agegender")
                jQuery.each(base.groups, function(i, a) { a.pictures.sort(function(x, y) { return y.dob - x.dob; }) });
            else
                jQuery.each(base.groups, function(i, a) { a.pictures.sort(function(x, y) { return x.name > y.name ? 1 : -1; }) });
                
            break;
    }
}

function showShortlistDialog(e) {
    initShortlistDialog();
    var x = e.pageX - parseInt($(dialogShortlists.dialog).css("width")) - 30;
    var y = Math.min(e.pageY, $(window).height() - (parseInt($(dialogShortlists.dialog).css("height")) + 30));

    e.stopPropagation();
    $(dialogShortlists.dialog).css("top", y).css("left", x).show();
    $(document).bind("click.shortlist", function(e) { hideOnClickAway(e, dialogShortlists.dialog, "shortlist") });
    return false;
}

function hideOnClickAway(e, dialog, eventqual) {
    if (e.target != dialog && $(e.target).parents().index(dialog) < 0) {
        $(dialog).hide();
        $(document).unbind("click." + eventqual);
    }
}

function addToShortlist(id, title) {
    if (curTargetPic != null) {
        if (title == null) {
            var s = PHAUser.findShortlist(id);
            title = (s == null ? "" : s.title);
        }
        var url = "/resource/services/shortlists/addtoshortlist.ashx?sid=" + id + "&pid=" + curTargetPic.id + "&title=" + (title == null ? "" : encodeURIComponent(title));
        jQuery.get(url, null, addToShortlistComplete, "json");
    }
    return false;
}
function addToShortlistComplete(data, textStatus) {
    if (data.Error == true) {
        alert(data.ErrorMsg);
    }
    else {
        if (data.IsNew) {
            if (PHAUser.id == null)
                document.cookie = "shortlist=" + data.ShortlistID;

            var sl = PHAUser.findShortlist(PHAUser.newSLID);
            if (sl != null) {
                sl.id = data.ShortlistID;
            }
            else {
                sl = new Shortlist(data.ShortlistID, data.Title, new Date(), data.PictureCount);
                PHAUser.shortlists.push(sl);
            }
        }

        var sl = PHAUser.findShortlist(data.ShortlistID);
        sl.includesCurrentTarget = true;
        
        $(dialogShortlists.dialog).hide();
        updateShortlistUI();
    }
}
function addToNewShortlist() {
    if (curTargetPic != null) {
        var sid = PHAUser.newSLID;
        var title = dialogShortlists.addNewTextbox.value;
        if (title.length == 0)
            alert("Please enter a name for your new shortlist");
        else
            addToShortlist(sid, title);
    }
    return false;
}

function updateShortlistUI() {
    var str = "", sl = null;
    for (var i = 0; i < PHAUser.shortlists.length; i++) {
        sl = PHAUser.shortlists[i];
        if (sl.includesCurrentTarget)
            str += "<a href=\"/shortlists/edit.aspx?ID=" + sl.id + "\">" + sl.title + "</a>, ";
    }
    if (str.length == 0)
        $(shortlistReferencesContainer).hide();
    else {
        shortlistReferences.innerHTML = str.substr(0, str.length - 2);
        $(shortlistReferencesContainer).show();
    }
}

function initShortlistDialog() {
    var strOpts = "";
    var sl;

    // Shortlists
    if (PHAUser.shortlists.length > 0) {
        for (var i = 0; i < PHAUser.shortlists.length; i++) {
            sl = PHAUser.shortlists[i];
            strOpts += "<li><a href=\"#\" onclick=\"return addToShortlist('" + sl.id + "')\">" + sl.title + "</a></li>";
        }
        dialogShortlists.list.innerHTML = strOpts;
        $(dialogShortlists.listContainer).show();
    }
    else {
        $(dialogShortlists.listContainer).hide();
    }

    // Teaser
    if (PHAUser.id == null) {
        $(dialogShortlists.listContainer).addClass("short");
        $(dialogShortlists.teaser).show();
    }
    else
        $(dialogShortlists.teaser).hide();

    // Add new
    if (PHAUser.fullRights) {
        $(dialogShortlists.addNewContainer).show();
        dialogShortlists.addNewTextbox.value = "";
    }
    else
        $(dialogShortlists.addNewContainer).hide();
}

function editorModeChange(e) {
    editorShowPics(document.getElementById("editorItems"), document.getElementById("shortlistSort").value, document.getElementById("shortlistSize").value, activeShortlist);
}

function editorShowPics(target, mode, size, shortlist) {
    var view = new ShortlistView(mode, shortlist);

    var str = "", g = null, p = null;
    for (var gi = 0; gi < view.groups.length; gi++) {
        g = view.groups[gi];
        if (g.pictures.length > 0) {
            str += "<div class=\"group\">";
            if (g.title != "") str += "<h4>" + g.title + "</h4>";
            for (var pi = 0; pi < g.pictures.length; pi++) {
                p = g.pictures[pi];
                str += "<div class=\"item" + size + (p.deleted ? " deleted" : "") + "\" id=\"item" + p.id + "\"><img src=\"" + p[size + "Url"] + "\" alt=\"" + p.name + "\" />"
                    + "<div class=\"toolbar\">"
					+ "<a href=\"#\" onclick=\"return showLargeImage('" + p.id + "')\"><img src=\"/img/shortlists/magnify.gif\" width=\"13\" height=\"13\" alt=\"View large picture\" /></a>"
					+ "<a href=\"" + p.profileUrl + "\" onclick=\"return checkShortlistDirty()\"><img src=\"/img/shortlists/profile.gif\" width=\"11\" height=\"14\" alt=\"View profile\" /></a>"
					+ "<a href=\"#\" onclick=\"return editorDeletePic(" + p.id + ")\"><img src=\"/img/shortlists/delete.gif\" width=\"12\" height=\"12\" alt=\"Remove this picture\" /></a>"
					+ "</div>"
                    + "</div>";
            }
            str += "</div>";
        }
    }
    target.innerHTML = str;
}

function editorDeletePic(id) {
    if (activeShortlist != null) {
        var p = activeShortlist.findPicture(id);
        if (p != null) {
            p.deleted = !p.deleted;
            if (p.deleted) $("#item" + id).addClass("deleted");
            else $("#item" + id).removeClass("deleted");
            activeShortlist.dirty();
        }
    }
}

function renameShow() {
    document.getElementById("actionRenameTextbox").value = activeShortlist.title;
    $("#actionRenameContainer").show();
    return false;
}
function renameOK() {
    var str = document.getElementById("actionRenameTextbox").value;
    if (str.length == 0) { alert("Please enter a name for the shortlist."); return false; }
    if (str != activeShortlist.title) {
        activeShortlist.title = str;
        lblShortlistTitle.innerText = str;
        activeShortlist.dirty();
    }

    $("#actionRenameContainer").hide();
    return false;
    
}
function renameCancel() {
    $("#actionRenameContainer").hide();
    return false;
}
function checkShortlistDirty(e) {
    if (activeShortlist.isDirty) {
        if (confirm("You have made changes to this shortlist.\nClick OK to save them before following this link or Cancel to discard your changes.")) {
            activeShortlist.save();
        }
        return true;
    }
}
function showLargeImage(id) {
    var p = activeShortlist.findPicture(id);
    if (p != null) window.open(p.jumboUrl);
    return false;
}
function deleteShortlist() {
    if (activeShortlist != null) {
        if (confirm("Are you sure you wish to delete this shortlist?\nAny email invites to view the shortlist that you may have sent will no longer work.")) {
            jQuery.get("/resource/services/shortlists/delete.ashx?id=" + activeShortlist.id, deleteShortlistComplete);
            return false;
        }
    }
}
function deleteShortlistComplete(data, textStatus) {
    if (data == "OK")
        window.location.href = "/shortlists/";
    else {
        alert("Sorry, your shortlist could not be deleted at this time. Please try again in a few moments and contact us if the problem persists.");
    }
}
function sendShortlistByEmail() {
    checkShortlistDirty();
    var url = "/shortlists/email.aspx?id=" + encodeURIComponent(activeShortlist.id) + "&sort=" + encodeURIComponent(document.getElementById("shortlistSort").value);
    window.location.href = url;
    return false;
}
function shortlistPdf() {
	checkShortlistDirty();
	var url = "/shortlists/pdf.ashx?id=" + encodeURIComponent(activeShortlist.id) + "&sort=" + encodeURIComponent(document.getElementById("shortlistSort").value);
	window.open(url);
	return false;
}
function createContactSheet() {
	checkShortlistDirty();
	var url = "/shortlists/contact/edit.aspx?Action=New&amp;slid=" + encodeURIComponent(activeShortlist.id);
	window.location.href = url;
}