// Common Functions
var aoa_heightHeaderAndFoter = 370;
var aoa_logged = false;

if (!Array.prototype.indexOf)
{
  Array.prototype.indexOf = function(elt /*, from*/)
  {
    var len = this.length;

    var from = Number(arguments[1]) || 0;
    from = (from < 0)
         ? Math.ceil(from)
         : Math.floor(from);
    if (from < 0)
      from += len;

    for (; from < len; from++)
    {
      if (from in this &&
          this[from] === elt)
        return from;
    }
    return -1;
  };
}

function aoa_getQueryVariable(variable, separator, eq) {
	if (typeof separator == 'undefined') {
		separator = '&';
	}
	if (typeof eq == 'undefined') {
		eq = '=';
	}
	var query = window.location.search.substring(1);
	var vars = query.split(separator);
	for (var i=0;i<vars.length;i++) {
		var pair = vars[i].split(eq);
		if (pair[0] == variable) {
			return pair[1];
		}
	}
	return null;
}

function aoa_getHashVariable(variable, separator, eq) {
	if (typeof separator == 'undefined') {
		separator = '&';
	}
	if (typeof eq == 'undefined') {
		eq = '=';
	}
	var query = window.location.hash.substring(1);
	var vars = query.split(separator);
	for (var i=0;i<vars.length;i++) {
		var pair = vars[i].split(eq);
		if (pair[0] == variable) {
			return pair[1];
		}
	}
	return null;
}

function aoa_addHashVariable(variable, value, separator, eq)
{
	if (typeof separator == 'undefined') {
		separator = '&';
	}
	if (typeof eq == 'undefined') {
		eq = '=';
	}
	var query = window.location.hash.substring(1);
	var vars = query.split(separator);
	var newQuery = '';
	var bAdded = false;
	
	for (var i=0;i<vars.length;i++) {
		var pair = vars[i].split(eq);
		if (i > 0) {
			newQuery += separator;
		}
		if (pair[0] == variable) {
			// The variable is already in the hash - replace it
			newQuery += pair[0]+eq+value;
			bAdded = true;
		} else if(pair[0] != '') {
			newQuery += pair[0]+eq+pair[1];
		}
	}
	
	if (!bAdded) {
		if (newQuery != '') {
			newQuery += separator+variable+eq+value;
		} else {
			newQuery += variable+eq+value;
		} 
	}
	
	window.location.hash = '#'+newQuery;
}

// Dynamically load js
function aoa_loadScript(sScriptSrc, oCallback) {
	var oHead = document.getElementsByTagName('head')[0];
	// Check if the script is already loaded
	var aScripts = document.getElementsByTagName('script');
	if (aScripts.length > 0) {
		for (var i = 0; i < aScripts.length; i++) {
			if (aScripts[i].src.match(sScriptSrc)) {
				// The script is loaded. Just execute the callback
				oCallback();
				return;
			}
		}
	}
	var oScript = document.createElement('script');
	oScript.type = 'text/javascript';
	oScript.src = sScriptSrc;
	// most browsers
	oScript.onload = oCallback;
	// IE 6 & 7
	oScript.onreadystatechange = function() {
		if (this.readyState == 'complete') {
		oCallback();
		}
	}
	oHead.appendChild(oScript);
}

// Dynamically load css
function aoa_loadStyle(sSrc, oCallback) {
	var oHead = document.getElementsByTagName('head')[0];
	// Is the style already loaded
	var aStyles = document.getElementsByTagName('link');
	if (aStyles.length > 0) {
		for (var i = 0; i < aStyles.length; i++) {
			if (aStyles[i].type == 'text/css' && aStyles[i].href.match(sSrc)) {
				// The style is loaded.
				return;
			}
		}
	}
	var oStyle = document.createElement('link');
	oStyle.rel = 'stylesheet';
	oStyle.type = 'text/css';
	oStyle.href = sSrc;
	oHead.appendChild(oStyle);
}


function aoa_popUp(page, w, h, left, top, resize, scrollbars)
{
	win = window.open(page, "", "dependent, height=" + h + ", width=" + w + ", left=" + left + ", top=" + top + ", resizable=" + resize + ", scrollbars=" + scrollbars);
	
	if (win) {
		return false;
	}
	return true;
}


function aoa_switchClass(obj,strClassName)
{
	obj.className	= strClassName;
}

function aoa_hasValueInArray(oNeedle, oHaystack)
{
	for (var i = 0; i < oHaystack.length; i++) {
		if (oNeedle == oHaystack[i]) {
			return true;
		}
	}
	return false;
}

