//**********************************************************
// Global Functions
//**********************************************************

//----------------------------------------------------------
// Cookies Manager
//----------------------------------------------------------
function $cookies(method, name, value, ttl) {

	switch(method){
		case "get":
			var cookieArray = document.cookie.split("; "); 
			for(var i=0; i<cookieArray.length; i++) { 
				var item = cookieArray[i].split("=");
				if(item[0] == name){
					return item[1];
				}
			}
			return "";
			break;

		case "set":
			if(!ttl) ttl = 30;
			var date = new Date();
			date.setTime(date.getTime() + (ttl * 24*60*60*1000));
			document.cookie = name + '=' + value + '; expires=' + date.toGMTString() + '; path=/';
			break;

		case "del":
			document.cookie = name + '=;expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/';
			break;

	}

} 

//----------------------------------------------------------
// Show/Hide Element
//----------------------------------------------------------
function $toggleElement(id, method, style){
	
	var obj = document.getElementById(id);
	if(!obj) return;

	if(!style) style = "block";

	switch(method){
		case "show":
			obj.style.display = style;
			break;

		case "hide":
			obj.style.display = "none";
			break;

		default:
			if(obj.style.display != "none"){
				obj.style.display = "none";
			}else{
				obj.style.display = style;
			}

	}

}

//----------------------------------------------------------
// Shortcut for document.write and object.innerHTML
//----------------------------------------------------------
function $write(content, id, append){

	if(id){
		var obj = document.getElementById(id);
		if(obj){
			if(append){
				obj.innerHTML += content;
			}else{
				obj.innerHTML = content;
			}
			return;
		}
	}

	document.write(content);

}


//----------------------------------------------------------
// Write Language String
//----------------------------------------------------------
function $writeLang(label){
  document.write($lang(label));
}

//----------------------------------------------------------
// Read Language String
//----------------------------------------------------------
function $lang(label){
	
	// Try load from language file
	var str = external.max_Lang("StartPage", label);
	if(str != "") return str;

	// Try load default data
	str = maxStartPage.lang[label];
	if(!str) return "?n/a?";

	return str;

}


//----------------------------------------------------------
// Clone an object/array
//----------------------------------------------------------
function $cloneObject(obj){
	
	if(typeof obj != "object") return;

	var newObj;

	if(obj instanceof Array){
		// Clone Array
		newObj = [];
		for(var i=0; i<obj.length; i++){
			if(typeof obj[i] == "object"){
				newObj[i] = $cloneObject(obj[i]);
			}else{
				newObj[i] = obj[i];
			}
		}
	}else{
		// Clone Object
		newObj = {};
		for(i in obj){
			if(typeof obj[i] == "object"){
				newObj[i] = $cloneObject(obj[i]);
			}else{
				newObj[i] = obj[i];
			}
		}
	}

	return newObj;

}


//----------------------------------------------------------
// Convert Object to JSON String
//----------------------------------------------------------
function $toJSONString(obj){

	switch(typeof(obj)){
		case "object":
			if(obj instanceof Array){
				var out = "[ \n";
				for(var i=0; i<obj.length; i++){
					var t = $toJSONString(obj[i]);
					if(t){
						out += t;
						out +=",\n";
					}
				}
				out = out.slice(0,-2);
				out += "\n]";
			}else if(obj instanceof Object){
				var out = "{ \n";
				for(label in obj){
					var l = $toJSONString(label);
					var t = $toJSONString(obj[label]);
					if(t){
						out += l + ":" + t;
						out +=",\n";
					}
				}
				out = out.slice(0,-2);
				out += "\n}";
			}
			return out;
			break;
		case "string":
			var str = obj.replace('\b', '\\b');
			str = str.replace('\r', '\\r');
			str = str.replace('\t', '\\t');
			str = str.replace('\n', '\\n');
			str = str.replace('\f', '\\f');
			str = str.replace('\"', '\\"');
			str = str.replace('\\"', '\\\\"');
			return '"' + str + '"';
			break;
		case "number":
			return isFinite(obj) ? String(obj) : 'null';
			break;
		case "boolean":
			return String(obj);
			break;
		case "null":
			return "null";
			break;
	}

}


