﻿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_OnPostback() {
    if (typeof work_id == 'number') {
        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();
    }
}

var AssetManager = new Object();

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 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 details = $("<div class=\"details\"><p>" + item.WorkTitle + "<br />File name: " + item.FileName + "<br />Uploaded: " + item.UploadTime + " ET</p></div>");
        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 + " <a class=\"help\" href=\"#upload_help\">Help</a></b></div>");
        var downloadLink = $("<a href=\"" + item.FileUrl + "\" target=\"_blank\" id=\"download_" + item.FileID + "\">Download Raw File</a>");
        details.append(printsize).append(downloadLink);
        var actions = $("<div class=\"actions\">");

        var delLink = $("<div><a href=\"#\" onclick=\"AssetManager.DeleteAsset(" + item.FileID + "); return false\">[X] Delete</a></div>");
        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).append(delLink);

        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);
        ul.append(li);
    }

    return ul;
}

AssetManager.GetAssetsByWork = function(work_id) {
    $.ajax(
        {
            type: "POST",
            url: "/Assets/ListAssetsByWork",
            data: ({work_id : work_id}),
            dataType: "html",
            success: function(msg) {
                AssetManager.PrintAssetList(msg, work_id);
                AssetManager.CheckCategoryLimits(work_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) { 
        div.html("");
        div.html(AssetManager.PrintFiles(list, work_id));
        AssetManager.MarkPrimary(work_id);
        var element = list[list.length-1];
        message.html(element.content).removeClass();
        if (element.content.length > 0) {
            message.addClass(element.type.toLowerCase());
        }
        $("a.help").fancybox({ 'zoomSpeedIn': 300, 'zoomSpeedOut': 300, 'overlayShow': false });
        $(divId + " ul").sortable({
            update: function(event, ui) {
                AssetManager.MarkPrimary(work_id);
                $.ajax({
                    type: "POST",
                    url: "/Assets/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 be uploaded yet.</div>");
    }
}

AssetManager.MarkPrimary = function(work_id) {
    $('#uploaded_files_'+work_id+' li').removeClass('primaryAsset');
    $($('#uploaded_files_'+work_id+' li:visible').get(0)).addClass('primaryAsset');
}

AssetManager.DeleteAsset = function(asset_id) {
    if (!confirm('Are you sure you want to delete selected file?')) {
        return false;
    }
    $.ajax(
        {
            type: "POST",
            url: "/Assets/Delete",
            data: ({ asset_id: asset_id }),
            success: function(objMsg) {
                if (objMsg.type == 'Success') {
                    $('#asset_' + asset_id).addClass('deleted').fadeOut('def', function() {
                        AssetManager.MarkPrimary(work_id);
                    });
                    $('#asset_' + asset_id + ' a.assetImage').removeAttr('rel');
                    AssetManager.ShowMessage(objMsg.content, 'success');
                }
                else if (objMsg.type == 'Failure') {
                    AssetManager.ShowMessage(objMsg.content, 'failure');
                }
                AssetManager.CheckCategoryLimits(work_id);
            }
        }
    );
}

AssetManager.UploadAssets = function(guidlist, work_id) {
    $.ajax(
        {
            type: "POST",
            url: "/Assets/UploadAjax",
            data: ({ guidlist: guidlist, work_id: work_id }),
            beforeSend: function() {
                $('#message').html('Please wait while the thumbnail is being generated.').removeClass().addClass('success');
            },
            success: function(msg) {
                AssetManager.PrintAssetList(msg, work_id);
                AssetManager.CheckCategoryLimits(work_id);
            }
        }
    );
}

AssetManager.UpdateAsset = function(guidlist, asset_id) {
    $.ajax(
        {
            type: "POST",
            url: "/Assets/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.RotateAsset = function(asset_id, angle) {
    $('#loader_' + asset_id).show();
    $.ajax({
        type: 'POST',
        url: '/Assets/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: '/Assets/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: '/Assets/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) {
    var limit = categoryLimits.getValue(work_id);
    var current_nb = $('#uploaded_files_'+work_id+' ul.assetList li:not(.deleted)').length;
    var button = $('#uploadbutton_'+work_id);
    current_nb >= limit ? button.hide() : button.show();
}

AssetManager.ShowMessage = function(message, className) {
    $('#message').html(message).removeClass().addClass(className);
    setTimeout(function() { $('#message').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: '/Assets/ToggleWorkActivity',
            data: ({ work_id: work_id }),
            success: function(msg) {
                $('#activity_switch').html(msg);
            }
        });
    }
    return false;    
}

AssetManager.ActivatePortfolioWorks = function(student_id, type_id) {
    if (confirm('You are trying to activate the work that is a part of a portfolio. You will activate all works in this portfolio. Do you want to continue?')) {
        $.ajax({
            type: 'POST',
            url: '/Assets/ActivatePortfolioWorks',
            data: ({ student_id: student_id, type_id: type_id }),
            success: function(msg) {
                $('#activity_switch').html(msg);
            }
        });
    }
    return false;    
}

AssetManager.DisablePortfolioWorks = function(student_id, type_id) {
    if (confirm('You are trying to disable the work that is a part of a portfolio. You will disable all works in this portfolio. Do you want to continue?')) {
        $.ajax({
            type: 'POST',
            url: '/Assets/DisablePortfolioWorks',
            data: ({ student_id: student_id, type_id: type_id }),
            success: function(msg) {
                $('#activity_switch').html(msg);
            }
        });
    }
    return false;
}
