Ext.namespace("Waps.modules")
Waps.modules = function(options){
    this.options = options
    AdminUrl = this.options.AdminUrl
    Ext.onReady(function(){
        if (this.options.ListFormat == 1) 
            this.CreateNewsGrid()
        else 
            if (this.options.ListFormat == 2) 
                this.CreateNewsDataView()
            else 
                if (this.options.ListFormat == 3) {
                    this.CreateNewsColumnView.init('/index.php/SiteDataService/Module,NewsCat1', 515, 350, this);
                }
                else 
                    if (this.options.ListFormat == 4) {
                        this.CreateNewsColumnViewLighBox.init('/index.php/SiteDataService/Module,NewsCat1', 515, 350, this);
                    }
                    else 
                        if (this.options.ListFormat == 5) {
                            this.CreateNewsColumnViewShadowBox.init('/index.php/SiteDataService/Module,News', Ext.get('NewsDiv').getComputedWidth(), 350, this);
                            ;
                        }
                        else 
                            if (this.options.ListFormat == 6) {
                                this.CreateNewsColumnViewBW.init('/index.php/SiteDataService/Module,ShowCase', 950, 350, this); // Live data has to be fetched from index.php/SiteDataService/Module,News
                                ;
                            }
                            else 
                                if (this.options.ListFormat == 7) {
                                    this.CreateNewsColumnViewBWTestimonial.init('/index.php/SiteDataService/Module,Testimonial', 950, 350, this); // Live data has to be fetched from index.php/SiteDataService/Module,News
                                    ;
                                }
        
    }, this)
}