//**********************************************************
// Create Global Namespace
//**********************************************************
var maxStartPage = {};

//----------------------------------------------------------
// Global Variables
//----------------------------------------------------------
maxStartPage.global = {};
maxStartPage.global.activeTab = 0;
maxStartPage.global.prevTab = 0;
maxStartPage.tabs = [];
maxStartPage.items = [];


//**********************************************************
// Page Functions
//**********************************************************

//----------------------------------------------------------
// Initialize Page
//----------------------------------------------------------
maxStartPage.init = function(){

	// Hide all wrappers
	$toggleElement("iframeWrapper", "hide");
	$toggleElement("scriptWrapper", "hide");
	$toggleElement("contentWrapper", "hide");
	$toggleElement("searchWrapper", "hide");

	// Load Settings
	maxStartPage.config.load();

	// Write basic ui elements
	maxStartPage.ui.writeCssSelector();
	maxStartPage.ui.writeTabs();

	// Activate default tab
	maxStartPage.tab.activate(0);

	// Write Columns & Panels
	maxStartPage.ui.writeColumns();
	maxStartPage.ui.writePanels();

	// Attach destroy event
	document.onunload = maxStartPage.destroy;

}


//----------------------------------------------------------
// Destroy Page
//----------------------------------------------------------
maxStartPage.destroy = function(){

	delete simpleAjax;
	delete simpleFeedParser;
	delete simpleMD5;
	delete maxStartPage;

}


//**********************************************************
// Config Related Functions
//**********************************************************
maxStartPage.config = {};

//----------------------------------------------------------
// Load all settings
//----------------------------------------------------------
maxStartPage.config.load = function(){

	maxStartPage.config.prepareTabList();
	maxStartPage.config.prepareItemList();

}


//----------------------------------------------------------
// Prepare the Tab List for Start Page
//----------------------------------------------------------
maxStartPage.config.prepareTabList = function(){

	var strList = external.max_getPersonal('startTab');

	try{
		maxStartPage.tabs = eval(strList);
	}catch(e){
		alert("config.prepareTabList :: can not load tab list");
	}

}


//----------------------------------------------------------
// Prepare the Item List for Start Page
//----------------------------------------------------------
maxStartPage.config.prepareItemList = function(){

	// Add User List to Item List
	var userList = maxStartPage.config.loadUserFeedList();

	if(userList){
		maxStartPage.config.addToItemList(userList);
	}
	
	// Add Server List to Item List
	var serverList = external.max_getPersonal('startItem');
	serverList = maxStartPage.config.parseItemList(serverList);

	if(serverList){
		maxStartPage.config.addToItemList(serverList, "server");
	}
	
}


//----------------------------------------------------------
// Parse Item List into Array
//----------------------------------------------------------
maxStartPage.config.parseItemList = function(strList, srcFlag){
	
	var itemList;
	try{
		itemList = eval(strList);
	}catch(e){
		itemList = [];
	}
	
	if(!(itemList instanceof Array)) itemList = [];

	// Generate ID for items - need a better place
	for(var i=0; i<itemList.length; i++){
		itemList[i].id = maxStartPage.config.generateItemId(itemList[i]);
	}

	return itemList;

}


