/*******************************************************************************************
** image and effects
********************************************************************************************/

var TREE_BUTTON_IMG_PATH = SHARED_IMAGE_DIR + "treeButtons/";
var HP_IMG_PATH = SHARED_IMAGE_DIR + "mod_hp/";
var HP_ICON_PATH = HP_IMG_PATH + "icons/";

var frameColors = new Array("B3DCEA", "A3C7EC", "D1CAB9", "BBD1B9", "B7BECF", "DBAFB9", "AAAAAA");
var colorNames = new Array("ltblue", "blue", "brown", "green", "purple", "pink", "gray");

var hpCID = new Array();
var hpComponent_settings = new Array();
//var hp_settingsContainer = new Array(); //getComponentMap() populates this for use in saving
var hpComponent_callbacks = new Array();


//preloading images
var hpImages = new Array("hp-arrow-right-button.gif", "hp-arrow-down-button.gif", "hp-delete-button.gif", 
	"hpcomp-left-top-corner.gif", "hpcomp-top-bg.gif", "hpcomp-right-top-corner.gif", "hpcomp-left-bg.gif",
	"hpcomp-left-btm-corner.gif", "hpcomp-btm-bg.gif", "hpcomp-right-btm-corner.gif", "hpcomp-right-bg.gif",
	"hpcomp-handle-bg-B3DCEA.gif", "hpcomp-handle-bg-A3C7EC.gif", "hpcomp-handle-bg-D1CAB9.gif", 
	"hpcomp-handle-bg-BBD1B9.gif", "hpcomp-handle-bg-B7BECF.gif", "hpcomp-handle-bg-DBAFB9.gif", "hpcomp-handle-bg-AAAAAA.gif",
	"icons/icon-oh.gif", "icons/icon-rss.gif", "loading-hp.gif");
if(document.images)
{
	for(var i=0; i<hpImages.length; i++)
	{
		eval("var pic" + i + " = hp_preload_image('" + HP_IMG_PATH + hpImages[i] + "');");
	}
}

function hp_preload_image(path)
{
	var I = new Image();
	I.src = path;
	return I;
}

//this collapses/shows the component lists grouped by type
function switchTypeView(id)
{
	var childObj = $("cTypeChildDiv" + id);
	var isExpanded 	= childObj.style.display == '' ? true : false;

	var img = $("cTypeImg" + id);
	if(img)
	{
		img.src = HP_IMG_PATH + "hp-arrow-" + (isExpanded ? "right" : "down") + "-button.gif";
	}

	childObj.style.display = isExpanded ? 'none' : '';
}

//this collapses/shows the components
function switchComponentView(id)
{		
	var componentObj = $("componentContent" + id);			
	var isExpanded 	= componentObj.style.display == 'block' ? true : false;

	var img = $("compArrowImg" + id);
	if(img)
	{
		img.src = HP_IMG_PATH + "hp-arrow-" + (isExpanded ? "right" : "down") + "-button.gif";			
	}

	componentObj.style.display = isExpanded ? 'none' : 'block';
	
	
	//save expansion status for this component
	hpComponent_settings[id]['fExpand'] = isExpanded ? 0 : 1;
	saveCustomization();
}


/*******************************************************************************************
** page building functions
********************************************************************************************/

