﻿/// <reference name="MicrosoftAjax.js"/>



Type.registerNamespace("TipsCommunity");



TipsCommunity.ImageViewer = function(element) {
    TipsCommunity.ImageViewer.initializeBase(this, [element]);
    this._$element = $(element);
    this._firstTimeSelectedImageChangedNotification = true;
}
TipsCommunity.ImageViewer.prototype = {
    initialize: function()
    {
        TipsCommunity.ImageViewer.callBaseMethod(this, 'initialize');
        // Don't do anything until the page have loaded to be sure that internal ImageSlider is initialized
        Sys.Application.add_load(Function.createDelegate(this, this.load));
    },
    load: function(sender, args)
    {
        if (args.get_isPartialLoad())
        {
            return;
        }

        // Check on possible URI-fragment if the ImageSlider should be loaded based on a specific image ID
        if (window.location.hash && window.location.hash != null)
        {
            var arr = /#imageID=([\d]*)/.exec(window.location.hash);
            if (arr != 'undefined' && arr != null && arr.length > 1)
            {
                this.get_imageSlider().set_startupPositionIdentifier(arr[1]);
            }
        }
        
        // Bind to ImageSlider events and kick it off!
        var imageSliderControl = this.get_imageSlider();
        imageSliderControl.add_selectedImageChanging(Function.createDelegate(this, this.imageSliderSelectedImageChanging));
        imageSliderControl.add_selectedImageChanged(Function.createDelegate(this, this.imageSliderSelectedImageChanged));
        imageSliderControl.add_imageRetrievalFailed(Function.createDelegate(this, this.imageSliderImageRetrievalFailed));
        imageSliderControl.start();
    },
    imageSliderSelectedImageChanging: function(sender, args)
    {
        // TODO: Consider adding a fadeout of the current image here
    },
    imageSliderSelectedImageChanged: function(sender, args)
    {
        var 
            $imageInfoDiv = this._$element.find('div.image-info'),
            currentStarImageControl = this.get_imageSlider().get_currentImage().control;

        if (this.get_displayMode() == 'Small')
        {
            $imageInfoDiv.find('img').attr('src', currentStarImageControl.get_UploaderAvatarImageUrl()).attr('title', currentStarImageControl.get_UploaderAlias());
            $imageInfoDiv.find('a').attr('href', currentStarImageControl.get_UploaderRemoved() ? 'javascript:void(0)' : currentStarImageControl.get_UploaderProfilePageUrl()).attr('title', currentStarImageControl.get_UploaderAlias()).text(currentStarImageControl.get_UploaderAlias());
            $imageInfoDiv.find('span.date').text(currentStarImageControl.get_UploadDate());
        }
        else
        {
            $imageInfoDiv.find('h2').html(currentStarImageControl.get_Name()).ensureMaxLength(50, "...");
        }

        $imageInfoDiv.attr('title', String.format('{0} ({1})', currentStarImageControl.get_Name() == '' ? globalResourceTextInstance.tipsImageTitleMissing : currentStarImageControl.get_Name(), this.get_displayMode() == 'Small' ? globalResourceTextInstance.tipsEnlargeImage : globalResourceTextInstance.tipsShowNextImage));
        $imageInfoDiv.css('background-image', String.format('url({0})', this._$element.hasClass('image-viewer-635') ? currentStarImageControl.get_ImageUrlHuge() : currentStarImageControl.get_ImageUrlLarge()));
        $imageInfoDiv.find('div.background').fadeTo('normal', 0.70);
        $imageInfoDiv.find('div.inner').fadeIn('normal');
        scheduleMethodInvocation(this, 'TipsCommunity.ImageViewer.scheduledImageInfoFadeOut', 3000, this.get_id());
        
        if (this.get_firstTimeSelectedImageChangedNotification())
        {
            // This is the first time the imageSliderSelectedImageChanged gets called - do initilizing stuff
            this._$element.find('div.image-info').hover( Function.createDelegate(this, this.imageInfoMouseOver), Function.createDelegate(this, this.imageInfoMouseOut) );
            this._$element.find('div.image-info a').click( Function.createDelegate(this, function (e) { e.preventDefault(); e.stopPropagation(); if (!currentStarImageControl.get_UploaderRemoved()) { window.location.href = e.target.href; } }) );
            if (this.get_displayMode() == 'Small')
            {
                // Clicking the image should redirect you to the large ImageViewer
                this._$element.find('div.image-info').click( Function.createDelegate(this, function() { window.location.href = String.format('{0}#imageID={2}', this.get_baseUrlLargerImageView(), this.get_imageSlider().get_ajaxHandlerImageSourceIdentifiers()["ImageSourceID"], this.get_imageSlider().get_currentImage().control.get_ID()); }) );
            }
            else
            {
                // Clicking the image should be equivalent to clicking the "next" button
                this._$element.find('div.image-info').click( Function.createDelegate(this, function() { this._$element.find('div.button-next').trigger('click'); }));
            }
            this.set_firstTimeSelectedImageChangedNotification(false);
        }
        else
        {
            // Add the latest selected image to browser history
            var historyPointName = currentStarImageControl.get_ImageGalleryName() + ': ';
            if (currentStarImageControl.get_Name() == null || currentStarImageControl.get_Name() == '')
            {
                historyPointName += globalResourceTextInstance.tipsImageLowerCase + ' ' + currentStarImageControl.get_ID();
            }
            else
            {
                historyPointName += currentStarImageControl.get_Name();
            }
            Sys.Application.addHistoryPoint({ 'imageID' : currentStarImageControl.get_ID() }, historyPointName);
        }
    },
    imageSliderImageRetrievalFailed: function(sender, args)
    {
        // Initialize ImageViewer to display empty content
        this.addCssClass('image-viewer-fallback');
        this._$element.find('div.image-info').css('background-image', String.format('url({0})', this.get_fallbackBackgroundImageUrl())).click(Function.createDelegate(this, function() { window.location.href = this.get_fallbackRegisterImageGalleryUrl(); }));
    },
    imageInfoMouseOver: function(e)
    {
        var $imageInfoDiv = this._$element.find('div.image-info');
        $imageInfoDiv.find('div.background').fadeTo('normal', 0.70);
        $imageInfoDiv.find('div.inner').fadeIn('normal');
    },
    imageInfoMouseOut: function(e)
    {
        var $imageInfoDiv = this._$element.find('div.image-info');
        $imageInfoDiv.find('div.background').fadeTo('normal', 0.00);
        $imageInfoDiv.find('div.inner').fadeOut('normal');
    },
    get_fallbackBackgroundImageUrl: function()
    {
        return this._fallbackBackgroundImageUrl;
    },
    set_fallbackBackgroundImageUrl: function(value)
    {
        this._fallbackBackgroundImageUrl = value;
    },
    get_fallbackRegisterImageGalleryUrl: function()
    {
        return this._fallbackRegisterImageGalleryUrl;
    },
    set_fallbackRegisterImageGalleryUrl: function(value)
    {
        this._fallbackRegisterImageGalleryUrl = value;
    },
    get_baseUrlLargerImageView: function()
    {
        return this._baseUrlLargerImageView;
    },
    set_baseUrlLargerImageView: function(value)
    {
        this._baseUrlLargerImageView = value;
    },
    get_displayMode: function()
    {
        return this._displayMode;
    },
    set_displayMode: function(value)
    {
        this._displayMode = value;
    },
    get_imageSlider: function()
    {
        return this._imageSlider;
    },
    set_imageSlider: function(value)
    {
        this._imageSlider = value;
    },
    get_firstTimeSelectedImageChangedNotification: function()
    {
        return this._firstTimeSelectedImageChangedNotification;
    },
    set_firstTimeSelectedImageChangedNotification: function(value)
    {
        this._firstTimeSelectedImageChangedNotification = value;
    }
}
TipsCommunity.ImageViewer.registerClass('TipsCommunity.ImageViewer', Sys.UI.Control);