//----------------------------------------------------------
// Add a Custom Item List to Start Page Item List
//----------------------------------------------------------
maxStartPage.config.addToItemList = function(customList, srcFlag){
	
	if(!srcFlag) srcFlag = "normal";

	// Check for duplicated item against Global Item List
	for(; customList.length != 0;){

		var found = false;

		// Check through the custom list
		for(var j=0; j<maxStartPage.items.length; j++){
			if(customList[0].id == maxStartPage.items[j].id){

				found = true;

				if(srcFlag == "server"){
					maxStartPage.items[j].isServer = true;
					maxStartPage.items[j].markServer = true;
				}

			}

		}

		if(!found){

			if(srcFlag == "server"){
				customList[0].isServer = true;
				customList[0].markServer = true;
			}

			// Add new item to the list
			maxStartPage.items[maxStartPage.items.length] = customList[0];

		}

		customList.splice(0, 1);

	}

	// Clean up un-marked server side items
	if(srcFlag == "server"){
		for(var i=0; i<maxStartPage.items.length; i++){
			if(maxStartPage.items[i].isServer && !maxStartPage.items[i].markServer){
				maxStartPage.items.splice(i, 1);
				i--;
			}else{
				delete maxStartPage.items[i].markServer;
			}
		}
	}

}


//----------------------------------------------------------
// Load User Feed List
//----------------------------------------------------------
maxStartPage.config.loadUserFeedList = function(){
	
	var strList = external.max_getPersonal('startFeed');

	var arrList = strList.split('$,$');
	var arrResult = [];
	var arrID = {};

	for(var i=0; i<arrList.length; i++){
		var pos = arrList[i].indexOf('=');
		if(pos>-1){

			// Generate item data
			var item = {"col": 1, "type": "feed"};
			item.title = arrList[i].substring(0,pos);
			item.url = arrList[i].substring(pos + 1, arrList[i].length);
			if(item.url.indexOf("*")==0){
				item.url = item.url.substring(1, item.url.length);
				item.isServer = true;
				item.hidden = true;
			}

			item.id = maxStartPage.config.generateItemId(item);
			
			// Avoid duplicate item - use last one to replace
			if(!arrID[item.id]){
				arrID[item.id] = arrResult.length;
				arrResult.push(item);
			}else{
				arrResult[arrID[item.id]] = item;
			}

		}
	}

	return arrResult;

}


//----------------------------------------------------------
// Save User Feed List
//----------------------------------------------------------
maxStartPage.config.saveUserFeedList = function(arrItems){
	
	var output = "";
	for(var i=0; i<arrItems.length; i++){
		if(arrItems[i].type == "feed"){
			if(!arrItems[i].title) arrItems[i].title = $lang("feed");
			output += arrItems[i].title + "=";
			if(arrItems[i].isServer && arrItems[i].hidden) output += "*";
			output += arrItems[i].url + "$,$";
		}
	}
	if(output != "") output = output.slice(0,-3);
	
	external.max_writePersonal('startFeed', output);

}


//----------------------------------------------------------
// Save User Item List
//----------------------------------------------------------
maxStartPage.config.saveUserItemList = function(){
	
	// Remove item id
	var tempArray = $cloneObject(maxStartPage.items);
	for(var i=0; i<maxStartPage.items.length; i++){
		delete tempArray[i].id;
	}

	// Save the Feed List
	maxStartPage.config.saveUserFeedList(tempArray);

}


//----------------------------------------------------------
// Generate Unique Id for Items
//----------------------------------------------------------
maxStartPage.config.generateItemId = function(item){

	switch(item.type){
		case "feed":
			return "feed_" + simpleMD5.hex_md5(item.url);
			break;
		case "html":
			return "html_" + simpleMD5.hex_md5(item.url);
			break;
		default:
			return item.type + "_" + item.value;
			break;
	}

}


//----------------------------------------------------------
// Get Item by ID
//----------------------------------------------------------
maxStartPage.config.getItemById = function(id) {

	for(var i=0; i<maxStartPage.items.length; i++){
		if(maxStartPage.items[i].id == id){
			return maxStartPage.items[i];
		}
	}

	return null;

}