function buildPage()
{
	//grabbing column order from cookie
	var tmp =  unescape(readCookie("hpColMap"));
	cookieColMap = _unserializeArray(tmp);	

	//loading column order into array or positions
	var colOrder = new Array(hpNumColumns);
	for(var col=0; col<hpNumColumns; col++) colOrder[col] = new Array();
	for(key in cookieColMap)
	{
		//only dealing w/ data (i.e. skipping methods)
		if(typeof(cookieColMap[key]) == "function" || typeof(cookieColMap[key]) == "object") continue;
		
		var pos = key.split("_");
		var col = pos[0];
		var row = pos[1];
		temp = cookieColMap[key];
		colOrder[col][row] = temp;
	}

	//looping through colOrder to add component frames
	var jsId = 1;
	for(var col=0; col<colOrder.length; col++)
	{
		if(colOrder[col] == "empty") continue;	
		var curColumn = $('col' + col);
		curColumn.innerHTML = "";
		
		for(var row=0; row<colOrder[col].length; row++)
		{
			if(colOrder[col][row] == "empty") continue;
			var settings = expandSettings(hpSettings[col][row]);
			hpComponent_settings[jsId] = settings;
			var frameColor = typeof(settings['fColor']) != "undefined" ? settings['fColor'] : "";
			var fExpand = typeof(settings['fExpand']) != "undefined" ? settings['fExpand'] : "";
			
			curColumn.innerHTML += getComponentFrame(jsId, frameColor, fExpand);
			jsId++;
		}
		Sortable.create(curColumn, hpMoveParams);
	}

	var rpcclient = new xmlrpc_client('xmlremote', WEB_ADDRESS);
	//rpcclient.debug = true;  
	
	rpcclient.addParam(colOrder);
	rpcclient.addParam(hpSettings);
	rpcclient.call('homepage.load_components', installComponents);
}


function getComponentFrame(js_id, frameColor, fExpand)
{
	//frameColor = frameColor && frameColor.length==7 ? frameColor.substr(1) : frameColors[0];
	fExpand = parseInt(fExpand) == 0 ? false : true;

	if(frameColor[0] === '#')
	{
		// Map color hex vals to names
		for(i=0; i < frameColors.length; i++)
		{
			if(frameColor == frameColor.substr(1))
			{
				frameColor = colorNames[i];
				break;
			}
		}
	}
	
	var colorPicker = "Color: " 
				+ "<input type=\"hidden\" name=\"fColor\" id=\"c_color" + js_id + "\" value=\"" + frameColor + "\">";

	for(i=0; i < frameColors.length; i++)
	//foreach($this->colors as $color_code => $color )
	{
		colorPicker += "<span class=\"colorBox\" id=\"c" + js_id + "_" + i + "\" " +
					"onmouseover=\"setcolor('" + colorNames[i] + "', " + js_id + ");\" " +
					"onmouseout=\"setcolor('', " + js_id + ");\" " +
					"style=\"border:" + (frameColor == frameColors[i] ? "2px solid red" : "1px solid #AAAAAA") + "; background-color:#" + frameColors[i] + "; cursor:pointer;\" " +
					"onclick=\"updateColor(this, '" + colorNames[i] + "', " + js_id + ")\">&nbsp;&nbsp;</span>\n";
	}

	var retVal = "<div id=\"component_" + js_id + "\" class=\"content_section2 content_section2_sortable clearfix\">\n"
		+ "<b class=\"spiffy\">\n"
		+ "<b class=\"spiffy1\"></b>\n"
		+ "<b class=\"spiffy2\"></b>\n"
		+ "<b class=\"spiffy3\"></b>\n"
		+ "<b class=\"spiffy4\"><b></b></b>\n"
		+ "<b class=\"spiffy5\"><b></b></b></b>\n"
		+ "<div class=\"spiffyfg clearfix\">\n"
		+ "<h1 id=\"componentFrame" + js_id + "\" class=\"componentFrame clearfix\"><span class=\"componentTitle clearfix\" id=\"componentTitle" + js_id + "\">&nbsp;&nbsp;</span>\n"
		+ "<div class=\"content_buttons\">\n"
		+ "	<b id=\"editbutton_" + js_id + "\" class=\"button editbutton\" onclick=\"editComponent(" + js_id + ")\">cancel</b>\n"
		+ "	<img id=\"compArrowImg" + js_id + "\" src=\"" + HP_IMG_PATH + "hp-arrow-down-button.gif\" border=\"0\" alt=\"&gt;\" title=\"Collapse/Show\" class=\"button\" style=\"margin:2px 0px 0px 3px\" onClick=\"switchComponentView(" + js_id + ")\">\n"
		+ " <b title=\"Remove\" class=\"button\" style=\"margin:3px 3px 6px 3px;\" onClick=\"removeComponent(" + js_id + ")\">X</b>"
		+ "</div>\n"
		+ "</h1>\n"
		+ "<div class=\"innerBox componentContent clearfix\">\n"
		+ "<div id=\"componentEditBox" + js_id + "\" class=\"component_options\" style=\"display: block;\">\n"
		+ "<form id=\"editForm" + js_id + "\">\n"
		+ colorPicker
		+ "<div id=\"componentEditBox_replace" + js_id + "\"></div>\n"
		+ "</form>\n"
		+ "<div style=\"margin: 0 0 0 auto; width: 5em;\"><input type=\"submit\" name=\"action\" value=\"Save\" onclick=\"saveEditing(" + js_id + ")\"/></div>"
		+ "</div>\n"
		+ "<div id=\"componentContent" + js_id + "\" class=\"inner_content\"><div style=\"text-align:center; padding:30px\"><img src=\"" + HP_IMG_PATH + "loading-hp-small.gif\" border=\"0\" alt=\"Loading...\"></div></div>\n"
		+ "</div>\n"
		+ "</div>\n"
		+ "<b class=\"spiffy\">\n"
		+ "<b class=\"spiffy5\"></b>\n"
		+ "<b class=\"spiffy4\"></b>\n"
		+ "<b class=\"spiffy3\"></b>\n"
		+ "<b class=\"spiffy2\"><b></b></b>\n"
		+ "<b class=\"spiffy6\"><b></b></b></b>\n"
		+ "</div>";

	
return retVal;	
}


