/*!
 * Ext JS Library 3.0.3
 * Copyright(c) 2006-2009 Ext JS, LLC
 * licensing@extjs.com
 * http://www.extjs.com/license
 */
var Tree;
var tree;
var createTree;
var selectedNode;
function loadTree()
{
Ext.onReady(function(){
    // shorthand
	Tree  = Ext.tree;
	tree = new Tree.TreePanel({
        useArrows: true,
        autoScroll: true,
        animate: true,
        enableDD: true,
        containerScroll: true,
        border: false,
        // auto create TreeLoader
        dataUrl: 'datahandler.php',
        
        root: {
            nodeType: 'async',
            text: 'Siden ',
            draggable: false,
            id: 'src'
        }
    });


		// render the tree
    	tree.render('tree-div');
    	tree.on("contextmenu",function(node){
    	//Set up some buttons
        selectedNode = node;
    	var button1 = new Ext.menu.Item({
    	text: "Opret menupunkt",
    	handler:function(node){
    		var node =selectedNode;
    		if(node.parentNode == undefined)
    		{
                    var test = 0;
    			if(node.lastChild != null)
                        {
                            test = parseInt(node.lastChild.attributes.position);
                        }

    			test++;
    			showPageHandle(0,'createPage',test,node.id);
    		}
    		else{
                var pos  = node.parentNode.lastChild.attributes.position
                pos++;
    		showPageHandle(0,'createPage',pos,node.id);
    		}
    		    		
    	}
    	});

    	var button2 = new Ext.menu.Item({
    	text: "Ret menupunkt",
    	handler:function(node){
    		var node =selectedNode;
    		
    		showPageHandle(node.id,'createPage','','');
    		    		
    	}
    	});

        var button3 = new Ext.menu.Item({
    	text: "Slet menupunkt",
    	handler:function(node){
    		var node =selectedNode;
    		if(node.firstChild == null)
                {
                    var answer = confirm("Er du sikker på du vil slette denne side?")
                    if (answer){
                    document.getElementById("inpDeletePage").value = node.id;
                    document.getElementById("deletePage").submit();
                    }
                }
                else
                {
                    alert('Du kan ikke slette dette menupunkt da der findes undersider');
                }
    	}
    	});


    	//Create the context menu to hold the buttons
    	var contextMenu = new Ext.menu.Menu();
    	contextMenu.add(button1, button2,button3);


    	//Show the menu
    	contextMenu.show(node.ui.getAnchor());
    	});
    	tree.expandAll();
});
}

function clickListener(node,event)
{
	document.getElementById('createPage').style.display = 'block';
	document.getElementById('spanRoot').innerText = node.text;
	document.getElementById('hidParentId').value = node.id;
}


function createNode()
{
	var parentId;
	var name;
	
	parentId = document.getElementById('hidParentId').value;
	name =document.getElementById('newPageName').value;
	
	 var received = function (response) {
		  x = Ext.decode( response.responseText );
		  console.log(this);
		  }

	
	
	Ext.Ajax.request(
	  		{
	  			url: 'ajax.php',
	  			success: received,
	  			failure: function (){console.log('failure');},
	  			headers: {'my-header': 'cmsTreeModified'},
	  			params:	{"name": name,"parentId": parentId, "operation": "addNodeToStructure"} 
	  		});
}