//----------------------------------------------------------
// Update Item by ID
//----------------------------------------------------------
maxStartPage.config.updateItem = function(item) {
	
	if(!item.id) return;

	for(var i=0; i<maxStartPage.items.length; i++){
		if(maxStartPage.items[i].id == item.id){
			maxStartPage.items[i] = item;
		}
	}

}


//----------------------------------------------------------
// Remove Item by ID
//----------------------------------------------------------
maxStartPage.config.removeItemById = function(id) {
	
	for(var i=0; i<maxStartPage.items.length; i++){

		if(maxStartPage.items[i].id == id){

			if(maxStartPage.items[i].isServer){
				// Just hide for server items
				maxStartPage.items[i].hidden = true;
			}else{
				// Remove item from list
				maxStartPage.items.splice(i, 1);
			}

		}

	}

}





//----------------------------------------------------------
// Remove Items in a Custom List From Start Page Item List
//----------------------------------------------------------
maxStartPage.config.removeFromItemList = function(customList){
}


//**********************************************************
// UI Related Functions
//**********************************************************
maxStartPage.ui = {};

//----------------------------------------------------------
// Output CSS <link> tag
//----------------------------------------------------------
maxStartPage.ui.attachCss = function(){

  for(var i=0;i<maxStartPage.cssFiles.length;i++){
    $write('<link title="css'+i+'" href="'+maxStartPage.cssFiles[i][1]+'" rel="stylesheet" disabled="true" type="text/css" />');
  }

}


//----------------------------------------------------------
// Output CSS Selector
//----------------------------------------------------------
maxStartPage.ui.writeCssSelector = function(){
	var output = "";
  for(var i=0;i<maxStartPage.cssFiles.length;i++){
    if(i>0) output += ' | ';
    output += '<a href="javascript:void(0)" onclick="maxStartPage.ui.applyStyleSheet(\'css'+i+'\')">' +
							maxStartPage.cssFiles[i][0] +
							'</a>';
  }
	$write(output, "cssSelector");
}


//----------------------------------------------------------
// Apply Selected CSS
//----------------------------------------------------------
maxStartPage.ui.applyStyleSheet = function(strCSS){
  var objs=document.getElementsByTagName("link");
  var intFound=0;
  for(var i=0;i<objs.length;i++){
    if(objs[i].type.indexOf("css")>-1&&objs[i].title){
      objs[i].disabled = true;
      if(objs[i].title==strCSS) intFound=i;
    }
  }
  objs[intFound].disabled = false;
  $cookies("set", "stylesheet", objs[intFound].title);
}


//----------------------------------------------------------
// Output Tabs
//----------------------------------------------------------
maxStartPage.ui.writeTabs = function(){

  var obj = document.getElementById("navtabs");
  for(var i=0;i<maxStartPage.tabs.length;i++){
    obj.innerHTML += '<li>'+
			'<a href="javascript:void(0)" onclick="maxStartPage.tab.activate('+i+');this.blur()">' +
			maxStartPage.tabs[i].title +
			'</a>'+
			'</li>\n';
  }

}


//----------------------------------------------------------
// Generate Columns
//----------------------------------------------------------
maxStartPage.ui.writeColumns = function(){
	
	var output = '<table width="100%" border="0" cellpadding="0" cellspacing="10">'+
							'<tr>';
	var width = 'width="' + Math.round(100 / maxStartPage.global.columnCount) + '%"';

	for(var i=0;i<maxStartPage.global.columnCount;i++){
		output += '<td valign="top" class="column" '+ (i != (maxStartPage.global.columnCount-1) ? width : '')+'><div id="column_'+i+'"></div></td>';
	}
	
	output += '</tr>'+
						'</table>';
	
	$write(output, "contentWrapper");

}


//----------------------------------------------------------
// Write and initialize panels
//----------------------------------------------------------
maxStartPage.ui.writePanels = function(){
	
	for(var i=0; i<maxStartPage.items.length;i++){
		
		maxStartPage.panel.add(maxStartPage.items[i]);
		maxStartPage.panel.init(maxStartPage.items[i]);

	}

}


