var aoa = {};
var musicalion = {};

// Common Functions
var aoa_heightHeaderAndFoter = 245;
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_refreshSession()
{
	document.getElementById('sessRefresh').src = 'sessrefresh.php';
  	window.frames['sessRefresh'].location.reload(); 
  	setTimeout("aoa_refreshSession()", 900000);
}

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;
}

/**
 * Add GET variable to the given url
 */
function aoa_addVariableToUrl(variable, value, url)
{
	var separator = '&';
	var eq = '=';
	
	var aTmp = url.split('#');
	var urlHash = aTmp[1];
	var urlNoHash = aTmp[0];
	aTmp = urlNoHash.split('?');
	var urlNoQuery = aTmp[0];
	var query = aTmp[1];
	if (typeof query == 'undefined') {
		query = '';
	}
	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
			if (typeof value != 'undefined') {
				newQuery += pair[0]+eq+value;
			} else {
				newQuery += pair[0];
			}
			bAdded = true;
		} else if(pair[0] != '') {
			if (typeof pair[1] != 'undefined') {
				newQuery += pair[0]+eq+pair[1];
			} else {
				newQuery += pair[0];
			}
		}
	}
	
	if (!bAdded) {
		if (newQuery != '') {
			if (typeof value != 'undefined') {
				newQuery += separator+variable+eq+value;
			} else {
				newQuery += separator+variable;
			}
		} else {
			if (typeof value != 'undefined') {
				newQuery += variable+eq+value;
			} else {
				newQuery += variable;
			}
		} 
	}
	
	if (typeof urlHash != 'undefined' && urlHash != '') {
		urlHash = '#'+urlHash;
	} else {
		urlHash = '';
	}
	
	return urlNoQuery+'?'+newQuery+urlHash;
}


function aoa_addHashVariableToUrl(url, variable, value, separator, eq)
{
	if (typeof separator == 'undefined') {
		separator = '&';
	}
	if (typeof eq == 'undefined') {
		eq = '=';
	}
	
	var aTmp = url.split('#');
	var query = aTmp[1];
	if (typeof query == 'undefined') {
		query = '';
	}
	var urlNoHash = aTmp[0];
	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
			if (typeof value != 'undefined') {
				newQuery += pair[0]+eq+value;
			} else {
				newQuery += pair[0];
			}
			bAdded = true;
		} else if(pair[0] != '') {
			if (typeof pair[1] != 'undefined') {
				newQuery += pair[0]+eq+pair[1];
			} else {
				newQuery += pair[0];
			}
		}
	}
	
	if (!bAdded) {
		if (newQuery != '') {
			if (typeof value != 'undefined') {
				newQuery += separator+variable+eq+value;
			} else {
				newQuery += separator+variable;
			}
		} else {
			if (typeof value != 'undefined') {
				newQuery += variable+eq+value;
			} else {
				newQuery += variable;
			}
		} 
	}
	
	return urlNoHash+'#'+newQuery;
}

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
			if (typeof value != 'undefined') {
				newQuery += pair[0]+eq+value;
			} else {
				newQuery += pair[0];
			}
			bAdded = true;
		} else if(pair[0] != '') {
			if (typeof pair[1] != 'undefined') {
				newQuery += pair[0]+eq+pair[1];
			} else {
				newQuery += pair[0];
			}
		}
	}
	
	if (!bAdded) {
		if (newQuery != '') {
			if (typeof value != 'undefined') {
				newQuery += separator+variable+eq+value;
			} else {
				newQuery += separator+variable;
			}
		} else {
			if (typeof value != 'undefined') {
				newQuery += variable+eq+value;
			} else {
				newQuery += variable;
			}
		} 
	}
	
	window.location.hash = '#'+newQuery;
}

function aoa_clearHash()
{
	window.location.hash = '#';
}

// 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);
}

var aoa_singleWindow = null;

