/**
 * This variable will contain all global variables used by a certain module.
 * @warning: When working in AJAX mode, all variables will be automatically deleted on a new request.
 */
var currentModule = {_mode: 'classic', _css: [], _js: [], _stack: []};

window.dhtmlHistory.create({
    toJSON: function(o) {
    	return Object.toJSON(o);
    },
    fromJSON: function(s) {
    	return s.evalJSON();
    }
});
	
function setup(body){
	//setupSifr(body);
	dhtmlHistory.initialize();
	dhtmlHistory.addListener(historyChange);
}

var historyChange = function (newLocation, historyData) {
	window.currentModule._mode = 'ajax';
	makeRequest(newLocation);
}

/**
 * Garbage Collector
 * @running in AJAX mode
 */
function garbageCollector(object) {
	if(object && typeof(object) == 'object') {
		if(Object.isFunction(object._garbageCollector)) {
			object._garbageCollector();
		}
		else {
			for(var component in object) {
				if(!component.startsWith('_')) {
					if(!Object.isFunction(object[component])) {
						garbageCollector(object[component]);
						delete object[component];
					}
				}
			}
		}
	}
	else {
		delete object;
	}
}

/**
 * This function dynamically removes any JS and CSS before loading the newly requested page.
 * @runnig in AJAX mode
 */
function removeDependencies () {
	['_css','_js'].each(function (type) {
		if(currentModule[type].length) {
			currentModule[type].each(function (resource) {
				resource.remove();
			})
			currentModule[type].clear();;
		}
	})
}

/**
 * Handler for links
 * @running in AJAX mode
 */
function goTo(action, parameters) {
	garbageCollector(currentModule);
	window.location.replace('#' + action + (parameters ? '?' + parameters : ''));
	document.fire('dom:loaded');
}

/**
 * Handler for AJAX requests
 * @running in AJAX mode
 */
function makeRequest(request) {
	var pattern = /([^\?]+)\??([a-zA-Z0-9\_\-=&\;]*)/;
	var request = pattern.exec(request);

	myAjax = new Ajax.Request(
		request[1] + '.goto',
		{
			method: 'get',
			parameters: request[2],
			message: 'Working on your request...',
			onSuccess: function(transport) {
				removeDependencies();
				refreshPage(transport.responseText);
			}
		}
	);
}

/**
 * This function is used to refresh portions of the page, encoded as JSON.
 * @running in AJAX mode
 */

function refreshPage( bodyParts, doNotEval ) {
	if(!doNotEval) {
		bodyParts = bodyParts.evalJSON(true);
	}
	
	if(bodyParts.__redirect) {
		window.location.replace(bodyParts.__redirect);
	}
	else {
		for (bodyPart in bodyParts) {
			switch(bodyParts[bodyPart].type) {
				case 'value': {
					$(bodyPart).value = bodyParts[bodyPart].content; 
				} break;
				case 'pagination': {
					if(window.currentModule.paginationObjs) {
						window.currentModule.paginationObjs.each(function(object) {
							var newSettings = bodyParts[bodyPart].content.evalJSON(); 
							object.rewind(newSettings);
						});
					}
				}
				break;
				case 'js': {
					var bodyID = document.getElementsByTagName('body')[0];
					var newJs = document.createElement('script');
					newJs.type = 'text/javascript';
					newJs.src = bodyParts[bodyPart].content;
					bodyID.appendChild(newJs);
					
					window.currentModule._js.push(newJs);
				}
				break;
				case 'css': {
					var headID = document.getElementsByTagName('head')[0];         
					var newCss = document.createElement('link');
					newCss.type = 'text/css';
					newCss.rel = 'stylesheet';
					newCss.href = bodyParts[bodyPart].content;
					headID.appendChild(newCss);
					
					window.currentModule._css.push(newCss);
				}
				break;
				case 'script': {
					window.currentModule._stack.push(bodyParts[bodyPart].content);
				}
				break;
				case 'text':
				default: {
					$(bodyPart).update(bodyParts[bodyPart].content);
				} break;
			}
		}
		if(window.currentModule._stack.length) {
			setTimeout(function() {
				window.currentModule._stack.each(function(script) {
					try {
						eval(script);
					}
					catch (e) {}
				});
				window.currentModule._stack.clear();
			}, 1000);
		}
	}
}

