function checkIt(string) {
	place = detect.indexOf(string) + 1;
	thestring = string;
	return place;
}

function bannerOff() {
	adbanner.style.visibility="hidden";
} 
  

function bannerOn() {
	adbanner.style.visibility="visible";
} 

/*
** ===================================================
** JS Object Functions
** ===================================================
*/

function getStyleObject(objectId) {
	// cross-browser function to get an object's style object given its id
	if (document.getElementById && document.getElementById(objectId)) {
		// W3C DOM
		return document.getElementById(objectId).style;
	} else if (document.all && document.all(objectId)) {
		// MSIE 4 DOM
		return document.all(objectId).style;
	} else if (document.layers && document.layers[objectId]) {
		// NN 4 DOM.. note: this won't find nested layers
		return document.layers[objectId];
	} else {
		return false;
	}
} // getStyleObject

function changeObjectVisibility(objectId, newVisibility) {
    // get a reference to the cross-browser style object and make sure the object exists
    var styleObject = getStyleObject(objectId);
    if (styleObject) {
		styleObject.visibility = newVisibility;
		return true;
    } else {
		// we couldn't find the object, so we can't change its visibility
		return false; 
	}
} // changeObjectVisibility

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function toggleAllObjects()
{
	var objs = document.getElementsByTagName("OBJECT");
	for (x=0; x<objs.length; x++)
		objs[x].style.display = objs[x].style.display == ''?'none':'';
	var sels = document.getElementsByTagName("SELECT");
	for (x=0; x<sels.length; x++)
		sels[x].style.display = sels[x].style.display == ''?'none':'';
}

// Change the opacity of the supplied DOM object to a value: 0-100
// Stolen from music, thanks guys!
function MMChangeOpacity(object, opacity)
{
var obj = object.style;
	if (opacity == 100) {
		obj.opacity = "";
		obj.MozOpacity = "";
		obj.HtmlOpacity = "";
		obj.filter = "";
	} else {
		obj.opacity = opacity / 100;
		obj.MozOpacity = opacity / 100;
		obj.HtmlOpacity = opacity / 100;
		obj.filter = "alpha(opacity=" + opacity + ")";
	}
	obj.visibility = "visible";
}

/*
** ===================================================
** Misc. Functions
** ===================================================
*/

// Show/hide a particular div id by using css display property
function ShowDiv($divname,$setting)
{
	if ($setting) {
		document.getElementById($divname).style.display = $setting==1?"block":"none";
	} else {
		if ($($divname).getStyle('display') == "none") $($divname).setStyle('display', 'block');
		else $($divname).setStyle('display', 'none');
	}
}

// Indended for <textarea>s , this function enforces the character limit 
// given by the 'maxlength' attribute.
function enforceMaxLength(field){
	var max = field.getAttribute("maxlength");
	if (field.value.length > max)
		field.value=field.value.substring(0,max)
}

function threadSubscribe($divname, $id, $forumid, $sub)
{
	new Ajax('/_forums/ajax/threadsub.php',{postBody:'threadid='+$id+'&forumid='+$forumid+'&sub='+$sub,update:$divname}).request();
	return false;

}

// Clear the login input fields when they're selected
function clearLoginForm()
{
	if (document.loginForm.login_username.value == "Username" && document.loginForm.login_password.value == "Password")
	{
		document.loginForm.login_username.value = "";
		document.loginForm.login_password.value = "";
	}
}

// Re-populate the login field if the user doesn't enter anything
function populateLoginForm()
{
	if (document.loginForm.login_username.value == "" && document.loginForm.login_password.value == "")
	{
		document.loginForm.login_username.value = "Username";
		document.loginForm.login_password.value = "Password";
	}
}

function sendEvent(typ) {
	thisMovie('ftmovie').sendEvent(typ);

};
function thisMovie(movieName) {
    if(navigator.appName.indexOf("Microsoft") != -1) {
		return window[movieName];
	} else {
		return document[movieName];
	}
};
// End Features


/*
** ===================================================
** Draggable Item Functions
** ===================================================
*/