//**********************************************************
// Tab Related Functions
//**********************************************************
maxStartPage.tab = {};

//----------------------------------------------------------
// Switch Tab
//----------------------------------------------------------
maxStartPage.tab.activate = function(tabNum){
	
	// Avoid duplicate activation of tab
	if(tabNum == maxStartPage.global.activeTab && maxStartPage.global.activeTab != 0) return;

	// Switch tab UI
	var obj = document.getElementById("navtabs");
	var objs = obj.getElementsByTagName("A");
	for(var i=0;i<objs.length;i++){
		objs[i].className="";
    if(i==tabNum) objs[i].className="active";
	}

	maxStartPage.global.prevTab = maxStartPage.global.activeTab;
	maxStartPage.global.activeTab = tabNum;
	
	if(!maxStartPage.tabs[maxStartPage.global.activeTab].type){
		maxStartPage.tabs[maxStartPage.global.activeTab].type = "unknown";
	}

	// Do hide stuff
	switch(maxStartPage.tabs[maxStartPage.global.prevTab].type){
		case "iframe":
			maxStartPage.tab.hideIFrame();
			break;
		case "script":
			maxStartPage.tab.hideScript();
			break;
		default:
			maxStartPage.tab.hideMain();
	}
	
	// Do show stuff
	switch(maxStartPage.tabs[maxStartPage.global.activeTab].type){
		case "iframe":
			maxStartPage.tab.showIFrame();
			break;
		case "script":
			maxStartPage.tab.showScript();
			break;
		default:
			maxStartPage.tab.showMain();
	}

}


//----------------------------------------------------------
// Show Main Content Tab
//----------------------------------------------------------
maxStartPage.tab.showMain = function(){

		$toggleElement("contentWrapper", "show");
		$toggleElement("searchWrapper", "show");


		var output = "";
		if(maxStartPage.tabs[maxStartPage.global.activeTab].label){
			output = maxStartPage.tabs[maxStartPage.global.activeTab].label;
		}else{
			output = maxStartPage.tabs[maxStartPage.global.activeTab].title;
		}
		
		output += '&nbsp;' +
							'	<input type="text" id="searchQuery" value="" onkeydown="if(event.keyCode==13){maxStartPage.search.execute()};" class="text" />' +
							'	<input id="searchButton" type="button" name="btn" onclick="maxStartPage.search.execute();" value=" '+$lang("search")+' " class="button" />';

		$write(output, "searchWrapper");

		document.getElementById("searchQuery").focus();

}


//----------------------------------------------------------
// Hide Main Content Tab
//----------------------------------------------------------
maxStartPage.tab.hideMain = function(){

	$toggleElement("contentWrapper", "hide");
	$toggleElement("searchWrapper", "hide");

}


//----------------------------------------------------------
// Show IFrame Tab
//----------------------------------------------------------
maxStartPage.tab.showIFrame = function(){

		$toggleElement("iframeWrapper", "show");
		
		var size = maxStartPage.tabs[maxStartPage.global.activeTab].size.split("*");

		var obj = document.getElementById("theIFrame");
		if(obj){
			obj.style.width = size[0];
			obj.style.height = size[1];
			obj.src = maxStartPage.tabs[maxStartPage.global.activeTab].url;
		}

}


//----------------------------------------------------------
// Hide IFrame Tab
//----------------------------------------------------------
maxStartPage.tab.hideIFrame = function(){

	$toggleElement("iframeWrapper", "hide");

}