function gotoAndGet (newLocation, parameters) {
	if(window.currentModule._mode == 'ajax') {
		goTo(newLocation, Object.toQueryString(parameters));
	}
	else {
		window.location.replace(newLocation + '?' + Object.toQueryString(parameters));
	}
}

function searchFocus(event, defaultText) {
	var element = Event.element(event);
	
	if(event.type == 'focus') {
		if(element.value == defaultText) {
			element.value = '';
		}
		else {
			element.select();
		}
		element.style.color = '#000000';
		
	}
	else {
		if(!element.value) {
			element.value = defaultText;
			element.style.color = '#CCCCCC';
		}
	}
}
/**
 * Inits sifr template
 * @depends: sifr library
 */ 
function setupSifr(template) {
	
	
}

/**
 * Prototype Ajax.Responders object that shows an info message on top of pag
 * @depends: prototype.js
 */
Ajax.Responders.register({
  onCreate: function( ajax ) {
  		if( !Object.isUndefined( ajax.options.message) ){
  			setDefaultMessageIcon();
  			$('loadingMessage').update( ajax.options.message );
			$('loading').style.display = 'block';
		}
  },
  onComplete: function( ajax ) {
  		var timeout;
  		var dispatch = true;
  		
  		if(Object.isUndefined(ajax.options.messageTimeout)) {
  			timeout = 1000;
  		}
  		else {
  			if(!(timeout = ajax.options.messageTimeout)) {
  				dispatch = false;
  			}
  		}
  		
  		if(dispatch) {
  			if(window.messageTimeoutAjax) {
  				clearTimeout(window.messageTimeoutAjax);
  			}
  			window.messageTimeoutAjax = setTimeout(function(){$('loading').hide();}, timeout);
  		} 
  }
});

/**
 * Utility functions used to display an informative message.
 */
function setDefaultMessageIcon() {
	var loadingIcon = $('loadingIcon');
	if(!window.oldIcon) {
		window.oldIcon = {src: '/modules/default/img/misc/loading.gif', width: 16, height: 16};
	}
	loadingIcon.src = window.oldIcon.src;
	loadingIcon.width = window.oldIcon.width;
	loadingIcon.height = window.oldIcon.height;	
}
function UIMessage(message, type, lastFor) {
	var loadingIcon = $('loadingIcon');
	switch (type) {
		case 'warning':
		{
			loadingIcon.src = '/modules/default/img/misc/_warning.png';
			loadingIcon.width = 14;
			loadingIcon.height = 14; 			
		} break;
		case 'error':
		{
			loadingIcon.src = '/modules/default/img/misc/_error.png';
			loadingIcon.width = 14;
			loadingIcon.height = 14; 
		} break;
		case 'done': {
			loadingIcon.src = '/modules/default/img/misc/_done.png';
			loadingIcon.width = 14;
			loadingIcon.height = 14; 
		} break;
		case 'help':
		{
			loadingIcon.src = '/modules/default/img/misc/_help.png';
			loadingIcon.width = 14;
			loadingIcon.height = 14;
		} break;
		case 'loading':
		{
			setDefaultMessageIcon();
		}
		break;
		case 'info':
		default:
		{
			loadingIcon.src = '/modules/default/img/misc/_info.png';
			loadingIcon.width = 14;
			loadingIcon.height = 14;
		} break;
	}
	$('loadingMessage').update( message );
	$('loading').style.display = 'block';
	
	setTimeout( function() { $('loading').hide(); }, (lastFor ? lastFor : 1000));
}


function setCookie(name, value, days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function fireEvent(obj, evt) {
	var fireOnThis = obj;
	if( document.createEvent ) {
		var evObj = document.createEvent('MouseEvents');
		evObj.initEvent( evt, true, false );
		fireOnThis.dispatchEvent(evObj);
	} else if( document.createEventObject ) {
		fireOnThis.fireEvent('on'+evt);
	}
}