// makeDraggable(document.getElementById('someid'));
function mouseCoords(ev)
{
	ev = ev || window.event;
	if(ev.pageX || ev.pageY)
		return { x:ev.pageX, y:ev.pageY};

	if(document.body != undefined)
		return {
			x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
			y:ev.clientY + document.body.scrollTop - document.body.clientTop
		 };
	return { x:0, y:0 };
}

var dragObject  = null;
var mouseOffset = null;

function getMouseOffset(target, ev){
	ev = ev || window.event;

	var docPos    = getPosition(target);
	var mousePos  = mouseCoords(ev);
	return {x:mousePos.x - docPos.x, y:mousePos.y - docPos.y};
}

function getPosition(e){
	var left = 0;
	var top  = 0;

	while (e.offsetParent){
		left += e.offsetLeft;
		top  += e.offsetTop;
		e     = e.offsetParent;
	}

	left += e.offsetLeft;
	top  += e.offsetTop;

	return {x:left, y:top};
}

function mouseMove(ev){
	ev           = ev || window.event;
	var mousePos = mouseCoords(ev);

	if(dragObject){
		dragObject.style.position = 'absolute';
		dragObject.style.right = '';
		dragObject.style.top      = mousePos.y - mouseOffset.y + "px";
		dragObject.style.left     = mousePos.x - mouseOffset.x + "px";
		return false;
	}
}
function mouseUp(){
	dragObject = null;
}

function makeDraggable(item){
	if(!item) return;
	item.onmousedown = function(ev){
		dragObject  = this;
		mouseOffset = getMouseOffset(this, ev);
		return false;
	}
}

function dragOnLoad()
{
	document.onmousemove = mouseMove;
	document.onmouseup   = mouseUp;
}

document.onload = dragOnLoad();

function setHover() {
	// get all ul's in the menu
	var ieULs = $ES('ul', "NavMenu");
	
	for (j=0; j<ieULs.length; j++) {
		if (window.ie6) {
			// IE script to cover <select> elements with <iframe>s
			var ieMat=document.createElement('iframe');
			if(document.location.protocol == "https:")
				ieMat.src="//0";
			else if(window.opera != "undefined")
				ieMat.src="";
			else
				ieMat.src="javascript:false";
			ieMat.scrolling="no";
			ieMat.frameBorder="0";
			ieMat.style.width=ieULs[j].offsetWidth+"px";
			ieMat.style.height=ieULs[j].offsetHeight+"px";
			ieMat.style.zIndex="-1";
			ieULs[j].insertBefore(ieMat, ieULs[j].childNodes[0]);
			ieULs[j].style.zIndex="101";
		}
	}
	
	if (window.ie6) {		
		// IE script to change class on mouseover
		var ieLIs = $ES('li', "NavMenu");
		for (var i=0; i<ieLIs.length; i++) if (ieLIs[i]) {
			// Add a hoverhack class to the li.
			ieLIs[i].onmouseover=function() {
				if(!/\bhoverhack\b/.test(this.className))
					this.className+=" hoverhack";
			}
			ieLIs[i].onmouseout=function() {
				if(!this.contains(event.toElement))
					this.className = this.className.replace(' hoverhack', '');
			}
		}
	} else {
		
		if (window.gecko) {	// hide the banner for ff2
			var version = navigator.userAgent;
			var index = version.indexOf("Firefox");
			
			if (parseFloat(version.substr(8 + index)) == "2") {
				$each($$('li.parentmenu'), function(menuitem, index){ 
					$(menuitem).addEvent('mouseenter', function () {$('BannerAd').setStyle('visibility', 'hidden');}); 
					$(menuitem).addEvent('mouseleave', function () {$('BannerAd').setStyle('visibility', 'visible');})
				});
			}
		}
	}
}

