function init() {
	Shadowbox.init();

	// History manager
	var bookmarkedViewState = YAHOO.util.History.getBookmarkedState("view");
	var initialViewState = bookmarkedViewState || "initial";

    YAHOO.util.History.register("view", initialViewState, function (state) {
        // This is called after calling YAHOO.util.History.navigate, or after the user
        // has trigerred the back/forward button. We cannot discrminate between
        // these two situations.
		defineState(state);
    });

	// Use the Browser History Manager onReady method to instantiate the widget.
    YAHOO.util.History.onReady(function () {
        var currentState = YAHOO.util.History.getCurrentState("view");
		if (currentState == "initial") {
			return;
		}
		defineState(currentState);
    });

    // Initialize the browser history management library.
    try {
        YAHOO.util.History.initialize("yui-history-field", "yui-history-iframe");
    } catch (e) {
        // The only exception that gets thrown here is when the browser is
        // not supported (Opera, or not A-grade) Degrade gracefully.
		alert('Use Mozilla Firefox or IE6+');
    }
	
	// Refresh automatically every xx seconds
	setInterval("refreshRndImgGal(YAHOO.util.Dom.get('refreshGal'))", 60000); // 1 min
}

function defineState(state) {
	switch (state) {
		case "initial":
			getInitialPage();
			break;

		case "advSearch":
			setSearchForm();
			break;

		case "news":
			getNews('');
			break;
			
		case "chronicles":
			getChronicles();
			break;

		default:
			_state = state.split("-");
			switch (_state[0]) {
				case 'cat':
					getCategoryContent(_state[1], _state[2]);
					break;

				case 'ant':
					getAntikeimenoContent(_state[1]);
					break;

				case 'qur':
					getSearchResults(_state[1]);
					break;

				case 'per':
					getChroniclesResults(_state[1]);
					break;

				case 'new':
					getNews(_state[1]);
					break;
					
				case 'sta':
					getStatic(_state[1], _state[2]);
					break;
				
				case "latest":
					getLatest(_state[1]);
					break;
			}
			break;
	}
}

function setDOMParser() {
	if (typeof DOMParser == "undefined") {
	   DOMParser = function () {}

	   DOMParser.prototype.parseFromString = function (str, contentType) {
	      if (typeof ActiveXObject != "undefined") {
	         var d = new ActiveXObject("MSXML.DomDocument");
	         d.loadXML(str);
	         return d;
	      } else if (typeof XMLHttpRequest != "undefined") {
	         var req = new XMLHttpRequest;
	         req.open("GET", "data:" + (contentType || "application/xml") +
	                         ";charset=utf-8," + encodeURIComponent(str), false);
	         if (req.overrideMimeType) {
	            req.overrideMimeType(contentType);
	         }
	         req.send(null);
	         return req.responseXML;
	      }
	   }
	}
}

var tree;
function setTree(e, id) {
	//instantiate the tree:
    tree = new YAHOO.widget.TreeView("treeDiv1");

	// Set collapse animation
	tree.setCollapseAnim(YAHOO.widget.TVAnim.FADE_OUT);

	// Set expand animation
	tree.setExpandAnim(YAHOO.widget.TVAnim.FADE_IN);

	var root = tree.getRoot();

	var categories = xmlobject.getElementsByTagName('cat');
	addChildren(root, categories, 0);

	// Draw
	tree.draw();
}

function stylePath(node) {
	// Clear previous nodes
	var selectednodes = tree.getNodesByProperty('selected', 1);
	for (var i in selectednodes) {
		selectednodes[i].labelStyle = 'ergo_node'; // default style for node
		node.data.selected = 0;
	}
	var root = tree.getRoot();

	var fullPathNodes = new Array();
	fullPathNodes.push(node);

	if (node.hasChildren()) {
		node.expand();
	}
	node.data.selected = 1;

	// Set style for nodes to path until the selected category
	while (node.parent != root) {
		node = node.parent;
		fullPathNodes.push(node);
		node.expand();
		node.data.selected = 1;
	}

	var len = fullPathNodes.length;
	fullPathNodes[0].labelStyle = 'ergo_selected_node';
	var fullpath = getNodeLabelAsLink(fullPathNodes[0]);
	for (var i=1; i<len; i++) {
		fullPathNodes[i].labelStyle = 'ergo_selected_node';
		fullpath = getNodeLabelAsLink(fullPathNodes[i]) + ' / ' + fullpath;
	}

	YAHOO.util.Dom.get('treeFullPath').innerHTML = fullpath + '<br /><br />';
}

function getNodeLabelAsLink(node) {
	var lnk = '<a href="#" onclick="YAHOO.util.History.navigate(\'view\',\'cat-'+node.data.id+'\'); return false;">'+node.label+'</a>';
	return lnk;
}

