/*
 *
 * accordionMenu gerenates an accordion style menu with contents from div, url, rss, json, text and custom function.
 *
 */

function renderAccordion1(contentId) {
    document.getElementById(contentId).innerHTML = "<iframe name='acc_1' width='100%' height='210' scrolling='no' border='0' frameborder='0' src='/accordion/mobilise.aspx'></iframe>";
}

function renderAccordion2(contentId) {
    document.getElementById(contentId).innerHTML = "<iframe name='acc_2' width='100%' height='210' scrolling='no' border='0' frameborder='0' src='/accordion/games.aspx'></iframe>";
}

function renderAccordion3(contentId) {
    document.getElementById(contentId).innerHTML = "<iframe name='acc_3' width='100%' height='110' MARGINHEIGHT='0' MARGINWIDTH='0' scrolling='no' border='0' frameborder='0' src='/accordion/ringtones.aspx'></iframe>";
}

function renderAccordion4(contentId) {
    document.getElementById(contentId).innerHTML = "<iframe name='acc_4' width='100%' height='150' MARGINHEIGHT='0' MARGINWIDTH='0' scrolling='no' border='0' frameborder='0' src='/accordion/wallpapers.aspx'></iframe>";
}


// create accordionMenu class
accordionMenu = function(name, pageId, doRandomDefault, useAdTrack, slideSpeed, isDebug) 
{
	// set the class variables
	this.isDebug = false;
	this.isIe = window.ActiveXObject;
	this.isFireFox = document.implementation && document.implementation.createDocument;
	this.maxList = 10;
	this.timer = 1;
	this.fireFoxHeightFix = 10;		// just for hack. this can be fixed in css level anyway
	this.titleIdSuffix = '_title';
	this.blindIdSuffix = '_menu';
	this.blindCssPrefix = 'asm-menu';
	this.spinner = '<div id="' + name + '_spinner"><img src="img/accordion_spinner.gif"></div>';

	try 
	{
		this.name = name;
		// check if the parameters are parsed all together
		var params = pageId && (typeof(pageId) == 'string') ? pageId.split(";") : '';
		var defaultSpeed = 20;
		if (params.length > 1) 
		{
			this.pageId = params[0] ? params[0] : false;
			this.doRandomDefault = params[1] ? this.isTrue(params[1]) : false;
			this.useAdTrack = params[2] ? this.isTrue(params[2]) : false;
			this.slideSpeed = params.length > 3 ? (params[3] ? parseInt(params[3],10) : defaultSpeed) : defaultSpeed;
			this.isDebug = params.length == 5 ? (params[4] ? this.isTrue(params[4]) : false) : false;
		}
		else 
		{
			// set the inital settings
			this.pageId = pageId ? pageId : false;
			this.doRandomDefault = doRandomDefault ? this.isTrue(doRandomDefault) : false;
			this.useAdTrack = useAdTrack ? this.isTrue(useAdTrack) : false;
			this.slideSpeed = slideSpeed ? parseInt(slideSpeed,10) : defaultSpeed;	// the higher, the faster
			this.isDebug = isDebug ? isDebug : false;
		}
		this.menu = new Array();
		
		// isDebug can be setup in query string as well
		this.isDebug = this.isTrue(this.getArgs().isAccordionDebug);
	}
	catch(e) 
	{
		if(this.isDebug) 
		{
			alert(e);
		}
	}
}

// add a menu to a array
accordionMenu.prototype.addMenu = function(menuId, contentId, target, mode, isOpen, autoUpdate, defaultHeight) 
{
	try 
	{
		// check if the parameters are parsed all together
		var params = mode && typeof(mode) == 'string' ? mode.split(";") : '';
		if (params.length > 1) 
		{
			mode = params[0];
			isOpen = this.isTrue(params[1]);
			autoUpdate = params.length > 2 ? (params[2] ? params[2] : false) : false;
			defaultHeight = params.length == 4 ? parseInt(params[3],10) : this.getDefaultHeight(contentId);
		}
		else 
		{
			mode = mode ? mode : 'div';
			isOpen = isOpen ? isOpen : false;
			autoUpdate = autoUpdate ? autoUpdate : false;
			defaultHeight = defaultHeight ? defaultHeight : this.getDefaultHeight(contentId);
		}

		// if no div for menu and content, nothing to do
		if((!menuId || !document.getElementById(menuId)) && this.isDebug) 
		{
			alert("Invalid menuId : " + menuId);
		}
		else 
		{
			this.addMenuEvent(menuId + this.blindIdSuffix, autoUpdate);
			this.addMenuEvent(menuId + this.titleIdSuffix, autoUpdate);
			this.menu.push({menuId:menuId,contentId:contentId,mode:mode,isOpen:isOpen,target:target,height:0,defaultHeight:defaultHeight});
		}
		
		// put the json object if it is json
		if(mode == 'json')
		{
			//this.setJsonObject(target);
		}
	}
	catch(e) 
	{
		if(this.isDebug) 
		{
			alert(e);
		}
	}	
}