function DoAnonComment(type) {
	if (type == "post") {
		if($('nickname').value.trim() == '') {
			alert("Please enter your nickname!");
			return false;
		}
		if($('email').value.trim() == '') {
			alert("Please enter your email address!");
			return false;
		}
		if($('comment').value.trim() == '') {
			alert("Please enter your comment!");
			return false;
		}
	}
	$('DoCommentButton').setProperty('disabled','disabled');
	$('DoPreviewButton').setProperty('disabled','disabled');
	$('nickname').setProperties({'readonly':'readonly', 'disabled':'disabled'});
	$('email').setProperties({'readonly':'readonly', 'disabled':'disabled'});
	$('comment').setProperties({'readonly':'readonly', 'disabled':'disabled'});
	
	var updatediv = type == "post" ? $('CommentsFooter') : $('CommentsUpdate');
	if (type == "post") $('CommentsUpdate').setHTML("");
	
	// little bit of code to work out which style (odd or even) to post the test comment in
	var oddsect = $('CommentsUpdate') ? ($$('.CommentHeader').length % 2)+1 : ($$('.CommentHeader').length % 2);
	
	var commentAjax = new Ajax("/ajax/comments.php", {
								update: updatediv,
								method: 'post',
								data: {
									comment: $('comment').value,
									nickname: $('nickname').value,
									email: $('email').value,
									itemid: $('itemid').getProperty('value'),
									viewid: $('viewid').getProperty('value'),
									posttype: type,
									oddsection: oddsect,
									section: $('section').getProperty('value'),
									sectionid: $('sectionid').getProperty('value'),
									anon:1
								},
								onComplete: function () {
									if (type == "preview") {
										$('DoCommentButton').setProperty('disabled','');
										$('nickname').setProperties({'readonly':'', 'disabled':''});
										$('email').setProperties({'readonly':'', 'disabled':''});
										$('comment').setProperties({'readonly':'', 'disabled':''});
										$('DoPreviewButton').setProperty('disabled','');
										$('CommentAjaxImage').setStyle('display','none');
									}
								}
							}).request();
	return false;
}

function DoComment(type) {
	if($('comment').value.trim() == '') {
		alert("Please enter your comment!");
		return false;
	}
	
	$('DoCommentButton').setProperty('disabled','disabled');
	$('DoPreviewButton').setProperty('disabled','disabled');
	$('comment').setProperties({'readonly':'readonly', 'disabled':'disabled'});
	$('CommentAjaxImage').setStyle('display','block');
	var updatediv = type == "post" ? $('CommentsFooter') : $('CommentsUpdate');
	if (type == "post") $('CommentsUpdate').setHTML("");
	
	// little bit of code to work out which style (odd or even) to post the test comment in
	var oddsect = $('CommentsUpdate').innerHTML ? (($$('.CommentHeader').length) % 2)+1 : (($$('.CommentHeader').length) % 2);
	
	var commentAjax = new Ajax("/ajax/comments.php", {
								update: updatediv,
								method: 'post',
								data: {
									comment: $('comment').value,
									subject: $('subject').value,
									itemid: $('itemid').getProperty('value'),
									posttype: type,
									viewid: $('viewid').getProperty('value'),
									section: $('section').getProperty('value'),
									oddsection: oddsect,
									sectionid: $('sectionid').getProperty('value')
								},
								onComplete: function () {
									if (type == "preview") {
										$('DoCommentButton').setProperty('disabled','');
										$('comment').setProperties({'readonly':'', 'disabled':''});
										$('DoPreviewButton').setProperty('disabled','');
										$('CommentAjaxImage').setStyle('display','none');
									}
								}
							}).request();
	
	return false;
}

function RHSSearch(section)
{
	if ($(section + 'search').value.trim() == ""){
		alert("Please enter text to search for.");
		return false;
	}
	$(section + 'SearchButton').setProperty('disabled','disabled');
	$(section + 'search').setProperties({'readonly':'readonly', 'disabled':'disabled'});
	$('Latest' + section + 'List').setStyle('display','none');
	$(section + 'AjaxImage').setStyle('display','block');
	
	var searchAjax = new Ajax("/ajax/rhssearch.php", {
								update: $('Latest' + section + 'List'),
								method: 'post',
								data: {
									query: $(section + 'search').value,
									section: section
								},
								onComplete: function () {
									$('Latest' + section + 'List').setStyle('display','block');
									$(section + 'AjaxImage').setStyle('display','none');
									$(section + 'SearchButton').setProperty('disabled','');
									$(section + 'search').setProperties({'readonly':'', 'disabled':''});
								}
							}).request();
	
	return false;
}

