/**
 * @author jwhitcraft
 */

var STARBAR_IMG_ROOT = "/images/stars/";
var TAG_LINK = "designitViewTagLink";
var forcePgRefresh =false;
function saveRating(path) {
    Ext.Ajax.request({
        url: path,
        callback: function(opt, is_success, o) {
            data = Ext.decode(o.responseText);
            if(data.total_ppl == 1) {
                var per = data.total_ppl + " person";
            } else {
                var per = data.total_ppl + " people";
            }
            Ext.fly("ratingdsp_" + data.item_id + "_" + data.type_id).update("<strong>Rating:</strong> " + data.dsp_rating + " by " + per);
        }
    })
}

Ext.namespace('Ext.IMS.Centennial');
Ext.IMS.Centennial = function(){

    var lastyear = null;
    var cfilter = null;
    var sections = [];

    var opencontainer = null;

    function beforeOpen(obj) {
        if(opencontainer != null) {
            opencontainer.close();
            opencontainer = null;
        }
    }

    function open(obj) {
        opencontainer = obj;
    }

    function processKeywordInput(e)
    {
        var v = Ext.fly('s_keyword').getValue();
        var re = new RegExp('([0-9]{4})');
        var m = re.exec(v);
        if(m == null) {
            _setFilter(v);
            Ext.History.add(0 + ':' + v);
        } else if(m != null) {
            v = v.replace(re, '').replace(/^\s+|\s+$/g,'');
            _setFilter(v);
            Ext.History.add(m[0] + ':' + v);
        }
    }

    function _setFilter(filter)
    {
        if(filter != cfilter) {
            Ext.each(sections, function(item, index, allItems) {
                item.setFilter(filter);
            }, this);
        }
    }


    return {
        init: function(){
            var items = Ext.fly('centennialContent').query('div.section');
            Ext.each(items, function(item, index, allItems){
                switch (item.id) {
                    case 'statsContainer':
                    case 'newsContainer':
                        toLoad = 8;
                        break;
                    case 'communityContainer':
                        toLoad = 2;
                        break;
                    default:
                        toLoad = 6;
                        break;
                }

                sections[index] = new Ext.IMS.Centennial.Section(item.id, toLoad);

                sections[index].on('beforeopen', beforeOpen, this);
                sections[index].on('open', open, this);

                if (item.id == 'photosContainer') {
                    sections[index].on('load', function(){
                        Ext.IMS.Centennial.photowin.initItemClick();
                    });

                    sections[index].on('beforeload', function(){
                        Ext.IMS.Centennial.photowin.removeItemClick();
                        return true;
                    });
                } else if (item.id == 'communityContainer') {
                    sections[index].on('load', function(){
                        Ext.IMS.Centennial.communitywin.initItemClick();
                        new Ext.ux.RatingDetails("communityContainer");
                    });

                    sections[index].on('beforeload', function(){
                        Ext.IMS.Centennial.communitywin.removeItemClick();
                        return true;
                    });
                }
            }, this);

            Ext.fly('s_button').on('click', processKeywordInput, this, {stopEvent: true});
            Ext.fly('s_keyword').on('keypress', function(evt){
                if(evt.getKey() == evt.ENTER) {
                    evt.stopEvent();
                    processKeywordInput(evt);
                }
            }, this)

            // setup the history
            // Handle this change event in order to restore the UI to the appropriate history state
            Ext.History.on('change', function(token){
                if (token) {
                    var parts = token.split(':');
                    if(parts[1]) {
                        lastyear = -1;
                        this.setFilter(parts[1]);
                        this.loadYear(parts[0]);
                    } else if(parts[0] != 0) {
                        this.setFilter('');
                        this.loadYear(parts[0]);
                    }
                }
            }, this);

            Ext.History.init(this.onHistory, this);

        },

        onHistory: function(hist) {
            var token = hist.getToken();
            if(token !== null) {
                var parts = token.split(':');
                if(parts[1]) {
                    this.setFilter(parts[1]);
                    this.loadYear(parts[0]);
                } else if(parts[0] != 0) {
                    this.setFilter('');
                    this.loadYear(parts[0]);
                }
            }
        },

        passYearToFlash: function(task) {
            try {
                Ext.fly('centennialslider').dom.setYearFromHtml(lastyear);
            } catch(e) {
                task.delay(50);
            }
        },

        setFilter : function(filter) {
            _setFilter(filter);
        },

        loadYear: function(year){
            if(Ext.fly("centennial_layout").hasClass("displayNone")) {
                Ext.fly("centennial_layout").removeClass("displayNone");
                Ext.fly("community_layout").addClass("displayNone");
            }
            if (year != "" && lastyear != year) {
                lastyear = year;

                var dt = new Ext.util.DelayedTask();
                dt.delay(50, this.passYearToFlash, this, [dt]);

                Ext.each(sections, function(item, index, allItems) {
                    item.load(year);
                }, this);
            }
        }
    }
}();


Ext.IMS.Centennial.photowin = new Ext.ux.Windows("photosReplace", "img.dsp_photo", null, "Photo");
Ext.IMS.Centennial.communitywin = new Ext.ux.Windows("communityReplace", "img.comm_image", ".comm_comments a", "Community");

Ext.IMS.Centennial.spinner = new Ext.Template(
       '<img src="/images/centennial/search/loading-icon.gif" class="loading_icon" width="32" height="32" id="{id}" />'
    );
