﻿function hashArray() {
    var hashArray = new Object();

    hashArray.arrKeys = new Array();
    hashArray.arrValues = new Array();

    hashArray.setValue = function(key, value) {
        this.arrKeys.push(key);
        this.arrValues.push(value);
    }

    hashArray.getValue = function(key) {
        var intKey = $.inArray(key, this.arrKeys);
        return this.arrValues[intKey];
    }

    return hashArray;
}

/* Ajax-Uploader */

function CuteWebUI_AjaxUploader_OnStart() {
    if (typeof(type) != "undefined" && type == "notifications_av") {
        $('#controlls').html("<div class='loadingMsg'>Please wait...</div>");
        $('#controlls').addClass('loading');
    }    
}

function CuteWebUI_AjaxUploader_OnPostback() {
    if (typeof work_id == 'number') {
        if (AssetManager.WorkMedia) {
            var uploader = $("#myuploader_" + AssetManager.PersonId)[0];
        } else {
            var uploader = $("#myuploader_" + work_id)[0];
        }
        var guidlist = uploader.value;
        AssetManager.UploadAssets(guidlist, work_id);
        uploader.reset();
    }
    else if (typeof asset_id == 'number') {
        var uploader = $("#myuploader_" + asset_id)[0];
        var guidlist = uploader.value;
        AssetManager.UpdateAsset(guidlist, asset_id);
        uploader.reset();
    }
    else if (typeof type != "undefined" && type == "notifications_av") {
        var uploader = this;
        var guidlist = uploader.value;
        var w_id = $(uploader).attr('id').split("_")[1];
        var student_id = $(uploader).attr('id').split("_")[2];
        
        AssetManager.UpdateNotificationsAV(guidlist, w_id, student_id);
        uploader.reset();
    }
    else if (AssetManager.IsPersonalMedia()) {
        var uploader = $("#myuploader_" + person_id)[0];
        var guidlist = uploader.value;
        AssetManager.UploadAssets(guidlist, person_id);
        uploader.reset();
    }
    else if (type == "asap") {
        var uploader = $("#ASAP_" + asap_id)[0];
        var guidlist = uploader.value;
        var asap_type = $(uploader).siblings('.asap_type').val();
        AssetManager.UploadASAPAssets(guidlist, asap_id, asap_type);
        uploader.reset();
    }
}

var AssetManager = new Object();
AssetManager.Area = "";
AssetManager.Controller = "Assets";
AssetManager.media_type = "";
AssetManager.group_id = "";
AssetManager.hide_delete = false;
AssetManager.WorkMedia = false;
AssetManager.PersonId = null;