//----------------------------------------------------------
// Switch To Script Tab
//----------------------------------------------------------
maxStartPage.tab.showScript = function(){

	$toggleElement("scriptWrapper", "show");

	// If already exists
	obj = document.getElementById("scriptWrapper_"+maxStartPage.tabs[maxStartPage.global.activeTab].namespace);
	if(obj){
		obj.style.display = "block";
		try{
			eval(maxStartPage.tabs[maxStartPage.global.activeTab].namespace+".show()");
		}catch(e){}
		return;
	}
	
	// Append New
	obj = document.getElementById("scriptWrapper");
	obj.innerHTML += '<div id="scriptWrapper_'+maxStartPage.tabs[maxStartPage.global.activeTab].namespace+'">'+
									 '<div class="script-comment">'+$lang("loading")+'</div>'+
									 '</div>';

	// Load the Script
	maxStartPage.script.load(maxStartPage.tabs[maxStartPage.global.activeTab].namespace,
													maxStartPage.tabs[maxStartPage.global.activeTab].url,
													maxStartPage.script.onLoad
													);

}


//----------------------------------------------------------
// Hide Script Tab
//----------------------------------------------------------
maxStartPage.tab.hideScript = function(){

	$toggleElement("scriptWrapper", "hide");

	try{
		$toggleElement("scriptWrapper_"+maxStartPage.tabs[maxStartPage.global.prevTab].namespace, "hide");
		eval(maxStartPage.tabs[maxStartPage.global.prevTab].namespace+".hide()");
	}catch(e){}

}


//**********************************************************
// Panel Related Functions
//**********************************************************
maxStartPage.panel = {};


//----------------------------------------------------------
// Add Panel to Columns
//----------------------------------------------------------
maxStartPage.panel.add = function(item){
	
	if(item.hidden) return; // To hide server-side items

	if(!item.col) item.col = 0;
	if(item.col > maxStartPage.global.columnCount) item.col = maxStartPage.global.columnCount;

	var output = '<div class="panel" id="panel_'+item.id+'">\n'+
							'<h5 id="panelHnd_'+item.id+'">'+
								'<div class="panel-control" id="panelCtrl_'+item.id+'"></div>'+
								'<a href="javascript:void(0)" onclick="$toggleElement(\'panelBox_'+item.id+'\');this.blur()" id="panelTtl_'+item.id+'">[Panel]</a>'+
							'</h5>\n'+
							'<div id="panelBox_'+item.id+'">'+
							'<div class="panel-content" id="panelCnt_'+item.id+'"></div>\n'+
							'</div>'+
							'</div>\n';
	
	$write(output, "column_"+item.col, true);

}


//----------------------------------------------------------
// Remove Panel
//----------------------------------------------------------
maxStartPage.panel.close = function(id){

	// Update Item List before clsoe
	maxStartPage.config.removeItemById(id);
	
	// Save the list
	maxStartPage.config.saveUserItemList();

	// Update UI
	var obj = maxStartPage.panel.getPanelById(id);
	if(obj){
		obj.removeNode(true);
	}

}


//----------------------------------------------------------
// Get Panel By Id
//----------------------------------------------------------
maxStartPage.panel.getPanelById = function(id){

	var obj = document.getElementById("panel_"+id);
	if(obj){
		return obj;
	}else{
		return null;
	}

}


//----------------------------------------------------------
// Initialize Panel Content
//----------------------------------------------------------
maxStartPage.panel.init = function(item){

	if(item.hidden) return; // To hide server-side items

	switch(item.type){
		case "internal":
			switch(item.value){
				case "hotfav":
					maxStartPage.panel.write(item.id, $lang("hotfav"), "title");
					maxStartPage.panel.write(item.id, maxStartPage.hotFav.generateHTML());
					break;
				default:
					alert("panel.init :: unknown internal panel type");
			}
			break;
		case "html":
			if(!item.title) item.title = $lang("html_content");
			maxStartPage.panel.write(item.id, item.title, "title");
			maxStartPage.html.load(item.id, item.url);
			break;
		case "feed":
			if(!item.title) item.title = $lang("feed");
			var strControl = '<a href="javascript:void(0)" onclick="maxStartPage.feed.load(\''+item.id+'\')"><img src="images/refresh.gif"/></a>'+
				'&nbsp;'+
				'<a href="javascript:void(0)" onclick="maxStartPage.panel.close(\''+item.id+'\')"><img src="images/close.gif"/></a>';
			maxStartPage.panel.write(item.id, strControl, "control");
			maxStartPage.panel.write(item.id, item.title, "title");
			maxStartPage.feed.load(item.id, item.url);
			break;
		default:
			alert("panel.init :: unknown item type");
	}

}