function installComponents(ret)
{
	for(var i=0; i<ret.length; i+=9)
	{
		var id=parseInt(ret[i]), js_id=parseInt(ret[i+1]), content=ret[i+2], col=ret[i+3], row=ret[i+4], init_func=ret[i+5],
			title=ret[i+6], form_options=ret[i+7], icon=ret[i+8];
		
		hpCID[js_id] = id;
		
		updateComponentData(js_id, icon, title, content, form_options, init_func);	
	}
}


function updateComponentData(js_id, icon, title, content, form_options, init_func)
{
	js_id = parseInt(js_id);		
	
	var cTitle = $('componentTitle' + js_id);
	var cFrame = $('componentFrame' + js_id);
	var cForm = $('componentEditBox_replace' + js_id);
	var cContent = $('componentContent' + js_id);
	
	if(title.length > 35)
	{
		cTitle.addClassName('multiline');
		cFrame.addClassName('multiline');
	}
	cTitle.innerHTML = title;
	cForm.innerHTML = form_options;
	cContent.innerHTML = content;

	if(init_func != 'none' && typeof(init_func) != "undefined")
	{
		eval(init_func + "(" + js_id + ")");		
	}
}


function expandSettings(settingsStr)
{
	var retSettings = new Array();
	var settings = settingsStr.split(";");
	for(var i=0, tmp; i<settings.length; i++)
	{
		tmp = settings[i].split('=');
		retSettings[ tmp[0] ] = tmp[1];
	}
	return retSettings;
}


function saveMapToCookie()
{
	//building cookie map
	var colMapStr = "";
	
	//building hpColData
	var cMap = getComponentMap();
	for(var col=0, isFirst=true; col<cMap.length; col++)
	{	
		len = cMap[col].length;
		for(var row=0; row<len; row++,isFirst=false)
		{
			var key = col + "_" + row;
			colMapStr += (isFirst ? "" : "|") + key + ":" + cMap[col][row];
		}
	}
	
	createCookie('hpColMap', colMapStr, 1);
}	


