﻿if (!window.jqsDCCJMG) jqsDCCJMG = jQuery.noConflict();
function WEBGetMediaList(_tabID, _PortalId, _ModuleId, _GalleryId, _FolderId, _UserId, _PageNo, _PageSize) {
    jqsDCCJMG('div#' + _ModuleId + '_MediaGallery').find('ul.dcc_gallery_medialist').html('').addClass("dcc_gallery_mg_ajaxloader");
    DNNCentric.JMediaGallery.MediaGalleryController.GetAllMediaInfo(_tabID, _PortalId, _ModuleId, _GalleryId, _FolderId, _UserId, _PageNo, _PageSize, SucceededCallbackGetMediaList, FailedCallback);
}

function SucceededCallbackGetMediaList(result, eventArgs) {
    if ((result != null)) {
        thumbShown = result.AlMediaList.length;
        ShowMediaList(result, thumbnailWidth, thumbnailHeight);
        restoreScroll();
    }
}

function FailedCallback(error) {
    //alert("Failed: " + error._message.toString());
}

function SucceededCallbackWithContext(result, userContext, methodName) {
    if (userContext == "XmlDocument") {
        GetWebServiceXMLResult(result);
    }
}

function WEBDeleteMedia(_PortalId, _ModuleId, _MediaId) {
    DNNCentric.JMediaGallery.MediaGalleryController.DeleteMedia(_PortalId, _ModuleId, _MediaId, SucceededCallbackModMedia, FailedCallback);
}

function WEBGetMedia(_PortalId, _ModuleId, _MediaId) {
    DNNCentric.JMediaGallery.MediaGalleryController.GetMediaInfo(_PortalId, _ModuleId, _MediaId, SucceededCallbackGetMedia, FailedCallback);
}

function SucceededCallbackGetMedia(result, eventArgs) {
    if ((result != null)) {
        jqsDCCJMG(document).ready(function() {
            var dialogEditMedia = jqsDCCJMG('#' + result.ModuleId + '_dialogEditMedia');
            dialogEditMedia.find('#' + result.ModuleId + '_title').val(result.InfoMedia.MediaTitle);
            dialogEditMedia.find('#' + result.ModuleId + '_description').val(result.InfoMedia.MediaDescription);
            dialogEditMedia.find("#lblDeleteBoxCharCount").html(maxCharCount - result.InfoMedia.MediaDescription.length);
        });
    }
}

function WEBSaveMedia(_PortalId, _ModuleId, _MediaId, _MediaTitle, _MediaDescription) {
    DNNCentric.JMediaGallery.MediaGalleryController.SaveMediaInfo(_PortalId, _ModuleId, _MediaId, _MediaTitle, _MediaDescription, SucceededCallbackModMedia, FailedCallback);
}

function SucceededCallbackModMedia(result, eventArgs) {
    if ((result != null)) {
        jqsDCCJMG.noConflict();
        jqsDCCJMG(document).ready(function() {
            if (thumbShown == 1) {
                if (PageNo > 1)
                    PageNo--;
                else
                    PageNo = 1;
            }
            WEBGetMediaList(MediaGallery.TabId, result.PortalId, result.ModuleId, result.GalleryId, parseInt(folderId), iThisUserID, PageNo, pageSize);
        });
    }
}
function rPosition(element, mouseX, mouseY) {
    var offset = jqsDCCJMG(element).offset();
    var x = mouseX - offset.left;
    var y = mouseY - offset.top;
    return { 'x': x, 'y': y };
}