//----------------------------------------------------------
// Write Content to Panel
//----------------------------------------------------------
maxStartPage.panel.write = function(id, content, part, append){

	switch(part){
		case "title":
			$write(content, "panelTtl_"+id, append);
			break;
		case "control":
			$write(content, "panelCtrl_"+id, append);
			break;
		default:
			$write(content, "panelCnt_"+id, append);
	}

}


//**********************************************************
// Search Related Functions
//**********************************************************
maxStartPage.search = {};

//----------------------------------------------------------
// Search Form Submision
//----------------------------------------------------------
maxStartPage.search.execute = function(){

	var tip = $lang("askforkeyword");
	var obj = document.getElementById("searchQuery");

	if(obj.value != "" && obj.value != tip){

		window.open(
			maxStartPage.tabs[maxStartPage.global.activeTab].url.replace("%s", encodeURI(obj.value))
		);
		
	}else{

		obj.value = tip;
		obj.focus();
		obj.select();
		
	}

}


//**********************************************************
// HTML Panel Functions
//**********************************************************
maxStartPage.html = {};

//----------------------------------------------------------
// Load HTML
//----------------------------------------------------------
maxStartPage.html.load = function(id, url){

  maxStartPage.panel.write(id, '<span class="comment">'+$lang("loading")+'</span>');
  
	if(!simpleAjax.get(id, url, maxStartPage.html.output, {"responseType": 0})){
		maxStartPage.panel.write(id, '<span class="comment">'+$lang("load_error")+'('+simpleAjax.error.description+')</span>');
  }

}


//----------------------------------------------------------
// Output HTML
//----------------------------------------------------------
maxStartPage.html.output = function(id, result, status, statusText){

  if(result){
		maxStartPage.panel.write(id, simpleAjax.result[id]);
  }else{
		maxStartPage.panel.write(id, '<span class="comment">'+$lang("load_error")+'('+status+':'+statusText+')</span>');
  }

}


//**********************************************************
// External Script Related Functions
//**********************************************************
maxStartPage.script = {};

//----------------------------------------------------------
// Load Script File - require simpleAjax
//----------------------------------------------------------
maxStartPage.script.load = function(id, url, callBackFunc){
	if(!simpleAjax.get(id, url, callBackFunc, {"responseType": 0})){
		$write('<div class="script-comment">'+$lang("load_script_error")+' ('+simpleAjax.error.number+':'+simpleAjax.error.description+')</div>', "scriptWrapper_");
	}
}

//----------------------------------------------------------
// When Script File is Loaded
//----------------------------------------------------------
maxStartPage.script.onLoad = function(id, result, status, statusText){
  if(result){
    eval(simpleAjax.result[id]);
  }else{
		$write('<div class="script-comment">'+$lang("load_script_error")+' ('+status+':'+statusText+')</div>', "scriptWrapper_"+id);
  }
}


//**********************************************************
// Feed Functions
//**********************************************************
maxStartPage.feed = {};


//----------------------------------------------------------
// Load Feed
//----------------------------------------------------------
maxStartPage.feed.load = function(id, url){
	
	// Check if URL presents
	if(!url){
		var item = maxStartPage.config.getItemById(id);
		if(item){
			url = item.url;
		}else{
			return;
		}
	}

	maxStartPage.panel.write(id, '<span class="comment">'+$lang("loading")+'</span>');

	if(!simpleAjax.load(id, url, maxStartPage.feed.output, 0)){
		maxStartPage.panel.write(id, '<span class="comment">'+$lang("load_error")+'('+simpleAjax.error.number+':'+simpleAjax.error.description+')</span>');
	}

}