function addChildren(parentNode, children, level) {
	for (var i=0; i<children.length; i++) {
		var deep = getNodeValue(children[i], 'deep');
		if (deep != level) { continue; }
		var id = getNodeValue(children[i], 'id');
		var name = getNodeValue(children[i], 'name');

		var myobj = { label:name, id:id, selected:0 };
		var tmpNode = new YAHOO.widget.TextNode(myobj, parentNode, false);
		tmpNode.multiExpand = false;
		tmpNode.labelStyle = "ergo_node"; // default style for node
		tmpNode.onLabelClick = function (node) {
			YAHOO.util.History.navigate("view", "cat-"+node.data.id);
			return false; // don't toggle node
		}
		var subcategories = children[i].getElementsByTagName('cat');

		addChildren(tmpNode, subcategories, parseInt(deep)+1);
	}
}

function getCategoryContent(id, page) {
	var node = tree.getNodeByProperty('id', id);
	stylePath(node);

	var AjaxObject = {

		handleSuccess:function(o){
			this.container.innerHTML = o.responseText;
		},

		handleFailure:function(o){
			// Failure handler
			this.container.innerHTML = 'Παρουσιάστηκε σφάλμα...';
		},

		startRequest:function() {
			this.container = YAHOO.util.Dom.get('content');
			this.container.innerHTML = '<img src="modules/Ergologic_client/images/loading.gif" /> '+YAHOO.tbekos.please_wait+'...';
			page = parseInt(page) || 1;
			var data = "catid="+id+'&page='+page+'&filter='+YAHOO.util.Dom.get('filter').value;
			YAHOO.util.Connect.asyncRequest('POST', 'modules.php?name=Ergologic_client&file=ajax/categoryContent', callback, data);
		}

	};

	/*
	 * Define the callback object for success and failure
	 * handlers as well as object scope.
	 */
	var callback =
	{
		success:AjaxObject.handleSuccess,
		failure:AjaxObject.handleFailure,
		scope: AjaxObject
	};

	// Start the transaction.
	AjaxObject.startRequest();
}

var antikeimenoTabs;
function getAntikeimenoContent(id) {
	var AjaxObject = {

		handleSuccess:function(o){
			this.container.innerHTML = o.responseText;

			var contentEl = YAHOO.util.Dom.get('demo');
			antikeimenoTabs = new YAHOO.widget.TabView(contentEl);
			
			Shadowbox.setup();
		},

		handleFailure:function(o){
			// Failure handler
			this.container.innerHTML = 'Παρουσιάστηκε σφάλμα...';
		},

		startRequest:function() {
			this.container = YAHOO.util.Dom.get('content');
			this.container.innerHTML = '<img src="modules/Ergologic_client/images/loading.gif" /> '+YAHOO.tbekos.please_wait+'...';
			var data = 'antid='+id+'&filter='+YAHOO.util.Dom.get('filter').value;
			YAHOO.util.Connect.asyncRequest('POST', 'modules.php?name=Ergologic_client&file=ajax/antikeimenoContent', callback, data);
		}

	};

	/*
	 * Define the callback object for success and failure
	 * handlers as well as object scope.
	 */
	var callback =
	{
		success:AjaxObject.handleSuccess,
		failure:AjaxObject.handleFailure,
		scope: AjaxObject
	};

	// Start the transaction.
	AjaxObject.startRequest();
}

function getImagesOnPage(typeid, antid, page, firstTime) {
	if (firstTime == true && YAHOO.util.Dom.get('thumb_gallery'+typeid).innerHTML != '') {
		return;
	}

	var AjaxObject = {
		handleSuccess:function(o){
			this.container.innerHTML = o.responseText;
			Shadowbox.setup();
		},

		handleFailure:function(o){
			// Failure handler
			this.container.innerHTML = 'Παρουσιάστηκε σφάλμα...';
		},

		startRequest:function() {
			this.container.innerHTML = '<img src="modules/Ergologic_client/images/loading.gif" /> '+YAHOO.tbekos.please_wait+'...';
			var data = 'typeid='+typeid+'&antid='+antid+'&thumb_page='+page+'&filter='+YAHOO.util.Dom.get('filter').value;;
			YAHOO.util.Connect.asyncRequest('POST', 'modules.php?name=Ergologic_client&file=ajax/imagesTabContent', callback, data);
		}

	};

	var callback =
	{
		success:AjaxObject.handleSuccess,
		failure:AjaxObject.handleFailure,
		scope: AjaxObject
	};

	AjaxObject.container = YAHOO.util.Dom.get('thumb_gallery'+typeid);
	
	// Start the transaction.
	AjaxObject.startRequest();
}