Ext.IMS.Centennial.shadow = new Ext.Shadow({mode: 'frame'});

Ext.IMS.Centennial.Section = function(section, initialDisplay){

    this.section = section.replace('Container', '');
    this.el = Ext.get(section);
    this.contentEl = Ext.get(this.el.query('div.container')[0]);
    this.orginalContent = null;
    this.initialDisplay = initialDisplay || 6;
    this.loadedYear = 0;
    this.canexpand = false;
    this.filter = null;

    this.el.child('div.section_header a.more_link').on('click', this.expandlink, this, {stopEvent: true});
    this.el.child('div.section_header a.more_link').hide();

    Ext.fly(this.section + 'Nav').child('a').on('click', this.navLink, this, {stopEvent: true});

    this.addEvents({
        'beforeload' : true,
        'load': true,
        'beforeopen' : true,
        'open' : true,
        'beforeclose' : true,
        'close' : true
    });
}

Ext.extend(Ext.IMS.Centennial.Section, Ext.util.Observable, {

    setFilter : function(filter, doLoad) {
        this.filter = filter;
    },
    navLink : function(e, obj) {
        window.scroll(0, this.el.getTop());
        if(this.canexpand) {
            this.open();
        } else {
            this.fireEvent('beforeopen', this);
        }
    },

    close : function() {
        if(this.contentEl.hasClass('expanded')) {
            this._expandlink(this.el.child('div.section_header a.more_link'));
        }
    },

    open : function() {
        if(!this.contentEl.hasClass('expanded')) {
            this._expandlink(this.el.child('div.section_header a.more_link'));
        }
    },

    expandlink: function(e, obj) {
        this._expandlink(e.getTarget(null, null, true));
    },

    _expandlink: function (ell) {
        if(this.contentEl.hasClass('expanded')) {
            if(this.fireEvent('beforeclose', this)) {
                ell.update('More &raquo;');
                this.contentEl.removeClass('expanded');
                if (!Ext.isIE) {
                    this.contentEl.setHeight(120);
                    Ext.IMS.Centennial.shadow.hide();
                } else {
                    this.contentEl.setHeight('auto');
                }
                this.load();
                this.fireEvent('close', this);
            }
        } else {
            if(this.fireEvent('beforeopen', this)) {
                ell.update('&laquo; Less');
                this.contentEl.addClass('expanded');
                this.load(this.loadedYear, 0, this.initialDisplay*3, true);
                this.fireEvent('open', this);
            }
        }
    },

    load : function(year, start, rows, includePageNav) {
        if(false !== this.fireEvent('beforeload', this.section)) {
            if(typeof year == 'undefined') year = this.loadedYear;
            this.loadedYear = year;
            if(typeof start == 'undefined') start = 0;
            if(typeof rows == 'undefined') rows = this.initialDisplay;

            link = '/centennial/view/' + this.section + '/start/' + start + '/rows/' + rows + '/year/' + year;

            if(this.filter != null) {
                link = link + '/keyword/' + this.filter;
            }

            if(includePageNav == true) {
                link = link + '/viewmore/1';
                if(this.orginalContent == null) {
                    this.orginalContent = this.contentEl.dom.innerHTML;
                }

            }
            this.contentEl.addClass('ajaxContainer');
            Ext.IMS.Centennial.spinner.overwrite(this.contentEl, this.section + 'Spinner');
            Ext.Ajax.request({
                url: link,
                callback: this._postLoad,
                scope: this
            });
        }
    },

    _postLoad : function(o, s, r) {
        if(s){
            var header = '';
            if(this.loadedYear != 0) {
                header = this.loadedYear;
            }

            if(this.filter != '' && this.filter != null) {
                header += ' ' + this.filter;
            }

            this.el.child('div.section_header h3 span').update(unescape(header.replace(/^\s+|\s+$/g,'')));
            this.contentEl.removeClass('ajaxContainer').update(r.responseText);
            if(o.url.indexOf('viewmore/1') != -1) {
                this.contentEl.select('td.has_link a').on('click', this._pageNavClick, this, {stopEvent: true});
                // set the height and readjust the shadow
                var child = this.contentEl.child('div.centennial_contents');
                if (child && !Ext.isIE) {
                    Ext.IMS.Centennial.shadow.show(this.contentEl);
                    this.contentEl.setHeight(child.getHeight());
                    Ext.IMS.Centennial.shadow.realign(this.contentEl.getLeft(true), this.contentEl.getTop(true), child.getWidth(), child.getHeight());
                }
            }
            this.fireEvent('load', this.section);
        }

        try {
            this.canexpand = false;
            if(this.contentEl.child('input[name=total' + this.section.slice(0,1).toUpperCase() + this.section.slice(1) + ']').getValue() < this.initialDisplay) {
                this.el.child('div.section_header a.more_link').hide();
            } else {
                this.canexpand = true;
                this.el.child('div.section_header a.more_link').show();
            }
        } catch (e) {
            // hide it if an error occurs.
            this.el.child('div.section_header a.more_link').hide();
        }
    },

    _pageNavClick : function(e, obj){
        this.contentEl.addClass('ajaxContainer');
        Ext.IMS.Centennial.spinner.overwrite(this.contentEl, this.section + 'Spinner');
        Ext.Ajax.request({
            url: e.getTarget().href,
            callback: this._postLoad,
            scope: this
        });
    }
});