function loadGameInfo(platform)
{
	var infos = $$("#Document #GamesHeader .GameInfo .Information");

	for (i = 0; i < infos.length; i++)
	{
		if ($(infos[i]).getStyle('display') == 'block')
		{
			var fadeout = new Fx.Style(infos[i], 'opacity', {
													duration:500, 
													onComplete: function(element) {
														$(element).setStyle('display','none');
														$("GameInfo"+platform).setStyle('display','block');
														var fadein = new Fx.Style("GameInfo"+platform, 'opacity', {duration:500})
														fadein.start(1);
													}
												});
			fadeout.start(0);
		}
	}
	
	// Only change the description if the dom component actually exists
	if ($("DescriptionPlatform"+platform)) {
		var descriptions = $$("#Document .GameOverview");

		for (j = 0; j < descriptions.length; j++)
		{
			if ($(descriptions[j]).getStyle('display') == 'block')
			{
				var fadeout2 = new Fx.Style(descriptions[j], 'opacity', {
														duration:500, 
														onComplete: function(element) {
															$(element).setStyle('display','none');
															$("DescriptionPlatform"+platform).setStyle('display','block');
															var fadein2 = new Fx.Style("DescriptionPlatform"+platform, 'opacity', {duration:500})
															fadein2.start(1);
														}
													});
				fadeout2.start(0);
			}
		}
	}
}


function ChangeScreenshot(index){
	var src = $('ss'+index).getProperty('src');
	
	seventwofive = src.replace('/images/230/', '/images/725/');
	source = src.replace('/images/230/', '/images/source/');
	
	$('MainScreenshot').setStyle('display','block');
	$('GameScreenshot').setProperty('src',"");
	$('GameScreenshot').setProperty('src',seventwofive);
	
	var screenshotlist = $$('#ScreenshotList img');
	
	var prevIndex = index == 0 ? screenshotlist.length-1 : index-1;
	var nextIndex = index == screenshotlist.length-1 ? 0 : index.toInt() + 1;
	
	if (window.ie) {
		$('PreviousScreenshot').removeEvents('click');
		$('NextScreenshot').removeEvents('click');
		$('PreviousScreenshot').addEvent('click', function () { ChangeScreenshot(prevIndex);} );
		$('NextScreenshot').addEvent('click', function () { ChangeScreenshot(nextIndex);} );
	} else {
		$('PreviousScreenshot').setProperty('onclick', 'ChangeScreenshot("' + prevIndex + '")');
		$('NextScreenshot').setProperty('onclick', 'ChangeScreenshot("' + nextIndex + '")');
	}
	
	$('GameScreenshotLink').setProperty('href',source);
	
	screenshotlist.setStyles({'border':'none', 'margin':'5px'}); 
	$('ss'+index).setStyles({'border':'5px solid #FFBC23', 'margin':'0'});
	
}

var OriginalGamesHeaderHeight;
function ShowVideo(show){
	if (show == "show") {
		var defaultNewHeight = 245;
		OriginalGamesHeaderHeight = $('GamesHeader').offsetHeight;
		$('GameInfo').setStyle('display','none');
		$('GameVideoThumb').setStyle('display','none');
		var grow = new Fx.Style($('GamesHeader'), 'height', {
													duration:500, 
													onComplete: function(element) {
														$('GameInfoVideo').setStyle('display','block');
														$('GameVideo').setStyle('display','block');
														InfoHeight = $('GameInfoVideo').offsetHeight;
														if (InfoHeight > defaultNewHeight)
															if ($('GamesHeader').offsetHeight != InfoHeight)
																grow.start(InfoHeight);
														if ($('GamesHeader').offsetHeight == InfoHeight || InfoHeight <= defaultNewHeight)
															sendEvent.delay(50, this, ['playpause']);
													},
													transition: Fx.Transitions.Quart.easeOut
												});
		grow.start(defaultNewHeight);
	} else {	
		sendEvent('stop');
		$('GameInfoVideo').setStyle('display','none');
		$('GameVideo').setStyle('display','none');
		var grow = new Fx.Style($('GamesHeader'), 'height', {
													duration:500, 
													onComplete: function(element) {
														$('GameInfo').setStyle('display','block');
														$('GameVideoThumb').setStyle('display','block');
													},
													transition: Fx.Transitions.Quart.easeIn
												});
		grow.start(OriginalGamesHeaderHeight);
	}
}


