Ext.onReady(function() {
    //page loading animation -start
    setTimeout(function(){
        Ext.get('loading').remove();
        Ext.get('loading-mask').fadeOut({
            remove:true
        });
    }, 250);
    //page loading animation -end

    Ext.state.Manager.setProvider(new Ext.state.CookieProvider());
    var postsStore= Ext.create('Ext.data.Store', {
        //        autoLoad:true,
        storeId:'PostsStore',
        pageSize:40,
        fields: ['id','blog_post_summery','blog_post_title','blog_post_url','blog_name','blog_url',
        {
            name:'posted_time',
            type:'time',
            dateFormat:'timestamp'
        }
        ],
        proxy: {
            type: 'ajax',
            extraParams: {
                language : language
            },
            api: {
                read: '/ajax-data/all-blog-posts'//,
            //                update: '',
            //                //create: '',
            //                destroy: ''
            },
            reader: {
                type: 'json',
                root: 'data',
                successProperty: 'success',
                idProperty: 'id',
                totalProperty: 'total'
                
            }

        }

    });
    postsStore.load();

    //SOF blog data

    var blogsStore= Ext.create('Ext.data.Store', {
        autoLoad:true,
        storeId:'BlogsStore',
        pageSize:40,
        fields: ['id','blog_name','blog_url'],
        proxy: {
            type: 'ajax',
            api: {
                read: '/ajax-data/get-blog-list/type/approved'//,
            //                update: '',
            //                //create: '',
            //                destroy: ''
            },
            reader: {
                type: 'json',
                root: 'data',
                successProperty: 'success',
                idProperty: 'id',
                totalProperty: 'total'

            }

        }

    });
    //EOF Blogs data


    var blogPostTemplate =new Ext.XTemplate('<tpl for=".">'+
        '<div class="post-item" id="{id}">'+
        '<div class="post-header"><a href="{blog_post_url}" class="post_url" target="_blank">{blog_post_title}</a> | <a href="{blog_url}" target="_blank">{blog_name}</a> | <span class="posted_time"> on {posted_time}</span></div>'+
        '<div class="summery">{blog_post_summery} <a href="{blog_post_url}" target="_blank">Read More ..</a></div>'+
        '<hr/></div></tpl>');

    var blogListTemplate =new Ext.XTemplate('<ul><tpl for=".">'+
        '<li class="blog-listing"><a href="{blog_url}" target="_blank" >{blog_name}</a></li>'+
        '</tpl></ul>');
    
    var signup= Ext.create('Ext.form.Panel', {
        url:'/ajax-data/add-new-blog',
        id:'signupForm',
        success:this.onSuccess,
        failure:this.onFailure,
        params:{
            cmd:'save'
        },
        waitMsg:'Saving...',
        bodyStyle:'padding:5px 5px 0',
        width: 350,
        fieldDefaults: {
            msgTarget: 'side',
            labelWidth: 100
        },
        defaultType: 'textfield',
        defaults: {
            anchor: '100%'
        },
        items: [{
            fieldLabel: 'Blog Address',
            name: 'blog_url',
            vtype:'url',
            allowBlank:false
        },
        {
            fieldLabel: 'Feed Address',
            name: 'feed_url',
            vtype:'url',
            allowBlank:false
        },
        {
            fieldLabel: 'Blog Name',
            name: 'blog_name',
            allowBlank:false
        }
        ,{
            fieldLabel: 'Your Name',
            name: 'author_name',
            allowBlank:false
        }, {
            fieldLabel: 'Your Email',
            name: 'author_email',
            vtype:'email',
            allowBlank:false
        },{
            xtype:          'combo',
            mode:           'local',
            triggerAction:  'all',
            forceSelection: true,
            editable:       false,
            fieldLabel:     'Language',
            name:           'language',
            displayField:   'name',
            valueField:     'value',
            queryMode: 'local',
            store:          Ext.create('Ext.data.Store', {
                fields : ['name', 'value'],
                data   : [
                {
                    name : 'Sinhala',
                    value: 'si'
                },

                {
                    name : 'English',
                    value: 'en'
                },

                {
                    name : 'Tamil',
                    value: 'ta'
                }
                ]
            })
        },
        {
            xtype: 'checkbox',
            name: 'agree',
            boxLabel: 'I have read and agree with <a href="#">terms and conditions</a>',
            hideLabel: true,
            checked: true,
            id:'agree',
            style: 'margin:10px;'
        }
        ],
        buttons: [{
            text: 'Save',
            handler : function (){
                var formTemp = Ext.getCmp('signupForm')
                if(Ext.getCmp('agree').getValue()){

                    Ext.getCmp('signupForm').submit({
                        success: function(formTemp, action) {
                            if(formTemp.isValid()){
                                Ext.Msg.alert('Success', action.result.message);
                            }else{
                                Ext.Msg.alert('Failed','please select a language');
                            }
                        },
                        failure: function(formTemp, action) {
                            Ext.Msg.alert('Failed', action.result.message);
                        }
                    });

                }else{
                    Ext.MessageBox.alert('Error', 'You must agree with terms and conditions to add your blog');
                }
            }
        },{
            text: 'Cancel',
            handler : function (){
                winSignup.hide()
            }
        }]
    });
    var siPressed,taPressed,enPressed;
    if(language=='all'){
        siPressed=true;
        taPressed=true;
        enPressed=true;
    }else if(language=='si'){
        siPressed=true;
        taPressed=false;
        enPressed=false;
    }else if(language=='ta'){
        siPressed=false;
        taPressed=true;
        enPressed=false;
    }else if(language=='en'){
        siPressed=false;
        taPressed=false;
        enPressed=true;
    }
    var mainToolbar = Ext.createWidget('toolbar', {
        renderTo: Ext.getBody(),
        items   : [
        {
            height:30,
            xtype: 'label',
            contentEl:'header'
        }
        ,'->',
        {
            xtype: 'buttongroup',
            //            title: 'Language',
            columns: 4,
            defaults: {
                scale: 'small'
            },
            stateId : 'Language',
            items: [
            {
                text:'Language',
                disabled:true
            //                margin: '5 5 5 5!important'
            },
            {
                text: 'Si',
                enableToggle: true,
                pressed:siPressed
            //            toggleHandler: onItemToggle,
            },
            {

                text: 'Ta',
                enableToggle: true,
                pressed:taPressed
            //            toggleHandler: onItemToggle,
            },
            {
                text: 'En',
                enableToggle: true,
                pressed:enPressed
            //            toggleHandler: onItemToggle,

            }]
        },{
            xtype: 'buttongroup',
            //            title: 'Actions',
            columns: 5,
            defaults: {
                scale: 'small'
            },
            stateId : 'actions',
            items: [
            {
                text: 'Add your blog',
                id:'signup',
                iconCls: 'feed_add'
            },
            {
                text: 'Subscribe',
                iconCls: 'email',
                menu:[
                {
                    text:'Sinhala',
                    handler:function(){
                        window.open('http://feedburner.google.com/fb/a/mailverify?uri=hathmaluwa/sinhala&amp;loc=en_US', 'popupwindow', 'scrollbars=yes,width=550,height=520');
                    }      
                },
                {
                    text:'English',
                    handler:function(){
                        window.open('http://feedburner.google.com/fb/a/mailverify?uri=hathmaluwa/english&amp;loc=en_US', 'popupwindow', 'scrollbars=yes,width=550,height=520');
                    }
                },
                {
                    text:'Tamil',
                    handler:function(){
                        window.open('http://feedburner.google.com/fb/a/mailverify?uri=hathmaluwa/tamil&amp;loc=en_U', 'popupwindow', 'scrollbars=yes,width=550,height=520');
                    }
                }
                ]
       
            },
            //            {
            //                text: 'Search Blogs',
            //                iconCls: 'feed_magnify'
            //            },
            {
                text: 'Link to us',
                iconCls: 'world_link',
                id:'link_to_us'
                
            },
            {
                text: 'Keep In Touch',
                iconCls: 'hathmaluwa',
                id:'contact_us'
            }
            ]
        }
        ]
    });
    
    Ext.create('Ext.container.Viewport', {
        layout: 'border',
        items: [{
            region: 'north',
            autoHeight: true,
            border: false,
            dockedItems:mainToolbar,
            height:36
        }, {
            region: 'west',
            xtype:'tabpanel',
            activeTab: 0,
            minWidth:250,
            stateId: 'LeftPanelState',
            collapsible: true,
            title: 'Links',
            split: true,
            width:"23%",
            dockedItems: [],
            items: [{
                title: 'Search Blogs',
                iconCls: 'feed_magnify',
                autoHeight: true,
                height:"100%",
                autoScroll:true,
                dockedItems: [
                {
                    xtype: 'toolbar',
                    items: ['->',
                    {
                        xtype: 'searchfield',
                        width: 240,
                        store:blogsStore
                    }
                    ]
                }, {
                    xtype: 'pagingtoolbar',
                    store: blogsStore,   // same store GridPanel is using
                    dock: 'bottom',
                    displayInfo: false//,
                //                    plugins: Ext.create('Ext.ux.SlidingPager', {})
                }],
                items: [{
                    xtype:'dataview',
                    //   Ext.data.StoreManager.lookup('PostsStore')
                    store: blogsStore,
                    emptyText : "no content to display",
                    tpl: blogListTemplate,
                    itemSelector: 'blog-post-wrap'
                }]
            },{
                title: 'Vote for Us',
                html:'<div class="sahithya"><a href="http://www.sahithya.lk/sinhala-blogging-competition/" target="_blank"><img src="http://www.sahithya.lk/wp-content/uploads/2011/08/od-150x150.jpg" width="150" height="150" border="0" title="විවෘත අංශය"></a></div>'
            }]
            
        },{
            region: 'center',
            id:'centerwindow',
            border:true,
            autoHeight: true,
            height:"100%",
            autoScroll:true,
            dockedItems: [{
                xtype: 'pagingtoolbar',
                store: postsStore,   // same store GridPanel is using
                dock: 'bottom',
                displayInfo: true,
                items: ['->',
                {
                    xtype: 'searchfield',
                    width: 200,
                    store:postsStore
                }
                ]
            }],
            items: [{
                title: 'Home',
                xtype:'dataview',
                emptyText : "no content to display",
                //   Ext.data.StoreManager.lookup('PostsStore')
                store: postsStore,
                tpl: blogPostTemplate,
                itemSelector: 'blog-item-wrap'
            }]
        }
        ]

    });
    //signup onclick
    
    var winSignup,
    button = Ext.get('signup');
    button.on('click', function(){
        if (!winSignup) {
            winSignup = Ext.create('widget.window', {
                title: 'Add Your Blog to Hathmaluwa',
                modal:true,
                closable: true,
                closeAction: 'hide',
                width: 450,
                minWidth: 350,
                height: 350,
                layout: 'fit',
                bodyStyle: 'padding: 5px;',
                items:signup
            });
        }
        button.dom.disabled = true;
        if (winSignup.isVisible()) {
            winSignup.hide(this, function() {
                button.dom.disabled = false;
            });
        } else {
            winSignup.show(this, function() {
                button.dom.disabled = false;
            });
        }
    });
    //link to us
    var imgTpl = new Ext.XTemplate( [
        '<tpl for=".">',
        '<div class="wid-thumb-wrap" id="{id}">',
        '<div class="wid-thumb"><img src="{url}"></div>',
        //        '<span>{size}</span>',
        '<div><textarea rows="5" cols="50" class="x-form-textarea x-form-field wid-code" ><a href="{code}" title="hathmaluwa" target="_blank" > <img src="{code}{url}" alt="hathmaluwa" /> </a></textarea></div> </div>',
        '</tpl>',
        '<div class="x-clear"></div>'
        ]);
    var Widstore = Ext.create('Ext.data.Store', {
        fields: ['id','url','size','code'],
        proxy: {
            type: 'ajax',
            api: {
                read: '/ajax-data/list-widgets'//,
            },
            reader: {
                type: 'json',
                root: 'images'
            }

        }
    })
    Widstore.load();

    var winLinktoUs,
    buttonLinktoUs = Ext.get('link_to_us');
    buttonLinktoUs.on('click', function(){
        if (!winLinktoUs) {
            winLinktoUs = Ext.create('widget.window', {
                title: 'Link back to hathmaluwa',
                modal:true,
                closable: true,
                closeAction: 'hide',
                autoScroll:true,
                width: 700,
                minWidth: 600,
                height: 600,
   
                layout: 'fit',
                bodyStyle: 'padding: 5px;',
                items:[{
                    xtype:'dataview',
                    style:{
                        background: "#FFFFFF"
                    },
                    //   Ext.data.StoreManager.lookup('PostsStore')
                    store: Widstore,
                    emptyText : "no content to display",
                    tpl:imgTpl,
                    itemSelector: 'images-view-wrap',
                    id: 'images-view'
                }]
            });
        }
        buttonLinktoUs.dom.disabled = true;
        if (winLinktoUs.isVisible()) {
            winLinktoUs.hide(this, function() {
                buttonLinktoUs.dom.disabled = false;
            });
        } else {
            winLinktoUs.show(this, function() {
                buttonLinktoUs.dom.disabled = false;
            });
        }
    });

    var winContactUs,
    buttonContactUs = Ext.get('contact_us');
    buttonContactUs.on('click', function(){
        if (!winContactUs) {
       
            winContactUs = Ext.create('widget.window', {
                title: 'Keep In Touch',
                modal:true,
                closable: true,
                closeAction: 'hide',
                width: 600,
                minWidth: 500,
                height: 500,
                bodyStyle: 'padding: 5px;',
                items: [{
                    xtype: 'fieldset',
                    title: 'Email',
                    autoHeight:true,
                    items: [
                    {
                        html:"<a href='mailto:admin@hathmaluwa.org'>admin@hathmaluwa.org</a>",
                        id:'admin-email',
                        style:{
                            padding:"10px 0",
                            border:false
                        }
                    }
                    ]
                },
                {
                    xtype: 'fieldset',
                    title: 'Social Media',
                    //            defaultType: 'textfield',
                    //            defaults: {
                    //                width: 280
                    //            },
                    items: [
           
                    {
                        html:'<div>Recommend Hathmaluwa to your facebook friends</div><iframe src="//www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.hathmaluwa.org%2F&amp;send=false&amp;layout=standard&amp;width=450&amp;show_faces=true&amp;action=like&amp;colorscheme=light&amp;font&amp;height=80" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:450px; height:80px;" allowTransparency="true"></iframe>',
                        style:{
                            padding:"10px 0"
                        }
                    },{
                        html:'<div>Join Hathmaluwa Facebook Fans </div><iframe src="//www.facebook.com/plugins/like.php?href=http%3A%2F%2Ffacebook.com%2Fhathmaluwa&amp;send=false&amp;layout=standard&amp;width=450&amp;show_faces=true&amp;action=like&amp;colorscheme=light&amp;font&amp;height=80" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:450px; height:80px;" allowTransparency="true"></iframe>',
                        style:{
                            padding:"10px 0"
                        }
                    }
               

                    ]
                }

                ]

            });
         
        }
        buttonContactUs.dom.disabled = true;
        if (winContactUs.isVisible()) {
            winContactUs.hide(this, function() {
                buttonContactUs.dom.disabled = false;
            });
        } else {
            winContactUs.show(this, function() {
                buttonContactUs.dom.disabled = false;
            });
        }
    });



});
  