/* Large ImageViewer */
TipsCommunity.ImageViewerLarge = function(element) {
    TipsCommunity.ImageViewerLarge.initializeBase(this, [element]);
}
TipsCommunity.ImageViewerLarge.prototype = {
    initialize: function()
    {
        TipsCommunity.ImageViewerLarge.callBaseMethod(this, 'initialize');
        this._$element.find('table.commands a.show-add-comment-dialog').click( Function.createDelegate(this, this.showAddCommentDialogClick) );
        this._$element.find('table.commands a.show-report-abuse-dialog').click( Function.createDelegate(this, this.showReportAbuseDialogClick) );
    },
    imageSliderSelectedImageChanged: function (sender, args) {        
        TipsCommunity.ImageViewerLarge.callBaseMethod(this, 'imageSliderSelectedImageChanged', [sender, args]);
        
        TUI.TipsCommunity.Templates.AjaxHandlers.Util.GetStarImageComments(this.get_imageSlider().get_currentImage().control.get_ID(), Function.createDelegate(this, this.onCommentsChanged));
        
        // Replace the imageID with the current image
        var $enlargeLink = this._$element.find('table.commands a.enlarge');
        var href = $enlargeLink.attr('href');
        var regexImageID = new RegExp(/imageID=([^&]*)/);
        if (href.match(regexImageID))
        {
            href = href.replace
            (
                regexImageID,
                Function.createDelegate(this, function (param1, param2) {  return param1.replace(param2, this.get_imageSlider().get_currentImage().control.get_ID()); })
            );
            $enlargeLink.attr('href', href);
        }
    },
    showAddCommentDialogClick: function(e) {
        e.preventDefault();
        e.stopPropagation();
        var dialog = this.setupAndShowDialog('add-comment-dialog-template', 'add-comment-dialog form', this.addCommentClick);
        $(dialog.get_element()).keypress( Function.createDelegate(this, function(e) { if (e.keyCode == Sys.UI.Key.enter && e.target.tagName.toLowerCase() != 'textarea') { this.addCommentClick(e); } }) );
    },
    showReportAbuseDialogClick: function(e) {
        e.preventDefault();
        e.stopPropagation();
        var dialog = this.setupAndShowDialog('report-abuse-dialog-template', 'report-abuse-dialog form', this.sendAbuseReportClick);
        $(dialog.get_element()).keypress( Function.createDelegate(this, function(e) { if (e.keyCode == Sys.UI.Key.enter && e.target.tagName.toLowerCase() != 'textarea') { this.sendAbuseReportClick(e); } }) );
    },
    setupAndShowDialog: function(targetTemplateCss, cssClasses, okHandler) 
    {
        var
            dialogProperties =
            {
                'innerHtmlCenter' : this._$element.find('.' + targetTemplateCss).html(),
                'showOverlay' : true
            },
            dialog = TUI.Web.UI.WebControls.Dialog.createNewGlobalDialog(dialogProperties, cssClasses),
            $dialog = $(dialog.get_element());

        if (okHandler)
        {            
            $dialog.find('.button-ok').click( Function.createDelegate(this, okHandler) );
        }
        
        $dialog.find('.button-cancel').click( function() { TUI.Web.UI.WebControls.Dialog.getCurrentGlobalDialog().hide(); } );
        dialog.show();
        $dialog.find('input.textbox').focus();
        
        return dialog;
    },
    addCommentClick: function(e) {
        e.preventDefault();
        
        var
            addCommentDialog = TUI.Web.UI.WebControls.Dialog.getCurrentGlobalDialog();
            $addCommentDialog = $(addCommentDialog.get_element()),
            commentTitle = $addCommentDialog.find('input.textbox').val(),
            commentContent = $addCommentDialog.find('textarea').val(),
            validationSuccess = true;
        
        $addCommentDialog.find('span.validator').css('display', 'none');
        
        if (commentTitle.length == 0)
        {
            $addCommentDialog.find('span.validator-comment-heading').css('display', 'block');
            validationSuccess = false;
        }
            
        if (commentContent.length == 0)
        {
            $addCommentDialog.find('span.validator-comment-body').css('display', 'block');
            validationSuccess = false;            
        }

        if (validationSuccess)
        {
            addCommentDialog.hide();
            TUI.TipsCommunity.Templates.AjaxHandlers.Util.AddStarImageComment(commentTitle, commentContent, this.get_imageSlider().get_currentImage().control.get_ID(), Function.createDelegate(this, this.onCommentsChanged));
        }
    },
    sendAbuseReportClick: function(e) {
        e.preventDefault();

        var 
            reportAbuseDialog = TUI.Web.UI.WebControls.Dialog.getCurrentGlobalDialog();
            $reportAbuseDialog = $(reportAbuseDialog.get_element()),
            reportEmail = $reportAbuseDialog.find('input.textbox').val(),
            reportContent = $reportAbuseDialog.find('textarea').val(),
            validationSuccess = true;
        
        $reportAbuseDialog.find('span.validator').css('display', 'none');
        reportEmail = typeof(reportEmail) == 'undefined' ? null : reportEmail;
        
        if (reportEmail != null)
        {
            if (reportEmail == '')
            {
                $reportAbuseDialog.find('span.validator-email-required').css('display', 'block');
                validationSuccess = false;
            }
            else if (!reportEmail.match(/.*@.*\..*/))
            {
                $reportAbuseDialog.find('span.validator-email-format').css('display', 'block');
                validationSuccess = false;
            }
        }
        
        if (reportContent == '' || reportContent == null)
        {
            $reportAbuseDialog.find('span.validator-content-required').css('display', 'block');
            validationSuccess = false;
        }
        
        if (validationSuccess)
        {
            reportAbuseDialog.hide();
            TUI.TipsCommunity.Templates.AjaxHandlers.Util.ReportAbuse(reportContent, reportEmail, this.get_imageSlider().get_currentImage().control.get_ID(), Function.createDelegate(this, this.reportSentCallback), Function.createDelegate(this, this.reportFailedCallback));
        }
    },
    add_commentsChanged: function(handler) { this.get_events().addHandler('commentsChanged', handler); },
    remove_commentsChanged: function(handler) { this.get_events().removeHandler('commentsChanged', handler); },
    onCommentsChanged: function(result) {
        var comments = Sys.Serialization.JavaScriptSerializer.deserialize(result);
        var handler = this.get_events().getHandler('commentsChanged');
        if (handler) handler(this, new TipsCommunity.CommentCommandEventArgs(comments));
    },
    reportSentCallback: function(result) {
        var dialog = this.setupAndShowDialog('report-abuse-result-dialog-template', 'form');
        $(dialog.get_element()).find('p').html(result);
    },
    reportFailedCallback: function() {        
        var dialog = this.setupAndShowDialog('report-abuse-result-dialog-template', 'form');
        $(dialog.get_element()).find('p').html(globalResourceTextInstance.tipsCommonError);
    }
}
TipsCommunity.ImageViewerLarge.registerClass('TipsCommunity.ImageViewerLarge', TipsCommunity.ImageViewer);



/* Comment command event args */
TipsCommunity.CommentCommandEventArgs = function(comments) {
    TipsCommunity.CommentCommandEventArgs.initializeBase(this);
    this.set_comments(comments);
}
TipsCommunity.CommentCommandEventArgs.prototype = {
    initialize: function() {
        TipsCommunity.CommentCommandEventArgs.callBaseMethod(this, 'initialize');
    },
    dispose: function() {
        TipsCommunity.CommentCommandEventArgs.callBaseMethod(this, 'dispose');
    },
    get_comments: function() { return this._comments; },
    set_comments: function(value) { this._comments = value; }
}
TipsCommunity.CommentCommandEventArgs.registerClass('TipsCommunity.CommentCommandEventArgs', Sys.EventArgs);



/* ImageViewer global functions */
TipsCommunity.ImageViewer.scheduledImageInfoFadeOut = function(clientID)
{
    var
        thisRef = $get(clientID).control,
        $imageInfoDiv = $(thisRef.get_element()).find('div.image-info');
        
    $imageInfoDiv.find('div.background').fadeTo('slow', 0.00);
    $imageInfoDiv.find('div.inner').fadeOut('slow');
}



if (typeof(Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();