function aoa_clearValueFromArray(oNeedle, oHaystack)
{
	var newArray = new Array();
	
	for (var i = 0; i < oHaystack.length; i++) {
		if (oNeedle != oHaystack[i]) {
			newArray[i] = oHaystack[i];
		}
	}
	
	return newArray;
}

function aoa_setCookie(cookieName, value, expiredays)
{
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=cookieName+ "=" +escape(value)+";path=/"+
	((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}

function aoa_getCookie(cookieName)
{
	var cookieString = document.cookie;
	var cookieSet = cookieString.split (';');
	var setSize = cookieSet.length;
	var cookiePieces;
	var returnValue = "";
	var x = 0;
	
	for (x = 0; ((x < setSize) && (returnValue == "")); x++) {
		cookiePieces = cookieSet[x].split ('=');
		
		if (cookiePieces[0].substring (0,1) == ' ') {
			cookiePieces[0] = cookiePieces[0].substring (1, cookiePieces[0].length);
		}
		
		if (cookiePieces[0] == cookieName) {
			returnValue = cookiePieces[1];
		}
	}
	
	return returnValue;
	
}

// End Common Functions
// These seems not to be used. Delete if no bugs appear
/*
function aoa_deleteConfirm(question, idPart)
{
	var inputsDom = document.getElementsByTagName("input");
	var re = new RegExp(idPart, "i")
	
	for (i = 0; i < inputsDom.length; i++) {
		if (re.test(inputsDom[i].id)) {
			// Check if it is checked
			if (inputsDom[i].checked == true) {
				return confirm(question);
			}
		}
	}
	
	return true;
}

function aoa_clearSearch(formId, findClearId)
{
	document.getElementById(findClearId).value = 'yes';
	document.getElementById(formId).submit();
}

function aoa_showExtendedSearch(elementId)
{
	var elementNode = document.getElementById(elementId);
	elementNode.style.display = 'block';
}

function aoa_hideExtendedSearch(elementId)
{
	var elementNode = document.getElementById(elementId);
	elementNode.style.display = 'none';
}
*/
function aoa_showBlock(blockId)
{
	document.getElementById(blockId).style.display = '';
}

function aoa_hideBlock(blockId)
{
	document.getElementById(blockId).style.display = 'none';
}

var AOA = {};

function aoa_toggleBlock(blockId)
{
	if (document.getElementById(blockId).style.display == 'none') {
		aoa_showBlock(blockId);
	} else {
		aoa_hideBlock(blockId);
	}
}

// site specific
// Not needed for now. Delete before launch the site
/*
function aoa_fixMultipleSelection(select, allValue)
{
	// If value different form the allValue is selected, disselect the allValue option
	var bToDisselect = false;
	
	if (select.options.length > 0) {
		for(var i = 0; i < select.options.length; i++) {
			if (select.options[i].selected && select.options[i].value != allValue) {
				bToDisselect = true;
				break;
			}
		}
		
		if (bToDisselect) {
		for(var i = 0; i < select.options.length; i++) {
				if (select.options[i].value == allValue) {
					select.options[i].selected = false;
					break;
				}
			}
		}
	}
}
*/
function aoa_showLoadingSplash(nodeId)
{
	var nodeTo = document.getElementById(nodeId);
	var loadingSplashNode = document.getElementById('loadingSplash');
	nodeTo.innerHTML = loadingSplashNode.innerHTML;
}

function aoa_updateNode(containerId, url, onUpdateEvalCode)
{
	aoa_showLoadingSplash(containerId);
	$.ajax({
		url: url,
		cache: false,
		success: function(html){
			$("#"+containerId).html(html);
			if (typeof onUpdateEvalCode != 'undefined') {
				eval(onUpdateEvalCode);
			}
		}
	});
}

function aoa_postAjaxForm(formId, options, funcSelfUpdate)
{
	var form = $('#'+formId);
	
	if (typeof funcSelfUpdate == 'undefined') {
		funcSelfUpdate = aoa_selfUpdate
	}
	
	if (typeof options == 'undefined' || options == null) {
		var options = {
			success: funcSelfUpdate,
			error: aoa_errorPostAjaxForm,
			timeout: 45000,
			cache: false
		};
	}
	form.ajaxSubmit(options);
}

// Default selfUpdate
function aoa_selfUpdate(responseText, statusText)
{
	aoa_showOnTop(responseText)
}

function aoa_showOnTop(htmlString)
{
	var div = document.createElement('div');
	var body = document.getElementsByTagName('body')[0];
	
	$(div).prependTo(body);
	
	$(div).html(htmlString);
}

function aoa_errorPostAjaxForm(XMLHttpRequest, textStatus, errorThrown)
{
	alert('Connection failed!');
}

function aoa_runCmd(button, message, cmd)
{
	if (typeof cmd == 'undefined') {
		cmd = 'delete';
	}
	
	if (confirm(message)) {
		button.form.cmd.value = cmd;
		button.form.submit();
	}
	
	return false;
}

function aoa_getDocumentHeight()
{
	var myHeight = 0;
	if( typeof( window.innerWidth ) == 'number' ) {
		//Non-IE
		myHeight = window.innerHeight;
	} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
		//IE 6+ in 'standards compliant mode'
		myHeight = document.documentElement.clientHeight;
	} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
		//IE 4 compatible
		myHeight = document.body.clientHeight;
	}
	return myHeight;
}