function ShowMediaList(mediaData, thmbnlWidth, thmbnlHeight) {
    jqsDCCJMG.noConflict();
    jqsDCCJMG(document).ready(function() {
        var strMediaItemList = "";
        var ULMedia = jqsDCCJMG('div#' + mediaData.ModuleId + '_MediaGallery').find('ul.dcc_gallery_medialist');
        jqsDCCJMG(ULMedia).removeClass("dcc_gallery_mg_ajaxloader");
        if (mediaData.AlMediaList.length > 0) {
            jqsDCCJMG.each(mediaData.AlMediaList, function() {
                var objMedia = this;
                objMediaTemp = new Media(objMedia);
                objMediaItemTemp = new MediaItem(objMediaTemp, thmbnlWidth, thmbnlHeight, mediaData.ModuleId);
                strMediaItemList = strMediaItemList + objMediaItemTemp.getMediaItem();
            });
            jqsDCCJMG(ULMedia).append(strMediaItemList);
            jqsDCCJMG(ULMedia).find("li").width(((parseInt(thmbnlWidth)) / jqsDCCJMG('div#' + mediaData.ModuleId + '_MediaGallery').width() * 100) + "%")
                              .css("background-color", '#' + strThumbnailContainerColor).css("border-color", '#' + strThumbBorderColor).css("padding", strThumbBorderWidth + "px").css("margin", strMarginBetweenThumbnails + "px");
            var dvToolTip = jqsDCCJMG("#dvToolTip");
            var isMouseOver = null;
            var timeoutID = 0;
            if (mediaData.ToolTipEnabled) {
                jqsDCCJMG(ULMedia).find("img").bind("mouseenter", function(e) {
                    isMouseOver = true;
                    var ev = e || window.event;
                    var obj = ev.target || ev.srcElement;
                    if (!dvToolTip.divGalleryContainer)
                        dvToolTip.divGalleryContainer = jQuery(".dcc_gallery_container");
                    dvToolTip.html(jqsDCCJMG(obj).attr("tooltip"));
                    if (jqsDCCJMG(obj).attr("tooltip") == '') return;
                    dvToolTip.css("position", "absolute").css("left", ev.pageX + 15).css("top", ev.pageY + 15);
                    timeoutID = setTimeout('jqsDCCJMG("#dvToolTip").show()', 500);
                    jqsDCCJMG(this).mousemove(function(e) {
                        var ev = e || window.event;
                        var obj = ev.target || ev.srcElement;
                        if (dvToolTip.divGalleryContainer) {
                            var pos = rPosition(dvToolTip.divGalleryContainer, ev.pageX, ev.pageY);
                            dvToolTip.css("left", pos.x + 15).css("top", pos.y + 15);
                        }
                    })
                }).mouseout(function(e) {
                    isMouseOver = false;
                    clearTimeout(timeoutID);
                    dvToolTip.hide();
                });
            }
            //if admin then attaching the jquery ui to it
            if (mediaData.ShowEdit) {
                //attaching the jqui sortable
                //jqsDCCJMG('div#' + mediaData.ModuleId + '_MediaGallery').find("ul.dcc_gallery_medialist").sortable();
                jqsDCCJMG('div#' + mediaData.ModuleId + '_MediaGallery').find("ul.dcc_gallery_medialist").disableSelection();
                //attaching the jqui dialogs for delete
                jqsDCCJMG('#' + mediaData.ModuleId + '_dialogDeleteMedia').dialog({
                    autoOpen: false,
                    bgiframe: true,
                    resizable: false,
                    height: 150,
                    modal: true,
                    overlay: {
                        backgroundColor: '#000',
                        opacity: 0.8
                    },
                    buttons: {
                        Cancel: function() {
                            jqsDCCJMG(this).dialog('close');
                        },
                        'Delete Media': function() {
                            jqsDCCJMG(this).dialog('close');
                            WEBDeleteMedia(mediaData.PortalId, mediaData.ModuleId, iMediaIdToMod);
                        }
                    }
                });
                //attaching the jqui dialog for edit
                var title = jqsDCCJMG('#' + mediaData.ModuleId + '_dialogEditMedia').find('#' + mediaData.ModuleId + '_title'),
			    description = jqsDCCJMG('#' + mediaData.ModuleId + '_dialogEditMedia').find('#' + mediaData.ModuleId + '_description'),
			    allFields = jqsDCCJMG([]).add(title).add(description),
			    lblEditBoxTitleErrorMessage = jqsDCCJMG('#' + mediaData.ModuleId + '_dialogEditMedia').find('#lblEditBoxTitleErrorMessage');
                function updateTips(t) {
                    lblEditBoxTitleErrorMessage.html(t); //.effect("highlight", {}, 1500);
                }
                function checkLength(o, n, min, max) {
                    if (o.val().length > max || o.val().length < min) {
                        jqsDCCJMG(o).css("border-color", "red");
                        updateTips("*");
                        return false;
                    } else {
                        jqsDCCJMG(o).css("border-color", "gray");
                        updateTips("");
                        return true;
                    }
                }
                function checkRegexp(o, regexp, n) {
                    if (!(regexp.test(o.val()))) {
                        o.addClass('ui-state-error');
                        updateTips(n);
                        return false;
                    } else {
                        return true;
                    }
                }
                jqsDCCJMG('#' + mediaData.ModuleId + '_dialogEditMedia').dialog({
                    autoOpen: false,
                    bgiframe: true,
                    height: 300,
                    modal: true,
                    overlay: {
                        backgroundColor: '#000',
                        opacity: 0.8
                    },
                    buttons: {
                        Cancel: function() {
                            jqsDCCJMG(this).find('#' + mediaData.ModuleId + '_title').css("border-color", "gray");
                            updateTips("");
                            jqsDCCJMG(this).dialog('close');
                        },
                        'Save': function() {
                            WEBSaveMedia(mediaData.PortalId, mediaData.ModuleId, iMediaIdToMod, title.val(), description.val());
                            jqsDCCJMG(this).dialog('close');

                        }
                    },
                    close: function() {
                        allFields.val('').removeClass('ui-state-error');
                    }
                });
                jqsDCCJMG('div#' + mediaData.ModuleId + '_MediaGallery').find("#dialogDeleteSuccess").dialog({
                    autoOpen: false,
                    bgiframe: true,
                    modal: true,
                    buttons: {
                        Ok: function() {
                            jqsDCCJMG(this).dialog('close');
                        }
                    }
                });
            }
            else {
                jqsDCCJMG('#' + mediaData.ModuleId + '_dialogEditMedia').hide();
                jqsDCCJMG('#' + mediaData.ModuleId + '_dialogDeleteMedia').hide();
            }
            //attaching the prettyphoto to the media
            jqsDCCJMG('div#' + mediaData.ModuleId + '_MediaGallery').find('.dcc_gallery_medialist a[rel^="prettyPhoto"]').prettyPhoto({
                animationSpeed: 'normal', /* fast/slow/normal */
                opacity: strOverlayTransparency, /* Value between 0 and 1 */
                showTitle: true, /* true/false */
                allowresize: true, /* true/false */
                default_width: mediaData.PP_DefaultWidth,
                default_height: mediaData.PP_DefaultHeight,
                counter_separator_label: '/', /* The separator for the gallery counter 1 "of" 2 */
                theme: 'light_rounded', /* light_rounded / dark_rounded / light_square / dark_square / facebook */
                hideflash: false, /* Hides all the flash object on a page, set to TRUE if flash appears over prettyPhoto */
                wmode: 'opaque', /* Set the flash wmode attribute */
                autoplay: true, /* Automatically start videos: True/False */
                modal: false /* If set to true, only the close button will close the window */
            });
            //jqsDCCJMG('a[rel^="prettyPhoto"]').prettyPhoto();
            if (mediaData.TotalPages > 1)
                handlePaging(mediaData.ModuleId, mediaData.PageNo, mediaData.TotalPages, 0);
            else
                handlePaging(mediaData.ModuleId, mediaData.PageNo, mediaData.TotalPages, 1);
        }
        else {
            //nothign to show
            //show msg
            //hidepager
            jqsDCCJMG(ULMedia).html("<span style=\"text-decoration:none; color:#000000;\">No Media Found!</span>");
            if (mediaData.TotalPages > 1)
                handlePaging(mediaData.ModuleId, mediaData.PageNo, mediaData.TotalPages, 0);
            else
                handlePaging(mediaData.ModuleId, mediaData.PageNo, mediaData.TotalPages, 1);
        }

    });

}