AssetManager.PrintFiles = function(list, work_id) {
    var ul = $("<ul class=\"assetList\"></ul>");

    for (var i = 0; i < (list.length - 1); i++) {
        var item = list[i];
        var li = $("<li id=\"asset_" + item.FileID + "\"></li>");
        var details = $("<div class=\"details\"><p>" + item.WorkTitle + "<br />File name: " + item.FileName + "<br />Uploaded: " + item.UploadTime + " ET</p></div>");
        if (item.ContentType == "image") {
            var link = $("<a class=\"assetImage\" href=\"" + item.FileViewUrl + "\" rel=\"assetImage" + work_id + "\" title=\"" + item.ImageTitle + "\"><img src=\"" + item.FileThumbUrl + "\" id=\"asset_img_" + item.FileID + "\" /></a>");
            var dpi = item.Dpi;
            var quality = "excellent";
            if (dpi < 200) {
                quality = "poor";
            } else if (dpi < 300) {
                quality = "good";
            }
            var printsize = $("<div class='quality " + quality + "'>Print Size: <b>" + quality + "</b></div>");
            details.append(printsize);
        }
        var downloadLink = $("<a href=\"" + item.FileUrl + "\" target=\"_blank\" id=\"download_" + item.FileID + "\">Download Raw File</a>");
        details.append(downloadLink);

        var actions = $("<div class=\"actions\">");
        if (item.ContentType == "image") {
            var uplLink = $("<div class=\"last\"><a href=\"/Assets/Edit/" + item.FileID + "\">Upload New</a></div>");
            var rotateLink = $("<div class=\"rotations\">Rotate<br /><a href=\"#\" onclick=\"AssetManager.RotateAsset(" + item.FileID + ", 90); return false\">90&#186;</a> <a href=\"#\" onclick=\"AssetManager.RotateAsset(" + item.FileID + ", 180); return false\">180&#186;</a> <a href=\"#\" onclick=\"AssetManager.RotateAsset(" + item.FileID + ", 270); return false\">270&#186;</a></div>");
            var flipLink = $("<div class=\"flip\"><a href=\"#\" onclick=\"AssetManager.FlipAssetHorizontal(" + item.FileID + "); return false\">Flip horizontal</a></div>");
            actions.append(rotateLink).append(flipLink);
        }
        if (!AssetManager.hide_delete) {
            var delLink = $("<div><a href=\"#\" onclick=\"AssetManager.DeleteAsset(" + item.FileID + "); return false\">[X] Delete</a></div>");
            actions.append(delLink);
        }
        var workcontent = "";
        if (item.CategoryName == "Comic Art") {
            workcontent = $("<div><textarea id=\"content_" + item.FileID + "\">" + item.Content + "</textarea><a href='/Asset/SaveAssetContent/'" + item.FileID + "' class='input-button' onclick='AssetManager.SaveAssetContent(\"" + item.FileID + "\" , \"content_" + item.FileID + "\"); return false;'>Save</a></div>");
        }
        var clearfix = $("<div class=\"clear\"></div>");
        var icons = $("<div class=\"icons\"><img src=\"/Images/move.gif\" class=\"handle\" alt=\"Move to change order\" /><img src=\"/Images/ajax-loader-blue.gif\" class=\"loader\" id=\"loader_" + item.FileID + "\" /></div>");

        li.append(link).append(details).append(icons).append(actions).append(clearfix).append(workcontent);
        ul.append(li);
    }

    return ul;
}

AssetManager.SaveWorkStatement = function(work_id, content_id) {
    var statement = CKEDITOR.instances[content_id].getData();
    $.ajax(
        {
            type: "POST",
            url: "/WorkRegistration/SaveStatement",
            data: ({ id: work_id, statement: statement }),
            dataType: "json",
            success: function(msg) {
                AssetManager.ShowMessage(msg.content, msg.type.toLowerCase());
            }
        }
    );
}

AssetManager.SaveWorkSources = function(work_id, content_box) {
    data = $('#work_sources_ajax_form').find('input:not([type="hidden"]), textarea').serializeArray();
    data.push(({ 'name': 'id', 'value': work_id }));

    $.ajax(
        {
            type: "POST",
            url: "/WorkRegistration/SaveSources",
            data: data,
            dataType: "json",
            success: function(msg) {
                AssetManager.DisplayMessage(content_box + ' #message_box', msg.content, msg.type.toLowerCase());
            }
        }
    )
    return true;
}

AssetManager.SaveAssetContent = function(work_id, content_id, message_id) {
    var content = CKEDITOR.instances[content_id].getData();
    $.ajax(
        {
            type: "POST",
            url: AssetManager.GetController() + "SaveAssetContent",
            data: ({ id: work_id, content: content }),
            dataType: "json",
            success: function(msg) {
                if (message_id != null)
                    AssetManager.DisplayMessage(message_id, msg.content, msg.type.toLowerCase());
                else
                    AssetManager.ShowMessage(msg.content, msg.type.toLowerCase());
                alert("The Content has been saved!");
            }
        }
    );
}

AssetManager.GetAssetsByWork = function(work_id) {
    $.ajax(
        {
            type: "POST",
            url: AssetManager.GetController() + "ListAssetsByWork",
            data: ({ work_id: work_id }),
            dataType: "html",
            success: function(msg) {
                AssetManager.PrintAssetList(msg, work_id);
                AssetManager.CheckCategoryLimits(work_id);
            }
        }
    );
}
AssetManager.GetPersonalMediaByWork = function(work_id, person_id) {
    var media_type = AssetManager.media_type;
    $.ajax(
        {
            type: "POST",
            url: AssetManager.GetController() + "ListPersonalMediaByWork",
            data: ({ work_id: work_id, media_type: media_type }),
            dataType: "html",
            success: function(msg) {
                AssetManager.PrintAssetList(msg, person_id);
            }
        }
    );
}