function getComponentMap()
{
	var retVal = new Array(hpNumColumns);

	//resetting settings storage array (this is a global array)
	hpSettings = new Array(hpNumColumns);

	//looping through columns to grab current map and settings for each component
	for(var col=0, tmp = Array(), serialData; col<hpNumColumns; col++)
	{
		colElement = $('col'+col);
		if(colElement == null)
		{
			retVal[col] = new Array();
			hpSettings[col] = new Array();
			continue;
		}
		
		var elements = colElement.getElementsByClassName('content_section2');
		if(elements.length > 0)
		{
			retVal[col] = new Array();
		}
		else
		{
			//initializing column to "empty" (so Array.toXMLRPC() doesn't error on empty array)
			retVal[col] = new Array("empty");
		}
		
		hpSettings[col] = new Array();
		for( var index = 0, pos = 0; index < elements.length; index++, pos++)
		{
			js_id = elements[index].id;
			js_id = js_id.substr(js_id.indexOf('_')+1);

			if(hpCID[ js_id ] != "removed")
			{
				var isFirst = true;
				
				hpSettings[col][pos] = "";
				if(typeof(hpComponent_settings[js_id]) != "undefined")
				{
					for(key in hpComponent_settings[js_id])
					{
						if(typeof(hpComponent_settings[js_id][key]) != "object" && typeof(hpComponent_settings[js_id][key]) != "function")
						{
							hpSettings[col][pos] += (isFirst ? "" : ";") + key + "=" + hpComponent_settings[js_id][key];
							isFirst = false;
						}
					}
				}
				retVal[col][pos] = hpCID[ js_id ];
			}
		}
	}

	return retVal;
}


function getShortestColumn()
{
	var map = getComponentMap(), sCol;
	for(var i=0, hasCol=false, curLen, sLen=0; i<hpNumColumns; i++)
	{
		curLen = 0;
		for(var j=0; j<map[i].length; j++)
		{
			if(map[i][j] != "removed") curLen++;
		}
			
		if(!hasCol || curLen < sLen)
		{
			hasCol = true;
			sLen = curLen;
			sCol = i;
		}
	}	
	return sCol;
}


function updateGlobalColor(handleToUpdate, color)
{
	$('newGlobalColor').value = color;
	for(i=0; i<7; i++)
	{
		$('global_c_' + i).style.border = '1px solid #AAAAAA';
	}	
	
	$(handleToUpdate).style.border = '2px solid red';
}


function updateColor(handleToUpdate, color, js_id)
{
	$$("form#editForm" + js_id + " span.colorBox").each(function(element,i)
	{
		element.style.border = '1px solid #AAAAAA';		
	});

	handleToUpdate.style.border = '2px solid red';
	$('c_color'+js_id).value = color;
	
	setcolor(color, js_id);
}


function setcolor(color, js_id)
{
	var elem_l = $$("#component_" + js_id + " h1").first();
	var elem_r = $$("#component_" + js_id + " h1 span").first();
	
	if(color == '')
	{
		color = $('c_color'+js_id).value;
	}
	
	// remove old colors
	for(i=0; i<colorNames.length; i++)
	{
		elem_l.removeClassName(colorNames[i]);
		elem_r.removeClassName(colorNames[i]);
	}
	
	elem_l.addClassName(color);
	elem_r.addClassName(color);
}


/*******************************************************************************************
** component removing, editing and saving
********************************************************************************************/

//this shows and hides the edit-form box for Components
function editComponent(id)
{
	var editBtn = $("editbutton_" + id);
	var editObj = $("componentEditBox" + id);
	if(editBtn.innerHTML == 'edit')
	{
		editBtn.innerHTML = 'cancel';
		editObj.style.display = 'block';
	}
	else
	{
		editBtn.innerHTML = 'edit';
		editObj.style.display = 'none';
	}
}


//this removes the given component from the page (only if js confirm is approved)
function removeComponent(id)
{
	var element = $("component_" + id);
	element.parentNode.removeChild(element);

	Droppables.reset();
	
	hpCID[id] = "removed";
	
	//adding removed component to the list of "My Added Feeds" (if applicable)
	
	
	//saving change
	saveCustomization();
}