function Media(objMedia) {
    this.id = objMedia.MediaID;
    this.title = objMedia.MediaTitle;
    this.desc = objMedia.MediaDescription;
    this.src = objMedia.MediaSrc;
    this.folder = objMedia.FolderID;
    this.type = objMedia.MediaType;
    this.filename = objMedia.MediaOriginalFileName;
    this.sortorder = objMedia.SortOrder;
    this.tooltip = objMedia.Tooltip;
}
function UrlEncode(url) {
    url = url.replace(/\r\n/g, "\n");
    var utftext = "";

    for (var n = 0; n < url.length; n++) {

        var c = url.charCodeAt(n);

        if (c < 128) {
            utftext += String.fromCharCode(c);
        }
        else if ((c > 127) && (c < 2048)) {
            utftext += String.fromCharCode((c >> 6) | 192);
            utftext += String.fromCharCode((c & 63) | 128);
        }
        else {
            utftext += String.fromCharCode((c >> 12) | 224);
            utftext += String.fromCharCode(((c >> 6) & 63) | 128);
            utftext += String.fromCharCode((c & 63) | 128);
        }

    }

    return utftext;
}
function MediaItem(media, prmthmbnlWidth, prmthmbnlHeight, modId) {
    this.id = media.id;
    this.title = media.title;
    this.description = media.desc
    this.sortorder = media.sortorder;
    this.url = media.src;
    this.type = media.type;
    this.src = strMediaPath + media.src;
    this.path = media.src;
    this.galleryId = eval(galleryId);
    var strMediaTemplate = "<img src=\"MTHUMB\" mediaTitle=\"MTITLE\" mediaDesc=\"MDESC\"  width=\"" + prmthmbnlWidth + "px\" height=\"" + prmthmbnlHeight + "px\" style='border: 0px;' tooltip='TOOLTIP' mediaid=\"MEDIAID\" >";
    this.getMediaItem = function() {
        var strMedia = "";
        if (this.type == "1") {
            strMedia = strMediaTemplate.replace(/MTHUMB/g, strModulePath + 'Thumbnail.ashx?image=' + this.path + '&ot=1&pid=' + MediaGallery.PortalId + '&mid=' + MediaGallery.ModuleId).replace(/MTITLE/g, this.title);
        }
        else {
            if (this.type == "2") {
                strMedia = strMediaTemplate.replace(/MTHUMB/g, strModulePath + 'Thumbnail.ashx?gid=' + this.galleryId + '&ot=4&url=' + UrlEncode(this.url) + '&pid=' + MediaGallery.PortalId + '&mid=' + MediaGallery.ModuleId).replace(/MTITLE/g, this.title);
            }
        }
        strMedia = strMedia.replace(/MEDIAID/g, this.id).replace(/TOOLTIP/g, media.tooltip).replace(/MDESC/g, this.description);
        var strfinalMedia = strTemplateMediaThumbNail;
        strfinalMedia = strfinalMedia.replace(/MID/g, this.id).replace(/MTITLE/g, this.title).replace(/MEDIA/g, strMedia).replace(/MODID/g, modId).replace(/MSOURCE/g, strModulePath + 'Thumbnail.ashx?image=' + this.path + '&ot=2&pid=' + MediaGallery.PortalId + '&mid=' + MediaGallery.ModuleId).replace(/MTITLE/g, this.title);
        strfinalMedia = strfinalMedia.replace(/MLSTCLASS/g, 'ui-state-default')
        return strfinalMedia;
    }
}
function AddSpace(title) {
    var index = 0;
    var maxContinuousLength = 15;
    var tempCommentText = title;
    if (maxContinuousLength < title.length) {
        tempCommentText = '';
        while (index < title.length) {
            var subStringSize = maxContinuousLength;
            if ((index + maxContinuousLength) > title.length) {
                subStringSize = title.length - index;
            }
            var subStr = title.substring(index, index + subStringSize);
            var spaceidx = subStr.indexOf(" ");
            if (subStr.length > maxContinuousLength - 1 && (spaceidx == -1 || spaceidx > maxContinuousLength)) {
                tempCommentText += " " + subStr + " ";
            }
            else {
                tempCommentText += subStr;
            }
            index += maxContinuousLength;
        }
    }
    return tempCommentText;
}