function getInitialPage() {
	YAHOO.util.Dom.get('treeFullPath').innerHTML = '';

	var AjaxObject = {

		handleSuccess:function(o){
			this.container.innerHTML = o.responseText;
		},

		handleFailure:function(o){
			// Failure handler
			this.container.innerHTML = 'Παρουσιάστηκε σφάλμα...';
		},

		startRequest:function() {
			this.container = YAHOO.util.Dom.get('content');
			this.container.innerHTML = '<img src="modules/Ergologic_client/images/loading.gif" /> '+YAHOO.tbekos.please_wait+'...';
			YAHOO.util.Connect.asyncRequest('POST', 'modules.php?name=Ergologic_client&file=ajax/initial', callback);
		}
	};

	/*
	 * Define the callback object for success and failure
	 * handlers as well as object scope.
	 */
	var callback =
	{
		success:AjaxObject.handleSuccess,
		failure:AjaxObject.handleFailure,
		scope: AjaxObject
	};

	// Start the transaction.
	AjaxObject.startRequest();
}

function getChronicles() {
	YAHOO.util.Dom.get('treeFullPath').innerHTML = '';

	var AjaxObject = {
		handleSuccess:function(o){
			this.container.innerHTML = '<div id="chroniclesTreeDiv"></div><div id="chroniclesButton" onclick="YAHOO.util.History.navigate(\'view\',\'chronicles\');" style="cursor: pointer; display: none;">&lt;&lt;</div><div id="chronicles_results"></div>';

			setChroniclesTree(o.responseXML);
		},

		handleFailure:function(o){
			// Failure handler
			this.container.innerHTML = 'Παρουσιάστηκε σφάλμα...';
		},

		startRequest:function() {
			this.container.innerHTML = '<img src="modules/Ergologic_client/images/loading.gif" /> '+YAHOO.tbekos.please_wait+'...';
			YAHOO.util.Connect.asyncRequest('POST', 'modules.php?name=Ergologic_client&file=ajax/chronicles', callback);
		}

	};

	/*
	 * Define the callback object for success and failure
	 * handlers as well as object scope.
	 */
	var callback =
	{
		success:AjaxObject.handleSuccess,
		failure:AjaxObject.handleFailure,
		scope: AjaxObject
	};

	AjaxObject.container = YAHOO.util.Dom.get('content');
	
	if (YAHOO.util.Dom.get('chroniclesTreeDiv') && YAHOO.util.Dom.get('chroniclesTreeDiv').innerHTML != '') {
		$('#chroniclesTreeDiv').show('slow');
		YAHOO.util.Dom.get('chroniclesButton').style.display = 'none';
		YAHOO.util.Dom.get('chronicles_results').innerHTML = '';
	} else {
		// Start the transaction.
		AjaxObject.startRequest();
	}
}

var chroniclesTree;
function setChroniclesTree(xmlObj) {
	//instantiate the tree:
    chroniclesTree = new YAHOO.widget.TreeView("chroniclesTreeDiv");

	var root = chroniclesTree.getRoot();

	var periods = xmlObj.getElementsByTagName('cat');
	addChronilesChildren(root, periods, 0);

	// Draw
	chroniclesTree.draw();
}

function addChronilesChildren(parentNode, children, level) {
	for (var i=0; i<children.length; i++) {
		var deep = getNodeValue(children[i], 'deep');
		if (deep != level) { continue; }
		var id = getNodeValue(children[i], 'id');
		var name = getNodeValue(children[i], 'name');

		var myobj = { label:name, id:id };
		var tmpNode = new YAHOO.widget.TextNode(myobj, parentNode, false);
		tmpNode.multiExpand = false;
		tmpNode.labelStyle = "ergo_node"; // default style for node
		tmpNode.onLabelClick = function (node) {
			YAHOO.util.History.navigate("view", "per-"+node.data.id);
			return false; // don't toggle node
		}
		var subcategories = children[i].getElementsByTagName('cat');

		addChronilesChildren(tmpNode, subcategories, parseInt(deep)+1);
	}
}

function showKeimenoBody(div) {
	var bd = YAHOO.util.Dom.getElementsByClassName('keimeno-body', 'div', div)[0];
	var link = YAHOO.util.Dom.getElementsByClassName('keimeno-button', null, div)[0];

	if (bd.style.display == 'none') {
		bd.style.display = '';
		link.innerHTML = '<img src="modules/Ergologic_client/images/hide.png" border="0" />';
	} else {
		bd.style.display = 'none';
		link.innerHTML = '<img src="modules/Ergologic_client/images/show.png" border="0" />';
	}
}

function refreshOnFilterChange() {
	var state = YAHOO.util.History.getCurrentState("view");

	_state = state.split("-");
	switch (_state[0]) {
		case 'cat':
			getCategoryContent(_state[1], _state[2]);
			break;

		case 'ant':
			getAntikeimenoContent(_state[1]);
			break;
	}
}
function getNodeValue(obj,tag) {
	return obj.getElementsByTagName(tag)[0].firstChild.nodeValue;
}
// by Tasos Bekos, tbekos (at) gmail

