
function funcClassActive(active,inactive){
	
	if(active.indexOf(",")!= -1)
	{
			var activeArray=active.split(",");
			
			for (i=0,n=activeArray.length; i<n; i++){
				 $(activeArray[i]).addClass('active');
			 }
		} 
		else 
		{
			$(active).addClass('active');
	}
	
	
	 if(inactive.indexOf(",")!= -1)
		{
			var inactiveArray=inactive.split(",");
			
		for (i=0,n=inactiveArray.length; i<n; i++){
				 $(inactiveArray[i]).removeClass('active');
		}

		} 
		else 
		{
			$(inactive).removeClass('active');
		}	
}


function funcShowScore(){
	alert('showscore');
}
function funcPostScore( token, score, securescore ){
	alert('Submit Score: token=' + token + ' : score=' + token + ' : secure=' + securescore);

}


function bookmarksite(pageName,urlAddress) { 
var str = navigator.userAgent;
	  if ((navigator.appName == "Microsoft Internet Explorer") && (parseInt(navigator.appVersion) >= 4)) {
			 window.external.AddFavorite(urlAddress,pageName);
	   } else if (str.indexOf('Firefox') != -1){
			window.sidebar.addPanel(pageName,urlAddress,"");
	  } else if (str.indexOf('Chrome') != -1 || str.indexOf('Opera') != -1 || str.indexOf('Safari') != -1){
			alert("Press CTRL-D to bookmark");
	  }
}

function getPagename(){
	var sPath = window.location.pathname;
	var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);
	return sPage;
}

function urlEncodeCharacter (c){
	return '%' + c.charCodeAt(0).toString(16);
}

function urlDecodeCharacter(str, c){
	return String.fromCharCode(parseInt(c, 16));
}