function DoSSAnim(screenshot, gameid) {
	
	if ($(screenshot).getStyle('width') == "230px"){
		var src = $(screenshot).getStyle('background');
		seventwofive = src.replace('/images/230/', '/images/725/');
		
		$(screenshot).setStyle('background', seventwofive);
		
		var grow = new Fx.Styles(screenshot, {
												duration:800, 
												onComplete: function(element) {
													
												},
												transition: Fx.Transitions.Quart.easeOut
											});
		grow.start({'height':391, 'width':725});
	} else {
		var grow = new Fx.Styles(screenshot, {
												duration:800, 
												onComplete: function(element) {
													var src = $(screenshot).getStyle('background');
													twothirty = src.replace('/images/725/', '/images/230/');
													$(screenshot).setStyle('background', twothirty);
												},
												transition: Fx.Transitions.Quart.easeIn
											});
		grow.start({'height':126, 'width':230});
	}
}


/* News Ticker */
var NewsTickerTimer;
function NextNewsTickerItem() {
	var items = $$("#CompactFeatures #RightFeatures #NewsTicker #NewsTickerContainer .NewsTickerText");

	for (i = 0; i < items.length; i++)
	{
		if ($(items[i]).getStyle('display') == 'block')
		{
			idx = (i+1) == items.length ? 0 : (i+1);
			var fadeout = new Fx.Style($("NewsTickerContainer"), 'opacity', {
													duration:1200, 
													onComplete: function() {
														$(items[i]).setStyle('display','none');
														$(items[idx]).setStyle('display','block');
														var fadein = new Fx.Style($("NewsTickerContainer"), 'opacity', {duration:1200})
														fadein.start(1);
													}
												});
			fadeout.start(0);
			break;
		}
	}
	DoNextNewsTickerItem();
}

function DoNextNewsTickerItem() {
	NewsTickerTimer = setTimeout("NextNewsTickerItem()",8000);
}

/* Compact Features */
var CompactFeatureTimer;
function ChangeCompactFeatureItem(direction,clicked) {
	if (CompactFeatureItems > 0) {
		if (clicked == 1)
			clearInterval(CompactFeatureTimer);
		switch (direction) {	
			case "prev":
				if (CurrentFeaturePosition == 1)
					CurrentFeaturePosition = CompactFeatureItems;
				else CurrentFeaturePosition--;
				break;
			case "next":
				if (CurrentFeaturePosition == CompactFeatureItems)
					CurrentFeaturePosition = 1;
				else CurrentFeaturePosition++;
				break;
		}

		newMargin = CurrentFeaturePosition > 1 ? (CurrentFeaturePosition-1) * 208 : 0;
		var slide = new Fx.Style($("MainCompactFeature"), 'margin-left', {duration:1200});
		slide.start("-"+newMargin+"px");
	}
}

function DoNextCompactFeatureItem() {
	CompactFeatureTimer = setInterval("ChangeCompactFeatureItem('next',0)",7000);
}


