var qs = window.location.search;
if(qs.length > 1) qs = qs.substr(1) + "&";

function ajaxExpandHierarchyControl (clickedParent){
	
	var hierarchy = getParentHierarchy(clickedParent);

	var formID = clickedParent.rel;
	var level = clickedParent.rev;
	var fieldID = clickedParent.id.substr("parent_tree_".length);
	var tree = $("tree_"  + fieldID);
	var openID = fieldID.substr(fieldID.indexOf("_") + 1);
	fieldID = fieldID.substr(0, fieldID.indexOf("_"));
	
	if (level.length == 0) { level = 1 }
	
	if (tree){
		if (tree.getStyle("display") == "block") {
			tree.setStyle("display", "none");
			clickedParent.removeClass("expanded");
		} else {
			tree.setStyle("display", "block");
			clickedParent.addClass("expanded");
		}
	} else {
		
		if ($("InitialValue_" + fieldID)) {
			var fieldValue = $("InitialValue_" + fieldID).value;
		} else {
			var fieldValue = "";
		}
		
		// Make an AJAX call back to the page for the Form to pick up
		new Ajax(window.location.pathname + '?' + qs + '&ts=' + new Date().getTime(),{
			postBody: "requestType=ajax&action=expandHierarchy&formID=" + formID + "&fieldID=" + fieldID + "&openID=" + openID + "&level=" + level,
			method: "post",
			onComplete: function(response){
				
				var content = new Element("div").setHTML(response);
				
				content.getElements(".parent").each(function(parentEl){
				    parentEl.addClass("expandable");
				});
				
				content.getElements(".parent").addEvent("click", function(e){ 
					var clickedParent = new Event(e).target;
	    			new Event(e).stop();
	    			ajaxExpandHierarchyControl(clickedParent);
				});
				
				clickedParent.addClass("expanded");
				clickedParent.addClass("ajaxExpanded");
				
				content.getFirst().injectAfter(clickedParent.getParent());
				delete content;
				
				/* Recolour the hierarchy based on the newly opened items */
				colourHierarchy( hierarchy );
				
				/* Reinitialize the lightbox links as there may be new ones */
				Lightbox.init();
				
			}
		}).request();
		
	}
}

function initializeHierarchy( h ) {
    
    if ( h.typeOf = "string" ) { h = $( h ) }
    
    if ( $(h) ) {
    	
    	if (!h.hasClass("nonexpandable")) {
	    	if (h.hasClass("tree_control_ajax")) {
	    	
	    		// Attach handlers to all the parent links within the hierarchy
		        $$("#" + h.id + " a.parent").each(function(el){
		        
		            el.addClass("expandable");
		            
		            var fieldID = el.id.substr("parent_tree_".length);
					var tree = $("tree_"  + fieldID);
		            
		            if(tree) {
	        			el.addClass( "expanded" );
	        		}
		            
	        		el.addEvent("click",  function(e){
	                    var clickedParent = new Event(e).target;
	        			new Event(e).stop();
	        			ajaxExpandHierarchyControl(clickedParent);
	        		});
	        		
		    	});
		    	
		    } else {
	    	
		        // Hide all sub items in the hierarchy
		        $$("#" + h.id + " ul ul").each(function(el){
		            if (h.hasClass("hExpandable") || h.hasClass("libraryHierarchy")) {
		                show(el.id);
		            } else {
		                hide(el.id);
		    		}
		    	});
		
		    	// If the item is not AJAX expandable then expand it from the relevant cookie
		        if (!h.hasClass("hExpandable")) {
		            var strCookie = Cookie.get( h.id );
		        	if ( !strCookie ) { strCookie = "" };
		            strCookie.split( "," ).each(function(el){
		                show( el );
		                if ($("parent_" + el)) { $("parent_" + el).addClass("expanded"); }
		            });
		        }
		        
		        // Attach handlers to all the parent links within the hierarchy
		        $$("#" + h.id + " a.parent").each(function(el){
		            el.addClass("expandable");
		            if (h.hasClass("hExpandable")) {
		                if( $ES( "ul", $("Item_" + el.getProperty("rel"))).length > 0) {
		        			el.addClass( "expanded" );
		        		}
		        		el.addEvent("click",  function(e){
		                    var clickedParent = new Event(e).target;
		        			new Event(e).stop();
		        			ajaxExpandable(clickedParent);
		        		});
		            } else {
		    			el.addEvent("click", function(e) {
		                    var clickedParent = new Event(e).target;
		    				new Event(e).stop();
		    				hierarchyParentClick(clickedParent);
		    				colourHierarchy( getParentHierarchy( clickedParent ) );
		    			});
		        	}
		    	});
		    	
		    }
		}
	    
	    // Handle sortable hierarchies
    	if (h.hasClass("sortable")) {
        	$$("#" + h.id + " .sortableColumn").each(function(el){
                hide( el );
            });
        	$$("#" + h.id + " ul").each(function(el){
        		makeSortable(el);
        	});
    	}
    	
    	// Colour the alternating rows
    	colourHierarchy( h );
    	
    }
	
}

function getParentHierarchy( parentHElement ) {
    if ( parentHElement.parentNode ) {
		if ( $(parentHElement).getParent().hasClass("hierarchy") ) {
            return parentHElement.parentNode;
        } else {
            return getParentHierarchy( parentHElement.parentNode );
        }
    }
}

function hierarchyParentClick( el ) {
    if( el.id ) {
    	if(showhidecookie( el.id.substring( 7 ), getParentHierarchy( el ).id ) == "shown"){
			el.addClass("expanded");
    	} else {
    		el.removeClass("expanded");
    	}
    }
}