AssetManager.GetPersonalMedia = function() {
    var person_id = AssetManager.group_id;
    var media_type = AssetManager.media_type;
    $.ajax(
        {
            type: "POST",
            url: AssetManager.GetController() + "ListPersonalMedia",
            data: ({ person_id: person_id, media_type: media_type }),
            dataType: "html",
            success: function(msg) {
                AssetManager.PrintAssetList(msg, person_id);
            }
        }
    );
}

AssetManager.PrintAssetList = function(msg, work_id) {
    var divId = typeof work_id == "undefined" ? "#uploaded_files" : "#uploaded_files_" + work_id;
    var div = $(divId);
    var message = $("#message");

    var list = eval(msg);
    if (list.length > 0) {
        var element = list[list.length - 1];

        message.html(element.content).removeClass();
        if (element.content.length > 0) {
            message.addClass(element.type.toLowerCase());
        }
    }

    if (list.length > 1) {
        div.html("");
        div.html(AssetManager.PrintFiles(list, work_id));

        AssetManager.printContentForm(list);
        AssetManager.MarkPrimary();
        $("a.help").fancybox({ 'zoomSpeedIn': 300, 'zoomSpeedOut': 300, 'overlayShow': false });
        $(divId + " .assetImage").fancybox({ 'zoomSpeedIn': 300, 'zoomSpeedOut': 300, 'overlayShow': false });
        $(divId + " ul").sortable({
            update: function(event, ui) {
                AssetManager.MarkPrimary();
                $.ajax({
                    type: "POST",
                    url: AssetManager.GetController() + "Sort",
                    data: $(this).sortable("serialize", { key: "assets" }) + '&work_id=' + work_id
                })
            },
            handle: "img.handle"
        });
    }
    else {
        div.html("<div style='padding:8px;border:solid 1px steelblue;color:maroon;'>No files have been uploaded yet.</div>");
    }
}

AssetManager.printContentForm = function(list) {
    for (var i = 0; i < (list.length - 1); i++) {
        var item = list[i];
        var textarea_id = "content_" + item.FileID;
        var textarea = $('#' + textarea_id);
        if (textarea.length > 0) {
            if (CKEDITOR.instances[textarea_id] == null)
                CKEDITOR.replace("content_" + item.FileID, { toolbar: 'StudentWorkContent', height: 290 });
        }
    }
}

AssetManager.MarkPrimary = function() {
    var group_id = AssetManager.GroupId();
    $('#uploaded_files_' + group_id + ' li').removeClass('primaryAsset');
    $($('#uploaded_files_' + group_id + ' li:visible').get(0)).addClass('primaryAsset');
}

AssetManager.GroupId = function() {
    return AssetManager.IsDigitalCollection()
        ? AssetManager.group_id
        : work_id;
}

AssetManager.DeleteAsset = function(asset_id) {
    if (!confirm('Are you sure you want to delete selected file?')) {
        return false;
    }
    $.ajax(
        {
            type: "POST",
            url: AssetManager.GetController() + "Delete",
            data: ({ asset_id: asset_id }),
            success: function(objMsg) {
                if (objMsg.type == 'Success') {
                    $('#asset_' + asset_id).addClass('deleted').fadeOut('def', function() {
                        AssetManager.MarkPrimary();
                    });
                    $('#asset_' + asset_id + ' a.assetImage').removeAttr('rel');
                    AssetManager.ShowMessage(objMsg.content, 'success');
                }
                else if (objMsg.type == 'Failure') {
                    AssetManager.ShowMessage(objMsg.content, 'failure');
                }
                AssetManager.CheckCategoryLimits(AssetManager.GroupId());
            }
        }
    );
}
AssetManager.UploadASAPAssets = function(guidlist, asap_id, uploader_id) {
    var parameters = { guidlist: guidlist, asap_id: asap_id, asap_type: uploader_id };
    $.ajax(
        {
            type: "POST",
            url: "/ASAP/UploadAjax",
            data: (parameters),
            type: "POST",
            beforeSend: function() {
                Message.Display('#asap_upload_message', 'Please wait while the thumbnail is being generated.', 'success');
            },
            success: function(msg) {
                if (msg.status == 'success') {
                    AssetManager.PrintASAPAsset(msg.asset, uploader_id);
                }
            }
        }
    );
}