function aoa_fixContentSize()
{
	var cont = document.getElementById('contentClipper');
	var sz = aoa_getDocumentHeight() - aoa_heightHeaderAndFoter;
	
	cont.style.height = sz+'px';
	cont.style.width = '100%';
}

function aoa_fixPopUpContentSize()
{
	var cont = document.getElementById('contentClipper');
	var sz = aoa_getDocumentHeight();
	
	cont.style.height = sz+'px';
	cont.style.width = '100%';
}

function aoa_fixBannersSize()
{
	var bnr = document.getElementById('bannersClipper');
	if (typeof(bnr) == 'undefined' || bnr == null) {
		return;
	}
	var sz = aoa_getDocumentHeight() - aoa_heightHeaderAndFoter;
	
	bnr.style.height = sz+'px';
	bnr.style.width = '100%';
}

function aoa_fixMenuSize()
{
	//var html = document.getElementsByTagName('body')[0];
	var html = document.getElementById('content');
	var mnu = document.getElementById('menuClipper');
	if (typeof(mnu) == 'undefined' || mnu == null) {
		return;
	}
	var sz = html.offsetHeight;
	
	mnu.style.height = sz+'px';
	mnu.style.width = '100%';
}

function aoa_fixAllSizes()
{
	aoa_fixContentSize();
	aoa_fixMenuSize();
	aoa_fixBannersSize();
}

function aoa_toggleVisibility(nodeId)
{
	var nodeElement = document.getElementById(nodeId);
	
	if (nodeElement.style.visibility == 'hidden') {
		nodeElement.style.visibility = 'visible';
	} else {
		nodeElement.style.visibility = 'hidden';
	}
}


function aoa_showFileType(url, id)
{
	if (typeof id == 'undefined') {
		id = 'fileType';
	}
	
	aoa_toggleVisibility(id+'Window')
	aoa_updateNode(id+'Content', url)
}

function aoa_MidiPlayer(midiSrc, noMidiPlayer)
{
		document.getElementById('midiPlayer').innerHTML = '<embed height="36" width="400" type="audio/mid" align="absmiddle" src="'+midiSrc+'" class="midiPlayer"><noembed>'+noMidiPlayer+'</noembed></embed>';
}

function aoa_showSplashFullScreen()
{
	var splash = document.getElementById('loadingSplash');
	splash.style.position = 'absolute';
	splash.style.backgroundColor = '#FFFFFF';
	splash.style.width = '100%';
	splash.style.height = '100%';
	splash.style.textAlign = 'center';
	splash.style.verticalAlign = 'middle';
	splash.innerHTML = '<img src="images/loading/loading_big.gif" />';
	splash.style.display = 'block';
	splash.style.top = '0px';
	// Make it cover the entire window
	var html = document.getElementsByTagName('html')[0];
	if (splash.offsetHeight < html.offsetHeight) {
		splash.style.bottom = html.offsetHeight+'px';
		splash.style.height = html.offsetHeight+'px';
	}
}

function aoa_hideSplashFullScreen()
{
	var splash = document.getElementById('loadingSplash');
	splash.style.position = 'static';
	splash.style.backgroundColor = '';
	splash.style.width = 'auto';
	splash.style.height = 'auto';
	splash.style.textAlign = '';
	splash.style.verticalAlign = '';
	splash.innerHTML = '<div class="loadingSplash"><img src="images/loading/icon_fg_loading.gif" /></div>';
	splash.style.display = 'none';
	
}

function aoa_getY(id)
{
	var oElement = document.getElementById(id);
	var iReturnValue = 0;
	while( oElement != null ) {
		iReturnValue += oElement.offsetTop;
		oElement = oElement.offsetParent;
	}
	var oElement = document.getElementById(id);
	while (oElement != null) {
		if (typeof oElement.scrollTop != 'undefined' && oElement.nodeName.toLowerCase() != 'html') {
			iReturnValue -= oElement.scrollTop;
		}
		oElement = oElement.parentNode;
	}
	return iReturnValue;
}