// add event to a menu
accordionMenu.prototype.addMenuEvent = function(id, autoUpdate) 
{
	var self = this;
	document.getElementById(id).onclick = function() 
	{ 
	    var thisId = this.id;
		if(self.useAdTrack && (typeof AdTrack != 'undefined')) 
		{
			AdTrack.t(this, self.name, (self.getMenuIndex(thisId)+1));
		}
		self.playAccordionMenu(self, thisId, autoUpdate);
	}
	document.getElementById(id).style.cursor = 'pointer';
}

// initialize the accordion menu
// it also makes menu open if it is set to open or randomly chosen
accordionMenu.prototype.initialize = function() 
{
	try 
	{
		// get the random index if random default is activated
		var randomIndex = this.doRandomDefault ? this.getRandomNumber() : 0;
		
		// go through all the menu
		var accordion = this;
		for(var i=0; i<this.menu.length; i++) 
		{
			// no contentDiv, no content
			var thisMenu = this.menu[i];
			if(document.getElementById(thisMenu.contentId)) 
			{
				// set the content div
				this.setContent(i);

				var makeOpen = false;
				if(this.doRandomDefault) 
				{
					makeOpen = randomIndex == i;
				}
				else 
				{
					makeOpen = thisMenu.isOpen === true;
				}
				
				var height = thisMenu.defaultHeight > -1
					? thisMenu.defaultHeight : this.getContentHeight(thisMenu.contentId);
				var contentDiv = document.getElementById(thisMenu.contentId);
				contentDiv.style.display = makeOpen ? 'block' : 'none';
				contentDiv.style.height = height + 'px';
				this.setMenu(i, makeOpen, height);
				
				var thisMode = thisMenu.mode;
				if((thisMode == 'url') || (thisMode == 'rss') || (thisMode == 'json'))
				{
					this.setAjaxRequest(i, thisMode, makeOpen);
				}
			}
			else if(this.isDebug) 
			{
				alert("Invalid contentId at " + this.menu[i].menuId);
			}
		}
	}
	catch(e) 
	{
		if(this.isDebug) 
		{
			alert(e);
		}
	}
}

// set the open status, height and blind div
accordionMenu.prototype.setMenu = function(index, isOpen, height) 
{
	this.menu[index].isOpen = isOpen;
	if(height && (height > -1)) 
	{
		this.menu[index].height = height;
	}

	var thisMenu = this.menu[index];

	// set the arrow direction if headIt is given
	var blindDiv = document.getElementById(thisMenu.menuId + this.blindIdSuffix);
		
	if(blindDiv) 
	{
		blindDiv.className = this.blindCssPrefix + (isOpen ? '-on' : '-off');
	}
}

// returns the menu having the same menuId or contentId as the given id
accordionMenu.prototype.getMenu = function(id) 
{
	for(var i=0; i<this.menu.length; i++) 
	{
		if(this.isSameMenu(this.menu[i].menuId, id)) 
		{
			return this.menu[i];
		}
	}
	return null;
}

// returns the menu having the same menuId or contentId as the given id
accordionMenu.prototype.getMenuIndex = function(id) 
{
	for(var i=0; i<this.menu.length; i++) 
	{
		if(this.isSameMenu(this.menu[i].menuId, id)) 
		{
			return i;
		}
	}
	return null;
}

// check if two ids are from the same menu
accordionMenu.prototype.isSameMenu = function(menuId, thisId) 
{
	return thisId.indexOf(menuId) > -1;
}

// return the default height of the content div
accordionMenu.prototype.getDefaultHeight = function(contentId)
{
	var defaultHeight = -1;
	if(document.getElementById(contentId))
	{
		var contentDiv = document.getElementById(contentId);
		var thisHeight = this.isIe 
			? contentDiv.currentStyle.height 
			: document.defaultView.getComputedStyle(contentDiv,null).height;

		if(thisHeight != 'auto')
		{
			if(thisHeight.indexOf("px") > 0)
			{
				defaultHeight = thisHeight.substring(0,thisHeight.length-2);
			}
			else
			{
				defaultHeight = thisHeight;
			}
		}
	}
	return parseInt(defaultHeight);
}