function urlEncode( s ){
      return encodeURIComponent( s ).replace( /\%20/g, '+' ).replace( /[!'()*~]/g, urlEncodeCharacter );
}

function urlDecode( s ){
      return decodeURIComponent(s.replace( /\+/g, '%20' )).replace( /\%([0-9a-f]{2})/g, urlDecodeCharacter);
}


function checkIllegalChars(str){
		var illegalChars= /[\ \'\#\!\£\$\%\^\&\*\+\=\`\|\¬\¦\~\@\{\}\-\(\)\<\>\,\;\:\\\/\"\[\]]/;
		if (str.match(illegalChars)) {
	 	 return false;
	}
		 return true;	
}

function checkIllegalCharsSearch(str){
		var illegalChars= /[\\.\'\#\!\£\$\%\^\&\*\+\=\`\|\¬\¦\~\@\{\}\-\(\)\<\>\,\;\:\\\/\"\[\]]/;
		if (str.match(illegalChars)) {
	 	 return false;
	}
		 return true;	
}

function funcPublishActiviyFeed(varBody,varAS,varRefresh,varRedirect){
	 $.ajax({
	 type: "GET",
	 async: true,
	 url: "calls.php?action=activitysubmit&activitybody=" + escape(varBody) + "&as=" + escape(varAS) + "&anticache=" + Date.parse(new Date()),
	 success: function(msg) { 
	 	}
	 }
 );
	if(varRedirect!=''){
		window.location=varRedirect;
	}
	
	if(varRefresh==true){
		funcActivity($('#filter').val()); 
	}
 }



function AllowOnlyNumeric(e){
         var charCode;
		
		 if(window.event){  //IE
      		 charCode = e.keyCode;
   		 }
		 
   		 if(e.which){ //Netscape/Firefox/Opera
       		  charCode = e.which;
   		 }

		 
         if (charCode > 31 && (charCode < 48 || charCode > 57)){
             if (charCode == 46){
		    return true;
			}
        	 return false;
		 }
		 return true;
      }
function funcToggleFlashContent(strOnOff){
	$('#flashtogglemarker').html(strOnOff);
	$("body").find("[class*=flashcontent]").each(function(callback){
		var collection = $(this);
			if(strOnOff=='on'){
				collection.removeClass('flashoff');
			} else {
				collection.addClass('flashoff');
			}
	});

}


function funcTranslateStr(target_lang,str){
	
	var lang_array= target_lang.split("||");
	target_lang = lang_array[0];
	if (target_lang!='en'){
		//alert('test');
			google.language.translate(str, "en", target_lang, function(result) { 
					 if (!result.error) { 
						return result.translation; 
					 } 
				});
	} else{
		return str; 
	}
}


function funcTranslate(target_lang) {
	var lang_array= target_lang.split("||");
	target_lang = lang_array[0];
	
	if (target_lang!='en'){
		// if not english translate
		 $("body").find("[class*=translate]").each(function(callback){
		 	// find elements with class translate
			var collection = $(this);
			var pid = 0;
			var lid = 0;
			
			if (collection.attr('type')=='button'){
				// translate form buttons
				google.language.translate(collection.val(), "en", target_lang, function(result) { 
					 if (!result.error) { 
						collection.val(result.translation); 
					 } 
					});
			}
			
			collection.find("p").each(function(pcallback){
				// find <p> in elements found and translate individually
					var ptags = $(this);
					var pid = 99;
					google.language.translate(ptags.html(), "en", target_lang, function(result) { 
					 if (!result.error) { 
						ptags.html(result.translation); 
					 } 
					});
				});
				
			collection.find("li").each(function(licallback){
				// find <li> in elements found and translate individually
					var litags = $(this);
					var lid = 99;
					google.language.translate(litags.html(), "en", target_lang, function(result) { 
					 if (!result.error) { 
						litags.html(result.translation); 
					 } 
					});
				});
				
			if (pid == 0 && lid==0){
				// translate all of element its has no <p><li>
				google.language.translate(collection.html(), "en", target_lang, function(result) { 
				  if (!result.error) { 
					collection.html(result.translation); 
				  } 
				});		
			}
			});  
		}
	}


function CalcKeyCode(aChar) {
  var character = aChar.substring(0,1);
  var code = aChar.charCodeAt(0);
  return code;
}

function funcCheckField(fieldid) {
  var val = document.getElementById(fieldid);
  var strPass = val.value;
  var strLength = strPass.length;
  var lchar = val.value.charAt((strLength) - 1);
  var allowedChars ='1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_'
  
  	if(allowedChars.indexOf(lchar)==-1){
		var myFieldVal = val.value.substring(0, (strLength) - 1);
		val.value = myFieldVal;
	}
  return false;
}


function funcAutoPop(url,h,w,closebtn){
	funcToggleFlashContent('off');
	 $('#autopop').fancybox({
        'autoScale'     	: true,
        'transitionIn'		: 'fade',
		'transitionOut'		: 'fade',
		'href'				: url,
		'type'				: 'iframe',
		'overlayOpacity'    : 0.6,
		'height'			: h,
		'width'			    : w,
		'centerOnScroll'	: true,
		'overlayColor'		: '#000000',
		'titleShow'			: true,
		'hideOnOverlayClick' : true,
		'showCloseButton'	 : closebtn,
		'onClosed'		: function() {
	    		funcToggleFlashContent('on');
					}

		
	}).trigger('click');

}

function funcFaceBookPublish(image,message,title,url,heading){
var timers = {}; 
clearTimeout(timers);
var publish = {
  method: 'stream.publish',
  message: '',
  attachment: {
  name: title,
  caption: title,
  description: (message),
   href: url,
   media:[{'type': 'image','src':image,'href':url}]
  },
  action_links: [
    { text: 'Koko Games', href: 'http://www.kokogames.com/' }
  ],
  user_prompt_message: 'Share your thoughts about Koko Games'
};
// set post data above
 FB.getLoginStatus(function(response) {
	if (response.session) {
	// if facebook logged in then check permissons
		 FB.api({method: 'fql.query',query: 'SELECT publish_stream FROM permissions WHERE uid=' + response.session.uid},
			  function(response) {
				
				if(response[0].publish_stream ==1 ){
					//auto post here
					$('#fbPostingDialog').slideDown("slow");
					$('.unread').hide();
						$(this).queue(function(){
							timers = setTimeout(function(){
								 $(this).dequeue(); 
									if($('#fbpost').val() =='1'){
										$('#fbPostingDialog').hide();
										$('.unread').show();
										$.ajax({url:'calls.php?action=fbPostToWall&message='+message+'&title='+title+'&url='+url+'&image='+ image});
										// auto post using php sdk method
										} else {
											$('#fbpost').val('1');
											$('#fbPostingDialog').hide();
											$('.unread').show();
										}	
									 }
									,4000);
								  });
							}else{
							funcToggleFlashContent('off');
							FB.ui(publish,function(response){funcToggleFlashContent('on');});
							// manual post using UI Javascript sdk
						}
				  }
				);
	 	 }
	});
}

function funcFaceBookPublishSneeze(image,message,title,url,heading){
	funcFaceBookPublish(image,message,title,url,heading);
}

   
   
function funcLogout(strUrl,fbid){
	
	var returnPath = strUrl.replace('logout.php','');
	
	if(fbid==''){
			  window.location=strUrl;
		//var response = $.ajax({url: strUrl,async: true,success:function(){window.location=returnPath+'index.php?logout=1'; }}).responseText;
	} else{
		FB.logout(function(response) {
		  // user is now logged out
		  window.location=strUrl;
			//var response = $.ajax({url: strUrl,async: true,success:function(){window.location=returnPath+'index.php?logout=2'; }}).responseText;
			
		});
	}
}


function funcReport(id,gid){
	funcAutoPop('assets/includes/inc_pop_report_review.php?rid='+id+'&gid='+gid,200,380,true);
}

function funcShowGame(){
  	// show embed code for game 
	  $("#advert_game").css("display", "none");


	   if ($("#swfObjGame").css("width")=="1px"){
	  	 		$("#swfObjGame").attr("width",$("#swfObjGame").attr("owidth"));
				$("#swfObjGame").attr("height",$("#swfObjGame").attr("oheight")); 
	   } 
  }  

function funcJavaUrlRewriter(url,reurl,onoff){
	if(onoff=='1'){
		return reurl;
	} else {
		return url;
	}
}



function funcRemoveFavRight(id,userid,onoff){
var strURL;
	if (id.indexOf('(') > 0){
		strURL ="calls.php?action=removefave&pid="+id.replace("(","").replace(")","").replace(/\|/g,"");
	} else {
		strURL= "calls.php?action=removefave&gid="+id.replace(/\|/g,"");
	}
	
	$.ajax({
	type: "GET",
	url: strURL,
    dataType: "html",
	async: true,
	success: function(html) {
	
		if (getPagename()=='account.php'){
			window.location=String(window.location).replace("#comments","");
			} else {
			funcYourFavourites(userid,onoff);
		}
		}
	});

}

function funcYourFavourites(userid,onoff){
 $('#loading').css("display", "");
 $('#activityfeed').css("display", "none");
 $('#divactivityfeed').css("display", "none");
 $('#divchatfilter').css("display", "none");
 $('#favourites').css("display", "none");
 $('#divfavourites').css("display", "none");
 $('#recently').css("display", "none");
 $('#divrecently').css("display", "none");
 $('#divFavfilter').css("display", "");
 $('#lastactivityid').val('');
 $('#favourites').css("display", "none");
 
if (userid!='') {

  var data = '';
  var a = 0;
  var sc = String.fromCharCode(39);
  var bs = String.fromCharCode(92);
     $.ajax({
	  type: "GET",
      url: "calls.php?action=favourites&search="+ $('#fav').val() +"&pmarker=" +$('#pmarker').val(),
	  async: true,
      dataType: "html",
      success: function(html) {
		
				if(html==''){
					 $('#favourites').html('<span class="translate">your currently have no favourites listed.</span>');
					} else{
					 $('#favourites').html(html);
					 $("#autolang").trigger("click"); 	
				 } 

				 
				 $('#loading').css("display", "none");
				 $('#favourites').css("display", "");
				 $('#divfavourites').css("display", "none");
				 $('#recently').css("display", "none")
				 $('#divrecently').css("display", "none");
			} 
		});
		
	 } else {
		$('#loading').css("display", "none");
		$('#favourites').css("display", "none");
		$('#divfavourites').css("display", "");
		$('#recently').css("display", "none")
		$('#divrecently').css("display", "none");
	 } 

}
function funcRemoveRecentRight(id,gid,userid,onoff){
	$.ajax({
	type: "GET",
	url: "calls.php?action=recentremove&rid="+id+"&gid="+gid,
    dataType: "html",
	async: true,
	success: function(html) {
		
		if (getPagename()=='account.php'){
			window.location=String(window.location).replace("#comments","");
			} else {
				funcYourRecently(userid,onoff);
		}
		}
	});
}

function funcYourRecently(userid,onoff){
 $('#loading').css("display", "");
 $('#favourites').css("display", "none");
 $('#divfavourites').css("display", "none");
 $('#recently').css("display", "none");
 $('#divrecently').css("display", "none");
 $('#activityfeed').css("display", "none");
 $('#divactivityfeed').css("display", "none");
 $('#divchatfilter').css("display", "none");
 $('#divFavfilter').css("display", "");
 
if(userid!=''){
  var data = '';
  var a = 0;
  var sc = String.fromCharCode(39);
  var bs = String.fromCharCode(92);
     $.ajax({
	  type: "GET",
      url: "calls.php?action=recentlyplayed&search="+ $('#fav').val()+"&pmarker=" +$('#pmarker').val(),
      async: true,
	  dataType: "html",
      success: function(html) {
				if(html==''){
					 $('#recently').html('<span class="translate">you haven\'t played any games recently.</span>');
					} else{
					 $('#recently').html(html);
					 $("#autolang").trigger("click");
				 } 
				 
				 $('#loading').css("display", "none");
				 $('#recently').css("display", "");
				 $('#divrecently').css("display", "none");
				 $('#favourites').css("display", "none");
 				 $('#divfavourites').css("display", "none");
			} 
		});
	 
	} else {
		$('#loading').css("display", "none");
		$('#recently').css("display", "none");
		$('#divrecently').css("display", "");
		$('#favourites').css("display", "none");
 		$('#divfavourites').css("display", "none");
		
	}
}

function funcActivity(filter,userid,onoff,privacyview){
if(userid=='' && filter !='everyone')
{
	$('#divactivityfeed').css("display", "block");
	$('#divchatfilter').css("display", "block");
	$('#divfavourites').css("display", "none");
	$('#divrecently').css("display", "none");
	$('#divFavfilter').css("display", "none");
	$('#activityfeed').css("display", "none");
	$('#recently').css("display", "none");
	$('#favourites').css("display", "none");
	$('#loading').css("display", "none");	
} else {
	
if($('#pmarker').val() =='activityfeed'){
	
	 $('#divchatfilter').css("display", "block");
	 $('#activityfeed').css("display", "block");
	 $('#divactivityfeed').css("display", "none");
	 $('#divfavourites').css("display", "none");
	 $('#divrecently').css("display", "none");
	 $('#divFavfilter').css("display", "none");
	 $('#recently').css("display", "none");
	 $('#favourites').css("display", "none");

var data = '';
var a = 0;
var f = 0;

if ($('#lastactivityid').val()=='' || filter != $('#filter').val()){
	
 	f = 1;
	 $('#loading').css("display", "block");
	 $('#activityfeed').css("display", "none");
	 $('#divactivityfeed').css("display", "none");
	 $('#favourites').css("display", "none");
	 $('#divfavourites').css("display", "none");
	 $('#recently').css("display", "none");
	 $('#divrecently').css("display", "none");
	 $('#divchatfilter').css("display", "");
	 $('#divFavfilter').css("display", "none");
	 $('#lastactivityid').val('');
	 $('#activityfeed').html('');
  }


  $('#filter').val(filter);
   $.ajax({
	  type: "GET",
      url: "calls.php?action=activityfeed&search="+filter+"&userid="+userid+"&loguserid="+userid+"&lastactivityid="+$('#lastactivityid').val()+"&pv="+privacyview+"&pmarker="+$('#pmarker').val()+"&colour=f8f8f8&size=35",
      async: true,
	  dataType: "html",
      success: function(html) {
			var arrayAct;
			arrayAct = html.split('|||');
			
			if (html.length >10){
				$('#lastactivityid').val(arrayAct[1]);
				$('#activityfeed').css("display", "block"); 
			    $('#loading').css("display", "none");
			    $('#divchatfilter').css("display", "");
				
				 	if($('#pmarker').val() =='activityfeed'){
			   	 		$('#activityfeed').html(arrayAct[0]+$('#activityfeed').html());
					} else{
						funcYourFavourites(userid,onoff);
					}
					$("#autolang").trigger("click");
			  
				} else {
			   		if (filter=='friends' && (arrayAct[0]+$('#activityfeed').html()) ==''){
						$('#activityfeed').html('<span class="translate">No activity from your friends! Find more exciting friends <a href="find.php" >click here </a></span>')
						// no friends activity
				}
			 		  // xml empty
			   }
			$('#activityfeed').animate({scrollTop:0}, 1);
	  }
	});
  }
 }
}

function funcTenActivity(userid,onoff,privacyview){
var data = '';
var a = 0;
var f = 0;
 if ($('#lastactivityid').val()==''){
 	 f = 1;
	 $('#tenactivity_loading').css("display", "block");
	 $('#tenactivity').css("display", "none");
 }
 
   $.ajax({
	  type: "GET",
   		url: "calls.php?action=activityfeed&search=profile&userid="+userid+"&loguserid="+userid+"&lastactivityid="+$('#lastactivityid').val()+"&pv="+privacyview+"&pmarker="+$('#pmarker').val()+"&colour=f8f8f8&size=35", 
	  
      async: true,
      dataType: "html",
      success: function(html) {
			var arrayAct;
			arrayAct = html.split('|||');
			
			if (html.length >10){
			   
			$('#lastactivityid').val(arrayAct[1]);
			  $('#tenactivity').css("display", "block"); 
			  $('#tenactivity_loading').css("display", "none");
			  $('#tenactivity').html(arrayAct[0]+$('#tenactivity').html());
			$("#autolang").trigger("click");
			  
			} else {
			   		if ((arrayAct[0]+$('#tenactivity').html()) ==''){
						$('#tenactivity').html('<span class="translate">sorry no activity</span>')
						// no friends activity
					}
			 		  // xml empty
			  }
			$('#activityfeed').animate({scrollTop:0}, 1);
			//timers = setTimeout("$('#tenactivity').animate({ scrollTop:0}, 1);",12);
			//timers = setTimeout("funcTenActivity();",220000);
	  }
	});
}


function funcCreateAvatar(strAvatar,strSize,strColour){
	return $.ajax({url: "calls.php?action=create_avatar&avatar="+strAvatar+"&colour="+strColour+"&size="+strSize, async: false}).responseText;
}

function funcPlayingGame(gid,userid,onoff,privacyview){
	 $.ajax({url: "calls.php?action=activitysubmit&activitybody=Is+Playing+&gid="+gid+"&colour=f8f8f8&size=35"});
	 funcActivity($('#filter').val(),userid,onoff,privacyview);
 }
 
function funcSearchResults(strPage,strSort,strSearch,silent){
	strPage = parseInt(strPage);
	strSort = parseInt(strSort);
	
	var data = '';
	$('#search_loading').css("height", "50px");
	$('#search_loading').css("display", "");
	
	if (silent==2){
		$('#search_loading').css("height", $('#searchWrapper').height()-25 + "px");
	}
	
	$('#searchWrapper').css("display", "none");
	
	$.ajax({
	  type: "GET",
      url: "calls.php?action=searchgames&gp=" +strPage+ "&search=" + strSearch + "&sort="+strSort,
      dataType: "html",
		  success: function(html){ 
		 	 data = html;
			 var sgarray = data.split("|##|");
			$('#searchlabel').html('Your search for <b>'+strSearch+'</b> found <b>'+sgarray[0]+'</b> games:')
			$('#searchcount').html('Games Found ('+ sgarray[0]+')')
			$('#search_games').html('Sorry no matches found, please try again.');
			if(sgarray[0]>0){
			$('#sort').css('display','')	
			$('#search_games').html(sgarray[1]);
			}
			
   			
			 
			$('#search_loading').css("display", "none");
		  }
	  });
}
 
function funcReviews(page,gid,silent){
	var data = '';
	var a = 0;
	var pagecount;
	$('#comments_loading').css("height", "50px");
	if (silent==0){
		$('#comments_loading').css("display", "");
		$('#comments').css("display", "none");
	}
	if (silent==2){
		$('#comments_loading').css("display", "");
		$('#comments_loading').css("height", $('#commentWrapper').height()-25 + "px");
		$('#commentWrapper').css("display", "none");
	}
	
	$.ajax({
	  type: "GET",
      url: "calls.php?action=latestreviews&page=" +page+ "&gid=" + gid + "&colour=f8f8f8&size=65",
      dataType: "xml",
      success: function(xml){ 
	 	 $(xml).find('review').each(function(){
     			var id = $(this).attr('id');
				var userid = $(this).attr('userid');
				var username = $(this).attr('username');
				var userlink = $(this).attr('userlink');
				var useravatar = $(this).attr('useravatar');
				var usercity = $(this).attr('usercity');
				var rating = $(this).attr('rating');
				pagecount = $(this).attr('pagecount');
				var dateold = $(this).attr('dateold');	
				var title = $(this).attr('title');
				var body = $(this).attr('body').replace(/\n/g, '<br>');

				var report = '';
				report = '<a href="#" onclick="funcReport('+id+','+gid+');return false" id="reportreview'+id+'" name="reportreview'+id+'" class="report">report</a>';
				
				data += '<div class="comment"><a href="'+userlink+'" alt="'+username+'" ><img src="assets/graphics/'+ useravatar +'" width="65" height="65" border="none" /></a><div id="commentbox"><div class="tl"><div class="tr"><div class="bl"><div class="br"><div class="body">'+report+'<p class="translate">'+body+'</p><b>Posted by: <a href="'+userlink+'" alt="'+username+'">'+username+'</a> </b>'+dateold+'.</div></div></div></div></div></div><div class="clearer"></div></div><div class="clearer"></div>';	
				
		  });
				if (data==''){
			   		$('#comments_loading').css("display", "none");
					$('#comments').css("display", "");
					$('#commentWrapper').css("visibility", "");
			   } else{
	
			// paging
	
			data = '<div id="commentWrapper">' + data + '</div>';

	
			if(pagecount>0){
				var width = parseInt(((page+1)+' of '+(parseInt(pagecount)+1)).length)*8
				
				data += '<div class="paging" style="width:'+ (width+28) +'px">';
					if (page>0){
						data +='<div class="prev"><a href="#" onClick="funcReviews('+(page-1)+','+gid+',2);return false"><<<</a></div>';
					} else {
						data +='<div class="prevoff"><<<</div>';
					}
						data +='<div class="count" style="width:'+ width +'px"><div class="leftpaging"><div class="rightpaging"><div class="body">'+(page+1)+' <b>of</b> '+(parseInt(pagecount)+1)+'</div><div class="clearer"></div></div></div></div>';
					
				if (page!= pagecount){
						data +='<div class="next"><a href="#" onClick="funcReviews('+(page+1)+','+gid+',2);return false">>>></a></div>';
					} else {
						data +='<div class="nextoff">>>></div>';
					} 
					data +='</div><div class="clearer"></div>';
				 }
				 
				$('#comments').css("display", "");
				$('#commentWrapper').css("visibility", "");
				$('#comments_loading').css("display", "none");
				 
			   	$('#comments').html(data);
				
			   }
	  }
	});
} 


 

function funcShortUrl(txtBody){
	var replaceUrls = $.ajax({url: "urlshort.php?body="+document.getElementById(txtBody).value,async: false}).responseText;
		//alert(replaceUrls);
		if(replaceUrls !='[][]_EMPTY_[][]'){
			document.getElementById(txtBody).value = replaceUrls;
		}	
}


function characterCount(txtBody,txtCounter,e){
	var KeyID = (window.event) ? event.keyCode : e.keyCode;
	if(KeyID==32 || KeyID==13){
		funcShortUrl(txtBody);
	}
	
 max_length=140;
	 if (document.getElementById(txtBody).value.length != 0){
	  document.getElementById(txtCounter).style.display ='';
		
		if (document.getElementById(txtBody).value.length  > max_length ){
			document.getElementById(txtCounter).style.color ='red';	
			document.getElementById('btnUpdate').style.backgroundColor ='';	
			document.getElementById('btnUpdate').disabled=true;
			document.getElementById('btnUpdate').style.cursor = 'default';
		} else{
			document.getElementById(txtCounter).style.color ='';
			document.getElementById('btnUpdate').style.backgroundColor ='#13b5ea';	
			document.getElementById('btnUpdate').disabled='';	
			document.getElementById('btnUpdate').style.cursor = '';
		}
	 }else{
			document.getElementById(txtCounter).style.display ='none';
			document.getElementById('btnUpdate').style.backgroundColor ='';	
			document.getElementById('btnUpdate').disabled=true;
			document.getElementById('btnUpdate').style.cursor = 'default';
	 }
  document.getElementById(txtCounter).innerHTML = max_length - document.getElementById(txtBody).value.length;
}




function funcDOB(valDay,valMonth,valYear){
	var strDOBField = document.getElementById('date_of_birth'); 
	if (valDay =='' && valMonth == '' && valYear == ''){
	}else{
		strDOBField.value =valYear + "-" + valMonth + "-" + valDay; 
	 }
}


function funcCompare(val1,val2,val3){
  var strTwitter =' ';
  
  if (val3==3){
	  strTwitter = ' twitter ';
  }
  
  
  if (val3==1 || val3==3){
	  if (val1 =='' || val2 == ''){
	   alert('The following error(s) occurred:\n  blank' + strTwitter + 'password');
		  document.MM_returnValue = false;
	  }else{
		 if (val1 !=val2)	{
			 alert('The following error(s) occurred:\n' + strTwitter + 'password mismatch');
			 document.MM_returnValue = false;
			  } else {
			  document.MM_returnValue = true;
		  }
		}
  }
  
    if (val3==2){
		  if (val1 =='' || val2 == ''){
		   alert('The following error(s) occurred:\n  blank email');
			  document.MM_returnValue = false;
		  }else{
			 if (val1 !=val2)	{
				 alert('The following error(s) occurred:\n email mismatch');
				 document.MM_returnValue = false;
				  } else {
				  document.MM_returnValue = true;
			  }
			  }
  }
  
}


function MM_validateForm() { //v4.0
  if (document.getElementById){
    var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
    for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=document.getElementById(args[i]);
      if (val) { nm=val.name.replace(/_/g,' '); if ((val=val.value)!="") {
        if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@');
          if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.\n';
        } else if (test!='R') { num = parseFloat(val);
          if (isNaN(val)) errors+='- '+nm+' must contain a number.\n';
          if (test.indexOf('inRange') != -1) { p=test.indexOf(':');
            min=test.substring(8,p); max=test.substring(p+1);
            if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';
      } } } else if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\n'; }
    } if (errors) alert('The following error(s) occurred:\n'+errors);
    document.MM_returnValue = (errors == '');
} }



function funcFluFriendsBuild(){
		var btnSave = document.getElementById('btnSaveFriendsList');
		var strDivField = document.getElementById('divflufriends'); 
		var strHiddenField = document.getElementById('flufriends'); 
	 	var strSglComma = String.fromCharCode(39);
		
		if(strHiddenField.value.indexOf('||')!=-1 ){
			btnSave.style.display ='inline';
			var arrayMy = strHiddenField.value.split("||");
			var i = 0;
			var strHolder ='';
			var arraySub={};
			var strContactDel ={};
			
						for (i=0,n=parseInt(arrayMy.length); i<n; i++){	
								arraySub = arrayMy[i].split("##");
								strContactDel = '';
								
								if (arraySub[1].replace('|','') !='' && arraySub[2].replace('|','') !=''){
									strContactDel = ' / ';
								}

							strHolder += '<tr><td>'+arraySub[3].replace('|','') +'</td>'+
										 '<td>'+arraySub[0].replace('|','')+'</td>'+
										 '<td>'+arraySub[1].replace('|','')+ strContactDel + 
										 arraySub[2].replace('|','')+'</td>'+ 
										 '<td align="right"><input type="button" name="btnRemove" id="btnRemove" value="remove" onClick="funcFluFriendsRemove(' +strSglComma+'|'+arraySub[0].replace('|','') + '##' +arraySub[1].replace('|','') + '##' + arraySub[2].replace('|','') + '##' + arraySub[3].replace('|','') + '|' +strSglComma+ ');"/></td></tr>';		
									
									strContactDel ='';
									i++;
							}
					strDivField.innerHTML = '<table width="100%" border="0" cellspacing="0" cellpadding="0">' + strHolder +	'</table>';	
		} else {
			
			if(strHiddenField.value.indexOf('##')!=-1 ){
				var arrayMy = strHiddenField.value.split('##');
				var strContactDel = '';
						if (arrayMy[1].replace('|','') !='' && arrayMy[2].replace('|','') !=''){
									strContactDel = ' / ';
								}
			
			 strDivField.innerHTML = '<table width="100%" border="0" cellspacing="0" cellpadding="0">'+
			 						 '<tr><td>' + arrayMy[3].replace('|','') + '</td>'+
									 '<td>' + arrayMy[0].replace('|','') + '</td>'+
									 '<td>' + arrayMy[1].replace('|','') + strContactDel +
									 arrayMy[2].replace('|','') + '</td>'+
									 '<td align="right"><input type="button" name="btnRemove" id="btnRemove" value="remove" onClick="funcFluFriendsRemove(' +strSglComma+strHiddenField.value + strSglComma + ');"/></td></tr></table>';
										btnSave.style.display ='inline';
									} else {
									 	strDivField.innerHTML ='';
										 btnSave.style.display ='none';
									 }
		}
		
	return false;
}

function funcFluFriendsRemove(str){
	var strDivField = document.getElementById('divflufriends'); 
    var strHiddenField = document.getElementById('flufriends'); 
	strHiddenField.value = strHiddenField.value.replace(str,'');
	funcFluFriendsBuild();
}

function funcFluFriendsAdd(){
		var strCritterField = document.getElementById('friendcritter'); 
		var strNameField = document.getElementById('friendname'); 
		var strEmailField = document.getElementById('friendemail'); 
		var strPhoneField = document.getElementById('friendphone'); 
		
		var strHiddenField = document.getElementById('flufriends'); 
		
		var strSglComma = String.fromCharCode(39);
		var strError = '';
		
		if (strNameField.value =='' || strNameField.value =='name') {
			strError += 'blank name\n';
		}
		
		if ((strPhoneField.value =='' || strPhoneField.value =='phone') && (strEmailField.value =='' || strEmailField.value =='email')) {
			strError += 'blank contact information\n';
		}
		
			if (strPhoneField.value =='phone') {
				strPhoneField.value ='';
			}
			if(strEmailField.value =='email'){
				strEmailField.value='';
			}
		
		if (strError !='' ){
			alert('Invalid friend information \n\n'+strError);
		} else{
			
			strHiddenField.value += '|' + strNameField.value.replace(strSglComma,'') + '##' + strEmailField.value + '##' + strPhoneField.value + '##' + strCritterField.value + '|';
				
				strCritterField.value='1'
				strNameField.value ='name';
				strEmailField.value ='email';
				strPhoneField.value ='phone';
				funcFluFriendsBuild();
		}
}

function funcCountSubStr(haystack,needle){
var count = 0; 
	if(haystack!=null){
		for (var i=0;i<haystack.length;i++) { 
			if (needle == haystack.substr(i,needle.length)){
				count++; 
			} 
		}
	}
return count;
}

function MM_goToURL() { //v3.0
  var i, args=MM_goToURL.arguments; document.MM_returnValue = false;
  for (i=0; i<(args.length-1); i+=2) eval(args[i]+".location='"+args[i+1]+"'");
}
function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}

function funcAddFav(id,strTitle,strImage,userid,onoff,privacyview,facebook,cdndomain,firstname){
var timers = {}; 
clearTimeout(timers);

	if (userid!=''){
		$('#addfav'+id).css("display", "none");
		$('#fav_loading'+id).css("display", "");
		timers = setTimeout(function(){$('#removefav'+id).css("display", "");$('#fav_loading'+id).css("display", "none");},10);
		$.ajax({url: "calls.php?action=addfave&as=<?=md5(session_id())?>&pid="+id})
		
		 if(facebook){
		funcFaceBookPublish(cdndomain + "assets/games/images/"+strImage+"",firstname+" Has added " +strTitle+ " Games to their favourites.","Play Free Games!","http://"+window.location.hostname+"/index.php?id="+id+"&gp=0",null);

		 } 
	} else { 
		alert('you need to be logged in to add to your favourite list.');
	} 
		if($('#pmarker').val()=='activityfeed'){
			funcActivity($('#filter').val(),userid,onoff,privacyview);
		}else if ($('#pmarker').val()=='favourites'){
			funcYourFavourites(userid,onoff);
		} else {
			$('#pmarker').val('recentlyplayed');
			funcYourRecently(userid,onoff);	
	 }
}


function funcMoreCat(){
	if($("#moregamecats").css("display")=='none'){
		$("#moregamecats").css("display","");
		$("#navigation ul li.more a").css("background","url(assets/graphics/template/arrowUp.png) no-repeat right 7px;");
		$("#navigation ul li.more a").css("padding-right","18px");
		$("#navigation ul li.more a").html("Less");
		$('#banner_right').css("top",(159+$("#moregamecats").height()+30)+"px");
	} else {
		$("#moregamecats").css("display","none");
		$("#navigation ul li.more a").css("background","url(assets/graphics/template/arrowDown.png) no-repeat right 7px;");
		$("#navigation ul li.more a").css("padding-right","14px");
		$("#navigation ul li.more a").html("More");
		$('#banner_right').css("top","159px");
		
	}
}
function funcSearch(fld,action,key,baseDomain,onoff){
	if(fld.value=='' && action =='blur'){
		fld.value ='search games...';
	}
	if(fld.value=='search games...' && action =='focus'){
		fld.value ='';
	}
	if(key!='' && key!='search games...' && action =='search'){
		if(key.replace(/ /g, "").length <=2){
			alert('Please refine your search term, as its too short');
			return;
		}
		
		if(checkIllegalCharsSearch(key) == false){
			alert('Please refine your search term, as it contains illegal characters');
			return;
		}
		 key = key.replace(/ /g, "-")
		 window.location = baseDomain+funcJavaUrlRewriter('/index.php?gp=0&sort=3&search='+key,'/Search/'+key+'/0-3/',onoff);
	}
}

function handleEnter(inField, e) {    
var charCode;
 	if(e && e.which){
 	 charCode = e.which;
  }else if(window.event){
  	 e = window.event;
  	 charCode = e.keyCode; 
   }    
  	 if(charCode == 13) { 
		 funcSearch('','search',inField.value);  
	}
}

function funcFeaturedFlash(id){
var isIE = navigator.appName.indexOf("Microsoft") != -1;
	if(isIE){
		window['featflash'].setFeature(id);
	} else{
		document['featflash'].setFeature(id);
	}
	funcFeaturedGame(id);
}

function funcFeaturedGame(id){
var total = 4;
	var prev = id-1;
	if(id == 1){
		prev = total;
	}
	$("#gameDetails-"+prev).fadeOut(400);
	setTimeout(function(){
		$("#gameDetails-"+id).fadeIn(400);
	},410);
	//show active one
	
	
	
	$("#featuredList").animate({top: -116},500,function(){
		$("#featuredList").append($("#featuredList>div:first"));
		$("#featuredList").css({top : 0});						  
	});
	
}

  function funcCatRoll(cat,game){
	 for (i=0; i<=5; i++) {
	
			if (i==game){
				$('#catthumb_'+cat+'_'+i+'').css('display','');
				$('#catlink_'+cat+'_'+i+'').addClass('catOver');
				$('#catlink_'+cat+'_'+i+'').removeClass('catOut');
				$('#catlink_'+cat+'_'+i+' a').addClass('active');
				$('#catlink_'+cat+'_'+i+'').addClass('active');
				
			} else{
				$('#catthumb_'+cat+'_'+i+'').css('display','none');
				$('#catlink_'+cat+'_'+i+'').removeClass('catOver');
				$('#catlink_'+cat+'_'+i+'').addClass('catOut');
				$('#catlink_'+cat+'_'+i+' a').removeClass('active');
				$('#catlink_'+cat+'_'+i+'').removeClass('active');
		}
	 }
	}
	
	function funcRemoveHomeFav(id){
		$('#removefav'+id).css("display", "none");
		$('#fav_loading'+id).css("display", "");
		$('#addfav'+id).css("display", "");
		$('#fav_loading'+id).css("display", "none");
		$.ajax({url: "calls.php?action=removefave&pid="+id});
	 }