//this save the component editing settings
function saveEditing(id)
{
	//set & globalize some JS variables based on edit-form's values
	var fm = document.forms['editForm'+id];
	if(typeof(hpComponent_settings[id]) == "undefined")
		hpComponent_settings[id] = new Array();
	for(var i = 0, value; i < fm.length; i++)
	{
		var el = fm.elements[i];
		switch (el.type)
		{
			case "checkbox":
				hpComponent_settings[id][el.name] = (el.checked ? "true" : "false");
				break;
			case "hidden":
			case "password":
			case "text":
			case "textarea":
				hpComponent_settings[id][el.name] = el.value;
				break;
			case "radio":
				if(el.checked)
					hpComponent_settings[id][el.name] = el.value;
				break;
			case "select-one":
				hpComponent_settings[id][el.name] = el.options[el.selectedIndex].value;
				break;
			case "select-multiple":
				hpComponent_settings[id][el.name] = new Array();
				var k = 0;
				for(var j = 0; j < el.options.length; j++)
				{
					if(el.options[j].selected)
						hpComponent_settings[id][el.name][k++] = el.options[j].value;
				}
				break;
		}
	}
	
	//closing edit box
	editComponent(id);
	
	//save changes
	saveCustomization();
	
	//reloading component
	var settings = compressSettings(hpComponent_settings[id]);
	reloadComponent(id, settings);
	
	return true;	
}

function compressSettings(settings)
{
	var ret = "";
	var isFirst = true;
	for(key in settings)
	{
		var val = settings[key];
		if(typeof val == "object" || typeof val == "function") continue;
		ret += (isFirst ? "" : ";") + key + "=" + val;
		isFirst =  false;
	}
	return ret;
}

function reloadComponent(js_id, settings)
{
	var rpcclient = new xmlrpc_client('xmlremote', WEB_ADDRESS);
	//rpcclient.debug = true;
	
	cid = hpCID[js_id];

	rpcclient.addParam(cid);
	rpcclient.addParam(js_id);
	rpcclient.addParam(settings);
	rpcclient.call('homepage.load_cust_component', finishReloadComponent);
}

function finishReloadComponent(value)
{
	if(typeof value['error'] != "undefined")
	{
		alert("Error: " + value['error']);
	}
	else
	{
		var id=value['id'], js_id=value['js_id'], content=value['content'], init_func=value['initFunc'],
			form_options=value['eForm'], title=value['title'], settings=value['settings'], icon=value['icon'];
			
		updateComponentData(js_id, icon, title, content, form_options, init_func);
	}
}

function saveCustomization()
{
	var rpcclient = new xmlrpc_client('xmlremote', WEB_ADDRESS);
	//rpcclient.debug = true;  
	
	rpcclient.addParam(application);
	rpcclient.addParam(hp_app_id);

	//grab current component map
	var cMap = getComponentMap();
	rpcclient.addParam(cMap);
	
	//grab component settings
	rpcclient.addParam(hpSettings);
	
	rpcclient.addParam(hpSecurityKey);
	//send to server for saving
	rpcclient.call('homepage.save_custom_set', finishSavingHp);	
}

function finishSavingHp(error)
{
	if(error != "")
	{
		alert(error);
	}
	saveMapToCookie();
}



function showCompList()
{
	var complist = $('comp_list');
	if(complist.style.display == 'none')
	{
		complist.style.display = 'block';
	}
	else
	{
		complist.style.display = 'none';
	}
}
/*******************************************************************************************
** adding components
********************************************************************************************/