// returns the height of the content div when it is displayed with the content
accordionMenu.prototype.getContentHeight = function(contentId) 
{
	var height = 0;
	var contentDiv = document.getElementById(contentId);
	var content = contentDiv.innerHTML;
	var display = contentDiv.style.display;

	// make a temperally div to measure the height
	var div = document.createElement('div');
	contentDiv.innerHTML = '';
	contentDiv.style.display = 'block';
	contentDiv.appendChild(div);
	div.style.display = 'block';
	div.innerHTML = content;
	height = contentDiv.scrollHeight > 1 ? contentDiv.scrollHeight : contentDiv.offsetHeight;
	contentDiv.removeChild(div);
	contentDiv.style.display = display;
	contentDiv.innerHTML = content;
	
	return height;
}

// set the height of the page
// the height of the page will be set only if the random default is false, no menu is open onload,
// pageId is given and the heigh of the page is not set already
accordionMenu.prototype.setPageHeight = function()
{
	// set the page height if pageId is given
	this.pageHeight = false;
	var pageDiv = document.getElementById(this.pageId);
	if(pageDiv)
	{
		var menuHeight = 0;
		for(var i=0; i<this.menu.length; i++)
		{
			if(this.menu[i].isOpen)
			{
				menuHeight += this.menu[i].height;
			}
		}
		this.pageHeight = (pageDiv.style.height > 1 ? pageDiv.style.height : pageDiv.offsetHeight) - menuHeight;
	}
}

// returns the content depending on the target mode
accordionMenu.prototype.setContent = function(index) 
{
	var thisMenu = this.menu[index];
	var contentDiv = document.getElementById(thisMenu.contentId);
	contentDiv.style.overflow = 'hidden';
	
	// do nothing if no target
	if(thisMenu.target) 
	{
		contentDiv.innerHTML = this.spinner;
		switch(thisMenu.mode) 
		{
			case 'url':
				this.setAjaxRequest(index);
				break;
			case 'rss':
				this.setAjaxRequest(index, 'rss');
				break;
			case 'json':
				this.setAjaxRequest(index, 'json');
				break;
			case 'text':
				contentDiv.innerHTML = thisMenu.target;
				break;
			case 'custom':
				eval(thisMenu.target + "('" + thisMenu.contentId + "');");
				break;
			default:
				if(document.getElementById(thisMenu.target)) 
				{
					var targetDiv = document.getElementById(thisMenu.target);
					targetDiv.style.display = 'none';
					contentDiv.innerHTML = targetDiv.innerHTML;
				}
				break;
		}
	}
}

// update the contents and the height for the div
// get ajax crequest
accordionMenu.prototype.setAjaxRequest = function(index, type, isOpening) 
{
	var thisMenu = this.menu[index];
	// no contentId or url, no ajx
	if((!thisMenu.contentId || !thisMenu.target) && this.isDebug) 
	{
		alert("Invalid Ajax Call");
	}
	else 
	{
		var request;
		var self = this;
		var url = thisMenu.target;
		
		// trick: if it is ie, put a tail with a random number so that it gets refreshed everytime
		if(self.isIe) 
		{
			url = url
				+ (thisMenu.target.indexOf("?") > -1 ? "&" : "?")
				+ "randomeNumber=" + self.getRandomNumber(100000);
		}

		// create ajax
		try 
		{
			request = new XMLHttpRequest();
		}
		catch (trymicrosoft) 
		{
			try 
			{
				request = new ActiveXObject("Msxml2.XMLHTTP");
			}
			catch (othermicrosoft) 
			{
				try 
				{
					request = new ActiveXObject("Microsoft.XMLHTTP");
				}
				catch (failed) 
				{
					request = false;
				}
			}
		}

		if (!request && self.isDebug) 
		{
			alert("Invalid AJAX Call : Error initializing XMLHttpRequest!");
		}
		else 
		{
			request.onreadystatechange = function() 
			{
					if (request.readyState == 4) 
					{ // ok for 200
						if (request.status == 200) 
						{
							document.getElementById(thisMenu.contentId).innerHTML = type == 'rss' 
								? self.getRssResult(request.responseXML) 
								: (type == 'json' ? self.getJsonResultByAjax(request.responseText) : request.responseText);

							var height = thisMenu.defaultHeight > -1
								? thisMenu.defaultHeight 
								: self.getContentHeight(thisMenu.contentId) 
									+ (self.isFireFox ? self.fireFoxHeightFix : 0);
								
							if(isOpening)
							{
								self = self.slideMenu(self, index, height, 1, true);
								self.setMenu(index, true, height);
							}
							else
							{
								self.setMenu(index, false, height);
							}
						}
						else if(self.isDebug) 
						{
							alert("There was a problem retrieving data:\n" + request.status);
						}
					} 			
				}; 
			request.open("get", url, true);
			request.send(null); 
		}
	}
}

