/* http://www.themonitor.com/common/tools/load.php?js=common_poll,common_nav,common_tabBox,common_contentslider,common_apticker,common_sitelife-json,common_sitelife-prototype,common_sitelife-pork-iframe,common_sitelife-requestbatch,common_sitelife-requesttypes,common_sitelife,common_sitelife-registration */
	function loadPoll(pollid,sitecode)
	{
			var pollwrapper = document.getElementById('pollwrapper');
			var scriptname = "/onsetfeature/pollcap.php?station=" + sitecode;
			getPollResult(pollid,sitecode,pollwrapper,scriptname);
	}
	
	function loadArticlePoll(pollid,sitecode)
	{
		var pollwrapper = document.getElementById('articlepoll_wrapper');
		var scriptname = "/onsetfeature/pollcap.php?pollid=" + pollid;
		getPollResult(pollid,sitecode,pollwrapper,scriptname);
	}
	
	function getPollResult(pollid,sitecode,pollwrapper,scriptname) {
		
		try
		{
			var cookie_value = GetCookie('poll');
		}
		catch(e)
		{}
		if(pollid && cookie_value)
		{
			if(pollwrapper != null) 
				{
					var voted_list_array = cookie_value.split('~');
					var thisPollID = pollid;
					var xmlHttp; 
					for(x=0;x<voted_list_array.length;x++)
					{
						if(voted_list_array[x] == thisPollID)
						{
							scriptname += "&action=results";
							break;
						}
					}
					try {
						xmlHttp = new XMLHttpRequest();
					}
					catch(e) {
						try {
							xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
						}
						catch (e) {
							try {
								xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
							}
							catch (e) {
								alert("not supported");
							} 
						}
					}
					xmlHttp.onreadystatechange=function() {
						if(xmlHttp.readyState == 4) {
							//alert(xmlHttp.responseText);
							pollwrapper.innerHTML = xmlHttp.responseText;
						}
					}
					xmlHttp.open("GET",scriptname, true);
					xmlHttp.send(null);
				}
		}
	}
	function navLoad( id )
{
	if( typeof(id) == 'undefined' )
		id = 'fi_nav_ul';
		
	var nav = document.getElementById(id);
	
	var children = nav.getElementsByTagName("LI");
	for( var i = 0; i < children.length; i++ )
	{
		for( var j = 0; j < children[i].childNodes.length; j++ )
		{
			if( children[i].childNodes[j].nodeName == "UL" && children[i].childNodes[j].className.indexOf('sub') > -1 )
			{
				children[i].setAttribute('ulPos', j);
				
				if( children[i].parentNode == nav )
					children[i].childNodes[j].setAttribute('drop', 'down');
				else
					children[i].className += " hasSub";
				break;
			}
		}
		
		children[i].onmouseover = function() {
			
			if( this.className.indexOf(" over" ) == -1 )
				this.className += " over";
			
			if( this.getAttribute('ulPos') )
				showAndPosition(this);
		}
		
		children[i].onmouseout = function() {
			this.className = this.className == "over" ? "" :  this.className.replace(" over", "");
				
			if( this.getAttribute('ulPos') )
				this.childNodes[this.getAttribute('ulPos')].style.visibility = 'hidden';
		}
	}
}

function showAndPosition( li )
{
	var subMenu = li.childNodes[li.getAttribute('ulPos')];
	
	if( subMenu.getAttribute('noPos') )
	{
		subMenu.style.visibility = 'visible';
	}
	else
	{
		if( subMenu.getAttribute('drop') == "down" )
		{
			subMenu.style.left = '0px';
			subMenu.style.top = li.offsetHeight + 'px';
			if(subMenu.offsetWidth < li.offsetWidth )
				subMenu.style.width = li.offsetWidth + 'px';
		}
		else
		{
			subMenu.style.left = 'auto';
			subMenu.style.right = (-subMenu.offsetWidth) + 'px';
			subMenu.style.top = '3px';
		}
		
		subMenu.setAttribute('noPos', true);
	}
}function showTab( tab, tabContentID )
{
	// figure out the id of the tab box being worked with
	// and the number of the tab that was clicked on
	var tboxID = getTabBoxID(tab);
	var tabNum = getTabNum(tab);
	
	// get the tab box and read the values on it
	var tabBox = getEl(tboxID);
	var lastTabNum = tabBox.getAttribute('lastTab');
	var baseName = tabBox.getAttribute('baseName');
	var tabSelected = baseName + "Selected";
	
	// get the last tab and it's content container
	var lastTab = getEl(tboxID+"_"+lastTabNum+"_tab");
	var lastTabContent = getEl(tboxID+"_"+lastTabNum+"_content");
	
	// get the current tab and it's content container.
	var currTab = getEl(tboxID+"_"+tabNum+"_tab");
	var currTabContent = getEl(tboxID+"_"+tabNum+"_content");
	
	// unselect the last tab and hide it's content container
	lastTab.className = lastTab.className.replace(tabSelected, "");
	lastTabContent.style.display = 'none';
	
	// select the current tab and show it's content container
	currTab.className = currTab.className + " " + tabSelected;
	currTabContent.style.display = '';
	
	// set the last tab to the current tab
	tabBox.setAttribute('lastTab', tabNum);
}

function getTabBoxID(tab)
{
	var tabID = tab.id;
	var first = tabID.indexOf("_");
	var second = tabID.indexOf("_", (first+1));
	return tabID.substr(0, first);
}

function getTabNum(tab)
{
	var tabID = tab.id;
	var first = tabID.indexOf("_");
	var second = tabID.indexOf("_", (first+1));
	return tabID.substr((first+1), (second-first-1));
}

function highlightTab(tab, highlight)
{
	var tboxID = getTabBoxID(tab);
	var tabBox = getEl(tboxID);
	var baseName = tabBox.getAttribute('baseName');
	var style = baseName+"Highlighted";
	
	if (highlight == true)
		tab.className += " "+style;
	else
		tab.className = tab.className.replace(style, "");
}

function getEl( id )
{
	return document.getElementById(id);
}//** Featured Content Slider script- (c) Dynamic Drive DHTML code library (http://www.dynamicdrive.com)
//** Last updated: Feb 28th- 07- Added ability to customize pagination links' text
//** Updated 20090429 - Only display nav if slideCount (alldivs) > 1

////Ajax related settings
var csbustcachevar=0 //bust potential caching of external pages after initial Ajax request? (1=yes, 0=no)
var csloadstatustext="<img src='http://common.onset.freedom.com/images/loading.gif' /> Requesting content..." //HTML to indicate Ajax page is being fetched
var csexternalfiles=[] //External .css or .js files to load to style the external content(s), if any. Separate multiple files with comma ie: ["cat.css", dog.js"]

////NO NEED TO EDIT BELOW////////////////////////
var enablepersist=false
var slidernodes=new Object() //Object array to store references to each content slider's DIV containers (<div class="contentdiv">)
var csloadedobjects="" //Variable to store file names of .js/.css files already loaded (if Ajax is used)

function ContentSlider(sliderid, autorun, customPaginateText, customNextText, cycles){
	var prevText
	var slider=document.getElementById(sliderid)
	if (typeof customPaginateText!="undefined" && customPaginateText!="") //Custom array of pagination links text defined?
		slider.paginateText=customPaginateText
	if (typeof customNextText!="undefined" && customNextText!="") //Custom HTML for "Next" link defined?
		slider.nextText=customNextText
	slidernodes[sliderid]=[] //Array to store references to this content slider's DIV containers (<div class="contentdiv">)
	ContentSlider.loadobjects(csexternalfiles) //Load external .js and .css files, if any
	var alldivs=slider.getElementsByTagName("div")
	for (var i=0; i<alldivs.length; i++){
		if (alldivs[i].className=="contentdiv"){
			slidernodes[sliderid].push(alldivs[i]) //add this DIV reference to array
			if (typeof alldivs[i].getAttribute("rel")=="string") //If get this DIV's content via Ajax (rel attr contains path to external page)
				ContentSlider.ajaxpage(alldivs[i].getAttribute("rel"), alldivs[i])
		}
	}
	ContentSlider.buildpagination(sliderid)
	var loadfirstcontent=true
	if (enablepersist && getCookie(sliderid)!=""){ //if enablepersist is true and cookie contains corresponding value for slider
		var cookieval=getCookie(sliderid).split(":") //process cookie value ([sliderid, int_pagenumber (div content to jump to)]
		if (document.getElementById(cookieval[0])!=null && typeof slidernodes[sliderid][cookieval[1]]!="undefined"){ //check cookie value for validity
			ContentSlider.turnpage(cookieval[0], parseInt(cookieval[1])) //restore content slider's last shown DIV
			loadfirstcontent=false
		}
	}
	if (loadfirstcontent==true) //if enablepersist is false, or cookie value doesn't contain valid value for some reason (ie: user modified the structure of the HTML)
		ContentSlider.turnpage(sliderid, 0) //Display first DIV within slider
	if (typeof autorun=="number" && autorun>0 && alldivs.length>1) //if autorun parameter (int_miliseconds) is defined, fire auto run sequence
		window[sliderid+"timer"]=setTimeout(function(){ContentSlider.autoturnpage(sliderid, autorun, cycles || 0)}, autorun)
	if (alldivs.length<2) {
		document.getElementById('paginate-slider1').innerHTML='&#160;';
	}
}

ContentSlider.buildpagination=function(sliderid){

	var slider=document.getElementById(sliderid)
	var paginatediv=document.getElementById("paginate-"+sliderid) //reference corresponding pagination DIV for slider
	var pcontent=""
	
	if(typeof (imgInfo)!="undefined")
		{
		pcontent+='<a href="#" style="font-weight: bold;" onclick=\"ContentSlider.turnpage(\''+sliderid+'\', parseInt(this.getAttribute(\'rel\'))); return false\">'+(slider.prevText || "<img src=\"http://common.onset.freedom.com/images/arrow_prev.gif\">")+'</a>'
		pcontent+= '<span id="cur_page" style="margin:0px 8px;">' + 1 + ' of '+ imgInfo.length +' </span>'
		//for (var i=0; i<slidernodes[sliderid].length; i++) //For each DIV within slider, generate a pagination link
		//	pcontent+='<a href="#" onclick=\"ContentSlider.turnpage(\''+sliderid+'\', '+i+'); return false\">'+(slider.paginateText? slider.paginateText[i] : i+1)+'</a> '
		pcontent+='<a href="#" style="font-weight: bold;" onclick=\"ContentSlider.turnpage(\''+sliderid+'\', parseInt(this.getAttribute(\'rel\'))); return false\">'+(slider.nextText || "<img src=\"http://common.onset.freedom.com/images/arrow_next.gif\">")+'</a>'
	} else {
		for (var i=0; i<slidernodes[sliderid].length; i++) //For each DIV within slider, generate a pagination link
			pcontent+='<a href="#" onclick=\"ContentSlider.turnpage(\''+sliderid+'\', '+i+'); return false\">'+(slider.paginateText? slider.paginateText[i] : i+1)+'</a> '
		pcontent+='<a href="#" style="font-weight: bold;" onclick=\"ContentSlider.turnpage(\''+sliderid+'\', parseInt(this.getAttribute(\'rel\'))); return false\">'+(slider.nextText || "Next")+'</a>'
		}

	paginatediv.innerHTML=pcontent
	paginatediv.onclick=function(){ //cancel auto run sequence (if defined) when user clicks on pagination DIV
	if (typeof window[sliderid+"timer"]!="undefined")
		clearTimeout(window[sliderid+"timer"])
		}
}

ContentSlider.turnpage=function(sliderid, thepage){
	
	var paginatelinks=document.getElementById("paginate-"+sliderid).getElementsByTagName("a") //gather pagination links
	var nFrames;
	if(typeof (imgInfo)!="undefined")
		{
		for (var i=0; i<imgInfo.length; i++){ //For each DIV within slider
			//paginatelinks[i].className="" //empty corresponding pagination link's class name
			slidernodes[sliderid][i].style.display="none" //hide DIV
			}
		nFrames=imgInfo.length;
		document.getElementById("cur_page").innerHTML = '' + (thepage + 1) + ' of '+ nFrames +''
	} else {
		for (var i=0; i<slidernodes[sliderid].length; i++){ //For each DIV within slider
			paginatelinks[i].className="" //empty corresponding pagination link's class name
			slidernodes[sliderid][i].style.display="none" //hide DIV
			}
		nFrames=slidernodes[sliderid].length;
		}
	//paginatelinks[thepage].className="selected" //for selected DIV, set corresponding pagination link's class name
	try{
	slidernodes[sliderid][thepage].style.display="block" //show selected DIV

	}catch(err){}
	// Set "Prev" link
	paginatelinks[0].setAttribute("rel", theprevpage=(thepage>0)? thepage-1 : (nFrames-1))
	//Set "Next" pagination link's (last link within pagination DIV) "rel" attribute to the next DIV number to show
	paginatelinks[paginatelinks.length-1].setAttribute("rel", thenextpage=(thepage<(nFrames-1))? thepage+1 : 0)
	if (enablepersist)
		setCookie(sliderid, sliderid+":"+thepage)
	
}

ContentSlider.autoturnpage=function(sliderid, autorunperiod, cycles){
	var paginatelinks=document.getElementById("paginate-"+sliderid).getElementsByTagName("a") //Get pagination links
	var nextpagenumber=parseInt(paginatelinks[paginatelinks.length-1].getAttribute("rel")) //Get page number of next DIV to show
	ContentSlider.turnpage(sliderid, nextpagenumber) //Show that DIV
	if (cycles>0){
	var slider=document.getElementById(sliderid)
	if (nextpagenumber==0)
	slider.cyclecount=(typeof slider.cyclecount!="undefined")? slider.cyclecount+1 : 1
	if (slider.cyclecount && slider.cyclecount==cycles)
	return
	}
	window[sliderid+"timer"]=setTimeout(function(){ContentSlider.autoturnpage(sliderid, autorunperiod, cycles)}, autorunperiod)
}

function getCookie(Name){ 
	var re=new RegExp(Name+"=[^;]+", "i"); //construct RE to search for target name/value pair
	if (document.cookie.match(re)) //if cookie found
		return document.cookie.match(re)[0].split("=")[1] //return its value
	return ""
}

function setCookie(name, value){
	document.cookie = name+"="+value
}

////////////////Ajax Related functions //////////////////////////////////

ContentSlider.ajaxpage=function(url, thediv){
	var page_request = false
	var bustcacheparameter=""
	if (window.XMLHttpRequest) // if Mozilla, Safari etc
		page_request = new XMLHttpRequest()
	else if (window.ActiveXObject){ // if IE
		try {
		page_request = new ActiveXObject("Msxml2.XMLHTTP")
		} 
		catch (e){
		try{
		page_request = new ActiveXObject("Microsoft.XMLHTTP")
		}
		catch (e){}
		}
	}
	else
		return false
	thediv.innerHTML=csloadstatustext
	page_request.onreadystatechange=function(){
		ContentSlider.loadpage(page_request, thediv)
	}
	if (csbustcachevar) //if bust caching of external page
		bustcacheparameter=(url.indexOf("?")!=-1)? "&"+new Date().getTime() : "?"+new Date().getTime()
	page_request.open('GET', url+bustcacheparameter, true)
	page_request.send(null)
}

ContentSlider.loadpage=function(page_request, thediv){
	if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1))
		thediv.innerHTML=page_request.responseText
}

ContentSlider.loadobjects=function(externalfiles){ //function to load external .js and .css files. Parameter accepts a list of external files to load (array)
	for (var i=0; i<externalfiles.length; i++){
		var file=externalfiles[i]
		var fileref=""
		if (csloadedobjects.indexOf(file)==-1){ //Check to see if this object has not already been added to page before proceeding
			if (file.indexOf(".js")!=-1){ //If object is a js file
				fileref=document.createElement('script')
				fileref.setAttribute("type","text/javascript");
				fileref.setAttribute("src", file);
			}
			else if (file.indexOf(".css")!=-1){ //If object is a css file
				fileref=document.createElement("link")
				fileref.setAttribute("rel", "stylesheet");
				fileref.setAttribute("type", "text/css");
				fileref.setAttribute("href", file);
			}
		}
		if (fileref!=""){
			document.getElementsByTagName("head").item(0).appendChild(fileref)
			csloadedobjects+=file+" " //Remember this object as being already added to page
		}
	}
}


// Freedom-specific modifications
var imgCount,htmlOut,imgsSlider,imgMaxWidth,imgMaxHeight,imgMaxTotalHeight;
imgCount=0;
function imageSlide(file,cutline,credit,picturealt,width,height,storyid,storydb)
{
  this.file=file;
  this.cutline=cutline;
  this.credit=credit;
  this.picturealt=picturealt;
  this.width=width;
  this.height=height;
	if (storyid != "")
		this.storyid=storyid;
	if (storydb != "")
		this.storydb=storydb;
}

function writeImageSlider () {
	htmlOut = ''
	htmlOut += '<div id="slider1" class="contentslide1" style="width:230px;">\n';
	for (i=0;i<imgCount;i++) {
		var myWidth = (imageSlide[i].width < 230)?'width="'+imageSlide[i].width+'"':'width=230';
		htmlOut += '<div class="contentdiv">\n';
		htmlOut += '<div class="image_mask" >'	
		htmlOut += '<div class="image_box"><div>'
		
		//if (imageSlide[i].width < 230)
			htmlOut += '<div align="center">';
			
		if (parseInt(imageSlide[i].storyid) > 0) {
			htmlOut += '  <a href="/sections/article/gallery/?pic='+(i+1)+'&amp;id='+imageSlide[i].storyid+'&amp;db='+imageSlide[i].storydb+'">';
		} else {
			htmlOut += '  <a href="'+imageSlide[i].file+'" target="_blank">';			
		}
		htmlOut += '<img src="'+imageSlide[i].file+'" '+myWidth+' style="max-width:230px;" alt="'+imageSlide[i].picturealt+'" border="0" />';
		htmlOut += '</a>';
		//if (imageSlide[i].width < 230)
			htmlOut += '</div>';
	
		htmlOut += '</div></div>' // end image_box and div
		
		htmlOut += '<div class="image_info_box"><div class="enlarge opaque">'
		htmlOut += '<a href="/sections/article/gallery/?pic='+(i+1)+'&amp;id='+imageSlide[i].storyid+'&amp;db='+imageSlide[i].storydb+'">enlarge</a>';
		htmlOut += '</div></div>' // end image_info_box, enlarge
		htmlOut += '</div>' // end image_mask
		
		if ('"'+imageSlide[i].credit+'"' != "") {
			htmlOut += '  <div class="credit">\n';
			htmlOut +=   ' '+imageSlide[i].credit+'&#160;\n';
			htmlOut += '  </div>\n';
		}			 
		if (imageSlide[i].cutline!='') {
			htmlOut += '  <div class="contentdivtxt" style="width:230px;overflow:auto;">\n';
			htmlOut +=     imageSlide[i].cutline+'&#160;';
			htmlOut += '  </div>\n';
		}
		/*
		if (parseInt(imageSlide[i].storyid) > 0) {
			htmlOut += '<br /><a href="/sections/article/gallery/?pic='+(i+1)+'&amp;id='+imageSlide[i].storyid+'&amp;db='+imageSlide[i].storydb+'" style="color:#036;font-size:9pt;font-weight:normal;">Click to Enlarge</a>\n';
		}
		*/
		htmlOut += '</div>\n';
	}
	htmlOut += '<div class="thumbnailpagination" id="paginate-slider1"></div>';
	htmlOut += '</div>';
	
	return htmlOut;
}

var imgCount,htmlOut,imgsSlider,imgMaxWidth,imgMaxHeight;
imgCount=0;

if( typeof(imgInfo) != 'undefined' )
{
	for(x = 0; x < imgInfo.length; x++)
	{
		if (imgInfo[x][0] != "" && imgInfo[x][0] != "medium/" && imgInfo[x][0] != "http://images.onset.freedom.com/"+imgInfo[x][7]+"/") 
		{
			if (imgInfo[x][6] != "")
				imgStoryId = imgInfo[x][6];
			if (imgInfo[x][7] != "")
				imgStoryDb = imgInfo[x][7];
			
			imageSlide[x] = new imageSlide(imagePrefix + imgInfo[x][0],imgInfo[x][1],imgInfo[x][2],imgInfo[x][3],imgInfo[x][4],imgInfo[x][5],imgStoryId,imgStoryDb);
			imgMaxWidth = imgInfo[x][4];
			imgMaxHeight = imgInfo[x][5];
			
			imgCount++;
			imgMaxTotalHeight = parseInt(imgMaxHeight)
			imgMaxTotalHeight += 100 ;
		}
	}
	
	/*
	//if (imgInfo[0][0] != "") 
	if (imgInfo[0][0] != "" && imgInfo[0][0] != "medium/" && imgInfo[0][0] != "http://images.onset.freedom.com/"+imgInfo[0][7]+"/") 
	{
	  if (imgInfo[0][6] != "")
	  	imgStoryId = imgInfo[0][6];
	  if (imgInfo[0][7] != "")
	  	imgStoryDb = imgInfo[0][7];

	  imageSlide[0] = new imageSlide(imagePrefix + imgInfo[0][0],imgInfo[0][1],imgInfo[0][2],imgInfo[0][3],imgInfo[0][4],imgInfo[0][5],imgStoryId,imgStoryDb);
	  imgMaxWidth = imgInfo[0][4];
	  imgMaxHeight = imgInfo[0][5];
	  
	  imgCount++;
		imgMaxTotalHeight = parseInt(imgMaxHeight)
		//if (imageSlide[0].cutline != '') {
			imgMaxTotalHeight += 100 ;
		//}
	}
	//if (imgInfo[1][0] != "")
	if (imgInfo[1][0] != "" && imgInfo[1][0] != "medium/" && imgInfo[1][0] != "http://images.onset.freedom.com/"+imgInfo[0][7]+"/")
	{
	  imageSlide[1] = new imageSlide(imagePrefix + imgInfo[1][0],imgInfo[1][1],imgInfo[1][2],imgInfo[1][3],imgInfo[1][4],imgInfo[1][5],imgStoryId,imgStoryDb);
	  if (imgMaxWidth < parseInt(imgInfo[1][4]))
	    imgMaxWidth=parseInt(imgInfo[1][4]);
	  if (imgMaxHeight < parseInt(imgInfo[1][5]))
	    imgMaxHeight=parseInt(imgInfo[1][5]);

			imgMaxTotalHeight = parseInt(imgMaxHeight)
			//if (imageSlide[1].cutline != '') {
				imgMaxTotalHeight += 100 ;
			//}
	  imgCount++;
	}
	//if (imgInfo[2][0] != "")
	if (imgInfo[2][0] != "" && imgInfo[2][0] != "medium/" && imgInfo[2][0] != "http://images.onset.freedom.com/"+imgInfo[0][7]+"/")
	{
	  imageSlide[2] = new imageSlide(imagePrefix + imgInfo[2][0],imgInfo[2][1],imgInfo[2][2],imgInfo[2][3],imgInfo[2][4],imgInfo[2][5],imgStoryId,imgStoryDb);
	  if (imgMaxWidth < parseInt(imgInfo[2][4]))
	    imgMaxWidth=parseInt(imgInfo[2][4]);
	  if (imgMaxHeight < parseInt(imgInfo[2][5]))
	    imgMaxHeight=parseInt(imgInfo[2][5]);
			imgMaxTotalHeight = parseInt(imgMaxHeight)
			//if (imageSlide[2].cutline != '') {
				imgMaxTotalHeight += 100 ;
			//}
	  imgCount++;
	}
	*/
}

if (imgCount > 1) {
  document.getElementById(articleDivID).innerHTML = writeImageSlider();
  ContentSlider("slider1", 0, "", "", 1);

}
var Ticker = function(params) {
 
  this.articleContainer = document.getElementById(params['articleContainer']);
  this.tickerContainer = document.getElementById(params['tickerContainer']);
  if(this.articleContainer != null && this.tickerContainer != null) {
	  this.articleTimeout = (params['timeout']) ? params['timeout'] : 2500;
	  this.imagePath = (params['imagePath']) ? params['imagePath'] : 'http://common.onset.freedom.com/images/';
	  this.target = (params['target']) ? params['target'] : '_top';
	  this.tickerArticles = [];
	  this.currentArticle = 0;
	  this.totalArticles = 0;
	  this.currentOpacity = 0;
	  this.tickerFade = null;
	  this.createTicker();
  }
}

