﻿/// <reference path="../API/Agility.js" />
/// <reference path="../API/Agility.UGC.API.js" />


Agility.RegisterNamespace("Whiskas.Modules.MediaUpload");

(function(MU, $) {

    var pnlMediaUpload = null;
    var selectedUGCCategory = 0;
    var BrowseButtonUrl = "";

    //Max video file size in MB
    var MaxVideoSize = 100;

    MU.OnInit = function(pnlMediaUploadID, btnSelectButtonUrl, UGCCategories, imgHelpID, browseButton) {

        pnlMediaUpload = $("#" + pnlMediaUploadID);

        BrowseButtonUrl = browseButton;

        _setupVideoInputFile();
        _setupPhotoInputFile();

        _renderDropdownFilter($('div[id$=divUGCCategory]', pnlMediaUpload), btnSelectButtonUrl, UGCCategories);

        var imgHelp = $('#' + imgHelpID);
        var popup = imgHelp.next().dialog({ autoOpen: false, draggable: false });
        $('img.CloseTip', popup).click(function(e) {
            popup.dialog("close");
        });
        imgHelp.click(function(e) {
            popup.dialog('option', 'position',
                [(-$(window).scrollLeft() + imgHelp.offset().left + imgHelp.width() + 5),
                 (-$(window).scrollTop() + imgHelp.offset().top)]);
            popup.dialog("open");
        });

        _bindTextAreaCount($('textarea[id$=txtDescription]'));
        _bindTextAreaCount($('textarea[id$=txtStory]'));

        $("input[id$=txtTitle]", pnlMediaUpload).focus();

        //Fade out the success message
        setTimeout(function() {
            $("div.SuccessfulyUploaded", pnlMediaUpload).fadeOut("normal", function() {
                $(this).hide();
            });
        }, 10000); //after 4 seconds
    };

    function _bindTextAreaCount(textarea) {

        var commentLength = eval(textarea.attr('maxchars'));
        textarea.keyup(function() {
            var count = textarea.val().length;
            if (count > commentLength) {
                textarea.val(textarea.val().substring(0, commentLength));
                count = commentLength;
            }
        });
    };

    function _renderDropdownFilter(divFilter, btnSelectButtonUrl, JSONcontent) {

        divFilter.WSelectBox({
            DefaultText: divFilter.html(),
            ClearItemText: null,
            Items: JSONcontent,
            SelectedValue: 0,
            SelectImage: btnSelectButtonUrl,
            Horizontal: false,
            onSelectedChange: function(selectedvalue, selectedtext) {
                selectedUGCCategory = selectedvalue;
                if (selectedvalue > 0) {
                    divFilter.next().val(selectedvalue);
                }
                else {
                    divFilter.next().val('');
                }
            }
        });
    };

    function _showError(panel, no) {
        var errors = $("span.Error", panel).hide();
        if (no != undefined) {
            errors.eq(no).show();
        }
    };

    var AllowedVideoMimeTypes = [
            "video/quicktime",  //.mov
            "video/avi",        //.avi
            "video/msvideo",
            "video/x-msvideo",
            "video/mpeg"        //.mpeg
        ];

    function _setupVideoInputFile() {

        var txtVideoFile = $("input[id$=txtVideoFile]", pnlMediaUpload);
        txtVideoFile.val("");
        var inputID = txtVideoFile.attr("id");
        var attachmentPanel = $("div.AttachmentPanel", txtVideoFile.parent().parent());

        var fieldType = { MaxLength: (MaxVideoSize * 1024) };

        Agility.UGC.API.GetAmazonS3Form({

            fieldName: "Video",
            fieldType: fieldType,
            inputID: inputID,
            fieldPanel: txtVideoFile.parent().parent(),
            swfUploadUrl: Agility.ResolveUrl("~/Scripts/SwfUpload/swfupload.swf"),
            uploadButtonImageUrl: Agility.ResolveUrl(BrowseButtonUrl),
            uploadButtonImageWidth: 91,
            uploadButtonImageHeight: 25,

            beforeUpload: function(fileName, mime, filesize, uploader) {

                //before upload
                var mimeOk = jQuery.inArray(mime, AllowedVideoMimeTypes) >= 0;
                if (!mimeOk) {
                    // Error wrong file type
                    //alert("Error wrong file type");
                    _showError(attachmentPanel.parent().next(), 0);
                    txtVideoFile.val("");
                    if (uploader != undefined && uploader != null) {
                        //Reset the fileName ..
                        uploader.cancelUpload(null, false);
                    }
                    return false;
                }

                _showError(attachmentPanel.parent().next());

                //show the progress...
                var AttachmentProgress = $("div.AttachmentProgress", attachmentPanel).show();

                $("div.AttachmentUploading", attachmentPanel).html(
                    "<img src='" + Agility.ResolveUrl("~/Images/LoadingArrow.gif") + "'/>" +
                    "&nbsp;&nbsp;<em>" + txtVideoFile.attr("UploadingLabel") + " " + fileName + "</em>");

                var percent = "50%";
                if (uploader != undefined && uploader != null) {
                    percent = "0%";

                    //show the cancel button if the uploader object is available...
                    var AttachmentCancel = $("div.AttachmentCancel", attachmentPanel).show();
                    $("a", AttachmentCancel).unbind("click").click(function() {
                        //if (confirm("Do you wish to cancel this upload?")) {
                        //cancel the upload...
                        uploader.cancelUpload(null, false);
                        AttachmentProgress.hide();
                        AttachmentCancel.hide();
                        $("div.AttachmentUploading", attachmentPanel).html("");
                        txtVideoFile.val("");
                        //}
                    });
                }
                $("div.AttachmentProgressInner", AttachmentProgress).css("width", percent);
            },

            uploadComplete: function(key, filesize) {

                //upload complete

                //hide the progress...
                $("div.AttachmentCancel", attachmentPanel).hide();
                setTimeout(function() {
                    $("div.AttachmentProgress", attachmentPanel).hide();
                }, 50);

                //Hide browse option
                attachmentPanel.next().hide();

                var path = key.split('/');
                txtVideoFile.prev().html("<b>" + path[path.length - 1] +
                    "</b>&nbsp;&nbsp;<a href='javascript:;'>" + txtVideoFile.attr("RemoveLabel") + "</a><br/>");
                $("div.AttachmentUploading", attachmentPanel).html("");

                $("a", txtVideoFile.prev()).click(function(e) {
                    Agility.UGC.API.DeleteFile(key, function() {
                        txtVideoFile.val("");
                        txtVideoFile.prev().html("");
                        //Show browse option
                        attachmentPanel.next().show();
                    });
                });
            },

            uploadError: function(file, errorCode, message) {

                //upload error...
                txtVideoFile.val("");

                //hide the progress
                $("div.AttachmentCancel a", attachmentPanel).hide();
                $("div.AttachmentProgress", attachmentPanel).hide();

                //determine the message...
                switch (errorCode) {
                    case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
                        //alert("Error:" + "Please choose a file less than or equal to " + fieldType.MaxLength + "kb");
                        _showError(attachmentPanel.parent().next(), 1);
                        break;
                    case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
                        //alert("Error:" + "Please choose a file greater than zero bytes.");
                        _showError(attachmentPanel.parent().next(), 1);
                        break;
                    case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
                    case SWFUpload.UPLOAD_ERROR.FILE_VALIDATION_FAILED:
                        //alert("Error:" + fieldType.ValidationMessage);
                        _showError(attachmentPanel.parent().next(), 0);
                        break;

                    case SWFUpload.UPLOAD_ERROR.HTTP_ERROR:
                    case SWFUpload.UPLOAD_ERROR.IO_ERROR:
                    case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED:
                    case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
                    case SWFUpload.UPLOAD_ERROR.SPECIFIED_FILE_ID_NOT_FOUND:
                    case SWFUpload.UPLOAD_ERROR.IO_ERROR:
                    case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR:
                        //alert("Error:" + "An error occurred while uploading the file.  Please check your connection and try again.");
                        _showError(attachmentPanel.parent().next(), 2);
                        break;
                    case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:
                    case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
                        //ignore these errors...
                        break;
                    default:
                        //alert("Error:" + message + " (code: " + errorCode + ")");
                        _showError(attachmentPanel.parent().next(), 2);
                        break;
                }
            },

            uploadProgress: function(file, bytesLoaded) {
                //progress...
                var percent = Math.ceil((bytesLoaded / file.size) * 100);
                $("div.AttachmentProgressInner", attachmentPanel).css("width", percent + "%");
            }
        });
    };

    var AllowedImageMimeTypes = [
            "image/gif",        //.gif
            "image/jpeg",       //.jpg
            "image/pjpeg",
            "image/png"         //.png
        ];

    function _setupPhotoInputFile() {

        var txtPhotoFile = $("input[id$=txtPhotoFile]", pnlMediaUpload);
        txtPhotoFile.val("");
        var inputID = txtPhotoFile.attr("id");
        var attachmentPanel = $("div.AttachmentPanel", txtPhotoFile.parent().parent());

        var fieldType = null;

        Agility.UGC.API.GetAmazonS3Form({

            fieldName: "Photo",
            fieldType: fieldType,
            inputID: inputID,
            fieldPanel: txtPhotoFile.parent().parent(),
            swfUploadUrl: Agility.ResolveUrl("~/Scripts/SwfUpload/swfupload.swf"),
            uploadButtonImageUrl: Agility.ResolveUrl(BrowseButtonUrl),
            uploadButtonImageWidth: 91,
            uploadButtonImageHeight: 25,

            beforeUpload: function(fileName, mime, filesize, uploader) {

                //before upload
                var mimeOk = jQuery.inArray(mime, AllowedImageMimeTypes) >= 0;
                if (!mimeOk) {
                    // Error wrong file type
                    //alert("Error wrong file type");
                    _showError(attachmentPanel.parent().next(), 0);
                    txtPhotoFile.val("");
                    if (uploader != undefined && uploader != null) {
                        //Reset the fileName ..
                        uploader.cancelUpload(null, false);
                    }
                    return false;
                }

                _showError(attachmentPanel.parent().next());

                //show the progress...
                var AttachmentProgress = $("div.AttachmentProgress", attachmentPanel).show();

                $("div.AttachmentUploading", attachmentPanel).html(
                    "<img src='" + Agility.ResolveUrl("~/Images/LoadingArrow.gif") + "'/>" +
                    "&nbsp;&nbsp;<em>" + txtPhotoFile.attr("UploadingLabel") + " " + fileName + "</em>");

                var percent = "50%";
                if (uploader != undefined && uploader != null) {
                    percent = "0%";

                    //show the cancel button if the uploader object is available...
                    var AttachmentCancel = $("div.AttachmentCancel", attachmentPanel).show();
                    $("a", AttachmentCancel).unbind("click").click(function() {
                        //if (confirm("Do you wish to cancel this upload?")) {
                        //cancel the upload...
                        uploader.cancelUpload(null, false);
                        AttachmentProgress.hide();
                        AttachmentCancel.hide();
                        $("div.AttachmentUploading", attachmentPanel).html("");
                        txtPhotoFile.val("");
                        //}
                    });
                }
                $("div.AttachmentProgressInner", AttachmentProgress).css("width", percent);
            },

            uploadComplete: function(key, filesize) {

                //upload complete

                //hide the progress...
                $("div.AttachmentCancel", attachmentPanel).hide();
                setTimeout(function() {
                    $("div.AttachmentProgress", attachmentPanel).hide();
                }, 50);

                //Hide browse option
                attachmentPanel.next().hide();

                var path = key.split('/');
                txtPhotoFile.prev().html("<b>" + path[path.length - 1] +
                    "</b>&nbsp;&nbsp;<a href='javascript:;'>" + txtPhotoFile.attr("RemoveLabel") + "</a><br/>");
                $("div.AttachmentUploading", attachmentPanel).html("");

                $("a", txtPhotoFile.prev()).click(function(e) {
                    Agility.UGC.API.DeleteFile(key, function() {
                        txtPhotoFile.val("");
                        txtPhotoFile.prev().html("");
                        //Show browse option
                        attachmentPanel.next().show();
                    });
                });
            },

            uploadError: function(file, errorCode, message) {

                //upload error...
                txtPhotoFile.val("");

                //hide the progress
                $("div.AttachmentCancel a", attachmentPanel).hide();
                $("div.AttachmentProgress", attachmentPanel).hide();

                //determine the message...
                switch (errorCode) {
                    case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
                        //alert("Error:" + "Please choose a file less than or equal to " + fieldType.MaxLength + "kb");
                        _showError(attachmentPanel.parent().next(), 1);
                        break;
                    case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
                        //alert("Error:" + "Please choose a file greater than zero bytes.");
                        _showError(attachmentPanel.parent().next(), 1);
                        break;
                    case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
                    case SWFUpload.UPLOAD_ERROR.FILE_VALIDATION_FAILED:
                        //alert("Error:" + fieldType.ValidationMessage);
                        _showError(attachmentPanel.parent().next(), 0);
                        break;

                    case SWFUpload.UPLOAD_ERROR.HTTP_ERROR:
                    case SWFUpload.UPLOAD_ERROR.IO_ERROR:
                    case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED:
                    case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
                    case SWFUpload.UPLOAD_ERROR.SPECIFIED_FILE_ID_NOT_FOUND:
                    case SWFUpload.UPLOAD_ERROR.IO_ERROR:
                    case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR:
                        //alert("Error:" + "An error occurred while uploading the file.  Please check your connection and try again.");
                        _showError(attachmentPanel.parent().next(), 2);
                        break;
                    case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:
                    case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
                        //ignore these errors...
                        break;
                    default:
                        //alert("Error:" + message + " (code: " + errorCode + ")");
                        _showError(attachmentPanel.parent().next(), 2);
                        break;
                }
            },

            uploadProgress: function(file, bytesLoaded) {
                //progress...
                var percent = Math.ceil((bytesLoaded / file.size) * 100);
                $("div.AttachmentProgressInner", attachmentPanel).css("width", percent + "%");
            }
        });
    };

    MU.OnDecline = function(sender) {
        $(sender).next().val(0); // Do not accept Terms & disable Submit button
        var buttons = $(sender).parent().parent().parent().next().next();
        $('div.Buttons:eq(0)', buttons).show();
        $('div.Buttons:eq(1)', buttons).hide();
        //Show validation message
        $('span', $(sender).parent().parent().next()).show();
    };

    MU.OnAccept = function(sender) {
        $(sender).next().val(1); // Terms Accepted & enable Submit button
        var buttons = $(sender).parent().parent().parent().next().next();
        $('div.Buttons:eq(0)', buttons).hide();
        $('div.Buttons:eq(1)', buttons).show();
        //Hide validation message
        $('span', $(sender).parent().parent().next()).hide();

        $(sender).parent().hide();
    };

    MU.OnCancel = function(sender) {
        //Reset form
        //_setupVideoInputFile();
        var txtVideoFile = $("input[id$=txtVideoFile]", pnlMediaUpload);
        var attachmentPanel = $("div.AttachmentPanel", txtVideoFile.parent().parent());
        Agility.UGC.API.DeleteFile(txtVideoFile.val(), function() {
            txtVideoFile.val("");
            txtVideoFile.prev().html("");
            //Show browse option
            attachmentPanel.next().show();
        });
        //_setupPhotoInputFile();
        var txtPhotoFile = $("input[id$=txtPhotoFile]", pnlMediaUpload);
        attachmentPanel = $("div.AttachmentPanel", txtPhotoFile.parent().parent());
        Agility.UGC.API.DeleteFile(txtPhotoFile.val(), function() {
            txtPhotoFile.val("");
            txtPhotoFile.prev().html("");
            //Show browse option
            attachmentPanel.next().show();
        });

        $("input[id$=txtTitle]", pnlMediaUpload).val('');
        $("textarea[id$=txtDescription]", pnlMediaUpload).val('');
        $("textarea[id$=txtStory]", pnlMediaUpload).val('');
        $("input[id$=txtTags]", pnlMediaUpload).val('');
        $("input[id$=txtFirstName]", pnlMediaUpload).val('');
        $("input[id$=txtLastName]", pnlMediaUpload).val('');
        $("input[id$=txtEmailAddress]", pnlMediaUpload).val('');

        $("div.Validators span").hide();

        $("input[id$=hfTermsAccepted]").val(0);
        $(sender).parent().hide();
        $(sender).parent().prev().show();
        $("div.Buttons", $(sender).parent().parent().parent().prev().prev()).show();
    };

    MU.OnAddTag = function(sender) {
        var txtTags = $('input[id$=txtTags]', $(sender).parent());
        var tag = $(sender).text()

        if (txtTags.val().toLowerCase().indexOf(tag.toLowerCase()) < 0) {
            if (txtTags.val().length > 0) {
                txtTags.val(txtTags.val() + ', ');
            }
            txtTags.val(txtTags.val() + tag);
        }
    };

    MU.OnSubmit = function(sender) {

        var mediaType = parseInt(pnlMediaUpload.attr('selectedMediaType'));
        switch (mediaType) {
            case 0: //Video
                if (Page_ClientValidate("SubmitVideo")) {
                    _uploadVideo();
                }
                break;
            case 1: //Photo
                if (Page_ClientValidate("SubmitPhoto")) {
                    _uploadPhoto();
                }
                break;
            case 2: //Story
                if (Page_ClientValidate("SubmitStory")) {
                    _uploadStory();
                }
                break;
        }
    };

    function _uploadPhoto() {

        var txtTags = $("input[id$=txtTags]", pnlMediaUpload).val();
        if (txtTags.length > 0) {
            txtTags = ', ' + txtTags;
        }
        var record = {
            ID: -1,
            RecordTypeName: "Photo",
            Category: selectedUGCCategory,
            Title: $("input[id$=txtTitle]", pnlMediaUpload).val(),
            Description: $("textarea[id$=txtDescription]", pnlMediaUpload).val(),
            Tags: $("input[id$=txtTags]", pnlMediaUpload).val(),
            FirstName: $("input[id$=txtFirstName]", pnlMediaUpload).val(),
            LastName: $("input[id$=txtLastName]", pnlMediaUpload).val(),
            EmailAddress: $("input[id$=txtEmailAddress]", pnlMediaUpload).val(),
            FlickrData: {
                __type: Agility.UGC.API.FileServiceMetaDataTypeName,

                FileService: Agility.UGC.API.FileService.Flickr,
                OriginalFilePath: $("input[id$=txtPhotoFile]", pnlMediaUpload).val(),
                title: $("input[id$=txtTitle]", pnlMediaUpload).val(),
                description: $("textarea[id$=txtDescription]", pnlMediaUpload).val(),
                is_public: true
            },
            UploadedByID: -1
        };

        //console.dir(record);

        Agility.UGC.API.SaveRecord(record, function(data) {
            if (data.ResponseType != 0) {
                alert("There was an error: " + data.Message);
            }
            else {
                _uploadedSuccessfully("Photo");
            }
        });

    };

    function _uploadVideo() {

        var txtTags = $("input[id$=txtTags]", pnlMediaUpload).val();
        if (txtTags.length > 0) {
            txtTags = ', ' + txtTags;
        }
        var record = {
            ID: -1,
            RecordTypeName: "Video",
            Category: selectedUGCCategory,
            Title: $("input[id$=txtTitle]", pnlMediaUpload).val(),
            Description: $("textarea[id$=txtDescription]", pnlMediaUpload).val(),
            Tags: $("input[id$=txtTags]", pnlMediaUpload).val(),
            FirstName: $("input[id$=txtFirstName]", pnlMediaUpload).val(),
            LastName: $("input[id$=txtLastName]", pnlMediaUpload).val(),
            EmailAddress: $("input[id$=txtEmailAddress]", pnlMediaUpload).val(),
            YouTubeData: {
                __type: Agility.UGC.API.FileServiceMetaDataTypeName,

                FileService: Agility.UGC.API.FileService.YouTube,
                OriginalFilePath: $("input[id$=txtVideoFile]", pnlMediaUpload).val(),
                Title: $("input[id$=txtTitle]", pnlMediaUpload).val(),
                Description: $("textarea[id$=txtDescription]", pnlMediaUpload).val(),
                Category: "Animals", //Fixed YouTube category
                Keywords: $("select[id$=ddlCategories] :selected", pnlMediaUpload).text() + txtTags,
                Private: false
            },
            UploadedByID: -1
        };

        //console.dir(record);

        Agility.UGC.API.SaveRecord(record, function(data) {
            if (data.ResponseType != 0) {
                //alert("There was an error: " + data.Message);
            }
            else {
                _uploadedSuccessfully("Video");
            }
        });

    };

    function _uploadStory() {

        var txtTags = $("input[id$=txtTags]", pnlMediaUpload).val();
        if (txtTags.length > 0) {
            txtTags = ', ' + txtTags;
        }
        var record = {
            ID: -1,
            RecordTypeName: "Story",
            Category: selectedUGCCategory,
            Title: $("input[id$=txtTitle]", pnlMediaUpload).val(),
            Story: $("textarea[id$=txtStory]", pnlMediaUpload).val(),
            Tags: $("input[id$=txtTags]", pnlMediaUpload).val(),
            FirstName: $("input[id$=txtFirstName]", pnlMediaUpload).val(),
            LastName: $("input[id$=txtLastName]", pnlMediaUpload).val(),
            EmailAddress: $("input[id$=txtEmailAddress]", pnlMediaUpload).val(),
            UploadedByID: -1
        };

        record.Story = record.Story.replace(/\n/g, '<br/>')

        Agility.UGC.API.SaveRecord(record, function(data) {
            if (data.ResponseType != 0) {
                //alert("There was an error: " + data.Message);
            }
            else {
                _uploadedSuccessfully("Story");
            }
        });

    };

    function _uploadedSuccessfully(mediaName) {
        // Reload the page with the Success message
        window.location = $.Params.set('UploadedSuccessfully', mediaName);
    };

})(Whiskas.Modules.MediaUpload, jQuery);