// return a list of the linked titles for the given rss
// the rss should have title and link element in item node
accordionMenu.prototype.getRssResult = function(rss) 
{
	var result = '';
	var rssDoc;
	
	// check if the source is already xml
	if(rss.firstChild && rss.firstChild.firstChild) 
	{
		rssDoc = rss;
	}
	else 
	{
		if (this.isFireFox) 
		{
			rssDoc = document.implementation.createDocument("", "", null);
		}
		else if (this.isIe) 
		{
			rssDoc = new ActiveXObject("Msxml2.DOMDocument.3.0");
		}
		else if(this.isDebug) 
		{
			alert("Your browser can't handle this script.");
		}		
		rssDoc.async = false;
		rssDoc.load(rss);
	}

	// check if xml is loaded properly
	if((rssDoc.childNodes.length < 1) && this.isDebug) 
	{
		alert("Invalid RSS");
	}
		
	var items = rssDoc.getElementsByTagName('item');

	if(items.length > 0) 
	{
		result += '<ul>';
		var max = items.length > this.maxList ? this.maxList : items.length;
		if(items[0].getElementsByTagName('title')[0]) 
		{
			for(var i=0; i<max; i++) 
			{
				result += '<li><a href="' + items[i].getElementsByTagName('link')[0].firstChild.nodeValue 
					+ '">' + items[i].getElementsByTagName('title')[0].firstChild.nodeValue + '</a></li>';
			}
		}
		else if(this.isDebug) 
		{
			alert("No title for rss");
		}
		result += '</ul>';
	}
	return result;
}

// return a list of the linked titles for the given json
// the json should have title and link element in item node
accordionMenu.prototype.getJsonResultByAjax = function(json) {
	var result = '';
	var jsonDoc;

	// check if the source is already xml
	if(json.value) {
		jsonDoc = json;
	}
	else {
		jsonDoc	= eval("(" + json + ")");
	}
	
	if(jsonDoc.count > 0) {
		result += '<ul>';
		var max = jsonDoc.count > this.maxList ? this.maxList : jsonDoc.count;

		if(jsonDoc.value.items[0].title || (jsonDoc.value.items[0].title === '')) {
			for(var i=0; i<max; i++) {
				result += '<li><a href="' + jsonDoc.value.items[i].link 
					+ '">' + jsonDoc.value.items[i].title + '</a></li>';
			}
		}
		else if(this.isDebug) {
			alert("No title for json");
		}
		result += '</ul>';
	}
	return result;
}

// use this json function if you return json with jsonId inside
accordionMenu.prototype.setJsonResultBySrc = function(contentId, json)
{
	var result = '';
	var jsonDoc;

	// check if the source is already xml
	if(json) 
	{
		//document.write('<scr' + 'ipt src="' + json + '"></scr' + 'ipt>');
		var startPos = json.indexOf('jsonId');
		if(startPos > 0)
		{
			startPos = json.indexOf('=',startPos) + 1;
			var endPos = json.indexOf('&',startPos);
			if(endPos < 0 )
			{
				endPos = json.length;
			}
			json = json.substring(startPos, endPos);
			jsonDoc = eval(json);
		}
		if(jsonDoc && (jsonDoc.count > 0))
		{
			result += '<ul>';
			var max = jsonDoc.count > this.maxList ? this.maxList : jsonDoc.count;

			if(jsonDoc.value.items[0].title || (jsonDoc.value.items[0].title === '')) 
			{
				for(var i=0; i<max; i++) 
				{
					result += '<li><a href="' + jsonDoc.value.items[i].link 
						+ '">' + jsonDoc.value.items[i].title + '</a></li>';
				}
			}
			else if(this.isDebug) 
			{
				alert("No title for json");
			}
			result += '</ul>';
		}
	}
	document.getElementById(contentId).innerHTML = result;
}

// set the json object
accordionMenu.prototype.setJsonObject = function(url)
{
	//document.write('<scr' + 'ipt src="' + target + '"></scr' + 'ipt>');
	var head = document.getElementsByTagName("head")[0];
	var script = document.createElement('script');
	script.type = 'text/javascript';
	script.src = url;
	head.appendChild(script);
}

// returns a random number smaller than the given max number
// if no maximum is given, use the length of the menu as the default
accordionMenu.prototype.getRandomNumber = function(max) 
{
	return Math.round(100*Math.random()) % (max ? max : this.menu.length);
}