function aoa_popUpSingle(page, w, h, left, top, resize, scrollbars)
{
	if (typeof w == 'undefined') {
		w = 950;
	}
	if (typeof h == 'undefined') {
		h = 700;
	}
	if (typeof left == 'undefined') {
		left = 0;
	}
	if (typeof top == 'undefined') {
		top = 0;
	}
	if (typeof resize == 'undefined') {
		resize = 1;
	}
	if (typeof scrollbars == 'undefined') {
		scrollbars = 1;
	}
	if (aoa_singleWindow != null) {
		try {
			aoa_singleWindow.close();
			aoa_singleWindow = null;
		} catch (e) {}
	}
	aoa_singleWindow = window.open(page, 'aoa_PopUpWindow', "dependent, height=" + h + ", width=" + w + ", left=" + left + ", top=" + top + ", resizable=" + resize + ", scrollbars=" + scrollbars);
	
	if (aoa_singleWindow) {
		return false;
	}
	return true;
}

function aoa_popUp(page, name, w, h, left, top, resize, scrollbars)
{
	if (typeof name == 'undefined') {
		name = 'aoa_PopUpWindow';
	}
	
	if (typeof w == 'undefined') {
		w = 950;
	}
	if (typeof h == 'undefined') {
		h = 700;
	}
	if (typeof left == 'undefined') {
		left = 0;
	}
	if (typeof top == 'undefined') {
		top = 0;
	}
	if (typeof resize == 'undefined') {
		resize = 1;
	}
	if (typeof scrollbars == 'undefined') {
		scrollbars = 1;
	}
	
	var win = window.open(page, name, "dependent, height=" + h + ", width=" + w + ", left=" + left + ", top=" + top + ", resizable=" + resize + ", scrollbars=" + scrollbars);
	
	if (win) {
		return false;
	}
	return true;
}

function aoa_popUpComposition(url, name)
{
	return aoa_popUp(url, name, 994, 720, 5, 5, 1, 1);
}

function aoa_popUpComposer(url, name)
{
	return aoa_popUp(url, name, 950, 720, 15, 15, 1, 1);
}

function aoa_popUpPerformer(url, name)
{
	return aoa_popUp(url, name, 950, 720, 25, 25, 1, 1);
}

function aoa_popUpInterpretation(url, name)
{
	return aoa_popUp(url, name, 460, 660, 100, 100, 1, 1);
}

function aoa_popUpInterpretationSimple(url, name)
{
	return aoa_popUp(url, name, 460, 200, 100, 100, 1, 1);
}

function aoa_popUpContactUs(url)
{
	return aoa_popUp(url, 'contact_us', 800, 650, 35, 35, 1, 1);
}

function aoa_popUpForgottenPassword(url, name)
{
	return aoa_popUp(url, 'forgetten_password', 800, 450, 35, 35, 1, 1);
}

function aoa_popUpMusicUpload(url, name)
{
	return aoa_popUp(url, name, 1012, 720, 10, 10, 1, 1);
}

function aoa_popUpSmall(url, name)
{
	return aoa_popUp(url, name, 600, 400, 55, 55, 1, 1);
}

function aoa_popUpCs(url)
{
	return aoa_popUp(url, 'aoa_PopUpWindow', 500, 520, 50, 50, 1, 1);
}


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;
	
}

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

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

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

// site specific
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');
	if (!cont) {
		return;
	}
	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%';
	// As IE8 needs contentClipper to have width auto if there is banners control and 100% if not
	// One more hack
	var cont = document.getElementById('contentClipper');
	if (!cont) {
		return;
	}
	cont.style.width = 'auto';
}

function aoa_fixMenuSize()
{
	var mnu = document.getElementById('menuClipper');
	if (typeof(mnu) == 'undefined' || mnu == null) {
		return;
	}
	var sz = aoa_getDocumentHeight() - aoa_heightHeaderAndFoter;
	
	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="500" 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.style.paddingTop = '100px';
	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';
	}
	try {
		document.getElementsByTagName('html')[0].scrollTop='0';
	} catch (e) {}
}

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.style.paddingTop = '';
	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()
{
	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();
    };
  }
}

function aoa_loginRefreshBackTo(form)
{
	form.backTo.value = window.location.href;
}
