/**
 * Intranet Javascript File - Web Fu!
 *
 * @author Eruera Goodwin
 * @package Web Fu! Intranet! Ka Pow!
 * @dependencies Prototype Library
 * @desc Written using Object Literal notation - should
 * make it compatible with any other JavaScript files
 *
 */

    var intranet = {
    
        /* Instantiate some global variables */
        delimiter: '<!-- Delimiter -->', /* Used to delimit AJAX strings */
        currentCategory: null, /* Set variables to hold current category and file for highlighting */
        currentFile: null,
        tree: 'tree',

        /* Initialize function */
        init: function() {

			if($(intranet.tree)) {
				intranet.attachToggles(); /* Attach Plus/Minus handles to the file tree */
				intranet.attachCategoryView(); /* Attach AJAX call on category click */
				intranet.attachTreeControls();
				intranet.expandAll(); /* Drop the class names on first */
		//		intranet.attachSearchHandler();
			}

			if(!$('wrapper')) return;

			$('wrapper').style.display = 'block'; /* Show wrapper after turning it off */

        },	

		attachToggles: function(e) {

			if(e != undefined) {
				Event.stop(e);
				fired = true; /* Happened on click */
			} else {
				fired = false; /* Happened on load */
			}

			thetree = $(intranet.tree);
			items = $A(thetree.getElementsByTagName('li'));

			items.each(function(item) {

				theClass = 'li-closed';

				if(Element.hasClassName(item, 'li-open')) {
					Element.removeClassName(item, 'li-open');
					Element.addClassName(item, theClass);
				} else {
					if(Element.hasClassName(item, 'banana')) {
						Element.addClassName(item, 'li-open');
						Element.removeClassName(item, 'banana');
					} else {
						Element.removeClassName(item, 'li-open');
						Element.addClassName(item, theClass);
					}
				}

       		});

			if(!fired) { /* Only being done once */

				spans = $A(items[0].getElementsByTagName('span'));
				spans.each(function(span) {

					Event.observe(span, 'click', intranet.toggleCategory);

				});

			}

        },

        attachCategoryView: function() {

			links = document.getElementsByClassName('category');

			links.each(function(link) {
				Event.observe(link, 'click', intranet.categoryAjax);
			});

        },

        attachTreeControls: function() {
			
			controlList = $('tree-control');
			
			controls = $A(controlList.getElementsByTagName('li'));
			
			controls.each(function(control) {
			
				switch(control.className) {
					case 'collapse-all':

						Event.observe(control.firstChild, 'click', intranet.attachToggles);

					break;
					case 'expand-all':
					
						Event.observe(control.firstChild, 'click', intranet.expandAll);
					
					break;
				}
			
			});
			
        },
        
        toggleCategory: function(e) {

			Event.stop(e);
        	span = Event.element(e);
        	theParent = span.parentNode;
        	
        	if(Element.hasClassName(theParent, 'li-closed')) {
				Element.addClassName(theParent, 'li-open');
				Element.removeClassName(theParent, 'li-closed');
        	} else {
				Element.removeClassName(theParent, 'li-open');
				Element.addClassName(theParent, 'li-closed');
        	}

        },
        
        categoryAjax: function(e) {

			Event.stop(e);
			link = Event.element(e);

			intranet.doCurrentThing(link.parentNode, 'category');
			intranet.cancelForm();

			url = link.getAttribute('href');
		
			var AjaxCall = new Ajax.Request(
				url,
				{
					method: 'post',
					onCreate: intranet.showLoading(),
					onComplete: intranet.handleAjax
				});
			
        },

        handleAjax: function(request) {

			intranet.ditchLoading();
			response = request.responseText.split(intranet.delimiter);

			files = document.getElementsByClassName('files', 'col-one');

			files.each(function(ul) {

				Element.update(ul, response[0]);
				links = $A(ul.getElementsByTagName('a'));

				links.each(function(link) {
					Event.observe(link, 'click', intranet.detailsAjax);
				});

			});

			Element.update($('admin-files'), response[1]);

			as = $A($('admin-files').getElementsByTagName('a')); /* A's, as in, <a href...></a> */
			as.each(function(a) {
				Event.observe(a, 'click', intranet.t2Ajax); /* t2Ajax (transform 2 Ajax) */
			});

			intranet.setDetails(null);

        },
        
        detailsAjax: function(e) {

			Event.stop(e);
			link = Event.element(e);
			
			intranet.doCurrentThing(link.parentNode, 'file');
			
			url = link.getAttribute('href');
			
			var AjaxCall = new Ajax.Request(
				url,
				{
					method: 'post',
					onCreate: intranet.showLoading(),
					onComplete: intranet.handleMajax
				}
			);

        },
        
        setDetails: function(first, second, third) {

			if(first == null) {
				first = '';
				second = '';
				third = '';
			}

			details = document.getElementsByClassName('details-box', 'col-two');

			details.each(function(detail) {
				Element.update(detail, first);
			});

			download = document.getElementsByClassName('download-box', 'col-two');
			
			download.each(function(dlbox) {
				Element.update(dlbox, second);
			});

			Element.update($('admin-details'), third);

        },
        
        handleMajax: function(request) {

			intranet.ditchLoading();
			response = request.responseText.split(intranet.delimiter);
			intranet.setDetails(response[0], response[1], response[2])

			as = $A($('admin-details').getElementsByTagName('a')); /* A's, as in, <a href...></a> */
			as.each(function(a) {
				Event.observe(a, 'click', intranet.t2Ajax); /* t2Ajax (transform 2 Ajax) */
			});

        },
        
        t2Ajax: function(e) {
			Event.stop(e);
			link = Event.element(e);

			url = link.getAttribute('href');

			/* Put content into $('col-wide') div */
			var AjaxCall = new Ajax.Updater(
				'col-wide',
				url,
				{
					method: 'post',
					onComplete: function() {
						intranet.alterPage();
						intranet.prepareForm();
					}
				}
			);

        },

        doCurrentThing: function(changeTo, toChange) {
			/* Take the class off of the current one */

			switch(toChange) {
				case 'file':
					current = $(intranet.currentFile);
				break;
				default: /* Assume category */
					current = $(intranet.currentCategory);
				break;
			}

			if(current) {
				newClass = current.className.replace(' on', '');
				current.className = newClass;
			}

			willGoTo = ' k on'; /* Use k as a placeholder ... very BAD - will try figure out a way around soon */
			changeTo.className += willGoTo; /* Append, instead of replacing */

			if(toChange == 'file') {
				intranet.currentFile = changeTo;
			} else {
				intranet.currentCategory = changeTo;			
			}
			
        },
        
        prepareForm: function() {

			wide = $('col-wide');
			aForm = wide.getElementsByTagName('form').item(0);

			cancelButton = document.getElementsByName('cancel').item(0);

			Event.observe(cancelButton, 'click', intranet.cancelForm);
			Event.observe(aForm, 'submit', intranet.postToIframe);

        },
        
        postToIframe: function(e) {

			Event.stop(e);
			aForm = Event.element(e);
			aForm.submit();
        
        },
        
        expandAll: function(e) {

			if(e) {
				Event.stop(e);
			}
			thetree = $('tree');

       		items = $A(thetree.getElementsByTagName('li'));
       		items.each(function(item) {

        		newClass = item.className.replace('li-closed','li-open');
        		item.className = newClass;

       		});

        },

		formPostedSafely: function(e) {
			
			$('col-wide').innerHTML = '<p class="success">File updated successfully</p>';

		},

        cancelForm: function() {
			intranet.alterPage('reset');
        },
        
        
        alterPage: function(to) {

			b = document.body;

			if(to == 'reset') {
				Element.removeClassName(b, 'wide');
				$('col-wide').innerHTML = '';
			} else if(to == 'wide') {
				Element.addClassName(b, 'wide');
			} else {

				if(Element.hasClassName(b, 'wide')) {
					Element.removeClassName(b, 'wide');
					$('col-wide').innerHTML = '';
				} else {
					Element.addClassName(b, 'wide');
				}

			}

        },
        
        showLoading: function(div) {
			body = document.body;
			
			loading = document.createElement('img');
			loading.id = 'processing';
			loading.setAttribute('src', '/images/loading.gif');
			body.appendChild(loading);

		},
		
		ditchLoading: function() {
			$('processing').parentNode.removeChild($('processing'));
		}

    }

	document.write('<style type="text/css">#wrapper { display: none; }</style>');
    Event.observe(window, 'load', intranet.init);