// parse the boolean for both boolean and string
accordionMenu.prototype.isTrue = function(value) 
{
	if(typeof(value) == 'boolean') 
	{
		return value;
	}
	else if(typeof(value) == 'string') 
	{
		return value == 'true';
	}
	else 
	{
		return false;
	}
}

// returns the argument on url
accordionMenu.prototype.getArgs = function() { 
	var args = new Object(); 
	var query = location.search.substring(1);
	var pairs = query.split("&");
	for(var i = 0; i < pairs.length; i++)
	{
		var pos = pairs[i].indexOf('=');
		if (pos == -1)
		{
			continue; 
		}
		var argname = pairs[i].substring(0,pos);
		var value = pairs[i].substring(pos+1);
		args[argname] = unescape(value);
	}
	return args; 
}

// do the actual accordion for all the menu
accordionMenu.prototype.playAccordionMenu = function(accordion, clickedId, autoUpdate) 
{
	// if no event, nothing to do
	if(!clickedId && accordion.isDebug) 
	{
		alert("Invalid clickedId");
	}
	else 
	{
		// go through all the menu
		try 
		{
			// set the page height before go into the menu
			if(accordion.pageId && !accordion.pageHeight)
			{
				accordion.setPageHeight();
			}
			
			for(var i=0; i<accordion.menu.length; i++) 
			{
				var thisMenu = accordion.menu[i];
				var height = thisMenu.height;
				if(accordion.isSameMenu(thisMenu.menuId, clickedId)) 
				{
					if(thisMenu.isOpen) 
					{
						accordion = accordion.slideMenu(accordion, i, height, height, false);
						accordion.setMenu(i, false);
					}
					else 
					{
						// if it is auto update, get the right content and height
						// otherwise just open the menu
						if(autoUpdate && document.getElementById(thisMenu.contentId)) 
						{
							// for ajax, let the ajax handle the slide
							// otherwise reset the content and height
							var thisMode = thisMenu.mode;
							if((thisMode == 'url') || (thisMode == 'rss') || (thisMode == 'json'))
							{
								accordion.setAjaxRequest(i, thisMode, true);
							}
							else
							{
								accordion.setContent(i);
								height = accordion.getContentHeight(thisMenu.contentId);
								accordion.slideMenu(accordion, i, height, 1, true);
							}
						}
						else
						{
							accordion = accordion.slideMenu(accordion, i, height, 1, true);
						}
						accordion.setMenu(i, true, height);
					}
				}
				else if(thisMenu.isOpen) 
				{
					accordion = accordion.slideMenu(accordion, i, height, height, false);
					accordion.setMenu(i, false);
				}
			}
		}
		catch(e) 
		{
			if(accordion.isDebug) 
			{
				alert(e);
			}
		}
	}
	return false;
}

// do animation for the menu with the given contentId
accordionMenu.prototype.slideMenu = function(accordion, index, originalHeight, currentHeight, isOpening) 
{
	var thisAccordion = accordion;
	var contentDiv = document.getElementById(accordion.menu[index].contentId);
	
	if(contentDiv) 
	{
		// recurse only if the current height is between 0 and the original height
		if ((currentHeight >= 1) &&
			(currentHeight <= originalHeight)) 
		{
    		contentDiv.style.display = 'block';
			contentDiv.style.height = currentHeight + 'px';	
			// also update the page height if page id is given
			if(this.pageHeight)
			{
				document.getElementById(this.pageId).style.height = this.pageHeight + currentHeight + 'px';
			}
			var thisHeight = isOpening ? currentHeight+accordion.slideSpeed : currentHeight-accordion.slideSpeed;
			setTimeout
			(
				function() 
				{ 
					thisAccordion = thisAccordion.slideMenu(thisAccordion, index, originalHeight, thisHeight, isOpening); 
				}, 
				accordion.timer
			);
		}
		else 
		{
			// if the currentHeight is less than 1, it must be closing so make the height 1
			if(currentHeight < 1) 
			{
				contentDiv.style.height = '1px';
		    	contentDiv.style.display = 'none';
				// also update the page height if page id is given
				if(this.pageHeight)
				{
					document.getElementById(this.pageId).style.height = this.pageHeight + 'px';
				}
			}
			// else if the current height is bigger than the original height, it must be opening so make the height the original height
			else if(currentHeight > originalHeight) 
			{
				contentDiv.style.height = originalHeight + 'px';
				// also update the page height if page id is given
				if(this.pageHeight)
				{
					document.getElementById(this.pageId).style.height = this.pageHeight + originalHeight + 'px';
				}
			}
		}
	}
	return thisAccordion;
}