function getCustComponent(cid)
{
	//adding component frame to page before doing xmlrpc call
	var js_id = hpCID.length;
	addComponentFrame(js_id);
	
	//loading content via xmlrpc
	var rpcclient = new xmlrpc_client('xmlremote', WEB_ADDRESS);
	//rpcclient.debug = true;  
	
	rpcclient.addParam(cid);
	rpcclient.addParam(js_id);
	rpcclient.call('homepage.load_cust_component', addComponent);
}

function getRssComponent(application, hp_app_id, rssPath)
{
	rssPath = rssPath.trim();
	if(rssPath.length < 6)
	{
		alert("You must enter a url in the format of http://www.website.com/rss.xml");
		return false;
	}

	//adding component frame to page before doing xmlrpc call
	var js_id = hpCID.length;
	addComponentFrame(js_id);
	
	//loading content via xmlrpc
	var rpcclient = new xmlrpc_client('xmlremote', WEB_ADDRESS);
	//rpcclient.debug = true;  
	rpcclient.addParam(application);
	rpcclient.addParam(hp_app_id);
	rpcclient.addParam(rssPath);
	rpcclient.addParam(js_id);
	rpcclient.addParam(hpSecurityKey);
	rpcclient.call('homepage.load_rss_component', addComponent);
}

function addComponentFrame(js_id)
{
	//grabbing column to add to
	var colId = 1;
	var column = $('col' + colId);

	//defaulting required settings for frame
	var fColor = "";
	var fExpand = "";
	
	//adding component frame to page
	var newComp = getComponentFrame(js_id, fColor, fExpand);
	
	new Insertion.Top(column, newComp);
	//column.innerHTML = newComp + column.innerHTML; // This will NOT work in IE... DON'T DO IT!
	
	Sortable.create(column, hpMoveParams);
}	

function addComponent(value)
{
	if(typeof value['error'] != "undefined")
	{
		alert(value['error']);
		var component = $('component_' + value['js_id']);
		component.parentNode.removeChild(component);
	}
	else
	{
		var id = parseInt(value['id']), js_id = parseInt(value['js_id']), init_func = value['initFunc'],
			form_options = value['eForm'], content = value['content'], title = value['title'],
			icon = value['icon'];		
	
		//adding rss feed to My Feeds if is new personal feed
		if(typeof value['my_feeds_option'] != "undefined")
		{
			var emptyNotice = $('myFeedsEmptyNotice');
			if(emptyNotice)
			{
				emptyNotice.style.display = 'none';
			}
			
			var ul = $('personalFeedList');
			ul.innerHTML += value['my_feeds_option'];
		}

		//updating component data in component frame
		updateComponentData(js_id, icon, title, content, form_options, init_func);
		
		//adding component id and js-id to id map
		hpCID[js_id] = id;

		//saving column order to cookie and saving customizations
		saveMapToCookie();
		saveCustomization();
	}
}


/*******************************************************************************************
** helper functions
********************************************************************************************/

//adding trim function to String object
String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); };
String.prototype.addslashes = function() {
	var s = this.replace(/\n/g, "\\n");
	s = s.replace(/\r/g, "\\r");
	s = s.replace(/\t/g, "\\t");
	s = s.replace(/["'"]/g, "\\$1");
	return s;
}

function _serializeArray(arr)
{
	var retStr = "";
	var isFirst = true;
	
	for(key in arr)
	{
		if(typeof(arr[key]) == "function" || typeof(arr[key]) == "object") continue;
		retStr += (isFirst ? "" : "|") + key + ":" + arr[key];
		isFirst = false;
	}
	
	return retStr;
}

function _unserializeArray(str)
{
	var retArr = new Array();
	if(str != null)
	{
		var varData = str.split("|");
		for(var i=0, tmpData; i<varData.length; i++)
		{
			tmpData = varData[i].split(":");
			if(tmpData.length == 2)
			{
				retArr[ tmpData[0] ] = tmpData[1];
			}
		}
	}

	return retArr;
}