function ajaxExpandable(el){
	var url = window.location.pathname;
	var hierarchy = getParentHierarchy(el);
	if(!$(el.getProperty("rel"))){
		new Ajax(url,{
			postBody: qs + "requestType=ajax&ajaxAction=expand&expandID=" + el.getProperty("rel") + "&level=" + $("Item_" + el.getProperty("rel")).getProperty("rel") + '&ts=' + new Date().getTime(),
			method: "get",
			onComplete: function(response){
				
				var content = new Element("div").setHTML(response);
				
				content.getElements(".parent").each(function(parentEl){
				    parentEl.addClass("expandable");
				});
				
				content.getElements(".parent").addEvent("click", function(e){ 
					var event = new Event(e).stop();
					ajaxExpandable(this);
				});
				
				el.addClass("expanded");
				
				content.getFirst().injectAfter(el.getParent());
				
				if(hierarchy.hasClass("sortable")){
				    makeSortable(el.getParent().getNext());
				}
				
				delete content;
				
				/* Recolour the hierarchy based on the newly opened items */
				colourHierarchy( hierarchy );
				
				/* Reinitialize the lightbox links as there may be new ones */
				Lightbox.init();
				
			}
		}).request();
		
	} else {
	   if ( $(el.getProperty("rel")).getStyle('display') == 'block' ) {
            el.removeClass("expanded");
            hide( $(el.id.substring( 7 )) );
            new Ajax(url,{
                postBody: qs + "requestType=ajax&ajaxAction=expand&hideID=" + el.getProperty("rel") + '&ts=' + new Date().getTime(),
                method: "get"
            }).request();
	   } else {
			el.addClass("expanded");
	       show( $(el.id.substring( 7 )) );
	       new Ajax(url,{
    			postBody: qs + "requestType=ajax&ajaxAction=expand&showID=" + el.getProperty("rel") + '&ts=' + new Date().getTime(),
    			method: "get"
    		}).request();
	   }
	   colourHierarchy( hierarchy );
	}
	
}

function getSortedListIDs(el){
	var ids = [];
	el.getParent().getChildren().each(function(item){ ids.push(item.getProperty("id")) });
	new Ajax(window.location.pathname,{
		postBody: qs + "requestType=ajax&ajaxAction=sort&sortedIDs=" + ids.toString() + '&ts=' + new Date().getTime(),
		method: "get"
	}).request();
}

function makeSortable(el){
    var handles = el.getChildren("li");
    var newHandles = new Array();
    handles.each(function(li){
        if (li.hasClass("notSortable")) {
            li.setStyle("cursor", "default");
        } else {
            newHandles.push(li);
            li.setStyle("cursor","move");
        }
    });
    el.getElements(".sortableColumn").each(function(sortableColumn){ sortableColumn.setStyle("display", "none") });
    if(el.getElements("li").length > 1) {
    	new Sortables(el, {
    		onDragStart: function(orig,ghost){
    			//stops the text selecting in ie7
    			ghost.setStyle("visibility","hidden");
    		},
    		onDragComplete: function(orig,ghost){
    			ghost.remove();
    		},
    		onStart: function(item){ 
    			this.serializedList = this.serialize();
    			this.classTimer = (function(){ item.addClass("drag"); }).delay(100);
    		},
    		onComplete: function(item){
    			clearTimeout(this.classTimer);
    			item.removeClass("drag");
    			if(this.serializedList.toString() != this.serialize().toString()){
    				getSortedListIDs(item);
    				colourHierarchy( getParentHierarchy(el) );
    			}
    		},
            handles: newHandles	
    	});
	}
}

function makeSortableTable(table) {
    table.getElements(".sortableColumn").each(function(sortableColumn){ sortableColumn.setStyle("display", "none") });
	
	var tbody = table.getElement("tbody");

    if(tbody.getElements("tr").length > 1) {
	tbody.setStyle("cursor","move");
		new Sortables(tbody, {
			onDragStart: function(orig,ghost){
				//stops the text selecting in ie7
				ghost.setStyle("visibility","hidden");
			},
			onDragComplete: function(orig,ghost){
				ghost.remove();
			},
			onStart: function(item){ 
				this.serializedList = this.serialize();
				this.classTimer = (function(){ item.addClass("drag"); }).delay(100);
			},
			onComplete: function(item){
				clearTimeout(this.classTimer);
				item.removeClass("drag");
				if(this.serializedList.toString() != this.serialize().toString()){
					getSortedListIDsForTable(item, table);
					colourTable(table);
				}
			}
						
		});
	}
}

function getSortedListIDsForTable(el, table){
	var ids = [];
	el.getParent().getChildren().each(function(item){ ids.push(item.getProperty("id")) });
	new Ajax(window.location.pathname,{
		postBody: qs + "requestType=ajax&ajaxAction=sort&sortedIDs=" + ids.toString() + "&tableID=" + table.id + '&ts=' + new Date().getTime(),
		method: "get"
	}).request();
}

function colourHierarchy( hierarchy ){
	var counter = 0;
	$ES("li", $(hierarchy)).each(function(li){
		if(li.getParent().getStyle("display") == "block"){
			if(counter % 2 == 0){
				li.removeClass("darkrow");
				li.addClass("lightrow");
			} else {
				li.removeClass("lightrow");
				li.addClass("darkrow");
			}
			counter++;
		}
	});
}

window.addEvent("load", function(){
	
	$$("div.hierarchy").each(function(el){
		initializeHierarchy(el);
	});
	
	$$("table.sortable").each(function(el){
		makeSortableTable(el);
	});
	
});