AssetManager.PrintASAPAsset = function(asset, asap_type) {
    var str = '<tr id="asset_' + asset.id + '"><td><a class="fancy_popup" href="' + asset.url + '">' + asset.fileName + '</a></td>';
    str += '<td><input type="button" class="input-button" onclick="removeASAPAsset(' + asset.id + ');" value="Delete"/></td>'
    str += '</tr>';
    $('#list_of_works_' + asap_type + ' table').append(str);

    if ($('#list_of_works_' + asap_type + ' table').find('tr').size() >= 5) {
        var id = asap_type == 1 ? "best_works" : "works_in_progress";
        $('#' + id).find('input[type="button"][value="Upload Work"]').hide();
    }
    $('#add_work_dialog').dialog("close");
    jQuery('a.fancy_popup').fancybox();
    jQuery('input[type="button"].input-button').button();
}

AssetManager.UploadAssets = function(guidlist, work_id) {
    var parameters = AssetManager.IsPersonalMedia()
        ? (!AssetManager.WorkMedia)
            ? { guidlist: guidlist, person_id: work_id, media_type: AssetManager.media_type }
            : { guidlist: guidlist, person_id: AssetManager.PersonId, work_id: work_id, media_type: AssetManager.media_type }
        : { guidlist: guidlist, work_id: work_id };

    $.ajax(
        {
            type: "POST",
            url: AssetManager.GetController() + "UploadAjax",
            data: (parameters),
            beforeSend: function() {
                $('#message').html('Please wait while the thumbnail is being generated.').removeClass().addClass('success');
            },
            success: function(msg) {
                if (AssetManager.WorkMedia) {
                    AssetManager.PrintAssetList(msg, AssetManager.PersonId);
                } else {
                    AssetManager.PrintAssetList(msg, work_id);
                }
                AssetManager.CheckCategoryLimits(work_id);
            }
        }
    );
}

AssetManager.UpdateAsset = function(guidlist, asset_id) {
    $.ajax(
        {
            type: "POST",
            url: AssetManager.GetController() + "Update",
            data: ({ guidlist: guidlist, asset_id: asset_id }),
            success: function(message) {
                if (message[0].FileThumbUrl) {
                    $('#assetImage')[0].src = message[0].FileThumbUrl;
                    $('#assetFileName').html(message[0].FileName);
                }
                if (message[1].type) {
                    AssetManager.ShowMessage(message[1].content, message[1].type.toLowerCase());
                }
            }
        }
    );
}

AssetManager.IsDigitalCollection = function() {
    return "DigitalCollection" == AssetManager.Area;
}

AssetManager.IsPersonalMedia = function() {
    return "PersonalMedia" == AssetManager.Controller;
}

AssetManager.GetController = function() {
    var area = AssetManager.Area.length > 0 
        ? "/" + AssetManager.Area
        : "";

    return area + "/" + AssetManager.Controller + "/";
}

AssetManager.RotateAsset = function(asset_id, angle) {
    $('#loader_' + asset_id).show();
    $.ajax({
        type: 'POST',
        url: AssetManager.GetController() + 'Rotate',
        data: ({ asset_id: asset_id, angle: angle }),
        success: function(msg) {
            var list = eval(msg);
            if (list[1].type == 'Success') {
                AssetManager.ShowMessage(list[1].content, 'success');
                $('#asset_img_' + asset_id).attr('src', list[0].FileThumbUrl);
                $('#download_' + asset_id).attr('href', list[0].FileUrl);
                $('#asset_' + asset_id + ' .assetImage').attr('href', list[0].FileViewUrl);
            }
        },
        complete: function() {
            $('#loader_' + asset_id).hide();
        }
    });
}

