/*
 * Ext JS Library 2.2
 * Copyright(c) 2006-2009, Ext JS, LLC.
 * licensing@extjs.com
 * 
 * http://extjs.com/license
 */
	
Ext.onReady(function(){
	
	Ext.QuickTips.init();
	 
	// reference local blank image
	Ext.BLANK_IMAGE_URL = '../../../js/ext-2.2/resources/images/default/s.gif';

	Ext.override(Ext.tree.TreeEditor, {
		triggerEdit: function(node, defer){
			this.completeEdit();
			if (node.attributes.editable !== false) {
				this.editNode = node;
				if (this.tree.autoScroll) {
					Ext.fly(node.ui.getEl()).scrollIntoView(this.tree.body);
				}
				this.autoEditTimer = this.startEdit.defer(this.editDelay, this, [node.ui.textNode, node.text]);
				return false;
			}
		}
	});

	var st_id = 0;

	var stories_form = new Ext.FormPanel({
        labelAlign: 'top',
        region:'center',
        id: 'stories_form',  
        url: location.href,
        border: true,
       	//layout: 'fit',
        title: 'Editor',
        split: false,
       	animCollapse: true,
        margins: '5 5 5 5',
		bodyStyle:'padding:10px',
       	width: 520,
       	height:280,
        items: [{
            xtype:'textfield',
            fieldLabel: 'Abstract (preview text)',
            name: 'st_abstract',
            width:520
        },{
            xtype:'htmleditor',
            fieldLabel:'Article',
            name: 'st_story',
            width:520,
            height:250,
            enableColors: false,
			enableAlignments: false,
			enableFont: false,
			enableSourceEdit: false,
			enableFontSize: false
        }],
        buttons: [{
            text: 'Save', 
            handler: function() {
                // check form value 
                if (stories_form.getForm().isValid()) {
	 		        stories_form.getForm().submit({
						params: {st_id:st_id,st_mi_id:st_mi_id,st_published:0,st_delete:0,st_active:1,st_us_id:1,cmd:'save',edit_stories:1},
			            //waitMsg:'In processing',
			            failure: function(form, action) {
						    Ext.MessageBox.alert('Error Message', action.result.errorInfo);
						},
						success: function(form, action) {
						    //Ext.MessageBox.alert('Confirm', action.result.info);
						    stories_window.hide();
						    location=location.href;
						}
			        });                   
                } else{
					Ext.MessageBox.alert('Errors', 'Please fix the errors noted.');
				}             
	        }
        },{
            text: 'Cancel',
            //handler: function(){window.hide();}
            handler: function()
            {
            	stories_window.hide();
            	location=location.href;
            }
        }]
    });

    function doAdd() {	
		Ext.getCmp("stories_form").getForm().reset();
    }    
    
	function doEdit() {
		//Ext.getCmp("stories_form").getForm().loadRecord(st_id);	
		// OR
		
   		Ext.getCmp("stories_form").getForm().reset();
		Ext.getCmp("stories_form").load({
			url:location.href,
			failure:function(){Ext.getCmp("stories_form").getForm().reset();},
			method: 'post',
			params: {st_id:st_id,cmd:'load',edit_stories:1}
		});	
		
	}
    
	var tree_loader = new Ext.tree.TreeLoader({
     	dataUrl:location.href,
		baseParams: {st_mi_id:st_mi_id,cmd:'tree_load',edit_stories:1},
     	listeners:{
     		// select the first node
     		'load':  function(to,tn,response){
     			tn.childNodes[0].select();
     		}
     	}
     });

     var root = new Ext.tree.AsyncTreeNode({
     	id: "st_id",
     	text: "text",
	    //allowDrag:false,
        //allowDrop:false,
        expandable:false
     });
    // Group toolbar
    //var newIndex = 3;
    var tb = new Ext.Toolbar({
        items:[{
            text: 'Add Item',
            iconCls: 'add',
            handler: function(){/*
                var node = root.appendChild(new Ext.tree.TreeNode({
                    text:'הריון ' + (++newIndex),
                    cls:'album-node',
                    allowDrag:false
                }));
                tree.getSelectionModel().select(node);
                setTimeout(function(){
                    ge.editNode = node;
                    ge.startEdit(node.ui.textNode);
                }, 10);*/
            	Ext.Ajax.request({
					url: location.href,
					method: 'post',
					params: {st_mi_id:st_mi_id,cmd:'tree_add',edit_stories:1},
					callback: function(options, success, response){
						if (success==true){
							tree_loader.load(root);
						}
					}
				});
            }
        },{
        	text: 'Delete Item',
            iconCls: 'remove',
            handler: function(){
			var sn = tree.selModel.selNode || {};		
		        if(sn){
		        	Ext.MessageBox.confirm('Warning', 'Do you really want to delete this article?',function (btn,value){
	        		   if(btn == 'yes') {
				        	Ext.Ajax.request({
								url: location.href,
								method: 'post',
								params: {st_id:st_id,cmd:'tree_delete',edit_stories:1},
								callback: function(options, success, response){
									if (success==true){
										//sn.unselect();
								        Ext.fly(sn.ui.elNode).ghost('l', {
								    		callback: sn.remove, scope: sn, duration: .4
								        });
										//tree_loader.load(root);
										if (sn.previousSibling)
						     				tree.root.childNodes[0].select();
						     			else if (sn.nextSibling)
						     				tree.root.childNodes[1].select();
						     			else
						     				location=location.href;
									}
								}
							});	        		   		
						}
		        	});
	            }
            }
        }]
    });

    
     // This is the Details panel that contains the description for each example layout.
	var detailsPanel = {
		id: 'details-panel',
        title: 'Tips',
        region: 'south',
        height: 120,
        bodyStyle: 'padding-bottom:15px;background:#eee;',
		autoScroll: true,
		html: '<p class="details-info">When you click on an article from the list: - One Click: edit the content <br> Double Clicks: edit item title <br> Drag&Drop: set order </p>'
    };
    
    var tree = new Ext.tree.TreePanel({
         // tree
		useArrows:true,
        autoScroll:true,
        animate:true,
        enableDD:true,
        containerScroll: true,
		collapsible: false,
         collapsed: false,
         lines: false, 
         ddGroup: 'organizerDD',
         rootVisible:false,
         // layout
         region:'center',
         width:150,
         split:false,
         // panel
         title:'Our Services',
         autoScroll:true,
         tbar: tb,
         margins: '5 0 5 5',
         //root & loader
		 loader: tree_loader,
         root: root,
         listeners:{
            'render': function(tp){
                tp.getSelectionModel().on('selectionchange', function(tree, node){
                	if (node) {
                		st_id = node.attributes.st_id;
	                    //ge.editNode = node;
	                    //ge.startEdit(node.ui.textNode);
                		doEdit();
                	}
                	else {
                		st_id = 0;
                	}
                });
                
//               tp.getSelectionModel().select(tp.root.childNodes[1], null, true);  tp.render();
            },
            // Given a TreePanel object called "tree":
			'nodedrop': function (e) {
			    var json = "[";
				for (var i = 0; i < tree.root.childNodes.length; i++)
				{
					json = json + "{\"st_id\":\"" + tree.root.childNodes[i].attributes.st_id + "\",\"st_order\":\"" + (i+1) + "\"},";
				}
			   	json = json.substring(0,json.lastIndexOf(",")) + "]";
				
			   	Ext.Ajax.request({
					url: location.href,
					method: 'post',
					params: {json:json,cmd:'tree_edit_order',edit_stories:1},
					callback: function(options, success, response){
						if (success==true){
							tree_loader.load(root);
						}
					}
				});
			},
			'textchange': function (node,text,old_text) {
            	Ext.Ajax.request({
					url: location.href,
					method: 'post',
					params: {st_id:node.attributes.st_id,st_headline:text,cmd:'tree_edit_title',edit_stories:1},
					callback: function(options, success, response){
						if (success==true){
							tree_loader.load(root);
						}
					}
				});
			}
        }
    });

    // add an inline editor for the nodes
    var ge = new Ext.tree.TreeEditor(tree, {
        allowBlank:false,
        blankText:'A name is required',
        //editDelay: 300
        selectOnFocus:true
    });
    
    
   
/*
 * ================  BorderLayout config  =======================
 */

    // define window and show it in desktop
    var stories_window = new Ext.Window({
        title: 'Edit',
        width: 800,
        height:460,
        minWidth: 800,
        minHeight: 460,
        animate:true,
        //minHeight: 250,
        layout: 'border',
        plain:true,
        closeAction:'hide',
        bodyStyle:'padding:5px;',
        buttonAlign:'center',
        id:'stories_window',
        
        items: [{
			layout: 'border',
	        region:'west',
	        border: false,
	        //collapsed: false,
	        split:true,
	        closeAction:'hide',
			margins: '2 0 5 5',
	        width: 200,
	        //minSize: 100,
	        //maxSize: 500,
			items: [tree,detailsPanel]
			}
			,stories_form
		]
    	//items:[tree,stories_form]
    });
	//////////////////////////////
	 	stories_window.show(); 
		stories_window.hide();
	//////////////////////////////
});
		
function show_homepage_window()
{
 	Ext.getCmp("stories_window").show(); 
}