﻿MSDImages.Utils = {

    /*
    * Show/Hide advanced search options
    */
    ToggleAdvancedSearch: function(a, more, less) {
        var adv = Ext.get('sf-advanced');
        if (a.innerHTML === more) {
            if (Ext.isIE) { adv.setVisible(true); }
            else { adv.slideIn('t'); }
            a.innerHTML = less;
        }
        else {
            if (Ext.isIE) { adv.setVisible(false); }
            else { adv.slideOut('t'); }
            a.innerHTML = more;
        }

        try { a.blur(); } catch (e) { }
        return false;
    },


    /*
    * Generic popup window
    * url : url of content to load into window
    * title : window title
    * width, height : window dimensions (will be constrained to browser window)
    * src : element window opened from - enables open/close animation
    */
    OpenWindow: function(url, title, width, height, src) {
        var w = width;
        var h = height;
        var vp = Ext.getCmp('viewport');

        if (vp) {
            var max = vp.getSize();
            max.width -= 50;
            max.height -= 50;
            w = (w > max.width) ? max.width : w;
            h = (h > max.height) ? max.height : h;
        }

        var win = new Ext.Window({
            maximizable: false,
            title: title,
            width: w,
            height: h,
            autoScroll: true,
            closable: true,
            closeAction: 'close',
            modal: true,
            plain: true,
            constrain: true,
            autoLoad: url
        });
        win.show(src);
        return false;
    },

    /*
    *	Log an action.
    * Generic method to easily swap log provider
    *	action : name of action to log (e.g. 'ViewImage')
    * [value] : optional action value (e.g. ImageId)
    */
    Log: function(action, value) {
        return this.log_GoogleAnalytics(action, value);
    },

    log_GoogleAnalytics: function(action, value) {
        try {
            var s = (arguments.length === 2 && value.toString() !== 'undefined') ? action + '/' + value : action;
            pageTracker._trackPageview(s);
        }
        catch (e) { }
        return true;
    },

    /*
    * Returns first instance of 'key' in querystring
    */
    GetQueryStringValue: function(key) {
        var matches = new RegExp(key + '[:|=]([^&]+)').exec(location.search);
        return (matches && matches.length > 1) ? decodeURIComponent(matches[1]).replace('+', ' ') : '';
    },

    /*
    * Message alert singleton
    * usage: Images.Utils.Message.show(message) or Images.Utils.Message.show(message, title)
    */
    Message: function() {
        var msgCt;

        function createBox(t, s) {
            return ['<div class="msg">',
				'<div class="x-box-tl"><div class="x-box-tr"><div class="x-box-tc"></div></div></div>',
				'<div class="x-box-ml"><div class="x-box-mr"><div class="x-box-mc"><h3>', t,
				'</h3>', s, '</div></div></div>',
				'<div class="x-box-bl"><div class="x-box-br"><div class="x-box-bc"></div></div></div>',
				'</div>'].join('');
        }

        return {
            show: function(text, title) {
                if (!msgCt) {
                    msgCt = Ext.DomHelper.insertFirst(document.body, { id: 'message-box' }, true);
                }
                var msgTitle = (arguments.length === 1) ? 'Information' : title;
                msgCt.alignTo(document, 't-t');
                var m = Ext.DomHelper.append(msgCt, { html: createBox(msgTitle, text) }, true);
                m.slideIn('t').pause(3).ghost("t", { remove: true });
            }
        };
    } (),

    /*
    * Reusable year and month stores
    */
    DateStores: function() {
        var months = [['', 'Month']];
        for (var m = 1; m < 13; m++) {
            months.push([m, Date.monthNames[m - 1]]);
        }

        var years = [['', 'Year']];
        for (var y = new Date().getFullYear(); y >= 1900; y--) {
            years.push([y, y]);
        }

        var monthStore = new Ext.data.SimpleStore({
            fields: ['val', 'desc'],
            data: months
        });

        var yearStore = new Ext.data.SimpleStore({
            fields: ['val', 'desc'],
            data: years
        });

        return {
            Years: yearStore,
            Months: monthStore
        };
    } (),

    /*
    * Expand/Collapse an element
    * elId : DOM Id of block level element
    * link : DOM object displaying more/less text
    * class "toggle-more-less" needs to set collapsed height and overflow:hidden.
    */
    toggleMoreLess: function(elId, link) {
        var el = Ext.get(elId);
        if (!el.hasClass('toggle-more-less')) {
            el.addClass('toggle-more-less');
            link.innerHTML = 'more &#x2026;';
        }
        else {
            el.removeClass('toggle-more-less');
            link.innerHTML = 'less &#x2026;';
        }
        link.blur();
        return false;
    },

    showFigure: function(o, link, rating, imageid, data, numberOfVotes, resultIndex) {

        MSDImages.Utils.Log('Large Figure View', imageid);

        var previousId, nextId;

        //if a result index is passed, previous and next buttons are needed
        if (resultIndex != null) {
            if (resultIndex > 1) {
                previousId = resultIndex - 2;
            }
            if (resultIndex < 20) {
                nextId = resultIndex;
            }
        }

        var figure = link.substring(link.lastIndexOf('/') + 1);

        //close existing window first
        var figWin = Ext.getCmp('figureWin');
        if (figWin) {
            figWin.close();
        }

        //default size
        var winWidth = 850; //-40
        var winHeight = 800; //-60

        //shrink to fit window
        var size = Ext.getBody().getViewSize();
        if (size['width'] < winWidth) winWidth = size['width'];
        if (size['height'] < winHeight) winHeight = size['height'];

        figureWin = new Ext.Window({
            id: 'figureWin',
            layout: 'fit',
            title: 'Image details',
            width: winWidth - 10,
            height: winHeight - 60,
            autoScroll: true,
            tbar: new Ext.Toolbar(),
            closeAction: 'close',
            modal: true,
            plain: true,
            constrain: true,
            html: '<div id="figureContent"><p class="loading-indicator">Loading</p></div>',
            autoLoad: link
        });

        //make top toolbar
        var figWinTbar = figureWin.getTopToolbar();

        //if there is a previous button
        if (previousId != null) {
            figWinTbar.addButton([{
                text: 'Previous Image',
                cls: 'x-btn-text-icon',
                icon: '/content/interface_images/icons/previous.png',
                handler: function() {
                MSDImages.Utils.showFigure(o, '/image/popup/' + Results[previousId].id, Results[previousId].rating, Results[previousId].id, Results[previousId], Results[previousId].numberOfVotes, previousId + 1);
                }
}]);
            }

            //add email button
            figWinTbar.addButton([{
                text: 'Email this image',
                cls: 'x-btn-text-icon',
                icon: '/content/interface_images/icons/email.png',
                handler: function() {

                    var idprefix = 'email';
                    Ext.fly('emailContainer').removeClass('windowContainer');
                    var emailWin = new Ext.Window({
                        layout: 'fit',
                        title: "Email image",
                        maximizable: false,
                        width: 320,
                        height: 400,
                        autoScroll: true,
                        closeAction: 'hide',
                        modal: true,
                        plain: true,
                        buttonAlign: 'left',
                        contentEl: 'emailContainer',
                        buttons: [{
                            text: 'Send email',
                            cls: 'x-btn-text-icon',
                            icon: '/content/interface_images/icons/email.png',
                            handler: function(btn) {
                                Ext.fly('lblEmailMessage').removeClass('help-error');
                                Ext.fly('lblEmailFrom').removeClass('help-error');
                                Ext.fly('lblEmailTo').removeClass('help-error');

                                var from = Ext.fly('emailFromAddress').getValue();
                                var to = Ext.fly('emailToAddress').getValue();
                                var msg = Ext.fly('emailMessage').getValue();

                                var error = '';

                                if (msg == '') {
                                    Ext.fly('lblEmailMessage').addClass('help-error');
                                    error = lang.email_message + '<br/>';
                                }
                                //		                    if (!globals.emailRegex.test(from)) {
                                //		                        Ext.fly('lblEmailFrom').addClass('help-error');
                                //		                        error += lang.email_invalid_from + '<br/>';
                                //		                    }
                                //		                    if (!globals.emailRegex.test(to)) {
                                //		                        Ext.fly('lblEmailTo').addClass('help-error');
                                //		                        error += lang.email_invalid_to;
                                //		                    }

                                if (error != '') {
                                    Ext.fly('emailError').update(error);
                                    return;
                                }


                                btn.disable();
                                Ext.fly('emailLoading').show();
                                Ext.fly('emailError').update('');

                                var conn = new Ext.data.Connection();
                                conn.request({
                                    url: '/image/EmailImage',
                                    params: { "ImageId": figure, "from": from, "to": to, "message": msg },
                                    success: function(data) {
                                        Ext.fly('email-form').setDisplayed(false);
                                        Ext.fly('emailLoading').setDisplayed(false);
                                        Ext.fly('email-confirm').setDisplayed(true);
                                        MSDImages.Utils.Log('Image Emailed', imageid);
                                    },
                                    failure: function() {
                                        Ext.fly('emailError').update(lang.email_error);
                                        Ext.fly('emailLoading').setDisplayed(false);
                                        btn.enable();
                                    }
                                });

                            }
}]
                        });
                        emailWin.show();
                        try {
                            Ext.fly('email-form').setDisplayed(true);
                            Ext.fly('email-confirm').setDisplayed(false);
                            if (user.email) {
                                Ext.fly('emailFromAddress').dom.value = user.email;
                            }
                            Ext.fly('emailError').update('');
                            Ext.fly('lblEmailMessage').removeClass('help-error');
                            Ext.fly('lblEmailFrom').removeClass('help-error');
                            Ext.fly('lblEmailTo').removeClass('help-error');
                        }
                        catch (e) { }
                    }
}]);

                    //Add "add image to collection" button
                    if (MSDImages.Config.loggedIn && data != null) {
                        figWinTbar.addSpacer();

                        figWinTbar.addButton([{
                            text: 'Add image to set',
                            cls: 'x-btn-text-icon',
                            icon: '/content/interface_images/icons/add.png',
                            handler: function(b, e) {
                                Ext.getCmp('ImageSets').addImage(data);
                                b.setDisabled(true);
                            }
}]);
                        }

                        //add stars
                        figWinTbar.addSpacer();
                        figWinTbar.addSpacer();

                        //label for stars
                        var starLabel = new Ext.Toolbar.TextItem({ xtype: 'tbtext', text: 'Please rate this image' });
                        figWinTbar.add(starLabel);
                        if (!MSDImages.Config.loggedIn) {
                            starLabel.setText('Image rating');
                        }

                        var stars = new Ext.ux.StarRating({
                            id: 'stars',
                            totalStars: 5,
                            average: rating
                        });

                        stars.on('rate', function(o, vote) {
                            if (MSDImages.Config.loggedIn) {
                                var conn = new Ext.data.Connection();
                                conn.request({
                                    url: '/image/AddRating',
                                    params: { "imageId": imageid, "rating": vote },
                                    success: function(data) {
                                        stars.average = data.responseText;
                                        stars.resetStars();
                                        starLabel.setText('Thanks for your vote');

                                        numberOfVotes = numberOfVotes + 1;
                                        numberOfVotesLabel.setText('(' + numberOfVotes + ' votes)');

                                        MSDImages.Utils.Log('Image Rated', imageid);
                                    },
                                    failure: function() {
                                        Ext.Msg.alert('Not signed in', 'Please sign in to rate this image');
                                    }
                                });
                            } else {
                                Ext.Msg.alert('Not signed in', 'Please sign in to rate images');
                            }
                        });

                        figWinTbar.add(stars);



                        //label for number of votes
                        var numberOfVotesLabel;
                        if (numberOfVotes != null && numberOfVotes != 0) {
                            numberOfVotesLabel = new Ext.Toolbar.TextItem({ xtype: 'tbtext', text: '(' + numberOfVotes + ' votes)' });
                            figWinTbar.add(numberOfVotesLabel);
                        }

                        //if there is a next button
                        if (nextId != null) {
                            figWinTbar.addButton([{
                                text: 'Next Image',
                                cls: 'x-btn-text-icon',
                                icon: '/content/interface_images/icons/next.png',
                                handler: function() {
                                MSDImages.Utils.showFigure(o, '/image/popup/' + Results[nextId].id, Results[nextId].rating, Results[nextId].id, Results[nextId], Results[nextId].numberOfVotes, nextId + 1);
                                }
}]);
                            }

                            figureWin.show();

                            return false;

                        }

                    };