function createCookie(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 eraseCookie(name)
{
	createCookie(name,"",-1);
}

function showAddFeedDiv()
{
	var form = $("rssAddForm");
	var formIsVisible = (form.style.display == '');
	form.style.display = formIsVisible ? 'none' : '';
	
	var link = $("addMyFeedLink");
	link.innerHTML = formIsVisible ? '+Add My Feed' : '-Add My Feed';
}

function search_selectTab(js_id, idx)
{
	var otherIdx = 1 - idx;
	var thisTab  = $("searchtab_"+js_id+"_"+otherIdx);
	var thisDiv  = $("searchdiv_"+js_id+"_"+otherIdx);
	var otherTab = $("searchtab_"+js_id+"_"+idx);
	var otherDiv = $("searchdiv_"+js_id+"_"+idx);
	if(thisDiv.style.display == "none")
		return;
	thisDiv.style.display = "none";
	otherDiv.style.display = "block";
	thisTab.style.backgroundColor = "#fafafa";
	thisTab.style.color = "#999";
	thisTab.style.cursor = "pointer";
	otherTab.style.backgroundColor = "#f0f0f0";
	otherTab.style.color = "black";
	otherTab.style.cursor = "default";
}
function search_validateTerms(s)
{
	if(s.value.length < 4)
	{
		alert("You must enter a search term.");
		s.focus();
		return false;
	}
	return true;
}

function open_homepage_help()
{
	var aw = new AjaxWindow('hpHelp');
  aw.title = 'Homepage Help';
  aw.width = 500;
  aw.backgroundColor = "#FFFFFF";
  aw.titleColor = "#CCE1FF";
  aw.borderColor = "#777777";
  var params = new Array('', 'homepage-help');
  aw.open('cms.getRemoteContent', params, '', null, null);
}

function showSmallHpWelcome()
{
	var smallWelcome = $("hpSmallWelcome");
	smallWelcome.style.display = '';
	
	var switcher = $("hpWelcomeSwitcher");
	switcher.src = HP_IMG_PATH + "welcome-header-down-button.gif";
}

function switchWelcomeView()
{
	var smallWelcome = $("hpSmallWelcome");
	var isExpanded = smallWelcome.style.display == 'none' ? true : false;
	if(isExpanded)
	{
		Effect.SlideUp("hpLargeWelcome");	
		window.setTimeout("showSmallHpWelcome()", 600);
	}
	else
	{
		smallWelcome.style.display = 'none';
		Effect.SlideDown("hpLargeWelcome");	
		
		var switcher = $("hpWelcomeSwitcher");
		switcher.src = HP_IMG_PATH + "welcome-header-up-button.gif";
	}
	
	updateExpansionStatus("expand_welcome_msg");
}		

function switchMyHomePageBoxView()
{
	var content = $("personalizeHpBoxContent");
	var isExpanded = content.style.display == '' ? true : false;
	if(isExpanded)
	{
		Effect.SlideUp("personalizeHpBoxContent");
	}
	else
	{
		Effect.SlideDown("personalizeHpBoxContent");
		
		//checking if welcome-bubble is showing
		var bubble = $("myHpWelcome");
		if(bubble)
		{
			bubble.style.display = 'none';
		}
	}
	var switcher = $("personalizeBoxSwitcher");
	switcher.innerHTML = "My Homepage " + (isExpanded ? "[ + ]" : "[ - ]");
	switcher.title = isExpanded ? "expand" : "collapse";
	
	updateExpansionStatus("expand_customize_box");
}

function saveMySettings()
{
	var cols = $("newNumColumns");
	var color = $("newGlobalColor");
	cols = 2; //cols.options[cols.selectedIndex].value;
	color = color.value;
	
	var alertMsg = '';
	if((cols == 3 && screen.width < 1024) || (cols == 4 && screen.width < 1280)) 
	{
		 alertMsg = "By using " + cols + " columns at your resolution " +
			"(" + screen.width + "x" + screen.height + "), " +
			"some components may not display correctly. Click OK if you want to continue.";
	}
	if(!alertMsg || (alertMsg && confirm(alertMsg)))
	{
		window.location.href = CURRENT_URL + '?newColor='+escape(color)+'&newColumns='+escape(cols);
	}
}

function cancelMySettings()
{
	switchTypeView('Settings');
}

function resetComponents()
{
	resetConfirm = "Are you sure you want to reset this page? The default set of components will " +
		"replace any modifications you have made (your My Feeds will still " +
		"be available). Click OK to continue.";
	if(confirm(resetConfirm)) window.location.href= CURRENT_URL + '?resetMySet=1';
	
}

function updateExpansionStatus(fld)
{
	var rpcclient = new xmlrpc_client('xmlremote', WEB_ADDRESS);
	//rpcclient.debug = true;  

	rpcclient.addParam(application);
	rpcclient.addParam(hp_app_id);
	rpcclient.addParam(fld);
	
	//send to server for saving
	rpcclient.call('homepage.update_expansion_status', finishUpdateExpansion);	
}	

function finishUpdateExpansion(result)
{
	if(result != '')
		alert("Result: " + result);
}

function confirmRmMyFeed(cid, elem)
{
	var del = confirm('Are you sure you want to permanently REMOVE your feed? Click OK to remove it.');
	if(del != false)
	{
		var rmCids = new Array();
		j=0;
		for(i=0; i<hpCID.length; i++)
		{
			if(hpCID[i]==cid)
			{
				rmCids[j++] = i;
			}
		}

		for(i=0;i<rmCids.length;i++)
		{
			var element = $("component_" + rmCids[i]);
			element.parentNode.removeChild(element);
			hpCID[rmCids[i]] = "removed";
		}
		Droppables.reset();
		var rpcclient = new xmlrpc_client('xmlremote', WEB_ADDRESS);
		//rpcclient.debug = true;  
	
		rpcclient.addParam(application);
		rpcclient.addParam(hp_app_id);
		rpcclient.addParam(cid);
		
		//send to server for saving
		rpcclient.call('homepage.rm_my_feed', finishRmMyFeed);	
		//ul parent
		var ul = elem.parentNode;
		while(ul.tagName!='UL')
		{
			ul = ul.parentNode;
		}
		
		var li = elem.parentNode;
		while(li.tagName!='LI')
		{
			li = li.parentNode;
		}
		ul.removeChild(li);
	}
	else
	{
		return false;
	}
}

function finishRmMyFeed(ret)
{
	if(!ret['error'])
	{
		if(ret['feedCount'] == 0)
		{
			$('myFeedsEmptyNotice').style.display='block';
		}
		saveCustomization();
	}
	
}

function loadMyHomepageBox(reqBoxId)
{
	var boxes = new Array('hpCustOhFeeds', 'hpCustFeaturedFeeds', 'hpCustMyFeeds', 
		'hpCustAddFeed', 'hpCustMySettings', 'hpCustHelp');
	for(var i=0; i<boxes.length; i++)
	{
		var box = $( boxes[i] ), li = $(boxes[i] + 'Li'), curBoxId = box.id;
		box.style.display = curBoxId == reqBoxId ? '' : 'none';
		var displayStatus = box.style.display;
		li.className = curBoxId == reqBoxId ? 'selected' : '';
	}
}

function loadMyHomepageBoxApp(reqBoxId)
{
	
	var boxes = new Array('hpCustOhFeedsApp', 'hpCustFeaturedFeedsApp', 'hpCustMyFeedsApp', 
		'hpCustAddFeedApp', 'hpCustMySettingsApp');
	for(var i=0; i<boxes.length; i++)
	{
		var box = $( boxes[i] ), li = $(boxes[i] + 'Li'), curBoxId = box.id;
		box.style.display = curBoxId == reqBoxId ? '' : 'none';
		var displayStatus = box.style.display;
		li.className = curBoxId == reqBoxId ? 'selected' : '';
	}
}