/* Auto Suggest Box */
var MMAutoSuggestBox = new Class({
	initialize: function(options) {
		this.options = options;
		this.canSubmit = true;
		this.currentSel = 0; // Current position of selected suggestion, 0 by default.
		this.latestServerQuery = ""; // Latest keyword sent to server, blank by default.
	},
	options: {
		throttle: 500,  // Period between checking the keyword looping, 500 by default.
		searchBox: "", // The id of the keyword search box.
		gameIdBox: "",
		suggestionBox: "",  // The id of the suggestion div.
		rowSelection: "", // The prefix name of row in the suggestion table.
		ajaxPage: "", // The name of the page receiving request.
		querystringPrefix: "" // The querystring prefix accepted by the server.
	},
	requestValidLoop: function() {
	    var objSearch = $(this.options.searchBox);
	    var objSuggest = $(this.options.suggestionBox);
	    var strSearchResult, blnReset;
	    blnReset = false;
		if(objSearch != undefined ) {
			if (objSearch.value.length > 0){
				// Check previous keyword
				if (objSearch.value != this.latestServerQuery){
					this.getSuggestion(objSearch.value);
					this.latestServerQuery = objSearch.value;
					this.currentSel = 0;
				}
			}
			else
				blnReset = true;
		}
		else {
			blnReset = true;
		}
	    
		// self.timedAjax = self.getAjaxData.delay(0, self, [el, mousePos]); // 1000 for 1 sec ... 0 for testing
		this.timedValidationLoop = this.requestValidLoop.delay(this.options.throttle,this);
	    // setTimeout('requestValidLoop();', this.options.throttle);
		if(objSuggest != undefined) {
			if (blnReset){
				this.latestServerQuery = '';
				this.currentSel = 0;
				objSuggest.innerHTML = '';
				this.ShowHide(true, this.suggestionBox);
				
				objSuggest.style.top = -999;
				objSuggest.style.left = -999;
			}
			else{
				objSuggest.style.top = objSuggest.style.left = 1;
			}
		}
	},
	updateSearchBox: function(SuggestionText,GameId){
		// Called when user click on one of the suggestion list
	    if (SuggestionText.length > 0) {
	        // Update the search box text
			$(this.options.searchBox).value = SuggestionText;
			if($(this.options.gameIdBox) != undefined)
				$(this.options.gameIdBox).value = GameId;
	        
			if(typeof DoGameTitleAjax == 'function')
				DoGameTitleAjax(2);
				// Horrible Hardcoded hack to call the function to get the data on the mappings ajax page
				// fail me, if you can find out who it was...... (and if it breaks anything) HINT: not bob
			
	        this.latestServerQuery = SuggestionText;
	        this.currentSel = 0;
	        
	        $(this.options.suggestionBox).innerHTML = '';
	        
	        // Hide the suggestion box
	        this.ShowHide(true, this.options.suggestionBox);
			this.canSubmit = false;
	    }
	},
	getSuggestion: function(keyword){
	    var strInput;
	    if (keyword.length > 2){
	        strInput = this.options.querystringPrefix + keyword;
		    var a = new Ajax(this.options.ajaxPage, {
						postBody: strInput, 
						evalScripts: true,
						update: this.options.suggestionBox
					});
			a.addEvent("onComplete",this.checkSuggestionBox.pass([this],a));
			a.request();
	    }
	},
	checkSuggestionBox: function(self) {
		// Check if there is any entry in the suggestion box once AJAX completed
	    self.ShowHide(!(this.response.text.length > 0), self.options.suggestionBox);	    
	},
	searchKeyHandler: function(e) {
		// Event key handler for the search box
	    var blnGotSuggestion;
	    var objRowSelected, objRowNext;
	    var intRowNext;
	    
	    objRowSelected = $(this.options.rowSelection + this.currentSel);

	    if (objRowSelected != undefined)
	        blnGotSuggestion = true;
	    else
	        blnGotSuggestion = false;
	    
	    if (blnGotSuggestion){
	        // Tab or Enter key
	        if(!e) e = window.event;
	        kc = (e.keyCode) ? e.keyCode : e.which;
	        if (kc == 9 || kc == 13) {
				this.canSubmit = false;
				objRowSelected.onclick();
	        }
	        else if (kc == 38 || kc == 40){
	            //Up key
	            if (kc == 38){
	                intRowNext = this.currentSel - 1;
	            }
	            //Down key
	            else if (kc == 40){
	                intRowNext = this.currentSel + 1;
	            }
	            objRowNext = $(this.options.rowSelection + intRowNext);
	            if (objRowNext != undefined){
	                currentSel = intRowNext;
					this.highlightRow(objRowNext);
	            }
	        }
	    }
	},
	highlightRow: function(element) {
		rows = $(this.options.suggestionBox).getElements("td");
		for(i = 0;i < rows.length;++i) {
			row = rows[i];
			if(row.id == element.id) {
				row.style.backgroundColor = "#90DEBF";
				this.currentSel = i;
			}
			else
				row.style.backgroundColor = "white";
		}
	},
	ShowHide: function(hide,_w) {
		if($defined(_w)) {
			if(!hide)
				$(_w).setStyles("display:block;visibility:visible");
			else
				$(_w).setStyles("display:none;visibility:hidden");
		}
	}
});