//----------------------------------------------------------
// Output Feed content into panel
//----------------------------------------------------------
maxStartPage.feed.output= function(id, result, errorCode, errorText){

	// Check if target panel exists
	var obj = maxStartPage.panel.getPanelById(id);
	if(!obj) return;

	if(result){
    maxStartPage.feed.parse(id, simpleAjax.result[id]);
  }else{
		maxStartPage.panel.write(id, '<span class="comment">'+$lang("load_error")+'('+errorCode+':'+errorText+')</span>');
  }

}


//----------------------------------------------------------
// Parse Feed Data into HTML
//----------------------------------------------------------
maxStartPage.feed.parse = function(id, feedSource){
	
	// Parse feed
	var objFeed = simpleFeedParser.parse(feedSource);

	// Process result
	if(typeof(objFeed)=="string"){
		
		// We got parse error
    maxStartPage.panel.write(id, '<span class="comment">'+$lang("parse_error")+'('+objFeed+')</span>');

  }else{

		// Prepare output content
    var outputHTML="";

    if(objFeed.items.length>0){
      for(var i=0;i<objFeed.items.length;i++){
        outputHTML+='<li><a href="javascript:void(0)" onclick="maxStartPage.feed.ui.toggleItem(this);this.blur()">'+objFeed.items[i].title+'</a>'+
          ' &nbsp;<a href="'+objFeed.items[i].link+'" target="_blank" class="feed-more">&raquo;</a>\n'+
          '<div class="feed-content" style="display:none">\n'+objFeed.items[i].description+'\n</div></li>\n';
      }
    }else{
      outputHTML='<li>'+$lang("no_content")+'</li>';
    }

    outputHTML='<div class="feed-box">\n<ul>\n'+outputHTML+'</ul>\n</div>\n';

    // Output now
		maxStartPage.panel.write(id, objFeed.title, 'title');
    maxStartPage.panel.write(id, outputHTML);

  }

}

//----------------------------------------------------------
// Feed UI Functions
//----------------------------------------------------------
maxStartPage.feed.ui = {};

//----------------------------------------------------------
// toggle show/hide a single feed content 
//----------------------------------------------------------
maxStartPage.feed.ui.toggleItem = function(objA){

  var obj=objA.parentElement;
  var objs=obj.getElementsByTagName("DIV");
	for(var i=0;i<objs.length;i++){
    if(objs[i].className=="feed-content"){
      if(objs[i].style.display!="none"){
        objs[i].style.display="none";
      }else{
        objs[i].style.display="block";
      }
    }
	}

}


//----------------------------------------------------------
// Hot Favorites List Related Functions
//----------------------------------------------------------
maxStartPage.hotFav ={};


//----------------------------------------------------------
// Load the Hot Favorites List
//----------------------------------------------------------
maxStartPage.hotFav.load = function(){

	var strList = external.max_getPersonal('hotfav');

	var arrList = strList.split('$,$');
	var arrResult = [];

	for(var i=0; i<arrList.length; i++){
		var pos = arrList[i].indexOf('=');
		if(pos>-1){
			var name = arrList[i].substring(0,pos);
			var url = arrList[i].substring(pos + 1, arrList[i].length);
			arrResult.push([name, url]);
		}
	}
	
	return arrResult;

}


//----------------------------------------------------------
// Genreate HTML for Hot Favorites List
//----------------------------------------------------------
maxStartPage.hotFav.generateHTML = function(){

	var arrList = maxStartPage.hotFav.load();
	var output = "";

	output += "<ul>";
	for(var i=0; i<arrList.length; i++){
		output += '<li><a href="'+arrList[i][1]+'" target="_blank">'+arrList[i][0]+'</a>';
	}
	output += "</ul>";
	
	return output;

}