Util.createCPObject('cpp.common.media');

cpp.common.media = {
    setUploadify: function(room, record_type, id, sessionID, extraParamObj){
        queueID   = 'fileQueueMedia_' + record_type;

        /** used in admin to re-load the media in the base container **/
        mainDivId = "media__" + record_type;
        mainDiv = $('#' + mainDivId);

        var uploadifyId = '#uploadifyMedia_' + record_type;
        var frmObj = $(uploadifyId).closest('form')

        var masterPathAlias = $('#masterPathAlias').val();
        var jssPath = $('#jssPath').val();

        var scopeRootAlias = $('#scopeRootAlias').val();

        var onAllCompleteFunction = null;
        var allowMultiUpload = true;

        if (!extraParamObj) {
            extraParamObj = {};
        }

        var lang = extraParamObj.lang;
        if (extraParamObj.onAllCompleteFunction) {
            onAllCompleteFunction = extraParamObj.onAllCompleteFunction;
        }

        if (extraParamObj.allowMultiUpload) {
            allowMultiUpload = extraParamObj.allowMultiUpload;
        }

        if (extraParamObj.uploadifyId) {
            uploadifyId = extraParamObj.uploadifyId;
        }

        var browseButtonImg = (extraParamObj.browseButtonImg) ? extraParamObj.browseButtonImg: masterPathAlias + 'images/icons/btn_browse.png';
        var btnWidth = (extraParamObj.btnWidth) ? extraParamObj.btnWidth : 50;
        var btnHeight = (extraParamObj.btnHeight) ? extraParamObj.btnHeight : 20;
        var sizeLimit = (extraParamObj.fileSizeLimit) ? extraParamObj.fileSizeLimit : 1024 * 1000;
        var queueSizeLimit = (extraParamObj.queueSizeLimit) ? extraParamObj.queueSizeLimit : 5;

        $(uploadifyId).uploadify({
              'uploader'       : jssPath + 'jquery/uploadify-2.1.4/uploadify.swf'
            , 'buttonImg'      : browseButtonImg
            , 'script'         : scopeRootAlias + 'index.php'
            , 'fileDataName'   : 'fileName'
            , 'cancelImg'      : jssPath + 'jquery/uploadify-2.1.4/cancel.png'
            , 'queueID'        : queueID
            , 'multi'          : allowMultiUpload
            , 'width'          : btnWidth
            , 'height'         : btnHeight
            , 'sizeLimit'      : sizeLimit
            , 'queueSizeLimit' : queueSizeLimit
            , 'scriptData'     : {
                                   'plugin'       :'common_media'
                                  ,'_spAction'   :'addMedia'
                                  ,'room'        :room
                                  ,'recordType'  :record_type
                                  ,'id'          :id
                                  ,'showHTML'    :'0'
                                  ,'sessionIDCP' :sessionID
                                  ,'successText' :'success'
                                  ,'lang'        : lang
                                 }
            , 'onSelect'         : function(e, queueID, fileObj){
                if(fileObj.size > sizeLimit){
                    var sizeLimitMB = sizeLimit/(1024 * 1024);
                    alert('The file size shoulb be less than ' + sizeLimitMB.toFixed(2) + ' MB.');
                    $(this).uploadifyCancel(queueID);
                }
            }
            , 'onOpen': function(){
                Util.showProgressInd();
            }
            , 'onComplete': function(e, queueID, fileObj, response){
                //alert (response);
            }
            , 'onAllComplete': function(e, data){
                if(onAllCompleteFunction) {
                    onAllCompleteFunction.call();
                } else if ($('.mediaFilesDisplayWrap', mainDiv).length != 0){
                    cpp.common.media.reloadMediaFilesDisplay($('.mediaFilesDisplayWrap', mainDiv));
                    $(uploadifyId).closest('div.popcontents').dialog('close');
                    $(uploadifyId).closest('div.popcontents').dialog('destroy');
                }
                if (extraParamObj.formSuccessMsg && extraParamObj.formSuccessMsg != '') {
                    var formHt = frmObj.height();
                    frmObj.css('height', formHt + 'px');
                    frmObj.html(extraParamObj.formSuccessMsg);
                    frmObj.hide().slideDown();
                }

                Util.hideProgressInd();
            }
            ,'onError': function (event, ID, fileObj, errorObj) {
                alert(errorObj.type + ' Error: ' + errorObj.info);
            }
        });

        $(function() {
            $('a.uploadQueue').livequery('click', function(e){
                e.preventDefault();
                var fileID = $('input[type=file]', $(this).closest('.uploadWrap')).attr('id');
                //alert($('#' + fileID).length);

                /*
                var record_type = $(this).attr('record_type');
                $('#' + fileID).uploadifySettings('scriptData', {'recordType': record_type});
                */

                $('#' + fileID).uploadifyUpload();
            });

            $('a.clearQueue').livequery('click', function(e){
                e.preventDefault();
                var fileID = $('input[type=file]', $(this).parent()).attr('id');
                $('#' + fileID).uploadifyClearQueue();
            });
        });
    },

    reloadMediaFilesDisplay: function(container) {
        var url = $(container).attr('url');
        $.get(url, function(data){
                $(container).hide();
                $(container).html(data);
                $(container).slideDown(1000);
                Util.hideProgressInd();
            }
        );
    },

    deleteMedia: function(e){
        e.preventDefault();
        var media_id    = $(this).attr('id');
        var link        = $(this);
        var url         = 'index.php?plugin=common_media&_spAction=deleteMedia&media_id=' + media_id + '&showHTML=0';

        msg = "Are you sure you want to delete this record?\nYou cannot undo this action!";

        Util.confirm(msg, function(){
            Util.showProgressInd();

            $.get(url, function(){
                var container = $(link).closest('.mediaFilesDisplayWrap');
                cpp.common.media.reloadMediaFilesDisplay(container);
            });
        });
    },

    editMediaPropeties: function(e){
        e.preventDefault();
        var media_id    = $(this).attr('id');
        var link        = this;
        var container   = $(this).closest('.mediaFilesDisplayWrap');

        var expObj = {
            validate: true,
            callbackOnSuccess: function(){
                cpp.common.media.reloadMediaFilesDisplay(container);
                $('#frmEditMediaProp').closest('div.popcontents').dialog('close');
                $('#frmEditMediaProp').closest('div.popcontents').dialog('destroy');
            }
        }
        Util.openFormInDialog.call(link, 'frmEditMediaProp', 'Edit Media Properties', 600, 400, expObj);
    },

    cropMediaForm: function(e){
        e.preventDefault();
        var media_id  = $(this).attr('id');
        var cropWidth  = $(this).attr('cropWidth');
        var cropHeight = $(this).attr('cropHeight');
        var aspectRatio = cropWidth/cropHeight;

        var link      = this;
        var container = $(this).closest('.mediaFilesDisplayWrap');

        xButtons = {};
        xButtons['Crop'] = function() {
            $('#frmCropMedia').submit();
        };

        xButtons['Cancel'] = function() {
            $(this).dialog('close');
            $(this).dialog('destroy');
            $(this).remove();
        };
        var expObj = {
            validate: true,
            callbackOnSuccess: function(){
                cpp.common.media.reloadMediaFilesDisplay(container);
                $('#frmCropMedia').closest('div.popcontents').dialog('close');
                $('#frmCropMedia').closest('div.popcontents').dialog('destroy');
            },
            onOpenFn: function(){
                var initialCropX = 10;
                var initialCropY = 10;
                $('#cropX').val(initialCropX);
                $('#cropY').val(initialCropY);
                $('#cropW').val(cropWidth);
                $('#cropH').val(cropHeight);
				$('#cropbox').Jcrop({
					aspectRatio: aspectRatio,
                    setSelect: [initialCropX, initialCropX, cropWidth, cropHeight],
					onSelect: function (c){
                        $('#cropX').val(c.x);
                        $('#cropY').val(c.y);
                        $('#cropW').val(c.w);
                        $('#cropH').val(c.h);
                    }
				});
                Util.hideProgressInd();
            },
            buttons: xButtons
        }
        Util.openFormInDialog.call(link, 'frmCropMedia', 'Crop Media', 800, 560, expObj);
    },

    setZoomImageDefaults: function(){
        if ($("a.cpZoom").length > 0){
            $("a.cpZoom").colorbox();
        }

        if ($("a[rel='cpZoomGallery']").length > 0){
            $("a[rel='cpZoomGallery']").colorbox({'maxHeight': $(window).height(), 'maxWidth': $(window).width()});
        }
    },

    init: function(){
        $(function(){
            $("a.btnSelectMedia").live('click', function (e) {
                e.preventDefault();
                Util.openDialogForLink.call(this, 'Upload Media', 400, 265, 1);
            });

            $("a.removeMedia").live('click', cpp.common.media.deleteMedia);
            $("a.editMedia").live('click', cpp.common.media.editMediaPropeties);
            $("a.cropMedia").live('click', cpp.common.media.cropMediaForm);
        });
    }
}

$(function(){
    cpp.common.media.init();
    cpp.common.media.setZoomImageDefaults();
});