function DoPollVote(id, main) {
	if (main) var polldiv = "mainpoll";
	else var polldiv = "rhspoll";
	$('pollvotebutton').setStyle('enabled','false');
	
	var responseid = false;
	
	$$('#'+polldiv+' .response').each(function(item, index) { 
			if ($(item).getProperty("checked")) responseid = $(item).getProperty("value");
		});
	if (!responseid) {
		alert("You must select an option before voting!");
		return;
	}
	$(polldiv).setHTML("<div style='text-align:center;color:red;'><img src='/res/static/images/icons/ajax-loader"+ (main ? "" : "2") +".gif' alt='Loading'/><br/>Please wait while your vote is submitted.</div>")
	
	new Ajax('/ajax/poll.php',{postBody:'pollid='+id+'&response='+responseid,update:$(polldiv)}).request();
}

function DoiPhoneJS(action, id, type) {
	var loading = "<div style='text-align:center;'><img src='/res/static/images/icons/ajax-loader.gif' alt='Loading...'/><br/> Loading....</div>";
	switch (action){
		case "Show":
			if ($('NewsArticle' + id).innerHTML) {
				if ($('NewsArticle' + id).getStyle('display') == 'block') {
					$('NewsArticle' + id).setStyle('display','none');
				} else {
					$$('.NewsArticle').setStyle('display','none');
					$('NewsArticle' + id).setStyle('display','block');
				}
			} else {
				$('NewsArticle' + id).setHTML(loading);
				$('NewsArticle' + id).setStyle('display','block');
				new Ajax('/ajax/iphone.php',{postBody:'itemid='+id+'&type='+type,update:$('NewsArticle' + id)}).request();
			}
			break;
		case "Scroll":
			if (id < 100) {
				$('MoreNewsLink').setStyle('display','none');
				$('More'+type+id).setHTML(loading);
				new Ajax('/ajax/iphone.php',{	postBody:'startid='+id+'&type='+type,update:$('More'+type+id), 
												evalScripts:true, 
												onComplete: function () { $('MoreNewsLink').setStyle('display','block'); }
											}).request();
				
			} else {
				$('MoreNewsLink').setStyle('display','none');
			}
			break;
	}
	
}

function PrepareVideoRater() {
	if ($('RateItButton')) {
		$('RateItButton').addEvent('click', function () { ShowDiv('StarsDiv') });
		for (var i = 1; i <= 5; i++) {
			$('Stars'+i).addEvent('mouseenter', function () { this.getElements('img').setProperty('src', '/res/static/images/videos/staron.png') });
			$('Stars'+i).addEvent('mouseleave', function () { this.getElements('img').setProperty('src', '/res/static/images/videos/staroff.png') });
			$('Stars'+i).addEvent('click', function () { RateVideo($('VideoId').value, this.getProperty('id').substr(5))});	// does a substr of the id because the variable i has a global scope
		}
	}
}

function RateVideo(videoid, rating) {
	new Ajax('/ajax/ratevideo.php',{postBody:'videoid='+videoid+'&rating='+rating,
									update:$('VideoRater')
								}).request();
}