var ExpandCollapse = function(id, minId, caller){

    //console.log(minId)
    Ext.get(minId).enableDisplayMode()
    Ext.get(id).enableDisplayMode()
    
    if (!Ext.get(minId).isDisplayed()) {
    
        Ext.get(minId).toggle(true)
        caller.innerHTML = "read more";
    }
    else 
        Ext.get(minId).toggle()
    
    if (!Ext.get(id).isDisplayed()) {
        Ext.get(id).toggle(true)
        caller.innerHTML = "collapse";
    }
    else 
        Ext.get(id).toggle()
    
}
String.prototype.stripHTML = function(strInputCode){
    // What a tag looks like
    strInputCode = strInputCode.replace(/&(lt|gt);/g, function(strMatch, p1){
        return (p1 == "lt") ? "<" : ">";
    });
    var strTagStrippedText = strInputCode.replace(/<\/?[^>]+(>|$)/g, "");
    return strTagStrippedText;
    /*
     
     var matchTag = /<(?:.|\s)*?>/g;
     var matchTag2 = /&(?:.|\s)*?;/g;
     var ret = this.replace(matchTag2, "");
     var ret = ret.replace(matchTag, "");
     //alert(ret)
     return ret
     */
};
Waps.modules.prototype = {
    TextRenderer: function(val){
        //console.log(val)
        if (val == null) 
            val = '-'
        return val;
    },
    ReadMoreRenderer: function(Description){
        if (Description != null) {
        
            Description = Description.stripHTML(Description);
            Description = Description.substr(0, 100) + '...';
        }
        else 
            Description = "";
        return Description
    },
    LinkRenderer: function(Description){
        return "<a href='http://" + Description + "' target='_blank'>" + Description + "</a>"
    },
    ImageRenderer: function(Description){
        return "<img src='" + AdminUrl + '' + Description + "'>"
    },
    DownloadRenderer: function(Description){
        if (Description != '') {
            var re = new RegExp('.pdf|.gif|.jpg|.jpeg|.JPEG|.JPG');
            var m = re.exec(Description);
            
            if (m != null) {
            
                for (var i = 0; i < m.length; i++) {
                    var s = '';
                    s = s + m[i];
                }
                
                var matchTag = /\./g;
                s = s.replace(matchTag, "");
                
                return "<a href='" + AdminUrl + '' + Description + "' target='_blank'><img src='/themes/en/images/icons/" + s + ".png' border='0'></a>";
            }
            else {
                return Description;
            }
            
        }
        else {
            return "<img src='/themes/Default/images/icons/no_download.gif' alt='No Download Available' title='No Download Available' border='0'>";
        }
    },
    CreateNewsGrid: function(){
    
        var store = new Ext.data.Store({
            proxy: new Ext.data.HttpProxy({
                url: "/index.php/SiteDataService/Module,NewsCat1",
                method: "POST"
            }),
            baseParams: {
                TimeFormat: "4",
                DateFormat: "1",
                Mid: this.options.Mid,
                ListingType: this.options.FormIdent,
                Out: 'Json',
                Category1: this.options.Category1,
                Category2: this.options.Category2
            },
            listeners: {
                "load": function(){
                
                }
            },
            reader: new Ext.data.JsonReader({
                root: "row",
                totalProperty: "TotalResults",
                id: 'ListingId'
            }, ["ListingId", "Category1", "Category2", "Category3", "Category4", "LTitle", 'LDescription', 'Url', 'Mid', 'Draft', 'URL']),
            "remoteSort": true
        });
        
        store.load({
            "params": {
                "limit": 20,
                "start": 0
            }
        });
        
        /*
         * Filters Setup
         */
        if (this.options.Expander) 
            var expander = new Ext.grid.RowExpander({
            
                tpl: new Ext.Template(this.options.ExpanderTemplate)
            });
        else 
            expander = {
                init: function(){
                }
            }
        
        /*
         * Dynamic column reader.
         * @returns Array of columns
         */
        var column = function(instance){
        
            var columnArray = new Array();
            var URLRenderer = new Array()
            for (var key in instance.options.ColumnDefination) {
            
                if (instance.options.ColumnDefination[key]['Renderer']) {
                    var matchTag = /this/g;
                    instance.options.ColumnDefination[key]['Renderer'] = instance.options.ColumnDefination[key]['Renderer'].replace(matchTag, "instance");
                    instance.options.ColumnDefination[key]['renderer'] = eval(instance.options.ColumnDefination[key]['Renderer'])
                }
                
                var re = new RegExp('URL*');
                var m = re.exec(instance.options.ColumnDefination[key]['dataIndex']);
                
                if (m) {
                
                    var actualDataIndex = instance.options.ColumnDefination[key]['dataIndex'];
                    var re2 = new RegExp('([0-9])');
                    var m2 = re2.exec(actualDataIndex);
                    
                    
                    //var actualDataIndex = actualDataIndex.replace(matchTag, "");
                    if (m2) {
                    
                    
                        actualDataIndex = m2[0]
                        
                        //var actualDataIndex = instance.options.ColumnDefination[key]['dataIndex'];
                        instance.options.ColumnDefination[key]['dataIndex'] = "URL";
                        instance.options.ColumnDefination[key]['Renderer'] = instance.options.ColumnDefination[key]['Renderer']
                        URLRenderer[actualDataIndex] = eval(instance.options.ColumnDefination[key]['Renderer'])
                        //instance.options.ColumnDefination[key]['renderer'] = URLRenderer(data)
                        
                        instance.options.ColumnDefination[key]['renderer'] = function(da, metadata){
                        
                            var re2Id = new RegExp('([0-9])');
                            var m2Id = re2Id.exec(this.id);
                            actualDataIndex = m2Id[0]
                            if (da[actualDataIndex]) {
                                //console.log(metadata)
                                //var re = eval(instance.options.ColumnDefination[key]['Renderer'])
                                if (URLRenderer[actualDataIndex]) {
                                    return URLRenderer[actualDataIndex](da[actualDataIndex].FilePath);
                                    
                                }
                                
                                else 
                                    return "-"
                            }
                            //return da[actualDataIndex].FilePath + actualDataIndex
                        }
                        
                    }
                    
                }
                
                columnArray[key] = instance.options.ColumnDefination[key]
            }
            columnArray.reverse();
            if (instance.options.Expander) 
                columnArray.push(expander);
            columnArray.reverse();
            
            return columnArray;
        }
        var grid = new Ext.grid.GridPanel({
            store: store,
            
            columns: column(this),
            stripeRows: true,
            viewConfig: { //forceFit: true
}            ,
            width: Ext.get('NewsDiv').getComputedWidth(),
            autoHeight: true,
            bbar: new Ext.PagingToolbar({
                pageSize: 20,
                store: store,
                displayInfo: true,
                displayMsg: "Displaying topics {0} - {1} of {2}",
                emptyMsg: "No topics to display"
            }),
            frame: false,
            loadMask: true,
            stateful: false,
            renderTo: 'NewsDiv',
            plugins: [new Ext.ux.grid.Search({
                iconCls: 'icon-zoom',
                minChars: 3,
                autoFocus: false
            }), expander] //, new Ext.ux.plugins.Print(),
        }, this)
        
        grid.autoSizeColumns = function(){
            for (var i = 0; i < this.colModel.getColumnCount(); i++) {
                grid.autoSizeColumn(i);
            }
        };
        grid.autoSizeColumn = function(c){
            var w = this.view.getHeaderCell(c).firstChild.scrollWidth;
            for (var i = 0, l = this.store.getCount(); i < l; i++) {
                w = Math.max(w, this.view.getCell(i, c).firstChild.scrollWidth);
            }
            this.colModel.setColumnWidth(c, w + 5);
            //Ext.get(Ext.query('div.x-grid3-scroller', grid.body.id)).applyStyles({'overflow': 'scroll'})
            return w;
        };
        grid.store.on('load', grid.autoSizeColumns, grid);
        
        //grid.render("NewsDiv")
    },
    CreateNewsDataView: function(){
    
    
        var store = new Ext.data.Store({
            proxy: new Ext.data.HttpProxy({
                url: "/index.php/SiteDataService/Module,NewsCat1",
                method: "POST"
            }),
            baseParams: {
                TimeFormat: "4",
                DateFormat: "1",
                Mid: this.options.Mid,
                ListingType: this.options.FormIdent,
                Out: 'Json',
                Category1: this.options.Category1,
                Category2: this.options.Category2
            },
            remoteSort: true,
            reader: new Ext.data.JsonReader({
                root: "row",
                totalProperty: "TotalResults",
                id: 'ListingId'
            }, ['ListingId', 'ListingType', 'Category1', 'Category2', 'Category3', 'Category4', 'LTitle', 'LDescription', 'Mid', 'Draft', 'PublishDate', 'URL', 'Url'])
        });
        
        store.load({
            params: {
                limit: 20,
                start: 0
            }
        });
        
        /*
         * Category combo
         */
        /*
         * Store
         */
        var categoryComboStore = new Ext.data.Store({
            "proxy": new Ext.data.HttpProxy({
                url: "/index.php/SiteDataService/Module,News", // TODO: NEED TO CHANGE THIS TO Dropdown service 
                method: "POST"
            }),
            baseParams: {
                TimeFormat: "4",
                DateFormat: "1",
                Mid: this.options.Mid,
                ListingType: this.options.FormIdent,
                start: "0",
                limit: "20",
                Out: 'Json'
            
            },
            reader: new Ext.data.JsonReader({
                root: "row",
                totalProperty: "TotalResults",
                id: 'ListingId'
            }, ['ListingId', 'ListingType', 'Category1', 'Category2', 'Category3', 'Category4', 'LTitle', 'LDescription', 'Url', 'Mid', 'Draft', 'PublishDate', 'URL']),
            remoteSort: true,
            listeners: {}
        });
        
        categoryComboStore.load({
            "params": {
                "limit": 20,
                "start": 0
            }
        });
        var categoryCombo = new Ext.form.ComboBox({
            store: categoryComboStore,
            mode: 'local',
            triggerAction: 'all',
            hiddenName: 'CategoryCombo',
            displayField: 'ListingType',
            emptyText: 'Select Catgory',
            listeners: {
                select: function(value, record, index){
                    NewsDataView.store.load({
                        "params": {
                            "limit": 20,
                            "start": 0
                        }
                    })
                }
            }
        })
        
        if (this.options.ShowCategoryDD) {
            categoryCombo.renderTo('CategoryCombo')
        }
        
        var createTpl = function(instance){
            var options = instance.options;
            
            var tpl = '<tpl for="."><tpl><table class="char_select_template" width="100%" cellpadding="0" cellspacing="0" border="0">';
            for (var i = 0; i < options.ColumnDefination.length; i++) {
            
                tpl += '<tpl if="values.' + options.ColumnDefination[i].dataIndex + '"><tr>'
                if (options.ColumnDefination[i].showTitles) 
                    tpl += '<td valign="top" >' + options.ColumnDefination[i].header + ':</td>'
                tpl += '</tpl>';
                
                var ident = options.ColumnDefination[i].dataIndex
                var re = new RegExp('URL*');
                var m = re.exec(ident);
                
                if (m) {
                    if (options.ColumnDefination[i].renderer == 'this.TextRenderer') {
                        tpl += "{[values." + options.ColumnDefination[i].dataIndex + ".FilePath}";
                    }
                    else 
                        if (options.ColumnDefination[i].renderer == 'this.ImageRenderer' || options.ColumnDefination[i].renderer == 'this.DownloadRenderer') {
                        
                            tpl += '<tpl if="values.' + options.ColumnDefination[i].dataIndex + '">{[' + options.ColumnDefination[i].renderer + '(values.' + options.ColumnDefination[i].dataIndex + '.FilePath)]}</tpl>'
                        }
                    
                }
                else {
                
                
                    if (options.ColumnDefination[i].renderer == 'this.ReadMoreRenderer') {
                        tpl += "<td><span id=\"minNews{[xindex]}\" >{[" + options.ColumnDefination[i].renderer + "(values." + options.ColumnDefination[i].dataIndex + ")]}</span><span id=\"maxNews{[xindex]}\" style='display:none;'>{" + options.ColumnDefination[i].dataIndex + "}</span></td></tr><tr><td width='100' class='newsExpand'   ><a href='#' onClick=' ExpandCollapse(\"maxNews{[xindex]}\", \"minNews{[xindex]}\", this); return false;'>read more</a>";
                    }
                    else 
                        if (options.ColumnDefination[i].renderer == 'this.TextRenderer') {
                            tpl += "{" + options.ColumnDefination[i].dataIndex + "}";
                        }
                        else 
                            if (options.ColumnDefination[i].renderer == 'this.ImageRenderer' || options.ColumnDefination[i].renderer == 'this.DownloadRenderer') {
                                tpl += "{[" + options.ColumnDefination[i].renderer + "(values." + options.ColumnDefination[i].dataIndex + ")]}"
                            }
                }
            }
            tpl += '</table><hr></tpl></tpl><div class="x-clear"><hr></div>';
            //console.log(tpl)
            return tpl;
        }
        
        if (this.options.Expander != "True") 
            var NewsDataViewTpl = new Ext.XTemplate(createTpl(this), this); //
        else 
            var NewsDataViewTpl = new Ext.XTemplate(this.options.ExpanderTemplate, this); //
        var NewsDataView = new Ext.DataView({
            "store": store,
            "tpl": NewsDataViewTpl,
            "autoHeight": true,
            "loadingText": "Loading..",
            itemSelector: '.newsExpand',
            loadingText: "Loading",
            listeners: {
                click: function(row){
                
                },
                render: function(){
                
                }
            }
        });
        NewsDataView.render('NewsDiv2');
        
    },
    CreateNewsColumnView: {
        TextRenderer: function(val){
            return val;
        },
        ReadMoreRenderer: function(Description){
            String.prototype.stripHTML = function(strInputCode){
                // What a tag looks like
                strInputCode = strInputCode.replace(/&(lt|gt);/g, function(strMatch, p1){
                    return (p1 == "lt") ? "<" : ">";
                });
                var strTagStrippedText = strInputCode.replace(/<\/?[^>]+(>|$)/g, "");
                return strTagStrippedText;
                /*
                 
                 var matchTag = /<(?:.|\s)*?>/g;
                 var matchTag2 = /&(?:.|\s)*?;/g;
                 var ret = this.replace(matchTag2, "");
                 var ret = ret.replace(matchTag, "");
                 //alert(ret)
                 return ret
                 */
            };
            Description = Description.stripHTML(Description);
            Description = Description.substr(0, 100) + '...';
            //console.log(Description)
            return Description
        },
        ImageRenderer: function(Description){
            //console.log(Description)
            return "<img src='" + Description + "' alt='" + Description + "' title='" + Description + "'>"
        },
        DownloadRenderer: function(Description){
            if (Description != '') {
                var re = new RegExp('.pdf|.gif');
                var m = re.exec(Description);
                if (m != null) {
                    for (var i = 0; i < m.length; i++) {
                        var s = '';
                        s = s + m[i];
                    }
                    var matchTag = /\./g;
                    s = s.replace(matchTag, "");
                    
                    return "<a href='" + Description + "'><img src='/themes/Default/images/icons/" + s + ".png' alt='" + Description + "' title='" + Description + "' border='0'></a>";
                }
                else {
                    return Description;
                }
                
            }
            else {
                return "<img src='/themes/Default/images/icons/no_download.gif' alt='No Download Available' title='No Download Available' border='0'>";
            }
            
            
            
        },
        init: function(url, width, height, instance){
            this.config = {}
            this.config.url = url;
            this.config.width = width;
            this.config.height = height
            this.config.options = instance.options
            this.config.instance = instance;
            this.show('NewsDiv', Ext.emptyFn)
        },
        lookup: {},
        show: function(el, callback){
            if (!this.win) {
            
                this.store = new Ext.data.Store({
                    proxy: new Ext.data.HttpProxy({
                        url: this.config.url,
                        method: "POST"
                    }),
                    baseParams: {
                        TimeFormat: "4",
                        DateFormat: "1",
                        Mid: this.options.Mid,
                        Out: 'Json'
                    },
                    reader: new Ext.data.JsonReader({
                        root: "row",
                        totalProperty: "TotalResults",
                        id: 'ListingId'
                    }, ['ListingId', 'ListingType', 'Category1', 'Category2', 'Category3', 'Category4', 'LTitle', 'LDescription', 'Url', 'Mid', 'Draft', 'PublishDate', 'URL']),
                    "remoteSort": true,
                    listeners: {
                        'load': {
                            fn: function(){
                                this.view.select(0);
                                this.view.emptyText = '<div style="padding:10px;">No images match the specified filter</div>'
                            },
                            scope: this,
                            single: true
                        }
                    }
                });
                
                
                this.store.load();
                
                var formatSize = function(data){
                    return data.size + " bytes";
                };
                
                var formatData = function(data){
                    this.lookup[data.LTitle] = data;
                    return data;
                };
                
                this.initTemplates();
                
                this.view = new Ext.DataView({
                    tpl: this.thumbTemplate,
                    singleSelect: true,
                    loadingText: "Loading....",
                    deferEmptyText: false,
                    overClass: 'x-view-over',
                    itemSelector: 'div.thumb-wrap',
                    emptyText: 'No data available',
                    store: this.store,
                    listeners: {
                        'selectionchange': {
                            fn: this.showDetails,
                            scope: this,
                            buffer: 100
                        },
                        'loadexception': {
                            fn: this.onLoadException,
                            scope: this
                        },
                        'beforeselect': {
                            fn: function(view){
                                return view.store.getRange().length > 0;
                            }
                        }
                    },
                    prepareData: formatData.createDelegate(this)
                });
                
                var cfg = {
                    title: 'Choose an Image',
                    id: 'img-chooser-dlg',
                    layout: 'border',
                    minWidth: 500,
                    minHeight: 300,
                    loader: true,
                    modal: true,
                    closeAction: 'hide',
                    border: false,
                    items: [{
                        id: 'img-chooser-view',
                        region: 'center',
                        autoScroll: true,
                        items: this.view,
                        tbar: [{
                            text: 'Filter:'
                        }, {
                            xtype: 'textfield',
                            id: 'filter',
                            selectOnFocus: true,
                            width: 100,
                            listeners: {
                                'render': {
                                    fn: function(){
                                        Ext.getCmp('filter').getEl().on('keyup', function(){
                                            this.filter();
                                        }, this, {
                                            buffer: 500
                                        });
                                    },
                                    scope: this
                                }
                            }
                        }, ' ', '-', {
                            text: 'Sort By:'
                        }, {
                            id: 'sortSelect',
                            xtype: 'combo',
                            typeAhead: true,
                            triggerAction: 'all',
                            width: 100,
                            editable: false,
                            mode: 'local',
                            displayField: 'desc',
                            valueField: 'name',
                            lazyInit: false,
                            value: 'name',
                            store: new Ext.data.SimpleStore({
                                fields: ['name', 'desc'],
                                data: [['LTitle', 'Name'], ['Category1', 'Industry'], ['Category2', 'Offering'], ['Category3', 'Location']]
                            }),
                            listeners: {
                                'select': {
                                    fn: this.sortImages,
                                    scope: this
                                }
                            }
                        }]
                    }, {
                        id: 'img-detail-panel',
                        region: 'east',
                        split: true,
                        width: 150,
                        autoScroll: true,
                        minWidth: 150,
                        maxWidth: 250
                    }],
                    keys: {
                        key: 27, // Esc key
                        handler: function(){
                            this.win.hide();
                        },
                        scope: this
                    }
                };
                Ext.apply(cfg, this.config);
                this.win = new Ext.Window(cfg);
            }
            
            this.reset();
            this.win.show(el);
            //this.callback = callback;
            this.animateTarget = el;
        },
        createTemplate: function(position){
            var options = this.config.options.ColumnDefination
            var tpl = '<tpl for=".">';
            var firstNode = true;
            for (var i = 0; i < options.length; i++) {
                if (!options[i].DataViewDefinations) {
                    options[i].DataViewDefinations = {}
                    options[i].DataViewDefinations.Position = "Right"
                }
                
                //console.log(options[i].DataViewDefinations.Clickable +"-"+ options[i].dataIndex)
                if (options[i].DataViewDefinations.Clickable == "True") 
                    var className = "thumb-wrap";
                else 
                    var className = "";
                
                if (options[i].DataViewDefinations.Position == position) {
                    //console.log(firstNode)
                    var ident = options[i].dataIndex;
                    
                    var re = new RegExp('URL*');
                    var m = re.exec(ident);
                    
                    if (m) {
                        var identter2 = ident;
                        ident = "[" + options[i].Renderer + "(values." + ident + ".FilePath)]"
                        //ident = "[values." + ident + ".FilePath]"  
                    }
                    
                    if (firstNode) {
                        if (!m) {
                            if (options[i].Renderer == 'this.ReadMoreRenderer') {
                                tpl += "<span id=\"minContent{[xindex]}\" >{[" + options[i].renderer + "(values." + ident + ")]}</span><span id=\"maxContent{[xindex]}\" style='display:none;'>{" + options[i].dataIndex + "}</span></td></tr><tr><td width='100' class='newsExpand'   ><a href='#' onClick=' ExpandCollapse(\"maxContent{[xindex]}\", \"minContent{[xindex]}\", this)'>read more</a>";
                            }
                            else {
                                tpl += '<div class="' + className + '" id="{' + ident + '}" >"{' + ident + '}"'
                            }
                            
                        }
                        
                        else 
                            tpl += '<tpl if="[values.' + identter2 + ']"><div class="' + className + '" id="{' + ident + '}" >{' + ident + '}</div></tpl>';
                    }
                    
                    else {
                        if (!m) 
                            tpl += '<div style="float:left"> "{' + ident + '}"</div>'
                        else 
                            tpl += '<tpl if="values.' + identter2 + '"><div   style="float:left">{' + ident + '}</div></tpl>';
                    }
                    firstNode = false;
                }
            }
            
            tpl += '</div>';
            tpl += '</tpl>'
            
            return tpl;
        },
        initTemplates: function(){
        
        
            this.thumbTemplate = new Ext.XTemplate(this.createTemplate("Left"), this);
            
            //new Ext.XTemplate('<tpl for=".">', '<div class="thumb-wrap" id="{name}">', '<div class="thumb"><img src="{url}" title="{name}"></div>', '<span>{shortName}</span></div>', '</tpl>');
            //this.thumbTemplate = new Ext.XTemplate('<tpl for=".">', '<div class="thumb-wrap" id="{LTitle}">', '</tpl>');
            //this.thumbTemplate.compile();
            
            this.detailsTemplate = new Ext.XTemplate(this.createTemplate("Right"), this);
            
            //new Ext.XTemplate('<div class="details">', '<tpl for=".">', '<img src="{url}"><div class="details-info">', '<b>Image Name:</b>', '<span>{name}</span>', '<b>Size:</b>', '<span>{sizeString}</span>', '<b>Last Modified:</b>', '<span>{dateString}</span></div>', '</tpl>', '</div>');
            //this.detailsTemplate = new Ext.XTemplate('<div class="details">', '<tpl for=".">', '<img src="{Url}">', '</tpl>', '</div>');
            //this.detailsTemplate.compile();
        },
        
        showDetails: function(){
            var selNode = this.view.getSelectedNodes();
            
            var detailEl = Ext.getCmp('img-detail-panel').body;
            if (selNode && selNode.length > 0) {
                //console.log(selNode)
                selNode = selNode[0];
                var data = this.lookup[selNode.id];
                detailEl.hide();
                this.detailsTemplate.overwrite(detailEl, data);
                detailEl.slideIn('l', {
                    stopFx: true,
                    duration: .2
                });
            }
            else {
                detailEl.update('');
            }
        },
        
        filter: function(){
        
            var filter = Ext.getCmp('filter');
            this.view.store.filter('name', filter.getValue());
            this.view.select(0);
        },
        
        sortImages: function(){
            this.view.store.load()
            var v = Ext.getCmp('sortSelect').getValue();
            this.view.store.sort(v, v == 'name' ? 'asc' : 'desc');
            this.view.select(0);
            
        },
        
        reset: function(){
            if (this.win.rendered) {
                Ext.getCmp('filter').reset();
                this.view.getEl().dom.scrollTop = 0;
            }
            this.view.store.clearFilter();
            this.view.select(0);
        },
        
        doCallback: function(){
            var selNode = this.view.getSelectedNodes()[0];
            var callback = this.callback;
            var lookup = this.lookup;
            this.win.hide(this.animateTarget, function(){
                if (selNode && callback) {
                    var data = lookup[selNode.id];
                    callback(data);
                }
            });
        },
        
        onLoadException: function(v, o){
            this.view.getEl().update('<div style="padding:10px;">Error loading images.</div>');
        }
        
    },
    CreateNewsColumnViewShadowBox: {
        TextRenderer: function(val){
            return val;
        },
        ReadMoreRenderer: function(Description){
            String.prototype.stripHTML = function(){
                // What a tag looks like
                var matchTag = /<(?:.|\s)*?>/g;
                var matchTag2 = /&(?:.|\s)*?;/g;
                var ret = this.replace(matchTag2, "");
                var ret = ret.replace(matchTag, "");
                //alert(ret)
                return ret
            };
            Description = Description.stripHTML();
            Description = Description.substr(0, 100) + '...';
            //console.log(Description)
            return Description
        },
        ImageRenderer: function(Desc){
        	
            //Description = new String(Desc.FilePath);
            var matchTag = /\//g;
            AdminUrlNew = AdminUrl.replace(matchTag, "__");
            DescriptionNew = Desc.FilePath.replace(matchTag, "__");
            return '<a rel="shadowbox[MustangThumbs];options={counterType:\'default\',animSequence:\'sync\'}" href="/index.php/WThumb/MaxHeight,600/MaxWidth,600/ImageServerPath,' + AdminUrlNew + DescriptionNew + '" title="' + Desc.MediaTitle + '"><img src="/index.php/WThumb/ImageServerPath,' + AdminUrlNew + DescriptionNew + '/MaxHeight,100/MaxWidth,100" alt=""></a>'
        },
        DownloadRenderer: function(Description){
            if (Description != '') {
                var re = new RegExp('.pdf|.gif');
                var m = re.exec(Description);
                if (m != null) {
                    for (var i = 0; i < m.length; i++) {
                        var s = '';
                        s = s + m[i];
                    }
                    var matchTag = /\./g;
                    s = s.replace(matchTag, "");
                    
                    return "<a href='" + Description + "'><img src='/themes/Default/images/icons/" + s + ".png' alt='" + Description + "' title='" + Description + "' border='0'></a>";
                }
                else {
                    return Description;
                }
                
            }
            else {
                return "<img src='/themes/Default/images/icons/no_download.gif' alt='No Download Available' title='No Download Available' border='0'>";
            }
            
            
            
        },
        init: function(url, width, height, instance){
            this.config = {}
            this.config.url = url;
            this.config.width = width;
            this.config.height = height
            this.config.options = instance.options
            this.config.instance = instance;
            this.show('NewsDiv', Ext.emptyFn)
        },
        lookup: {},
        show: function(el, callback){
            if (!this.win) {
            
                this.store = new Ext.data.Store({
                    proxy: new Ext.data.HttpProxy({
                        url: this.config.url,
                        method: "POST"
                    }),
                    baseParams: {
                        TimeFormat: "4",
                        DateFormat: "1",
                        Mid: this.config.options.Mid,
                        Out: 'Json',
                        Category1: this.config.options.Category1,
                        ListingType: this.config.options.FormIdent
                    },
                    reader: new Ext.data.JsonReader({
                        root: "row",
                        totalProperty: "TotalResults",
                        id: 'ListingId'
                    }, ['ListingId', 'ListingType', 'Category1', 'Category2', 'Category3', 'Category4', 'LTitle', 'LDescription', 'Url', 'Mid', 'Draft', 'PublishDate', 'URL']),
                    "remoteSort": true,
                    listeners: {
                        'load': {
                            fn: function(){
                                var options = {
                                    continuous: false,
                                    counterType: 'default',
                                    counterLimit: 10
                                };
                                Shadowbox.clearCache()
                                Shadowbox.init(options)
                                Shadowbox.setup();
                                //console.log(Shadowbox.getOptions())
                                ///this.view.select(0);
                                this.view.emptyText = '<div style="padding:10px;">No images found</div>'
                            },
                            scope: this
                        }
                    }
                });
                
                var par = Ext.decode(this.config.options.StoreLoadParam);
                if (!par) 
                    par = {};
                if (!par.limit) 
                    par.limit = 18
                if (!par.start) 
                    par.start = 0
                if (!par.Category2) 
                    par.Category2 = '%'
                
                this.store.baseParams.Category2 = par.Category2;
                this.store.load({
                    params: par
                });
                this.store.on('beforeload', function(sto, options){
                    options.Category2 = par.Category2;
                    //console.log(options)
                })
                
                var formatSize = function(data){
                    return data.size + " bytes";
                };
                
                var formatData = function(data){
                    this.lookup[data.LTitle] = data;
                    return data;
                };
                
                this.initTemplates();
                
                this.view = new Ext.DataView({
                    tpl: this.thumbTemplate,
                    singleSelect: true,
                    loadingText: "Loading....",
                    deferEmptyText: false,
                    overClass: 'x-view-over',
                    itemSelector: 'div.thumb-wrap',
                    emptyText: 'No Data available',
                    store: this.store,
                    listeners: {
                        'selectionchange': {
                            fn: this.showDetails,
                            scope: this,
                            buffer: 100
                        },
                        
                        'loadexception': {
                            fn: this.onLoadException,
                            scope: this
                        },
                        'beforeselect': {
                            fn: function(view){
                                return view.store.getRange().length > 0;
                            }
                        }
                    },
                    prepareData: formatData.createDelegate(this)
                });
                
                var cfg = {
                    //title: 'Choose an Image',
                    id: 'img-chooser-dlg',
                    layout: 'table',
                    width: this.config.width,
                    //minWidth: 780,
                    autoWidth: true,
                    autoHeight: true,
                    //minHeight: 400,
                    loader: true,
                    modal: true,
                    closeAction: 'hide',
                    border: false,
                    items: [{
                        id: 'img-chooser-view',
                        width: this.config.width,
                        //autoScroll: true,
                        items: this.view,
                        tbar: []
                    }],
                    bbar: new Ext.PagingToolbar({
                        pageSize: par.limit,
                        store: this.store,
                        displayInfo: true,
                        displayMsg: 'Displaying topics {0} - {1} of {2}',
                        emptyMsg: "No data to display"
                    })
                };
                
                if (eval(this.config.options.ShowCategoryDD)) {
                    cfg.items[0].tbar = [{
                        text: 'Select'
                    }, {
                        id: 'sortSelect',
                        xtype: 'combo',
                        typeAhead: true,
                        triggerAction: 'all',
                        width: 100,
                        editable: false,
                        mode: 'local',
                        displayField: 'name',
                        valueField: 'desc',
                        lazyInit: false,
                        value: 2008,
                        store: new Ext.data.SimpleStore({
                            fields: ['desc', 'name'],
                            data: [[147, (new Date()).getFullYear() - 2], [146, (new Date()).getFullYear() - 1], [145, (new Date()).getFullYear()]]
                        }),
                        listeners: {
                            'select': {
                                fn: this.sortImages,
                                scope: this
                            }
                        }
                    }]
                }
                
                Ext.apply(cfg, this.config);
                this.win = new Ext.Panel(cfg);
            }
            
            this.reset();
            this.win.render(el);
            //this.callback = callback;
            this.animateTarget = el;
        },
        createTemplate: function(position){
            var options = this.config.options.ColumnDefination
            var tpl = '<tpl for=".">';
            var firstNode = true;
            for (var i = 0; i < options.length; i++) {
                if (!options[i].DataViewDefinations) {
                    options[i].DataViewDefinations = {}
                    options[i].DataViewDefinations.Position = "Right"
                }
                
                //console.log(options[i].DataViewDefinations.Clickable +"-"+ options[i].dataIndex)
                if (options[i].DataViewDefinations.Clickable == "True") 
                    var className = "thumb-wrap";
                else 
                    var className = "";
                
                if (options[i].DataViewDefinations.Position == position) {
                    //console.log(firstNode)
                    var ident = options[i].dataIndex;
                    
                    var re = new RegExp('URL*');
                    var m = re.exec(ident);
                    
                    if (m) {
                        var identter2 = ident;
                        ident = "[" + options[i].Renderer + "(values." + ident + ")]"
                        //ident = "[values." + ident + ".FilePath]"  
                    }
                    
                    if (firstNode) {
                        if (!m) {
                            if (options[i].Renderer == 'this.ReadMoreRenderer') {
                                tpl += "<span id=\"minContent{[xindex]}\" >{[" + options[i].renderer + "(values." + ident + ")]}</span><span id=\"maxContent{[xindex]}\" style='display:none;'>{" + options[i].dataIndex + "}</span></td></tr><tr><td width='100' class='newsExpand'   ><a href='#' onClick=' ExpandCollapse(\"maxContent{[xindex]}\", \"minContent{[xindex]}\", this)'>read more</a>";
                            }
                            else {
                                tpl += '<div class="' + className + '" id="{' + ident + '}" >'
                            }
                            
                        }
                        
                        else 
                            tpl += '<tpl if="[values.' + identter2 + ']"><div class="' + className + '" id="{' + ident + '}" ></div></tpl>';
                    }
                    
                    else {
                        if (!m) 
                            tpl += '<div style="float:left"> "{' + ident + '}"</div>'
                        else 
                            tpl += '<tpl if="values.' + identter2 + '"><div   style="float:left">{' + ident + '}</div></tpl>';
                    }
                    
                    
                    
                    //console.log(tpl)
                    firstNode = false;
                    
                }
                
                
            }
            
            tpl += '</div>';
            tpl += '</tpl>'
            
            return tpl;
        },
        initTemplates: function(){
        
        
            this.thumbTemplate = new Ext.XTemplate(this.createTemplate("Left"), this);
            
            //new Ext.XTemplate('<tpl for=".">', '<div class="thumb-wrap" id="{name}">', '<div class="thumb"><img src="{url}" title="{name}"></div>', '<span>{shortName}</span></div>', '</tpl>');
            //this.thumbTemplate = new Ext.XTemplate('<tpl for=".">', '<div class="thumb-wrap" id="{LTitle}">', '</tpl>');
            //this.thumbTemplate.compile();
            
            this.detailsTemplate = new Ext.XTemplate(this.createTemplate("Right"), this);
            
            //new Ext.XTemplate('<div class="details">', '<tpl for=".">', '<img src="{url}"><div class="details-info">', '<b>Image Name:</b>', '<span>{name}</span>', '<b>Size:</b>', '<span>{sizeString}</span>', '<b>Last Modified:</b>', '<span>{dateString}</span></div>', '</tpl>', '</div>');
            //this.detailsTemplate = new Ext.XTemplate('<div class="details">', '<tpl for=".">', '<img src="{Url}">', '</tpl>', '</div>');
            //this.detailsTemplate.compile();
        },
        showDetails: function(){
            var selNode = this.view.getSelectedNodes();
            
            //var detailEl = Ext.getCmp('img-detail-panel').body;
            if (selNode && selNode.length > 0) {
                //console.log(selNode)
                selNode = selNode[0];
                var data = this.lookup[selNode.id];
                var selectedLocalImageNode = this.lookup[selNode.id];
                
                selectedLocalImage = selectedLocalImageNode.URL[0].FilePath;
                //console.log(selNode)
                //console.log(Shadowbox.getCurrent())
            
                //console.log(Shadowbox.getCurrent())
                //this.showDetails();
                //Shadowbox.setup()
            
                //Shadowbox.open(selNode, options);
            }
        },
        filter: function(){
        
            var filter = Ext.getCmp('filter');
            this.view.store.filter('name', filter.getValue());
            this.view.select(0);
        },
        
        sortImages: function(combo, record){
        
            this.view.store.baseParams.Category2 = record.data.desc
            this.view.store.load({
                params: {
                    limit: 18,
                    start: 0
                }
            })
            //var v = Ext.getCmp('sortSelect').getValue();
            //this.view.store.sort(v, v == 'name' ? 'asc' : 'desc');
            //this.view.select(0);
        },
        
        reset: function(){
            if (this.win.rendered) {
                Ext.getCmp('filter').reset();
                this.view.getEl().dom.scrollTop = 0;
            }
            this.view.store.clearFilter();
            this.view.select(0);
        },
        
        doCallback: function(){
            var selNode = this.view.getSelectedNodes()[0];
            var callback = this.callback;
            var lookup = this.lookup;
            this.win.hide(this.animateTarget, function(){
                if (selNode && callback) {
                    var data = lookup[selNode.id];
                    callback(data);
                }
            });
        },
        
        onLoadException: function(v, o){
            this.view.getEl().update('<div style="padding:10px;">Error loading images.</div>');
        }
        
    },
    CreateNewsColumnViewLighBox: {
        TextRenderer: function(val){
            return val;
        },
        ReadMoreRenderer: function(Description){
            String.prototype.stripHTML = function(){
                // What a tag looks like
                var matchTag = /<(?:.|\s)*?>/g;
                var matchTag2 = /&(?:.|\s)*?;/g;
                var ret = this.replace(matchTag2, "");
                var ret = ret.replace(matchTag, "");
                //alert(ret)
                return ret
            };
            Description = Description.stripHTML();
            Description = Description.substr(0, 100) + '...';
            //console.log(Description)
            return Description
        },
        ImageRenderer: function(Desc){
            //console.log(Desc)
            var Description = Desc
            var matchTag = /\//g;
            AdminUrlNew = AdminUrl.replace(matchTag, "__");
            DescriptionNew = Description.replace(matchTag, "__");
            return '<a rel="shadowbox[MustangThumbs];options={counterType:\'default\',animSequence:\'sync\'}" href="/index.php/WThumb/MaxHeight,400/MaxWidth,400/ImageServerPath,' + AdminUrlNew + DescriptionNew + '" title="' + Desc.MediaTitle + '"><img src="/index.php/WThumb/ImageServerPath,' + AdminUrlNew + DescriptionNew + '/MaxHeight,100/MaxWidth,100" alt=""></a>'
        },
        DownloadRenderer: function(Description){
            if (Description != '') {
                var re = new RegExp('.pdf|.gif');
                var m = re.exec(Description);
                if (m != null) {
                    for (var i = 0; i < m.length; i++) {
                        var s = '';
                        s = s + m[i];
                    }
                    var matchTag = /\./g;
                    s = s.replace(matchTag, "");
                    
                    return "<a href='" + Description + "'><img src='/themes/Default/images/icons/" + s + ".png' alt='" + Description + "' title='" + Description + "' border='0'></a>";
                }
                else {
                    return Description;
                }
                
            }
            else {
                return "<img src='/themes/Default/images/icons/no_download.gif' alt='No Download Available' title='No Download Available' border='0'>";
            }
            
            
            
        },
        init: function(url, width, height, instance){
            this.config = {}
            this.config.url = url;
            this.config.width = width;
            this.config.height = height
            this.config.options = instance.options
            this.config.instance = instance;
            this.show('NewsDiv', Ext.emptyFn)
        },
        lookup: {},
        show: function(el, callback){
            if (!this.win) {
                this.store = new Ext.data.Store({
                    proxy: new Ext.data.HttpProxy({
                        url: this.config.url,
                        method: "POST"
                    }),
                    baseParams: {
                        TimeFormat: "4",
                        DateFormat: "1",
                        Mid: this.config.options.Mid,
                        Out: 'Json',
                        Category1: this.config.options.Category1,
                        ListingType: this.config.options.FormIdent,
                        Category2: this.options.Category2
                    },
                    reader: new Ext.data.JsonReader({
                        root: "row",
                        totalProperty: "TotalResults",
                        id: 'ListingId'
                    }, ['ListingId', 'ListingType', 'Category1', 'Category2', 'Category3', 'Category4', 'LTitle', 'LDescription', 'Url', 'Mid', 'Draft', 'PublishDate', 'URL']),
                    "remoteSort": true,
                    listeners: {
                        'load': {
                            fn: function(){
                                this.view.select(0);
                                this.view.emptyText = '<div style="padding:10px;">No images match the specified filter</div>'
                            },
                            scope: this,
                            single: true
                        }
                    }
                });
                
                
                this.store.load({
                    "params": {
                        "limit": 20,
                        "start": 0
                    }
                });
                
                var formatSize = function(data){
                    return data.size + " bytes";
                };
                
                var formatData = function(data){
                    this.lookup[data.LTitle] = data;
                    return data;
                };
                
                this.initTemplates();
                
                this.view = new Ext.DataView({
                    tpl: this.thumbTemplate,
                    singleSelect: true,
                    loadingText: "Loading....",
                    deferEmptyText: false,
                    overClass: 'x-view-over',
                    itemSelector: 'div.thumb-wrap',
                    emptyText: 'No Data available',
                    store: this.store,
                    plugins: [new Ext.ux.DataView.LightBox({
                        nextImage: '../arrow_right.png',
                        prevImage: '../arrow_left.png',
                        event: 'click',
                        //TitleField: 'LTitle',
                        ImageUrlField: 'URL[0].FilePath'
                    })],
                    listeners: {
                        'loadexception': {
                            fn: this.onLoadException,
                            scope: this
                        }
                    },
                    prepareData: formatData.createDelegate(this)
                });
                
                var cfg = {
                    title: 'Choose an Image',
                    id: 'img-chooser-dlg',
                    layout: 'border',
                    minWidth: 500,
                    minHeight: 300,
                    loader: true,
                    closeAction: 'hide',
                    border: false,
                    items: [{
                        id: 'img-chooser-view',
                        region: 'center',
                        autoScroll: true,
                        items: this.view,
                        tbar: [{
                            text: 'Filter:'
                        }, {
                            xtype: 'textfield',
                            id: 'filter',
                            selectOnFocus: true,
                            width: 100,
                            listeners: {
                                'render': {
                                    fn: function(){
                                        Ext.getCmp('filter').getEl().on('keyup', function(){
                                            this.filter();
                                        }, this, {
                                            buffer: 500
                                        });
                                    },
                                    scope: this
                                }
                            }
                        }, ' ', '-', {
                            text: 'Sort By:'
                        }, {
                            id: 'sortSelect',
                            xtype: 'combo',
                            typeAhead: true,
                            triggerAction: 'all',
                            width: 100,
                            editable: false,
                            mode: 'local',
                            displayField: 'desc',
                            valueField: 'name',
                            lazyInit: false,
                            value: 'name',
                            store: new Ext.data.SimpleStore({
                                fields: ['name', 'desc'],
                                data: [['name', 'Name'], ['size', 'File Size'], ['lastmod', 'Last Modified']]
                            }),
                            listeners: {
                                'select': {
                                    fn: this.sortImages,
                                    scope: this
                                }
                            }
                        }]
                    }]
                };
                Ext.apply(cfg, this.config);
                this.win = new Ext.Panel(cfg);
            }
            
            this.reset();
            this.win.render(el);
            //this.callback = callback;
            this.animateTarget = el;
        },
        createTemplate: function(position){
            var options = this.config.options.ColumnDefination
            var tpl = '<tpl for=".">';
            var firstNode = true;
            for (var i = 0; i < options.length; i++) {
                if (!options[i].DataViewDefinations) {
                    options[i].DataViewDefinations = {}
                    options[i].DataViewDefinations.Position = "Right"
                }
                
                //console.log(options[i].DataViewDefinations.Clickable +"-"+ options[i].dataIndex)
                if (options[i].DataViewDefinations.Clickable == "True") 
                    var className = "thumb-wrap";
                else 
                    var className = "";
                
                if (options[i].DataViewDefinations.Position == position) {
                    //console.log(firstNode)
                    var ident = options[i].dataIndex;
                    
                    var re = new RegExp('URL*');
                    var m = re.exec(ident);
                    
                    if (m) {
                        var identter2 = ident;
                        ident = "[" + options[i].Renderer + "(values." + ident + ".FilePath)]"
                        //ident = "[values." + ident + ".FilePath]"  
                    }
                    
                    if (firstNode) {
                        if (!m) {
                            if (options[i].Renderer == 'this.ReadMoreRenderer') {
                                tpl += "<span id=\"minContent{[xindex]}\" >{[" + options[i].renderer + "(values." + ident + ")]}</span><span id=\"maxContent{[xindex]}\" style='display:none;'>{" + options[i].dataIndex + "}</span></td></tr><tr><td width='100' class='newsExpand'   ><a href='#' onClick=' ExpandCollapse(\"maxContent{[xindex]}\", \"minContent{[xindex]}\", this)'>read more</a>";
                            }
                            else {
                                tpl += '<div class="' + className + '" id="{' + ident + '}" >{' + ident + '}'
                            }
                            
                        }
                        
                        else 
                            tpl += '<tpl if="[values.' + identter2 + ']"><div class="' + className + '" id="{' + ident + '}" >{' + ident + '}</div></tpl>';
                    }
                    
                    else {
                        if (!m) 
                            tpl += '<div style="float:left"> "{' + ident + '}"</div>'
                        else 
                            tpl += '<tpl if="values.' + identter2 + '"><div   style="float:left">{' + ident + '}</div></tpl>';
                    }
                    
                    
                    
                    //console.log(tpl)
                    firstNode = false;
                    
                }
                
                
            }
            
            tpl += '</div>';
            tpl += '</tpl>'
            
            return tpl;
        },
        initTemplates: function(){
        
        
            this.thumbTemplate = new Ext.XTemplate(this.createTemplate("Left"), this);
            
            //new Ext.XTemplate('<tpl for=".">', '<div class="thumb-wrap" id="{name}">', '<div class="thumb"><img src="{url}" title="{name}"></div>', '<span>{shortName}</span></div>', '</tpl>');
            //this.thumbTemplate = new Ext.XTemplate('<tpl for=".">', '<div class="thumb-wrap" id="{LTitle}">', '</tpl>');
            //this.thumbTemplate.compile();
            
            this.detailsTemplate = new Ext.XTemplate(this.createTemplate("Right"), this);
            
            //new Ext.XTemplate('<div class="details">', '<tpl for=".">', '<img src="{url}"><div class="details-info">', '<b>Image Name:</b>', '<span>{name}</span>', '<b>Size:</b>', '<span>{sizeString}</span>', '<b>Last Modified:</b>', '<span>{dateString}</span></div>', '</tpl>', '</div>');
            //this.detailsTemplate = new Ext.XTemplate('<div class="details">', '<tpl for=".">', '<img src="{Url}">', '</tpl>', '</div>');
            //this.detailsTemplate.compile();
        },
        
        showDetails: function(){
            var selNode = this.view.getSelectedNodes();
            
            var detailEl = Ext.getCmp('img-detail-panel').body;
            if (selNode && selNode.length > 0) {
                //console.log(selNode)
                selNode = selNode[0];
                var data = this.lookup[selNode.id];
                detailEl.hide();
                this.detailsTemplate.overwrite(detailEl, data);
                detailEl.slideIn('l', {
                    stopFx: true,
                    duration: .2
                });
            }
            else {
                detailEl.update('');
            }
        },
        
        filter: function(){
        
            var filter = Ext.getCmp('filter');
            this.view.store.filter('name', filter.getValue());
            this.view.select(0);
        },
        
        sortImages: function(){
            this.view.store.load()
            var v = Ext.getCmp('sortSelect').getValue();
            this.view.store.sort(v, v == 'name' ? 'asc' : 'desc');
            this.view.select(0);
            
        },
        
        reset: function(){
            if (this.win.rendered) {
                Ext.getCmp('filter').reset();
                this.view.getEl().dom.scrollTop = 0;
            }
            this.view.store.clearFilter();
            this.view.select(0);
        },
        
        doCallback: function(){
            var selNode = this.view.getSelectedNodes()[0];
            var callback = this.callback;
            var lookup = this.lookup;
            this.win.hide(this.animateTarget, function(){
                if (selNode && callback) {
                    var data = lookup[selNode.id];
                    callback(data);
                }
            });
        },
        
        onLoadException: function(v, o){
            this.view.getEl().update('<div style="padding:10px;">Error loading images.</div>');
        }
        
    },
    CreateNewsColumnViewBW: {
        TextRenderer: function(val){
            return val;
        },
        ReadMoreRenderer: function(Description){
            String.prototype.stripHTML = function(){
                // What a tag looks like
                var matchTag = /<(?:.|\s)*?>/g;
                var matchTag2 = /&(?:.|\s)*?;/g;
                var ret = this.replace(matchTag2, "");
                var ret = ret.replace(matchTag, "");
                //alert(ret)
                return ret
            };
            Description = Description.stripHTML();
            Description = Description.substr(0, 100) + '...';
            //console.log(Description)
            return Description
        },
        ImageRenderer: function(Desc, title){
            //console.log(Desc)
            var Description = Desc
            var matchTag = /\//g;
            AdminUrlNew = AdminUrl.replace(matchTag, "__");
            DescriptionNew = Description.replace(matchTag, "__");
            return '<a href="/index.php/WThumb/MaxHeight,400/MaxWidth,400/ImageServerPath,' + AdminUrlNew + DescriptionNew + '" ><img src="/index.php/WThumb/ImageServerPath,' + AdminUrlNew + DescriptionNew + '/MaxHeight,86/MaxWidth,156" alt="' + title + '" title="' + title + '"></a>'
        },
        DownloadRenderer: function(Description){
            if (Description != '') {
                var re = new RegExp('.pdf|.gif');
                var m = re.exec(Description);
                if (m != null) {
                    for (var i = 0; i < m.length; i++) {
                        var s = '';
                        s = s + m[i];
                    }
                    var matchTag = /\./g;
                    s = s.replace(matchTag, "");
                    
                    return "<a href='" + Description + "'><img src='/themes/Default/images/icons/" + s + ".png' alt='" + Description + "' title='" + Description + "' border='0'></a>";
                }
                else {
                    return Description;
                }
                
            }
            else {
                return "<img src='/themes/Default/images/icons/no_download.gif' alt='No Download Available' title='No Download Available' border='0'>";
            }
            
            
            
        },
        init: function(url, width, height, instance){
            this.config = {}
            this.config.url = url;
            this.config.width = width;
            this.config.height = height
            this.config.options = instance.options
            this.config.instance = instance;
            this.show('NewsDiv', Ext.emptyFn)
        },
        lookup: {},
        show: function(el, callback){
            if (!this.win) {
                this.store = new Ext.data.Store({
                    proxy: new Ext.data.HttpProxy({
                        url: this.config.url,
                        method: "POST"
                    }),
                    baseParams: {
                        Mid: this.config.options.Mid,
                        Out: 'Json'
                    },
                    reader: new Ext.data.JsonReader({
                        root: "row",
                        totalProperty: "TotalResults",
                        id: 'PortfolioId'
                    }, ['PortfolioId', 'PTitle', 'Description', 'Url', 'Logo', 'Industry', 'ClientId']),
                    "remoteSort": false,
                    listeners: {
                        'load': {
                            fn: function(){
                                // this.view.select(0);
                                this.view.emptyText = '<div style="padding:10px;">No images match the specified filter</div>'
                            },
                            scope: this,
                            single: true
                        }
                    }
                });
                
                
                this.store.load({
                    "params": {
                        "limit": 6,
                        "start": 0,
                        fields: '[Portfolio.ShowcaseTag]',
                        query: 305
                    }
                });
                
                var formatSize = function(data){
                    return data.size + " bytes";
                };
                
                var formatData = function(data){
                    this.lookup[data.LTitle] = data;
                    return data;
                };
                
                this.initTemplates();
                
                this.view = new Ext.DataView({
                    tpl: this.thumbTemplate,
                    singleSelect: true,
                    loadingText: "Loading....",
                    deferEmptyText: false,
                    overClass: 'x-view-over',
                    itemSelector: 'div.thumb-wrap',
                    store: this.store,
                    plugins: [new Ext.ux.DataView.BWGallery({
                        nextImage: '../arrow_right.png',
                        prevImage: '../arrow_left.png',
                        event: 'click',
                        //TitleField: 'LTitle',
                        ImageUrlField: 'URL[0].FilePath'
                    })],
                    listeners: {
                        'loadexception': {
                            fn: this.onLoadException,
                            scope: this
                        }
                    },
                    prepareData: formatData.createDelegate(this)
                });
                
                var cfg = {
                    id: 'img-chooser-dlg',
                    layout: 'border',
                    minWidth: 700,
                    minHeight: 300,
                    loader: true,
                    closeAction: 'hide',
                    border: false,
                    bbar: new Ext.PagingToolbar({
                        store: this.store,
                        pageSize: 6,
                        displayInfo: true,
                        displayMsg: 'Displaying categories {0} - {1} of {2}',
                        emptyMsg: "No categories to display"
                    }),
                    items: [{
                        id: 'img-chooser-view',
                        region: 'center',
                        autoScroll: true,
                        items: this.view,
                        tbar: [{
                            text: 'Filter:'
                        }, {
                            id: 'MainSelector',
                            hidden: false,
                            xtype: 'combo',
                            typeAhead: true,
                            triggerAction: 'all',
                            width: 100,
                            editable: false,
                            mode: 'local',
                            displayField: 'desc',
                            value: 'offering',
                            valueField: 'name',
                            lazyInit: false,
                            store: new Ext.data.SimpleStore({
                                fields: ['name', 'desc'],
                                data: [['offering', 'offering'], ['industry', 'industry'], ['location', 'location']]
                            }),
                            listeners: {
                                'select': {
                                    fn: this.sortImages,
                                    scope: this
                                }
                            }
                        }, {
                            id: 'ServiceSelector',
                            hidden: false,
                            xtype: 'combo',
                            typeAhead: true,
                            triggerAction: 'all',
                            width: 100,
                            editable: false,
                            mode: 'local',
                            displayField: 'name',
                            emptyText: 'select',
                            valueField: 'ID',
                            lazyInit: false,
                            value: 'website',
                            store: new Ext.data.JsonStore({
                                url: "/index.php/SiteDataService/Module,DataEddValue",
                                baseParams: {
                                    FormId: 54,
                                    fieldID: 0
                                },
                                autoLoad: true,
                                root: "data",
                                fields: ["ID", "name"]
                            }),
                            listeners: {
                                'select': {
                                    fn: function(combo){
                                        if (this.view.store.lastOptions && this.view.store.lastOptions.params) {
                                            this.view.store.lastOptions.params['start'] = 0;
                                            this.view.store.lastOptions.params['limit'] = 6;
                                        }
                                        delete (this.view.store.baseParams['fields']);
                                        delete (this.view.store.baseParams['query']);
                                        this.view.store.baseParams['fields'] = '[Portfolio.ShowcaseTag]';
                                        this.view.store.baseParams['query'] = combo.value;
                                        this.view.store.reload()
                                    },
                                    scope: this
                                }
                            }
                        }, {
                            id: 'IndustrySelector',
                            hidden: true,
                            xtype: 'combo',
                            typeAhead: true,
                            triggerAction: 'all',
                            editable: false,
                            mode: 'local',
                            displayField: 'name',
                            valueField: 'ID',
                            lazyInit: false,
                            emptyText: 'select industry',
                            store: new Ext.data.JsonStore({
                                url: "/index.php/SiteDataService/Module,DataEddValue",
                                baseParams: {
                                    FormId: 49,
                                    fieldID: 0
                                },
                                autoLoad: true,
                                root: "data",
                                fields: ["ID", "name"]
                            }),
                            listeners: {
                                'select': {
                                    fn: function(combo){
                                        if (this.view.store.lastOptions && this.view.store.lastOptions.params) {
                                            this.view.store.lastOptions.params['start'] = 0;
                                            this.view.store.lastOptions.params['limit'] = 6;
                                        }
                                        delete (this.view.store.baseParams['fields']);
                                        delete (this.view.store.baseParams['query']);
                                        this.view.store.baseParams['fields'] = '[Accounts.Industry]';
                                        this.view.store.baseParams['query'] = combo.value;
                                        this.view.store.reload()
                                    },
                                    scope: this
                                }
                            }
                        }, {
                            id: 'CountrySelector',
                            hidden: true,
                            xtype: 'combo',
                            typeAhead: true,
                            triggerAction: 'all',
                            editable: false,
                            mode: 'local',
                            displayField: 'name',
                            valueField: 'ID',
                            lazyInit: false,
                            emptyText: 'select location',
                            store: new Ext.data.JsonStore({
                                url: "/index.php/SiteDataService/Module,DataEddValue",
                                baseParams: {
                                    FormId: 5,
                                    fieldID: 0
                                },
                                autoLoad: true,
                                root: "data",
                                fields: ["ID", "name"]
                            }),
                            listeners: {
                                'select': {
                                    fn: function(combo){
                                        if (this.view.store.lastOptions && this.view.store.lastOptions.params) {
                                            this.view.store.lastOptions.params['start'] = 0;
                                            this.view.store.lastOptions.params['limit'] = 6;
                                        }
                                        delete (this.view.store.baseParams['fields']);
                                        delete (this.view.store.baseParams['query']);
                                        this.view.store.baseParams['fields'] = '[Accounts.Country]';
                                        this.view.store.baseParams['query'] = combo.value;
                                        this.view.store.reload()
                                    },
                                    scope: this
                                }
                            }
                        }]
                    }]
                };
                Ext.apply(cfg, this.config);
                this.win = new Ext.Panel(cfg);
            }
            
            this.reset();
            this.win.render(el);
            //this.callback = callback;
            this.animateTarget = el;
        },
        
        initTemplates: function(){
            this.thumbTemplate = new Ext.XTemplate('<table><tr><tpl for="."><td><div class="thumb-wrap" ><table border=0 cellpadding=0 cellspacing=0 ><tr><td rowspan=8 valign="top" width="118"><tpl if="values.Logo"><div style="float:left">{[this.ImageRenderer(values.Logo, values.PTitle)]}</div></tpl></td></tr><tr><td valign="top" rowspan="8" style="width:20px">&nbsp;</td></tr>	<tr>		<td style="color:#c1000f;">{PTitle}</td></tr>	<tr><td>{Products}		<td></tr><tr><td>{Industry}<td></tr><tr><td>{PTitle}<td></tr><tr><td  width="125"><a href="http://{Url}" target="_blank" title="{PTitle}" >Visit Website</a><td></tr></table></div></td>{[xindex % 3 ===  0 ? "</tr><tr>" : ""]}</tpl></table>', this)
            
        },
        
        showDetails: function(){
            var selNode = this.view.getSelectedNodes();
            
            var detailEl = Ext.getCmp('img-detail-panel').body;
            if (selNode && selNode.length > 0) {
                //console.log(selNode)
                selNode = selNode[0];
                var data = this.lookup[selNode.id];
                detailEl.hide();
                this.detailsTemplate.overwrite(detailEl, data);
                detailEl.slideIn('l', {
                    stopFx: true,
                    duration: .2
                });
            }
            else {
                detailEl.update('');
            }
        },
        
        filter: function(){
        
            var filter = Ext.getCmp('filter');
            //this.view.store.filter('LTitle', filter.getValue());
            var matcher = this.view.store.data.createValueMatcher(filter.getValue(), true, false);
            this.view.store.filterBy(function(r){
                return matcher.test(r.data['Category1']) || matcher.test(r.data['Category2']) || matcher.test(r.data['Category3']) || matcher.test(r.data['Category4']) || matcher.test(r.data['LTitle']) || matcher.test(r.data['LDescrition']);
            });
            
            this.view.select(0);
        },
        
        sortImages: function(combo, record){
            if (combo.value == 'offering') {
                Ext.getCmp('ServiceSelector').show().clearValue()
                Ext.getCmp('IndustrySelector').hide().reset()
                Ext.getCmp('CountrySelector').hide().reset()
            }
            if (combo.value == 'industry') {
                Ext.getCmp('ServiceSelector').hide().reset()
                Ext.getCmp('IndustrySelector').show().clearValue()
                Ext.getCmp('CountrySelector').hide().reset()
            }
            if (combo.value == 'location') {
                Ext.getCmp('ServiceSelector').hide().reset()
                Ext.getCmp('IndustrySelector').hide().reset()
                Ext.getCmp('CountrySelector').show()
            }
        },
        
        reset: function(){
            if (this.win.rendered) {
                Ext.getCmp('filter').reset();
                this.view.getEl().dom.scrollTop = 0;
            }
            this.view.store.clearFilter();
            this.view.select(0);
        },
        
        doCallback: function(){
            var selNode = this.view.getSelectedNodes()[0];
            var callback = this.callback;
            var lookup = this.lookup;
            this.win.hide(this.animateTarget, function(){
                if (selNode && callback) {
                    var data = lookup[selNode.id];
                    callback(data);
                }
            });
        },
        
        onLoadException: function(v, o){
            this.view.getEl().update('<div style="padding:10px;">Error loading images.</div>');
        }
        
    },
    // TESTIMONIALS FOR BW
    CreateNewsColumnViewBWTestimonial: {
    
        TextRenderer: function(val){
            return val;
        },
        ReadMoreRenderer: function(Description){
            String.prototype.stripHTML = function(){
                // What a tag looks like
                var matchTag = /<(?:.|\s)*?>/g;
                var matchTag2 = /&(?:.|\s)*?;/g;
                var ret = this.replace(matchTag2, "");
                var ret = ret.replace(matchTag, "");
                //alert(ret)
                return ret
            };
            Description = Description.stripHTML();
            Description = Description.substr(0, 100) + '...';
            //console.log(Description)
            return Description
        },
        ImageRenderer: function(Desc, title){
            //console.log(Desc)
            var Description = Desc
            var matchTag = /\//g;
            AdminUrlNew = AdminUrl.replace(matchTag, "__");
            DescriptionNew = Description.replace(matchTag, "__");
            return '<a href="/index.php/WThumb/MaxHeight,400/MaxWidth,400/ImageServerPath,' + AdminUrlNew + DescriptionNew + '" ><img src="/index.php/WThumb/ImageServerPath,' + AdminUrlNew + DescriptionNew + '/MaxHeight,86/MaxWidth,156" alt="' + title + '" title="' + title + '"></a>'
        },
        DownloadRenderer: function(Description){
            if (Description != '') {
                var re = new RegExp('.pdf|.gif');
                var m = re.exec(Description);
                if (m != null) {
                    for (var i = 0; i < m.length; i++) {
                        var s = '';
                        s = s + m[i];
                    }
                    var matchTag = /\./g;
                    s = s.replace(matchTag, "");
                    
                    return "<a href='" + Description + "'><img src='/themes/Default/images/icons/" + s + ".png' alt='" + Description + "' title='" + Description + "' border='0'></a>";
                }
                else {
                    return Description;
                }
                
            }
            else {
                return "<img src='/themes/Default/images/icons/no_download.gif' alt='No Download Available' title='No Download Available' border='0'>";
            }
            
            
            
        },
        init: function(url, width, height, instance){
            this.config = {}
            this.config.url = url;
            this.config.width = width;
            this.config.height = height
            this.config.options = instance.options
            this.config.instance = instance;
            this.show('NewsDiv', Ext.emptyFn)
        },
        lookup: {},
        show: function(el, callback){
            if (!this.win) {
                this.store = new Ext.data.Store({
                    proxy: new Ext.data.HttpProxy({
                        url: this.config.url,
                        method: "POST"
                    }),
                    baseParams: {
                        Mid: this.config.options.Mid,
                        Out: 'Json'
                    },
                    reader: new Ext.data.JsonReader({
                        root: "row",
                        totalProperty: "TotalResults",
                        id: 'TestimonialId'
                    }, ['TestimonialId', 'Author', 'Designation', 'TDate', 'Testimonial', 'Logo', 'ClientId']),
                    "remoteSort": false,
                    listeners: {
                        'load': {
                            fn: function(){
                                // this.view.select(0);
                                this.view.emptyText = '<div style="padding:10px;">No images match the specified filter</div>'
                            },
                            scope: this,
                            single: true
                        }
                    }
                });
                
                
                this.store.load({
                    "params": {
                        "limit": 6,
                        "start": 0,
                        fields: '[Testimonial.ShowcaseTag]',
                        query: 305
                    }
                });
                
                var formatSize = function(data){
                    return data.size + " bytes";
                };
                
                var formatData = function(data){
                    this.lookup[data.LTitle] = data;
                    return data;
                };
                
                this.initTemplates();
                
                this.view = new Ext.DataView({
                    tpl: this.thumbTemplate,
                    singleSelect: true,
                    loadingText: "Loading....",
                    deferEmptyText: false,
                    overClass: 'x-view-over',
                    itemSelector: 'div.thumb-wrap',
                    store: this.store,
                    listeners: {
                        'loadexception': {
                            fn: this.onLoadException,
                            scope: this
                        }
                    },
                    prepareData: formatData.createDelegate(this)
                });
                
                var cfg = {
                    id: 'img-chooser-dlg',
                    layout: 'border',
                    minWidth: 700,
                    minHeight: 300,
                    loader: true,
                    closeAction: 'hide',
                    border: false,
                    bbar: new Ext.PagingToolbar({
                        store: this.store,
                        pageSize: 6,
                        displayInfo: true,
                        displayMsg: 'Displaying categories {0} - {1} of {2}',
                        emptyMsg: "No categories to display"
                    }),
                    items: [{
                        id: 'img-chooser-view',
                        region: 'center',
                        autoScroll: true,
                        items: this.view,
                        tbar: [{
                            text: 'Filter:'
                        }, {
                            id: 'MainSelector',
                            hidden: false,
                            xtype: 'combo',
                            typeAhead: true,
                            triggerAction: 'all',
                            width: 100,
                            editable: false,
                            mode: 'local',
                            displayField: 'desc',
                            value: 'offering',
                            valueField: 'name',
                            lazyInit: false,
                            store: new Ext.data.SimpleStore({
                                fields: ['name', 'desc'],
                                data: [['offering', 'offering'], ['industry', 'industry'], ['location', 'location']]
                            }),
                            listeners: {
                                'select': {
                                    fn: this.sortImages,
                                    scope: this
                                }
                            }
                        }, {
                            id: 'ServiceSelector',
                            hidden: false,
                            xtype: 'combo',
                            typeAhead: true,
                            triggerAction: 'all',
                            width: 100,
                            editable: false,
                            mode: 'local',
                            displayField: 'name',
                            emptyText: 'select',
                            valueField: 'ID',
                            lazyInit: false,
                            value: 'website',
                            store: new Ext.data.JsonStore({
                                url: "/index.php/SiteDataService/Module,DataEddValue",
                                baseParams: {
                                    FormId: 54,
                                    fieldID: 0
                                },
                                autoLoad: true,
                                root: "data",
                                fields: ["ID", "name"]
                            }),
                            listeners: {
                                'select': {
                                    fn: function(combo){
                                        if (this.view.store.lastOptions && this.view.store.lastOptions.params) {
                                            this.view.store.lastOptions.params['start'] = 0;
                                            this.view.store.lastOptions.params['limit'] = 6;
                                        }
                                        delete (this.view.store.baseParams['fields']);
                                        delete (this.view.store.baseParams['query']);
                                        this.view.store.baseParams['fields'] = '[Testimonial.ShowcaseTag]';
                                        this.view.store.baseParams['query'] = combo.value;
                                        this.view.store.reload()
                                    },
                                    scope: this
                                }
                            }
                        }, {
                            id: 'IndustrySelector',
                            hidden: true,
                            xtype: 'combo',
                            typeAhead: true,
                            triggerAction: 'all',
                            editable: false,
                            mode: 'local',
                            displayField: 'name',
                            valueField: 'ID',
                            lazyInit: false,
                            emptyText: 'select industry',
                            store: new Ext.data.JsonStore({
                                url: "/index.php/SiteDataService/Module,DataEddValue",
                                baseParams: {
                                    FormId: 49,
                                    fieldID: 0
                                },
                                autoLoad: true,
                                root: "data",
                                fields: ["ID", "name"]
                            }),
                            listeners: {
                                'select': {
                                    fn: function(combo){
                                        if (this.view.store.lastOptions && this.view.store.lastOptions.params) {
                                            this.view.store.lastOptions.params['start'] = 0;
                                            this.view.store.lastOptions.params['limit'] = 6;
                                        }
                                        delete (this.view.store.baseParams['fields']);
                                        delete (this.view.store.baseParams['query']);
                                        this.view.store.baseParams['fields'] = '[Accounts.Industry]';
                                        this.view.store.baseParams['query'] = combo.value;
                                        this.view.store.reload()
                                    },
                                    scope: this
                                }
                            }
                        }, {
                            id: 'CountrySelector',
                            hidden: true,
                            xtype: 'combo',
                            typeAhead: true,
                            triggerAction: 'all',
                            editable: false,
                            mode: 'local',
                            displayField: 'name',
                            valueField: 'ID',
                            lazyInit: false,
                            emptyText: 'select location',
                            store: new Ext.data.JsonStore({
                                url: "/index.php/SiteDataService/Module,DataEddValue",
                                baseParams: {
                                    FormId: 5,
                                    fieldID: 0
                                },
                                autoLoad: true,
                                root: "data",
                                fields: ["ID", "name"]
                            }),
                            listeners: {
                                'select': {
                                    fn: function(combo){
                                        if (this.view.store.lastOptions && this.view.store.lastOptions.params) {
                                            this.view.store.lastOptions.params['start'] = 0;
                                            this.view.store.lastOptions.params['limit'] = 6;
                                        }
                                        delete (this.view.store.baseParams['fields']);
                                        delete (this.view.store.baseParams['query']);
                                        this.view.store.baseParams['fields'] = '[Accounts.Country]';
                                        this.view.store.baseParams['query'] = combo.value;
                                        this.view.store.reload()
                                    },
                                    scope: this
                                }
                            }
                        }]
                    }]
                };
                Ext.apply(cfg, this.config);
                this.win = new Ext.Panel(cfg);
            }
            
            this.reset();
            this.win.render(el);
            //this.callback = callback;
            this.animateTarget = el;
        },
        
        initTemplates: function(){
            this.thumbTemplate = new Ext.XTemplate('<table><tpl for="."><tr><td><div class="thumb-wrap" style="float:none;" ><table border=0 cellpadding=0 cellspacing=0 ><tr><td rowspan=8 valign="top" width="118"><tpl if="values.Logo"><div style="float:left">{[this.ImageRenderer(values.Logo, "logo")]}</div></tpl></td></tr><tr><td valign="top" rowspan="8" style="width:20px">&nbsp;</td></tr>	<tr>		<td style="color:#c1000f;">date: {TDate}</td></tr>	<tr><td>author: {Author}		<td></tr><tr><td>designation: {Designation}<td></tr><tr><td>testimonial : {Testimonial}<td></tr></table></div></td></tr><tr></tpl></table>', this)
            
        },
        
        showDetails: function(){
            var selNode = this.view.getSelectedNodes();
            
            var detailEl = Ext.getCmp('img-detail-panel').body;
            if (selNode && selNode.length > 0) {
                //console.log(selNode)
                selNode = selNode[0];
                var data = this.lookup[selNode.id];
                detailEl.hide();
                this.detailsTemplate.overwrite(detailEl, data);
                detailEl.slideIn('l', {
                    stopFx: true,
                    duration: .2
                });
            }
            else {
                detailEl.update('');
            }
        },
        
        filter: function(){
        
            var filter = Ext.getCmp('filter');
            //this.view.store.filter('LTitle', filter.getValue());
            var matcher = this.view.store.data.createValueMatcher(filter.getValue(), true, false);
            this.view.store.filterBy(function(r){
                return matcher.test(r.data['Category1']) || matcher.test(r.data['Category2']) || matcher.test(r.data['Category3']) || matcher.test(r.data['Category4']) || matcher.test(r.data['LTitle']) || matcher.test(r.data['LDescrition']);
            });
            
            this.view.select(0);
        },
        
        sortImages: function(combo, record){
            if (combo.value == 'offering') {
                Ext.getCmp('ServiceSelector').show().clearValue()
                Ext.getCmp('IndustrySelector').hide().reset()
                Ext.getCmp('CountrySelector').hide().reset()
            }
            if (combo.value == 'industry') {
                Ext.getCmp('ServiceSelector').hide().reset()
                Ext.getCmp('IndustrySelector').show().clearValue()
                Ext.getCmp('CountrySelector').hide().reset()
            }
            if (combo.value == 'location') {
                Ext.getCmp('ServiceSelector').hide().reset()
                Ext.getCmp('IndustrySelector').hide().reset()
                Ext.getCmp('CountrySelector').show()
            }
        },
        
        reset: function(){
            if (this.win.rendered) {
                Ext.getCmp('filter').reset();
                this.view.getEl().dom.scrollTop = 0;
            }
            this.view.store.clearFilter();
            this.view.select(0);
        },
        
        doCallback: function(){
            var selNode = this.view.getSelectedNodes()[0];
            var callback = this.callback;
            var lookup = this.lookup;
            this.win.hide(this.animateTarget, function(){
                if (selNode && callback) {
                    var data = lookup[selNode.id];
                    callback(data);
                }
            });
        },
        
        onLoadException: function(v, o){
            this.view.getEl().update('<div style="padding:10px;">Error loading images.</div>');
        }
    }
}


Ext.override(Ext.grid.GridView, {
    layout: function(){
        if (!this.mainBody) {
            return;
        }
        var g = this.grid;
        var c = g.getGridEl(), cm = this.cm, expandCol = g.autoExpandColumn, gv = this;
        var csize = c.getSize(true);
        var vw = csize.width;
        if (vw < 20 || csize.height < 20) {
            return;
        }
        if (g.autoHeight) {
            csize.height = this.mainHd.getHeight() + this.mainBody.getHeight();
            if (!this.forceFit) {
                csize.height += this.scrollOffset;
            }
        }
        this.el.setSize(csize.width, csize.height);
        var hdHeight = this.mainHd.getHeight();
        var vh = csize.height - (hdHeight);
        this.scroller.setSize(vw, vh);
        if (this.innerHd) {
            this.innerHd.style.width = (vw) + 'px';
        }
        if (this.forceFit) {
            if (this.lastViewWidth != vw) {
                this.fitColumns(false, false);
                this.lastViewWidth = vw;
            }
        }
        else {
            this.autoExpand();
        }
        this.onLayout(vw, vh);
    }
});