AssetManager.RotateAssetInDashboard = function(asset_id) {
    if ($('#rotateBtn').hasClass('btnClicked')) { return; }
    $('#loader').css('left', Math.ceil(($('#mainView').width() - $('#loader').width()) / 2 + $('.verticalList').width()));
    $('#loader').css('top', Math.ceil(($('#mainView').height() - $('#loader').height()) / 2));
    $('#loader').show();
    $('#rotateBtn').addClass('btnClicked');
    $.ajax({
        type: 'POST',
        url: AssetManager.GetController() + 'Rotate',
        data: ({ asset_id: asset_id, angle: 90 }),
        success: function(msg) {
            var list = eval(msg);
            if (list[1].type == 'Success') {
                $('#assetSrc').attr('src', list[0].FileViewUrl);
                $('#assetThumb_' + asset_id).attr('src', list[0].FileThumbUrl);
            }
        },
        complete: function() {
            $('#loader').hide();
            $('#rotateBtn').removeClass('btnClicked');
        }
    });
}

AssetManager.FlipAssetHorizontal = function(asset_id) {
    $('#loader_' + asset_id).show();
    $.ajax({
        type: 'POST',
        url: AssetManager.GetController() + 'FlipHorizontal',
        data: ({ asset_id: asset_id }),
        success: function(msg) {
            var list = eval(msg);
            if (list[1].type == 'Success') {
                AssetManager.ShowMessage(list[1].content, 'success');
                $('#asset_img_' + asset_id).attr('src', list[0].FileThumbUrl);
                $('#download_' + asset_id).attr('href', list[0].FileUrl);
                $('#asset_' + asset_id + ' .assetImage').attr('href', list[0].FileViewUrl);
            }
        },
        complete: function() {
            $('#loader_' + asset_id).hide();      
        }
    });
}

AssetManager.CheckCategoryLimits = function(work_id) {
    if (AssetManager.IsDigitalCollection()) { return; }
    
    var limit = categoryLimits.getValue(work_id);
    var current_nb = $('#uploaded_files_' + work_id + ' ul.assetList li:not(.deleted)').length;
    var button = $('#uploadbutton_' + work_id);
    if (current_nb > 0) {
        $("#print_registration_form").show();
    } else {
        $("#print_registration_form").hide();
    }
    current_nb >= limit ? button.hide() : button.show();
}

AssetManager.ShowMessage = function(message, className) {
    AssetManager.DisplayMessage("#message", message, className);
}

AssetManager.DisplayMessage = function(message_id, message, className) {
    $(message_id).html(message).removeClass().addClass(className);
    setTimeout(function() { $(message_id).html('').removeClass(); }, 5000);
}

AssetManager.ToggleWorkActivity = function(work_id, is_portfolio) {
    if ((is_portfolio && confirm('You are trying to change the activity status of the work that is a part of a portfolio. You will change the status of all works in this portfolio. Do you want to continue?')) || (!is_portfolio && confirm('Are you sure, you want to change the activity status of this work? Disabled works won\'t be included in the judging process.'))) {
        $.ajax({
            type: 'POST',
            url: AssetManager.GetController() + 'ToggleWorkActivity',
            data: ({ work_id: work_id }),
            success: function(msg) {
                $('#activity_switch').html(msg);
            }
        });
    }
    return false;    
}

AssetManager.UpdateNotificationsAV = function(guidlist, work_id, student_id) {
    Notifications.ResetAVControlls(work_id);
    $.ajax({
        type: "POST",
        url: "/Notifications/UploadAjax",
        data: ({ guidlist: guidlist, work_id: work_id, student_id: student_id }),
        success: function(message) {
            AssetManager.DisplayMessage("#notifications_message", message.content, message.type.toLowerCase());
            Notifications.GetAVControlls(work_id, student_id);
            Notifications.SetWorkUploadButton(work_id, "upload");
        }
    });
    return false;
}