function saveTree()
{
	  
	  var s = new Ext.tree.XmlTreeSerializer(tree, {nodeFilter:function(node){return true}});
	  var received = function (response) {
	  x = Ext.decode( response.responseText );
	  console.log(this);
	  }

	  	Ext.Ajax.request(
	  		{
	  			url: 'ajax.php',
	  			success: received,
	  			failure: function (){console.log('failure');},
	  			headers: {'my-header': 'cmsTreeModified'},
	  			params:	{"treeXml": s, "operation": "updateStructure"} 
	  		}
	  		
	  	
	  	);
	  	
}

	
	/*global Ext*/

	/**
	 * @class Ext.tree.TreeSerializer
	 * A base class for implementations which provide serialization of an
	 * {@link Ext.tree.TreePanel}.
	 * <p>
	 * Implementations must provide a toString method which returns the serialized
	 * representation of the tree.
	 * 
	 * @constructor
	 * @param {TreePanel} tree
	 * @param {Object} config
	 */
	Ext.tree.TreeSerializer = function(tree, config){
	    if (typeof this.toString !== 'function') {
	    	throw 'Ext.tree.TreeSerializer implementation does not implement toString()';
	    }
		this.tree = tree;

		if (this.attributeFilter) {
			this.attributeFilter = this.attributeFilter.createInterceptor(this.defaultAttributeFilter);
		} else {
			this.attributeFilter = this.defaultAttributeFilter;
		}
		if (this.nodeFilter) {
			this.nodeFilter = this.nodeFilter.createInterceptor(this.defaultNodeFilter);
		} else {
			this.nodeFilter = this.defaultNodeFilter;
		}
		
		Ext.apply(this, config);

	};

	Ext.tree.TreeSerializer.prototype = {

		/*
		 * @cfg nodeFilter {Function} (optional) A function, which when passed the node, returns true or false to include
		 * or exclude the node.
		 */
		 
		/*
		 * @cfg attributeFilter {Function} (optional) A function, which when passed an attribute name, and an attribute value,
		 * returns true or false to include or exclude the attribute.
		 */
		 
		/*
		 * @cfg attributeMap {Array} (Optional) An associative array mapping Node attribute names to XML attribute names.
		 */

		/* @private
		 * Array of node attributes to ignore.
		 */
	    standardAttributes: ["expanded", "allowDrag", "allowDrop", "disabled", "icon",
	    "cls", "iconCls", "href", "hrefTarget", "qtip", "singleClickExpand", "uiProvider", "allowChildren", "expandable"],
	    

		/** @private
		 * Default attribute filter.
		 * Rejects functions and standard attributes.
		 */
		defaultAttributeFilter: function(attName, attValue) {
			return	(typeof attValue != 'function') &&
					(this.standardAttributes.indexOf(attName) == -1);
		},

		/** @private
		 * Default node filter.
		 * Accepts all nodes.
		 */
		defaultNodeFilter: function(node) {
			return true;
		}
	};

	/**
	 * @class Ext.tree.XmlTreeSerializer
	 * An implementation of Ext.tree.TreeSerializer which serializes an
	 * {@link Ext.tree.TreePanel} to an XML string.
	 */
	Ext.tree.XmlTreeSerializer = function(tree, config){
		Ext.tree.XmlTreeSerializer.superclass.constructor.apply(this, arguments);
	};

	Ext.extend(Ext.tree.XmlTreeSerializer, Ext.tree.TreeSerializer, {
		/**
		 * Returns a string of XML that represents the tree
		 * @return {String}
		 */
		toString: function(){
			return '<?xml version="1.0"?><tree>' +
				this.nodeToString(this.tree.getRootNode()) + '</tree>';
		},

		/**
		 * Returns a string of XML that represents the node
		 * @param {Object} node The node to serialize
		 * @return {String}
		 */
		nodeToString: function(node){
		    if (!this.nodeFilter(node)) {
		        return '';
		    }
		    var result = ''
		    if( node.id == 'src')
		    {
		    	result = '<rootNode';
		    }
		    else
		    {
		    	result = '<node';
		    }
		    
		    
		    
		    /**
		     *  This doesn't appear necessary. Since the iteration below will include id, 
		     *  this block simply includes it twice
		     
		    if (this.attributeFilter("id", node.id)) {
		        result += ' id="' + node.id + '"';
		    }
		    ***/

//			Add all user-added attributes unless rejected by the attributeFilter.
		    for(var key in node.attributes) {
		        if (this.attributeFilter(key, node.attributes[key]))
                        {
                            if([key] != "text"){
			        result += ' ' + (this.attributeMap ? (this.attributeMap[key] || key) : key) + '="' + node.attributes[key] + '"';
                            }
			}
		    }

//			Add child nodes if any
		    var children = node.childNodes;
		    var clen = children.length;
		    if(clen == 0){
		        result += '/>';
		    }else{
		        result += '>';
		        for(var i = 0; i < clen; i++){
		            result += this.nodeToString(children[i]);
		        }
		        
		        
		        if( node.id == 'src')
			    {
			    	result += '</rootNode>';
			    }
			    else
			    {
			    	 result += '</node>';
			    }
		        
		        
		       
		    }
		    return result;
		}

	});

	/**
	 * @class Ext.tree.JsonTreeSerializer
	 * An implementation of Ext.tree.TreeSerializer which serializes an
	 * {@link Ext.tree.TreePanel} to a Json string.
	 */
	Ext.tree.JsonTreeSerializer = function(tree, config){
		Ext.tree.JsonTreeSerializer.superclass.constructor.apply(this, arguments);
	};

	Ext.extend(Ext.tree.JsonTreeSerializer, Ext.tree.TreeSerializer, {

		/**
		 * Returns a string of Json that represents the tree
		 * @return {String}
		 */
		toString: function(){
		      return this.nodeToString(this.tree.getRootNode());
		},

		/**
		 * Returns a string of Json that represents the node
		 * @param {Object} node The node to serialize
		 */
		nodeToString: function(node){
//			Exclude nodes based on caller-supplied filtering function
		    if (!this.nodeFilter(node)) {
		        return '';
		    }
		    var c = false, result = "{";
		    /** don't double-include id
		    
		    if (this.attributeFilter("id", node.id)) {
		        result += '"id":"' + node.id + '"';
		        c = true;
		    }
		    
		    */

//			Add all user-added attributes unless rejected by the attributeFilter.
		    for(var key in node.attributes) {
		        if (this.attributeFilter(key, node.attributes[key])) {
			        if (c) {result += ',';}
			        result += '"' + (this.attributeMap ? (this.attributeMap[key] || key) : key) + '":"' + node.attributes[key] + '"';
			        c = true;
			    }
		    }
		
//			Add child nodes if any
		    var children = node.childNodes;
		    var clen = children.length;
		    if(clen != 0){
		        if (c) {result += ',';}
		        result += '"children":[';
		        for(var i = 0; i < clen; i++){
		            if (i > 0) {result += ',';}
		            result += this.nodeToString(children[i]);
		        }
		        result += ']';
		    }
		    return result + "}";
		}
	});	
	
	
	