function aoa_getX(id)
{
	var oElement = document.getElementById(id);
	var iReturnValue = 0;
	while( oElement != null ) {
		iReturnValue += oElement.offsetLeft;
		oElement = oElement.offsetParent;
	}
	var oElement = document.getElementById(id);
	while (oElement != null) {
		if (typeof oElement.scrollLeft != 'undefined' && oElement.nodeName.toLowerCase() != 'html') {
			iReturnValue -= oElement.scrollLeft;
		}
		oElement = oElement.parentNode;
	}
	return iReturnValue;
}

function aoa_showLoginForm()
{
	document.getElementById('loginFormBlockPopup').style.visibility = 'hidden';
	document.getElementById('coverAll').style.visibility = 'hidden';
	aoa_toggleLoginFormVisibility();
}

function aoa_flashMessage(message, type, duration)
{
	var div = document.createElement('div');
	var body = document.getElementsByTagName('body')[0];
	var html = document.getElementsByTagName('html')[0];
	
	div.style.top = html.scrollTop+'px';
	
	div.innerHTML = message;
	div.className = 'jsFlashMessage '+type;
	div.id = 'jsFlashMessageId'+Math.random()*1000;
	$(div).prependTo(body);
	
	if (typeof duration == 'undefined') {
		duration = 5000;
	}
	
	$(div).animate({opacity: 1}, {'duration': 800});
	$(div).animate({opacity: 0.7}, {'duration': 200});
	$(div).animate({opacity: 1}, {'duration': 150});
	$(div).animate({opacity: 0.7}, {'duration': 200});
	$(div).animate({opacity: 1}, {'duration': 150});
	$(div).animate({opacity: 0.7}, {'duration': 200});
	$(div).animate({opacity: 1}, {'duration': 150});
	$(div).animate({opacity: 1}, {'duration': duration});
	
	$(div).animate({opacity: 0}, {'duration': 1500, 'easing': 'linear', 'callback': function () {$('#'+div.id).remove()}});
	
}

// For login events
var aoa_loginOnSuccessToEval = '';

function aoa_onLoginSuccess(messageToFlash)
{
	aoa_logged = true;
	aoa_flashMessage(messageToFlash, 'success');
	if (aoa_loginOnSuccessToEval != '') {
		eval(aoa_loginOnSuccessToEval);
	}
}

function aoa_onLoginError(message)
{
	alert(message);
}


function aoa_checkAndShowLogin()
{
	if (!aoa_logged) {
		aoa_showLoginForm();
		
		return false;
	}
	
	return true;
}

function aoa_decodeEmails(emailText)
{
	var allEmailNodes = document.getElementsByName('aoaencrem');
	var numElements = allEmailNodes.length;
	var email = '';
	
	for (var iEl = 0; iEl < numElements; iEl++) {
		email = aoa_decodeString(allEmailNodes[iEl].innerHTML);
		if (typeof emailText == 'undefined') {
			emailToShow = email;
		} else {
			emailToShow = emailText;
		}
		allEmailNodes[iEl].innerHTML = emailToShow;
		allEmailNodes[iEl].href = 'mailto:'+email;
	}
	
}

function aoa_decodeString(encodedString)
{
	var aChars = encodedString.split(' ');
	var size = aChars.length;
	var decodedString = '';
	for (var i = 0; i < size; i++) {
	
		if (aChars[i] < 128) {
			decodedString += String.fromCharCode(aChars[i]);
		} else if((c > 127) && (c < 2048)) {
			decodedString += String.fromCharCode((aChars[i] >> 6) | 192);
			decodedString += String.fromCharCode((aChars[i] & 63) | 128);
		} else {
			decodedString += String.fromCharCode((aChars[i] >> 12) | 224);
			decodedString += String.fromCharCode(((aChars[i] >> 6) & 63) | 128);
			decodedString += String.fromCharCode((aChars[i] & 63) | 128);
		}
	}
	
	return decodedString;
}

function aoa_init()
{
	// Can be overwritten in the page source
}

// Will fire the listeners after all the elements (images) on the page are loaded
function aoa_addOnLoadEventListener(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}

function aoa_addOnWindowResizeEventListener(func) {
  var oldonresize = window.onresize;
  if (typeof window.onresize != 'function') {
    window.onresize = func;
  } else {
    window.onresize = function() {
      if (oldonresize) {
        oldonresize();
      }
      func();
    }
  }
}