function handlePaging(moduleId, thisPageNo, totalPages, hidePager) {

    idlbPrevText = jqsDCCJMG('div#' + moduleId + '_MediaGallery').find('a#PrevText');
    idlbPrevPrevPrevPrev = jqsDCCJMG('div#' + moduleId + '_MediaGallery').find('a#PrevPrevPrevPrev');
    idlbPrevPrevPrev = jqsDCCJMG('div#' + moduleId + '_MediaGallery').find('a#PrevPrevPrev');
    idlbPrevPrev = jqsDCCJMG('div#' + moduleId + '_MediaGallery').find('a#PrevPrev');
    idlbPrev = jqsDCCJMG('div#' + moduleId + '_MediaGallery').find('a#Prev');
    idlbCurrent = jqsDCCJMG('div#' + moduleId + '_MediaGallery').find('span#Current');
    idlbNext = jqsDCCJMG('div#' + moduleId + '_MediaGallery').find('a#Next');
    idlbNextNext = jqsDCCJMG('div#' + moduleId + '_MediaGallery').find('a#NextNext');
    idlbNextNextNext = jqsDCCJMG('div#' + moduleId + '_MediaGallery').find('a#NextNextNext');
    idlbNextNextNextNext = jqsDCCJMG('div#' + moduleId + '_MediaGallery').find('a#NextNextNextNext');
    idlbNextText = jqsDCCJMG('div#' + moduleId + '_MediaGallery').find('a#NextText');
    jqsDCCJMG('div#' + moduleId + '_MediaGallery').find("a").css("color", '#' + strPagingBGColor);

    if (hidePager != 1) {
        idlbCurrent.parents('div.dcc_gallery_mediapager').show();

        if (((thisPageNo - 4) <= 0) || ((thisPageNo - 4) > totalPages)) {
            idlbPrevPrevPrevPrev.hide();
            idlbPrevPrevPrevPrev.parent('li').hide();
        }
        else {
            idlbPrevPrevPrevPrev.show();
            idlbPrevPrevPrevPrev.parent('li').show();
            idlbPrevPrevPrevPrev.html(thisPageNo - 4);
            idlbPrevPrevPrevPrev.data("PageNo", thisPageNo - 4);


        }

        if (((thisPageNo - 3) <= 0) || ((thisPageNo - 3) > totalPages)) {
            idlbPrevPrevPrev.hide();
            idlbPrevPrevPrev.parent('li').hide();
        }
        else {
            idlbPrevPrevPrev.show();
            idlbPrevPrevPrev.parent('li').show();
            idlbPrevPrevPrev.html(thisPageNo - 3);
            idlbPrevPrevPrev.data("PageNo", thisPageNo - 3);

        }

        if (((thisPageNo - 2) <= 0) || ((thisPageNo - 2) > totalPages)) {
            idlbPrevPrev.hide();
            idlbPrevPrev.parent('li').hide();

        }
        else {
            idlbPrevPrev.show();
            idlbPrevPrev.parent('li').show();
            idlbPrevPrev.html(thisPageNo - 2);
            idlbPrevPrev.data("PageNo", thisPageNo - 2);


        }

        if (((thisPageNo - 1) <= 0) || ((thisPageNo - 1) > totalPages)) {
            idlbPrev.hide();
            idlbPrev.parent('li').hide();
            idlbPrevText.hide();
            idlbPrevText.parent('li').hide();
        }
        else {
            idlbPrev.show();
            idlbPrev.parent('li').show();
            idlbPrevText.show();
            idlbPrevText.parent('li').show();
            idlbPrev.html(thisPageNo - 1);
            idlbPrev.data("PageNo", thisPageNo - 1);

        }

        if ((thisPageNo <= 0) || (thisPageNo > totalPages)) {
            idlbCurrent.hide();
            idlbCurrent.parent('li').hide();
        }
        else {
            idlbCurrent.show();
            idlbCurrent.parent('li').show();
            idlbCurrent.html(thisPageNo);
            idlbCurrent.data("PageNo", thisPageNo);

        }

        if ((thisPageNo + 1) <= 0 || (thisPageNo + 1) > totalPages) {
            idlbNext.hide();
            idlbNext.parent('li').hide();

            idlbNextText.hide();
            idlbNextText.parent('li').hide();

        }
        else {
            idlbNext.show();
            idlbNext.parent('li').show();

            idlbNextText.show();
            idlbNextText.parent('li').show();

            idlbNext.html(thisPageNo + 1);
            idlbNext.data("PageNo", thisPageNo + 1);

        }



        if (((thisPageNo + 2) <= 0) || ((thisPageNo + 2) > totalPages)) {
            idlbNextNext.hide();
            idlbNextNext.parent('li').hide();

        }
        else {
            idlbNextNext.show();
            idlbNextNext.parent('li').show();

            idlbNextNext.html(thisPageNo + 2);
            idlbNextNext.data("PageNo", thisPageNo + 2);
        }

        if (((thisPageNo + 3) <= 0) || ((thisPageNo + 3) > totalPages)) {
            idlbNextNextNext.hide();
            idlbNextNextNext.parent('li').hide();

        }
        else {
            idlbNextNextNext.show();
            idlbNextNextNext.parent('li').show();

            idlbNextNextNext.html(thisPageNo + 3);
            idlbNextNextNext.data("PageNo", thisPageNo + 3);
        }

        if (((thisPageNo + 4) <= 0) || ((thisPageNo + 4) > totalPages)) {
            idlbNextNextNextNext.hide();
            idlbNextNextNextNext.parent('li').hide();

        }
        else {
            idlbNextNextNextNext.show();
            idlbNextNextNextNext.parent('li').show();

            idlbNextNextNextNext.html(thisPageNo + 4);
            idlbNextNextNextNext.data("PageNo", thisPageNo + 4);
        }

        idlbPrevText.data("PageNo", thisPageNo - 1);
        idlbNextText.data("PageNo", thisPageNo + 1);
    }
    else {
        idlbCurrent.parents('div.dcc_gallery_mediapager').hide();


    }
}


//every external Javascript file that is being referenced from ScriptManager must have a call to Sys.Application.
if (typeof (Sys) !== "undefined") Sys.Application.notifyScriptLoaded();