Ticker.prototype = {
  createTicker : function() {
		this.tickerArticles = this.articleContainer.getElementsByTagName('a');
		this.totalArticles = this.tickerArticles.length;
		this.tickerContainer.innerHTML = null;
		this.writeArticle(this.currentArticle);
	},
	writeArticle : function(n) {
	  this.currentArticle = n;
	  this.currentOpacity = 0;
		this.tickerContainer.innerHTML = '<span class="navigation"><a href="'+this.tickerArticles[this.getArticle(-1)]+'" onclick="ticker.writeArticle(ticker.getArticle(-1)); return false;" target="'+this.target+'" title="'+this.tickerArticles[this.getArticle(-1)].firstChild.nodeValue+'"><img src="'+this.imagePath+'smallarrow_left.gif" border="0" height="9px" /></a>'+
		                                 '<a href="'+this.tickerArticles[this.getArticle(1)].href+'" onclick="ticker.writeArticle(ticker.getArticle(1)); return false;" target="'+this.target+'" title="'+this.tickerArticles[this.getArticle(1)].firstChild.nodeValue+'"><img src="'+this.imagePath+'smallarrow_right.gif" border="0" height="9px" /></a></span>';
		this.tickerContainer.innerHTML += '<a href="'+this.tickerArticles[this.currentArticle].href+'" style="opacity: 0; filter: alpha(opacity=0);" target="'+this.target+'">'+this.tickerArticles[this.currentArticle].firstChild.nodeValue+'</a>';
		clearTimeout(this.tickerFade);
		setTimeout(this.fadeInTicker, 0);
	},
	fadeOutTicker : function() {
	  var a = ticker.tickerContainer.childNodes[1];
	  a.style.opacity = (a.style.opacity) ? a.style.opacity : 1;
	  if (ticker.currentOpacity > 0) {
		  ticker.currentOpacity -= 10;
	    ticker.setOpacity(a, ticker.currentOpacity);
		  setTimeout(ticker.fadeOutTicker, 25);
		}
		else {
			ticker.writeArticle(ticker.getArticle(1));
		}
	},
	fadeInTicker : function() {
	  var a = ticker.tickerContainer.childNodes[1];
	  if (ticker.currentOpacity < 100) {
		  ticker.currentOpacity += 10;
	    ticker.setOpacity(a, ticker.currentOpacity);
	    setTimeout(ticker.fadeInTicker, 25);
		}
		else {
			ticker.tickerFade = setTimeout(ticker.fadeOutTicker, ticker.articleTimeout);
		}
	},
	setOpacity : function(el, opacity) {
		el.style.opacity = opacity/100;
		el.style.filter = 'alpha(opacity=' + opacity + ')';
	},
	getArticle : function(direction) {
	  if ((this.currentArticle + parseInt(direction)) >= 0 && this.tickerArticles[this.currentArticle + parseInt(direction)]) {
		  return this.currentArticle+direction;
		}
		else {
		  return (direction > 0) ? 0 : this.totalArticles - 1;
		}
	}
}
/*
Copyright (c) 2005 JSON.org

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The Software shall be used for Good, not Evil.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

/*
    The global object JSON contains two methods.

    JSON.stringify(value) takes a JavaScript value and produces a JSON text.
    The value must not be cyclical.

    JSON.parse(text) takes a JSON text and produces a JavaScript value. It will
    return false if there is an error.
*/
var JSON = function () {
    var m = {
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"' : '\\"',
            '\\': '\\\\'
        },
        s = {
            'boolean': function (x) {
                return String(x);
            },
            number: function (x) {
                return isFinite(x) ? String(x) : 'null';
            },
            string: function (x) {
                if (/["\\\x00-\x1f]/.test(x)) {
                    x = x.replace(/([\x00-\x1f\\"])/g, function(a, b) {
                        var c = m[b];
                        if (c) {
                            return c;
                        }
                        c = b.charCodeAt();
                        return '\\u00' +
                            Math.floor(c / 16).toString(16) +
                            (c % 16).toString(16);
                    });
                }
                return '"' + x + '"';
            },
            object: function (x) {
                if (x) {
                    var a = [], b, f, i, l, v;
                    if (x instanceof Array) {
                        a[0] = '[';
                        l = x.length;
                        for (i = 0; i < l; i += 1) {
                            v = x[i];
                            f = s[typeof v];
                            if (f) {
                                v = f(v);
                                if (typeof v == 'string') {
                                    if (b) {
                                        a[a.length] = ',';
                                    }
                                    a[a.length] = v;
                                    b = true;
                                }
                            }
                        }
                        a[a.length] = ']';
                    } else if (x instanceof Object) {
                        a[0] = '{';
                        for (i in x) {
                            v = x[i];
                            f = s[typeof v];
                            if (f) {
                                v = f(v);
                                if (typeof v == 'string') {
                                    if (b) {
                                        a[a.length] = ',';
                                    }
                                    a.push(s.string(i), ':', v);
                                    b = true;
                                }
                            }
                        }
                        a[a.length] = '}';
                    } else {
                        return;
                    }
                    return a.join('');
                }
                return 'null';
            }
        };
    return {
        copyright: '(c)2005 JSON.org',
        license: 'http://www.crockford.com/JSON/license.html',
/*
    Stringify a JavaScript value, producing a JSON text.
*/
        stringify: function (v) {
            var f = s[typeof v];
            if (f) {
                v = f(v);
                if (typeof v == 'string') {
                    return v;
                }
            }
            return null;
        },
/*
    Parse a JSON text, producing a JavaScript value.
    It returns false if there is a syntax error.
*/
        eval: function (text) {
            try {
                return !(/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.test(
                        text.replace(/"(\\.|[^"\\])*"/g, ''))) &&
                    eval('(' + text + ')');
            } catch (e) {
                return false;
            }
        },

        parse: function (text) {
            var at = 0;
            var ch = ' ';

            function error(m) {
                throw {
                    name: 'JSONError',
                    message: m,
                    at: at - 1,
                    text: text
                };
            }

            function next() {
                ch = text.charAt(at);
                at += 1;
                return ch;
            }

            function white() {
                while (ch) {
                    if (ch <= ' ') {
                        next();
                    } else if (ch == '/') {
                        switch (next()) {
                            case '/':
                                while (next() && ch != '\n' && ch != '\r') {}
                                break;
                            case '*':
                                next();
                                for (;;) {
                                    if (ch) {
                                        if (ch == '*') {
                                            if (next() == '/') {
                                                next();
                                                break;
                                            }
                                        } else {
                                            next();
                                        }
                                    } else {
                                        error("Unterminated comment");
                                    }
                                }
                                break;
                            default:
                                error("Syntax error");
                        }
                    } else {
                        break;
                    }
                }
            }

            function string() {
                var i, s = '', t, u;

                if (ch == '"') {
    outer:          while (next()) {
                        if (ch == '"') {
                            next();
                            return s;
                        } else if (ch == '\\') {
                            switch (next()) {
                            case 'b':
                                s += '\b';
                                break;
                            case 'f':
                                s += '\f';
                                break;
                            case 'n':
                                s += '\n';
                                break;
                            case 'r':
                                s += '\r';
                                break;
                            case 't':
                                s += '\t';
                                break;
                            case 'u':
                                u = 0;
                                for (i = 0; i < 4; i += 1) {
                                    t = parseInt(next(), 16);
                                    if (!isFinite(t)) {
                                        break outer;
                                    }
                                    u = u * 16 + t;
                                }
                                s += String.fromCharCode(u);
                                break;
                            default:
                                s += ch;
                            }
                        } else {
                            s += ch;
                        }
                    }
                }
                error("Bad string");
            }

            function array() {
                var a = [];

                if (ch == '[') {
                    next();
                    white();
                    if (ch == ']') {
                        next();
                        return a;
                    }
                    while (ch) {
                        a.push(value());
                        white();
                        if (ch == ']') {
                            next();
                            return a;
                        } else if (ch != ',') {
                            break;
                        }
                        next();
                        white();
                    }
                }
                error("Bad array");
            }

            function object() {
                var k, o = {};

                if (ch == '{') {
                    next();
                    white();
                    if (ch == '}') {
                        next();
                        return o;
                    }
                    while (ch) {
                        k = string();
                        white();
                        if (ch != ':') {
                            break;
                        }
                        next();
                        o[k] = value();
                        white();
                        if (ch == '}') {
                            next();
                            return o;
                        } else if (ch != ',') {
                            break;
                        }
                        next();
                        white();
                    }
                }
                error("Bad object");
            }

            function number() {
                var n = '', v;
                if (ch == '-') {
                    n = '-';
                    next();
                }
                while (ch >= '0' && ch <= '9') {
                    n += ch;
                    next();
                }
                if (ch == '.') {
                    n += '.';
                    while (next() && ch >= '0' && ch <= '9') {
                        n += ch;
                    }
                }
                if (ch == 'e' || ch == 'E') {
                    n += 'e';
                    next();
                    if (ch == '-' || ch == '+') {
                        n += ch;
                        next();
                    }
                    while (ch >= '0' && ch <= '9') {
                        n += ch;
                        next();
                    }
                }
                v = +n;
                if (!isFinite(v)) {
                    ////error("Bad number");
                } else {
                    return v;
                }
            }

            function word() {
                switch (ch) {
                    case 't':
                        if (next() == 'r' && next() == 'u' && next() == 'e') {
                            next();
                            return true;
                        }
                        break;
                    case 'f':
                        if (next() == 'a' && next() == 'l' && next() == 's' &&
                                next() == 'e') {
                            next();
                            return false;
                        }
                        break;
                    case 'n':
                        if (next() == 'u' && next() == 'l' && next() == 'l') {
                            next();
                            return null;
                        }
                        break;
                }
                error("Syntax error");
            }

            function value() {
                white();
                switch (ch) {
                    case '{':
                        return object();
                    case '[':
                        return array();
                    case '"':
                        return string();
                    case '-':
                        return number();
                    default:
                        return ch >= '0' && ch <= '9' ? number() : word();
                }
            }

            return value();
        }
    };
}();/*  Prototype JavaScript framework, version 1.5.0_rc1
 *  (c) 2005 Sam Stephenson <sam@conio.net>
 *
 *  Prototype is freely distributable under the terms of an MIT-style license.
 *  For details, see the Prototype web site: http://prototype.conio.net/
 *
/*--------------------------------------------------------------------------*/

var Prototype = {
  Version: '1.5.0_rc1',
  ScriptFragment: '(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)',

  emptyFunction: function() {},
  K: function(x) {return x}
}

var Class = {
  create: function() {
    return function() {
      this.initialize.apply(this, arguments);
    }
  }
}

var Abstract = new Object();

Object.extend = function(destination, source) {
  for (var property in source) {
    destination[property] = source[property];
  }
  return destination;
}

Object.extend(Object, {
  inspect: function(object) {
    try {
      if (object == undefined) return 'undefined';
      if (object == null) return 'null';
      return object.inspect ? object.inspect() : object.toString();
    } catch (e) {
      if (e instanceof RangeError) return '...';
      throw e;
    }
  },

  keys: function(object) {
    var keys = [];
    for (var property in object)
      keys.push(property);
    return keys;
  },

  values: function(object) {
    var values = [];
    for (var property in object)
      values.push(object[property]);
    return values;
  },

  clone: function(object) {
    return Object.extend({}, object);
  }
});

Function.prototype.bind = function() {
  var __method = this, args = $A(arguments), object = args.shift();
  return function() {
    return __method.apply(object, args.concat($A(arguments)));
  }
}

Function.prototype.bindAsEventListener = function(object) {
  var __method = this, args = $A(arguments), object = args.shift();
  return function(event) {
    return __method.apply(object, [( event || window.event)].concat(args).concat($A(arguments)));
  }
}

Object.extend(Number.prototype, {
  toColorPart: function() {
    var digits = this.toString(16);
    if (this < 16) return '0' + digits;
    return digits;
  },

  succ: function() {
    return this + 1;
  },

  times: function(iterator) {
    $R(0, this, true).each(iterator);
    return this;
  }
});

var Try = {
  these: function() {
    var returnValue;

    for (var i = 0; i < arguments.length; i++) {
      var lambda = arguments[i];
      try {
        returnValue = lambda();
        break;
      } catch (e) {}
    }

    return returnValue;
  }
}

/*--------------------------------------------------------------------------*/

var PeriodicalExecuter = Class.create();
PeriodicalExecuter.prototype = {
  initialize: function(callback, frequency) {
    this.callback = callback;
    this.frequency = frequency;
    this.currentlyExecuting = false;

    this.registerCallback();
  },

  registerCallback: function() {
    this.timer = setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
  },

  stop: function() {
    if (!this.timer) return;
    clearInterval(this.timer);
    this.timer = null;
  },

  onTimerEvent: function() {
    if (!this.currentlyExecuting) {
      try {
        this.currentlyExecuting = true;
        this.callback(this);
      } finally {
        this.currentlyExecuting = false;
      }
    }
  }
}
Object.extend(String.prototype, {
  gsub: function(pattern, replacement) {
    var result = '', source = this, match;
    replacement = arguments.callee.prepareReplacement(replacement);

    while (source.length > 0) {
      if (match = source.match(pattern)) {
        result += source.slice(0, match.index);
        result += (replacement(match) || '').toString();
        source  = source.slice(match.index + match[0].length);
      } else {
        result += source, source = '';
      }
    }
    return result;
  },

  sub: function(pattern, replacement, count) {
    replacement = this.gsub.prepareReplacement(replacement);
    count = count === undefined ? 1 : count;

    return this.gsub(pattern, function(match) {
      if (--count < 0) return match[0];
      return replacement(match);
    });
  },

  scan: function(pattern, iterator) {
    this.gsub(pattern, iterator);
    return this;
  },

  truncate: function(length, truncation) {
    length = length || 30;
    truncation = truncation === undefined ? '...' : truncation;
    return this.length > length ?
      this.slice(0, length - truncation.length) + truncation : this;
  },

  strip: function() {
    return this.replace(/^\s+/, '').replace(/\s+$/, '');
  },

  stripTags: function() {
    return this.replace(/<\/?[^>]+>/gi, '');
  },

  stripScripts: function() {
    return this.replace(new RegExp(Prototype.ScriptFragment, 'img'), '');
  },

  extractScripts: function() {
    var matchAll = new RegExp(Prototype.ScriptFragment, 'img');
    var matchOne = new RegExp(Prototype.ScriptFragment, 'im');
    return (this.match(matchAll) || []).map(function(scriptTag) {
      return (scriptTag.match(matchOne) || ['', ''])[1];
    });
  },

  evalScripts: function() {
    return this.extractScripts().map(function(script) { return eval(script) });
  },

  escapeHTML: function() {
    var div = document.createElement('div');
    var text = document.createTextNode(this);
    div.appendChild(text);
    return div.innerHTML;
  },

  unescapeHTML: function() {
    var div = document.createElement('div');
    div.innerHTML = this.stripTags();
    return div.childNodes[0] ? div.childNodes[0].nodeValue : '';
  },

  toQueryParams: function() {
    var pairs = this.match(/^\??(.*)$/)[1].split('&');
    return pairs.inject({}, function(params, pairString) {
      var pair  = pairString.split('=');
      var value = pair[1] ? decodeURIComponent(pair[1]) : undefined;
      params[decodeURIComponent(pair[0])] = value;
      return params;
    });
  },

  toArray: function() {
    return this.split('');
  },

  camelize: function() {
    var oStringList = this.split('-');
    if (oStringList.length == 1) return oStringList[0];

    var camelizedString = this.indexOf('-') == 0
      ? oStringList[0].charAt(0).toUpperCase() + oStringList[0].substring(1)
      : oStringList[0];

    for (var i = 1, len = oStringList.length; i < len; i++) {
      var s = oStringList[i];
      camelizedString += s.charAt(0).toUpperCase() + s.substring(1);
    }

    return camelizedString;
  },

  inspect: function(useDoubleQuotes) {
    var escapedString = this.replace(/\\/g, '\\\\');
    if (useDoubleQuotes)
      return '"' + escapedString.replace(/"/g, '\\"') + '"';
    else
      return "'" + escapedString.replace(/'/g, '\\\'') + "'";
  }
});

String.prototype.gsub.prepareReplacement = function(replacement) {
  if (typeof replacement == 'function') return replacement;
  var template = new Template(replacement);
  return function(match) { return template.evaluate(match) };
}

String.prototype.parseQuery = String.prototype.toQueryParams;

var Template = Class.create();
Template.Pattern = /(^|.|\r|\n)(#\{(.*?)\})/;
Template.prototype = {
  initialize: function(template, pattern) {
    this.template = template.toString();
    this.pattern  = pattern || Template.Pattern;
  },

  evaluate: function(object) {
    return this.template.gsub(this.pattern, function(match) {
      var before = match[1];
      if (before == '\\') return match[2];
      return before + (object[match[3]] || '').toString();
    });
  }
}

var $break    = new Object();
var $continue = new Object();

var Enumerable = {
  each: function(iterator) {
    var index = 0;
    try {
      this._each(function(value) {
        try {
          iterator(value, index++);
        } catch (e) {
          if (e != $continue) throw e;
        }
      });
    } catch (e) {
      if (e != $break) throw e;
    }
  },

  all: function(iterator) {
    var result = true;
    this.each(function(value, index) {
      result = result && !!(iterator || Prototype.K)(value, index);
      if (!result) throw $break;
    });
    return result;
  },

  any: function(iterator) {
    var result = false;
    this.each(function(value, index) {
      if (result = !!(iterator || Prototype.K)(value, index))
        throw $break;
    });
    return result;
  },

  collect: function(iterator) {
    var results = [];
    this.each(function(value, index) {
      results.push(iterator(value, index));
    });
    return results;
  },

  detect: function (iterator) {
    var result;
    this.each(function(value, index) {
      if (iterator(value, index)) {
        result = value;
        throw $break;
      }
    });
    return result;
  },

  findAll: function(iterator) {
    var results = [];
    this.each(function(value, index) {
      if (iterator(value, index))
        results.push(value);
    });
    return results;
  },

  grep: function(pattern, iterator) {
    var results = [];
    this.each(function(value, index) {
      var stringValue = value.toString();
      if (stringValue.match(pattern))
        results.push((iterator || Prototype.K)(value, index));
    })
    return results;
  },

  include: function(object) {
    var found = false;
    this.each(function(value) {
      if (value == object) {
        found = true;
        throw $break;
      }
    });
    return found;
  },

  inject: function(memo, iterator) {
    this.each(function(value, index) {
      memo = iterator(memo, value, index);
    });
    return memo;
  },

  invoke: function(method) {
    var args = $A(arguments).slice(1);
    return this.collect(function(value) {
      return value[method].apply(value, args);
    });
  },

  max: function(iterator) {
    var result;
    this.each(function(value, index) {
      value = (iterator || Prototype.K)(value, index);
      if (result == undefined || value >= result)
        result = value;
    });
    return result;
  },

  min: function(iterator) {
    var result;
    this.each(function(value, index) {
      value = (iterator || Prototype.K)(value, index);
      if (result == undefined || value < result)
        result = value;
    });
    return result;
  },

  partition: function(iterator) {
    var trues = [], falses = [];
    this.each(function(value, index) {
      ((iterator || Prototype.K)(value, index) ?
        trues : falses).push(value);
    });
    return [trues, falses];
  },

  pluck: function(property) {
    var results = [];
    this.each(function(value, index) {
      results.push(value[property]);
    });
    return results;
  },

  reject: function(iterator) {
    var results = [];
    this.each(function(value, index) {
      if (!iterator(value, index))
        results.push(value);
    });
    return results;
  },

  sortBy: function(iterator) {
    return this.collect(function(value, index) {
      return {value: value, criteria: iterator(value, index)};
    }).sort(function(left, right) {
      var a = left.criteria, b = right.criteria;
      return a < b ? -1 : a > b ? 1 : 0;
    }).pluck('value');
  },

  toArray: function() {
    return this.collect(Prototype.K);
  },

  zip: function() {
    var iterator = Prototype.K, args = $A(arguments);
    if (typeof args.last() == 'function')
      iterator = args.pop();

    var collections = [this].concat(args).map($A);
    return this.map(function(value, index) {
      return iterator(collections.pluck(index));
    });
  },

  inspect: function() {
    return '#<Enumerable:' + this.toArray().inspect() + '>';
  }
}

Object.extend(Enumerable, {
  map:     Enumerable.collect,
  find:    Enumerable.detect,
  select:  Enumerable.findAll,
  member:  Enumerable.include,
  entries: Enumerable.toArray
});
var $A = Array.from = function(iterable) {
  if (!iterable) return [];
  if (iterable.toArray) {
    return iterable.toArray();
  } else {
    var results = [];
    for (var i = 0; i < iterable.length; i++)
      results.push(iterable[i]);
    return results;
  }
}

Object.extend(Array.prototype, Enumerable);

if (!Array.prototype._reverse)
  Array.prototype._reverse = Array.prototype.reverse;

Object.extend(Array.prototype, {
  _each: function(iterator) {
    for (var i = 0; i < this.length; i++)
      iterator(this[i]);
  },

  clear: function() {
    this.length = 0;
    return this;
  },

  first: function() {
    return this[0];
  },

  last: function() {
    return this[this.length - 1];
  },

  compact: function() {
    return this.select(function(value) {
      return value != undefined || value != null;
    });
  },

  flatten: function() {
    return this.inject([], function(array, value) {
      return array.concat(value && value.constructor == Array ?
        value.flatten() : [value]);
    });
  },

  without: function() {
    var values = $A(arguments);
    return this.select(function(value) {
      return !values.include(value);
    });
  },

  indexOf: function(object) {
    for (var i = 0; i < this.length; i++)
      if (this[i] == object) return i;
    return -1;
  },

  reverse: function(inline) {
    return (inline !== false ? this : this.toArray())._reverse();
  },

  reduce: function() {
    return this.length > 1 ? this : this[0];
  },

  uniq: function() {
    return this.inject([], function(array, value) {
      return array.include(value) ? array : array.concat([value]);
    });
  },

  inspect: function() {
    return '[' + this.map(Object.inspect).join(', ') + ']';
  }
});
var Hash = {
  _each: function(iterator) {
    for (var key in this) {
      var value = this[key];
      if (typeof value == 'function') continue;

      var pair = [key, value];
      pair.key = key;
      pair.value = value;
      iterator(pair);
    }
  },

  keys: function() {
    return this.pluck('key');
  },

  values: function() {
    return this.pluck('value');
  },

  merge: function(hash) {
    return $H(hash).inject($H(this), function(mergedHash, pair) {
      mergedHash[pair.key] = pair.value;
      return mergedHash;
    });
  },

  toQueryString: function() {
    return this.map(function(pair) {
      return pair.map(encodeURIComponent).join('=');
    }).join('&');
  },

  inspect: function() {
    return '#<Hash:{' + this.map(function(pair) {
      return pair.map(Object.inspect).join(': ');
    }).join(', ') + '}>';
  }
}

function $H(object) {
  var hash = Object.extend({}, object || {});
  Object.extend(hash, Enumerable);
  Object.extend(hash, Hash);
  return hash;
}
ObjectRange = Class.create();
Object.extend(ObjectRange.prototype, Enumerable);
Object.extend(ObjectRange.prototype, {
  initialize: function(start, end, exclusive) {
    this.start = start;
    this.end = end;
    this.exclusive = exclusive;
  },

  _each: function(iterator) {
    var value = this.start;
    while (this.include(value)) {
      iterator(value);
      value = value.succ();
    }
  },

  include: function(value) {
    if (value < this.start)
      return false;
    if (this.exclusive)
      return value < this.end;
    return value <= this.end;
  }
});

var $R = function(start, end, exclusive) {
  return new ObjectRange(start, end, exclusive);
}

var Ajax = {
  getTransport: function() {
    return Try.these(
      function() {return new XMLHttpRequest()},
      function() {return new ActiveXObject('Msxml2.XMLHTTP')},
      function() {return new ActiveXObject('Microsoft.XMLHTTP')}
    ) || false;
  },

  activeRequestCount: 0
}

Ajax.Responders = {
  responders: [],

  _each: function(iterator) {
    this.responders._each(iterator);
  },

  register: function(responderToAdd) {
    if (!this.include(responderToAdd))
      this.responders.push(responderToAdd);
  },

  unregister: function(responderToRemove) {
    this.responders = this.responders.without(responderToRemove);
  },

  dispatch: function(callback, request, transport, json) {
    this.each(function(responder) {
      if (responder[callback] && typeof responder[callback] == 'function') {
        try {
          responder[callback].apply(responder, [request, transport, json]);
        } catch (e) {}
      }
    });
  }
};

Object.extend(Ajax.Responders, Enumerable);

Ajax.Responders.register({
  onCreate: function() {
    Ajax.activeRequestCount++;
  },

  onComplete: function() {
    Ajax.activeRequestCount--;
  }
});

Ajax.Base = function() {};
Ajax.Base.prototype = {
  setOptions: function(options) {
    this.options = {
      method:       'post',
      asynchronous: true,
      contentType:  'application/x-www-form-urlencoded',
      parameters:   ''
    }
    Object.extend(this.options, options || {});
  },

  responseIsSuccess: function() {
    return this.transport.status == undefined
        || this.transport.status == 0
        || (this.transport.status >= 200 && this.transport.status < 300);
  },

  responseIsFailure: function() {
    return !this.responseIsSuccess();
  }
}

Ajax.Request = Class.create();
Ajax.Request.Events =
  ['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete'];

Ajax.Request.prototype = Object.extend(new Ajax.Base(), {
  initialize: function(url, options) {
    this.transport = Ajax.getTransport();
    this.setOptions(options);
    this.request(url);
  },

  request: function(url) {
    var parameters = this.options.parameters || '';
    if (parameters.length > 0) parameters += '&_=';

    /* Simulate other verbs over post */
    if (this.options.method != 'get' && this.options.method != 'post') {
      parameters += (parameters.length > 0 ? '&' : '') + '_method=' + this.options.method;
      this.options.method = 'post';
    }

    try {
      this.url = url;
      if (this.options.method == 'get' && parameters.length > 0)
        this.url += (this.url.match(/\?/) ? '&' : '?') + parameters;

      Ajax.Responders.dispatch('onCreate', this, this.transport);

      this.transport.open(this.options.method, this.url,
        this.options.asynchronous);

      if (this.options.asynchronous)
        setTimeout(function() { this.respondToReadyState(1) }.bind(this), 10);

      this.transport.onreadystatechange = this.onStateChange.bind(this);
      this.setRequestHeaders();

      var body = this.options.postBody ? this.options.postBody : parameters;
      this.transport.send(this.options.method == 'post' ? body : null);

      /* Force Firefox to handle ready state 4 for synchronous requests */
      if (!this.options.asynchronous && this.transport.overrideMimeType)
        this.onStateChange();

    } catch (e) {
      this.dispatchException(e);
    }
  },

  setRequestHeaders: function() {
    var requestHeaders =
      ['X-Requested-With', 'XMLHttpRequest',
       'X-Prototype-Version', Prototype.Version,
       'Accept', 'text/javascript, text/html, application/xml, text/xml, */*'];

    if (this.options.method == 'post') {
      requestHeaders.push('Content-type', this.options.contentType);

      /* Force "Connection: close" for Mozilla browsers to work around
       * a bug where XMLHttpReqeuest sends an incorrect Content-length
       * header. See Mozilla Bugzilla #246651.
       */
      if (this.transport.overrideMimeType)
        requestHeaders.push('Connection', 'close');
    }

    if (this.options.requestHeaders)
      requestHeaders.push.apply(requestHeaders, this.options.requestHeaders);

    for (var i = 0; i < requestHeaders.length; i += 2)
      this.transport.setRequestHeader(requestHeaders[i], requestHeaders[i+1]);
  },

  onStateChange: function() {
    var readyState = this.transport.readyState;
    if (readyState != 1)
      this.respondToReadyState(this.transport.readyState);
  },

  header: function(name) {
    try {
      return this.transport.getResponseHeader(name);
    } catch (e) {}
  },

  evalJSON: function() {
    try {
      return eval('(' + this.header('X-JSON') + ')');
    } catch (e) {}
  },

  evalResponse: function() {
    try {
      return eval(this.transport.responseText);
    } catch (e) {
      this.dispatchException(e);
    }
  },

  respondToReadyState: function(readyState) {
    var event = Ajax.Request.Events[readyState];
    var transport = this.transport, json = this.evalJSON();

    if (event == 'Complete') {
      try {
        (this.options['on' + this.transport.status]
         || this.options['on' + (this.responseIsSuccess() ? 'Success' : 'Failure')]
         || Prototype.emptyFunction)(transport, json);
      } catch (e) {
        this.dispatchException(e);
      }

      if ((this.header('Content-type') || '').match(/^text\/javascript/i))
        this.evalResponse();
    }

    try {
      (this.options['on' + event] || Prototype.emptyFunction)(transport, json);
      Ajax.Responders.dispatch('on' + event, this, transport, json);
    } catch (e) {
      this.dispatchException(e);
    }

    /* Avoid memory leak in MSIE: clean up the oncomplete event handler */
    if (event == 'Complete')
      this.transport.onreadystatechange = Prototype.emptyFunction;
  },

  dispatchException: function(exception) {
    (this.options.onException || Prototype.emptyFunction)(this, exception);
    Ajax.Responders.dispatch('onException', this, exception);
  }
});

Ajax.Updater = Class.create();

Object.extend(Object.extend(Ajax.Updater.prototype, Ajax.Request.prototype), {
  initialize: function(container, url, options) {
    this.containers = {
      success: container.success ? $(container.success) : $(container),
      failure: container.failure ? $(container.failure) :
        (container.success ? null : $(container))
    }

    this.transport = Ajax.getTransport();
    this.setOptions(options);

    var onComplete = this.options.onComplete || Prototype.emptyFunction;
    this.options.onComplete = (function(transport, object) {
      this.updateContent();
      onComplete(transport, object);
    }).bind(this);

    this.request(url);
  },

  updateContent: function() {
    var receiver = this.responseIsSuccess() ?
      this.containers.success : this.containers.failure;
    var response = this.transport.responseText;

    if (!this.options.evalScripts)
      response = response.stripScripts();

    if (receiver) {
      if (this.options.insertion) {
        new this.options.insertion(receiver, response);
      } else {
        Element.update(receiver, response);
      }
    }

    if (this.responseIsSuccess()) {
      if (this.onComplete)
        setTimeout(this.onComplete.bind(this), 10);
    }
  }
});

Ajax.PeriodicalUpdater = Class.create();
Ajax.PeriodicalUpdater.prototype = Object.extend(new Ajax.Base(), {
  initialize: function(container, url, options) {
    this.setOptions(options);
    this.onComplete = this.options.onComplete;

    this.frequency = (this.options.frequency || 2);
    this.decay = (this.options.decay || 1);

    this.updater = {};
    this.container = container;
    this.url = url;

    this.start();
  },

  start: function() {
    this.options.onComplete = this.updateComplete.bind(this);
    this.onTimerEvent();
  },

  stop: function() {
    this.updater.options.onComplete = undefined;
    clearTimeout(this.timer);
    (this.onComplete || Prototype.emptyFunction).apply(this, arguments);
  },

  updateComplete: function(request) {
    if (this.options.decay) {
      this.decay = (request.responseText == this.lastText ?
        this.decay * this.options.decay : 1);

      this.lastText = request.responseText;
    }
    this.timer = setTimeout(this.onTimerEvent.bind(this),
      this.decay * this.frequency * 1000);
  },

  onTimerEvent: function() {
    this.updater = new Ajax.Updater(this.container, this.url, this.options);
  }
});
function $() {
  var results = [], element;
  for (var i = 0; i < arguments.length; i++) {
    element = arguments[i];
    if (typeof element == 'string')
      element = document.getElementById(element);
    results.push(Element.extend(element));
  }
  return results.reduce();
}

document.getElementsByClassName = function(className, parentElement) {
  var children = ($(parentElement) || document.body).getElementsByTagName('*');
  return $A(children).inject([], function(elements, child) {
    if (child.className.match(new RegExp("(^|\\s)" + className + "(\\s|$)")))
      elements.push(Element.extend(child));
    return elements;
  });
}

/*--------------------------------------------------------------------------*/

if (!window.Element)
  var Element = new Object();

Element.extend = function(element) {
  if (!element) return;
  if (_nativeExtensions || element.nodeType == 3) return element;

  if (!element._extended && element.tagName && element != window) {
    var methods = Object.clone(Element.Methods), cache = Element.extend.cache;

    if (element.tagName == 'FORM')
      Object.extend(methods, Form.Methods);
    if (['INPUT', 'TEXTAREA', 'SELECT'].include(element.tagName))
      Object.extend(methods, Form.Element.Methods);

    for (var property in methods) {
      var value = methods[property];
      if (typeof value == 'function')
        element[property] = cache.findOrStore(value);
    }
  }

  element._extended = true;
  return element;
}

Element.extend.cache = {
  findOrStore: function(value) {
    return this[value] = this[value] || function() {
      return value.apply(null, [this].concat($A(arguments)));
    }
  }
}

Element.Methods = {
  visible: function(element) {
    return $(element).style.display != 'none';
  },

  toggle: function(element) {
    element = $(element);
    Element[Element.visible(element) ? 'hide' : 'show'](element);
    return element;
  },

  hide: function(element) {
    $(element).style.display = 'none';
    return element;
  },

  show: function(element) {
    $(element).style.display = '';
    return element;
  },

  remove: function(element) {
    element = $(element);
    element.parentNode.removeChild(element);
    return element;
  },

  update: function(element, html) {
    $(element).innerHTML = html.stripScripts();
    setTimeout(function() {html.evalScripts()}, 10);
    return element;
  },

  replace: function(element, html) {
    element = $(element);
    if (element.outerHTML) {
      element.outerHTML = html.stripScripts();
    } else {
      var range = element.ownerDocument.createRange();
      range.selectNodeContents(element);
      element.parentNode.replaceChild(
        range.createContextualFragment(html.stripScripts()), element);
    }
    setTimeout(function() {html.evalScripts()}, 10);
    return element;
  },

  inspect: function(element) {
    element = $(element);
    var result = '<' + element.tagName.toLowerCase();
    $H({'id': 'id', 'className': 'class'}).each(function(pair) {
      var property = pair.first(), attribute = pair.last();
      var value = (element[property] || '').toString();
      if (value) result += ' ' + attribute + '=' + value.inspect(true);
    });
    return result + '>';
  },

  recursivelyCollect: function(element, property) {
    element = $(element);
    var elements = [];
    while (element = element[property])
      if (element.nodeType == 1)
        elements.push(Element.extend(element));
    return elements;
  },

  ancestors: function(element) {
    return $(element).recursivelyCollect('parentNode');
  },

  descendants: function(element) {
    element = $(element);
    return $A(element.getElementsByTagName('*'));
  },

  previousSiblings: function(element) {
    return $(element).recursivelyCollect('previousSibling');
  },

  nextSiblings: function(element) {
    return $(element).recursivelyCollect('nextSibling');
  },

  siblings: function(element) {
    element = $(element);
    return element.previousSiblings().reverse().concat(element.nextSiblings());
  },

  match: function(element, selector) {
    element = $(element);
    if (typeof selector == 'string')
      selector = new Selector(selector);
    return selector.match(element);
  },

  up: function(element, expression, index) {
    return Selector.findElement($(element).ancestors(), expression, index);
  },

  down: function(element, expression, index) {
    return Selector.findElement($(element).descendants(), expression, index);
  },

  previous: function(element, expression, index) {
    return Selector.findElement($(element).previousSiblings(), expression, index);
  },

  next: function(element, expression, index) {
    return Selector.findElement($(element).nextSiblings(), expression, index);
  },

  getElementsBySelector: function() {
    var args = $A(arguments), element = $(args.shift());
    return Selector.findChildElements(element, args);
  },

  getElementsByClassName: function(element, className) {
    element = $(element);
    return document.getElementsByClassName(className, element);
  },

  getHeight: function(element) {
    element = $(element);
    return element.offsetHeight;
  },

  classNames: function(element) {
    return new Element.ClassNames(element);
  },

  hasClassName: function(element, className) {
    if (!(element = $(element))) return;
    return Element.classNames(element).include(className);
  },

  addClassName: function(element, className) {
    if (!(element = $(element))) return;
    Element.classNames(element).add(className);
    return element;
  },

  removeClassName: function(element, className) {
    if (!(element = $(element))) return;
    Element.classNames(element).remove(className);
    return element;
  },

  observe: function() {
    Event.observe.apply(Event, arguments);
    return $A(arguments).first();
  },

  stopObserving: function() {
    Event.stopObserving.apply(Event, arguments);
    return $A(arguments).first();
  },

  // removes whitespace-only text node children
  cleanWhitespace: function(element) {
    element = $(element);
    var node = element.firstChild;
    while (node) {
      var nextNode = node.nextSibling;
      if (node.nodeType == 3 && !/\S/.test(node.nodeValue))
        element.removeChild(node);
      node = nextNode;
    }
    return element;
  },

  empty: function(element) {
    return $(element).innerHTML.match(/^\s*$/);
  },

  childOf: function(element, ancestor) {
    element = $(element), ancestor = $(ancestor);
    while (element = element.parentNode)
      if (element == ancestor) return true;
    return false;
  },

  scrollTo: function(element) {
    element = $(element);
    var x = element.x ? element.x : element.offsetLeft,
        y = element.y ? element.y : element.offsetTop;
    window.scrollTo(x, y);
    return element;
  },

  getStyle: function(element, style) {
    element = $(element);
    var value = element.style[style.camelize()];
    if (!value) {
      if (document.defaultView && document.defaultView.getComputedStyle) {
        var css = document.defaultView.getComputedStyle(element, null);
        value = css ? css.getPropertyValue(style) : null;
      } else if (element.currentStyle) {
        value = element.currentStyle[style.camelize()];
      }
    }

    if (window.opera && ['left', 'top', 'right', 'bottom'].include(style))
      if (Element.getStyle(element, 'position') == 'static') value = 'auto';

    return value == 'auto' ? null : value;
  },

  setStyle: function(element, style) {
    element = $(element);
    for (var name in style)
      element.style[name.camelize()] = style[name];
    return element;
  },

  getDimensions: function(element) {
    element = $(element);
    if (Element.getStyle(element, 'display') != 'none')
      return {width: element.offsetWidth, height: element.offsetHeight};

    // All *Width and *Height properties give 0 on elements with display none,
    // so enable the element temporarily
    var els = element.style;
    var originalVisibility = els.visibility;
    var originalPosition = els.position;
    els.visibility = 'hidden';
    els.position = 'absolute';
    els.display = '';
    var originalWidth = element.clientWidth;
    var originalHeight = element.clientHeight;
    els.display = 'none';
    els.position = originalPosition;
    els.visibility = originalVisibility;
    return {width: originalWidth, height: originalHeight};
  },

  makePositioned: function(element) {
    element = $(element);
    var pos = Element.getStyle(element, 'position');
    if (pos == 'static' || !pos) {
      element._madePositioned = true;
      element.style.position = 'relative';
      // Opera returns the offset relative to the positioning context, when an
      // element is position relative but top and left have not been defined
      if (window.opera) {
        element.style.top = 0;
        element.style.left = 0;
      }
    }
    return element;
  },

  undoPositioned: function(element) {
    element = $(element);
    if (element._madePositioned) {
      element._madePositioned = undefined;
      element.style.position =
        element.style.top =
        element.style.left =
        element.style.bottom =
        element.style.right = '';
    }
    return element;
  },

  makeClipping: function(element) {
    element = $(element);
    if (element._overflow) return;
    element._overflow = element.style.overflow || 'auto';
    if ((Element.getStyle(element, 'overflow') || 'visible') != 'hidden')
      element.style.overflow = 'hidden';
    return element;
  },

  undoClipping: function(element) {
    element = $(element);
    if (!element._overflow) return;
    element.style.overflow = element._overflow == 'auto' ? '' : element._overflow;
    element._overflow = null;
    return element;
  }
}

// IE is missing .innerHTML support for TABLE-related elements
if(document.all){
  Element.Methods.update = function(element, html) {
    element = $(element);
    var tagName = element.tagName.toUpperCase();
    if (['THEAD','TBODY','TR','TD'].indexOf(tagName) > -1) {
      var div = document.createElement('div');
      switch (tagName) {
        case 'THEAD':
        case 'TBODY':
          div.innerHTML = '<table><tbody>' +  html.stripScripts() + '</tbody></table>';
          depth = 2;
          break;
        case 'TR':
          div.innerHTML = '<table><tbody><tr>' +  html.stripScripts() + '</tr></tbody></table>';
          depth = 3;
          break;
        case 'TD':
          div.innerHTML = '<table><tbody><tr><td>' +  html.stripScripts() + '</td></tr></tbody></table>';
          depth = 4;
      }
      $A(element.childNodes).each(function(node){
        element.removeChild(node)
      });
      depth.times(function(){ div = div.firstChild });

      $A(div.childNodes).each(
        function(node){ element.appendChild(node) });
    } else {
      element.innerHTML = html.stripScripts();
    }
    setTimeout(function() {html.evalScripts()}, 10);
    return element;
  }
}

Object.extend(Element, Element.Methods);

var _nativeExtensions = false;

if (!window.HTMLElement && /Konqueror|Safari|KHTML/.test(navigator.userAgent)) {
  /* Emulate HTMLElement, HTMLFormElement, HTMLInputElement, HTMLTextAreaElement,
     and HTMLSelectElement in Safari */
  ['', 'Form', 'Input', 'TextArea', 'Select'].each(function(tag) {
    var klass = window['HTML' + tag + 'Element'] = {};
    klass.prototype = document.createElement(tag ? tag.toLowerCase() : 'div').__proto__;
  });
}

Element.addMethods = function(methods) {
  Object.extend(Element.Methods, methods || {});

  function copy(methods, destination) {
    var cache = Element.extend.cache;
    for (var property in methods) {
      var value = methods[property];
      destination[property] = cache.findOrStore(value);
    }
  }

  if (typeof HTMLElement != 'undefined') {
    copy(Element.Methods, HTMLElement.prototype);
    copy(Form.Methods, HTMLFormElement.prototype);
    [HTMLInputElement, HTMLTextAreaElement, HTMLSelectElement].each(function(klass) {
      copy(Form.Element.Methods, klass.prototype);
    });
    _nativeExtensions = true;
  }
}

var Toggle = new Object();
Toggle.display = Element.toggle;

/*--------------------------------------------------------------------------*/

Abstract.Insertion = function(adjacency) {
  this.adjacency = adjacency;
}

Abstract.Insertion.prototype = {
  initialize: function(element, content) {
    this.element = $(element);
    this.content = content.stripScripts();

    if (this.adjacency && this.element.insertAdjacentHTML) {
      try {
        this.element.insertAdjacentHTML(this.adjacency, this.content);
      } catch (e) {
        var tagName = this.element.tagName.toLowerCase();
        if (tagName == 'tbody' || tagName == 'tr') {
          this.insertContent(this.contentFromAnonymousTable());
        } else {
          throw e;
        }
      }
    } else {
      this.range = this.element.ownerDocument.createRange();
      if (this.initializeRange) this.initializeRange();
      this.insertContent([this.range.createContextualFragment(this.content)]);
    }

    setTimeout(function() {content.evalScripts()}, 10);
  },

  contentFromAnonymousTable: function() {
    var div = document.createElement('div');
    div.innerHTML = '<table><tbody>' + this.content + '</tbody></table>';
    return $A(div.childNodes[0].childNodes[0].childNodes);
  }
}

var Insertion = new Object();

Insertion.Before = Class.create();
Insertion.Before.prototype = Object.extend(new Abstract.Insertion('beforeBegin'), {
  initializeRange: function() {
    this.range.setStartBefore(this.element);
  },

  insertContent: function(fragments) {
    fragments.each((function(fragment) {
      this.element.parentNode.insertBefore(fragment, this.element);
    }).bind(this));
  }
});

Insertion.Top = Class.create();
Insertion.Top.prototype = Object.extend(new Abstract.Insertion('afterBegin'), {
  initializeRange: function() {
    this.range.selectNodeContents(this.element);
    this.range.collapse(true);
  },

  insertContent: function(fragments) {
    fragments.reverse(false).each((function(fragment) {
      this.element.insertBefore(fragment, this.element.firstChild);
    }).bind(this));
  }
});

Insertion.Bottom = Class.create();
Insertion.Bottom.prototype = Object.extend(new Abstract.Insertion('beforeEnd'), {
  initializeRange: function() {
    this.range.selectNodeContents(this.element);
    this.range.collapse(this.element);
  },

  insertContent: function(fragments) {
    fragments.each((function(fragment) {
      this.element.appendChild(fragment);
    }).bind(this));
  }
});

Insertion.After = Class.create();
Insertion.After.prototype = Object.extend(new Abstract.Insertion('afterEnd'), {
  initializeRange: function() {
    this.range.setStartAfter(this.element);
  },

  insertContent: function(fragments) {
    fragments.each((function(fragment) {
      this.element.parentNode.insertBefore(fragment,
        this.element.nextSibling);
    }).bind(this));
  }
});

/*--------------------------------------------------------------------------*/

Element.ClassNames = Class.create();
Element.ClassNames.prototype = {
  initialize: function(element) {
    this.element = $(element);
  },

  _each: function(iterator) {
    this.element.className.split(/\s+/).select(function(name) {
      return name.length > 0;
    })._each(iterator);
  },

  set: function(className) {
    this.element.className = className;
  },

  add: function(classNameToAdd) {
    if (this.include(classNameToAdd)) return;
    this.set(this.toArray().concat(classNameToAdd).join(' '));
  },

  remove: function(classNameToRemove) {
    if (!this.include(classNameToRemove)) return;
    this.set(this.select(function(className) {
      return className != classNameToRemove;
    }).join(' '));
  },

  toString: function() {
    return this.toArray().join(' ');
  }
}

Object.extend(Element.ClassNames.prototype, Enumerable);
var Selector = Class.create();
Selector.prototype = {
  initialize: function(expression) {
    this.params = {classNames: []};
    this.expression = expression.toString().strip();
    this.parseExpression();
    this.compileMatcher();
  },

  parseExpression: function() {
    function abort(message) { throw 'Parse error in selector: ' + message; }

    if (this.expression == '')  abort('empty expression');

    var params = this.params, expr = this.expression, match, modifier, clause, rest;
    while (match = expr.match(/^(.*)\[([a-z0-9_:-]+?)(?:([~\|!]?=)(?:"([^"]*)"|([^\]\s]*)))?\]$/i)) {
      params.attributes = params.attributes || [];
      params.attributes.push({name: match[2], operator: match[3], value: match[4] || match[5] || ''});
      expr = match[1];
    }

    if (expr == '*') return this.params.wildcard = true;

    while (match = expr.match(/^([^a-z0-9_-])?([a-z0-9_-]+)(.*)/i)) {
      modifier = match[1], clause = match[2], rest = match[3];
      switch (modifier) {
        case '#':       params.id = clause; break;
        case '.':       params.classNames.push(clause); break;
        case '':
        case undefined: params.tagName = clause.toUpperCase(); break;
        default:        abort(expr.inspect());
      }
      expr = rest;
    }

    if (expr.length > 0) abort(expr.inspect());
  },

  buildMatchExpression: function() {
    var params = this.params, conditions = [], clause;

    if (params.wildcard)
      conditions.push('true');
    if (clause = params.id)
      conditions.push('element.id == ' + clause.inspect());
    if (clause = params.tagName)
      conditions.push('element.tagName.toUpperCase() == ' + clause.inspect());
    if ((clause = params.classNames).length > 0)
      for (var i = 0; i < clause.length; i++)
        conditions.push('Element.hasClassName(element, ' + clause[i].inspect() + ')');
    if (clause = params.attributes) {
      clause.each(function(attribute) {
        var value = 'element.getAttribute(' + attribute.name.inspect() + ')';
        var splitValueBy = function(delimiter) {
          return value + ' && ' + value + '.split(' + delimiter.inspect() + ')';
        }

        switch (attribute.operator) {
          case '=':       conditions.push(value + ' == ' + attribute.value.inspect()); break;
          case '~=':      conditions.push(splitValueBy(' ') + '.include(' + attribute.value.inspect() + ')'); break;
          case '|=':      conditions.push(
                            splitValueBy('-') + '.first().toUpperCase() == ' + attribute.value.toUpperCase().inspect()
                          ); break;
          case '!=':      conditions.push(value + ' != ' + attribute.value.inspect()); break;
          case '':
          case undefined: conditions.push(value + ' != null'); break;
          default:        throw 'Unknown operator ' + attribute.operator + ' in selector';
        }
      });
    }

    return conditions.join(' && ');
  },

  compileMatcher: function() {
    this.match = new Function('element', 'if (!element.tagName) return false; \
      return ' + this.buildMatchExpression());
  },

  findElements: function(scope) {
    var element;

    if (element = $(this.params.id))
      if (this.match(element))
        if (!scope || Element.childOf(element, scope))
          return [element];

    scope = (scope || document).getElementsByTagName(this.params.tagName || '*');

    var results = [];
    for (var i = 0; i < scope.length; i++)
      if (this.match(element = scope[i]))
        results.push(Element.extend(element));

    return results;
  },

  toString: function() {
    return this.expression;
  }
}

Object.extend(Selector, {
  matchElements: function(elements, expression) {
    var selector = new Selector(expression);
    return elements.select(selector.match.bind(selector));
  },

  findElement: function(elements, expression, index) {
    if (typeof expression == 'number') index = expression, expression = false;
    return Selector.matchElements(elements, expression || '*')[index || 0];
  },

  findChildElements: function(element, expressions) {
    return expressions.map(function(expression) {
      return expression.strip().split(/\s+/).inject([null], function(results, expr) {
        var selector = new Selector(expr);
        return results.inject([], function(elements, result) {
          return elements.concat(selector.findElements(result || element));
        });
      });
    }).flatten();
  }
});

function $$() {
  return Selector.findChildElements(document, $A(arguments));
}
var Form = {
  reset: function(form) {
    $(form).reset();
    return form;
  }
};

Form.Methods = {
  serialize: function(form) {
    var elements = Form.getElements($(form));
    var queryComponents = new Array();

    for (var i = 0; i < elements.length; i++) {
      var queryComponent = Form.Element.serialize(elements[i]);
      if (queryComponent)
        queryComponents.push(queryComponent);
    }

    return queryComponents.join('&');
  },

  getElements: function(form) {
    form = $(form);
    var elements = new Array();

    for (var tagName in Form.Element.Serializers) {
      var tagElements = form.getElementsByTagName(tagName);
      for (var j = 0; j < tagElements.length; j++)
        elements.push(tagElements[j]);
    }
    return elements;
  },

  getInputs: function(form, typeName, name) {
    form = $(form);
    var inputs = form.getElementsByTagName('input');

    if (!typeName && !name)
      return inputs;

    var matchingInputs = new Array();
    for (var i = 0; i < inputs.length; i++) {
      var input = inputs[i];
      if ((typeName && input.type != typeName) ||
          (name && input.name != name))
        continue;
      matchingInputs.push(input);
    }

    return matchingInputs;
  },

  disable: function(form) {
    form = $(form);
    var elements = Form.getElements(form);
    for (var i = 0; i < elements.length; i++) {
      var element = elements[i];
      element.blur();
      element.disabled = 'true';
    }
    return form;
  },

  enable: function(form) {
    form = $(form);
    var elements = Form.getElements(form);
    for (var i = 0; i < elements.length; i++) {
      var element = elements[i];
      element.disabled = '';
    }
    return form;
  },

  findFirstElement: function(form) {
    return Form.getElements(form).find(function(element) {
      return element.type != 'hidden' && !element.disabled &&
        ['input', 'select', 'textarea'].include(element.tagName.toLowerCase());
    });
  },

  focusFirstElement: function(form) {
    form = $(form);
    Field.activate(Form.findFirstElement(form));
    return form;
  }
}

Object.extend(Form, Form.Methods);

/*--------------------------------------------------------------------------*/

Form.Element = {
  focus: function(element) {
    $(element).focus();
    return element;
  },

  select: function(element) {
    $(element).select();
    return element;
  }
}

Form.Element.Methods = {
  serialize: function(element) {
    element = $(element);
    var method = element.tagName.toLowerCase();
    var parameter = Form.Element.Serializers[method](element);

    if (parameter) {
      var key = encodeURIComponent(parameter[0]);
      if (key.length == 0) return;

      if (parameter[1].constructor != Array)
        parameter[1] = [parameter[1]];

      return parameter[1].map(function(value) {
        return key + '=' + encodeURIComponent(value);
      }).join('&');
    }
  },

  getValue: function(element) {
    element = $(element);
    var method = element.tagName.toLowerCase();
    var parameter = Form.Element.Serializers[method](element);

    if (parameter)
      return parameter[1];
  },

  clear: function(element) {
    $(element).value = '';
    return element;
  },

  present: function(element) {
    return $(element).value != '';
  },

  activate: function(element) {
    element = $(element);
    element.focus();
    if (element.select)
      element.select();
    return element;
  },

  disable: function(element) {
    element = $(element);
    element.disabled = '';
    return element;
  },

  enable: function(element) {
    element = $(element);
    element.blur();
    element.disabled = 'true';
    return element;
  }
}

Object.extend(Form.Element, Form.Element.Methods);
var Field = Form.Element;

/*--------------------------------------------------------------------------*/

Form.Element.Serializers = {
  input: function(element) {
    switch (element.type.toLowerCase()) {
      case 'checkbox':
      case 'radio':
        return Form.Element.Serializers.inputSelector(element);
      default:
        return Form.Element.Serializers.textarea(element);
    }
    return false;
  },

  inputSelector: function(element) {
    if (element.checked)
      return [element.name, element.value];
  },

  textarea: function(element) {
    return [element.name, element.value];
  },

  select: function(element) {
    return Form.Element.Serializers[element.type == 'select-one' ?
      'selectOne' : 'selectMany'](element);
  },

  selectOne: function(element) {
    var value = '', opt, index = element.selectedIndex;
    if (index >= 0) {
      opt = element.options[index];
      value = opt.value || opt.text;
    }
    return [element.name, value];
  },

  selectMany: function(element) {
    var value = [];
    for (var i = 0; i < element.length; i++) {
      var opt = element.options[i];
      if (opt.selected)
        value.push(opt.value || opt.text);
    }
    return [element.name, value];
  }
}

/*--------------------------------------------------------------------------*/

var $F = Form.Element.getValue;

/*--------------------------------------------------------------------------*/

Abstract.TimedObserver = function() {}
Abstract.TimedObserver.prototype = {
  initialize: function(element, frequency, callback) {
    this.frequency = frequency;
    this.element   = $(element);
    this.callback  = callback;

    this.lastValue = this.getValue();
    this.registerCallback();
  },

  registerCallback: function() {
    setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
  },

  onTimerEvent: function() {
    var value = this.getValue();
    if (this.lastValue != value) {
      this.callback(this.element, value);
      this.lastValue = value;
    }
  }
}

Form.Element.Observer = Class.create();
Form.Element.Observer.prototype = Object.extend(new Abstract.TimedObserver(), {
  getValue: function() {
    return Form.Element.getValue(this.element);
  }
});

Form.Observer = Class.create();
Form.Observer.prototype = Object.extend(new Abstract.TimedObserver(), {
  getValue: function() {
    return Form.serialize(this.element);
  }
});

/*--------------------------------------------------------------------------*/

Abstract.EventObserver = function() {}
Abstract.EventObserver.prototype = {
  initialize: function(element, callback) {
    this.element  = $(element);
    this.callback = callback;

    this.lastValue = this.getValue();
    if (this.element.tagName.toLowerCase() == 'form')
      this.registerFormCallbacks();
    else
      this.registerCallback(this.element);
  },

  onElementEvent: function() {
    var value = this.getValue();
    if (this.lastValue != value) {
      this.callback(this.element, value);
      this.lastValue = value;
    }
  },

  registerFormCallbacks: function() {
    var elements = Form.getElements(this.element);
    for (var i = 0; i < elements.length; i++)
      this.registerCallback(elements[i]);
  },

  registerCallback: function(element) {
    if (element.type) {
      switch (element.type.toLowerCase()) {
        case 'checkbox':
        case 'radio':
          Event.observe(element, 'click', this.onElementEvent.bind(this));
          break;
        default:
          Event.observe(element, 'change', this.onElementEvent.bind(this));
          break;
      }
    }
  }
}

Form.Element.EventObserver = Class.create();
Form.Element.EventObserver.prototype = Object.extend(new Abstract.EventObserver(), {
  getValue: function() {
    return Form.Element.getValue(this.element);
  }
});

Form.EventObserver = Class.create();
Form.EventObserver.prototype = Object.extend(new Abstract.EventObserver(), {
  getValue: function() {
    return Form.serialize(this.element);
  }
});
if (!window.Event) {
  var Event = new Object();
}

Object.extend(Event, {
  KEY_BACKSPACE: 8,
  KEY_TAB:       9,
  KEY_RETURN:   13,
  KEY_ESC:      27,
  KEY_LEFT:     37,
  KEY_UP:       38,
  KEY_RIGHT:    39,
  KEY_DOWN:     40,
  KEY_DELETE:   46,
  KEY_HOME:     36,
  KEY_END:      35,
  KEY_PAGEUP:   33,
  KEY_PAGEDOWN: 34,

  element: function(event) {
    return event.target || event.srcElement;
  },

  isLeftClick: function(event) {
    return (((event.which) && (event.which == 1)) ||
            ((event.button) && (event.button == 1)));
  },

  pointerX: function(event) {
    return event.pageX || (event.clientX +
      (document.documentElement.scrollLeft || document.body.scrollLeft));
  },

  pointerY: function(event) {
    return event.pageY || (event.clientY +
      (document.documentElement.scrollTop || document.body.scrollTop));
  },

  stop: function(event) {
    if (event.preventDefault) {
      event.preventDefault();
      event.stopPropagation();
    } else {
      event.returnValue = false;
      event.cancelBubble = true;
    }
  },

  // find the first node with the given tagName, starting from the
  // node the event was triggered on; traverses the DOM upwards
  findElement: function(event, tagName) {
    var element = Event.element(event);
    while (element.parentNode && (!element.tagName ||
        (element.tagName.toUpperCase() != tagName.toUpperCase())))
      element = element.parentNode;
    return element;
  },

  observers: false,

  _observeAndCache: function(element, name, observer, useCapture) {
    if (!this.observers) this.observers = [];
    if (element.addEventListener) {
      this.observers.push([element, name, observer, useCapture]);
      element.addEventListener(name, observer, useCapture);
    } else if (element.attachEvent) {
      this.observers.push([element, name, observer, useCapture]);
      element.attachEvent('on' + name, observer);
    }
  },

  unloadCache: function() {
    if (!Event.observers) return;
    for (var i = 0; i < Event.observers.length; i++) {
      Event.stopObserving.apply(this, Event.observers[i]);
      Event.observers[i][0] = null;
    }
    Event.observers = false;
  },

  observe: function(element, name, observer, useCapture) {
    element = $(element);
    useCapture = useCapture || false;

    if (name == 'keypress' &&
        (navigator.appVersion.match(/Konqueror|Safari|KHTML/)
        || element.attachEvent))
      name = 'keydown';

    Event._observeAndCache(element, name, observer, useCapture);
  },

  stopObserving: function(element, name, observer, useCapture) {
    element = $(element);
    useCapture = useCapture || false;

    if (name == 'keypress' &&
        (navigator.appVersion.match(/Konqueror|Safari|KHTML/)
        || element.detachEvent))
      name = 'keydown';

    if (element.removeEventListener) {
      element.removeEventListener(name, observer, useCapture);
    } else if (element.detachEvent) {
      try {
        element.detachEvent('on' + name, observer);
      } catch (e) {}
    }
  }
});

/* prevent memory leaks in IE */
if (navigator.appVersion.match(/\bMSIE\b/))
  Event.observe(window, 'unload', Event.unloadCache, false);
var Position = {
  // set to true if needed, warning: firefox performance problems
  // NOT neeeded for page scrolling, only if draggable contained in
  // scrollable elements
  includeScrollOffsets: false,

  // must be called before calling withinIncludingScrolloffset, every time the
  // page is scrolled
  prepare: function() {
    this.deltaX =  window.pageXOffset
                || document.documentElement.scrollLeft
                || document.body.scrollLeft
                || 0;
    this.deltaY =  window.pageYOffset
                || document.documentElement.scrollTop
                || document.body.scrollTop
                || 0;
  },

  realOffset: function(element) {
    var valueT = 0, valueL = 0;
    do {
      valueT += element.scrollTop  || 0;
      valueL += element.scrollLeft || 0;
      element = element.parentNode;
    } while (element);
    return [valueL, valueT];
  },

  cumulativeOffset: function(element) {
    var valueT = 0, valueL = 0;
    do {
      valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;
      element = element.offsetParent;
    } while (element);
    return [valueL, valueT];
  },

  positionedOffset: function(element) {
    var valueT = 0, valueL = 0;
    do {
      valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;
      element = element.offsetParent;
      if (element) {
        p = Element.getStyle(element, 'position');
        if (p == 'relative' || p == 'absolute') break;
      }
    } while (element);
    return [valueL, valueT];
  },

  offsetParent: function(element) {
    if (element.offsetParent) return element.offsetParent;
    if (element == document.body) return element;

    while ((element = element.parentNode) && element != document.body)
      if (Element.getStyle(element, 'position') != 'static')
        return element;

    return document.body;
  },

  // caches x/y coordinate pair to use with overlap
  within: function(element, x, y) {
    if (this.includeScrollOffsets)
      return this.withinIncludingScrolloffsets(element, x, y);
    this.xcomp = x;
    this.ycomp = y;
    this.offset = this.cumulativeOffset(element);

    return (y >= this.offset[1] &&
            y <  this.offset[1] + element.offsetHeight &&
            x >= this.offset[0] &&
            x <  this.offset[0] + element.offsetWidth);
  },

  withinIncludingScrolloffsets: function(element, x, y) {
    var offsetcache = this.realOffset(element);

    this.xcomp = x + offsetcache[0] - this.deltaX;
    this.ycomp = y + offsetcache[1] - this.deltaY;
    this.offset = this.cumulativeOffset(element);

    return (this.ycomp >= this.offset[1] &&
            this.ycomp <  this.offset[1] + element.offsetHeight &&
            this.xcomp >= this.offset[0] &&
            this.xcomp <  this.offset[0] + element.offsetWidth);
  },

  // within must be called directly before
  overlap: function(mode, element) {
    if (!mode) return 0;
    if (mode == 'vertical')
      return ((this.offset[1] + element.offsetHeight) - this.ycomp) /
        element.offsetHeight;
    if (mode == 'horizontal')
      return ((this.offset[0] + element.offsetWidth) - this.xcomp) /
        element.offsetWidth;
  },

  page: function(forElement) {
    var valueT = 0, valueL = 0;

    var element = forElement;
    do {
      valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;

      // Safari fix
      if (element.offsetParent==document.body)
        if (Element.getStyle(element,'position')=='absolute') break;

    } while (element = element.offsetParent);

    element = forElement;
    do {
      if (!window.opera || element.tagName=='BODY') {
        valueT -= element.scrollTop  || 0;
        valueL -= element.scrollLeft || 0;
      }
    } while (element = element.parentNode);

    return [valueL, valueT];
  },

  clone: function(source, target) {
    var options = Object.extend({
      setLeft:    true,
      setTop:     true,
      setWidth:   true,
      setHeight:  true,
      offsetTop:  0,
      offsetLeft: 0
    }, arguments[2] || {})

    // find page position of source
    source = $(source);
    var p = Position.page(source);

    // find coordinate system to use
    target = $(target);
    var delta = [0, 0];
    var parent = null;
    // delta [0,0] will do fine with position: fixed elements,
    // position:absolute needs offsetParent deltas
    if (Element.getStyle(target,'position') == 'absolute') {
      parent = Position.offsetParent(target);
      delta = Position.page(parent);
    }

    // correct by body offsets (fixes Safari)
    if (parent == document.body) {
      delta[0] -= document.body.offsetLeft;
      delta[1] -= document.body.offsetTop;
    }

    // set position
    if(options.setLeft)   target.style.left  = (p[0] - delta[0] + options.offsetLeft) + 'px';
    if(options.setTop)    target.style.top   = (p[1] - delta[1] + options.offsetTop) + 'px';
    if(options.setWidth)  target.style.width = source.offsetWidth + 'px';
    if(options.setHeight) target.style.height = source.offsetHeight + 'px';
  },

  absolutize: function(element) {
    element = $(element);
    if (element.style.position == 'absolute') return;
    Position.prepare();

    var offsets = Position.positionedOffset(element);
    var top     = offsets[1];
    var left    = offsets[0];
    var width   = element.clientWidth;
    var height  = element.clientHeight;

    element._originalLeft   = left - parseFloat(element.style.left  || 0);
    element._originalTop    = top  - parseFloat(element.style.top || 0);
    element._originalWidth  = element.style.width;
    element._originalHeight = element.style.height;

    element.style.position = 'absolute';
    element.style.top    = top + 'px';;
    element.style.left   = left + 'px';;
    element.style.width  = width + 'px';;
    element.style.height = height + 'px';;
  },

  relativize: function(element) {
    element = $(element);
    if (element.style.position == 'relative') return;
    Position.prepare();

    element.style.position = 'relative';
    var top  = parseFloat(element.style.top  || 0) - (element._originalTop || 0);
    var left = parseFloat(element.style.left || 0) - (element._originalLeft || 0);

    element.style.top    = top + 'px';
    element.style.left   = left + 'px';
    element.style.height = element._originalHeight;
    element.style.width  = element._originalWidth;
  }
}

// Safari returns margins on body which is incorrect if the child is absolutely
// positioned.  For performance reasons, redefine Position.cumulativeOffset for
// KHTML/WebKit only.
if (/Konqueror|Safari|KHTML/.test(navigator.userAgent)) {
  Position.cumulativeOffset = function(element) {
    var valueT = 0, valueL = 0;
    do {
      valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;
      if (element.offsetParent == document.body)
        if (Element.getStyle(element, 'position') == 'absolute') break;

      element = element.offsetParent;
    } while (element);

    return [valueL, valueT];
  }
}

Element.addMethods();document.iframeLoaders = {};

iframe = Class.create();
iframe.prototype = {
	initialize: function(form, options,count){
		if (!options) options = {};
		this.form = form;
		this.uniqueId = count;
		document.iframeLoaders[this.uniqueId] = this;
		this.transport = this.getTransport();
		this.onComplete = options.onComplete || null;
		this.update = $(options.update) || null;
		this.updateMultiple = options.multiple || false;
		if (((navigator.vendor && (navigator.vendor.indexOf('Apple')) > -1) || window.opera) // safari and opera only
     && /\/Direct\/Process$/.test(form.action) && form.elements && (form.elements.length == 1)) { // only change calls that contain 1 element and whose actions end with /Direct/Process
			var url = form.action + '?jsonRequest=' + escape(form.elements[0].value), // change form submit to string; similar to changing form method to get
					doc = this.transport.contentWindow || this.transport.contentDocument; // retrieve the document of the iframe
			if (url.length < 80000) { // allow fallback to normal submission (80k is the max length for urls in safari)
				if (doc.document) // make sure we have the document and not the window
					doc = doc.document;
				
				try { // if this fails, fallback to normal submission
					doc.location.replace(url); // use location.replace to overwrite elements in history 
					return;
				} catch (e) { };
			}
		}
		form.target= 'frame_'+this.uniqueId;
		form.setAttribute("target", 'frame_'+this.uniqueId); // in case the other one fails.
		form.submit();
	},

	onStateChange: function() {
		this.transport = $('frame_'+this.uniqueId);
		try {	 var doc = this.transport.contentDocument.document.body.innerHTML; this.transport.contentDocument.document.close(); }	// For NS6
		catch (e){ 
			try{ var doc = this.transport.contentWindow.document.body.innerHTML; this.transport.contentWindow.document.close(); } // For IE5.5 and IE6
			 catch (e){
				 try { var doc = this.transport.document.body.innerHTML; this.transport.document.body.close(); } // for IE5
					catch (e) {
						try	{ var doc = window.frames['frame_'+this.uniqueId].document.body.innerText; } // for really nasty browsers
						catch (e) { //alert(e); 
						} // forget it.
				 }
			}
		}
		this.transport.responseText = doc;
		if (this.onComplete) setTimeout(function(){this.onComplete(this.transport);}.bind(this), 10);
		if (this.update) setTimeout(function(){this.update.innerHTML = this.transport.responseText;}.bind(this), 10);
		if (this.updateMultiple){ setTimeout(function(){ // JSON support!
				try	{ var hasscript = false; eval("var inputObject = "+this.transport.responseText);	// we're expecting a JSON object, eval it to inputObject
					for (var i in inputObject) { if (i == 'script') { hasscript = true; } // check if we passed some javascript along too
						else {if ( elm = $(i)) { elm.innerHTML = inputObject[i]; } else { 
						//alert("element "+i+" not found!"); 
						} } // if it's not script, update the corresponding div
					} if (hasscript) eval(inputObject['script']); // some on-the-fly-javascript exchanging support too
				} catch (e) { //alert('There was an error processing: '+this.transport.responseText); 
				} // in case of an error					
			}.bind(this), 10);
		}	
	},

	getTransport: function() {
		var divElm = document.createElement('DIV'), frame;
		divElm.style.position = "absolute";
		divElm.style.top = "0";
		divElm.style.marginLeft = "-10000px";
		if (navigator.userAgent.indexOf('MSIE') > 0 && navigator.userAgent.indexOf('Opera') == -1) {// switch to the crappy solution for IE
		 divElm.innerHTML = '<iframe name=\"frame_'+this.uniqueId+'\" id=\"frame_'+this.uniqueId+'\" src=\"about:blank\" onload=\"setTimeout(function(){document.iframeLoaders['+this.uniqueId+'].onStateChange()},20);"></iframe>';
		} else {
			frame = document.createElement("iframe");
			frame.setAttribute("name", "frame_"+this.uniqueId);
			frame.setAttribute("id", "frame_"+this.uniqueId);
			frame.addEventListener("load", 	function(){	this.onStateChange(); }.bind(this), false);
			divElm.appendChild(frame);
		}
		document.body.appendChild(divElm);
		return frame;
	}
};
RequestBatch = Class.create();

// for unique id
RequestBatch.counter = 0;

// how many requests are still pending?
var pendingRequests = 0;

function DirectAccessErrorHandler(msg,ex){
//alert(msg);
}

// the core object to request batches
RequestBatch.prototype = {
    initialize: function() {
        this.UniqueId = RequestBatch.counter++;
        this.Requests = new Array()
    },

    AddToRequest: function(requestThis) {
        this.Requests[this.Requests.length] = requestThis;
    },
   
    BeginRequest: function(serverUrl, callback) {
        pendingRequests++;
        
        var jsonString = JSON.stringify(this);
        
        var form = generateForm(this.UniqueId, serverUrl, jsonString);
        new iframe(form, {onComplete: function(request) {processResponse(callback, request);} }, this.UniqueId);

        // in case they reuse the requestbatch
        this.UniqueId = RequestBatch.counter++;
    }
};

function generateForm(formId, serverUrl, inputVal) {
    // create the form
	var form = document.createElement("form");
	form.name = "f" + formId;
	form.id = "f" + formId;
	form.action = serverUrl;
	
	// create the input element on the form
	var inputElem = document.createElement("input");
	inputElem.name = "jsonRequest";
	inputElem.type = "hidden";
	inputElem.value = inputVal;
	form.appendChild(inputElem);

	// Firefox has a behavior on refresh that displays a popup confirming that is it reloading a form.
	// We work around this by attempting to perform a get action if the size is below a threshold, else
	// we will run as a post
	form.method = "post";
    if(navigator.userAgent.toLowerCase().indexOf('firefox') != -1) {
        var separator = serverUrl.indexOf('?') == -1 ? "?" : "&";
        var fullRequestURL = serverUrl + separator + "jsonRequest="+ escape(inputVal);
        if (fullRequestURL.length < 15000) {
            // we plan to perform a get, so we need to parse the sid out of the url and place it
            // inside the form
            var sidPos = serverUrl.indexOf('sid=');
            if (sidPos != -1) {
                var endPos = serverUrl.indexOf('&', sidPos);
                var sid = serverUrl.substring(sidPos + 'sid='.length, endPos == -1 ? serverUrl.length : endPos);
	            var sidInputElem = document.createElement("input");
	            sidInputElem.name = "sid";
	            sidInputElem.type = "hidden";
	            sidInputElem.value = sid;
	            form.appendChild(sidInputElem);
	            // remove the sid from the url
	            form.action = serverUrl.substring(0, sidPos-1);
            }
            form.method = "get";
        }
    }
	
	// append the form to the document body
	// users must be cautious of when they call this due to a bug in IE
	// see http://support.microsoft.com/kb/927917 for details
	document.body.appendChild(form);
	return form;
}

function processResponse(callback, request)
{   
    pendingRequests--;
    try { 
        var jsonResponse = unescape(request.responseText);
        var responseObject = JSON.parse(jsonResponse);
        try {
            callback(responseObject.ResponseBatch);
        } catch (e) {
            DirectAccessErrorHandler("exception during client callback", e);
        }
    } catch (e) {
        DirectAccessErrorHandler("exception during processResponse", e);
    }
}

function getPendingRequestCount()
{
    return pendingRequests;
}// ------------------------------------------------------------------------------------
// This file contains all the request type objects for the SiteLife JSON Direct API.
// Create instances of these objects, place them in a RequestBatch, and send them off.
// ------------------------------------------------------------------------------------

// Identify a user
UserKey = Class.create();
UserKey.prototype = {
   initialize: function(key) {
        var data = new Object();
        data.Key = key;
        this.UserKey = data;
   }
};
// Identify a comment
CommentKey = Class.create();
CommentKey.prototype = {
   initialize: function(key) {
        var data = new Object();
        data.Key = key;
        this.CommentKey = data;
   }
};
// Identify an article
ArticleKey = Class.create();
ArticleKey.prototype = {
   initialize: function(key) {
        var data = new Object();
        data.Key = key;
        this.ArticleKey = data;
   }
};

// Identify a persona message
PersonaMessageKey = Class.create();
PersonaMessageKey.prototype = {
   initialize: function(key) {
        var data = new Object();
        data.Key = key;
        this.PersonaMessageKey = data;
   }
};

// Identify a review
ReviewKey = Class.create();
ReviewKey.prototype = {
   initialize: function(key) {
        var data = new Object();
        data.Key = key;
        this.ReviewKey = data;
   }
};
// Identify a gallery
GalleryKey = Class.create();
GalleryKey.prototype = {
    initialize: function(key) {
        var data = new Object();
        data.Key = key;
        this.GalleryKey = data;
    }
};
// Identify a photo
PhotoKey = Class.create();
PhotoKey.prototype = {
    initialize: function(key) {
        var data = new Object();
        data.Key = key;
        this.PhotoKey = data;
    }
};
// Identify a video
VideoKey = Class.create();
VideoKey.prototype = {
    initialize: function(key) {
        var data = new Object();
        data.Key = key;
        this.VideoKey = data;
    }
};

// Wrapper to request a comment page
CommentPage = Class.create();
CommentPage.prototype = {
   initialize: function(articleKey, numberPerPage, onPage, sort) {
        var data = new Object();
        data.ArticleKey = articleKey;
        data.NumberPerPage = numberPerPage;
        data.OnPage = onPage;
        data.Sort = sort;
        this.CommentPage = data;
   }
};

// Wrapper to request a persona message page
PersonaMessagePage = Class.create();
PersonaMessagePage.prototype = {
   initialize: function(userKey, numberPerPage, onPage, sort) {
        var data = new Object();
        data.UserKey = userKey;
        data.NumberPerPage = numberPerPage;
        data.OnPage = onPage;
        data.Sort = sort;
        this.PersonaMessagePage = data;
   }
};

// Wrapper to request a review page
ReviewPage = Class.create();
ReviewPage.prototype = {
   initialize: function(articleKey, numberPerPage, onPage,sort) {
        var data = new Object();
        data.ArticleKey = articleKey;
        data.NumberPerPage = numberPerPage;
        data.OnPage = onPage;
        data.Sort = sort;
        this.ReviewPage = data;
   }
};
// Wrapper of types a gallery can contain
MediaType = Class.create();
MediaType.prototype = {
    initialize: function(name) {
        var data = new Object();
        data.Name = name;
        this.MediaType = data;
    }
};
// Wrapper to request a page of public galleries
PublicGalleryPage = Class.create();
PublicGalleryPage.prototype = {
    initialize: function(numberPerPage, onPage, mediaType) {
        var data = new Object();
        data.NumberPerPage = numberPerPage;
        data.OnPage = onPage;
        data.MediaType = mediaType;
        this.PublicGalleryPage = data;
    }
};
// Wrapper to request a page of user galleries
UserGalleryPage = Class.create();
UserGalleryPage.prototype = {
    initialize: function(userKey, numberPerPage, onPage, mediaType) {
        var data = new Object();
        data.UserKey = userKey;
        data.NumberPerPage = numberPerPage;
        data.OnPage = onPage;
        data.MediaType = mediaType;
        this.UserGalleryPage = data;
    }
};
// Wrapper to request a page of photos
PhotoPage = Class.create();
PhotoPage.prototype = {
    initialize: function(galleryKey, numberPerPage, onPage) {
        var data = new Object();
        data.GalleryKey = galleryKey;
        data.NumberPerPage = numberPerPage;
        data.OnPage = onPage;
        this.PhotoPage = data;
    }
};
// Wrapper to request a page of videos
VideoPage = Class.create();
VideoPage.prototype = {
    initialize: function(galleryKey, numberPerPage, onPage) {
        var data = new Object();
        data.GalleryKey = galleryKey;
        data.NumberPerPage = numberPerPage;
        data.OnPage = onPage;
        this.VideoPage = data;
    }
};
// Wrapper to request a comment action
CommentAction = Class.create();
CommentAction.prototype = {
   initialize: function(commentOnKey, onPageUrl, onPageTitle, commentBody) {
        var data = new Object();
        data.CommentOnKey = commentOnKey;
        data.OnPageUrl = onPageUrl;
        data.OnPageTitle = onPageTitle;
        data.CommentBody = commentBody;
        this.CommentAction = data;
   }
};
// Wrapper to request a review action
ReviewAction = Class.create();
ReviewAction.prototype = {
   initialize: function(reviewOnThisKey, onPageUrl, onPageTitle, 
                        reviewTitle, reviewRating, reviewBody, reviewPros, reviewCons) {
        var data = new Object();
        data.ReviewOnKey = reviewOnThisKey;
        data.OnPageUrl = onPageUrl;
        data.OnPageTitle = onPageTitle;
        data.ReviewTitle = reviewTitle;
        data.ReviewRating = reviewRating;
        data.ReviewBody = reviewBody;
        data.ReviewPros = reviewPros;
        data.ReviewCons = reviewCons;
        this.ReviewAction = data;
   }
};
// Wrapper to request a recommend action
RecommendAction = Class.create();
RecommendAction.prototype = {
   initialize: function(recommendThisKey) {
        var data = new Object();
        data.RecommendThisKey = recommendThisKey;
        this.RecommendAction = data;
   }
};
// Wrapper to request a rate action
RateAction = Class.create();
RateAction.prototype = {
   initialize: function(rateThisKey, rating) {
        var data = new Object();
        data.RateThisKey = rateThisKey;
        data.Rating = rating;
        this.RateAction = data;
   }
};

// Permanently delete a gallery, video or photo
DeleteContentAction = Class.create();
DeleteContentAction.prototype = {
   initialize: function(deleteThisContent) {
        var data = new Object();
        data.DeleteThisContent = deleteThisContent;
        this.DeleteContentAction = data;
   }
};

// Email from the SiteLife system
EmailContentAction = Class.create();
EmailContentAction.prototype = {
   initialize: function(toAddress, subject, body) {
        var data = new Object();
        data.ToAddress = toAddress;
        data.Subject = subject;
        data.Body = body;
        this.EmailContentAction = data;
   }
};

// Wrapper to request a report abuse action
ReportAbuseAction = Class.create();
ReportAbuseAction.prototype = {
   initialize: function(reportThisKey, abuseReason, abuseDescription) {
        var data = new Object();
        data.ReportThisKey = reportThisKey;
        data.AbuseReason = abuseReason;
        data.AbuseDescription = abuseDescription;
        this.ReportAbuseAction = data;
   }
};
// Category used for discovery
Category = Class.create();
Category.prototype = {
   initialize: function(name) {
        var data = new Object();
        data.Name = name;
        this.Category = data;
   }
};
// Section used for discovery
Section = Class.create();
Section.prototype = {
    initialize: function(name) {
        var data = new Object();
        data.Name = name;
        this.Section = data;
    }
};
// Update or create an article
UpdateArticleAction = Class.create();
UpdateArticleAction.prototype = {
   initialize: function(updateArticle, onPageUrl, onPageTitle, section,categories) {
        var data = new Object();
        data.UpdateArticle = updateArticle;
        data.OnPageUrl = onPageUrl;
        data.OnPageTitle = onPageTitle;
        data.Section = section;
        data.Categories = categories;
        this.UpdateArticleAction = data;
   }
};
// Update or create a gallery
UpdateGalleryAction = Class.create();
UpdateGalleryAction.prototype = {
    initialize: function(updateGallery, galleryType, mediaType, title, description, tags, section, galleryPromo) {
        var data = new Object();
        data.UpdateGallery = updateGallery;
        data.GalleryType = galleryType;
        data.MediaType = mediaType;
        data.Title = title;
        data.Description = description;
        data.Tags = tags;
        data.Section = section;
        data.GalleryPromo = galleryPromo;
        this.UpdateGalleryAction = data;
    }
};
// Update or create a photo
UpdatePhotoAction = Class.create();
UpdatePhotoAction.prototype = {
    initialize: function(updatePhoto, title, description, tags, section) {
        var data = new Object();
        data.UpdatePhoto = updatePhoto;
        data.Title = title;
        data.Description = description;
        data.Tags = tags;
        data.Section = section;
        this.UpdatePhotoAction = data;
    }
};
// Update or create a video
UpdateVideoAction = Class.create();
UpdateVideoAction.prototype = {
    initialize: function(updateVideo, title, description, tags, section) {
        var data = new Object();
        data.UpdateVideo = updateVideo;
        data.Title = title;
        data.Description = description;
        data.Tags = tags;
        data.Section = section;
        this.UpdateVideoAction = data;
    }
};
// 
GalleryType = Class.create();
GalleryType.prototype = {
    initialize: function(name) {
        var data = new Object();
        data.Name = name;
        this.GalleryType = data;
    }
};
// GalleryPromo used for setting promotional text for public galleries
GalleryPromo = Class.create();
GalleryPromo.prototype = {
    initialize: function(title, body, photoKey) {
        var data = new Object();
        data.Title = title;
        data.Body = body;
        data.PhotoKey = photoKey;
    }
};
// UserTier used for discovery
UserTier = Class.create();
UserTier.prototype = {
    initialize: function(name) {
        var data = new Object();
        data.Name = name;
        this.UserTier = data;
    }
};
// Activity used for discovery
Activity = Class.create();
Activity.prototype = {
    initialize: function(name) {
        var data = new Object();
        data.Name = name;
        this.Activity = data;
    }
};
// Discovery on articles
DiscoverArticlesAction = Class.create();
DiscoverArticlesAction.prototype = {
   initialize: function(searchSections,searchCategories,limitToContributors,activity,age,maximumNumberOfDiscoveries) {
        var data = new Object();
        data.SearchSections = searchSections;
        data.SearchCategories = searchCategories;
        data.LimitToContributors = limitToContributors;
        data.Activity = activity;
        data.Age = age;
        data.MaximumNumberOfDiscoveries = maximumNumberOfDiscoveries;

        this.DiscoverArticlesAction = data;
   }
};

// Action used to add a friend
AddFriendAction = Class.create();
AddFriendAction.prototype = {
    initialize: function(friendUserKey) {
        var data = new Object();
        data.FriendUserKey = friendUserKey;
        this.AddFriendAction = data;
    }
};

// Action used to add a message
AddPersonaMessageAction = Class.create();
AddPersonaMessageAction.prototype = {
    initialize: function(toUserKey, body) {
        var data = new Object();
        data.ToUserKey = toUserKey;
        data.Body = body;
        this.AddPersonaMessageAction = data;
    }
};

// Action used to remove a message
RemovePersonaMessageAction = Class.create();
RemovePersonaMessageAction.prototype = {
    initialize: function(personaMessageKey) {
        var data = new Object();
        data.PersonaMessageKey = personaMessageKey;
        this.RemovePersonaMessageAction = data;
    }
};

// Action used to approve a friend
ApproveFriendAction = Class.create();
ApproveFriendAction.prototype = {
    initialize: function(friendUserKey, isApproved) {
        var data = new Object();
        data.FriendUserKey = friendUserKey;
        data.IsApproved = isApproved;
        this.ApproveFriendAction = data;
    }
};

// Action used to remove a friend
RemoveFriendAction = Class.create();
RemoveFriendAction.prototype = {
    initialize: function(friendUserKey) {
        var data = new Object();
        data.FriendUserKey = friendUserKey;
        this.RemoveFriendAction = data;
    }
};

// Wrapper to request a friend page
FriendPage = Class.create();
FriendPage.prototype = {
   initialize: function(userKey, numberPerPage, onPage, isPendingList) {
        var data = new Object();
        data.UserKey = userKey;
        data.NumberPerPage = numberPerPage;
        data.OnPage = onPage;
        data.IsPendingList = isPendingList;
        this.FriendPage = data;
   }
};

// Wrapper to request if a given user key is a friend of the user specified by the second parameter
// if the userKey parameter is not specified, the currently logged-in user is used
IsFriend = Class.create();
IsFriend.prototype = {
   initialize: function(friendUserKey, userKey) {
        var data = new Object();
        data.FriendUserKey = friendUserKey;
        data.UserKey = userKey;
        this.IsFriend = data;
   }
};
												
// Discovery on content
DiscoverContentAction = Class.create();
DiscoverContentAction.prototype = {
   initialize: function(searchSections,searchCategories,limitToContributors,activity,contentType,age,maximumNumberOfDiscoveries) {
        var data = new Object();
        data.SearchSections = searchSections;
        data.SearchCategories = searchCategories;
        data.LimitToContributors = limitToContributors;
        data.Activity = activity;
        data.ContentType = contentType;
        data.Age = age;
        data.MaximumNumberOfDiscoveries = maximumNumberOfDiscoveries;
        this.DiscoverContentAction = data;
   }
};

// Content type for discovery
ContentType = Class.create();
ContentType.prototype = {
    initialize: function(name) {
        var data = new Object();
        data.Name = name;
        this.ContentType = data;
    }
};
												
UpdateUserProfileAction = Class.create();
UpdateUserProfileAction.prototype = {
   initialize: function(   userKey, 
                            aboutMe, 
                            location,
                            signature,
                            dateOfBirth, 
                            sex, 
                            personaPrivacyMode, 
                            commentsTabVisible, 
                            photosTabVisible, 
                            messagesOpenToEveryone, 
                            isEmailNotificationsEnabled, 
                            selectedStyleId, 
                            customAnswers, 
                            extendedProfile) {
                            
        var data = new Object();
        data.UserKey = userKey;
        data.AboutMe = aboutMe;
        data.Location = location;
        data.Signature = signature;
        data.DateOfBirth = dateOfBirth;
        data.Sex = sex;
		data.PersonaPrivacyMode = personaPrivacyMode;
		data.CommentsTabVisible = commentsTabVisible;
		data.PhotosTabVisible = photosTabVisible;
		data.MessagesOpenToEveryone = messagesOpenToEveryone;
		data.IsEmailNotificationsEnabled = isEmailNotificationsEnabled;
		data.SelectedStyleId = selectedStyleId;
		data.CustomAnswers = customAnswers;
		data.ExtendedProfile = extendedProfile;        
        this.UpdateUserProfileAction = data;
   }
};

SearchAction = Class.create();
SearchAction.prototype = {
   initialize: function(searchType, searchString, numberPerPage, onPage ) {
        var data = new Object();
        data.SearchType = searchType;
        data.SearchString = searchString;
        data.NumberPerPage = numberPerPage;
        data.OnPage = onPage;
        this.SearchAction = data;
   }
};

// Wrapper to request a watch item page
WatchItemPage = Class.create();
WatchItemPage.prototype = {
   initialize: function(userKey, numberPerPage, onPage) {
        var data = new Object();
        data.UserKey = userKey;
        data.NumberPerPage = numberPerPage;
        data.OnPage = onPage;
        this.WatchItemPage = data;
   }
};

// Wrapper to add a watch item
AddWatchItemAction = Class.create();
AddWatchItemAction.prototype = {
   initialize: function(userKey, watchTargetKey, title, url ) {
        var data = new Object();
        data.UserKey = userKey;
        data.WatchTargetKey = watchTargetKey;
        data.WatchItemTitle = title;
        data.WatchItemUrl = url;
        this.AddWatchItemAction = data;
   }
};

// Wrapper to delete a watch item
DeleteWatchItemAction = Class.create();
DeleteWatchItemAction.prototype = {
   initialize: function(userKey, watchTargetKey) {
        var data = new Object();
        data.UserKey = userKey;
        data.WatchTargetKey = watchTargetKey;
        this.DeleteWatchItemAction = data;
   }
};

// Identify a blog with this blog key
BlogKey = Class.create();
BlogKey.prototype = {
   initialize: function(key) {
        var data = new Object();
        data.Key = key;
        this.BlogKey = data;
   }
};

// Identify a blog post with this blog post key
BlogPostKey = Class.create();
BlogPostKey.prototype = {
   initialize: function(key) {
        var data = new Object();
        data.Key = key;
        this.BlogPostKey = data;
   }
};

// Wrapper to request a blog post page
BlogPostPage = Class.create();
BlogPostPage.prototype = {
   initialize: function(blogKey, numberPerPage, onPage, sort) {
        var data = new Object();
        data.BlogKey = blogKey;
        data.NumberPerPage = numberPerPage;
        data.OnPage = onPage;
        data.Sort = sort;
        this.BlogPostPage = data;
   }
};


// Wrapper to request a blog post archive count
BlogPostArchiveCount = Class.create();
BlogPostArchiveCount.prototype = {
   initialize: function(blogKey) {
        var data = new Object();
        data.BlogKey = blogKey;
        this.BlogPostArchiveCount = data;
   }
};


// Wrapper to request a blog post archive content page
BlogPostArchiveContentPage = Class.create();
BlogPostArchiveContentPage .prototype = {
   initialize: function(blogKey, month, numberPerPage, onPage, sort) {
        var data = new Object();
        data.BlogKey = blogKey;
        data.Month = month;
        data.NumberPerPage = numberPerPage;
        data.OnPage = onPage;
        data.Sort = sort;
        this.BlogPostArchiveContentPage = data;
   }
};


// Wrapper to request a user comment page
UserCommentPage = Class.create();
UserCommentPage.prototype = {
   initialize: function(userKey, numberPerPage, onPage, sort) {
        var data = new Object();
        data.UserKey = userKey;
        data.NumberPerPage = numberPerPage;
        data.OnPage = onPage;
        data.Sort = sort;
        this.UserCommentPage = data;
   }
};


// Wrapper to request blog tag 
RecentBlogTag = Class.create();
RecentBlogTag.prototype = {
   initialize: function(blogKey) {
        var data = new Object();
        data.BlogKey = blogKey;
        this.RecentBlogTag = data;
   }
};


// Wrapper to request recent user photo page
RecentUserPhotoPage = Class.create();
RecentUserPhotoPage.prototype = {
   initialize: function(userKey, numberPerPage, onPage) {
        var data = new Object();
        data.UserKey = userKey;
        data.NumberPerPage = numberPerPage;
        data.OnPage = onPage;
        this.RecentUserPhotoPage = data;
   }
};

// Wrapper to request recent user video page
RecentUserVideoPage = Class.create();
RecentUserVideoPage .prototype = {
   initialize: function(userKey, numberPerPage, onPage) {
        var data = new Object();
        data.UserKey = userKey;
        data.NumberPerPage = numberPerPage;
        data.OnPage = onPage;
        this.RecentUserVideoPage  = data;
   }
};


// Wrapper to request recent public gallery page
RecentPublicGalleryPage = Class.create();
RecentPublicGalleryPage .prototype = {
   initialize: function(userKey, numberPerPage, onPage) {
        var data = new Object();
        data.UserKey = userKey;
        data.NumberPerPage = numberPerPage;
        data.OnPage = onPage;
        this.RecentPublicGalleryPage  = data;
   }
};
    
    
// Wrapper to request recent user activity page
RecentUserActivity = Class.create();
RecentUserActivity .prototype = {
   initialize: function(userKey) {
        var data = new Object();
        data.UserKey = userKey;
       this.RecentUserActivity  = data;
   }
};

  
// Wrapper to request recent forum discussion page
RecentForumDiscussionPage = Class.create();
RecentForumDiscussionPage .prototype = {
   initialize: function(userKey, numberPerPage, onPage) {
        var data = new Object();
        data.UserKey = userKey;
        data.NumberPerPage = numberPerPage;
        data.OnPage = onPage;
        this.RecentForumDiscussionPage = data;
   }
};

    
// Wrapper to request user group forum page
UserGroupForumPage = Class.create();
UserGroupForumPage .prototype = {
   initialize: function(userKey, numberPerPage, onPage, sort) {
        var data = new Object();
        data.UserKey = userKey;
        data.NumberPerPage = numberPerPage;
        data.OnPage = onPage;
        data.Sort = sort;
        this.UserGroupForumPage = data;
   }
};

// The blogRollEntry used in UpdateBlogAction
BlogRollEntry = Class.create();
BlogRollEntry.prototype = {
   initialize: function(name, url) {
        var data = new Object();
        data.Name = name;
        data.Url = url;
        this.BlogRollEntry = data;
   }
};

// Update or create a blog
UpdateBlogAction = Class.create();
UpdateBlogAction.prototype = {
   initialize: function(updateBlog, title, tagline, blogRollEntries) {
        var data = new Object();
        data.BlogKey = updateBlog;
        data.Title = title;
        data.Tagline = tagline;
        data.BlogRollEntries = blogRollEntries;
        this.UpdateBlogAction = data;
   }
};

// Identify a forum discussion with this DiscussionKey 
DiscussionKey = Class.create();
DiscussionKey.prototype = {
   initialize: function(key) {
        var data = new Object();
        data.Key = key;
        this.DiscussionKey = data;
   }
};
		function submitRequest() {   
			
            pullCounts(articleid);

        }

		function pullCounts(articlekey) {

            var articleKey = new ArticleKey(articlekey);   

            var requestBatch = new RequestBatch();   

            requestBatch.AddToRequest(articleKey);    

            requestBatch.BeginRequest(serverUrl, renderArticle);    

        }  

           

        function renderArticle(responseBatch) { 

            if (responseBatch.Responses.length == 0) {    

				var commentCount = document.getElementById('articleCommentCount' + articleid);   

                var recommendCount = document.getElementById('articleRecommendCount' + articleid);   

                // update page elements  

				commentCount.style.visibility = 'hidden';

				recommendCount.style.visibility = 'hidden'; 

                commentCount.innerHTML = 0;   

                recommendCount.innerHTML = 0;

            } else {   

                // get article from response   

                var article = responseBatch.Responses[0].Article;

                // get page elements   

                var commentCount = document.getElementById('articleCommentCount' + article.ArticleKey.Key);   

                var recommendCount = document.getElementById('articleRecommendCount' + article.ArticleKey.Key);

                // update page elements   

                commentCount.innerHTML = article.Comments.NumberOfComments;   

                recommendCount.innerHTML = article.Recommendations.NumberOfRecommendations;

				var isRecommended = article.Recommendations.CurrentUserHasRecommended;

				if(isRecommended == "True") {

					var recommendLink = document.getElementById('recommendlink' + article.ArticleKey.Key);

					recommendLink.innerHTML = "<span class='Article_Recommended'>Recommended</span>";

				}

				commentCount.style.visibility = 'visible';

				recommendCount.style.visibility = 'visible';

            }   

        }

		function recommendReview(key) {  
		
			var requestBatch = new RequestBatch();   

            var articleKey = new ArticleKey(key);   

            var recommendAction = new RecommendAction(articleKey);   

            requestBatch.AddToRequest(recommendAction);    

            requestBatch.BeginRequest(serverUrl, recommendationComplete);     

        }   

           

        function recommendationComplete(responseBatch) {
            if(responseBatch.Responses.length > 0) {

                submitRequest();
			}
			else {
				//alert('did not exist');
				updateArticle();	
			}

        }


		function updateArticle() {   

            // get form elements and page info   

            var articleKey = new ArticleKey(articleid);   

            var pageUrl = document.location.href;
			
			var section = new Section(sectionTitle);
			
			var categories = new Array();

  

            // create and send request   

            var requestBatch = new RequestBatch();               

            var updateAction = new UpdateArticleAction(articleKey, pageUrl, pageTitle, section);   

            requestBatch.AddToRequest(updateAction);    

            requestBatch.BeginRequest(serverUrl, articleUpdated);    

        }   

           

        function articleUpdated(responseBatch) {   

            if (responseBatch.Messages[0].Message == 'ok') {   
                  submitRequest();
				  //recommendReview(articleid);

            } 

        }
		
		function recommendReviewAbox(key) {

            var requestBatch = new RequestBatch();   

            var articleKey = new ArticleKey(key);   

            var recommendAction = new RecommendAction(articleKey);   

            requestBatch.AddToRequest(recommendAction);    

            requestBatch.BeginRequest(serverUrl, recommendationCompleteAbox); 

        }
		
		function recommendationCompleteAbox(responseBatch) { 

                	SubmitListRequest();

        }
		
		function recommendReviewList(key) {

            var requestBatch = new RequestBatch();   

            var articleKey = new ArticleKey(key);   

            var recommendAction = new RecommendAction(articleKey);   

            requestBatch.AddToRequest(recommendAction);    

            requestBatch.BeginRequest(serverUrl, recommendationCompleteList); 

        }   

           

        function recommendationCompleteList(responseBatch) { 

                	getRecentActivity();

        }
		
		function getRecentActivity() {
			var sections = new Array(new Section("All"));
			var categories = new Array(new Category("All"));
			var contributors = new Array(new UserTier("All"));
			var activity = new Activity("Commented");
			var age = 2;
			var numItemsToGet = 5;
			
			if(cacheMostCommentedRecommended) {
				renderRecentContent(cacheMostCommentedRecommended.ResponseBatch, 5);  				
			}
			else {
				var requestBatch = new RequestBatch();
				var discoveryAction = new DiscoverArticlesAction(sections, categories, contributors, activity, age, numItemsToGet);
				requestBatch.AddToRequest(discoveryAction);
				requestBatch.BeginRequest(serverUrl, renderRecentContent, 5);
			}
		}
		
		function renderRecentContent(responseBatch, numItemsToGet) { 
		       
             if (responseBatch.Responses.length >= 1) {
                 var discoveryAction = responseBatch.Responses[0].DiscoverArticlesAction;
				if(!numItemsToGet) {
					numItemsToGet = discoveryAction.DiscoveredArticles.length;
				}
				else if(numItemsToGet > discoveryAction.DiscoveredArticles.length) {
					numItemsToGet = discoveryAction.DiscoveredArticles.length;
				}

                 var recentList = document.getElementById('mostcommented_list');
			
				 if(recentList) {
                 	var recentHTML = "<ul>";  
                 	for (var i = 0; i < numItemsToGet; i++) {
                     	recentHTML += getArticleLink(discoveryAction.DiscoveredArticles[i]);  
                 	}  
				 	recentHTML += "</ul>";
                 	recentList.innerHTML = recentHTML;
				 }
             }  
         }
           
         function getArticleLink(article) {
			 
			 var hashes = article.PageUrl.split('#');
			 var commentLink = hashes[0]+"#slComments";

             var html = "<li><a href='" + article.PageUrl + "' class='article_list_title'>" + unescape(article.PageTitle) + "</a><br>";
			 html += "<span id='commentsummary'><a href='" + commentLink + "' class='Article_Comment'>Comments <span id='articleCommentCount' class='Article_Comment_Count'>" + article.Comments.NumberOfComments + "</span></a></span> | ";
			 
			 if(article.Recommendations.CurrentUserHasRecommended == "True") {
				 html += "<span id='recommendations'><span id='recommendlink'><span class='Article_Recommended'>Recommended</span></span><span id='articleRecommendCount' class='Article_Recommend_Count'>" + article.Recommendations.NumberOfRecommendations + "</span></span>";
				// html += "<span id='recommendations'><span id='recommendlink'><span class='Article_Recommended'><a href='" + article.PageUrl +"' class='Article_Recommend_Count'>Recommended</a></span></span><span id='articleRecommendCount' class='Article_Recommend_Count'>" + article.Recommendations.NumberOfRecommendations + "</span></span>";
			 }
			 else {
			 	
				html += "<span id='recommendations'><span id='recommendlink'><a href='" + hashes[0] + "'  class='Article_Recommend'>Recommend </a></span><span id='articleRecommendCount' class='Article_Recommend_Count'>" + article.Recommendations.NumberOfRecommendations + "</span></span>";
				
				//html += "<span id='recommendations'><span id='recommendlink'><a href=\"#\" onclick='recommendReviewList(\"" + article.ArticleKey.Key + "\")' class=\"Article_Recommend\">Recommend </a></span><span id='articleRecommendCount' class='Article_Recommend_Count'>" + article.Recommendations.NumberOfRecommendations + "</span></span>";
				
			 }
			 html += "</li>\n";
             return html;  
         }  
		 
		 function getMostCommentedArticle() {
			var sections = new Array(new Section("All"));
			var categories = new Array(new Category("All"));
			var contributors = new Array(new UserTier("All"));
			var activity = new Activity("Commented");
			var age = 2;
			var numItemsToGet = 5;

			var requestBatch = new RequestBatch();
			var discoveryAction = new DiscoverArticlesAction(sections, categories, contributors, activity, age, numItemsToGet);
			requestBatch.AddToRequest(discoveryAction);
			requestBatch.BeginRequest(serverUrl, renderMostCommentedArticle);
		}
		
		
		
		function renderMostCommentedArticle(responseBatch) {  
             if (responseBatch.Responses.length == 1) {
                 var discoveryAction = responseBatch.Responses[0].DiscoverArticlesAction;
                 var recentList = document.getElementById('mostcommented_list_article');  
				 if(recentList) {
                 	var recentHTML = ""; 
                 	for (var i = 0; i < discoveryAction.DiscoveredArticles.length; i++) {
						if(discoveryAction.DiscoveredArticles[i])
						{
                    	 recentHTML += getArticleLinkArticle(discoveryAction.DiscoveredArticles[i]);  
						}
                 	}  
                 	recentList.innerHTML = "<ul>" + recentHTML + "</ul>";
				 }
             }
         }  
           
         function getArticleLinkArticle(article) { 
		 	 
              if(unescape(article.PageTitle) == "null")
			  {				 
				 return '';
			  }
			  else
			  {			  
			     var html = "<li><a href='" + article.PageUrl + "'>" + unescape(article.PageTitle) + "</a>";
				 html += "</li>\n";
				 return html; 		  
			  }
         }
		 
		 function getMostRecommendedArticle() {
			var sections = new Array(new Section("All"));
			var categories = new Array(new Category("All"));
			var contributors = new Array(new UserTier("All"));
			var activity = new Activity("Recommended");
			var age = 2;
			var numItemsToGet = 5;
			
			var requestBatch = new RequestBatch();
			var discoveryAction = new DiscoverArticlesAction(sections, categories, contributors, activity, age, numItemsToGet);
			requestBatch.AddToRequest(discoveryAction);
			requestBatch.BeginRequest(serverUrl, renderMostRecommendedArticle);
		}
		
		function renderMostRecommendedArticle(responseBatch) {  
             if (responseBatch.Responses.length == 1) {
                 var discoveryAction = responseBatch.Responses[0].DiscoverArticlesAction;
                 var recentList = document.getElementById('mostrecommended_list_article');  
				 if(recentList) {
                 	var recentHTML = "";  
                 	for (var i = 0; i < discoveryAction.DiscoveredArticles.length; i++) {  
						if(discoveryAction.DiscoveredArticles[i])
						{
                     		recentHTML += getArticleLinkArticle(discoveryAction.DiscoveredArticles[i]);  
						}
                 	}  
                 	recentList.innerHTML = "<ul>" + recentHTML + "</ul>";  
				 }
             }  
         }
		 
		 var aboxMostCommented = new Array();
		 var aboxMostRecommended = new Array();
		 function getMostCommentedRecommendedArticleList(numItemsToGet) {
			 
			var sections = new Array(new Section("All"));
			var categories = new Array(new Category("All"));
			var contributors = new Array(new UserTier("All"));
			var commentactivity = new Activity("Commented");
			var recommendactivity = new Activity("Recommended");
			var age = 2;
			if(!numItemsToGet) {
				numItemsToGet = 5;
			}

			if(cacheMostCommentedRecommended) {
				renderMostCommentedArticle(cacheMostCommentedRecommended.ResponseBatch, numItemsToGet);
			}
			else {
				var requestBatch = new RequestBatch();
				var commentdiscoveryAction = new DiscoverArticlesAction(sections, categories, contributors, commentactivity, age, numItemsToGet);
				var recommendeddiscoveryAction = new DiscoverArticlesAction(sections, categories, contributors, recommendactivity, age, numItemsToGet);
				requestBatch.AddToRequest(commentdiscoveryAction);
				requestBatch.AddToRequest(recommendeddiscoveryAction);
				requestBatch.BeginRequest(serverUrl, renderMostCommentedArticle);
			}
			
		}
		
				            

		 
		 function getMostCommentedRecommendedArticleList2(numItemsToGet) {
			var sections = new Array(new Section("All"));
			var categories = new Array(new Category("All"));
			var contributors = new Array(new UserTier("All"));
			var commentactivity = new Activity("Commented");
			var recommendactivity = new Activity("Recommended");
			var age = 2;
			if(!numItemsToGet) {
				numItemsToGet = 3;
			}

			var requestBatch = new RequestBatch();
			var commentdiscoveryAction = new DiscoverArticlesAction(sections, categories, contributors, commentactivity, age, numItemsToGet);
			var recommendeddiscoveryAction = new DiscoverArticlesAction(sections, categories, contributors, recommendactivity, age, numItemsToGet);
			requestBatch.AddToRequest(commentdiscoveryAction);
			requestBatch.AddToRequest(recommendeddiscoveryAction);
			requestBatch.BeginRequest(serverUrl, renderMostCommentedArticle);
		}

		

		
		function renderMostCommentedArticle(responseBatch, numItemsToGet) {
             if (responseBatch.Responses.length >= 1) {
                 var discoveryAction = responseBatch.Responses[0].DiscoverArticlesAction;
				 if(!numItemsToGet) {
					numItemsToGet = 5;
				}
				if(numItemsToGet > discoveryAction.DiscoveredArticles.length) {
					numItemsToGet = discoveryAction.DiscoveredArticles.length;
				}
				
				 if(aboxMostCommented.length >= 1) {
					 for(var i = 0; i < aboxMostCommented.length; i++) {
						 var recentList = document.getElementById(aboxMostCommented[i]);  
						 if(recentList) {
                 		 	var recentHTML = ""; 
                 		 	for (var j = 0; j < numItemsToGet; j++) {
								if(discoveryAction.DiscoveredArticles[j])
								{
                     			  recentHTML += getArticleLinkArticle(discoveryAction.DiscoveredArticles[j]);  
								}
                 		 	}  
                 		 	recentList.innerHTML = "<ul>" + recentHTML + "</ul>";
						 }
					 }
				 }
				 else {
                 	var recentList = document.getElementById('mostcommented_list_article'); 
					if(recentList) {
                 		var recentHTML = ""; 
                 		for (var i = 0; i < numItemsToGet; i++) {
							if(discoveryAction.DiscoveredArticles[i])
							{
                     		  recentHTML += getArticleLinkArticle(discoveryAction.DiscoveredArticles[i]); 
							}
                 		}  
                 		recentList.innerHTML = "<ul>" + recentHTML + "</ul>";
					}
				 }
             }
			 if (responseBatch.Responses.length >= 2) {
				 var discoveryAction = responseBatch.Responses[1].DiscoverArticlesAction;
				 if(!numItemsToGet) {
					numItemsToGet = 5;
				}
				if(numItemsToGet > discoveryAction.DiscoveredArticles.length) {
					numItemsToGet = discoveryAction.DiscoveredArticles.length;
				}
				
				 if(aboxMostRecommended.length >= 1) {
					 for(var i = 0; i < aboxMostRecommended.length; i++) {
					 	var recentList = document.getElementById(aboxMostRecommended[i]);  
						if(recentList) {
                 			var recentHTML = "";  
                 			for (var j = 0; j < numItemsToGet; j++) { 
							   if(discoveryAction.DiscoveredArticles[j])
							   {
                     			recentHTML += getArticleLinkArticle(discoveryAction.DiscoveredArticles[j]);  
							   }
                 			}  
                 			recentList.innerHTML = "<ul>" + recentHTML + "</ul>";
						}
					 }
				 }
				 else {
                 	var recentList = document.getElementById('mostrecommended_list_article'); 
					if(recentList) {
                 		var recentHTML = "";  
                 		for (var i = 0; i < numItemsToGet; i++) { 
						   if(discoveryAction.DiscoveredArticles[i])
						   {
                     		recentHTML += getArticleLinkArticle(discoveryAction.DiscoveredArticles[i]);
						   }
                 		}  
                 		recentList.innerHTML = "<ul>" + recentHTML + "</ul>";
					}
				 }
			 } 
         }

				/*
				* Common function to process all responses in a batch
				* 
				* responseBatch - batch of items to process
				* numiItems     - array of integers identifying the maximum number
				*                 of items to display for each response in the batch
				*                 (max = 10)
				*                 numItems = [5,3];
				* divIds        - multidimensional array of divIds to put the response
				*                 source into. Each item in this list can either be a
				*                 string (a single element) or a list of strings
				*                 (indicating multiple elements) to receive the source
				*                 load into Recommended and skip Commented:
				*                 divIds = ['',recommendedDivs];
				*/
			function pluckProcessResponseBatch(responseBatch,responseType,numItems,divIds) {
				var loopCount=0;

				// Determine number of times to loop based on number of responses in batch and number of divIds
				if (responseBatch.Responses.length > divIds.length)
					loopCount= divIds.length;
				else
					loopCount= responseBatch.Responses.length;

				for (var i=0; i < loopCount; i++) {
					var renderAction = responseBatch.Responses[i]["Discover"+responseType+"Action"];
					var divId = divIds[i];
					var numItemsUsed = (renderAction["Discovered"+responseType].length < numItems[i]) ? renderAction["Discovered"+responseType].length : numItems[i];

					// generate content for div
					var out = "<ul>";
					for (var j = 0; j < numItemsUsed; j++) {  
						out += getArticleLinkArticle(renderAction["Discovered"+responseType][j]);  
					}
					out += "</ul>";

					//determine if divId is array of divIds. If so insert html (out) into each divId
					if (typeof(divId)=='string') {
						var docEl = document.getElementById(divId);
						if (docEl)
							docEl.innerHTML = out;
					} else {
						for (var k = 0; k < divId.length; k++) {  
							var docEl = document.getElementById(divId[k]);
							if (docEl)
								docEl.innerHTML = out;
						}
					}
				}
			}
		 
		 function renderMostCommentedArticle(responseBatch, numItemsToGet) {
                          
			    if (responseBatch.Responses.length >= 1) { 
                 var discoveryAction = responseBatch.Responses[0].DiscoverArticlesAction;
				 if(!numItemsToGet) {
					numItemsToGet = 5;
				}
				var numItemsToUse;
				if(numItemsToGet > discoveryAction.DiscoveredArticles.length)
					numItemsToUse = discoveryAction.DiscoveredArticles.length;
				else
					numItemsToUse = numItemsToGet;
				
				 if(aboxMostCommented.length >= 1) {
					 for(var i = 0; i < aboxMostCommented.length; i++) {
						 var recentList = document.getElementById(aboxMostCommented[i]);  
						 if(recentList) {
                 		 	var recentHTML = ""; 
                 		 	for (var j = 0; j < numItemsToUse; j++) { 
							   if(discoveryAction.DiscoveredArticles[j])
							   {
                     				recentHTML += getArticleLinkArticle(discoveryAction.DiscoveredArticles[j]);  
							   }
							}
                 		 	recentList.innerHTML = "<ul>" + recentHTML + "</ul>";
						 }
					 }
				 }
				 else {
                 	var recentList = document.getElementById('mostcommented_list_article'); 
					if(recentList) {
                 		var recentHTML = ""; 
                 		for (var i = 0; i < numItemsToUse; i++) {
							if(discoveryAction.DiscoveredArticles[i])
							{
                     		  recentHTML += getArticleLinkArticle(discoveryAction.DiscoveredArticles[i]);  
							}
                 		}  
                 		recentList.innerHTML = "<ul>" + recentHTML + "</ul>";
					}
				 }
             }
			 if (responseBatch.Responses.length >= 2) {
				 var discoveryAction = responseBatch.Responses[1].DiscoverArticlesAction;
				 if(!numItemsToGet) {
					numItemsToGet = 5;
				}
				if(numItemsToGet > discoveryAction.DiscoveredArticles.length)
					numItemsToUse = discoveryAction.DiscoveredArticles.length;
				else
					numItemsToUse = numItemsToGet;
				
				 if(aboxMostRecommended.length >= 1) {
					 for(var i = 0; i < aboxMostRecommended.length; i++) {
					 	var recentList = document.getElementById(aboxMostRecommended[i]);  
						if(recentList) {
                 			var recentHTML = "";  
                 			for (var j = 0; j < numItemsToUse; j++) { 
							   if(discoveryAction.DiscoveredArticles[j])
							   {
                     			  recentHTML += getArticleLinkArticle(discoveryAction.DiscoveredArticles[j]);  
							   }
                 			}  
                 			recentList.innerHTML = "<ul>" + recentHTML + "</ul>";
						}
					 }
				 } 
				 else {
                 	var recentList = document.getElementById('mostrecommended_list_article'); 
					if(recentList) {
                 		var recentHTML = "";  
                 		for (var i = 0; i < numItemsToGet; i++) { 
						  if(discoveryAction.DiscoveredArticles[i])
						  {
                     		recentHTML += getArticleLinkArticle(discoveryAction.DiscoveredArticles[i]);  
						  }
                 		}  
                 		recentList.innerHTML = "<ul>" + recentHTML + "</ul>";
					}
				 }
			 }
         }
		 
		 
		 
		 
		 
		 function isLoggedIn() {
			var ocCookies = document.cookie.split( ';' );
			var tempCookie = "";
			for(i=0; i < ocCookies.length; i++) {
				tempCookie = ocCookies[i].split('=');
				cookie_name = tempCookie[0].replace(/^\s+|\s+$/g, '');
				
				if(cookie_name == "at") {
					return true;
				}
			}
			return false;
		 }
		 
		 
		 function slLogout() {
			var cookie_date = new Date(2000, 01, 01);
			var ocCookies = document.cookie.split( ';' );
						var tempCookie = "";
			var domainName=window.document.domain;
			//alert(domainName);
            //var nameparts = domainName.split( '.' );
            //domainName=nameparts[1]+"."+nameparts[2];
			//alert(domainName);
			var found = false;
			for(i=0; i < ocCookies.length; i++) {
				tempCookie = ocCookies[i].split('=');
				cookie_name = tempCookie[0].replace(/^\s+|\s+$/g, '');
				
				if(cookie_name == "at" || cookie_name == "free_ak" || cookie_name == "free_prof" || cookie_name == "freeAuth") {
					document.cookie = cookie_name + "=;	expires=" + cookie_date.toGMTString() + "; path=/; domain=."+domainName+";";
					found = true;
				}
			}
			//if(found) location.reload(true); 
			if(found) location = "/";
		 }
		 
		 function changeWidgetLinks() {
			var commentsFrame = document.getElementById('commentsiframe');
			var login_text = "You must be logged in to contribute. <a href=\"javascript:parent.scroll(0,0);parent.show_login()\">Login</a> | <a href='javascript:parent.scroll(0,0);parent.show_registration()'>Register</a>";
			if(commentsFrame) {
				var sl_login_text = commentsFrame.contentWindow.document.getElementById('SiteLife_Login');
				if(sl_login_text) {
					sl_login_text.innerHTML = login_text;
				}
			}
			
			var messagesFrame = document.getElementById('messagesiframe');
			if(messagesFrame) {
				var sl_login_text = messagesFrame.contentWindow.document.getElementById('Messages_NewMessageHead');
				if(sl_login_text) {
					sl_login_text.innerHTML = login_text;
				}
			}
			
			var personaFrame = document.getElementById('personaprofileiframe');
			 if(personaFrame) {
				 //personaFrame.style.width = "600px";
				 var editLink = personaFrame.contentWindow.document.getElementById('ProfileEdit_SectionDescription_Link');
				 editLink.style.display = "none";
			 }
		 }
		 
		 function LoginPage() {
			var domainName=window.document.domain
			var login_link = "http://www." + domainName + "/sections/share/users/login";
			window.location.href = login_link;
		 }
		 
		 function RegPage() {
			var domainName=window.document.domain
			var reg_link = "http://www." + domainName + "/sections/share/users/register";
			window.location.href = reg_link;
		 }
		 
		 function changePluckLoginLinks() {
			if(!isLoggedIn()) {
			var login_link = "javascript:parent.LoginPage()";
			var reg_link = "javascript:parent.RegPage()";
			var commentsFrame = document.getElementById('commentsiframe');
			var login_text = "You must be logged in to contribute. <a href=\"" + login_link + "\">Login</a> | <a href='" + reg_link + "'>Register</a>";
			if(commentsFrame) {
				var sl_login_text = commentsFrame.contentWindow.document.getElementById('SiteLife_Login');
				if(sl_login_text) {
					sl_login_text.innerHTML = login_text;
				}
			}
			
			var messagesFrame = document.getElementById('messagesiframe');
			if(messagesFrame) {
				var sl_login_text = messagesFrame.contentWindow.document.getElementById('Messages_NewMessageHead');
				if(sl_login_text) {
					sl_login_text.innerHTML = login_text;
				}
			}
			
			var personaFrame = document.getElementById('personaprofileiframe');
			 if(personaFrame) {
				 //personaFrame.style.width = "600px";
				 var editLink = personaFrame.contentWindow.document.getElementById('ProfileEdit_SectionDescription_Link');
				 editLink.style.display = "none";
			 }
			 
			 	var login_btn = document.getElementById('CreateDiscussion1');
				var login_btn2 = document.getElementById('CreateDiscussion2');
				var reg_btn = document.getElementById('A1');
				var add_post_btn = document.getElementById('ForumDiscussionAddPost');
				if(login_btn) {
					login_btn.href = login_link;	
				}
				if(login_btn2) {
					login_btn2.href = login_link;	
				}
				if(reg_btn) {
					reg_btn.href = reg_link;
					reg_att = reg_btn.attributes;
					for(i=0;i<reg_att.length;i++) {
						if(reg_att[i].name == "onclick") {
							reg_att[i].value = reg_link;
						}
					}
				}
				if(add_post_btn) {
					add_post_btn.href = login_link;	
				}
			 
			}
		 }
		 
		 function changeForumLinks() {
			if(!isLoggedIn()) {
				var login_btn = document.getElementById('CreateDiscussion1');
				var login_btn2 = document.getElementById('CreateDiscussion2');
				var reg_btn = document.getElementById('A1');
				var add_post_btn = document.getElementById('ForumDiscussionAddPost');
				if(login_btn) {
					login_btn.href = "javascript:scroll(0,0);show_login();";	
				}
				if(login_btn2) {
					login_btn2.href = "javascript:scroll(0,0);show_login();";	
				}
				if(reg_btn) {
					reg_btn.href = "javascript:scroll(0,0);show_registration();";
					reg_att = reg_btn.attributes;
					for(i=0;i<reg_att.length;i++) {
						if(reg_att[i].name == "onclick") {
							reg_att[i].value = "scroll(0,0);show_registration();";
						}
					}
				}
				if(add_post_btn) {
					add_post_btn.href = "javascript:scroll(0,0);show_login();";	
				}
			}

		 }
		 
		 function createArticle(articleid, pageUrl, pageTitle, sectionTitle) { 

            // get form elements and page info   

            var articleKey = new ArticleKey(articleid);
			
			var section = new Section(sectionTitle);
			
			var categories = new Array();

            // create and send request   

            var requestBatch = new RequestBatch();               

            var updateAction = new UpdateArticleAction(articleKey, pageUrl, pageTitle, section);   

            requestBatch.AddToRequest(updateAction);    

            requestBatch.BeginRequest(serverUrl, articleCreated);    

        }   

	


           

        function articleCreated(responseBatch) {   
            if (responseBatch.Messages[0].Message == "ok") {   
            } 

        }
		
/****start of james edit 2/29 */ 
		// Fetch a cookie.
		function getCookieVal (offset) {
		  var endstr = document.cookie.indexOf (";", offset);
		  if (endstr == -1)
			endstr = document.cookie.length;
		  return unescape(document.cookie.substring(offset, endstr));
		}
		function GetCookie (name) {
		  var arg = name + "=";
		  var alen = arg.length;
		  var clen = document.cookie.length;
		  var i = 0;
		  while (i < clen) {
			var j = i + alen;
			if (document.cookie.substring(i, j) == arg)
			  return getCookieVal (j);
			i = document.cookie.indexOf(" ", i) + 1;
			if (i == 0)
			  break;
		  }
		  return null;
		}

		// read based off cookie
		function getUserInfoCookie() {
			uuId = "";
			var cookie_value = GetCookie('at');
			if(cookie_value)
			{
				var cookie_values = cookie_value.split('&'); 
				at = ''; 
				for(x = 0; x < cookie_values.length; x++)
				{
					if(cookie_values[x].indexOf('u=') >= 0)
					{
						userkey = cookie_values[x];
						
						uuId = userkey.substring(2,userkey.length); 
						break;
					}
				}
				//alert('logged in. userkey = ' + userkey);
			}
			//else
				//alert('not logged in ');
				
			
			if(uuId != "") {
				var userKey = new UserKey(uuId);
				var requestBatch = new RequestBatch();
				requestBatch.AddToRequest(userKey);
				requestBatch.BeginRequest(serverUrl, renderUserData);
			}
		}

/*****/
		function getUserInfo(uuId) {
			if(uuId != "" && uuId != "anonymous") {
				var userKey = new UserKey(uuId);
				var requestBatch = new RequestBatch();
				requestBatch.AddToRequest(userKey);
				requestBatch.BeginRequest(serverUrl, renderUserData);
			}
		}
		 
		function renderUserData(responseBatch) {
			if(responseBatch.Responses.length != 0) {
				var user = responseBatch.Responses[0].User;
				
				if(user.UserKey.Key != "anonymous") {
				
				var status_links = document.getElementById('status_links');
				var user_messages = document.getElementById('user_messages');
				var avatar = document.getElementById('status_avatar');
				var StatusBoxAvatar = document.getElementById('StatusBoxAvatar');
				var BillboardAvatarTabImg = document.getElementById('BillboardAvatarTabImg');
				var you_image = document.getElementById('you_image');
				var status_box_logged_in = document.getElementById('status_box_logged_in');
				var status_box_logged_out = document.getElementById('status_box_logged_out');
				var join_link = document.getElementById('SitelifeJoin');
				var login_link = document.getElementById('SitelifeLogin');
				var buttons = document.getElementById('BillboardButtons');
				
				//var AvatarTabImg = document.getElementById('AvatarTabImg');
				//AvatarTabImg.innerHTML = '<a href=/share/profiles/?plckPersonaPage=PersonaHome&slid='+ user.UserKey.Key + '&plckUserId=' + user.UserKey.Key + '> <img src='+user.AvatarPhotoUrl+' id=status_avatar border=0 height=44 width=44 /></a>'; 
				
				if(document.getElementById('StatusBoxHelp'))
				{
				   var StatusBoxHelp = document.getElementById('StatusBoxHelp');
				   StatusBoxHelp.style.display = "none";
				}
				
				
				status_box_logged_out.style.display = "none";
				status_box_logged_in.style.display = "block";
				
				if(join_link) {
					join_link.style.display = "none";
				}
				if(login_link) {
					login_link.style.display = "none";
				}
				if(buttons) {
					buttons.style.display = "none";
				}
				
				var status_html = "Welcome, " + user.DisplayName + "<br>";
				status_html += "<a href='/share/profiles/?plckPersonaPage=PersonaHome&slid=" + user.UserKey.Key + "&plckUserId=" + user.UserKey.Key + "'>My Profile</a> | <a href='javascript:slLogout()'>Logout</a><br>";
				var message_html = user.NumberOfMessages + " messages";
				
				status_links.innerHTML = status_html;
				user_messages.innerHTML = message_html;
				//avatar.src = user.AvatarPhotoUrl;
				
				StatusBoxAvatar.innerHTML = '<a href=/share/profiles/?plckPersonaPage=PersonaHome&slid='+ user.UserKey.Key + '&plckUserId=' + user.UserKey.Key + '> <img src='+user.AvatarPhotoUrl+' id=status_avatar border=0 height=40 width=40 /></a>';
				
				BillboardAvatarTabImg.innerHTML = '<a href=/share/profiles/?plckPersonaPage=PersonaHome&slid='+ user.UserKey.Key + '&plckUserId=' + user.UserKey.Key + '> <img src='+user.AvatarPhotoUrl+' id=you_image border=0 height=44 width=44 /></a>';
				
				if(document.getElementById('AvatarTabImg'))
				{
					
				  //var AvatarTabImg = document.getElementById('AvatarTabImg');
				  //AvatarTabImg.innerHTML = '<a href=/share/profiles/?plckPersonaPage=PersonaHome&slid='+ user.UserKey.Key + '&plckUserId=' + user.UserKey.Key + '> <img src='+user.AvatarPhotoUrl+' id=you_image border=0 height=44 width=44 /></a>';
				}
				
				//you_image.src = user.AvatarPhotoUrl;
				
				}
				
			}
		}
		
		var aboxArticles = new Array();
		function SubmitListRequest() {
			
			var requestBatch = new RequestBatch();
			
			for(var i=0;i<aboxArticles.length;i++) {
				requestBatch.AddToRequest(new ArticleKey(aboxArticles[i]));
			}
			
			requestBatch.BeginRequest(serverUrl, renderArticleList); 
		}
		
		function renderArticleList(responseBatch) { 

            if (responseBatch.Responses.length == 0) {    

				var commentCount = document.getElementById('articleCommentCount' + articleid);   

                var recommendCount = document.getElementById('articleRecommendCount' + articleid);   

                // update page elements  

				commentCount.style.visibility = 'hidden';

				recommendCount.style.visibility = 'hidden'; 

                commentCount.innerHTML = 0;   

                recommendCount.innerHTML = 0;

            } else {   
			
				for(var i=0;i<responseBatch.Responses.length;i++) {

                // get article from response   

                var article = responseBatch.Responses[i].Article;

                // get page elements   

                var commentCount = document.getElementById('articleCommentCount' + article.ArticleKey.Key);   

                var recommendCount = document.getElementById('articleRecommendCount' + article.ArticleKey.Key);

                // update page elements   

                commentCount.innerHTML = article.Comments.NumberOfComments;   

                recommendCount.innerHTML = article.Recommendations.NumberOfRecommendations;

				var isRecommended = article.Recommendations.CurrentUserHasRecommended;

				if(isRecommended == "True") {

					var recommendLink = document.getElementById('recommendlink' + article.ArticleKey.Key);

					recommendLink.innerHTML = "<span class='Article_Recommended'>Recommended</span>";

				}

				commentCount.style.visibility = 'visible';

				recommendCount.style.visibility = 'visible';
				
				}

            }  
			
			for(var i=0;i<aboxArticles.length;i++) {
				var commentCountcheck = document.getElementById('articleCommentCount' + aboxArticles[i]);
				var recommendCountcheck = document.getElementById('articleRecommendCount' + aboxArticles[i]);
				
				if(commentCountcheck) {
					if(commentCountcheck.innerHTML == "") {
						commentCountcheck.innerHTML = "0";
					}
				}
				if(recommendCountcheck) {
					if(recommendCountcheck.innerHTML == "") {
						recommendCountcheck.innerHTML = "0";
					}
				}
			}

        }
		
		function combineAboxRecommendedCommentedUser() {
			var requestBatch = new RequestBatch();
			
			// abox articles
			for(var i=0;i<aboxArticles.length;i++) {
				requestBatch.AddToRequest(new ArticleKey(aboxArticles[i]));
			} // end abox articles
			
			// most commented and recommended
			var sections = new Array(new Section("All"));
			var categories = new Array(new Category("All"));
			var contributors = new Array(new UserTier("All"));
			var commentactivity = new Activity("Commented");
			var recommendactivity = new Activity("Recommended");
			var age = 2;
			var numItemsToGet = 5;

			var commentdiscoveryAction = new DiscoverArticlesAction(sections, categories, contributors, commentactivity, age, numItemsToGet);
			var recommendeddiscoveryAction = new DiscoverArticlesAction(sections, categories, contributors, recommendactivity, age, numItemsToGet);
			requestBatch.AddToRequest(commentdiscoveryAction);
			requestBatch.AddToRequest(recommendeddiscoveryAction);
			// end most commented and recommended
			
			
			requestBatch.BeginRequest(serverUrl, renderMostCommentedArticle);
			
			
			

			requestBatch.BeginRequest(serverUrl, renderArticleList);
		}
		
		function combineAboxRecommendedCommentedUserRender(responseBatch) {
			if (responseBatch.Responses.length == 0) {    

				var commentCount = document.getElementById('articleCommentCount' + articleid);   

                var recommendCount = document.getElementById('articleRecommendCount' + articleid);   

                // update page elements  

				commentCount.style.visibility = 'hidden';

				recommendCount.style.visibility = 'hidden'; 

                commentCount.innerHTML = 0;   

                recommendCount.innerHTML = 0;

            } else {   
			
				for(var i=0;i<responseBatch.Responses.length;i++) {

                // get article from response   

                var article = responseBatch.Responses[i].Article;

                // get page elements   

                var commentCount = document.getElementById('articleCommentCount' + article.ArticleKey.Key);   

                var recommendCount = document.getElementById('articleRecommendCount' + article.ArticleKey.Key);

                // update page elements   

                commentCount.innerHTML = article.Comments.NumberOfComments;   

                recommendCount.innerHTML = article.Recommendations.NumberOfRecommendations;

				var isRecommended = article.Recommendations.CurrentUserHasRecommended;

				if(isRecommended == "True") {

					var recommendLink = document.getElementById('recommendlink' + article.ArticleKey.Key);

					recommendLink.innerHTML = "<span class='Article_Recommended'>Recommended</span>";

				}

				commentCount.style.visibility = 'visible';

				recommendCount.style.visibility = 'visible';
				
				}

            }   
		}
		
		function popUp(URL) {
			day = new Date();
			id = day.getTime();
			eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=700,height=300,left = 390,top = 312');");
		}
		
		function billboardNav(linktype) {
			var linkbox = document.getElementById(linktype);
			location.href = linkbox.value;
		}
		
		function getCookieUUID() {
			var ocCookies = document.cookie.split( ';' );
			var tempCookie = "";
			var tempCookie2 = "";
			var tempCookie3 = "";
			var uuid = "";
			for(i=0; i < ocCookies.length; i++) {
				tempCookie = ocCookies[i].split('=');
				cookie_name = tempCookie[0].replace(/^\s+|\s+$/g, '');
				
				if(cookie_name == "at") {
					var atcookie = tempCookie[1];
					tempCookie2 = atcookie.split("%26");
					for(j=0; j < tempCookie2.length; j++) {
						tempCookie3 = tempCookie2[j].split("%3D");
						if(tempCookie3[0] == "u") {
							uuid = tempCookie3[1];
						}
					}
				}
			}
			return uuid;
			
		}
		
		var showRecommendedOnly = false;
		var orderby = 'TimeStampDescending';
		var oncommentsPage = 1;
		var pstTimeDifference = 0;
		
		var vars = [], hash;
		var vars = [], cleanHash;
		var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
		
		for(var i = 0; i < hashes.length; i++)
		{ 
			hash = hashes[i].split('='); 
			
			if(hash[0] == "orderby" || hash[0] == "oncommentsPage" || hash[0] == "showRecommendedOnly")
			  var cleanHash = hash[1].split('#');   //Remove #slComments from the value 	  
			
			if(hash[0] == "orderby")    	
				var orderby = cleanHash[0]; //var orderby = hash[1];
			
			if(hash[0] == "oncommentsPage")
				var oncommentsPage = cleanHash[0];
							
			if(hash[0] == "showRecommendedOnly")
			{	  
			  if(cleanHash[0] == 0)
				   var showRecommendedOnly = false;
			  else
				    var showRecommendedOnly = true;			 
			}
		}
		
		function pullComments(orderby, showRecommendedOnly, oncommentsPage, timeDifference, lang)
		{
			var windowLocation = window.location.href.split("?");
			var showAll = 'Show All Comments';
			var showRecommended = 'Show Recommended Comments Only';
			
			if (lang == 'es') {
				showAll = 'Ver todos comentarios';
				showRecommended = 'Ver s&oacute;lo comentarios recomendados';
			}
			
			//alert(timeDifference);
			pstTimeDifference = timeDifference;
			
			if(showRecommendedOnly == 1)
			    var showRecommendedOnly = true;
			else
			    var showRecommendedOnly = false; 
			
			 
			var showreconlylink = document.getElementById('showreconly');
			if(showreconlylink) {
				if(showRecommendedOnly)
				{			 
					showreconlylink.innerHTML = showAll;
				}
				else
				{
					showreconlylink.innerHTML = showRecommended;
				}
			}
			var requestBatch = new RequestBatch();  
			var articleKey = new ArticleKey(articleid);  
			var commentPage = new CommentPage(articleKey, 10, oncommentsPage, orderby);          
			requestBatch.AddToRequest(commentPage);   
			requestBatch.BeginRequest(serverUrl, renderCommentPage); 
		}
		
		
		
		
		function renderCommentPage(responseBatch)
		{
			
			var windowLocation = window.location.href.split("?");
			windowLocation[0] = windowLocation[0].replace(/#.+$/, '');
			var nextPage = ((oncommentsPage * 1) + 1) ;
			var prePage = ((oncommentsPage) - 1) ;
			
			if (responseBatch.Responses.length == 0)
			{  
				//alert('Article Not Found.');  
			}
			else
			{  
				var commentBlock = document.getElementById('slrenderedComments'); 
				var commentBlockHtml = "<div id='Comments_OuterContainer' class='Comments_Container'><table class='Comments_Table' cellspacing='0' cellpadding='0'>";  
				var commentPage = responseBatch.Responses[0].CommentPage;  
				var total_comments = commentPage.NumberOfComments;
				
				var uuid = getCookieUUID();
				for(var i=0; i < commentPage.Comments.length; i++) 
				{  
					if((showRecommendedOnly && commentPage.Comments[i].NumberOfRecommendations > 0) || !showRecommendedOnly)
					{
						if((commentPage.Comments[i].Author.IsBlocked == "False" && commentPage.Comments[i].AbuseReportCount < 4) || (commentPage.Comments[i].Author.IsBlocked == "True" && commentPage.Comments[i].Author.UserKey.Key == uuid))
						{
							commentBlockHtml += getCommentHtml(commentPage.Comments[i]);
							
						}
					}
				}
				
				commentBlockHtml += "</table><div class='commentPagination'>";
				var numPages = Math.ceil(total_comments / 10);
				//alert("pages="+numPages);
				
				if(showRecommendedOnly)
					showRecommendedOnly = 1;
				else
				    showRecommendedOnly = 0; 
			
				//alert(showRecommendedOnly);
				
					
				if(numPages > 1 && oncommentsPage != 1)
				{
					commentBlockHtml += ' <a href='+windowLocation[0]+'?orderby='+orderby+'&showRecommendedOnly='+showRecommendedOnly+'&oncommentsPage=1#slComments>&lt;&lt;First</a> |';
					
					commentBlockHtml += ' <a href='+windowLocation[0]+'?orderby='+orderby+'&showRecommendedOnly='+showRecommendedOnly+'&oncommentsPage='+prePage+'#slComments> &lt;Prev </a> |';
				}
				
				for(var j=1; j <= numPages; j++)
				{
					if(j == oncommentsPage)
					{
						commentBlockHtml += " " + j + " ";	
					}
					else
					{				
						commentBlockHtml += ' <a href='+windowLocation[0]+'?orderby='+orderby+'&showRecommendedOnly='+showRecommendedOnly+'&oncommentsPage='+j+'#slComments>' + j + '</a>';
						
					}
				}
				
				if(numPages > 1 && oncommentsPage != numPages)
				{			
					commentBlockHtml += ' | <a href='+windowLocation[0]+'?orderby='+orderby+'&showRecommendedOnly='+showRecommendedOnly+'&oncommentsPage='+nextPage+'#slComments>Next&gt; </a> |';
					commentBlockHtml += ' <a href='+windowLocation[0]+'?orderby='+orderby+'&showRecommendedOnly='+showRecommendedOnly+'&oncommentsPage='+numPages+'#slComments> Last&gt;&gt;</a>';
				}
				
				commentBlockHtml += "</div></div>";
				commentBlock.innerHTML = commentBlockHtml;  
			}  
		} 
	
   function getDays(month)
   {
	  var monthAry = new Array();
	  monthAry[1] = 31;
	  monthAry[2] = 28;
	  monthAry[3] = 31;
	  monthAry[4] = 30;
	  monthAry[5] = 31;
	  monthAry[6] = 30;
	  monthAry[7] = 31;
	  monthAry[8] = 31;
	  monthAry[9] = 30;
	  monthAry[10] = 31;
	  monthAry[11] = 30;
	  monthAry[12] = 31;
	  
	  return monthAry[month];	  
   }
	
 /*--------------------------For TimeStamp-------------------------------------*/
 function y2k(number) { return (number < 1000) ? number + 1900 : number; }
 
	function formatTimeStamp(dateStr)
	{
		//alert("date="+dateStr);
		
		var datesplit = dateStr.split(" ");
		var dateAry = datesplit[0].split("/");
		var timeAry = datesplit[1].split(":");
		
		var ampm    = datesplit[2];
		var year = dateAry[2];
		var month = dateAry[0];
		var day = dateAry[1];
		var hour = timeAry[0];
		var minute = timeAry[1];
		var sec = timeAry[2];
		
		var newhour = (hour*1) + (pstTimeDifference*1);
		
		if(newhour > 12)
		{
		   newhour = newhour - 12;
		   var newampm = (ampm == "AM") ? "PM" : "AM";
		   
		   if(ampm == "PM")
		   {
				 day = (day*1) + 1;
				 var daysinmonth = getDays(month);
				  if(day > daysinmonth)
				  {
					 month = (month*1) + 1;  
					 day = 1;
					 if(month > 12)
					 {
						 month = 1;
						 year = (year*1) + 1;
					 }
				  }						  
		    }
			
		  var newDate = month+"/"+day+"/"+year+" "+newhour+":"+minute+":"+sec+" "+newampm;
		}
		else
		{
			var newDate = month+"/"+day+"/"+year+" "+newhour+":"+minute+":"+sec+" "+ampm;
		}
				
		return newDate;
		
		/*		
		var date = new Date(dateStr);		
		var difference = pstTimeDifference;		
		
		var ampmFlag = "AM";		

		var dates = new Date(Date.UTC(y2k(date.getYear()),date.getMonth(),date.getDate(),date.getHours(),date.getMinutes(),date.getSeconds()) + 8*60*60*1000 + (difference)*60*60*1000);
				
		var hrs = dates.getHours();
		
		if(hrs > 12)
  		{
    		hrs = (hrs-12);
			ampmFlag = "PM";	
  		}
  
  		var minutes = (dates.getMinutes() < 10) ? "0"+dates.getMinutes() : dates.getMinutes();
		var secs    = (dates.getSeconds() < 10) ? "0"+dates.getSeconds() : dates.getSeconds();
		
		var finalDate = (dates.getMonth()+1)+"/"+dates.getDate()+"/"+dates.getFullYear()+"&nbsp;"+hrs+":"+minutes+":"+secs+"&nbsp;"+ampmFlag; 
		
		return finalDate;
		*/
	}
 
 
 /*----------------------------------------------------------------------------*/		
		
		
          
		function getCommentHtml(comment) {
			var html = "";
			html += '<tr class="Comments_TableRowColor"><td class="Comments_UserImage">';
			html += '<a href="/share/profiles/?slid=' + comment.Author.UserKey.Key + '&plckUserId=' + comment.Author.UserKey.Key + '">';
			html += '<img src="' + comment.Author.AvatarPhotoUrl + '" border="0"></a>';
			html += '</td><td class="Comments_TableRight"><div class="Comments_From">';
			html += '<a href="/share/profiles/?slid=' + comment.Author.UserKey.Key + '&plckUserId=' + comment.Author.UserKey.Key + '">';
			html += comment.Author.DisplayName + '</a> wrote:</div>';
			html += '<div id="CommentBody" class="Comments_CommentText">' + comment.CommentBody + '</div>';
			
			
			
			var formatedDate = formatTimeStamp(comment.PostedAtTime);
			
						
			
			//html += '<div class="Comments_NestedDate">' + comment.PostedAtTime + '</div>';			
			html += '<div class="Comments_NestedDate">' + formatedDate + '</div>';			
			
			
			html += '<table class="Comments_NestedTable" cellspacing="0" cellpadding="0"><tr>';
			html += '<td class="Comments_NestedRecommend">';
			if(comment.CurrentUserHasRecommended == "True") {
				html += '<div id="recommend:' + comment.CommentKey.Key + '">';
				html += '<div style="display: inline;"><div class="Recommend_Container">';
				
				html += '<span class="SiteLife_Recommended">Recommended (' + comment.NumberOfRecommendations + ')</span></div></div></div>';
			}
			else {
				html += '<div id="recommend:' + comment.CommentKey.Key + '">';
				html += '<a class="SiteLife_Recommend" onclick="return gSiteLife.PostRecommendation(';
				html += "'Comment', '" + comment.CommentKey.Key + "', 'recommend:" + comment.CommentKey.Key + "', document.title);";
				html += '" href="#none">Recommend</a>(' + comment.NumberOfRecommendations + ')</div>';
			}
			html += '</td><td class="Comments_NestedReport">';
			if(comment.CurrentUserHasReportedAbuse == "True") {
				html += '<div id="rpt_' + comment.CommentKey.Key + '"><div style="display: inline;">';
				html += '<span class="SiteLife_Reported">Reported</span></div></div>';
			}
			else {
				html += '<div id="rpt_' + comment.CommentKey.Key + '"><span>';
				html += '<a id="' + comment.CommentKey.Key + '_RptAbuse" class="SiteLife_ReportAbuse" onclick="ShowReportAbuse(event,document.URL,gSiteLife.__baseUrl + \'/AbuseReport/ReportAbuse?plckElementId=rpt_' + comment.CommentKey.Key + '&plckTargetKey=' + comment.CommentKey.Key + '&plckTargetKeyType=Comment\');';
				html += 'return false;" href="#none">Report Abuse</a></span></div>';
			}
			html += '</td></tr></table></td></tr>';
			return html;  
		}
		
		function getMostRecentPhotos(numPhotos) {
			if(!numPhotos) {
				numPhotos = 5;
			}
			
			var recentPhotos = document.getElementById('recent_list_photos');  
				
			if(cacheMostRecentPhotos) {
				var photoHtml = '<div class="Summary_Container">';
				photoHtml += '<table class="Summary_PhotoTable" cellspacing="0" cellpadding="0"><tbody>';
				photoHtml += createPhotoHtml(cacheMostRecentPhotos.ResponseBatch, numPhotos);
				photoHtml += '</tbody></table></div>';
				
                recentPhotos.innerHTML = photoHtml;  
				
			}
			
		}
		
		function createPhotoHtml(ResponseBatch, numPhotos) {
			discoveredContent = ResponseBatch.Responses[0].DiscoverContentAction.DiscoveredContent;
			if(numPhotos > discoveredContent.length) {
				numPhotos = discoveredContent.length;
			}
			var html = "";
			for(var i = 0; i < numPhotos; i++) {
				if(discoveredContent[i].IsPendingApproval == "False" && discoveredContent[i].Author.IsBlocked == "False") {
					html += '<tr><td class="Summary_PhotoTableLeft">';
					html += '<a href="' + discoveredContent[i].PhotoUrl + '">';
					html += '<img src="' + discoveredContent[i].Image.Small + '" border="0"></a></td>';
					html += '<td class="Summary_PhotoTableRight">';
					html += '<div class="Summary_PhotoTitle">';
					html += '<a href="' + discoveredContent[i].PhotoUrl + '">' + discoveredContent[i].Title + '</a></div>';
					//html += '<div class="Summary_PhotoIn">';
					//html += 'In: <a href="/share/gallery?plckGalleryId=' + discoveredContent[i].GalleryKey.Key + '">';
					html += '<div class="Summary_PhotoBy">';
					html += 'By: <a href="/share/profiles/?slid=' + discoveredContent[i].Author.UserKey.Key + '&plckUserId=' + discoveredContent[i].Author.UserKey.Key + '">';
					html += discoveredContent[i].Author.DisplayName + '</a></div>';
				}
				else {
					numPhotos++;	
				}
			}
			return html;
		}
		
		function getBillboardLinks() {
			
			if(document.getElementById('photo1link'))
				var photo1link = document.getElementById('photo1link');
				
			if(document.getElementById('photo2link'))	
				var photo2link = document.getElementById('photo2link');
				
			if(document.getElementById('photo3link'))		
				var photo3link = document.getElementById('photo3link');
				
			if(document.getElementById('photo1img'))	
				var photo1img = document.getElementById('photo1img');
			
			if(document.getElementById('photo2img'))	
				var photo2img = document.getElementById('photo2img');
				
			if(document.getElementById('photo3img'))	
				var photo3img = document.getElementById('photo3img');
				
			if(cacheMostRecentPhotos) {
				discoveredContent = cacheMostRecentPhotos.ResponseBatch.Responses[0].DiscoverContentAction.DiscoveredContent;
                
                var numSet = 0;
                for(var i = 0; i < discoveredContent.length; i++) {
                	if(discoveredContent[i].IsPendingApproval == "False" && discoveredContent[i].Author.IsBlocked == "False" && numSet != 3) {
                    	if(numSet == 0) {
							if(photo1link)
							{
								photo1link.href = discoveredContent[0].PhotoUrl;
								photo1img.src = discoveredContent[0].Image.Small;
								numSet++;
							}
                        }
                        else if(numSet == 1) {
							if(photo2link)
							{
								photo2link.href = discoveredContent[1].PhotoUrl;
								photo2img.src = discoveredContent[1].Image.Small;
								numSet++;
							}
                        }
                        else if(numSet == 2) {
							if(photo3link)
							{
								photo3link.href = discoveredContent[2].PhotoUrl;
								photo3img.src = discoveredContent[2].Image.Small;
								numSet++;
							}
                        }
                    }
                }
			}
			else {
				var searchSections = new Array();  
				searchSections[0] = new Section("All");  
 
				var searchCategories = new Array();  
				searchCategories[0] = new Category("All");  

				var activityDisco = new Activity("Recent");  
				var contentType = new ContentType("PublicPhoto");  
				var limitToContributorsDisco = new Array();  
				limitToContributorsDisco[1] = new UserTier("All");  
				var age = 15;  
				var maximumNumberOfDiscoveries = 10;  

				var requestBatch = new RequestBatch();  
				var discoveryAction = new DiscoverContentAction(  
					searchSections,  
					searchCategories,  
					limitToContributorsDisco,  
					activityDisco,  
					contentType,  
					age,  
					maximumNumberOfDiscoveries);  

				requestBatch.AddToRequest(discoveryAction);  
				requestBatch.BeginRequest(serverUrl, renderBillboardLinks);	
			}
		}
		
		function renderBillboardLinks(responseBatch) {
			if (responseBatch.Responses.length >= 1) {
				
			if(document.getElementById('photo1link'))
				var photo1link = document.getElementById('photo1link');
				
			if(document.getElementById('photo2link'))	
				var photo2link = document.getElementById('photo2link');
				
			if(document.getElementById('photo3link'))		
				var photo3link = document.getElementById('photo3link');
				
			if(document.getElementById('photo1img'))	
				var photo1img = document.getElementById('photo1img');
			
			if(document.getElementById('photo2img'))	
				var photo2img = document.getElementById('photo2img');
				
			if(document.getElementById('photo3img'))	
				var photo3img = document.getElementById('photo3img');
				
				var discoveredContent = responseBatch.Responses[0].DiscoverContentAction.DiscoveredContent;
				var numSet = 0;
                for(var i = 0; i < discoveredContent.length; i++) {
                	if(discoveredContent[i].IsPendingApproval == "False" && discoveredContent[i].Author.IsBlocked == "False" && numSet != 3) {
                    	if(numSet == 0) {
							if(photo1link)
							{
								photo1link.href = discoveredContent[0].PhotoUrl;
								photo1img.src = discoveredContent[0].Image.Small;
								numSet++;
							}
                        }
                        else if(numSet == 1) {
							if(photo2link)
							{
								photo2link.href = discoveredContent[1].PhotoUrl;
								photo2img.src = discoveredContent[1].Image.Small;
								numSet++;
							}
                        }
                        else if(numSet == 2) {
							if(photo3link)
							{
								photo3link.href = discoveredContent[2].PhotoUrl;
								photo3img.src = discoveredContent[2].Image.Small;
								numSet++;
							}
                        }
                    }
                }
			}
		}
		
		function getMostRecommendedPhotos(numPhotos) {
			if(!numPhotos) {
				numPhotos = 5;
			}
			
			var recommendedPhotos = document.getElementById('mostrecommended_list_photos');  
				
			if(cacheMostRecommendedPhotos) {
				var photoHtml = '<div class="Summary_Container">';
				photoHtml += '<table class="Summary_PhotoTable" cellspacing="0" cellpadding="0"><tbody>';
				photoHtml += createPhotoHtml(cacheMostRecommendedPhotos.ResponseBatch, numPhotos);
				photoHtml += '</tbody></table></div>';
				
                recommendedPhotos.innerHTML = photoHtml;  
			}
		}
		
		
var defaultEmptyOK = false;
var whitespace = " \t\n\r"; 
var alreadySubmitted = false;
var EMAIL = "email";
var EMAIL_MSG = "Please enter a valid email address.";
var USER_NAME = "userName";
var USER_NAME_MSG = "Please enter a username that is at least 6 characters long\nand contains only letters and numbers.";
var PASSWORD = "password";
var PASSWORD_MSG = "Please enter a password that is at least 6 characters long\ncontaining only letters and numbers.";
var PASSWORD2 = "password2";
var PASSWORD2_MSG = "Your password entries must match, please re-enter.";
var GENDER = "gender";
var GENDER_MSG = "Please select your gender.";
var BIRTHYEAR = "birthYear";
var BIRTHYEAR_MSG = "Please enter a valid year of birth. You must be at least 13 years of age to register.";
var TERMS = "submit";
var TERMS_MSG = "You must agree to the user agreement terms to register.";

errorMsgArr = new Array();
errorMsgArr[EMAIL] = EMAIL_MSG;
errorMsgArr[USER_NAME] = USER_NAME_MSG;
errorMsgArr[PASSWORD] = PASSWORD_MSG;
errorMsgArr[PASSWORD2] = PASSWORD2_MSG;
errorMsgArr[GENDER] = GENDER_MSG;
errorMsgArr[BIRTHYEAR] = BIRTHYEAR_MSG;
errorMsgArr[TERMS] = TERMS_MSG;

function trim(str) {
  	while (str.substring(0,1) == ' ') str = str.substring(1,str.length);
	while (str.substring(str.length-1,str.length) == ' ') str = str.substring(0,str.length-1);
	return str;
}
function isWhitespace (s) {
	var i;
	if (isEmpty(s)) return true;
	for (i = 0; i < s.length; i++) {
		var c = s.charAt(i);
		if (whitespace.indexOf(c) == -1) return false;
	}
	return true;
}
function isEmpty(s) {
	return ((s == null) || (s.length == 0))
}


function validateNewOnlineOnly(form) {
	
	
	if(!isValidUserName(form.userName.value)) {
		alert(errorMsgArr[USER_NAME]); form.userName.focus();
		return false;
	}
	if(isWhitespace(form.password.value)) {
		alert(errorMsgArr[PASSWORD]); form.password.focus();
		return false;
	}	
	if(isWhitespace(form.password2.value)) {
		alert("Please confirm password"); 
		form.password2.focus();
		return false;
	}	
	if(form.password.value!=form.password2.value) {
		alert(errorMsgArr[PASSWORD2]); form.password2.focus();
		return false;
	}	
	if(!isValidUserName(form.password.value)) {
		alert(errorMsgArr[PASSWORD]); 
		form.password.focus();
		return false;
	}
	if(!isValidZipCode(form.zipCode.value)) {
		alert("Please enter a valid zip code"); 
		form.password.focus();
		return false;
	}
	
	if(!isValidEmail(form.email.value)) {
		alert(errorMsgArr[EMAIL]);
		form.email.focus();
		return false;
	}
	
	if(!isValidBirthYear(form.birthYear.value)) {
		alert(errorMsgArr[BIRTHYEAR]);
		form.birthYear.focus();
		return false;
	}
	
	if(!validateRadioButton(form.gender)) {
		alert(errorMsgArr[GENDER]);
		return false;
	}
	
	if(form.submit.checked == false) {
		alert(errorMsgArr[TERMS]);
		return false;
	}
	
	return true;
}


function isValidEmail(email) {
	if(isWhitespace(email)) return false;
	email = trim(email);
	var reg1 = /\s/;
	if(reg1.test(email)) return false;
	var reg2 = /^.+@.+\.[a-zA-Z]+/;
	if(reg2.test(email)) return true;
	return false;
}
function isValidDiscusNum(discus) {
	if(isWhitespace(discus)) return false;
	discus = trim(discus);
	var reg1 = /\D/;
	return(!reg1.test(discus));
}
function isValidUserName(userName) {
	if(isWhitespace(userName)) return false;
	userName = trim(userName);
	var reg1 = /\s/;
	if(reg1.test(userName)) return false;
	var reg2 = /\W/;
	if(reg2.test(userName)) return false;
	if(userName.length<6) return false;	
	return true;
}

function isValidZipCode(userName) {
	if(isWhitespace(userName)) return false;
	userName = trim(userName);
	var reg1 = /\s/;
	if(reg1.test(userName)) return false;
	var reg2 = /\W/;
	if(reg2.test(userName)) return false;
	if(userName.length!=5) return false;	
	return true;
}
function isValidBirthYear(birthYear) {
	if(isWhitespace(birthYear)) return false;
	birthYear = trim(birthYear);
	var reg1 = /\D/;
	if(reg1.test(birthYear)) return false;
	var now = new Date();
	var ny = now.getFullYear();
	if(birthYear>(ny-13)) return false;
	return true;
}
function validateRadioButton(radioButton) {
	index = -1;
	for(i=0; i<radioButton.length; i++) {
		if(radioButton[i].checked) index = i;
	}
	return(index>-1);
}
function getRadioValue(radioButton) {
	index = -1;
	for(i=0; i<radioButton.length; i++) {
		if(radioButton[i].checked) { 
			return radioButton[i].value;	
		}
	}
	return("");
}
function validateSelect(select) {
	index = -1;
	for(i=0; i<select.length; i++) {
		if(select[i].selected) { 
			index = i;
			break;
		}
	}
	return(index>-1);
}
function getSelectedValue(select) {
	index = -1;
	for(i=0; i<select.length; i++) {
		if(select[i].selected) { 
			return select[i].value;	
		}
	}
	return("");
}

function show_registration() {
	var reg_form = document.getElementById('RegistrationContainer');
	reg_form.style.display = 'inline';
	reg_form.style.visibility = 'visible';
	reg_form.style.zIndex = '1000';
	
	var reg_form2 = document.getElementById('reg_form');
	reg_form2.style.display = 'inline';
	reg_form2.style.visibility = 'visible';
	reg_form2.style.zIndex = '1001';
}

function hide_registration() {
	var reg_form = document.getElementById('RegistrationContainer');
	reg_form.style.display = 'none';
	reg_form.style.visibility = 'hidden';
	reg_form.style.zIndex = '0';
	
	var reg_form2 = document.getElementById('reg_form');
	reg_form2.style.display = 'none';
	reg_form2.style.visibility = 'hidden';
	reg_form2.style.zIndex = '0';
}

function show_login() {
	var reg_form = document.getElementById('RegistrationContainer');
	reg_form.style.display = 'inline';
	reg_form.style.visibility = 'visible';
	reg_form.style.zIndex = '1000';
	
	var sl_login = parent.document.getElementById('sitelife_login');
	sl_login.style.display = 'inline';
	sl_login.style.visibility = 'visible';
	sl_login.style.zIndex = '1001';
	sl_login.focus();
}

function hide_login() {
	var reg_form = document.getElementById('RegistrationContainer');
	reg_form.style.display = 'none';
	reg_form.style.visibility = 'hidden';
	reg_form.style.zIndex = '0';
	
	var sl_login = parent.document.getElementById('sitelife_login');
	sl_login.style.display = 'none';
	sl_login.style.visibility = 'hidden';
	sl_login.style.zIndex = '0';
}

function show_getpass() {
	var reg_form = document.getElementById('RegistrationContainer');
	reg_form.style.display = 'inline';
	reg_form.style.visibility = 'visible';
	reg_form.style.zIndex = '1000';
	
	var sl_login = parent.document.getElementById('forgotten_password');
	sl_login.style.display = 'inline';
	sl_login.style.visibility = 'visible';
	sl_login.style.zIndex = '1001';
}

function hide_getpass() {
	var reg_form = document.getElementById('RegistrationContainer');
	reg_form.style.visibility = 'hidden';
	reg_form.style.zIndex = '0';
	
	var sl_login = parent.document.getElementById('forgotten_password');
	sl_login.style.visibility = 'hidden';
	sl_login.style.zIndex = '0';
}

function show_faq() {
	var faq = parent.document.getElementById('faq_page');
	if(faq) {
		faq.style.display = 'inline';
		faq.style.visibility = 'visible';
		faq.style.zIndex = '1001';
	}
}
function hide_faq() {
	var faq = parent.document.getElementById('faq_page');
	faq.style.display = 'none';
	faq.style.visibility = 'hidden';
	faq.style.zIndex = '0';
}
function show_help() {
	var help = parent.document.getElementById('pluckhelp_page');
	if(help) {
		help.style.display = 'inline';
		help.style.visibility = 'visible';
		help.style.zIndex = '1001';
	}
}
function hide_help() {
	var help = parent.document.getElementById('pluckhelp_page');
	help.style.display = 'none';
	help.style.visibility = 'hidden';
	help.style.zIndex = '0';
}
function show_resend() {
	var reg_form = document.getElementById('RegistrationContainer');
	if(reg_form) {
		reg_form.style.display = 'inline';
		reg_form.style.visibility = 'visible';
		reg_form.style.zIndex = '1000';
	}
	
	var sl_login = parent.document.getElementById('resend_confirmation');
	sl_login.style.display = 'inline';
	sl_login.style.visibility = 'visible';
	sl_login.style.zIndex = '1001';
}

function hide_resend() {
	var reg_form = document.getElementById('RegistrationContainer');
	if(reg_form) {
		reg_form.style.visibility = 'hidden';
		reg_form.style.zIndex = '0';
	}
	
	var sl_login = parent.document.getElementById('resend_confirmation');
	sl_login.style.visibility = 'hidden';
	sl_login.style.zIndex = '0';
}

function show_changepw() {
	var reg_form = document.getElementById('RegistrationContainer');
	if(reg_form) {
		reg_form.style.display = 'inline';
		reg_form.style.visibility = 'visible';
		reg_form.style.zIndex = '1000';
	}
	
	var sl_login = parent.document.getElementById('change_password');
	
	sl_login.style.display = 'inline';
	sl_login.style.visibility = 'visible';
	sl_login.style.zIndex = '1001';
}
function hide_changepw() {
	var reg_form = document.getElementById('RegistrationContainer');
	reg_form.style.visibility = 'hidden';
	reg_form.style.zIndex = '0';
	
	var sl_login = parent.document.getElementById('change_password');
	sl_login.style.visibility = 'hidden';
	sl_login.style.zIndex = '0';

}


function checkLogin() {
	var xmlHttp;
	var login_status = document.getElementById('login_result');
	var username = document.sitelife_login_form.userName.value;
	var password = document.sitelife_login_form.password.value;
	var redirect = document.sitelife_login_form.redirect.value;
	var remember = document.sitelife_login_form.remember.checked;
	var scriptname = "/share/passport_login.php?userName=" + username + "&password=" + password + "&remember=" + remember  + "&redirect=" + redirect;
	try {
		xmlHttp = new XMLHttpRequest();
	}
	catch(e) {
		try {
			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
		}
    	catch (e) {
			try {
				xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e) {
				alert("not supported");
			}
      	}
	}
	xmlHttp.onreadystatechange=function() {
		if(xmlHttp.readyState == 4) {
			login_status.innerHTML = xmlHttp.responseText;
			if(xmlHttp.responseText == "logged in") {
				//hide_login();
				setTimeout('location.reload(true)', 1000);
			}
		}
	}
	xmlHttp.open("GET",scriptname, true);
	xmlHttp.send(null);
}

function checkLoginCommon() {
	var xmlHttp;
	var login_status = document.getElementById('login_result');
	var username = document.sitelife_login_form.userName.value;
	var password = document.sitelife_login_form.password.value;
	var redirect = document.sitelife_login_form.redirect.value;
	var remember = document.sitelife_login_form.remember.checked;
	var scriptname = "/common/pluck/share/passport_login.php?userName=" + username + "&password=" + password + "&remember=" + remember  + "&redirect=" + redirect;
	try {
		xmlHttp = new XMLHttpRequest();
	}
	catch(e) {
		try {
			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
		}
    	catch (e) {
			try {
				xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e) {
				alert("not supported");
			}
      	}
	}
	xmlHttp.onreadystatechange=function() {
		if(xmlHttp.readyState == 4) {
			login_status.innerHTML = xmlHttp.responseText;
			if(xmlHttp.responseText == "logged in") {
				//hide_login();
				setTimeout('location.reload(true)', 1000);
			}
		}
	}
	xmlHttp.open("GET",scriptname, true);
	xmlHttp.send(null);
}

function RetrievePassword() {
	var xmlHttp;
	var password_retrieved = document.getElementById('password_retrieved');
	var username = document.retrieve_password.userName.value;
	var email = document.retrieve_password.email.value;
	var scriptname = "/share/retrieve_password.php?username=" + username + "&email=" + email;
	try {
		xmlHttp = new XMLHttpRequest();
	}
	catch(e) {
		try {
			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
		}
    	catch (e) {
			try {
				xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e) {
				alert("not supported");
			}
      	}
	}
	xmlHttp.onreadystatechange=function() {
		if(xmlHttp.readyState == 4) {
			password_retrieved.innerHTML = xmlHttp.responseText;
		}
	}
	xmlHttp.open("GET",scriptname, true);
	xmlHttp.send(null);
}

function RetrievePasswordCommon() {
	var xmlHttp;
	var password_retrieved = document.getElementById('password_retrieved');
	var username = document.retrieve_password.userName.value;
	var email = document.retrieve_password.email.value;
	var scriptname = "/common/pluck/share/retrieve_password.php?username=" + username + "&email=" + email;
	try {
		xmlHttp = new XMLHttpRequest();
	}
	catch(e) {
		try {
			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
		}
    	catch (e) {
			try {
				xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e) {
				alert("not supported");
			}
      	}
	}
	xmlHttp.onreadystatechange=function() {
		if(xmlHttp.readyState == 4) {
			password_retrieved.innerHTML = xmlHttp.responseText;
		}
	}
	xmlHttp.open("GET",scriptname, true);
	xmlHttp.send(null);
}

function ResendConfirm() {
	var xmlHttp;
	var email_sent = document.getElementById('email_sent');
	var username = document.resend_confirmation.userName.value;
	var email = document.resend_confirmation.email.value;
	var scriptname = "/share/resend_confirmation.php?userName=" + username + "&email=" + email;
	try {
		xmlHttp = new XMLHttpRequest();
	}
	catch(e) {
		try {
			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
		}
    	catch (e) {
			try {
				xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e) {
				alert("not supported");
			}
      	}
	}
	xmlHttp.onreadystatechange=function() {
		if(xmlHttp.readyState == 4) {
			email_sent.innerHTML = xmlHttp.responseText;
		}
	}
	xmlHttp.open("GET",scriptname, true);
	xmlHttp.send(null);
}

function ResendConfirmCommon() {
	var xmlHttp;
	var email_sent = document.getElementById('email_sent');
	var userName = document.getElementById('userName');
	
	//var resend_confirmation = document.getElementById('resend_confirmation');
	
	//var username = document.resend_confirmation.userName.value;
	var username = document.getElementById('userName').value;
	
	var email = document.resend_confirmation.email.value;
	var scriptname = "/common/pluck/share/resend_confirmation.php?userName=" + username + "&email=" + email;
	try {
		xmlHttp = new XMLHttpRequest();
	}
	catch(e) {
		try {
			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
		}
    	catch (e) {
			try {
				xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e) {
				alert("not supported");
			}
      	}
	}
	xmlHttp.onreadystatechange=function() {
		if(xmlHttp.readyState == 4) {
			email_sent.innerHTML = xmlHttp.responseText;
		}
	}
	xmlHttp.open("GET",scriptname, true);
	xmlHttp.send(null);
}


function ChangePassword()
{

	var xmlHttp;
	var changePw_status = document.getElementById('changePw_status');
	var userName 			= document.frmChangePassword.userName.value;
	var oldPassword		= document.frmChangePassword.oldPassword.value;
	var newPassword		= document.frmChangePassword.newPassword.value;
	var confirmNewPassword 	= document.frmChangePassword.confirmNewPassword.value;

	
	var scriptname = "/share/change_password.php?userName=" +userName+ "&oldPassword=" +oldPassword+ "&newPassword=" +newPassword+ "&confirmNewPassword=" +confirmNewPassword;
	
	try
	{
		xmlHttp = new XMLHttpRequest();
	}
	catch(e)
	{
		try
		{
			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
		}
    		catch (e)
		{
			try {
				xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e) {
				alert("not supported");
			}
      		}
	}
	xmlHttp.onreadystatechange=function()
	{
		if(xmlHttp.readyState == 4) {
			changePw_status.innerHTML = xmlHttp.responseText;  
		}
	}
	
	xmlHttp.open("GET",scriptname, true);
	xmlHttp.send(null); 	

}
function changeFaqLink()
        {
            var domainName=window.document.domain
			var faq_link = "http://" + domainName + "/sections/share/faq/";
			window.location.href = faq_link;
         }