function SwapTab(Section, SectionNumber, numSections, SectionType, SwapContent) {
	if (SectionNumber == 0) { PreSwitch = ""; SectionPreType = "first"; }
	else { PreSwitch = "off"; SectionPreType = "middle"; }
	for (i=0;i<numSections;i++) {
		if (SwapContent) $(Section+'SectionContent'+i).setStyle('display', 'none');

		if (i == 0) { PreType = 'first'; PreAllSwitch = ""; }
		else { PreType = 'middle';PreAllSwitch = "off"; }
		
		$(Section+'SectionTab'+i).setStyle('background-image','url(/res/static/images/tabs/'+SectionType+'/tab-bg-off.png)');
		var alttag = $(Section+'SectionTab'+i).getElement('img').getProperty('alt');
		$(Section+'SectionTab'+i).setHTML("<img src=\"/res/images/header.php/taboff/"+alttag+".png\" alt=\""+alttag+"\"/>");
		$(Section+'Tab'+i+'Pre').setStyle('background-image','url(/res/static/images/tabs/'+SectionType+'/tab-'+PreType+'-'+PreAllSwitch+'off.png)');
		$(Section+'Post').setStyle('background-image','url(/res/static/images/tabs/'+SectionType+'/tab-last-off.png)');
	}

	if (SwapContent) $(Section+'SectionContent'+SectionNumber).setStyle('display','block');
	$(Section+'SectionTabs').setStyle('background-image','none');
	$(Section+'SectionTab'+SectionNumber).setStyle('background-image','url(/res/static/images/tabs/'+SectionType+'/tab-bg-on.png)');
	var alttag = $(Section+'SectionTab'+SectionNumber).getElement('img').getProperty('alt');
	$(Section+'SectionTab'+SectionNumber).setHTML("<img src=\"/res/images/header.php/tabon/"+alttag+".png\" alt=\""+alttag+"\"/>");
	
	$(Section+'Tab'+SectionNumber+'Pre').setStyle('background-image','url(/res/static/images/tabs/'+SectionType+'/tab-'+SectionPreType+'-'+PreSwitch+'on.png)');
	if((SectionNumber+1)!=numSections)
		$(Section+'Tab'+(SectionNumber+1)+'Pre').setStyle('background-image','url(/res/static/images/tabs/'+SectionType+'/tab-middle-onoff.png)');
	else { 
		$(Section+'Post').setStyle('background-image','url(/res/static/images/tabs/'+SectionType+'/tab-last-on.png)');
	}
}

function SetImage(el, img) {
	$(el).setProperty('src',img);
}

function ResizeImages(type) {
	
	if (type == "news"){
		var maxwidth = 630;
		var images = $$('#Document .CommentArticle img');
	} else if (type == "forums"){
		var maxwidth = 738;
		var images = $$('#Document .ThreadContent img');
	}
	for (var i = 0; i < images.length; i++) {
		img = images[i];
		var width = img.width;
		if (width > maxwidth){
			var height = img.height;
			var ratio = height/width;
			var newheight = maxwidth*ratio;
			$(img).setStyles({'width':maxwidth, 'height':newheight, 'cursor':'pointer'});
			$(img).setProperty('rel', width+'|'+height);
			$(img).addEvent('click', function () {
				var currentwidth = this.width;
				var currentheight = this.height;
				
				// pull out the width and height from the rel tag
				var thispole = this.getProperty('rel').indexOf("|");
				var thiswidth = this.getProperty('rel').substr(0,thispole).toInt();
				var thisheight = this.getProperty('rel').substr(thispole+1, this.getProperty('rel').length).toInt();
				
				this.setStyles({'width':thiswidth, 'height':thisheight});
				
				this.setProperty('rel', currentwidth+'|'+currentheight);
				
			});
			
		}
	}
}

function CommentsTrigger() {
	if ($defined($('CommentsDiv'))) {
		if ($('CommentsDiv').getStyle('display') == "none") {
			$('CommentsTrigger').setHTML("Hide");
			$('CommentsDiv').setStyle('display', 'block');
		} else {
			$('CommentsTrigger').setHTML("Show");
			$('CommentsDiv').setStyle('display', 'none');
		}
	}
}
