/** DEFINE SOME GLOBAL VARIABLES **/
var WWW = 'http://www.trickerbattle.com';
var sURL = unescape(window.location.pathname);
//var youtubeRegex = /https?:\/\/(?:[a-zA_Z]{2,3}.)?(?:youtube\.com\/watch\?)((?:[\w\d\-\_\=]+&amp;(?:amp;)?)*v(?:&lt;[A-Z]+&gt;)?=([0-9a-zA-Z\-\_]+))/i;
var youtubeRegex = /http:\/\/(.*youtube\.com\/watch.*|.*\.youtube\.com\/v\/.*|youtu\.be\/.*|.*\.youtube\.com\/user\/.*#.*|.*\.youtube\.com\/.*#.*\/.*)/i
//var vimeoRegex = /http:\/\/(www.vimeo|vimeo)\.com(\/|\/clip:)(\d+)(.*?)/;
var vimeoRegex = /http:\/\/(www\.vimeo\.com\/groups\/.*\/videos\/.*|www\.vimeo\.com\/.*|vimeo\.com\/groups\/.*\/videos\/.*|vimeo\.com\/.*)/i
window.APP_FB_UID = 109855759055143;
window.USER_ID = getCookie('USER_ID');
window.PHPSESSID = getCookie('PHPSESSID');
window.fb_uid = getCookie('fb_uid');
window.fb_name = getCookie('fb_name');
window.fb_profile_pic = getCookie('fb_profile_pic');
window.force_wildcard_trick_alert = false;

//alert(window.fb_uid);
window.filteredUsersArray = new Array(window.USER_ID);
window.filteredUsers = window.USER_ID;

/** ARRAY FOR MODS ***/
var mod_array = new Array(5094,5126,1234);

/** GLOBALIZE PERMISSIONS - IF YOU ADD ANY, DO NOT FORGET TO ALSO ADD TO THE SET_USER_PREF FUNCTION ON LINE 1928 (AT THE TIME OF THIS COMMENT) **/
window.fbStreamPublishOnBattleInitiate = getCookie('fb_stream_publish_on_battle_initiate');
window.fbStreamPublishWhenChallenged = getCookie('fb_stream_publish_when_challenged');
window.fbStreamPublishOnChallengeAccept = getCookie('fb_stream_publish_on_challenge_accept');
window.fbStreamPublishWhenChallengeAccepted = getCookie('fb_stream_publish_when_challenge_accepted');
window.fbSyncOnLogin = getCookie('fb_sync_on_login');
	
/** CONSTANT FOR _SEE DESCRIPTION_ TRICK ID */
var wildcard_trick_id = 313;

/** USE THIS FUNCTION UNTIL --ALL-- BROWSERS HAVE A NATIVE SUPPORT */
document.getElementsByClassName = function(cl) {
var retnode = [];
var myclass = new RegExp('\\b'+cl+'\\b');
var elem = this.getElementsByTagName('*');
for (var i = 0; i < elem.length; i++) {
var classes = elem[i].className;
if (myclass.test(classes)) retnode.push(elem[i]);
}
return retnode;
}; 

/** UNIX TIME STAMP CONVERTER **/
function EpochToHuman(t){
	var inputtext = (t*1);
	var outputtext = "";
	var extraInfo = 0;
	if(inputtext > 1000000000000){
		//outputtext += "<b>Assuming that this timestamp is in milliseconds:</b><br/>";	
	}else{
		if(inputtext > 10000000000)extraInfo=1;
		inputtext=(inputtext*1000);
	}
	var datum = new Date(inputtext);
	var hour = datum.getHours();
	var meridiem = (hour < 12)? 'am' : 'pm';
	hour = (hour < 13)? hour : hour - 12;
	var minutes = (datum.getMinutes() < 10)? '0' + datum.getMinutes() : datum.getMinutes();
	var dateString = datum.toLocaleDateString();
	var baseTime = dateString+ ' ' + hour + ':' + minutes + meridiem;
	
	return baseTime;	
}

/** NL2BR RECREATION ***/
String.prototype.nl2br = function() {
var breakTag = '<br />';
return (this + '').replace(/([^&gt;]?)\n/g, '$1'+ breakTag +'\n');
}

/** ADD SLASHES & STRIP SLASHES RECREATION ***/
function addslashes(str) {
	if(typeof(str) == 'undefined')
		return false;

	str=str.replace(/\\/g,'\\\\');
	str=str.replace(/\'/g,'\\\'');
	str=str.replace(/\"/g,'\\"');
	str=str.replace(/\0/g,'\\0');
	return str;
}
function stripslashes(str) {

	if(typeof(str) == 'undefined')
		return false;

	str=str.replace(/\\'/g,'\'');
	str=str.replace(/\\"/g,'"');
	str=str.replace(/\\0/g,'\0');
	str=str.replace(/\\\\/g,'\\');
	return str;
}

/** SLEEP FUNCTION **/
function sleep(delay){

	var start = new Date().getTime();
	while (new Date().getTime() < start + delay);
}

/** SET TAB INDEX ON ELEMENTS IN A FORM */
function tabIndexify(form){
	
	e = document.getElementById(form).elements;

	for (i=1;i<e.length;i++)
		e[i].tabIndex = i;
	
}

/** FUNCTION TO MIMICK PHPs in_array **/
Array.prototype.has=function(v){
for (i=0; i<this.length; i++){
if (this[i]==v) return i;
}
return false;
}

/** DYNAMIC PROGRESS BAR **/
function updateProgressBar(containerID,barID,percent){

	container = document.getElementById(containerID);
	containerWidth = parseInt(container.style.width);
	
	bar = document.getElementById(barID);
	
	bar.style.width = Math.round(containerWidth * (parseInt(percent)/100))+"px";
	//alert(bar.style.width);
	
}

/** CHECK KEY PRESS TO SEE IF SHIFT ENTER OR CTRL ENTER, ETC */
function chkKey(evt) {

	alert('key was pressed');

	var mykey, alt, ctrl, shift, str;
	if (window.Event) {
		mykey = evt.which;
		alt = (evt.modifiers & Event.ALT_MASK) ? true : false;
		ctrl = (evt.modifiers & Event.CONTROL_MASK) ? true : false;
		shift = (evt.modifiers & Event.SHIFT_MASK) ? true : false;
	} 
	else {
		mykey = event.keyCode;
		alt = event.altKey;
		ctrl = event.ctrlKey;
		shift = event.shiftKey;
	}
	
	if(shift && mykey == 13) {
	alert("Shift-Enter was pressed");
	}
	return true;
}

/** CREATE COOKIE */
function setCookie(c_name,value,expiredays)
{
/**
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+
	((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
*/
	// we cant pass a fully qualified url as a query string argument, so mask it here - php will switch it back
	value = value.replace('http://','HTTPHERE');
	
	var dataString = 'c_key='+c_name+'&c_val='+value;
	$.ajax({
		type: "GET",
		url: WWW+"/ajax.set-cookie.php",
		data: dataString,
		success: function(data) {

			//$('#ajax_msg').show().html(data);
			//setTimeout("fade_div('ajax_msg')",3000);
			
		}
	});

}

/** GET COOKIE */
function getCookie(c_name){
	if (document.cookie.length>0){
		c_start=document.cookie.indexOf(c_name + "=");

		if (c_start!=-1){
			c_start=c_start + c_name.length+1;
			c_end=document.cookie.indexOf(";",c_start);
			if (c_end==-1) c_end=document.cookie.length;
			return unescape(document.cookie.substring(c_start,c_end));
		}
	}
	return "";
}

/** DELETE A COOKIE **/
function eraseCookie(name) {
    setCookie(name,"",-1);
}

/** DELETE ALL COOKIES **/
function deleteAllCookies(){

	var cookies = document.cookie.split(";");
	for (var i = 0; i < cookies.length; i++)
	  eraseCookie(cookies[i].split("=")[0]);
}

/** POPULATES EVENT ADDRESS FORM */
function use_saved_event_address(address,country_code){

	document.getElementById('address').value=address;
	document.getElementById('country_code').value=country_code;
}

/** HIDES DIV */
function hide_div(div_id){
	//document.getElementById(div_id).style.visibility='hidden';
	document.getElementById(div_id).style.display='none';
}

/** SHOW DIV */
function show_div(div_id){
	//document.getElementById(div_id).style.visibility='visible';
	document.getElementById(div_id).style.display='block';
}

/** FADE DIV */
function fade_div(div_id){
$("div#"+div_id).fadeOut("slow");

}

/** ON USER.ADD-VIDEO.PHP, THIS DETERMINES WHICH SELECT MENU APPEARS, SINGLE OR MULTI */
function user_video_trick_select(thisForm){
	
	// SINGLE TRICK
	if(thisForm.uv_uvc_id.value == 1){
    
		show_div('trick_select_container');
		show_div('uv_featured_trick_container');
		hide_div('uv_featured_tricks_container'); 
		hide_div('successful_trick_msg'); 
	}
	// COMBO OR TUTORIAL
	if(thisForm.uv_uvc_id.value == 2 || thisForm.uv_uvc_id.value == 8){
    
		show_div('trick_select_container');
		hide_div('uv_featured_trick_container');
		show_div('uv_featured_tricks_container'); 
		hide_div('successful_trick_msg'); 
	}
	// FORM, SAMPLER, SHOWREEL, OR CRASH COMBO
	if(thisForm.uv_uvc_id.value == 3 || thisForm.uv_uvc_id.value == 4 || thisForm.uv_uvc_id.value == 5 || thisForm.uv_uvc_id.value == 7){
	
		show_div('trick_select_container');
		hide_div('uv_featured_trick_container');
		show_div('uv_featured_tricks_container'); 
		show_div('successful_trick_msg'); 
	}
	// CRASH TRICK
	if(thisForm.uv_uvc_id.value == 6){
	
		show_div('trick_select_container');
		hide_div('uv_featured_trick_container');
		hide_div('uv_featured_tricks_container'); 
		hide_div('successful_trick_msg'); 
	}
	
}

function selectAll(field,_v){

	for(var i=0;i<document.getElementById(field).length;i++)
		document.getElementById(field)[i].selected=_v;

}

function checkAll(field,_v){
	for(var i=0;i<document.getElementsByName(field).length;i++)
		document.getElementsByName(field)[i].checked=_v;

}

function toggleDiv(box,div) {
	if (box.checked)
		show_div(div);
	else
  		hide_div(div);
}

function setOpacity(opacity) {

	if (navigator.appName.indexOf("Netscape")!=-1 &&parseInt(navigator.appVersion)>=5)
    		document.getElementById('maincontent').style.MozOpacity=opacity/100
 	else
    		document.getElementById('maincontent').style.filter = 'alpha(opacity=' + value + ')';

		//document.getElementById('maincontent').style.opacity = value;
		//document.getElementById('maincontent').style.filter = 'alpha(opacity=' + value + ')';
}


//enforce max characters on field
function ismaxlength(obj){

	var mlength=obj.getAttribute ? parseInt(obj.getAttribute("maxlength")) : ""
	if (obj.getAttribute && obj.value.length>mlength)
	obj.value=obj.value.substring(0,mlength)
}


function letternumber(e)
{
var key;
var keychar;

if (window.event)
   key = window.event.keyCode;
else if (e)
   key = e.which;
else
   return true;
keychar = String.fromCharCode(key);
keychar = keychar.toLowerCase();

// control keys
if ((key==null) || (key==0) || (key==8) || 
    (key==9) || (key==13) || (key==27) )
   return true;

// alphas and numbers
else if ((("abcdefghijklmnopqrstuvwxyz0123456789").indexOf(keychar) > -1))
   return true;
else
   return false;
}

function numbersonly(e)
{
var key;
var keychar;

if (window.event)
   key = window.event.keyCode;
else if (e)
   key = e.which;
else
   return true;
keychar = String.fromCharCode(key);
keychar = keychar.toLowerCase();

// control keys
if ((key==null) || (key==0) || (key==8) || 
    (key==9) || (key==13) || (key==27) )
   return true;

// numbers only
else if ((("0123456789-.").indexOf(keychar) > -1))
   return true;
else
   return false;
}

function nokeys(e)
{
var key;
var keychar;

if (window.event)
   key = window.event.keyCode;
else if (e)
   key = e.which;
else
   return true;
keychar = String.fromCharCode(key);
keychar = keychar.toLowerCase();

// control keys
if ((key==null) || (key==0) || (key==8) || 
    (key==9) || (key==13) || (key==27) )
   return true;

// alphas and numbers
else if ((("x").indexOf(keychar) > -1))
   return true;
else
   return false;
}

function popUp(url) { open(url,"","height=450,width=450,scrollbars=1; window.focus()"); }
function converterPopUp(url) { open(url,"","height=220,width=320,scrollbars=0; window.focus()"); }

function openWin( windowURL, windowName, windowFeatures )
{
return window.open( windowURL, windowName, windowFeatures ) ;
}


function alertSize() {
  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement &&
      ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
 // window.alert( 'Width = ' + myWidth );
 // window.alert( 'Height = ' + myHeight );
 return myHeight;
}


function showColor(val) {
document.colorform.hexval.value = val;
document.all["colorbox"].style.backgroundColor = val;
}

function grabColor(field) {
field.value = document.colorform.hexval.value;
field.style.backgroundColor = field.value;
}




/* COOKIE FUNCTIONS */
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}


/** BROWSER DETECTION **/
var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari",
			versionSearch: "Version"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			   string: navigator.userAgent,
			   subString: "iPhone",
			   identity: "iPhone/iPod"
	    },
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();


var  TimeToFade = 1000.0;

function fade(eid)
{
  var element = document.getElementById(eid);
  if(element == null)
    return;
   
  if(element.FadeState == null)
  {
    if(element.style.opacity == null
        || element.style.opacity == ''
        || element.style.opacity == '1')
    {
      element.FadeState = 2;
    }
    else
    {
      element.FadeState = -2;
    }
  }
   
  if(element.FadeState == 1 || element.FadeState == -1)
  {
    element.FadeState = element.FadeState == 1 ? -1 : 1;
    element.FadeTimeLeft = TimeToFade - element.FadeTimeLeft;
  }
  else
  {
    element.FadeState = element.FadeState == 2 ? -1 : 1;
    element.FadeTimeLeft = TimeToFade;
    setTimeout("animateFade(" + new Date().getTime() + ",'" + eid + "')", 33);
  }  
}

function  animateFade(lastTick, eid)
{  
  var curTick = new Date().getTime();
  var elapsedTicks = curTick - lastTick;
 
  var element = document.getElementById(eid);
 
  if(element.FadeTimeLeft <= elapsedTicks)
  {
    element.style.opacity = element.FadeState == 1 ? '1' : '0';
    element.style.filter = 'alpha(opacity = '
        + (element.FadeState == 1 ? '100' : '0') + ')';
    element.FadeState = element.FadeState == 1 ? 2 : -2;
    
    return;
  }
 
  element.FadeTimeLeft -= elapsedTicks;
  var newOpVal = element.FadeTimeLeft/TimeToFade;
  if(element.FadeState == 1)
    newOpVal = 1 - newOpVal;

  element.style.opacity = newOpVal;
  element.style.filter = 'alpha(opacity = ' + (newOpVal*100) + ')';
 
  setTimeout("animateFade(" + curTick + ",'" + eid + "')", 33);
}

/** JQUERY SCROLLTO FUNCTION *************************************************/
jQuery.fn.extend({
  scrollTo : function(speed, easing) {
    return this.each(function() {
      var targetOffset = $(this).offset().top;
      $('html,body').animate({scrollTop: targetOffset}, speed, easing);
    });
  }
});

/** SLIDING PANEL ************************************************************/
$(document).ready(function() {
	
	// Expand Panel
	$("#open").click(function(){
		$("div#dashboard").slideDown("slow");
	
	});	
	
	// Collapse Panel
	$("#close").click(function(){
		$("div#dashboard").slideUp("slow");
		load_dashboard();
		resetFilteredUsersArray();
	});		
	
	// Switch buttons from "Log In | Register" to "Close Panel" on click
	$("#toggle a").click(function () {
		$("#toggle a").toggle();
	});		
		
});


function urlencode (str) {
    // http://kevin.vanzonneveld.net
    // +   original by: Philip Peterson
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: AJ
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: travc
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Lars Fischer
    // +      input by: Ratheous
    // +      reimplemented by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Joris
    // +      reimplemented by: Brett Zamir (http://brett-zamir.me)
    // %          note 1: This reflects PHP 5.3/6.0+ behavior
    // %        note 2: Please be aware that this function expects to encode into UTF-8 encoded strings, as found on
    // %        note 2: pages served as UTF-8
    // *     example 1: urlencode('Kevin van Zonneveld!');
    // *     returns 1: 'Kevin+van+Zonneveld%21'
    // *     example 2: urlencode('http://kevin.vanzonneveld.net/');
    // *     returns 2: 'http%3A%2F%2Fkevin.vanzonneveld.net%2F'
    // *     example 3: urlencode('http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a');
    // *     returns 3: 'http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a'

    str = (str+'').toString();
    
    // Tilde should be allowed unescaped in future versions of PHP (as reflected below), but if you want to reflect current
    // PHP behavior, you would need to add ".replace(/~/g, '%7E');" to the following.
    return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').
                                                                    replace(/\)/g, '%29').replace(/\*/g, '%2A').replace(/%20/g, '+');
}


/** IPOD BUTTONS *************************************************************/
/*!
// iPhone-style Checkboxes jQuery plugin
// Copyright Thomas Reynolds, licensed GPL & MIT
*/
;(function($, iphoneStyle) {

// Constructor
$[iphoneStyle] = function(elem, options) {
  this.$elem = $(elem);
  
  // Import options into instance variables
  var obj = this;
  $.each(options, function(key, value) {
    obj[key] = value;
  });
  
  // Initialize the control
  this.wrapCheckboxWithDivs();
  this.attachEvents();
  this.disableTextSelection();
  
  if (this.resizeHandle)    { this.optionallyResize('handle'); }
  if (this.resizeContainer) { this.optionallyResize('container'); }
  
  this.initialPosition();
};

$.extend($[iphoneStyle].prototype, {
  // Wrap the existing input[type=checkbox] with divs for styling and grab DOM references to the created nodes
  wrapCheckboxWithDivs: function() {
    this.$elem.wrap('<div class="' + this.containerClass + '" />');
    this.container = this.$elem.parent();
    
    this.offLabel  = $('<label class="'+ this.labelOffClass +'">' +
                         '<span>'+ this.uncheckedLabel +'</span>' +
                       '</label>').appendTo(this.container);
    this.offSpan   = this.offLabel.children('span');
    
    this.onLabel   = $('<label class="'+ this.labelOnClass +'">' +
                         '<span>'+ this.checkedLabel +'</span>' +
                       '</label>').appendTo(this.container);
    this.onSpan    = this.onLabel.children('span');
    
    this.handle    = $('<div class="' + this.handleClass + '">' +
                         '<div class="' + this.handleRightClass + '">' +
                           '<div class="' + this.handleCenterClass + '" />' +
                         '</div>' +
                       '</div>').appendTo(this.container);
  },
  
  // Disable IE text selection, other browsers are handled in CSS
  disableTextSelection: function() {
    if (!$.browser.msie) { return; }

    // Elements containing text should be unselectable
    $.each([this.handle, this.offLabel, this.onLabel, this.container], function(el) {
      $(el).attr("unselectable", "on");
    });
  },
  
  // Automatically resize the handle or container
  optionallyResize: function(mode) {
    var onLabelWidth  = this.onLabel.width(),
        offLabelWidth = this.offLabel.width(),
        newWidth      = (onLabelWidth < offLabelWidth) ? onLabelWidth : offLabelWidth;

    if (mode == 'container') { newWidth += this.handle.width() + 15; }
    this[mode].css({ width: newWidth });
  },
  
  attachEvents: function() {
    var obj = this;
    
    // A mousedown anywhere in the control will start tracking for dragging
    this.container
      .bind('mousedown touchstart', function(event) {          
        event.preventDefault();
        
        if (obj.$elem.is(':disabled')) { return; }
          
        var x = event.pageX || event.originalEvent.changedTouches[0].pageX;
        $[iphoneStyle].currentlyClicking = obj.handle;
        $[iphoneStyle].dragStartPosition = x - (parseInt(obj.handle.css('left'), 10) || 0);
      })
    
      // Utilize event bubbling to handle drag on any element beneath the container
      .bind('iPhoneDrag', function(event, x) {
        event.preventDefault();
        
        if (obj.$elem.is(':disabled')) { return; }
        
        var p = (x - $[iphoneStyle].dragStartPosition) / obj.rightSide;
        if (p < 0) { p = 0; }
        if (p > 1) { p = 1; }
      
        obj.handle.css({ left: p * obj.rightSide });
        obj.onLabel.css({ width: p * obj.rightSide + 4 });
        obj.offSpan.css({ marginRight: -p * obj.rightSide });
        obj.onSpan.css({ marginLeft: -(1 - p) * obj.rightSide });
      })
    
        // Utilize event bubbling to handle drag end on any element beneath the container
      .bind('iPhoneDragEnd', function(event, x) {
        if (obj.$elem.is(':disabled')) { return; }
        
        if ($[iphoneStyle].dragging) {
          var p = (x - $[iphoneStyle].dragStartPosition) / obj.rightSide;
          obj.$elem.attr('checked', (p >= 0.5));
        } else {
          obj.$elem.attr('checked', !obj.$elem.attr('checked'));
        }

        $[iphoneStyle].currentlyClicking = null;
        $[iphoneStyle].dragging = null;
        obj.$elem.change();
      });
  
    // Animate when we get a change event
    this.$elem.change(function() {
      if (obj.$elem.is(':disabled')) {
        obj.container.addClass(obj.disabledClass);
        return false;
      } else {
        obj.container.removeClass(obj.disabledClass);
      }
      
      var new_left = obj.$elem.attr('checked') ? obj.rightSide : 0;

      obj.handle.animate({         left: new_left },                 obj.duration);
      obj.onLabel.animate({       width: new_left + 4 },             obj.duration);
      obj.offSpan.animate({ marginRight: -new_left },                obj.duration);
      obj.onSpan.animate({   marginLeft: new_left - obj.rightSide }, obj.duration);
    });
  },
  
  // Setup the control's inital position
  initialPosition: function() {
    this.offLabel.css({ width: this.container.width() - 5 });

    var offset = ($.browser.msie && $.browser.version < 7) ? 3 : 6;
    this.rightSide = this.container.width() - this.handle.width() - offset;

    if (this.$elem.is(':checked')) {
      this.handle.css({ left: this.rightSide });
      this.onLabel.css({ width: this.rightSide + 4 });
      this.offSpan.css({ marginRight: -this.rightSide });
    } else {
      this.onLabel.css({ width: 0 });
      this.onSpan.css({ marginLeft: -this.rightSide });
    }
    
    if (this.$elem.is(':disabled')) {
      this.container.addClass(this.disabledClass);
    }
  }
});

// jQuery-specific code
$.fn[iphoneStyle] = function(options) {
  var checkboxes = this.filter(':checkbox');
  
  // Fail early if we don't have any checkboxes passed in
  if (!checkboxes.length) { return this; }
  
  // Merge options passed in with global defaults
  var opt = $.extend({}, $[iphoneStyle].defaults, options);
  
  checkboxes.each(function() {
    $(this).data(iphoneStyle, new $[iphoneStyle](this, opt));
  });

  if (!$[iphoneStyle].initComplete) {
    // As the mouse moves on the page, animate if we are in a drag state
    $(document)
      .bind('mousemove touchmove', function(event) {
        if (!$[iphoneStyle].currentlyClicking) { return; }
        if (event.pageX != $[iphoneStyle].dragStartPosition) { $[iphoneStyle].dragging = true; }
        event.preventDefault();
    
        var x = event.pageX || event.originalEvent.changedTouches[0].pageX;
        $(event.target).trigger('iPhoneDrag', [x]);
      })

      // When the mouse comes up, leave drag state
      .bind('mouseup touchend', function(event) {        
        if (!$[iphoneStyle].currentlyClicking) { return; }
        event.preventDefault();
    
        var x = event.pageX || event.originalEvent.changedTouches[0].pageX;
        $($[iphoneStyle].currentlyClicking).trigger('iPhoneDragEnd', [x]);
      });
      
    $[iphoneStyle].initComplete = true;
  }
  
  return this;
}; // End of $.fn[iphoneStyle]

$[iphoneStyle].defaults = {
  duration:          200,                       // Time spent during slide animation
  checkedLabel:      'YES',                      // Text content of "on" state
  uncheckedLabel:    'NO',                     // Text content of "off" state
  resizeHandle:      true,                      // Automatically resize the handle to cover either label
  resizeContainer:   true,                      // Automatically resize the widget to contain the labels
  disabledClass:     'iPhoneCheckDisabled',
  containerClass:    'iPhoneCheckContainer',
  labelOnClass:      'iPhoneCheckLabelOn',
  labelOffClass:     'iPhoneCheckLabelOff',
  handleClass:       'iPhoneCheckHandle',
  handleCenterClass: 'iPhoneCheckHandleCenter',
  handleRightClass:  'iPhoneCheckHandleRight'
};

})(jQuery, 'iphoneStyle');


/*
###############################################################################
################## TAKEN FROM INC.FOOTER.PHP ##################################
###############################################################################
*/

/** WHEN AJAX CONNECTION IS COMPLETED, BLINK PAGE TITLE ******************/
function whenCompleted(){
	setTimeout('sexyTOGLoader()',100);
//		alert('completed');
	setTimeout("fade_div('ajax_msg')",2000);//fade out
	//blinkTitle();
}

/** FUNCTION CHECKS EMAIL PERMISSIONS AND ROUTES APPROPRIATELY ***********/
function checkPermsAndLogin(){
	
	/** ENSURE WE HAVE PERMISSION TO EMAIL USER **************************/
	FB.login(function(response) {
	
		$('#ajax_loading').show('slow');
		
		if (response.session) {
			if (response.perms) {
				//alert(response.perms);
				setLocalFacebookSession();
			} else {
				// user is logged in, but did not grant any permissions
				alert('Please allow the permission requests. If you do not want TrickerBattle posting to your wall, you can set that option in your config settings after you login.');
			}
		} else {
			// user is not logged in
			alert('Please allow the permission requests. If you do not want TrickerBattle posting to your wall, you can set that option in your config settings after you login.');
			$('#ajax_loading').hide('slow');
		}
	}, {perms:'publish_stream,offline_access'});


}

/** FUNCTION POST COMMENT ****************************************************/
function postComment(fb_xid,fb_comment){

	FB.api('/'+window.APP_FB_UID+'/comment', 'post', {
		
		xid: fb_xid,
		wall_text: fb_comment
	}, 
	function(response) {
		if (!response || response.error) {
	    		alert('Error occured');
	  	} else {
	    		alert('Comment ID: ' + response);
	  	}
	});

}

/** TEST FUNCTION TO POST TO WALL ********************************************/
function publishToWall(fb_uid, fb_message, fb_attachment_desc, fb_attachment_name, fb_attachment_caption, fb_attachment_url){


	FB.api('/'+fb_uid+'/feed', 'post', {
		
		name: fb_attachment_name,
		message: fb_message,
		link: fb_attachment_url,
		description: fb_attachment_desc,
		caption: (fb_attachment_caption)
	}, 
	function(response) {
		if (!response || response.error) {
	    		//alert('Error occured');
	  	} else {
	    		//alert('Post ID: ' + response);
	  	}
	});


   
   
/*
	 FB.ui(
	   {
	     	method: 'stream.publish',
		message: fb_message,
		attachment: {
			name: 'TrickerBattle Challenge',
			caption: '',
			description: (fb_attachment_desc),
			href: 'http://www.trickerbattle.com'
		},
	     action_links: [
	       { text: 'Go Battle!', href: 'http://www.trickerbattle.com' }
	     ],
	     user_message_prompt: 'TrickerBattle.com News Feed'
	   },
	   function(response) {
	     if (response && response.post_id) {
	       alert('Post was published.');
	     } else {
	       alert('Post was not published.');
	     }
	   }
	 );
*/

}

/** FUNCTION GRABS USERS FRIENDS *********************************************/
function getConnectedFriends(){

	$(document).ready(function() {

		if(!window.fb_uid){

			/** GRAB FACEBOOK UID ****************************************/
			var uid = FB.getSession().uid;
			window.fb_uid = uid;
		}
		
		FB.api(
		  {
		    method: 'fql.query',
		    query: 'SELECT uid FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1=' + uid + ') AND is_app_user = 1'
		  },
		  function(response) {

			for(var i=0; i<response.length; i++)
				alert('name = ' + response[i].name);


		  }
		);
	});	
}





/** FUNCTION GETS COMMENTS FROM COMMENT TABLE VIA FQL ************************/
function getLocalComments(xid,limit,offset){
	
	
	if(!limit)
		limit = 20;
	
	if(!offset)
		offset = 0;
		
	$(document).ready(function() {
		
		var total_comments = 0;

		var dataString = 'xid=' + xid +
			      '&limit=' + limit + 
			      '&offset=' + offset;
		
		$.ajax({
			type: "POST",
			url: WWW+"/ajax.get-comments.php",
			data: dataString,
			dataType:'text',
			success: function(response) {
			
			
				var str_html = '';
				var display_name = '';
				var comment = '';
				var profile_pic = '';
				var dataString = '';
				var post_time = '';
				var posterRow = '';
				var posterData = '';
				var responseData = '';
				var poster = '';
				var poster_list = '';
				var posterArray = new Array();
				var delete_link = '';
				var displaying_comments = '';


				posterData = response;


				/** CREATE NEXT PAGE AND PREV PAGE LINKS *************/
				var pager_div = '<div class="pager">';

				if((offset+1) > (limit*2))
					pager_div += '<img class="prev" src="http://www.trickerbattle.com/images/icons/app/rewindtostart.png" alt="First Page" title="First ' + limit + ' comments" onclick="getLocalComments(\'' + xid + '\',' + limit + ',0);" />&nbsp;&nbsp;&nbsp;';

				if(offset > 0)
					pager_div += '<img class="prev" src="http://www.trickerbattle.com/images/icons/app/play-back.png" alt="Prev Page" title="Previous ' + limit + ' comments" onclick="getLocalComments(\'' + xid + '\',' + limit + ','  + (offset-limit) + ');" />&nbsp;&nbsp;&nbsp;';

				if((offset+limit) < total_comments){
					pager_div += '<img class="next" src="http://www.trickerbattle.com/images/icons/app/play.png" alt="Next Page" title="Next ' + limit + ' comments" onclick="getLocalComments(\'' + xid + '\',' + limit + ','  + (offset+limit) + ');" />';
					//alert('offset = '+offset+' -- total = '+total_comments);
				}
				pager_div += '</div>';

				/** FAILSAFE FOR EMPTY COMMENTS BOX ******************/
				if(total_comments <= limit)
					pager_div = '';
				if((offset+limit) > total_comments){
					var offset_limit = total_comments;
					displaying_comments = 'Displaying all ' + offset_limit + 'comments';
				}
				else{
					var offset_limit = (offset+limit);
					displaying_comments = 'Displaying comments ' + (offset+1) + ' to ' + offset_limit;
				}

				/** TOUCH UPS ****************************************/
				if(total_comments < 3)
					displaying_comments = ''; // why bother.. user isnt stupid 

				/** DISPLAY WHAT COMMENT RANGE IS LOADED *************/
				pager_div += '<div style="float:left; width:auto; color:#9cd03f; font-size:12px;">' + displaying_comments + '</div>';
				str_html += pager_div + '<div class="clear"></div>';

				/** SPLIT DATA STRING INTO ARRAY */
				// [0] = total_comments
				// [1] = fromid
				// [2] = time
				// [3] = text
				// [4] = id
				// [5] = ufb_fb_uid
				// [6] = user_nickname
				// [7] = user_fname
				// [8] = user_lname
				// [9] = ufb_fb_profile_pic
				// [10]= c_user_id

				/** ITERATE THE DATA AND CREATE AN ARRAY WE CAN REFERENCE */
				response = response.split('|');

				/** ITERATE COMMENTS *********************************/			
				for(var i=0; i<response.length; i++){

					var c = response[i].split(',');
					
					//alert(c[2]);
					
					/** CHECK IF THIS IS SESSION USERS POST ******/
					if(window.fb_uid == c[1] || (mod_array.has(window.USER_ID) !== false))
						delete_link = '<div style="margin-top:10px;"><a style="font-style:italic; text-decoration:none; font-size:0.9em;" href="#" onclick="removeLocalComment(\'' + xid + '\',' + c[4] + '); return false;">Delete Comment</a></div>';
					else
						delete_link = '';
					
					//alert('uid='+window.fb_uid+' -- comment uid = ' + c[1]);

					/** NICKNAME CHECK ***************************/
					if(c[6])
						display_name = c[6];
					else
						display_name = c[7] + ' ' + c[8];

					if(c[9])
						profile_pic = c[9];
					else
						profile_pic = 'http://profile.ak.fbcdn.net/object2/56/110/q109855759055143_9952.jpg';

					/** REPLACE URLS WITH LINKS IN COMMENT *******/
					var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
					if(c[3]){
						comment = stripslashes(unescape(c[3]));
						//alert('comment = '+comment);
						comment = comment.replace('<','&lt;');
						comment = comment.replace('>','&gt;');
						comment = comment.replace("'",'&#039;');
						comment = comment.replace(exp, "<a href='$1' target='_blank'>$1</a>");
						comment = comment.nl2br();
						
						/** FORMAT TIME ******************************/
						post_time = EpochToHuman(c[2]);

						str_html+= '<div class="wallkit_post" id="comment_' + c[4] + '_container">'

							/** PROFILE PIC **/
							+  '<div class="wallkit_profile_pic">'
								+  '<a href="#" onclick="get_user_profile(' + c[10] + '); return false;"><img src="' + profile_pic + '" alt="" /></a>'
							+  '</div>'


							/** POST CONTENT **/
							+  '<div class="wallkit_postcontent">'

								+  '<h4>'
									+  '<a href="#" onclick="get_user_profile(' + c[10] + '); return false;">' + display_name + '</a>'
									+  '&nbsp;&nbsp;<span class="wall_time">' + post_time + '</span>'
								+  '</h4>'

								+ '<div>' + comment + '</div>'
								+ delete_link

							+  '</div>'
							+  '<div style="clear:both; margin-bottom:20px;"></div>'

						+  '</div>';
						
					} // end if comment exists

				} // next

				/** ADD ANOTHER PAGER AT THE BOTTOM ******************/
				str_html += pager_div + '<div class="clear"></div>';

				/** ADD COMMENTS DATA TO CONTAINER DIV ***************/
				$("#"+xid+"_comments").html(str_html);

					


		  	
		  	}
		});
	});

}


/** FUNCTION ADDS A COMMENT **************************************************/
function addLocalComment(xid, xid_title){
	
	var publish_to_stream_box = $("#"+xid+"_publish_to_stream");
	if(publish_to_stream_box.is(':checked'))
		var publish_to_stream = 'true';
	else
		var publish_to_stream = 'false';
		
	var text = $("#"+xid+"_text").val();
		
	var dataString='xid=' + xid +
			'&publish_to_stream=' + publish_to_stream + 
			'&text=' + text + 
			'&url=' + location.href;
			
	if(text == 'Add a comment...' || text == ''){
	
		$("#"+xid+"_text").effect("highlight", {}, 3000);
		return;
	}

	$.ajax({
		type: "POST",
		url: WWW+"/ajax.add-comment.php",
		data: dataString,
		success: function(data) {

			if(data == 'ok'){
				
				if(publish_to_stream == 'true'){
				
					var fb_attachment_desc = '';
					var fb_attachment_name = xid_title;
					var fb_attachment_caption = '';
					var fb_attachment_url = location.protocol + "//" + location.host + location.pathname + "#" + xid;

					// session_user
					var fb_message = text;
					publishToWall(window.fb_uid,fb_message,fb_attachment_desc,fb_attachment_name,fb_attachment_caption,fb_attachment_url);

					// app wall
					var fb_message = text;
					publishToWall(window.APP_FB_UID,fb_message,fb_attachment_desc,fb_attachment_name,fb_attachment_caption,fb_attachment_url);
					
					var posted_to_wall = true;
				}							

				//alert(data);
				var comment_msg = "Thank you for your comment!";
				
				if(posted_to_wall)
					comment_msg += ' It has been copied to your wall per your request.';
					
				$('#ajax_msg').show().html(comment_msg);
				setTimeout("fade_div('ajax_msg')",2000);
				var default_text = $("#"+xid+"_default_text").val();
				$("#"+xid+"_text").val(default_text);
				$("#"+xid+"_comments").hide('slow');
				setTimeout('getLocalComments("'+xid+'")',500);
				setTimeout('$("#'+xid+'_comments").show("slow")',1500);

			}
			else{
			
				$('#ajax_msg').show().html("There was an error processing your comment. Please try again later. Sorry!");
				setTimeout("fade_div('ajax_msg')",3000);
			
			}

		} // end success

	});


}

/** FUNCTION REMOVE A COMMENT ************************************************/
function removeLocalComment(xid,comment_id){
	
	
	var dataString='id=' + comment_id;
	
	$.ajax({
		type: "POST",
		url: WWW+"/ajax.remove-comment.php",
		data: dataString,
		success: function(data) {

			if(data == 'ok'){

				$('#ajax_msg').show().html("Comment deleted");
				setTimeout("fade_div('ajax_msg')",2000);
				$('#comment_' + comment_id + '_container').hide('slow');
			}
			else{
			
				$('#ajax_msg').show().html("There was an error deleting your comment. You may not have permission to do so.");
				alert(data);
				setTimeout("fade_div('ajax_msg')",3000);
			
			}

		} // end success

	});


}







/** FUNCTION GETS COMMENTS FROM COMMENT TABLE VIA FQL ************************/
function getComments(xid,limit,offset){
	
	
	if(!limit)
		limit = 20;
	
	if(!offset)
		offset = 0;
		
	$(document).ready(function() {
		
		var total_comments = 0;
		
		
		/** DAMN REDUNDANT API CALL JUST TO GET THE TOTAL POST COUNT */
		FB.api(
		  {
		    method: 'fql.query',
		    format: 'xml',
		    query: 'SELECT id FROM comment WHERE xid = "'+xid+'"'
		  },
		  function(response) {
		  	
		  	//alert('xid = '+xid);
		  	
		  	/** HERE WE SET THE TOTAL COMMENTS VALUE FOR THE PAGER */
			total_comments = response.length;
			//alert(total_comments);
		  }
		);
		
		/** TRUE API CALL TO GET COMMENTS BASED OFF OF OUR OFFSET AND LIMIT */
		FB.api(
		  {
		    method: 'fql.query',
		    format: 'xml',
		    query: 'SELECT fromid,time,text,id FROM comment WHERE xid = "'+xid+'" LIMIT '+ offset + ',' + limit
		  },
		  function(response) {
			
			var str_html = '';
			var display_name = '';
			var comment = '';
			var profile_pic = '';
			var dataString = '';
			var post_time = '';
			var posterRow = '';
			var posterData = '';
			var responseData = '';
			var poster = '';
			var poster_list = '';
			var posterArray = new Array();
			var delete_link = '';
			var displaying_comments = '';
			
			/** FIRST ITERATE RESPONSE TO POPULATE ARRAY OF UIDS SO WE ONLY HAVE TO MAKE ONE REQUEST TO THE SERVER */
			for(var i=0; i<response.length; i++){
				poster_list += response[i].fromid + ',';
			}
			
			/** TRIM COMMA ***************************************/
			poster_list = poster_list.replace(/(^,)|(,$)/g, "")
													
			/** AJAX GRAB USER DATA FOR EACH COMMENT **/
			//dataString = 'fb_uid=' + response[i].fromid;
			dataString = 'fb_uids=' + poster_list;
			
			responseData = $.ajax({
				type: "POST",
				url: WWW+"/ajax.get-comment-poster-data.php",
				data: dataString,
				dataType:'text',
				async: false,
				success: function(data) {
					//alert(data);

					posterData = data;
					
					/** SPLIT DATA STRING INTO ARRAY */
					// [0] = fb_uid
					// [1] = username
					// [2] = first name
					// [3] = last name
					// [4] = profile pic

					/** ITERATE THE DATA AND CREATE AN ARRAY WE CAN REFERENCE */
					posterRow = posterData.split('|');

					//alert('posterData = '+ posterData);

					/** WE NOW HAVE AN ARRAY OF ROWS *********************/
					/** ITERATE THESE ROWS AND USE THE FIRST ARRAY VALUE TO CREATE A NEW ARRAY WITH THE KEY BEING THAT VALUE */
					for(var i=0; i<posterRow.length; i++){

						//alert('row = '+posterRow[i]);

						poster = posterRow[i].split(',');

						posterArray[poster[0]] = new Array(poster[0],poster[1],poster[2],poster[3],poster[4]);

						//alert('poster0 = '+poster[0]+' array = '+posterArray.toString());
					}

					/** CREATE NEXT PAGE AND PREV PAGE LINKS *************/
					var pager_div = '<div class="pager">';

					if((offset+1) > (limit*2))
						pager_div += '<img class="prev" src="http://www.trickerbattle.com/images/icons/app/rewindtostart.png" alt="First Page" title="First ' + limit + ' comments" onclick="getComments(\'' + xid + '\',' + limit + ',0);" />&nbsp;&nbsp;&nbsp;';

					if(offset > 0)
						pager_div += '<img class="prev" src="http://www.trickerbattle.com/images/icons/app/play-back.png" alt="Prev Page" title="Previous ' + limit + ' comments" onclick="getComments(\'' + xid + '\',' + limit + ','  + (offset-limit) + ');" />&nbsp;&nbsp;&nbsp;';

					if((offset+limit) < total_comments){
						pager_div += '<img class="next" src="http://www.trickerbattle.com/images/icons/app/play.png" alt="Next Page" title="Next ' + limit + ' comments" onclick="getComments(\'' + xid + '\',' + limit + ','  + (offset+limit) + ');" />';
						//alert('offset = '+offset+' -- total = '+total_comments);
					}
					pager_div += '</div>';

					/** FAILSAFE FOR EMPTY COMMENTS BOX ******************/
					if(total_comments <= limit)
						pager_div = '';
					if((offset+limit) > total_comments){
						var offset_limit = total_comments;
						displaying_comments = 'Displaying all ' + offset_limit + 'comments';
					}
					else{
						var offset_limit = (offset+limit);
						displaying_comments = 'Displaying comments ' + (offset+1) + ' to ' + offset_limit;
					}

					/** TOUCH UPS ****************************************/
					if(total_comments < 3)
						displaying_comments = ''; // why bother.. user isnt stupid 

					/** DISPLAY WHAT COMMENT RANGE IS LOADED *************/
					pager_div += '<div style="float:left; width:auto; color:#9cd03f; font-size:12px;">' + displaying_comments + '</div>';
					str_html += pager_div + '<div class="clear"></div>';

					/** ITERATE COMMENTS *********************************/			
					for(var i=0; i<response.length; i++){

						/** CHECK IF THIS IS SESSION USERS POST ******/
						if(window.fb_uid == response[i].fromid)
							delete_link = '<div style="margin-top:10px;"><a style="font-style:italic; text-decoration:none; font-size:0.9em;" href="#" onclick="removeComment(\'' + xid + '\',' + response[i].id + '); return false;">Delete Comment</a></div>';
						else
							delete_link = '';

						if(posterArray[response[i].fromid][1])
							display_name = posterArray[response[i].fromid][1];
						else
							display_name = posterArray[response[i].fromid][2] + ' ' + posterArray[response[i].fromid][3];

						if(posterArray[response[i].fromid][4])
							profile_pic = posterArray[response[i].fromid][4];
						else
							profile_pic = 'http://profile.ak.fbcdn.net/object2/56/110/q109855759055143_9952.jpg';

						/** REPLACE URLS WITH LINKS IN COMMENT *******/
						var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
						comment = stripslashes(response[i].text);
						comment = comment.replace('<','&lt;');
						comment = comment.replace('>','&gt;');
						comment = comment.replace("'",'&#039;');
						comment = comment.replace(exp, "<a href='$1' target='_blank'>$1</a>");
						comment = comment.nl2br();

						/** FORMAT TIME ******************************/
						post_time = EpochToHuman(response[i].time);

						str_html+= '<div class="wallkit_post" id="comment_' + response[i].id + '_container">'

							/** PROFILE PIC **/
							+  '<div class="wallkit_profile_pic">'
								+  '<a href="LINK_TO_PROFILE"><img src="' + profile_pic + '" alt="" /></a>'
							+  '</div>'


							/** POST CONTENT **/
							+  '<div class="wallkit_postcontent">'

								+  '<h4>'
									+  '<a href="LINK_TO_PROFILE">' + display_name + '</a>'
									+  '&nbsp;&nbsp;<span class="wall_time">' + post_time + '</span>'
								+  '</h4>'

								+ '<div>' + comment + '</div>'
								+ delete_link

							+  '</div>'
							+  '<div style="clear:both; margin-bottom:20px;"></div>'

						+  '</div>';


					} // next

					/** ADD ANOTHER PAGER AT THE BOTTOM ******************/
					str_html += pager_div + '<div class="clear"></div>';

					/** ADD COMMENTS DATA TO CONTAINER DIV ***************/
					$("#"+xid+"_comments").html(str_html);

				}
			}).responseText;

		  	
		  }
		);
	});

}

/** FUNCTION ADDS A COMMENT **************************************************/
function addComment(xid, xid_title){
	
	var publish_to_stream_box = $("#"+xid+"_publish_to_stream");
	if(publish_to_stream_box.is(':checked'))
		var publish_to_stream = 'true';
	else
		var publish_to_stream = 'false';
		
	var text = $("#"+xid+"_text").val();
		
	var dataString='xid=' + xid +
			'&publish_to_stream=' + publish_to_stream + 
			'&text=' + text + 
			'&url=' + location.href;
			
	if(text == 'Add a comment...' || text == ''){
	
		$("#"+xid+"_text").effect("highlight", {}, 3000);
		return;
	}

	$.ajax({
		type: "POST",
		url: WWW+"/curl.add-comment.php",
		data: dataString,
		success: function(data) {

			if(data){
				
				if(publish_to_stream == 'true'){
				
					var fb_attachment_desc = '';
					var fb_attachment_name = xid_title;
					var fb_attachment_caption = '';
					var fb_attachment_url = location.protocol + "//" + location.host + location.pathname + "#" + xid;

					// session_user
					var fb_message = text;
					publishToWall(window.fb_uid,fb_message,fb_attachment_desc,fb_attachment_name,fb_attachment_caption,fb_attachment_url);

					// app wall
					var fb_message = text;
					publishToWall(window.APP_FB_UID,fb_message,fb_attachment_desc,fb_attachment_name,fb_attachment_caption,fb_attachment_url);
					
					var posted_to_wall = true;
				}							

				//alert(data);
				var comment_msg = "Thank you for your comment!";
				
				if(posted_to_wall)
					comment_msg += ' It has been copied to your wall per your request.';
					
				$('#ajax_msg').show().html(comment_msg);
				setTimeout("fade_div('ajax_msg')",2000);
				$("#"+xid+"_text").val('Add a comment...');
				$("#"+xid+"_comments").hide('slow');
				setTimeout('getComments("'+xid+'")',500);
				setTimeout('$("#'+xid+'_comments").show("slow")',1500);

			}
			else{
			
				$('#ajax_msg').show().html("There was an error processing your comment. Please try again later. Sorry!");
				setTimeout("fade_div('ajax_msg')",3000);
			
			}

		} // end success

	});


}

/** FUNCTION REMOVE A COMMENT ************************************************/
function removeComment(xid,comment_id){
	
	
	var dataString='xid=' + xid +
			'&comment_id=' + comment_id;
	
	$.ajax({
		type: "POST",
		url: WWW+"/curl.remove-comment.php",
		data: dataString,
		success: function(data) {

			if(data.indexOf('error') == -1){

				$('#ajax_msg').show().html("Comment deleted");
				setTimeout("fade_div('ajax_msg')",2000);
				$('#comment_' + comment_id + '_container').hide('slow');
			}
			else{
			
				$('#ajax_msg').show().html("There was an error deleting your comment. You may not have permission to do so.");
				alert(data);
				setTimeout("fade_div('ajax_msg')",3000);
			
			}

		} // end success

	});


}


/** FUNCTION SETS LOCAL SESSION FOR FB CONNECT *******************************/
function setLocalFacebookSession(){

	/** GRAB FACEBOOK UID ************************************************/
	var uid = FB.getSession().uid;
	window.fb_uid = uid;
	//alert('...uid is now '+uid);
	setCookie('fb_uid',uid);

	/** CONCATINATE QUERY STRING *****************************************/
	var queryString = "" +
	"fb_uid=" + uid +
	"&redir=" + urlencode(window.location);

	/** GRAB USER INFO HERE SO WE DONT HAVE TO MAKE PHP DO IT AND SLOW SHIT DOWN */
	// grab profile info
	FB.api(
	  {
	    method: 'fql.query',
	    query: 'SELECT name,username,pic_square FROM profile WHERE id=' + uid
	  },
	  function(response) {
		
		/* FOR SOME REASON WE CANT PASS THE PROFILE PIC URL IN THE QUERY STRING */
		/* SET AS COOKIE AND HAVE PHP READ IT IN AJAX FILE */
		setCookie('fb_profile_pic',response[0].pic_square,1);
		window.fb_profile_pic = response[0].pic_square;
		
		setCookie('fb_name',response[0].name,100);
		
		queryString = queryString + "&fb_name=" + response[0].name +
		"&fb_username=" + response[0].username;
	
	
		// delay for 1 second to allow cookies to be set
		sleep(1000);
		grab_gender_and_continue();
	  }
	);

	/** GRAB MORE USER INFO **********************************************/
	function grab_gender_and_continue(){

		// grab profile info
		FB.api(
		  {
			method: 'fql.query',
			query: 'SELECT sex FROM user WHERE uid=' + uid
		  },
		  function(response) {
			queryString = queryString +
			"&fb_gender=" + response[0].sex;
			"&fb_email=" + response[0].email;

			set_session_via_ajax();
		  }
		);

	}

	function set_session_via_ajax(){

		$.ajax({
			type: "GET",
			url: WWW+"/ajax.set-facebook-session.php",
			data: queryString,
			success: function(data) {

				$('#ajax_msg_absolute').show().html(data);
				$('html').scrollTo(500,'swing');
				//$('#ajax_loading').hide(); //let page refresh do it
				
				if(data == 'Synced with Facebook!'){
					setTimeout("fade_div('ajax_msg_absolute')",2000);//fade out
					
					//if(window.fb_uid != '100000987349893')
						setTimeout("window.location.reload()",3000);
				}

			}
		});

	}
}

/** FUNCTION DESTROYS PHP SESSION WHEN USER LEAVES SITE OR CLOSES BROWSER */
/** THIS IS IMPORTANT TO MAKE SURE OUR SESSIONS ARE CURRENT WITH FACEBOOKs COOKIES */
function destroy_facebook_session(){

	$.ajax({
		type: "GET",
		url: WWW+"/ajax.destroy-facebook-session.php",
		success: function(data) {
			
			$('#ajax_msg').show().html(data);
			setTimeout("fade_div('ajax_msg')",3000);
			
		}
	});

}

function destroy_session(){	

	$.ajax({
		type: "GET",
		url: WWW+"/ajax.destroy-session.php",
		success: function(data) {
			
			//alert('session destroyed');
			//$('#ajax_msg').show().html(data);
			//setTimeout("fade_div('ajax_msg')",3000);
			
		}
	});

}


/** FUNCTION GETS CALLED WHEN FBCONNECT LOGS OUT FACEBOOK USER ***********/
function php_logout(){
	window.location = WWW+"/logout";
}

function fb_logout(){
	FB.logout(php_logout());
}


/*
###################################
##### AJAX CALLS FOR DASHBOARD ####
###################################
*/

/** FUNCTION LOADS DASHBOARD *************************************************/
function load_dashboard(){

	$.ajax({
		type: "GET",
		url: WWW+"/inc.dashboard-home.php",
		data: "o=1",
		success: function(data) {

			$('#dashboard_content_ajax').html(data);
			
		}
	});
}


/** FUNCTION LOADS USER CONFIG MENU ******************************************/
function load_config_menu(){

	$.ajax({
		type: "GET",
		url: WWW+"/ajax.user-config.php",
		success: function(data) {

			$('#dashboard_content_ajax').html(data);
			
			$(document).ready(function() {
						

				var button = $('#upload_user_portrait_button'), interval;
				new AjaxUpload(button,{
					action: WWW+'/ajax.update-user-portrait.php',
					name: 'user_portrait',
					autoSubmit: true,

					onSubmit : function(file, ext){

						// filter only images
						if (! (ext && /^(jpg|png|jpeg|gif)$/i.test(ext))){
							// extension is not allowed
							alert('Error: invalid file extension');
							// cancel upload
							return false;
						}
						
						$('#current_portrait').fadeOut("slow");
						
						// change button text, when user selects file			
						button.html('Uploading <img src="http://www.trickerbattle.com/images/ajax-loader-green-16.gif" style="vertical-align:text-bottom;" />');

						// If you want to allow uploading only 1 file at time,
						// you can disable upload button
						this.disable();


					},
					onComplete: function(file, response){
						button.html('Upload new photo...');

						window.clearInterval(interval);

						// enable upload button
						this.enable();

						// add file to the list
						$('#current_portrait').html(response);						
						$('#current_portrait').fadeIn("slow");
					}
				});


				function setPref(e){
					
					var pref_val = 0;
					
					/** SET A VALUE TO SEND TO THE DATABASE */
					if(e.checked)
						pref_val = 1;
						

					/** CREATE CONCATINATED QUERY STRING */
					var dataString = 'pref_key=' + e.name +
							 '&pref_val=' + pref_val;

					/** AJAX CALLS FOR PREFERENCE UPDATES */
					$.ajax({
						type: "POST",
						url: WWW+"/ajax.set-user-preference.php",
						data: dataString,
						success: function(data) {

							load_config_menu();
							
							/** RE-GET THE COOKIES IN CASE THEY DID THIS FROM A BATTLE PAGE */
							window.fbStreamPublishOnBattleInitiate = getCookie('fb_stream_publish_on_battle_initiate');
							window.fbStreamPublishWhenChallenged = getCookie('fb_stream_publish_when_challenged');
							window.fbStreamPublishOnChallengeAccept = getCookie('fb_stream_publish_on_challenge_accept');
							window.fbStreamPublishWhenChallengeAccepted = getCookie('fb_stream_publish_when_challenge_accepted');
							window.fbSyncOnLogin = getCookie('fb_sync_on_login');


						} // end success

					});

				} // end setPref
			
				function checkUsernameAvail(u,ou){
				
					if(u.toLowerCase() == ou.toLowerCase()){
						
						$('#username_availability').html('');
						$('#username_update_container').hide('slow');
						$('#username').attr("disabled", false).css('color','#15ADFF');
						return;
					}
					
					//u=username, ou=original username
					var dataString = 'u='+u;
				
					$.ajax({
						type: "POST",
						url: WWW+"/ajax.check-username-availability.php",
						data: dataString,
						beforeSend: function(){
						
							$('#username').attr("disabled", true).css('color','#555');
						},
						success: function(data) {
							
							if(data == 'taken'){
								$('#username_availability').html('<span style="color:#999;">Username taken</span>');
								$('#username_update_container').hide('slow');
							}
							if(data == 'available'){
								$('#username_update_container').show('slow');
								$('#username_availability').html('<span style="color:#15ADFF;">Username available!</span>');
								$('#update_username_button').html('Change Username to '+u+'.');
							}
						},
						complete: function(){
						
							$('#username').attr("disabled", false).css('color','#15ADFF');
						}
					});	
					
					
				}
				
				
				/** WHEN UPDATE USERNAME BUTTON IS PRESSED, MAKE IT HAPPEN HERE */
				$('#update_username_button').click(function(){

					var dataString = 'u='+ $('#username').val();
					
					$.ajax({
						type: "POST",
						url: WWW+"/ajax.set-user-nickname.php",
						data: dataString,
						success: function(data) {
							
							$('#username_update_container').hide('slow');
							
							if(data == 'fail'){
								$('#username_availability').html('<span style="color:#999;">Error:Username was not changed!</span>');			
								$('#username').val($('#original_username').val());
							}
							else {
								$('#username_availability').html('<span style="color:#15ADFF;">Username changed to '+data+'!</span>');
								$('#username').val(data);
								$('#original_username').val(data);
							}
						}
					});	
					
				});
				
				$('#username').keyup(function(){
					
					var u = $('#username').val();
					
					if(u.length < 3){
						$('#username_update_container').hide('slow');
						return;
					}
						
					var ou = $('#original_username').val();
					
					checkUsernameAvail(u,ou);
				});
				
				
				$('input:checkbox.iphone').iphoneStyle();

				$('input:checkbox.iphone').change(function(){setPref(this);});
			});
			
			
		}
	});
}



/** FUNCTION LOADS BATTLE CREATOR MENU ***************************************/
function load_battle_creator_menu(){

	$.ajax({
		type: "GET",
		url: WWW+"/ajax.battle-create-menu.php",
		success: function(data) {

			$('#dashboard_content_ajax').html(data);
			
		}
	});
}


/** FUNCTION LOADS MANO-A-MANO BATTLE CREATE FORM ****************************/
function load_battle_creator_mano(bo_user_id,bo_user_fname,bo_user_lname,bo_user_nickname,bo_ufb_fb_uid,bo_ufb_fb_profile_pic){

	/** DEFINE PHP FILE FOR AJAX CALL ************************************/
	$.ajax({
		type: "GET",
		url: WWW+"/ajax.battle-create-mano.php",
		beforeSend: function(){
			
			$('#ajax_loading').show('slow');
		},
		success: function(data) {

			$('#ajax_loading').hide('slow');

			$('#dashboard_content_ajax').html(data);			

			if(typeof(bo_user_id) != "undefined"){
				
				/** PRELOAD OPPONENT IN AUTOSELECT FIELD *****/
				preload_mano_opponent(bo_user_id,bo_user_fname,bo_user_lname,bo_user_nickname,bo_ufb_fb_uid,bo_ufb_fb_profile_pic);
			}
			
			/** HANDLE FORM SUBMIT - VALIDATE ********************/
			/*
			$("div").click(function () {
			      $(this).effect("highlight", {}, 3000);
			});
			*/
			$("form").submit(function() {

				var formFail = false;

				/** OPPONENT *********************************/
				var b_opponent = $("#b_opponent_id").val();
				var b_opponent_name = $("#b_opponent_name").val();
				if (b_opponent == "") {
					$("#b_opponent").effect("highlight", {}, 3000);
					formFail = true;
				}

				/** TITLE ************************************/
				var b_title = $("#b_title").val();
				var b_default_title = document.getElementById('b_title').defaultValue;			
				if (b_title == "" || b_title == b_default_title) {
					$("#b_title").effect("highlight", {}, 3000);
					formFail = true;
				}

				/** VIDEO URL ********************************/
				var video_url = $("#video_url").val();
				if (video_url == "Video URL") {
					$("#video_url").effect("highlight", {}, 3000);
					formFail = true;
				}
				else{	
					/** COMPARE URL TO YOUTUBE FORMAT ****/
					if($("#video_url").val().match(youtubeRegex))
						var tmp=1; //alert('valid youtube url');

					/** COMPARE URL TO VIMEO FORMAT ******/
					else if($("#video_url").val().match(vimeoRegex))
						var tmp=1 //alert('valid vimeo url');

					/** SHOW ERROR MESSAGE ***************/
					else {						
						show_div('ajax_msg');	
						$('#ajax_msg').html("Invalid video url format - Youtube or Vimeo only please!");
						setTimeout("fade_div('ajax_msg')",3000);//fade out
						formFail = true;					
					}
				}

				/** JUDGING PANEL ****************************/
				var judging_method = $("#b_bjm_id").val();
				var private_judges = $("#b_private_judges_hidden").val(); 
				if (judging_method == 3) {
					if ($("#b_private_judge_1").val() == "") {
						$("#b_private_judge_1").effect("highlight", {}, 3000);
						formFail = true;
					}
					if ($("#b_private_judge_2").val() == "") {
						$("#b_private_judge_2").effect("highlight", {}, 3000);
						formFail = true;
					}
					if ($("#b_private_judge_3").val() == "") {
						$("#b_private_judge_3").effect("highlight", {}, 3000);
						formFail = true;
					}

				}

				/** SELECTED TRICKS **************************/
				var selected_tricks = $("#selected_tricks_list_hidden").val();
				if (selected_tricks == "") {
					$("#featured_tricks").effect("highlight", {}, 3000);
					formFail = true;
				}

				/** SELECTED TRICK TYPES *********************/
				var selected_trick_types = $("#selected_trick_types_list_hidden").val();
				var tricks_or_types = $("#tricks_or_types").val();
				if(tricks_or_types == "types"){
					if (selected_trick_types == "") {
						$("#featured_trick_types").effect("highlight", {}, 3000);
						formFail = true;
					}
				}
				
				/** AJAX FORM SUBMIT ONLY IF VALID FORM ******/
				if(formFail === false){


					/** CREATE CONCATINATED QUERY STRING */
					//b_bt_id=1 means battle type of head-to-head
					var dataString = 'b_bt_id=1' + 
							 '&b_opponent=' + b_opponent + 
							 '&b_opponent_name=' + b_opponent_name + 
							 '&video_url=' + urlencode(video_url);

					/** APPEND PRIVATE JUDGES IF APPLICABLE */
					if(judging_method == 3)
						dataString += '&b_bjm_id=3&private_judges=' + private_judges;
					else
						dataString += '&b_bjm_id=' + judging_method;

					/** APPEND THE REST OF THE FORM FIELDS */
					dataString += '&selected_tricks=' + selected_tricks +
						      '&selected_trick_types=' + selected_trick_types + 
						      '&tricks_or_types=' + $("#tricks_or_types").val() + 
						      '&b_title=' + b_title +
					              '&b_desc=' + $("#b_desc").val() +
						      '&b_bsm_id=' + $("#b_bsm_id").val() + 
						      '&b_ct_id=' + $("#b_ct_id").val() +
						      '&b_upp_id=' + $("#b_upp_id").val();
					
					/** GLOBALIZE SOME VARIABLES FOR FACEBOOK NOTIFICATION */
					window.battle_title = b_title;
					window.battle_desc = $("#b_desc").val();
					
					//alert (dataString);

					
					$.ajax({
						type: "POST",
						url: WWW+"/ajax.battle-initiate.php",
						data: dataString,
						success: function(data) {

							/** CLEAR OUT FILTERED USERS */
							window.filteredUsers = '';
							window.filteredUsersArray = new Array();
							
							load_pending_ajax = function(){

								$.ajax({
									type: "POST",
									url: WWW+"/ajax.get-pending-battles.php",
									data: dataString,
									success: function(data) {

										$('#dashboard_content_ajax').html(data);
			
										/** INITIALIZE TABLESORTER ************/
										$("#pending_battles").tablesorter({ 
											// sort on the deadline column, order asc 
											sortList: [[6,0]] 
										});

										/** INITIALIZE TOOLTIP ****************/
										tooltip();
										imgtooltip();

									} // end success

								});
							}
							
							show_div('ajax_msg');	
							$('#ajax_msg').html(data);
							
							if(data == 'Battle Initiated!'){
								
									
								if(tricks_or_types == 'tricks')
									var trick_list = window.battle_trick_names;
								if(tricks_or_types == 'types')
									var trick_list = window.battle_trick_type_names;

								var fb_attachment_desc = 'The battle consists of the following ' + window.battle_trick_or_combo + ': ' + trick_list.replace(/,/gi," -> ") + '. Check it out at TrickerBattle.com.';
								var fb_attachment_name = window.battle_title;
								var fb_attachment_caption = 'http://www.trickerbattle.com';
								var fb_attachment_url = 'http://www.trickerbattle.com/battles';
								if(window.battle_desc)
									fb_attachment_caption = window.battle_desc;

								/** HERE WE SHOULD POST TO FACEBOOK WALL **/
								if(window.fbStreamPublishOnBattleInitiate == 1){
									
									// challenger
									var fb_message = 'challenged ' + b_opponent_name + ' to a tricking battle!';
									publishToWall(window.fb_uid,fb_message,fb_attachment_desc,fb_attachment_name,fb_attachment_caption,fb_attachment_url);
								}
								
								/** CHECK OPPONENTS USER PREFERENCE IF THEY WANT TO BE NOTIFIED **/
								dataString = 'ufb_fb_uid=' + window.b_opponent_fb_uid +
									     '&pref_key=fb_stream_publish_when_challenged';
								$.ajax({
									type: "POST",
									url: WWW+"/ajax.get-user-pref.php",
									data: dataString,
									success: function(data) {
										
										if(data != 0){
											// opponent
											var fb_message = 'has challenged you to a tricking battle!';
											publishToWall(window.b_opponent_fb_uid,fb_message,fb_attachment_desc,fb_attachment_name,fb_attachment_caption,fb_attachment_url);
										}
										
									} // end success

								});


								// app wall
								var fb_message = 'has challenged ' + b_opponent_name + ' to a tricking battle!';
								publishToWall(window.APP_FB_UID,fb_message,fb_attachment_desc,fb_attachment_name,fb_attachment_caption,fb_attachment_url);									


									
								setTimeout("fade_div('ajax_msg')",2000); //fade out
								setTimeout("$('html').scrollTo(500,'swing')",2500);
								setTimeout("load_pending_ajax()",2800);
							
							}
							else
							alert('data = '+data);
						} // end success
						
					});

				}

					
				/** DONT SUBMIT FORM - AJAX ONLY *************/
				return false;
			});

			/** SHOW/HIDE PRIVATE JUDGES PANEL BASED ON SELECTION */
			$('#b_bjm_id').change(function() {
				if ($(this).val() == 3) { 
					//id of 3 = private judging panel
					$('#b_private_judges_container').show(500);
				}
				 else
					$('#b_private_judges_container').hide(500);
			});

			/** SHOW/HIDE TRICK TYPES BASED ON SELECTION *********/
			$('#tricks_or_types').change(function() {
				if ($(this).val() == 'types')					
					$('#trick_types_container').show(500);
				 else
					$('#trick_types_container').hide(500);
				
				/** THIS IS FOR THE WILDCARD TRICK ***********/
				window.force_wildcard_trick_alert = true;
				rebuildSelectedTricksList("selected_tricks_sortable");
			});

			/** CHECK FOR WILDCARD TRICK ON SCORING METHOD CHANGE */
			$('#b_bsm_id').change(function() {
				
				/** IF THIS IS NOT WIN / LOSS SCORING, CHECK FOR WILDCARD TRICK */
				if ($(this).val() != 3) {

					/** THIS IS FOR THE WILDCARD TRICK ***********/
					window.force_wildcard_trick_alert = true;
					rebuildSelectedTricksList("selected_tricks_sortable");
				
				}
			});

			/** ALERT THAT MONETARY CREDITS ARE COMING SOON */
			$('#b_ct_id').change(function() {
				if ($(this).val() == 2) { 
					//id of 2 = monetary credits
					show_div("ajax_msg");	
					$('#ajax_msg').html("Support for monetary credits will be added when we have enough members to justify the Paypal costs and coding time, hopefully sooner than later!");
					$("#b_ct_id option[value='1']").attr('selected', 'selected');
					setTimeout("fade_div('ajax_msg')",7000);//fade out

				}
			});

			/** ALERT THAT RANDOM JUDGES AND SELECT JUDGES ARE COMING SOON */
			$('#b_bjm_id').change(function() {
				if ($(this).val() == 2) { 
					//id of 2 = random judges
					show_div("ajax_msg");	
					$('#ajax_msg').html("Random judge panels will be allowed once we have enough members who have a good judging reputation.");
					setTimeout("$(\"#b_bjm_id option[value='1']\").attr('selected', 'selected')",1000);
					setTimeout("fade_div('ajax_msg')",5000);//fade out

				}
				if ($(this).val() == 3) { 
					//id of 3 = private judges
					show_div("ajax_msg");	
					$('#ajax_msg').html("Private judge panels will be allowed once we have enough members, hopefully/probably just a week or two.");
					setTimeout("$(\"#b_bjm_id option[value='1']\").attr('selected', 'selected')",1000);
					setTimeout("$('#b_private_judges_container').hide(500)",1000);
					setTimeout("fade_div('ajax_msg')",5000);//fade out

				}
			});


			/** AUTOCOMPLETE FOR CONTENDER SELECT ****************/
			//log(ui.item ? ("Selected: " + ui.item.user_fname + " " + ui.item.user_lname + "(" + ui.item.user_id + ")") : "Nothing selected, input was " + this.value);
			$(function() {
				$("#b_opponent").autocomplete({
					source: WWW+"/ajax.get-autocomplete-users-json.php",
					minLength: 2,
					focus: function(event, ui) {

						/** FAILSAFE MISSING NICKNAME */
						if(!ui.item.user_nickname)
							ui.item.user_nickname = ui.item.user_fname + ' ' + ui.item.user_lname;
					
						$('#b_opponent').val(ui.item.user_nickname);
						return false;
					},
					select: function(event, ui) {

						// ENSURE OPPONENT IS NOT USER
						if(ui.item.user_id == window.USER_ID){

							show_div('ajax_msg');	
							$('#ajax_msg').html("You can not compete against yourself!");
							setTimeout("fade_div('ajax_msg')",3000);//fade out

							return false;

						}

						// CHECK OPPONENT AGAINST JUDGE PANEL
						if(!checkAgainstFilteredUsersArray(ui.item.user_id)){
							show_div('ajax_msg');	
							$('#ajax_msg').html(ui.item.user_fname + " " + ui.item.user_lname + " can not be both a judge and your opponent.");
							setTimeout("fade_div('ajax_msg')",3000);//fade out

							return false;

						}
						
						window.b_opponent_fb_uid = ui.item.ufb_fb_uid;

						/** FAILSAFE MISSING NICKNAME */
						if(!ui.item.user_nickname)
							ui.item.user_nickname = ui.item.user_fname + ' ' + ui.item.user_lname;
						
						$('#b_opponent').val(ui.item.user_nickname);
						$('#b_opponent_name').val(ui.item.user_fname + ' ' + ui.item.user_lname);
						$('#b_opponent_result_container').html("<div class='form_field_results'><div style='margin-bottom:4px;'><img src='" + ui.item.ufb_fb_profile_pic + "' alt='' style='border:1px solid #79a42d;' /></div><div style='position:absolute; top:0; left:55px; padding:5px; height:40px;'><b style='font-size:10px;'>" + ui.item.user_fname.toUpperCase() + " " + ui.item.user_lname.toUpperCase() + "</b><br /><span style='font-weight:normal; font-size:10px;'>" + ui.item.user_nickname.toUpperCase() + "</span></div><img src='"+WWW+"/images/icons/x_9_red.gif' style='position:absolute; top:5px; right:5px;' alt='' id='b_opponent_reset' onclick='autocompleteReset(\"b_opponent\");' /></div>");
						$('#b_opponent_result_container').show();
						$('#b_opponent').hide();
						$('#b_opponent_id').val(ui.item.user_id);
						rebuildFilteredUsersArray();

						return false;
					}
				})
				.data( "autocomplete" )._renderItem = function( ul, item ) {
					return $( "<li style='text-align:left;'></li>" )
						.data( "item.autocomplete", item )
						.append( "<a><div style='display:inline-block;'><img src='" + item.ufb_fb_profile_pic + "' alt='' style='border:1px solid #79a42d;' /></div><div style='display:inline-block; padding:5px; line-height:15px; position:relative; vertical-align:top;'><b>" + item.user_fname.toUpperCase() + " " + item.user_lname.toUpperCase() + "</b><span style='font-weight:normal; font-size:10px; position:absolute; left:5px; top:18px;'>" + item.user_nickname.toUpperCase() + "</span></div></a>" )
						.appendTo( ul );
				};

			});

			/** AUTOCOMPLETE FOR JUDGES SELECT *******************/
			$(function() {

				$('#b_private_judge_1').autocomplete({
					source: WWW+"/ajax.get-autocomplete-users-json.php",
					minLength: 2,
					focus: function(event, ui) {

						/** FAILSAFE MISSING NICKNAME */
						if(!ui.item.user_nickname)
							ui.item.user_nickname = ui.item.user_fname + ' ' + ui.item.user_lname;

						$('#b_private_judge_1').val(ui.item.user_nickname);
						return false;
					},
					select: function(event, ui) {

						// ENSURE JUDGE IS NOT USER
						if(ui.item.user_id == window.USER_ID){

							show_div('ajax_msg');	
							$('#ajax_msg').html("You can not judge your own battle!");
							setTimeout("fade_div('ajax_msg')",3000);//fade out

							return false;

						}

						// ENSURE JUDGE HAS JUDGE POINTS
						if(ui.item.us_judge_points < 1){

							show_div('ajax_msg');	
							$('#ajax_msg').html(ui.item.user_fname + " " + ui.item.user_lname + " has lost all his judging points from shitty judging and is not eligible to be a judge at this time!");
							setTimeout("fade_div('ajax_msg')",4000);//fade out

							return false;

						}

						// CHECK OPPONENT AGAINST JUDGE PANEL
						if(!checkAgainstFilteredUsersArray(ui.item.user_id)){

							if(ui.item.user_id == $("#b_opponent_id").val()){
								show_div('ajax_msg');	
								$('#ajax_msg').html(ui.item.user_fname + " " + ui.item.user_lname + " can not be both a judge and your opponent.");
								setTimeout("fade_div('ajax_msg')",3000);//fade out
							}
							else{
								//alert('opponent = '+$("#b_opponent_id").val()+'and user = '+ui.item.user_id);
								show_div('ajax_msg');	
								$('#ajax_msg').html(ui.item.user_fname + " " + ui.item.user_lname + " is already a judge.");
								setTimeout("fade_div('ajax_msg')",3000);//fade out
							}

							return false;

						}


						/** FAILSAFE MISSING NICKNAME */
						if(!ui.item.user_nickname)
							ui.item.user_nickname = ui.item.user_fname + ' ' + ui.item.user_lname;

						$('#b_private_judge_1').val(ui.item.user_nickname);
						$('#b_private_judge_1_result_container').html("<div class='form_field_results'><div style='margin-bottom:4px;'><img src='" + ui.item.ufb_fb_profile_pic + "' alt='' style='border:1px solid #79a42d;' /></div><div style='position:absolute; top:0; left:55px; padding:5px; height:40px;'><b style='font-size:10px;'>" + ui.item.user_fname.toUpperCase() + " " + ui.item.user_lname.toUpperCase() + "</b><br /><span style='font-weight:normal; font-size:10px;'>" + ui.item.user_nickname.toUpperCase() + "</span></div><img src='"+WWW+"/images/icons/x_9_red.gif' style='position:absolute; top:5px; right:5px;' alt='' id='b_private_judge_1' onclick='autocompleteReset(\"b_private_judge_1\"); rebuildPrivateJudgeList();' /></div>");
						$('#b_private_judge_1_result_container').show();
						$('#b_private_judge_1').hide();
						$('#b_private_judge_1_id').val(ui.item.user_id);
						rebuildPrivateJudgeList();
						rebuildFilteredUsersArray();

						return false;
					}
				})
				.data( "autocomplete" )._renderItem = function( ul, item ) {
					return $( "<li style='text-align:left;'></li>" )
						.data( "item.autocomplete", item )
						.append( "<a><div style='display:inline-block;'><img src='" + item.ufb_fb_profile_pic + "' alt='' style='border:1px solid #79a42d;' /></div><div style='display:inline-block; padding:5px; line-height:15px; position:relative; vertical-align:top;'><b>" + item.user_fname.toUpperCase() + " " + item.user_lname.toUpperCase() + "</b><span style='font-weight:normal; font-size:10px; position:absolute; left:5px; top:18px;'>" + item.user_nickname.toUpperCase() + "</span></div></a>" )
						.appendTo( ul );
				};

			});

			$(function() {

				$('#b_private_judge_2').autocomplete({
					source: WWW+"/ajax.get-autocomplete-users-json.php",
					minLength: 2,
					focus: function(event, ui) {

						/** FAILSAFE MISSING NICKNAME */
						if(!ui.item.user_nickname)
							ui.item.user_nickname = ui.item.user_fname + ' ' + ui.item.user_lname;

						$('#b_private_judge_2').val(ui.item.user_nickname);
						return false;
					},
					select: function(event, ui) {

						// ENSURE JUDGE IS NOT USER
						if(ui.item.user_id == window.USER_ID){

							show_div('ajax_msg');	
							$('#ajax_msg').html("You can not judge your own battle!");
							setTimeout("fade_div('ajax_msg')",3000);//fade out

							return false;

						}

						// ENSURE JUDGE HAS JUDGE POINTS
						if(ui.item.us_judge_points < 1){

							show_div('ajax_msg');	
							$('#ajax_msg').html(ui.item.user_fname + " " + ui.item.user_lname + " has lost all his judging points from shitty judging and is not eligible to be a judge at this time!");
							setTimeout("fade_div('ajax_msg')",4000);//fade out

							return false;

						}

						// CHECK OPPONENT AGAINST JUDGE PANEL
						if(!checkAgainstFilteredUsersArray(ui.item.user_id)){

							if(ui.item.user_id == $("#b_opponent_id").val()){
								show_div('ajax_msg');	
								$('#ajax_msg').html(ui.item.user_fname + " " + ui.item.user_lname + " can not be both a judge and your opponent.");
								setTimeout("fade_div('ajax_msg')",3000);//fade out
							}
							else{
								//alert('opponent = '+$("#b_opponent_id").val()+'and user = '+ui.item.user_id);
								show_div('ajax_msg');	
								$('#ajax_msg').html(ui.item.user_fname + " " + ui.item.user_lname + " is already a judge.");
								setTimeout("fade_div('ajax_msg')",3000);//fade out
							}

							return false;

						}


						/** FAILSAFE MISSING NICKNAME */
						if(!ui.item.user_nickname)
							ui.item.user_nickname = ui.item.user_fname + ' ' + ui.item.user_lname;

						$('#b_private_judge_2').val(ui.item.user_nickname);
						$('#b_private_judge_2_result_container').html("<div class='form_field_results'><div style='margin-bottom:4px;'><img src='" + ui.item.ufb_fb_profile_pic + "' alt='' style='border:1px solid #79a42d;' /></div><div style='position:absolute; top:0; left:55px; padding:5px; height:40px;'><b style='font-size:10px;'>" + ui.item.user_fname.toUpperCase() + " " + ui.item.user_lname.toUpperCase() + "</b><br /><span style='font-weight:normal; font-size:10px;'>" + ui.item.user_nickname.toUpperCase() + "</span></div><img src='"+WWW+"/images/icons/x_9_red.gif' style='position:absolute; top:5px; right:5px;' alt='' id='b_private_judge_2' onclick='autocompleteReset(\"b_private_judge_2\"); rebuildPrivateJudgeList();' /></div>");
						$('#b_private_judge_2_result_container').show();
						$('#b_private_judge_2').hide();
						$('#b_private_judge_2_id').val(ui.item.user_id);
						rebuildPrivateJudgeList();
						rebuildFilteredUsersArray();

						return false;
					}
				})
				.data( "autocomplete" )._renderItem = function( ul, item ) {
					return $( "<li style='text-align:left;'></li>" )
						.data( "item.autocomplete", item )
						.append( "<a><div style='display:inline-block;'><img src='" + item.ufb_fb_profile_pic + "' alt='' style='border:1px solid #79a42d;' /></div><div style='display:inline-block; padding:5px; line-height:15px; position:relative; vertical-align:top;'><b>" + item.user_fname.toUpperCase() + " " + item.user_lname.toUpperCase() + "</b><span style='font-weight:normal; font-size:10px; position:absolute; left:5px; top:18px;'>" + item.user_nickname.toUpperCase() + "</span></div></a>" )
						.appendTo( ul );
				};

			});

			$(function() {

				$('#b_private_judge_3').autocomplete({
					source: WWW+"/ajax.get-autocomplete-users-json.php",
					minLength: 2,
					focus: function(event, ui) {

						/** FAILSAFE MISSING NICKNAME */
						if(!ui.item.user_nickname)
							ui.item.user_nickname = ui.item.user_fname + ' ' + ui.item.user_lname;

						$('#b_private_judge_3').val(ui.item.user_nickname);
						return false;
					},
					select: function(event, ui) {

						// ENSURE JUDGE IS NOT USER
						if(ui.item.user_id == window.USER_ID){

							show_div('ajax_msg');	
							$('#ajax_msg').html("You can not judge your own battle!");
							setTimeout("fade_div('ajax_msg')",3000);//fade out

							return false;

						}

						// ENSURE JUDGE HAS JUDGE POINTS
						if(ui.item.us_judge_points < 1){

							show_div('ajax_msg');	
							$('#ajax_msg').html(ui.item.user_fname + " " + ui.item.user_lname + " has lost all his judging points from shitty judging and is not eligible to be a judge at this time!");
							setTimeout("fade_div('ajax_msg')",4000);//fade out

							return false;

						}

						// CHECK OPPONENT AGAINST JUDGE PANEL
						if(!checkAgainstFilteredUsersArray(ui.item.user_id)){

							if(ui.item.user_id == $("#b_opponent_id").val()){
								show_div('ajax_msg');	
								$('#ajax_msg').html(ui.item.user_fname + " " + ui.item.user_lname + " can not be both a judge and your opponent.");
								setTimeout("fade_div('ajax_msg')",3000);//fade out
							}
							else{
								//alert('opponent = '+$("#b_opponent_id").val()+'and user = '+ui.item.user_id);
								show_div('ajax_msg');	
								$('#ajax_msg').html(ui.item.user_fname + " " + ui.item.user_lname + " is already a judge.");
								setTimeout("fade_div('ajax_msg')",3000);//fade out
							}

							return false;

						}


						/** FAILSAFE MISSING NICKNAME */
						if(!ui.item.user_nickname)
							ui.item.user_nickname = ui.item.user_fname + ' ' + ui.item.user_lname;

						$('#b_private_judge_3').val(ui.item.user_nickname);
						$('#b_private_judge_3_result_container').html("<div class='form_field_results'><div style='margin-bottom:4px;'><img src='" + ui.item.ufb_fb_profile_pic + "' alt='' style='border:1px solid #79a42d;' /></div><div style='position:absolute; top:0; left:55px; padding:5px; height:40px;'><b style='font-size:10px;'>" + ui.item.user_fname.toUpperCase() + " " + ui.item.user_lname.toUpperCase() + "</b><br /><span style='font-weight:normal; font-size:10px;'>" + ui.item.user_nickname.toUpperCase() + "</span></div><img src='"+WWW+"/images/icons/x_9_red.gif' style='position:absolute; top:5px; right:5px;' alt='' id='b_private_judge_3' onclick='autocompleteReset(\"b_private_judge_3\"); rebuildPrivateJudgeList();' /></div>");
						$('#b_private_judge_3_result_container').show();
						$('#b_private_judge_3').hide();
						$('#b_private_judge_3_id').val(ui.item.user_id);
						rebuildPrivateJudgeList();
						rebuildFilteredUsersArray();

						return false;
					}
				})
				.data( "autocomplete" )._renderItem = function( ul, item ) {
					return $( "<li style='text-align:left;'></li>" )
						.data( "item.autocomplete", item )
						.append( "<a><div style='display:inline-block;'><img src='" + item.ufb_fb_profile_pic + "' alt='' style='border:1px solid #79a42d;' /></div><div style='display:inline-block; padding:5px; line-height:15px; position:relative; vertical-align:top;'><b>" + item.user_fname.toUpperCase() + " " + item.user_lname.toUpperCase() + "</b><span style='font-weight:normal; font-size:10px; position:absolute; left:5px; top:18px;'>" + item.user_nickname.toUpperCase() + "</span></div></a>" )
						.appendTo( ul );
				};

			});

			$(function() {

				$('#b_private_judge_4').autocomplete({
					source: WWW+"/ajax.get-autocomplete-users-json.php",
					minLength: 2,
					focus: function(event, ui) {

						/** FAILSAFE MISSING NICKNAME */
						if(!ui.item.user_nickname)
							ui.item.user_nickname = ui.item.user_fname + ' ' + ui.item.user_lname;

						$('#b_private_judge_4').val(ui.item.user_nickname);
						return false;
					},
					select: function(event, ui) {

						// ENSURE JUDGE IS NOT USER
						if(ui.item.user_id == window.USER_ID){

							show_div('ajax_msg');	
							$('#ajax_msg').html("You can not judge your own battle!");
							setTimeout("fade_div('ajax_msg')",3000);//fade out

							return false;

						}

						// ENSURE JUDGE HAS JUDGE POINTS
						if(ui.item.us_judge_points < 1){

							show_div('ajax_msg');	
							$('#ajax_msg').html(ui.item.user_fname + " " + ui.item.user_lname + " has lost all his judging points from shitty judging and is not eligible to be a judge at this time!");
							setTimeout("fade_div('ajax_msg')",4000);//fade out

							return false;

						}

						// CHECK OPPONENT AGAINST JUDGE PANEL
						if(!checkAgainstFilteredUsersArray(ui.item.user_id)){

							if(ui.item.user_id == $("#b_opponent_id").val()){
								show_div('ajax_msg');	
								$('#ajax_msg').html(ui.item.user_fname + " " + ui.item.user_lname + " can not be both a judge and your opponent.");
								setTimeout("fade_div('ajax_msg')",3000);//fade out
							}
							else{
								//alert('opponent = '+$("#b_opponent_id").val()+'and user = '+ui.item.user_id);
								show_div('ajax_msg');	
								$('#ajax_msg').html(ui.item.user_fname + " " + ui.item.user_lname + " is already a judge.");
								setTimeout("fade_div('ajax_msg')",3000);//fade out
							}

							return false;

						}


						/** FAILSAFE MISSING NICKNAME */
						if(!ui.item.user_nickname)
							ui.item.user_nickname = ui.item.user_fname + ' ' + ui.item.user_lname;

						$('#b_private_judge_4').val(ui.item.user_nickname);
						$('#b_private_judge_4_result_container').html("<div class='form_field_results'><div style='margin-bottom:4px;'><img src='" + ui.item.ufb_fb_profile_pic + "' alt='' style='border:1px solid #79a42d;' /></div><div style='position:absolute; top:0; left:55px; padding:5px; height:40px;'><b style='font-size:10px;'>" + ui.item.user_fname.toUpperCase() + " " + ui.item.user_lname.toUpperCase() + "</b><br /><span style='font-weight:normal; font-size:10px;'>" + ui.item.user_nickname.toUpperCase() + "</span></div><img src='"+WWW+"/images/icons/x_9_red.gif' style='position:absolute; top:5px; right:5px;' alt='' id='b_private_judge_4' onclick='autocompleteReset(\"b_private_judge_4\"); rebuildPrivateJudgeList();' /></div>");
						$('#b_private_judge_4_result_container').show();
						$('#b_private_judge_4').hide();
						$('#b_private_judge_4_id').val(ui.item.user_id);
						rebuildPrivateJudgeList();
						rebuildFilteredUsersArray();

						return false;
					}
				})
				.data( "autocomplete" )._renderItem = function( ul, item ) {
					return $( "<li style='text-align:left;'></li>" )
						.data( "item.autocomplete", item )
						.append( "<a><div style='display:inline-block;'><img src='" + item.ufb_fb_profile_pic + "' alt='' style='border:1px solid #79a42d;' /></div><div style='display:inline-block; padding:5px; line-height:15px; position:relative; vertical-align:top;'><b>" + item.user_fname.toUpperCase() + " " + item.user_lname.toUpperCase() + "</b><span style='font-weight:normal; font-size:10px; position:absolute; left:5px; top:18px;'>" + item.user_nickname.toUpperCase() + "</span></div></a>" )
						.appendTo( ul );
				};

			});

			$(function() {

				$('#b_private_judge_5').autocomplete({
					source: WWW+"/ajax.get-autocomplete-users-json.php",
					minLength: 2,
					focus: function(event, ui) {

						/** FAILSAFE MISSING NICKNAME */
						if(!ui.item.user_nickname)
							ui.item.user_nickname = ui.item.user_fname + ' ' + ui.item.user_lname;

						$('#b_private_judge_5').val(ui.item.user_nickname);
						return false;
					},
					select: function(event, ui) {

						// ENSURE JUDGE IS NOT USER
						if(ui.item.user_id == window.USER_ID){

							show_div('ajax_msg');	
							$('#ajax_msg').html("You can not judge your own battle!");
							setTimeout("fade_div('ajax_msg')",3000);//fade out

							return false;

						}

						// ENSURE JUDGE HAS JUDGE POINTS
						if(ui.item.us_judge_points < 1){

							show_div('ajax_msg');	
							$('#ajax_msg').html(ui.item.user_fname + " " + ui.item.user_lname + " has lost all his judging points from shitty judging and is not eligible to be a judge at this time!");
							setTimeout("fade_div('ajax_msg')",4000);//fade out

							return false;

						}

						// CHECK OPPONENT AGAINST JUDGE PANEL
						if(!checkAgainstFilteredUsersArray(ui.item.user_id)){

							if(ui.item.user_id == $("#b_opponent_id").val()){
								show_div('ajax_msg');	
								$('#ajax_msg').html(ui.item.user_fname + " " + ui.item.user_lname + " can not be both a judge and your opponent.");
								setTimeout("fade_div('ajax_msg')",3000);//fade out
							}
							else{
								//alert('opponent = '+$("#b_opponent_id").val()+'and user = '+ui.item.user_id);
								show_div('ajax_msg');	
								$('#ajax_msg').html(ui.item.user_fname + " " + ui.item.user_lname + " is already a judge.");
								setTimeout("fade_div('ajax_msg')",3000);//fade out
							}

							return false;

						}


						/** FAILSAFE MISSING NICKNAME */
						if(!ui.item.user_nickname)
							ui.item.user_nickname = ui.item.user_fname + ' ' + ui.item.user_lname;

						$('#b_private_judge_5').val(ui.item.user_nickname);
						$('#b_private_judge_5_result_container').html("<div class='form_field_results'><div style='margin-bottom:4px;'><img src='" + ui.item.ufb_fb_profile_pic + "' alt='' style='border:1px solid #79a42d;' /></div><div style='position:absolute; top:0; left:55px; padding:5px; height:40px;'><b style='font-size:10px;'>" + ui.item.user_fname.toUpperCase() + " " + ui.item.user_lname.toUpperCase() + "</b><br /><span style='font-weight:normal; font-size:10px;'>" + ui.item.user_nickname.toUpperCase() + "</span></div><img src='"+WWW+"/images/icons/x_9_red.gif' style='position:absolute; top:5px; right:5px;' alt='' id='b_private_judge_5' onclick='autocompleteReset(\"b_private_judge_5\"); rebuildPrivateJudgeList();' /></div>");
						$('#b_private_judge_5_result_container').show();
						$('#b_private_judge_5').hide();
						$('#b_private_judge_5_id').val(ui.item.user_id);
						rebuildPrivateJudgeList();
						rebuildFilteredUsersArray();

						return false;
					}
				})
				.data( "autocomplete" )._renderItem = function( ul, item ) {
					return $( "<li style='text-align:left;'></li>" )
						.data( "item.autocomplete", item )
						.append( "<a><div style='display:inline-block;'><img src='" + item.ufb_fb_profile_pic + "' alt='' style='border:1px solid #79a42d;' /></div><div style='display:inline-block; padding:5px; line-height:15px; position:relative; vertical-align:top;'><b>" + item.user_fname.toUpperCase() + " " + item.user_lname.toUpperCase() + "</b><span style='font-weight:normal; font-size:10px; position:absolute; left:5px; top:18px;'>" + item.user_nickname.toUpperCase() + "</span></div></a>" )
						.appendTo( ul );
				};

			});

			/** INITIALIZE TOOL TIP ******************************/
			tooltip();

			/** DECLARE SELECT MENUS FOR JQUERY UI ***************/
			//$('select#b_bsm_id').selectmenu();

			/** DECLARE SELECTED TRICKS AS SORTABLE **************/
			$(document).ready(function() {
				$("#selected_tricks_sortable").sortable({

					cursor: 's-resize',
					placeholder: 'sortable-state-highlight',
					stop: function(event, ui) {

						rebuildSelectedTricksList('selected_tricks_sortable');
					}


				});
			});

			/** DECLARE LIST PLUGIN FOR JQUERY *******************/
			 $('#featured_tricks').listnav({ 
			    initLetter: 's', 
			    includeAll: false, 
			    includeOther: false,
			    includeNums: true,
			    flagDisabled: false, 
			    noMatchText: 'No tricks found, please click another letter.', 
			    showCounts: false, 
			    cookieName: 'trick-list', 
			    //onClick: function(letter){ alert('You clicked ' + letter); }, 
			    prefixes: ['the','a','pop','swingthru','**'] 
			});


			/** DECLARE SELECTED TRICK TYPES AS SORTABLE *********/
			$(document).ready(function() {
				$("#selected_trick_types_sortable").sortable({

					cursor: 's-resize',
					placeholder: 'sortable-state-highlight',
					stop: function(event, ui) {

						rebuildSelectedTrickTypesList('selected_trick_types_sortable');
					}


				});
			});

			/** DECLARE LIST PLUGIN FOR JQUERY *******************/
			/*
			 $('#featured_trick_types').listnav({ 
			    initLetter: 'a', 
			    includeAll: false, 
			    includeOther: false,
			    includeNums: true,
			    flagDisabled: false, 
			    noMatchText: 'No tricks found, please click another letter.', 
			    showCounts: false, 
			    cookieName: 'trick-type-list', 
			    //onClick: function(letter){ alert('You clicked ' + letter); }, 
			    prefixes: ['the','a'] 
			});
			*/

			/** WHEN USER FOCUSES THE TITLE FIELD, CLEAR IT OUT */
			$("#b_title").focus(function(){

				if($("#b_title").val() == "Trick Battle")
					$("#b_title").val("");

			});
			
			$("#b_title").blur(function(){

				if($("#b_title").val() == "")
					$("#b_title").val("Trick Battle");
			
			});
			
			/** WHEN USER FOCUSES THE VIDEO URL FIELD, CLEAR IT OUT */
			$("#video_url").focus(function(){

				if(document.getElementById("video_url").value == "Video URL")
					document.getElementById("video_url").value = "";

			});

			/** WHEN USER BLURS THE VIDEO URL FIELD, CHECK FOR BLANK, OR FETCH ***/
			$("#video_url").blur(function(){

				if(document.getElementById("video_url").value == "")
					document.getElementById("video_url").value = "Video URL";
				else {
					document.getElementById("video_url_field_container").style.display = 'none';
					document.getElementById("video_url_oembed_container").style.display = 'block';

					/** CREATE DOM ANCHOR DOM ELEMENT TO HOLD THE URL ************/
					var oembed_anchor = document.createElement("a");
					oembed_anchor.setAttribute("href", document.getElementById("video_url").value);
					oembed_anchor.setAttribute("id", "video_url_oembed");

					/** SHOW DIV CONTAINER AND CLEAR IT OUT **********************/
					document.getElementById("video_url_oembed_container").style.display = "block";
					document.getElementById("video_url_oembed_container").innerHTML = "";

					/** CREATE RESET LINK ****************************************/
					var reset_link = document.createElement("a");
					reset_link.setAttribute("id","video_url_reset");
					reset_link.setAttribute("href","#");
					reset_link.setAttribute("onclick","resetVideo();");
					var reset_link_text = document.createTextNode("Wrong video / no video?");
					reset_link.appendChild(reset_link_text);

					/** APPEND THE NEW NODES TO THE CONTAINER ********************/
					document.getElementById("video_url_oembed_container").appendChild(oembed_anchor);
					//document.getElementById("video_url_oembed_container").appendChild(document.createElement("br"));
					document.getElementById("video_url_oembed_container").appendChild(reset_link);
					document.getElementById("video_url_reset").style.display = "block";
					document.getElementById("video_url_reset").style.width = "100%";
					document.getElementById("video_url_reset").style.textAlign = "right";
					document.getElementById("video_url_reset").style.marginTop = "2px";

					//embedmethod:append seems to remove the title and volume, etc from vimeo
					$("#video_url_oembed").oembed(null, {
					vimeo: {color: "9cd03f", portrait: false},
					/*embedMethod: "append",*/
					maxWidth: 275
					});

				}


			});
			
			tabIndexify('form');

		}
	});

}

/** FUNCTION LOADS FREE-FOR-ALL BATTLE CREATE FORM ***************************/
function load_battle_creator_free(){

	$.ajax({
		type: "GET",
		url: WWW+"/ajax.battle-create-free.php",
		beforeSend: function(){
			
			$('#ajax_loading').show('slow');
		},
		success: function(data) {

			$('#ajax_loading').hide('slow');

			$('#dashboard_content_ajax').html(data);			
			
			/** HANDLE FORM SUBMIT - VALIDATE ********************/
			/*
			$("div").click(function () {
			      $(this).effect("highlight", {}, 3000);
			});
			*/
			$("form").submit(function() {

				var formFail = false;

				/** TITLE ************************************/
				var b_title = $("#b_title").val();
				var b_default_title = document.getElementById('b_title').defaultValue;			
				if (b_title == "" || b_title == b_default_title) {
					$("#b_title").effect("highlight", {}, 3000);
					formFail = true;
				}

				/** VIDEO URL ********************************/
				var video_url = $("#video_url").val();
				if (video_url == "Video URL") {
					$("#video_url").effect("highlight", {}, 3000);
					formFail = true;
				}
				else{	
					/** COMPARE URL TO YOUTUBE FORMAT ****/
					if($("#video_url").val().match(youtubeRegex))
						var tmp=1; //alert('valid youtube url');

					/** COMPARE URL TO VIMEO FORMAT ******/
					else if($("#video_url").val().match(vimeoRegex))
						var tmp=1 //alert('valid vimeo url');

					/** SHOW ERROR MESSAGE ***************/
					else {						
						show_div('ajax_msg');	
						$('#ajax_msg').html("Invalid video url format - Youtube or Vimeo only please!");
						setTimeout("fade_div('ajax_msg')",3000);//fade out
						formFail = true;					
					}
				}


				/** OPPONENTS PANEL **************************/
				var opponent_method = $("#b_bom_id").val();
				var private_opponents = $("#b_private_opponents_hidden").val();
				var prompt_opponent_alert = false;
				if (opponent_method == 2) {
					if ($("#b_private_opponent_1").val() == "") {
						$("#b_private_opponent_1").effect("highlight", {}, 3000);
						formFail = true;
						prompt_opponent_alert = true;
						
					}
					if ($("#b_private_opponent_2").val() == "") {
						$("#b_private_opponent_2").effect("highlight", {}, 3000);
						formFail = true;
						prompt_opponent_alert = true;
					}

					if(prompt_opponent_alert){
						show_div("ajax_msg");	
						$('#ajax_msg').html("At least two invites must be sent out for a private free-for-all battle.");
						setTimeout("fade_div('ajax_msg')",3000);//fade out
					}

				}

				/** JUDGING PANEL ****************************/
				var judging_method = $("#b_bjm_id").val();
				var private_judges = $("#b_private_judges_hidden").val(); 
				if (judging_method == 3) {
					if ($("#b_private_judge_1").val() == "") {
						$("#b_private_judge_1").effect("highlight", {}, 3000);
						formFail = true;
					}
					if ($("#b_private_judge_2").val() == "") {
						$("#b_private_judge_2").effect("highlight", {}, 3000);
						formFail = true;
					}
					if ($("#b_private_judge_3").val() == "") {
						$("#b_private_judge_3").effect("highlight", {}, 3000);
						formFail = true;
					}

				}

				/** SELECTED TRICKS **************************/
				var selected_tricks = $("#selected_tricks_list_hidden").val();
				if (selected_tricks == "") {
					$("#featured_tricks").effect("highlight", {}, 3000);
					formFail = true;
				}

				/** SELECTED TRICK TYPES *********************/
				var selected_trick_types = $("#selected_trick_types_list_hidden").val();
				var tricks_or_types = $("#tricks_or_types").val();
				if(tricks_or_types == "types"){
					if (selected_trick_types == "") {
						$("#featured_trick_types").effect("highlight", {}, 3000);
						formFail = true;
					}
				}
				
				/** AJAX FORM SUBMIT ONLY IF VALID FORM ******/
				if(formFail === false){


					/** CREATE CONCATINATED QUERY STRING */
					//b_bt_id=2 means battle type of free-for-all
					var dataString = 'b_bt_id=2' + 
							 '&video_url=' + urlencode(video_url);

					/** APPEND PRIVATE JUDGES IF APPLICABLE */
					if(judging_method == 3)
						dataString += '&b_bjm_id=3&private_judges=' + private_judges;
					else
						dataString += '&b_bjm_id=' + judging_method;

					/** APPEND PRIVATE OPPONENTS IF APPLICABLE */
					if(opponent_method == 2)
						dataString += '&b_bom_id=2&private_opponents=' + private_opponents;
					else
						dataString += '&b_bom_id=' + opponent_method;

					/** APPEND THE REST OF THE FORM FIELDS */
					dataString += '&selected_tricks=' + selected_tricks +
						      '&selected_trick_types=' + selected_trick_types + 
						      '&tricks_or_types=' + $("#tricks_or_types").val() + 
						      '&b_title=' + b_title +
					              '&b_desc=' + $("#b_desc").val() +
						      '&b_bsm_id=' + $("#b_bsm_id").val() + 
						      '&b_ct_id=' + $("#b_ct_id").val() +
						      '&b_upp_id=' + $("#b_upp_id").val();
					
					/** GLOBALIZE SOME VARIABLES FOR FACEBOOK NOTIFICATION */
					window.battle_title = b_title;
					window.battle_desc = $("#b_desc").val();
					
					//alert (dataString);

					
					$.ajax({
						type: "POST",
						url: WWW+"/ajax.battle-initiate.php",
						data: dataString,
						success: function(data) {

							/** CLEAR OUT FILTERED USERS */
							window.filteredUsers = '';
							window.filteredUsersArray = new Array();
							
							load_pending_ajax = function(){

								$.ajax({
									type: "POST",
									url: WWW+"/ajax.get-pending-battles.php",
									data: dataString,
									success: function(data) {

										$('#dashboard_content_ajax').html(data);
			
										/** INITIALIZE TABLESORTER ************/
										$("#pending_battles").tablesorter({ 
											// sort on the deadline column, order asc 
											sortList: [[6,0]] 
										});

										/** INITIALIZE TOOLTIP ****************/
										tooltip();
										imgtooltip();

									} // end success

								});
							}
							
							show_div('ajax_msg');	
							$('#ajax_msg').html(data);
							
							if(data == 'Battle Initiated!'){
								
								if(tricks_or_types == 'tricks')
									var trick_list = window.battle_trick_names;
								if(tricks_or_types == 'types')
									var trick_list = window.battle_trick_type_names;

								var fb_attachment_desc = 'The battle consists of the following ' + window.battle_trick_or_combo + ': ' + trick_list.replace(/,/gi," -> ") + '. Check it out at TrickerBattle.com.';
								var fb_attachment_name = window.battle_title;
								var fb_attachment_caption = 'http://www.trickerbattle.com';
								var fb_attachment_url = 'http://www.trickerbattle.com/battles';
								if(window.battle_desc)
									fb_attachment_caption = window.battle_desc;

								/** HERE WE SHOULD POST TO FACEBOOK WALL **/
								if(window.fbStreamPublishOnBattleInitiate == 1){
									
									// challenger
									// later, figure out how to loop this with their names...
									var fb_message = 'challenged multiple trickers to a tricking battle!';
									publishToWall(window.fb_uid,fb_message,fb_attachment_desc,fb_attachment_name,fb_attachment_caption,fb_attachment_url);
								}
								
								/** CHECK OPPONENTS USER PREFERENCE IF THEY WANT TO BE NOTIFIED **/
								var po_array = private_opponents.split(',');
								for(var i=0; i<po_array.length; i++){
								
									dataString = 'user_id=' + po_array[i] +
										     '&pref_key=fb_stream_publish_when_challenged';
									$.ajax({
										type: "POST",
										url: WWW+"/ajax.get-user-pref.php",
										data: dataString,
										success: function(data) {

											if(data != 0 && data != 'FAIL'){
												// data will equal fb_uid
												// opponent
												var fb_message = 'has challenged you to a tricking battle!';
												publishToWall(data,fb_message,fb_attachment_desc,fb_attachment_name,fb_attachment_caption,fb_attachment_url);
											}

										} // end success

									});
									
								} // next

								// app wall
								var fb_message = 'has challenged multiple trickers to a tricking battle!';
								publishToWall(window.APP_FB_UID,fb_message,fb_attachment_desc,fb_attachment_name,fb_attachment_caption,fb_attachment_url);									
									
								setTimeout("fade_div('ajax_msg')",2000); //fade out
								setTimeout("$('html').scrollTo(500,'swing')",2500);
								setTimeout("load_pending_ajax()",2800);
							
							}
							else
							alert('data = '+data);
						} // end success
						
					});

				}

					
				/** DONT SUBMIT FORM - AJAX ONLY *************/
				return false;
			});

			/** SHOW/HIDE PRIVATE OPPONENTS PANEL BASED ON SELECTION */
			$('#b_bom_id').change(function() {
				if ($(this).val() == 2) { 
					//id of 2 =invite only, show user select
					$('#b_private_opponents_container').show(500);
				}
				 else
					$('#b_private_opponents_container').hide(500);
			});

			/** SHOW/HIDE PRIVATE JUDGES PANEL BASED ON SELECTION */
			$('#b_bjm_id').change(function() {
				if ($(this).val() == 3) { 
					//id of 3 = private judging panel
					$('#b_private_judges_container').show(500);
				}
				 else
					$('#b_private_judges_container').hide(500);
			});

			/** SHOW/HIDE TRICK TYPES BASED ON SELECTION *********/
			$('#tricks_or_types').change(function() {
				if ($(this).val() == 'types')					
					$('#trick_types_container').show(500);
				 else
					$('#trick_types_container').hide(500);
				
				/** THIS IS FOR THE WILDCARD TRICK ***********/
				window.force_wildcard_trick_alert = true;
				rebuildSelectedTricksList("selected_tricks_sortable");
			});

			/** CHECK FOR WILDCARD TRICK ON SCORING METHOD CHANGE */
			$('#b_bsm_id').change(function() {
				
				/** IF THIS IS NOT WIN / LOSS SCORING, CHECK FOR WILDCARD TRICK */
				if ($(this).val() != 3) {

					/** THIS IS FOR THE WILDCARD TRICK ***********/
					window.force_wildcard_trick_alert = true;
					rebuildSelectedTricksList("selected_tricks_sortable");
				
				}
			});

			/** ALERT THAT MONETARY CREDITS ARE COMING SOON */
			$('#b_ct_id').change(function() {
				if ($(this).val() == 2) { 
					//id of 2 = monetary credits
					show_div("ajax_msg");	
					$('#ajax_msg').html("Support for monetary credits will be added when we have enough members to justify the Paypal costs and coding time, hopefully sooner than later!");
					$("#b_ct_id option[value='1']").attr('selected', 'selected');
					setTimeout("fade_div('ajax_msg')",7000);//fade out

				}
			});

			/** ALERT THAT RANDOM JUDGES AND SELECT JUDGES ARE COMING SOON */
			$('#b_bjm_id').change(function() {
				if ($(this).val() == 2) { 
					//id of 2 = random judges
					show_div("ajax_msg");	
					$('#ajax_msg').html("Random judge panels will be allowed once we have enough members who have a good judging reputation.");
					setTimeout("$(\"#b_bjm_id option[value='1']\").attr('selected', 'selected')",1000);
					setTimeout("fade_div('ajax_msg')",5000);//fade out

				}
				if ($(this).val() == 3) { 
					//id of 3 = private judges
					show_div("ajax_msg");	
					$('#ajax_msg').html("Private judge panels will be allowed once we have enough members, hopefully/probably just a week or two.");
					setTimeout("$(\"#b_bjm_id option[value='1']\").attr('selected', 'selected')",1000);
					setTimeout("$('#b_private_judges_container').hide(500)",1000);
					setTimeout("fade_div('ajax_msg')",5000);//fade out

				}
			});


			/** AUTOCOMPLETE FOR OPPONENTS SELECT ****************/
			$(function() {

				$('#b_private_opponent_1').autocomplete({
					source: WWW+"/ajax.get-autocomplete-users-json.php",
					minLength: 2,
					focus: function(event, ui) {

						/** FAILSAFE MISSING NICKNAME */
						if(!ui.item.user_nickname)
							ui.item.user_nickname = ui.item.user_fname + ' ' + ui.item.user_lname;

						$('#b_private_opponent_1').val(ui.item.user_nickname);
						return false;
					},
					select: function(event, ui) {

						// ENSURE opponent IS NOT USER
						if(ui.item.user_id == window.USER_ID){

							show_div('ajax_msg');	
							$('#ajax_msg').html("You can not compete against yourself!");
							setTimeout("fade_div('ajax_msg')",3000);//fade out

							return false;

						}

						// CHECK OPPONENT AGAINST opponent PANEL
						if(!checkAgainstFilteredUsersArray(ui.item.user_id)){

							show_div('ajax_msg');	
							$('#ajax_msg').html(ui.item.user_fname + " " + ui.item.user_lname + " is already an opponent or a judge.");
							setTimeout("fade_div('ajax_msg')",3000);//fade out


							return false;

						}
						
						/** FAILSAFE MISSING NICKNAME */
						if(!ui.item.user_nickname)
							ui.item.user_nickname = ui.item.user_fname + ' ' + ui.item.user_lname;
							
						$('#b_private_opponent_1').val(ui.item.user_nickname);
						$('#b_private_opponent_1_result_container').html("<div class='form_field_results'><div style='margin-bottom:4px;'><img src='" + ui.item.ufb_fb_profile_pic + "' alt='' style='border:1px solid #79a42d;' /></div><div style='position:absolute; top:0; left:55px; padding:5px; height:40px;'><b style='font-size:10px;'>" + ui.item.user_fname.toUpperCase() + " " + ui.item.user_lname.toUpperCase() + "</b><br /><span style='font-weight:normal; font-size:10px;'>" + ui.item.user_nickname.toUpperCase() + "</span></div><img src='"+WWW+"/images/icons/x_9_red.gif' style='position:absolute; top:5px; right:5px;' alt='' id='b_private_opponent_1' onclick='autocompleteReset(\"b_private_opponent_1\"); rebuildPrivateOpponentList();' /></div>");
						$('#b_private_opponent_1_result_container').show();
						$('#b_private_opponent_1').hide();
						$('#b_private_opponent_1_id').val(ui.item.user_id);
						rebuildPrivateOpponentList();
						rebuildFilteredUsersArray();

						return false;
					}
				})
				.data( "autocomplete" )._renderItem = function( ul, item ) {
					return $( "<li style='text-align:left;'></li>" )
						.data( "item.autocomplete", item )
						.append( "<a><div style='display:inline-block;'><img src='" + item.ufb_fb_profile_pic + "' alt='' style='border:1px solid #79a42d;' /></div><div style='display:inline-block; padding:5px; line-height:15px; position:relative; vertical-align:top;'><b>" + item.user_fname.toUpperCase() + " " + item.user_lname.toUpperCase() + "</b><span style='font-weight:normal; font-size:10px; position:absolute; left:5px; top:18px;'>" + item.user_nickname.toUpperCase() + "</span></div></a>" )
						.appendTo( ul );
				};

			});

			$(function() {

				$('#b_private_opponent_2').autocomplete({
					source: WWW+"/ajax.get-autocomplete-users-json.php",
					minLength: 2,
					focus: function(event, ui) {

						/** FAILSAFE MISSING NICKNAME */
						if(!ui.item.user_nickname)
							ui.item.user_nickname = ui.item.user_fname + ' ' + ui.item.user_lname;

						$('#b_private_opponent_2').val(ui.item.user_nickname);
						return false;
					},
					select: function(event, ui) {

						// ENSURE opponent IS NOT USER
						if(ui.item.user_id == window.USER_ID){

							show_div('ajax_msg');	
							$('#ajax_msg').html("You can not compete against yourself!");
							setTimeout("fade_div('ajax_msg')",3000);//fade out

							return false;

						}

						// CHECK OPPONENT AGAINST opponent PANEL
						if(!checkAgainstFilteredUsersArray(ui.item.user_id)){

							show_div('ajax_msg');	
							$('#ajax_msg').html(ui.item.user_fname + " " + ui.item.user_lname + " is already an opponent or a judge.");
							setTimeout("fade_div('ajax_msg')",3000);//fade out

							return false;

						}


						/** FAILSAFE MISSING NICKNAME */
						if(!ui.item.user_nickname)
							ui.item.user_nickname = ui.item.user_fname + ' ' + ui.item.user_lname;

						$('#b_private_opponent_2').val(ui.item.user_nickname);
						$('#b_private_opponent_2_result_container').html("<div class='form_field_results'><div style='margin-bottom:4px;'><img src='" + ui.item.ufb_fb_profile_pic + "' alt='' style='border:1px solid #79a42d;' /></div><div style='position:absolute; top:0; left:55px; padding:5px; height:40px;'><b style='font-size:10px;'>" + ui.item.user_fname.toUpperCase() + " " + ui.item.user_lname.toUpperCase() + "</b><br /><span style='font-weight:normal; font-size:10px;'>" + ui.item.user_nickname.toUpperCase() + "</span></div><img src='"+WWW+"/images/icons/x_9_red.gif' style='position:absolute; top:5px; right:5px;' alt='' id='b_private_opponent_2' onclick='autocompleteReset(\"b_private_opponent_2\"); rebuildPrivateOpponentList();' /></div>");
						$('#b_private_opponent_2_result_container').show();
						$('#b_private_opponent_2').hide();
						$('#b_private_opponent_2_id').val(ui.item.user_id);
						rebuildPrivateOpponentList();
						rebuildFilteredUsersArray();

						return false;
					}
				})
				.data( "autocomplete" )._renderItem = function( ul, item ) {
					return $( "<li style='text-align:left;'></li>" )
						.data( "item.autocomplete", item )
						.append( "<a><div style='display:inline-block;'><img src='" + item.ufb_fb_profile_pic + "' alt='' style='border:1px solid #79a42d;' /></div><div style='display:inline-block; padding:5px; line-height:15px; position:relative; vertical-align:top;'><b>" + item.user_fname.toUpperCase() + " " + item.user_lname.toUpperCase() + "</b><span style='font-weight:normal; font-size:10px; position:absolute; left:5px; top:18px;'>" + item.user_nickname.toUpperCase() + "</span></div></a>" )
						.appendTo( ul );
				};

			});

			$(function() {

				$('#b_private_opponent_3').autocomplete({
					source: WWW+"/ajax.get-autocomplete-users-json.php",
					minLength: 2,
					focus: function(event, ui) {

						/** FAILSAFE MISSING NICKNAME */
						if(!ui.item.user_nickname)
							ui.item.user_nickname = ui.item.user_fname + ' ' + ui.item.user_lname;

						$('#b_private_opponent_3').val(ui.item.user_nickname);
						return false;
					},
					select: function(event, ui) {

						// ENSURE opponent IS NOT USER
						if(ui.item.user_id == window.USER_ID){

							show_div('ajax_msg');	
							$('#ajax_msg').html("You can not compete against yourself!");
							setTimeout("fade_div('ajax_msg')",3000);//fade out

							return false;

						}

						// CHECK OPPONENT AGAINST opponent PANEL
						if(!checkAgainstFilteredUsersArray(ui.item.user_id)){

							show_div('ajax_msg');	
							$('#ajax_msg').html(ui.item.user_fname + " " + ui.item.user_lname + " is already an opponent or a judge.");
							setTimeout("fade_div('ajax_msg')",3000);//fade out

							return false;

						}


						/** FAILSAFE MISSING NICKNAME */
						if(!ui.item.user_nickname)
							ui.item.user_nickname = ui.item.user_fname + ' ' + ui.item.user_lname;

						$('#b_private_opponent_3').val(ui.item.user_nickname);
						$('#b_private_opponent_3_result_container').html("<div class='form_field_results'><div style='margin-bottom:4px;'><img src='" + ui.item.ufb_fb_profile_pic + "' alt='' style='border:1px solid #79a42d;' /></div><div style='position:absolute; top:0; left:55px; padding:5px; height:40px;'><b style='font-size:10px;'>" + ui.item.user_fname.toUpperCase() + " " + ui.item.user_lname.toUpperCase() + "</b><br /><span style='font-weight:normal; font-size:10px;'>" + ui.item.user_nickname.toUpperCase() + "</span></div><img src='"+WWW+"/images/icons/x_9_red.gif' style='position:absolute; top:5px; right:5px;' alt='' id='b_private_opponent_3' onclick='autocompleteReset(\"b_private_opponent_3\"); rebuildPrivateOpponentList();' /></div>");
						$('#b_private_opponent_3_result_container').show();
						$('#b_private_opponent_3').hide();
						$('#b_private_opponent_3_id').val(ui.item.user_id);
						rebuildPrivateOpponentList();
						rebuildFilteredUsersArray();

						return false;
					}
				})
				.data( "autocomplete" )._renderItem = function( ul, item ) {
					return $( "<li style='text-align:left;'></li>" )
						.data( "item.autocomplete", item )
						.append( "<a><div style='display:inline-block;'><img src='" + item.ufb_fb_profile_pic + "' alt='' style='border:1px solid #79a42d;' /></div><div style='display:inline-block; padding:5px; line-height:15px; position:relative; vertical-align:top;'><b>" + item.user_fname.toUpperCase() + " " + item.user_lname.toUpperCase() + "</b><span style='font-weight:normal; font-size:10px; position:absolute; left:5px; top:18px;'>" + item.user_nickname.toUpperCase() + "</span></div></a>" )
						.appendTo( ul );
				};

			});

			$(function() {

				$('#b_private_opponent_4').autocomplete({
					source: WWW+"/ajax.get-autocomplete-users-json.php",
					minLength: 2,
					focus: function(event, ui) {

						/** FAILSAFE MISSING NICKNAME */
						if(!ui.item.user_nickname)
							ui.item.user_nickname = ui.item.user_fname + ' ' + ui.item.user_lname;

						$('#b_private_opponent_4').val(ui.item.user_nickname);
						return false;
					},
					select: function(event, ui) {

						// ENSURE opponent IS NOT USER
						if(ui.item.user_id == window.USER_ID){

							show_div('ajax_msg');	
							$('#ajax_msg').html("You can not compete against yourself!");
							setTimeout("fade_div('ajax_msg')",3000);//fade out

							return false;

						}

						// CHECK OPPONENT AGAINST opponent PANEL
						if(!checkAgainstFilteredUsersArray(ui.item.user_id)){

							show_div('ajax_msg');	
							$('#ajax_msg').html(ui.item.user_fname + " " + ui.item.user_lname + " is already an opponent or a judge.");
							setTimeout("fade_div('ajax_msg')",3000);//fade out

							return false;

						}


						/** FAILSAFE MISSING NICKNAME */
						if(!ui.item.user_nickname)
							ui.item.user_nickname = ui.item.user_fname + ' ' + ui.item.user_lname;

						$('#b_private_opponent_4').val(ui.item.user_nickname);
						$('#b_private_opponent_4_result_container').html("<div class='form_field_results'><div style='margin-bottom:4px;'><img src='" + ui.item.ufb_fb_profile_pic + "' alt='' style='border:1px solid #79a42d;' /></div><div style='position:absolute; top:0; left:55px; padding:5px; height:40px;'><b style='font-size:10px;'>" + ui.item.user_fname.toUpperCase() + " " + ui.item.user_lname.toUpperCase() + "</b><br /><span style='font-weight:normal; font-size:10px;'>" + ui.item.user_nickname.toUpperCase() + "</span></div><img src='"+WWW+"/images/icons/x_9_red.gif' style='position:absolute; top:5px; right:5px;' alt='' id='b_private_opponent_4' onclick='autocompleteReset(\"b_private_opponent_4\"); rebuildPrivateOpponentList();' /></div>");
						$('#b_private_opponent_4_result_container').show();
						$('#b_private_opponent_4').hide();
						$('#b_private_opponent_4_id').val(ui.item.user_id);
						rebuildPrivateOpponentList();
						rebuildFilteredUsersArray();

						return false;
					}
				})
				.data( "autocomplete" )._renderItem = function( ul, item ) {
					return $( "<li style='text-align:left;'></li>" )
						.data( "item.autocomplete", item )
						.append( "<a><div style='display:inline-block;'><img src='" + item.ufb_fb_profile_pic + "' alt='' style='border:1px solid #79a42d;' /></div><div style='display:inline-block; padding:5px; line-height:15px; position:relative; vertical-align:top;'><b>" + item.user_fname.toUpperCase() + " " + item.user_lname.toUpperCase() + "</b><span style='font-weight:normal; font-size:10px; position:absolute; left:5px; top:18px;'>" + item.user_nickname.toUpperCase() + "</span></div></a>" )
						.appendTo( ul );
				};

			});

			$(function() {

				$('#b_private_opponent_5').autocomplete({
					source: WWW+"/ajax.get-autocomplete-users-json.php",
					minLength: 2,
					focus: function(event, ui) {

						/** FAILSAFE MISSING NICKNAME */
						if(!ui.item.user_nickname)
							ui.item.user_nickname = ui.item.user_fname + ' ' + ui.item.user_lname;

						$('#b_private_opponent_5').val(ui.item.user_nickname);
						return false;
					},
					select: function(event, ui) {

						// ENSURE opponent IS NOT USER
						if(ui.item.user_id == window.USER_ID){

							show_div('ajax_msg');	
							$('#ajax_msg').html("You can not compete against yourself!");
							setTimeout("fade_div('ajax_msg')",3000);//fade out

							return false;

						}

						// CHECK OPPONENT AGAINST opponent PANEL
						if(!checkAgainstFilteredUsersArray(ui.item.user_id)){

							show_div('ajax_msg');	
							$('#ajax_msg').html(ui.item.user_fname + " " + ui.item.user_lname + " is already an opponent or a judge.");
							setTimeout("fade_div('ajax_msg')",3000);//fade out

							return false;

						}


						/** FAILSAFE MISSING NICKNAME */
						if(!ui.item.user_nickname)
							ui.item.user_nickname = ui.item.user_fname + ' ' + ui.item.user_lname;

						$('#b_private_opponent_5').val(ui.item.user_nickname);
						$('#b_private_opponent_5_result_container').html("<div class='form_field_results'><div style='margin-bottom:4px;'><img src='" + ui.item.ufb_fb_profile_pic + "' alt='' style='border:1px solid #79a42d;' /></div><div style='position:absolute; top:0; left:55px; padding:5px; height:40px;'><b style='font-size:10px;'>" + ui.item.user_fname.toUpperCase() + " " + ui.item.user_lname.toUpperCase() + "</b><br /><span style='font-weight:normal; font-size:10px;'>" + ui.item.user_nickname.toUpperCase() + "</span></div><img src='"+WWW+"/images/icons/x_9_red.gif' style='position:absolute; top:5px; right:5px;' alt='' id='b_private_opponent_5' onclick='autocompleteReset(\"b_private_opponent_5\"); rebuildPrivateOpponentList();' /></div>");
						$('#b_private_opponent_5_result_container').show();
						$('#b_private_opponent_5').hide();
						$('#b_private_opponent_5_id').val(ui.item.user_id);
						rebuildPrivateOpponentList();
						rebuildFilteredUsersArray();

						return false;
					}
				})
				.data( "autocomplete" )._renderItem = function( ul, item ) {
					return $( "<li style='text-align:left;'></li>" )
						.data( "item.autocomplete", item )
						.append( "<a><div style='display:inline-block;'><img src='" + item.ufb_fb_profile_pic + "' alt='' style='border:1px solid #79a42d;' /></div><div style='display:inline-block; padding:5px; line-height:15px; position:relative; vertical-align:top;'><b>" + item.user_fname.toUpperCase() + " " + item.user_lname.toUpperCase() + "</b><span style='font-weight:normal; font-size:10px; position:absolute; left:5px; top:18px;'>" + item.user_nickname.toUpperCase() + "</span></div></a>" )
						.appendTo( ul );
				};

			});
			
			
			/** AUTOCOMPLETE FOR JUDGES SELECT *******************/
			$(function() {

				$('#b_private_judge_1').autocomplete({
					source: WWW+"/ajax.get-autocomplete-users-json.php",
					minLength: 2,
					focus: function(event, ui) {

						/** FAILSAFE MISSING NICKNAME */
						if(!ui.item.user_nickname)
							ui.item.user_nickname = ui.item.user_fname + ' ' + ui.item.user_lname;

						$('#b_private_judge_1').val(ui.item.user_nickname);
						return false;
					},
					select: function(event, ui) {

						// ENSURE JUDGE IS NOT USER
						if(ui.item.user_id == window.USER_ID){

							show_div('ajax_msg');	
							$('#ajax_msg').html("You can not judge your own battle!");
							setTimeout("fade_div('ajax_msg')",3000);//fade out

							return false;

						}

						// ENSURE JUDGE HAS JUDGE POINTS
						if(ui.item.us_judge_points < 1){

							show_div('ajax_msg');	
							$('#ajax_msg').html(ui.item.user_fname + " " + ui.item.user_lname + " has lost all his judging points from shitty judging and is not eligible to be a judge at this time!");
							setTimeout("fade_div('ajax_msg')",4000);//fade out

							return false;

						}

						// CHECK OPPONENT AGAINST JUDGE PANEL
						if(!checkAgainstFilteredUsersArray(ui.item.user_id)){

							if(ui.item.user_id == $("#b_opponent_id").val()){
								show_div('ajax_msg');	
								$('#ajax_msg').html(ui.item.user_fname + " " + ui.item.user_lname + " can not be both a judge and your opponent.");
								setTimeout("fade_div('ajax_msg')",3000);//fade out
							}
							else{
								//alert('opponent = '+$("#b_opponent_id").val()+'and user = '+ui.item.user_id);
								show_div('ajax_msg');	
								$('#ajax_msg').html(ui.item.user_fname + " " + ui.item.user_lname + " is already a judge.");
								setTimeout("fade_div('ajax_msg')",3000);//fade out
							}

							return false;

						}


						/** FAILSAFE MISSING NICKNAME */
						if(!ui.item.user_nickname)
							ui.item.user_nickname = ui.item.user_fname + ' ' + ui.item.user_lname;

						$('#b_private_judge_1').val(ui.item.user_nickname);
						$('#b_private_judge_1_result_container').html("<div class='form_field_results'><div style='margin-bottom:4px;'><img src='" + ui.item.ufb_fb_profile_pic + "' alt='' style='border:1px solid #79a42d;' /></div><div style='position:absolute; top:0; left:55px; padding:5px; height:40px;'><b style='font-size:10px;'>" + ui.item.user_fname.toUpperCase() + " " + ui.item.user_lname.toUpperCase() + "</b><br /><span style='font-weight:normal; font-size:10px;'>" + ui.item.user_nickname.toUpperCase() + "</span></div><img src='"+WWW+"/images/icons/x_9_red.gif' style='position:absolute; top:5px; right:5px;' alt='' id='b_private_judge_1' onclick='autocompleteReset(\"b_private_judge_1\"); rebuildPrivateJudgeList();' /></div>");
						$('#b_private_judge_1_result_container').show();
						$('#b_private_judge_1').hide();
						$('#b_private_judge_1_id').val(ui.item.user_id);
						rebuildPrivateJudgeList();
						rebuildFilteredUsersArray();

						return false;
					}
				})
				.data( "autocomplete" )._renderItem = function( ul, item ) {
					return $( "<li style='text-align:left;'></li>" )
						.data( "item.autocomplete", item )
						.append( "<a><div style='display:inline-block;'><img src='" + item.ufb_fb_profile_pic + "' alt='' style='border:1px solid #79a42d;' /></div><div style='display:inline-block; padding:5px; line-height:15px; position:relative; vertical-align:top;'><b>" + item.user_fname.toUpperCase() + " " + item.user_lname.toUpperCase() + "</b><span style='font-weight:normal; font-size:10px; position:absolute; left:5px; top:18px;'>" + item.user_nickname.toUpperCase() + "</span></div></a>" )
						.appendTo( ul );
				};

			});

			$(function() {

				$('#b_private_judge_2').autocomplete({
					source: WWW+"/ajax.get-autocomplete-users-json.php",
					minLength: 2,
					focus: function(event, ui) {

						/** FAILSAFE MISSING NICKNAME */
						if(!ui.item.user_nickname)
							ui.item.user_nickname = ui.item.user_fname + ' ' + ui.item.user_lname;

						$('#b_private_judge_2').val(ui.item.user_nickname);
						return false;
					},
					select: function(event, ui) {

						// ENSURE JUDGE IS NOT USER
						if(ui.item.user_id == window.USER_ID){

							show_div('ajax_msg');	
							$('#ajax_msg').html("You can not judge your own battle!");
							setTimeout("fade_div('ajax_msg')",3000);//fade out

							return false;

						}

						// ENSURE JUDGE HAS JUDGE POINTS
						if(ui.item.us_judge_points < 1){

							show_div('ajax_msg');	
							$('#ajax_msg').html(ui.item.user_fname + " " + ui.item.user_lname + " has lost all his judging points from shitty judging and is not eligible to be a judge at this time!");
							setTimeout("fade_div('ajax_msg')",4000);//fade out

							return false;

						}

						// CHECK OPPONENT AGAINST JUDGE PANEL
						if(!checkAgainstFilteredUsersArray(ui.item.user_id)){

							if(ui.item.user_id == $("#b_opponent_id").val()){
								show_div('ajax_msg');	
								$('#ajax_msg').html(ui.item.user_fname + " " + ui.item.user_lname + " can not be both a judge and your opponent.");
								setTimeout("fade_div('ajax_msg')",3000);//fade out
							}
							else{
								//alert('opponent = '+$("#b_opponent_id").val()+'and user = '+ui.item.user_id);
								show_div('ajax_msg');	
								$('#ajax_msg').html(ui.item.user_fname + " " + ui.item.user_lname + " is already a judge.");
								setTimeout("fade_div('ajax_msg')",3000);//fade out
							}

							return false;

						}


						/** FAILSAFE MISSING NICKNAME */
						if(!ui.item.user_nickname)
							ui.item.user_nickname = ui.item.user_fname + ' ' + ui.item.user_lname;

						$('#b_private_judge_2').val(ui.item.user_nickname);
						$('#b_private_judge_2_result_container').html("<div class='form_field_results'><div style='margin-bottom:4px;'><img src='" + ui.item.ufb_fb_profile_pic + "' alt='' style='border:1px solid #79a42d;' /></div><div style='position:absolute; top:0; left:55px; padding:5px; height:40px;'><b style='font-size:10px;'>" + ui.item.user_fname.toUpperCase() + " " + ui.item.user_lname.toUpperCase() + "</b><br /><span style='font-weight:normal; font-size:10px;'>" + ui.item.user_nickname.toUpperCase() + "</span></div><img src='"+WWW+"/images/icons/x_9_red.gif' style='position:absolute; top:5px; right:5px;' alt='' id='b_private_judge_2' onclick='autocompleteReset(\"b_private_judge_2\"); rebuildPrivateJudgeList();' /></div>");
						$('#b_private_judge_2_result_container').show();
						$('#b_private_judge_2').hide();
						$('#b_private_judge_2_id').val(ui.item.user_id);
						rebuildPrivateJudgeList();
						rebuildFilteredUsersArray();

						return false;
					}
				})
				.data( "autocomplete" )._renderItem = function( ul, item ) {
					return $( "<li style='text-align:left;'></li>" )
						.data( "item.autocomplete", item )
						.append( "<a><div style='display:inline-block;'><img src='" + item.ufb_fb_profile_pic + "' alt='' style='border:1px solid #79a42d;' /></div><div style='display:inline-block; padding:5px; line-height:15px; position:relative; vertical-align:top;'><b>" + item.user_fname.toUpperCase() + " " + item.user_lname.toUpperCase() + "</b><span style='font-weight:normal; font-size:10px; position:absolute; left:5px; top:18px;'>" + item.user_nickname.toUpperCase() + "</span></div></a>" )
						.appendTo( ul );
				};

			});

			$(function() {

				$('#b_private_judge_3').autocomplete({
					source: WWW+"/ajax.get-autocomplete-users-json.php",
					minLength: 2,
					focus: function(event, ui) {

						/** FAILSAFE MISSING NICKNAME */
						if(!ui.item.user_nickname)
							ui.item.user_nickname = ui.item.user_fname + ' ' + ui.item.user_lname;

						$('#b_private_judge_3').val(ui.item.user_nickname);
						return false;
					},
					select: function(event, ui) {

						// ENSURE JUDGE IS NOT USER
						if(ui.item.user_id == window.USER_ID){

							show_div('ajax_msg');	
							$('#ajax_msg').html("You can not judge your own battle!");
							setTimeout("fade_div('ajax_msg')",3000);//fade out

							return false;

						}

						// ENSURE JUDGE HAS JUDGE POINTS
						if(ui.item.us_judge_points < 1){

							show_div('ajax_msg');	
							$('#ajax_msg').html(ui.item.user_fname + " " + ui.item.user_lname + " has lost all his judging points from shitty judging and is not eligible to be a judge at this time!");
							setTimeout("fade_div('ajax_msg')",4000);//fade out

							return false;

						}

						// CHECK OPPONENT AGAINST JUDGE PANEL
						if(!checkAgainstFilteredUsersArray(ui.item.user_id)){

							if(ui.item.user_id == $("#b_opponent_id").val()){
								show_div('ajax_msg');	
								$('#ajax_msg').html(ui.item.user_fname + " " + ui.item.user_lname + " can not be both a judge and your opponent.");
								setTimeout("fade_div('ajax_msg')",3000);//fade out
							}
							else{
								//alert('opponent = '+$("#b_opponent_id").val()+'and user = '+ui.item.user_id);
								show_div('ajax_msg');	
								$('#ajax_msg').html(ui.item.user_fname + " " + ui.item.user_lname + " is already a judge.");
								setTimeout("fade_div('ajax_msg')",3000);//fade out
							}

							return false;

						}


						/** FAILSAFE MISSING NICKNAME */
						if(!ui.item.user_nickname)
							ui.item.user_nickname = ui.item.user_fname + ' ' + ui.item.user_lname;

						$('#b_private_judge_3').val(ui.item.user_nickname);
						$('#b_private_judge_3_result_container').html("<div class='form_field_results'><div style='margin-bottom:4px;'><img src='" + ui.item.ufb_fb_profile_pic + "' alt='' style='border:1px solid #79a42d;' /></div><div style='position:absolute; top:0; left:55px; padding:5px; height:40px;'><b style='font-size:10px;'>" + ui.item.user_fname.toUpperCase() + " " + ui.item.user_lname.toUpperCase() + "</b><br /><span style='font-weight:normal; font-size:10px;'>" + ui.item.user_nickname.toUpperCase() + "</span></div><img src='"+WWW+"/images/icons/x_9_red.gif' style='position:absolute; top:5px; right:5px;' alt='' id='b_private_judge_3' onclick='autocompleteReset(\"b_private_judge_3\"); rebuildPrivateJudgeList();' /></div>");
						$('#b_private_judge_3_result_container').show();
						$('#b_private_judge_3').hide();
						$('#b_private_judge_3_id').val(ui.item.user_id);
						rebuildPrivateJudgeList();
						rebuildFilteredUsersArray();

						return false;
					}
				})
				.data( "autocomplete" )._renderItem = function( ul, item ) {
					return $( "<li style='text-align:left;'></li>" )
						.data( "item.autocomplete", item )
						.append( "<a><div style='display:inline-block;'><img src='" + item.ufb_fb_profile_pic + "' alt='' style='border:1px solid #79a42d;' /></div><div style='display:inline-block; padding:5px; line-height:15px; position:relative; vertical-align:top;'><b>" + item.user_fname.toUpperCase() + " " + item.user_lname.toUpperCase() + "</b><span style='font-weight:normal; font-size:10px; position:absolute; left:5px; top:18px;'>" + item.user_nickname.toUpperCase() + "</span></div></a>" )
						.appendTo( ul );
				};

			});

			$(function() {

				$('#b_private_judge_4').autocomplete({
					source: WWW+"/ajax.get-autocomplete-users-json.php",
					minLength: 2,
					focus: function(event, ui) {

						/** FAILSAFE MISSING NICKNAME */
						if(!ui.item.user_nickname)
							ui.item.user_nickname = ui.item.user_fname + ' ' + ui.item.user_lname;

						$('#b_private_judge_4').val(ui.item.user_nickname);
						return false;
					},
					select: function(event, ui) {

						// ENSURE JUDGE IS NOT USER
						if(ui.item.user_id == window.USER_ID){

							show_div('ajax_msg');	
							$('#ajax_msg').html("You can not judge your own battle!");
							setTimeout("fade_div('ajax_msg')",3000);//fade out

							return false;

						}

						// ENSURE JUDGE HAS JUDGE POINTS
						if(ui.item.us_judge_points < 1){

							show_div('ajax_msg');	
							$('#ajax_msg').html(ui.item.user_fname + " " + ui.item.user_lname + " has lost all his judging points from shitty judging and is not eligible to be a judge at this time!");
							setTimeout("fade_div('ajax_msg')",4000);//fade out

							return false;

						}

						// CHECK OPPONENT AGAINST JUDGE PANEL
						if(!checkAgainstFilteredUsersArray(ui.item.user_id)){

							if(ui.item.user_id == $("#b_opponent_id").val()){
								show_div('ajax_msg');	
								$('#ajax_msg').html(ui.item.user_fname + " " + ui.item.user_lname + " can not be both a judge and your opponent.");
								setTimeout("fade_div('ajax_msg')",3000);//fade out
							}
							else{
								//alert('opponent = '+$("#b_opponent_id").val()+'and user = '+ui.item.user_id);
								show_div('ajax_msg');	
								$('#ajax_msg').html(ui.item.user_fname + " " + ui.item.user_lname + " is already a judge.");
								setTimeout("fade_div('ajax_msg')",3000);//fade out
							}

							return false;

						}


						/** FAILSAFE MISSING NICKNAME */
						if(!ui.item.user_nickname)
							ui.item.user_nickname = ui.item.user_fname + ' ' + ui.item.user_lname;

						$('#b_private_judge_4').val(ui.item.user_nickname);
						$('#b_private_judge_4_result_container').html("<div class='form_field_results'><div style='margin-bottom:4px;'><img src='" + ui.item.ufb_fb_profile_pic + "' alt='' style='border:1px solid #79a42d;' /></div><div style='position:absolute; top:0; left:55px; padding:5px; height:40px;'><b style='font-size:10px;'>" + ui.item.user_fname.toUpperCase() + " " + ui.item.user_lname.toUpperCase() + "</b><br /><span style='font-weight:normal; font-size:10px;'>" + ui.item.user_nickname.toUpperCase() + "</span></div><img src='"+WWW+"/images/icons/x_9_red.gif' style='position:absolute; top:5px; right:5px;' alt='' id='b_private_judge_4' onclick='autocompleteReset(\"b_private_judge_4\"); rebuildPrivateJudgeList();' /></div>");
						$('#b_private_judge_4_result_container').show();
						$('#b_private_judge_4').hide();
						$('#b_private_judge_4_id').val(ui.item.user_id);
						rebuildPrivateJudgeList();
						rebuildFilteredUsersArray();

						return false;
					}
				})
				.data( "autocomplete" )._renderItem = function( ul, item ) {
					return $( "<li style='text-align:left;'></li>" )
						.data( "item.autocomplete", item )
						.append( "<a><div style='display:inline-block;'><img src='" + item.ufb_fb_profile_pic + "' alt='' style='border:1px solid #79a42d;' /></div><div style='display:inline-block; padding:5px; line-height:15px; position:relative; vertical-align:top;'><b>" + item.user_fname.toUpperCase() + " " + item.user_lname.toUpperCase() + "</b><span style='font-weight:normal; font-size:10px; position:absolute; left:5px; top:18px;'>" + item.user_nickname.toUpperCase() + "</span></div></a>" )
						.appendTo( ul );
				};

			});

			$(function() {

				$('#b_private_judge_5').autocomplete({
					source: WWW+"/ajax.get-autocomplete-users-json.php",
					minLength: 2,
					focus: function(event, ui) {

						/** FAILSAFE MISSING NICKNAME */
						if(!ui.item.user_nickname)
							ui.item.user_nickname = ui.item.user_fname + ' ' + ui.item.user_lname;

						$('#b_private_judge_5').val(ui.item.user_nickname);
						return false;
					},
					select: function(event, ui) {

						// ENSURE JUDGE IS NOT USER
						if(ui.item.user_id == window.USER_ID){

							show_div('ajax_msg');	
							$('#ajax_msg').html("You can not judge your own battle!");
							setTimeout("fade_div('ajax_msg')",3000);//fade out

							return false;

						}

						// ENSURE JUDGE HAS JUDGE POINTS
						if(ui.item.us_judge_points < 1){

							show_div('ajax_msg');	
							$('#ajax_msg').html(ui.item.user_fname + " " + ui.item.user_lname + " has lost all his judging points from shitty judging and is not eligible to be a judge at this time!");
							setTimeout("fade_div('ajax_msg')",4000);//fade out

							return false;

						}

						// CHECK OPPONENT AGAINST JUDGE PANEL
						if(!checkAgainstFilteredUsersArray(ui.item.user_id)){

							if(ui.item.user_id == $("#b_opponent_id").val()){
								show_div('ajax_msg');	
								$('#ajax_msg').html(ui.item.user_fname + " " + ui.item.user_lname + " can not be both a judge and your opponent.");
								setTimeout("fade_div('ajax_msg')",3000);//fade out
							}
							else{
								//alert('opponent = '+$("#b_opponent_id").val()+'and user = '+ui.item.user_id);
								show_div('ajax_msg');	
								$('#ajax_msg').html(ui.item.user_fname + " " + ui.item.user_lname + " is already a judge.");
								setTimeout("fade_div('ajax_msg')",3000);//fade out
							}

							return false;

						}


						/** FAILSAFE MISSING NICKNAME */
						if(!ui.item.user_nickname)
							ui.item.user_nickname = ui.item.user_fname + ' ' + ui.item.user_lname;

						$('#b_private_judge_5').val(ui.item.user_nickname);
						$('#b_private_judge_5_result_container').html("<div class='form_field_results'><div style='margin-bottom:4px;'><img src='" + ui.item.ufb_fb_profile_pic + "' alt='' style='border:1px solid #79a42d;' /></div><div style='position:absolute; top:0; left:55px; padding:5px; height:40px;'><b style='font-size:10px;'>" + ui.item.user_fname.toUpperCase() + " " + ui.item.user_lname.toUpperCase() + "</b><br /><span style='font-weight:normal; font-size:10px;'>" + ui.item.user_nickname.toUpperCase() + "</span></div><img src='"+WWW+"/images/icons/x_9_red.gif' style='position:absolute; top:5px; right:5px;' alt='' id='b_private_judge_5' onclick='autocompleteReset(\"b_private_judge_5\"); rebuildPrivateJudgeList();' /></div>");
						$('#b_private_judge_5_result_container').show();
						$('#b_private_judge_5').hide();
						$('#b_private_judge_5_id').val(ui.item.user_id);
						rebuildPrivateJudgeList();
						rebuildFilteredUsersArray();

						return false;
					}
				})
				.data( "autocomplete" )._renderItem = function( ul, item ) {
					return $( "<li style='text-align:left;'></li>" )
						.data( "item.autocomplete", item )
						.append( "<a><div style='display:inline-block;'><img src='" + item.ufb_fb_profile_pic + "' alt='' style='border:1px solid #79a42d;' /></div><div style='display:inline-block; padding:5px; line-height:15px; position:relative; vertical-align:top;'><b>" + item.user_fname.toUpperCase() + " " + item.user_lname.toUpperCase() + "</b><span style='font-weight:normal; font-size:10px; position:absolute; left:5px; top:18px;'>" + item.user_nickname.toUpperCase() + "</span></div></a>" )
						.appendTo( ul );
				};

			});

			/** INITIALIZE TOOL TIP ******************************/
			tooltip();

			/** DECLARE SELECT MENUS FOR JQUERY UI ***************/
			//$('select#b_bsm_id').selectmenu();

			/** DECLARE SELECTED TRICKS AS SORTABLE **************/
			$(document).ready(function() {
				$("#selected_tricks_sortable").sortable({

					cursor: 's-resize',
					placeholder: 'sortable-state-highlight',
					stop: function(event, ui) {

						rebuildSelectedTricksList('selected_tricks_sortable');
					}


				});
			});

			/** DECLARE LIST PLUGIN FOR JQUERY *******************/
			 $('#featured_tricks').listnav({ 
			    initLetter: 's', 
			    includeAll: false, 
			    includeOther: false,
			    includeNums: true,
			    flagDisabled: false, 
			    noMatchText: 'No tricks found, please click another letter.', 
			    showCounts: false, 
			    cookieName: 'trick-list', 
			    //onClick: function(letter){ alert('You clicked ' + letter); }, 
			    prefixes: ['the','a','pop','swingthru','**'] 
			});


			/** DECLARE SELECTED TRICK TYPES AS SORTABLE *********/
			$(document).ready(function() {
				$("#selected_trick_types_sortable").sortable({

					cursor: 's-resize',
					placeholder: 'sortable-state-highlight',
					stop: function(event, ui) {

						rebuildSelectedTrickTypesList('selected_trick_types_sortable');
					}


				});
			});

			/** DECLARE LIST PLUGIN FOR JQUERY *******************/
			/*
			 $('#featured_trick_types').listnav({ 
			    initLetter: 'a', 
			    includeAll: false, 
			    includeOther: false,
			    includeNums: true,
			    flagDisabled: false, 
			    noMatchText: 'No tricks found, please click another letter.', 
			    showCounts: false, 
			    cookieName: 'trick-type-list', 
			    //onClick: function(letter){ alert('You clicked ' + letter); }, 
			    prefixes: ['the','a'] 
			});
			*/

			/** WHEN USER FOCUSES THE TITLE FIELD, CLEAR IT OUT */
			$("#b_title").focus(function(){

				if($("#b_title").val() == "Trick Battle")
					$("#b_title").val("");

			});
			
			$("#b_title").blur(function(){

				if($("#b_title").val() == "")
					$("#b_title").val("Trick Battle");
			
			});
			
			/** WHEN USER FOCUSES THE VIDEO URL FIELD, CLEAR IT OUT */
			$("#video_url").focus(function(){

				if(document.getElementById("video_url").value == "Video URL")
					document.getElementById("video_url").value = "";

			});

			/** WHEN USER BLURS THE VIDEO URL FIELD, CHECK FOR BLANK, OR FETCH ***/
			$("#video_url").blur(function(){

				if(document.getElementById("video_url").value == "")
					document.getElementById("video_url").value = "Video URL";
				else {
					document.getElementById("video_url_field_container").style.display = 'none';
					document.getElementById("video_url_oembed_container").style.display = 'block';

					/** CREATE DOM ANCHOR DOM ELEMENT TO HOLD THE URL ************/
					var oembed_anchor = document.createElement("a");
					oembed_anchor.setAttribute("href", document.getElementById("video_url").value);
					oembed_anchor.setAttribute("id", "video_url_oembed");

					/** SHOW DIV CONTAINER AND CLEAR IT OUT **********************/
					document.getElementById("video_url_oembed_container").style.display = "block";
					document.getElementById("video_url_oembed_container").innerHTML = "";

					/** CREATE RESET LINK ****************************************/
					var reset_link = document.createElement("a");
					reset_link.setAttribute("id","video_url_reset");
					reset_link.setAttribute("href","#");
					reset_link.setAttribute("onclick","resetVideo();");
					var reset_link_text = document.createTextNode("Wrong video / no video?");
					reset_link.appendChild(reset_link_text);

					/** APPEND THE NEW NODES TO THE CONTAINER ********************/
					document.getElementById("video_url_oembed_container").appendChild(oembed_anchor);
					//document.getElementById("video_url_oembed_container").appendChild(document.createElement("br"));
					document.getElementById("video_url_oembed_container").appendChild(reset_link);
					document.getElementById("video_url_reset").style.display = "block";
					document.getElementById("video_url_reset").style.width = "100%";
					document.getElementById("video_url_reset").style.textAlign = "right";
					document.getElementById("video_url_reset").style.marginTop = "2px";

					//embedmethod:append seems to remove the title and volume, etc from vimeo
					$("#video_url_oembed").oembed(null, {
					vimeo: {color: "9cd03f", portrait: false},
					/*embedMethod: "append",*/
					maxWidth: 275
					});

				}


			});
			
			tabIndexify('form');
			
		}
	});
}

/** FUNCTION LOADS TOURNAMENT CREATE FORM ************************************/
function load_battle_creator_tournament(){

	$.ajax({
		type: "GET",
		url: WWW+"/ajax.battle-create-tournament.php",
		success: function(data) {

			$('#dashboard_content_ajax').html(data);
			
		}
	});
}

/** FUNCTION LOADS PENDING CHALLENGES ****************************************/
function load_pending_battles(){

	$.ajax({
		type: "GET",
		url: WWW+"/ajax.get-pending-battles.php",
		success: function(data) {

			$('#dashboard_content_ajax').html(data);

			/** INITIALIZE TABLESORTER ***************************/
			$("#pending_battles").tablesorter({ 
				// sort on the deadline column, order asc 
				sortList: [[7,0]] 
			});
			
			/** INITIALIZE TOOLTIP *******************************/
			tooltip();
			imgtooltip();
		}
	});
}

/** FUNCTION LOADS ACTIVE BATTLES ********************************************/
function load_active_battles(){

	$.ajax({
		type: "GET",
		url: WWW+"/ajax.get-active-battles.php",
		success: function(data) {

			$('#dashboard_content_ajax').html(data);

			/** INITIALIZE TABLESORTER ***************************/
			$("#active_battles").tablesorter({ 
				// sort on the deadline column, order asc 
				sortList: [[5,0]] 
			});
			
			/** INITIALIZE TOOLTIP *******************************/
			tooltip();
			imgtooltip();
		}
	});
}
/** FUNCTION LOADS BATTLE ACCEPT FORM HANDLER ********************************/
function load_battle_accept_form(b_id,video_only,join_ffa){

	var dataString = 'b_id=' + b_id;
	
	if(video_only == 1)
		dataString += '&video_only=1';
	
	if(join_ffa == 'join')
		dataString += '&join=1';
		
	$.ajax({
		type: "POST",
		url: WWW+"/ajax.battle-accept-challenge.php",
		data: dataString,
		success: function(data) {
			
			$('#ajax_msg_absolute').show().html(data);
			$('html').scrollTo(500,'swing');
			
			/** INITIALIZE TOOLTIP *******************************/
			tooltip();
			imgtooltip();
			
			/** VALIDATE FORM SUBMISSION *************************/
			$("form").submit(function() {

				var formFail = false;

				/** VIDEO URL ********************************/
				var video_url = $("#video_url").val();
				if(video_url == "Video URL") {
					if($("#video_only").val() == 1){
						$("#video_url").effect("highlight", {}, 3000);
						formFail = true;
					}
				}
				else{	
					/** COMPARE URL TO YOUTUBE FORMAT ****/
					if($("#video_url").val().match(youtubeRegex))
						var tmp=1; //alert('valid youtube url');

					/** COMPARE URL TO VIMEO FORMAT ******/
					else if($("#video_url").val().match(vimeoRegex))
						var tmp=1 //alert('valid vimeo url');

					/** SHOW ERROR MESSAGE ***************/
					else {						
						show_div('ajax_msg');	
						$('#ajax_msg').html("Invalid video url format - Youtube or Vimeo only please!");
						setTimeout("fade_div('ajax_msg')",3000);//fade out
						formFail = true;					
					}
				}

				/** JUDGING PANEL ****************************/
				var judging_method = $("#b_bjm_id").val();
				var private_judges = $("#b_private_judges_hidden").val(); 

				/** BATTLE INFO ******************************/
				window.battle_type = $("#b_bt_id").val();
				window.battle_title = $("#b_title").val(); 
				window.battle_creator_id = $("#b_creator_id").val(); 
				window.battle_creator_name = $("#b_creator_name").val(); 
				window.battle_creator_fb_uid = $("#b_creator_fb_uid").val(); 

				/** SELECTED TRICK TYPES *********************/
				var selected_tricks = $("#selected_tricks_list_hidden").val();
				var tricks_or_types = $("#tricks_or_types").val();
				if(tricks_or_types == "types"){
					if (selected_tricks == "") {
						$("#featured_tricks").effect("highlight", {}, 3000);
						formFail = true;
					}
				}
				
				/** AJAX FORM SUBMIT ONLY IF VALID FORM ******/
				if(formFail === false){

					/** CREATE CONCATINATED QUERY STRING */
					//b_bt_id=1 means battle type of head-to-head
					var dataString = 'b_id=' + b_id + 
							 '&b_accept=1';
					
					/** ENSURE WE HAVE A VIDEO */
					if(video_url != "Video URL")
						dataString += '&video_url=' + urlencode(video_url);
					
					/** CHECK FOR VIDEO ONLY *************/
					if($("#video_only").val() == 1)
						dataString += '&video_only=1';
						
					/** APPEND PRIVATE JUDGES IF APPLICABLE */
					if(judging_method == 3)
						dataString += '&b_bjm_id=3&private_judges=' + private_judges;
					else
						dataString += '&b_bjm_id=' + judging_method;

					/** APPEND THE REST OF THE FORM FIELDS */
					dataString += '&selected_tricks=' + selected_tricks +
						      '&tricks_or_types=' + tricks_or_types; 
					
					if(video_url == "Video URL")
						var ajaxUrl = WWW+"/ajax.get-pending-battles.php";
					else
						var ajaxUrl = WWW+"/ajax.get-active-battles.php";
						
					$.ajax({
						type: "POST",
						url: WWW+"/ajax.battle-accept-challenge.php",
						data: dataString,
						success: function(data) {

							load_active_ajax = function(){

								$.ajax({
									type: "POST",
									url: ajaxUrl,
									data: dataString,
									success: function(data) {

										$('#dashboard_content_ajax').html(data);
			
										/** INITIALIZE TABLESORTER ************/
										$("#active_battles").tablesorter({ 
											// sort on the deadline column, order asc 
											sortList: [[5,0]] 
										});

										/** INITIALIZE TOOLTIP ****************/
										tooltip();
										imgtooltip();

									} // end success

								});

							}


							load_pending_ajax = function(){

								$.ajax({
									type: "POST",
									url: ajaxUrl,
									data: dataString,
									success: function(data) {

										$('#dashboard_content_ajax').html(data);
			
										/** INITIALIZE TABLESORTER ************/
										$("#pending_battles").tablesorter({ 
											// sort on the deadline column, order asc 
											sortList: [[5,0]] 
										});

										/** INITIALIZE TOOLTIP ****************/
										tooltip();
										imgtooltip();

									} // end success

								});
							}
							
							show_div('ajax_msg_absolute');	
							$('#ajax_msg_absolute').html(data);
							
							if(data == 'Challenge Accepted!'){
								
								/** HERE WE POST TO CHALLENGERs WALL LETTING THEM KNOW THEIR CHALLENGE HAS BEEN ACCEPTED **/

								if(private_judges == '')
									var fb_attachment_desc = 'Who wants to judge this battle?!';
								else
									var fb_attachment_desc = 'Privately judged.'
									
								var fb_attachment_name = window.battle_title;
								var fb_attachment_caption = 'http://www.trickerbattle.com';
								var fb_attachment_url = 'http://www.trickerbattle.com/battles';
								if(window.battle_desc)
									fb_attachment_caption = window.battle_desc;

								/** HERE WE SHOULD POST TO FACEBOOK WALL **/
								if(window.fbStreamPublishOnChallengeAccept == 1){
							
									// challenger
									var fb_message = 'accepted ' + window.battle_creator_name + '\'s battle challenge!';
									publishToWall(window.fb_uid,fb_message,fb_attachment_desc,fb_attachment_name,fb_attachment_caption,fb_attachment_url);
								}
								
								/** CHECK OPPONENTS USER PREFERENCE IF THEY WANT TO BE NOTIFIED **/
								dataString = 'ufb_fb_uid=' + window.battle_creator_fb_uid +
									     '&pref_key=fb_stream_publish_when_challenge_accepted';
								$.ajax({
									type: "POST",
									url: WWW+"/ajax.get-user-pref.php",
									data: dataString,
									success: function(data) {
										
										if(data != 0){
											// creator
											var fb_message = 'has accepted your tricking battle challenge!';
											publishToWall(window.battle_creator_fb_uid,fb_message,fb_attachment_desc,fb_attachment_name,fb_attachment_caption,fb_attachment_url);
										}
										
									} // end success

								});


								// app wall
								var fb_message = 'has accepted ' + window.battle_creator_name + '\'s battle challenge!!';
								publishToWall(window.APP_FB_UID,fb_message,fb_attachment_desc,fb_attachment_name,fb_attachment_caption,fb_attachment_url);									



								setTimeout("fade_div('ajax_msg_absolute')",2000); //fade out
								setTimeout("$('html').scrollTo(500,'swing')",2500);
								setTimeout("load_pending_ajax()",2800);
							
							}
							if(data == 'Challenge accepted - this battle is ready to go! Activating...'){
							
								/** HERE WE SHOULD POST TO CHALLENGERs WALL LETTING THEM KNOW THEIR CHALLENGE HAS BEEN ACCEPTED AND THE BATTLE IS STARTING EARLY **/

								if(private_judges == '')
									var fb_attachment_desc = 'This battle is now active and open for judging!';
								else
									var fb_attachment_desc = 'Privately judged.'
									
								var fb_attachment_name = window.battle_title;
								var fb_attachment_caption = 'http://www.trickerbattle.com';
								var fb_attachment_url = 'http://www.trickerbattle.com/battles';
								if(window.battle_desc)
									fb_attachment_caption = window.battle_desc;

								/** HERE WE SHOULD POST TO FACEBOOK WALL **/
								if(window.fbStreamPublishOnChallengeAccept == 1){
							
									// challenger
									var fb_message = 'accepted ' + window.battle_creator_name + '\'s battle challenge!';
									publishToWall(window.fb_uid,fb_message,fb_attachment_desc,fb_attachment_name,fb_attachment_caption,fb_attachment_url);
								}
								
								/** CHECK OPPONENTS USER PREFERENCE IF THEY WANT TO BE NOTIFIED **/
								dataString = 'ufb_fb_uid=' + window.battle_creator_fb_uid +
									     '&pref_key=fb_stream_publish_when_challenge_accepted';
								$.ajax({
									type: "POST",
									url: WWW+"/ajax.get-user-pref.php",
									data: dataString,
									success: function(data) {
										
										if(data != 0){
											// creator
											var fb_message = 'has accepted your tricking battle challenge!';
											publishToWall(window.battle_creator_fb_uid,fb_message,fb_attachment_desc,fb_attachment_name,fb_attachment_caption,fb_attachment_url);
										}
										
									} // end success

								});


								// app wall
								var fb_message = 'has accepted ' + window.battle_creator_name + '\'s battle challenge!!';
								publishToWall(window.APP_FB_UID,fb_message,fb_attachment_desc,fb_attachment_name,fb_attachment_caption,fb_attachment_url);									

								
								setTimeout("fade_div('ajax_msg_absolute')",2000); //fade out
								setTimeout("$('html').scrollTo(500,'swing')",2500);
								setTimeout("load_active_ajax()",2800);
							
							}
							
							if(join_ffa == 'join' || video_only == 1){
								setTimeout("window.location.reload()",1000);
							}
							
						} // end success
						
					});

				}
					
				/** DONT SUBMIT FORM - AJAX ONLY *************/
				return false;
			});
			

			/** AUTOCOMPLETE FOR JUDGES SELECT *******************/
			$(function() {

				$('#b_private_judge_1').autocomplete({
					source: WWW+"/ajax.get-autocomplete-users-json.php",
					minLength: 2,
					focus: function(event, ui) {

						/** FAILSAFE MISSING NICKNAME */
						if(!ui.item.user_nickname)
							ui.item.user_nickname = ui.item.user_fname + ' ' + ui.item.user_lname;

						$('#b_private_judge_1').val(ui.item.user_nickname);
						return false;
					},
					select: function(event, ui) {

						// ENSURE JUDGE IS NOT USER
						if(ui.item.user_id == window.USER_ID){

							show_div('ajax_msg');	
							$('#ajax_msg').html("You can not judge your own battle!");
							setTimeout("fade_div('ajax_msg')",3000);//fade out

							return false;

						}

						// ENSURE JUDGE HAS JUDGE POINTS
						if(ui.item.us_judge_points < 1){

							show_div('ajax_msg');	
							$('#ajax_msg').html(ui.item.user_fname + " " + ui.item.user_lname + " has lost all his judging points from shitty judging and is not eligible to be a judge at this time!");
							setTimeout("fade_div('ajax_msg')",4000);//fade out

							return false;

						}

						// CHECK OPPONENT AGAINST JUDGE PANEL
						if(!checkAgainstFilteredUsersArray(ui.item.user_id)){

							if(ui.item.user_id == $("#b_opponent_id").val()){
								show_div('ajax_msg');	
								$('#ajax_msg').html(ui.item.user_fname + " " + ui.item.user_lname + " can not be both a judge and your opponent.");
								setTimeout("fade_div('ajax_msg')",3000);//fade out
							}
							else{
								//alert('opponent = '+$("#b_opponent_id").val()+'and user = '+ui.item.user_id);
								show_div('ajax_msg');	
								$('#ajax_msg').html(ui.item.user_fname + " " + ui.item.user_lname + " is already a judge.");
								setTimeout("fade_div('ajax_msg')",3000);//fade out
							}

							return false;

						}

						/** FAILSAFE MISSING NICKNAME */
						if(!ui.item.user_nickname)
							ui.item.user_nickname = ui.item.user_fname + ' ' + ui.item.user_lname;

						$('#b_private_judge_1').val(ui.item.user_nickname);
						$('#b_private_judge_1_result_container').html("<div class='form_field_results'><div style='margin-bottom:4px;'><img src='" + ui.item.ufb_fb_profile_pic + "' alt='' style='border:1px solid #79a42d;' /></div><div style='position:absolute; top:0; left:55px; padding:5px; height:40px;'><b style='font-size:10px;'>" + ui.item.user_fname.toUpperCase() + " " + ui.item.user_lname.toUpperCase() + "</b><br /><span style='font-weight:normal; font-size:10px;'>" + ui.item.user_nickname.toUpperCase() + "</span></div><img src='"+WWW+"/images/icons/x_9_red.gif' style='position:absolute; top:5px; right:5px;' alt='' id='b_private_judge_1' onclick='autocompleteReset(\"b_private_judge_1\"); rebuildPrivateJudgeList();' /></div>");
						$('#b_private_judge_1_result_container').show();
						$('#b_private_judge_1').hide();
						$('#b_private_judge_1_id').val(ui.item.user_id);
						rebuildPrivateJudgeList();
						rebuildFilteredUsersArray();

						return false;
					}
				})
				.data( "autocomplete" )._renderItem = function( ul, item ) {
					return $( "<li style='text-align:left;'></li>" )
						.data( "item.autocomplete", item )
						.append( "<a><div style='display:inline-block;'><img src='" + item.ufb_fb_profile_pic + "' alt='' style='border:1px solid #79a42d;' /></div><div style='display:inline-block; padding:5px; line-height:15px; position:relative; vertical-align:top;'><b>" + item.user_fname.toUpperCase() + " " + item.user_lname.toUpperCase() + "</b><span style='font-weight:normal; font-size:10px; position:absolute; left:5px; top:18px;'>" + item.user_nickname.toUpperCase() + "</span></div></a>" )
						.appendTo( ul );
				};

			});

			$(function() {

				$('#b_private_judge_2').autocomplete({
					source: WWW+"/ajax.get-autocomplete-users-json.php",
					minLength: 2,
					focus: function(event, ui) {

						/** FAILSAFE MISSING NICKNAME */
						if(!ui.item.user_nickname)
							ui.item.user_nickname = ui.item.user_fname + ' ' + ui.item.user_lname;

						$('#b_private_judge_2').val(ui.item.user_nickname);
						return false;
					},
					select: function(event, ui) {

						// ENSURE JUDGE IS NOT USER
						if(ui.item.user_id == window.USER_ID){

							show_div('ajax_msg');	
							$('#ajax_msg').html("You can not judge your own battle!");
							setTimeout("fade_div('ajax_msg')",3000);//fade out

							return false;

						}

						// ENSURE JUDGE HAS JUDGE POINTS
						if(ui.item.us_judge_points < 1){

							show_div('ajax_msg');	
							$('#ajax_msg').html(ui.item.user_fname + " " + ui.item.user_lname + " has lost all his judging points from shitty judging and is not eligible to be a judge at this time!");
							setTimeout("fade_div('ajax_msg')",4000);//fade out

							return false;

						}

						// CHECK OPPONENT AGAINST JUDGE PANEL
						if(!checkAgainstFilteredUsersArray(ui.item.user_id)){

							if(ui.item.user_id == $("#b_opponent_id").val()){
								show_div('ajax_msg');	
								$('#ajax_msg').html(ui.item.user_fname + " " + ui.item.user_lname + " can not be both a judge and your opponent.");
								setTimeout("fade_div('ajax_msg')",3000);//fade out
							}
							else{
								//alert('opponent = '+$("#b_opponent_id").val()+'and user = '+ui.item.user_id);
								show_div('ajax_msg');	
								$('#ajax_msg').html(ui.item.user_fname + " " + ui.item.user_lname + " is already a judge.");
								setTimeout("fade_div('ajax_msg')",3000);//fade out
							}

							return false;

						}


						/** FAILSAFE MISSING NICKNAME */
						if(!ui.item.user_nickname)
							ui.item.user_nickname = ui.item.user_fname + ' ' + ui.item.user_lname;

						$('#b_private_judge_2').val(ui.item.user_nickname);
						$('#b_private_judge_2_result_container').html("<div class='form_field_results'><div style='margin-bottom:4px;'><img src='" + ui.item.ufb_fb_profile_pic + "' alt='' style='border:1px solid #79a42d;' /></div><div style='position:absolute; top:0; left:55px; padding:5px; height:40px;'><b style='font-size:10px;'>" + ui.item.user_fname.toUpperCase() + " " + ui.item.user_lname.toUpperCase() + "</b><br /><span style='font-weight:normal; font-size:10px;'>" + ui.item.user_nickname.toUpperCase() + "</span></div><img src='"+WWW+"/images/icons/x_9_red.gif' style='position:absolute; top:5px; right:5px;' alt='' id='b_private_judge_2' onclick='autocompleteReset(\"b_private_judge_2\"); rebuildPrivateJudgeList();' /></div>");
						$('#b_private_judge_2_result_container').show();
						$('#b_private_judge_2').hide();
						$('#b_private_judge_2_id').val(ui.item.user_id);
						rebuildPrivateJudgeList();
						rebuildFilteredUsersArray();

						return false;
					}
				})
				.data( "autocomplete" )._renderItem = function( ul, item ) {
					return $( "<li style='text-align:left;'></li>" )
						.data( "item.autocomplete", item )
						.append( "<a><div style='display:inline-block;'><img src='" + item.ufb_fb_profile_pic + "' alt='' style='border:1px solid #79a42d;' /></div><div style='display:inline-block; padding:5px; line-height:15px; position:relative; vertical-align:top;'><b>" + item.user_fname.toUpperCase() + " " + item.user_lname.toUpperCase() + "</b><span style='font-weight:normal; font-size:10px; position:absolute; left:5px; top:18px;'>" + item.user_nickname.toUpperCase() + "</span></div></a>" )
						.appendTo( ul );
				};

			});

			$(function() {

				$('#b_private_judge_3').autocomplete({
					source: WWW+"/ajax.get-autocomplete-users-json.php",
					minLength: 2,
					focus: function(event, ui) {

						/** FAILSAFE MISSING NICKNAME */
						if(!ui.item.user_nickname)
							ui.item.user_nickname = ui.item.user_fname + ' ' + ui.item.user_lname;

						$('#b_private_judge_3').val(ui.item.user_nickname);
						return false;
					},
					select: function(event, ui) {

						// ENSURE JUDGE IS NOT USER
						if(ui.item.user_id == window.USER_ID){

							show_div('ajax_msg');	
							$('#ajax_msg').html("You can not judge your own battle!");
							setTimeout("fade_div('ajax_msg')",3000);//fade out

							return false;

						}

						// ENSURE JUDGE HAS JUDGE POINTS
						if(ui.item.us_judge_points < 1){

							show_div('ajax_msg');	
							$('#ajax_msg').html(ui.item.user_fname + " " + ui.item.user_lname + " has lost all his judging points from shitty judging and is not eligible to be a judge at this time!");
							setTimeout("fade_div('ajax_msg')",4000);//fade out

							return false;

						}

						// CHECK OPPONENT AGAINST JUDGE PANEL
						if(!checkAgainstFilteredUsersArray(ui.item.user_id)){

							if(ui.item.user_id == $("#b_opponent_id").val()){
								show_div('ajax_msg');	
								$('#ajax_msg').html(ui.item.user_fname + " " + ui.item.user_lname + " can not be both a judge and your opponent.");
								setTimeout("fade_div('ajax_msg')",3000);//fade out
							}
							else{
								//alert('opponent = '+$("#b_opponent_id").val()+'and user = '+ui.item.user_id);
								show_div('ajax_msg');	
								$('#ajax_msg').html(ui.item.user_fname + " " + ui.item.user_lname + " is already a judge.");
								setTimeout("fade_div('ajax_msg')",3000);//fade out
							}

							return false;

						}


						/** FAILSAFE MISSING NICKNAME */
						if(!ui.item.user_nickname)
							ui.item.user_nickname = ui.item.user_fname + ' ' + ui.item.user_lname;

						$('#b_private_judge_3').val(ui.item.user_nickname);
						$('#b_private_judge_3_result_container').html("<div class='form_field_results'><div style='margin-bottom:4px;'><img src='" + ui.item.ufb_fb_profile_pic + "' alt='' style='border:1px solid #79a42d;' /></div><div style='position:absolute; top:0; left:55px; padding:5px; height:40px;'><b style='font-size:10px;'>" + ui.item.user_fname.toUpperCase() + " " + ui.item.user_lname.toUpperCase() + "</b><br /><span style='font-weight:normal; font-size:10px;'>" + ui.item.user_nickname.toUpperCase() + "</span></div><img src='"+WWW+"/images/icons/x_9_red.gif' style='position:absolute; top:5px; right:5px;' alt='' id='b_private_judge_3' onclick='autocompleteReset(\"b_private_judge_3\"); rebuildPrivateJudgeList();' /></div>");
						$('#b_private_judge_3_result_container').show();
						$('#b_private_judge_3').hide();
						$('#b_private_judge_3_id').val(ui.item.user_id);
						rebuildPrivateJudgeList();
						rebuildFilteredUsersArray();

						return false;
					}
				})
				.data( "autocomplete" )._renderItem = function( ul, item ) {
					return $( "<li style='text-align:left;'></li>" )
						.data( "item.autocomplete", item )
						.append( "<a><div style='display:inline-block;'><img src='" + item.ufb_fb_profile_pic + "' alt='' style='border:1px solid #79a42d;' /></div><div style='display:inline-block; padding:5px; line-height:15px; position:relative; vertical-align:top;'><b>" + item.user_fname.toUpperCase() + " " + item.user_lname.toUpperCase() + "</b><span style='font-weight:normal; font-size:10px; position:absolute; left:5px; top:18px;'>" + item.user_nickname.toUpperCase() + "</span></div></a>" )
						.appendTo( ul );
				};

			});

			$(function() {

				$('#b_private_judge_4').autocomplete({
					source: WWW+"/ajax.get-autocomplete-users-json.php",
					minLength: 2,
					focus: function(event, ui) {

						/** FAILSAFE MISSING NICKNAME */
						if(!ui.item.user_nickname)
							ui.item.user_nickname = ui.item.user_fname + ' ' + ui.item.user_lname;

						$('#b_private_judge_4').val(ui.item.user_nickname);
						return false;
					},
					select: function(event, ui) {

						// ENSURE JUDGE IS NOT USER
						if(ui.item.user_id == window.USER_ID){

							show_div('ajax_msg');	
							$('#ajax_msg').html("You can not judge your own battle!");
							setTimeout("fade_div('ajax_msg')",3000);//fade out

							return false;

						}

						// ENSURE JUDGE HAS JUDGE POINTS
						if(ui.item.us_judge_points < 1){

							show_div('ajax_msg');	
							$('#ajax_msg').html(ui.item.user_fname + " " + ui.item.user_lname + " has lost all his judging points from shitty judging and is not eligible to be a judge at this time!");
							setTimeout("fade_div('ajax_msg')",4000);//fade out

							return false;

						}

						// CHECK OPPONENT AGAINST JUDGE PANEL
						if(!checkAgainstFilteredUsersArray(ui.item.user_id)){

							if(ui.item.user_id == $("#b_opponent_id").val()){
								show_div('ajax_msg');	
								$('#ajax_msg').html(ui.item.user_fname + " " + ui.item.user_lname + " can not be both a judge and your opponent.");
								setTimeout("fade_div('ajax_msg')",3000);//fade out
							}
							else{
								//alert('opponent = '+$("#b_opponent_id").val()+'and user = '+ui.item.user_id);
								show_div('ajax_msg');	
								$('#ajax_msg').html(ui.item.user_fname + " " + ui.item.user_lname + " is already a judge.");
								setTimeout("fade_div('ajax_msg')",3000);//fade out
							}

							return false;

						}


						/** FAILSAFE MISSING NICKNAME */
						if(!ui.item.user_nickname)
							ui.item.user_nickname = ui.item.user_fname + ' ' + ui.item.user_lname;

						$('#b_private_judge_4').val(ui.item.user_nickname);
						$('#b_private_judge_4_result_container').html("<div class='form_field_results'><div style='margin-bottom:4px;'><img src='" + ui.item.ufb_fb_profile_pic + "' alt='' style='border:1px solid #79a42d;' /></div><div style='position:absolute; top:0; left:55px; padding:5px; height:40px;'><b style='font-size:10px;'>" + ui.item.user_fname.toUpperCase() + " " + ui.item.user_lname.toUpperCase() + "</b><br /><span style='font-weight:normal; font-size:10px;'>" + ui.item.user_nickname.toUpperCase() + "</span></div><img src='"+WWW+"/images/icons/x_9_red.gif' style='position:absolute; top:5px; right:5px;' alt='' id='b_private_judge_4' onclick='autocompleteReset(\"b_private_judge_4\"); rebuildPrivateJudgeList();' /></div>");
						$('#b_private_judge_4_result_container').show();
						$('#b_private_judge_4').hide();
						$('#b_private_judge_4_id').val(ui.item.user_id);
						rebuildPrivateJudgeList();
						rebuildFilteredUsersArray();

						return false;
					}
				})
				.data( "autocomplete" )._renderItem = function( ul, item ) {
					return $( "<li style='text-align:left;'></li>" )
						.data( "item.autocomplete", item )
						.append( "<a><div style='display:inline-block;'><img src='" + item.ufb_fb_profile_pic + "' alt='' style='border:1px solid #79a42d;' /></div><div style='display:inline-block; padding:5px; line-height:15px; position:relative; vertical-align:top;'><b>" + item.user_fname.toUpperCase() + " " + item.user_lname.toUpperCase() + "</b><span style='font-weight:normal; font-size:10px; position:absolute; left:5px; top:18px;'>" + item.user_nickname.toUpperCase() + "</span></div></a>" )
						.appendTo( ul );
				};

			});

			$(function() {

				$('#b_private_judge_5').autocomplete({
					source: WWW+"/ajax.get-autocomplete-users-json.php",
					minLength: 2,
					focus: function(event, ui) {

						/** FAILSAFE MISSING NICKNAME */
						if(!ui.item.user_nickname)
							ui.item.user_nickname = ui.item.user_fname + ' ' + ui.item.user_lname;

						$('#b_private_judge_5').val(ui.item.user_nickname);
						return false;
					},
					select: function(event, ui) {

						// ENSURE JUDGE IS NOT USER
						if(ui.item.user_id == window.USER_ID){

							show_div('ajax_msg');	
							$('#ajax_msg').html("You can not judge your own battle!");
							setTimeout("fade_div('ajax_msg')",3000);//fade out

							return false;

						}

						// ENSURE JUDGE HAS JUDGE POINTS
						if(ui.item.us_judge_points < 1){

							show_div('ajax_msg');	
							$('#ajax_msg').html(ui.item.user_fname + " " + ui.item.user_lname + " has lost all his judging points from shitty judging and is not eligible to be a judge at this time!");
							setTimeout("fade_div('ajax_msg')",4000);//fade out

							return false;

						}

						// CHECK OPPONENT AGAINST JUDGE PANEL
						if(!checkAgainstFilteredUsersArray(ui.item.user_id)){

							if(ui.item.user_id == $("#b_opponent_id").val()){
								show_div('ajax_msg');	
								$('#ajax_msg').html(ui.item.user_fname + " " + ui.item.user_lname + " can not be both a judge and your opponent.");
								setTimeout("fade_div('ajax_msg')",3000);//fade out
							}
							else{
								//alert('opponent = '+$("#b_opponent_id").val()+'and user = '+ui.item.user_id);
								show_div('ajax_msg');	
								$('#ajax_msg').html(ui.item.user_fname + " " + ui.item.user_lname + " is already a judge.");
								setTimeout("fade_div('ajax_msg')",3000);//fade out
							}

							return false;

						}


						/** FAILSAFE MISSING NICKNAME */
						if(!ui.item.user_nickname)
							ui.item.user_nickname = ui.item.user_fname + ' ' + ui.item.user_lname;

						$('#b_private_judge_5').val(ui.item.user_nickname);
						$('#b_private_judge_5_result_container').html("<div class='form_field_results'><div style='margin-bottom:4px;'><img src='" + ui.item.ufb_fb_profile_pic + "' alt='' style='border:1px solid #79a42d;' /></div><div style='position:absolute; top:0; left:55px; padding:5px; height:40px;'><b style='font-size:10px;'>" + ui.item.user_fname.toUpperCase() + " " + ui.item.user_lname.toUpperCase() + "</b><br /><span style='font-weight:normal; font-size:10px;'>" + ui.item.user_nickname.toUpperCase() + "</span></div><img src='"+WWW+"/images/icons/x_9_red.gif' style='position:absolute; top:5px; right:5px;' alt='' id='b_private_judge_5' onclick='autocompleteReset(\"b_private_judge_5\"); rebuildPrivateJudgeList();' /></div>");
						$('#b_private_judge_5_result_container').show();
						$('#b_private_judge_5').hide();
						$('#b_private_judge_5_id').val(ui.item.user_id);
						rebuildPrivateJudgeList();
						rebuildFilteredUsersArray();

						return false;
					}
				})
				.data( "autocomplete" )._renderItem = function( ul, item ) {
					return $( "<li style='text-align:left;'></li>" )
						.data( "item.autocomplete", item )
						.append( "<a><div style='display:inline-block;'><img src='" + item.ufb_fb_profile_pic + "' alt='' style='border:1px solid #79a42d;' /></div><div style='display:inline-block; padding:5px; line-height:15px; position:relative; vertical-align:top;'><b>" + item.user_fname.toUpperCase() + " " + item.user_lname.toUpperCase() + "</b><span style='font-weight:normal; font-size:10px; position:absolute; left:5px; top:18px;'>" + item.user_nickname.toUpperCase() + "</span></div></a>" )
						.appendTo( ul );
				};

			});
			
			/** WHEN USER FOCUSES THE VIDEO URL FIELD, CLEAR IT OUT */
			$("#video_url").focus(function(){

				if(document.getElementById("video_url").value == "Video URL")
					document.getElementById("video_url").value = "";

			});

			/** WHEN USER BLURS THE VIDEO URL FIELD, CHECK FOR BLANK, OR FETCH ***/
			$("#video_url").blur(function(){

				if(document.getElementById("video_url").value == "")
					document.getElementById("video_url").value = "Video URL";
				else {
					document.getElementById("video_url_field_container").style.display = 'none';
					document.getElementById("video_url_oembed_container").style.display = 'block';

					/** CREATE DOM ANCHOR DOM ELEMENT TO HOLD THE URL ************/
					var oembed_anchor = document.createElement("a");
					oembed_anchor.setAttribute("href", document.getElementById("video_url").value);
					oembed_anchor.setAttribute("id", "video_url_oembed");

					/** SHOW DIV CONTAINER AND CLEAR IT OUT **********************/
					document.getElementById("video_url_oembed_container").style.display = "block";
					document.getElementById("video_url_oembed_container").innerHTML = "";

					/** CREATE RESET LINK ****************************************/
					var reset_link = document.createElement("a");
					reset_link.setAttribute("id","video_url_reset");
					reset_link.setAttribute("href","#");
					reset_link.setAttribute("onclick","resetVideo();");
					var reset_link_text = document.createTextNode("Wrong video / no video?");
					reset_link.appendChild(reset_link_text);

					/** APPEND THE NEW NODES TO THE CONTAINER ********************/
					document.getElementById("video_url_oembed_container").appendChild(oembed_anchor);
					//document.getElementById("video_url_oembed_container").appendChild(document.createElement("br"));
					document.getElementById("video_url_oembed_container").appendChild(reset_link);
					document.getElementById("video_url_reset").style.display = "block";
					document.getElementById("video_url_reset").style.width = "100%";
					document.getElementById("video_url_reset").style.textAlign = "right";
					document.getElementById("video_url_reset").style.marginTop = "2px";

					//embedmethod:append seems to remove the title and volume, etc from vimeo
					$("#video_url_oembed").oembed(null, {
					vimeo: {color: "9cd03f", portrait: false},
					/*embedMethod: "append",*/
					maxWidth: 275
					});

				}


			});	
			
			

			/** DECLARE SELECTED TRICKS AS SORTABLE **************/
			$(document).ready(function() {
				$("#selected_tricks_sortable").sortable({

					cursor: 's-resize',
					placeholder: 'sortable-state-highlight',
					stop: function(event, ui) {

						rebuildSelectedTricksList('selected_tricks_sortable');
					}


				});
			});

			/** DECLARE LIST PLUGIN FOR JQUERY *******************/
			 $('#featured_tricks').listnav({ 
			    initLetter: 'a', 
			    includeAll: false, 
			    includeOther: false,
			    includeNums: true,
			    flagDisabled: false, 
			    noMatchText: 'No tricks found, please click another letter.', 
			    showCounts: false, 
			    cookieName: 'trick-list', 
			    //onClick: function(letter){ alert('You clicked ' + letter); }, 
			    prefixes: ['the','a'] 
			});


			/** DECLARE SELECTED TRICK TYPES AS SORTABLE *********/
			/*
			$(document).ready(function() {
				$("#selected_trick_types_sortable").sortable({

					cursor: 's-resize',
					placeholder: 'sortable-state-highlight',
					stop: function(event, ui) {

						rebuildSelectedTrickTypesList('selected_trick_types_sortable');
					}


				});
			});
			*/


		}
	});
}

/** FUNCTION LOADS MANO BATTLE AND POPULATES OPPONENT FIELD WITH SELECTED TRICKER */
function direct_challenge_mano(bo_user_id,bo_user_fname,bo_user_lname,bo_user_nickname,bo_ufb_fb_uid,bo_ufb_fb_profile_pic){

	//bo = battle opponent
	
	$('div#dashboard').slideDown('slow'); 
	$('#toggle a').toggle(); 
	load_battle_creator_mano(bo_user_id,bo_user_fname,bo_user_lname,bo_user_nickname,bo_ufb_fb_uid,bo_ufb_fb_profile_pic);
	
}

/** THIS WORKS WITH ABOVE FUNCTION - CALLED VIA THE AJAX LOAD ****************/
function preload_mano_opponent(bo_user_id,bo_user_fname,bo_user_lname,bo_user_nickname,bo_ufb_fb_uid,bo_ufb_fb_profile_pic){
	
	// UNESCAPE STRINGS
	bo_user_fname = unescape(bo_user_fname);
	bo_user_lname = unescape(bo_user_lname);
	bo_user_nickname = unescape(bo_user_nickname);
	
	// ENSURE OPPONENT IS NOT USER
	if(bo_user_id == window.USER_ID){

		show_div('ajax_msg');	
		$('#ajax_msg').html("You can not compete against yourself!");
		setTimeout("fade_div('ajax_msg')",3000);//fade out

		return false;

	}

	// CHECK OPPONENT AGAINST JUDGE PANEL
	if(!checkAgainstFilteredUsersArray(bo_user_id)){
		show_div('ajax_msg');	
		$('#ajax_msg').html(bo_user_fname + " " + bo_user_lname + " can not be both a judge and your opponent.");
		setTimeout("fade_div('ajax_msg')",3000);//fade out

		return false;

	}

	window.b_opponent_fb_uid = bo_ufb_fb_uid;

	$('#b_opponent').val(bo_user_nickname);
	$('#b_opponent_name').val(bo_user_fname + ' ' + bo_user_lname);
	$('#b_opponent_result_container').html("<div class='form_field_results'><div style='margin-bottom:4px;'><img src='" + bo_ufb_fb_profile_pic + "' alt='' style='border:1px solid #79a42d;' /></div><div style='position:absolute; top:0; left:55px; padding:5px; height:40px;'><b style='font-size:10px;'>" + bo_user_fname.toUpperCase() + " " + bo_user_lname.toUpperCase() + "</b><br /><span style='font-weight:normal; font-size:10px;'>" + bo_user_nickname.toUpperCase() + "</span></div><img src='"+WWW+"/images/icons/x_9_red.gif' style='position:absolute; top:5px; right:5px;' alt='' id='b_opponent_reset' onclick='autocompleteReset(\"b_opponent\");' /></div>");
	$('#b_opponent_result_container').show();
	$('#b_opponent').hide();
	$('#b_opponent_id').val(bo_user_id);
	rebuildFilteredUsersArray();

}

/** FUNCTION POPS DIALOGE AND GRABS NEW PASS PHRASES *************************/
function get_new_pass_phrases(){

	$.ajax({
		type: "GET",
		url: WWW+"/ajax.get-new-pass-phrases.php",
		success: function(data) {

			setTimeout("$('html').scrollTo(500,'swing')",1500);		
			$('#ajax_msg_absolute').show().html(data);
		}
	});
}

/** FUNCTION POPS DIALOGE AND LOADS TRICKER PROFILE **************************/
function get_user_profile(user_id){
	
	var dataString = 'user_id='+user_id;
	$.ajax({
		type: "GET",
		url: WWW+"/ajax.get-user-profile.php",
		data: dataString,
		success: function(data) {


			setTimeout("$('html').scrollTo(300,'swing')",500);		
			$('#ajax_msg_absolute').show().html(data);
		}
	});
}

/** FUNCTION CLOSES BATTLE ACCEPT FORM DIALOGUE ******************************/
function close_battle_accept(){

	$('#ajax_msg_absolute').hide(200);

}
function closeAjaxMsgAbsolute(){

	$('#ajax_msg_absolute').hide(200);

}

function closeAjaxMsg(){

	$('#ajax_msg').hide(200);

}

/** FUNCTION FETCHES OEMBED URL **********************************************/
function fetch_oembed_url(div_id){

	$.ajax({
		type: "GET",
		url: WWW+"/ajax.fetch_oembed_url.php",
		success: function(data) {

			$('#'+div_id).html(data);
			
		}
	});

}

/** FUNCTION PROCESSES JUDGE SCORING FOR BATTLE ******************************/
function judge_battle_submit_scores(form,b_id,bt_id,user){

	var incomplete = 0;
	var slider_count = 0;
	
	var dataString='b_id=' + b_id +
			'&b_bt_id=' + bt_id + 
			'&judge_id='+window.USER_ID;
	
	/** LOOP THRUOGH ALL SLIDER INPUTS ***********************************/
	$.each($("."+form+"-slider"),function(i,e){
		
		if(e.value.indexOf('-') == -1){
			incomplete = 1;
		}
		
		/** APPEND SLIDER INPUT ID AND VALUE TO QUERY STRING *********/
		dataString += '&' + e.id + '=' + e.value;
		
		/** COUNT SLIDER FOR JUDGE POINT *****************************/
		slider_count++;
	});
	
	if(slider_count == 1)
		var point_points = 'point';
	else
		var point_points = 'points';
		
	//alert(dataString);

	if(incomplete == 1){
	
		$('#ajax_msg').show().html('Please position ALL the sliders to the appropriate score.');
		setTimeout("fade_div('ajax_msg')",3000);
	
	}
	else {
		
		dataString += '&judge_points=' + slider_count;
		
		$.ajax({
			type: "POST",
			url: WWW+"/ajax.battle-log-score.php",
			data: dataString,
			success: function(data) {

				if(data == 'success'){

					$('#'+form+'-container').html('Thank you for judging this tricker battle! +' + slider_count + ' judging ' + point_points + ' for you!<br /><br />Please make sure you judge ALL the trickers in this battle if you haven&#039;t already.');
					$('#score_user_'+user+'_text').html('<em style="line-height:50px;  vertical-align:middle;">Scores logged, thanks for judging!</em><img src="'+WWW+'/images/icons/app/scales-check-16.png" alt="" style="vertical-align:text-bottom; margin-left:15px;" />');
				}
				else
					$('#'+form+'-container').html(data);

			} // end success

		});
	}
}


/** FUNCTION PROCESSES JUDGE SCORING FOR WIN/LOSS BATTLE *********************/
function judge_battle_winloss(form,bt_id,b_id,winner,winner_name){

	var dataString='b_id=' + b_id +
			'&b_bt_id=' + bt_id + 
			'&winner=' + winner +
			'&judge_id='+window.USER_ID;
	
	//alert(dataString);

	var r=confirm("Are you sure you want to vote for "+winner_name+"?");
	if (r==true)
	  {
	  	/** HIDE ALL SUBMIT BUTTONS FOR FAILSAFE *********************/
	  	$('.button_battle_submit_scores').hide('slow');
	  	
		$.ajax({
			type: "POST",
			url: WWW+"/ajax.battle-log-winloss.php",
			data: dataString,
			success: function(data) {

				if(data == 'success'){

					$('#'+form+'-container').html('Thank you for judging this tricker battle! +5 judging points for you! This page will automatically reload once your vote has been cast...');
					$('#score_user_'+winner+'_text').html('<em style="line-height:50px;  vertical-align:middle;">Vote logged, thanks for judging!</em><img src="'+WWW+'/images/icons/app/scales-check-16.png" alt="" style="vertical-align:text-bottom; margin-left:15px;" />');
					setTimeout("window.location.reload()",100);
				}
				else
					$('#'+form+'-container').html(data);

			} // end success

		});
	}
}


/** FUNCTION RATES A JUDGE TO AWARD JUDGE POINTS  ****************************/
function rate_judge(judge_id,contender_id,b_id,up_down,judge_name){

	var dataString='b_id=' + b_id +
			'&contender_id=' + contender_id + 
			'&up_down=' + up_down +
			'&judge_id=' + judge_id +
			'&rater_id='+window.USER_ID;
	
	//alert(dataString);
	
	if(up_down == 'down')
		var r=confirm("Are you sure you want give " + judge_name + " a thumbs down? They will be informed of your vote and also lose 10 judge points.");
	else
		var r=true;
	if (r==true)
	  {
	  	
	  	/** SUBMIT AJAX POST AND LOG JUDGE RATING ********************/
		$.ajax({
			type: "POST",
			url: WWW+"/ajax.battle-rate-judge.php",
			data: dataString,
			success: function(data) {

				if(data == 'success'){

					$('#rate_judge_'+b_id+contender_id+judge_id).html('Your thumbs ' + up_down + ' has been logged!');
				}
				else
					alert('FAIL! '+data);

			} // end success

		});
	}
}


/** FUNCTION RESETS VIDEO URL FIELD ******************************************/
function resetVideo(){

	document.getElementById("video_url_field_container").style.display = 'block';
	document.getElementById("video_url_oembed_container").style.display = 'none';
	document.getElementById("video_url_oembed_container").innerHTML = "";
	document.getElementById("video_url").value = "Video URL";

	/** CREATE DOM ANCHOR DOM ELEMENT TO HOLD THE URL ********************/
	var link = document.createElement("a");
	link.setAttribute("href", "#");
	link.setAttribute("id", "video_url_oembed");

	/** APPEND THE NEW NODE TO THE CONTAINER *****************************/
	document.getElementById("video_url_oembed_container").appendChild(link);

}

/** RESET AUTOCOMPLETE FIELD AFTER SELECTION WAS MADE ************************/
var autocompleteReset = function(e){

	$('#'+e).show();
	$('#'+e).val('');
	$('#'+e+'_id').val('');
	$('#'+e+'_result_container').hide();
	
	rebuildFilteredUsersArray();
}

/** ADD SELECTED BATTLE TRICK TO TRICKS LIST *********************************/
function addSelectedTrickToList(trick_id,trick_name){
	
		
	/** PARSE ID FROM STRING - WILL BE COMING AS 'trick_125' and we just need the 125 */
	var arr = trick_id.split("trick_");
	trick_id = arr[1];
	
	/** DEFINE LIST BOX **************************************************/
	tricks_list = document.getElementById("selected_tricks_sortable");
	var new_trick = document.createElement("li");
	new_trick.setAttribute("id",trick_id);
	new_trick.setAttribute("title",trick_name);
	
	/** DEFINE TRICK TEXT GOING INSIDE THE <li> **************************/
	var new_trick_text = document.createTextNode(trick_name);
	var new_trick_x = document.createElement("img");
	
	/** DEFINE THE X IMAGE WHICH WILL REMOVE ITEM FROM LIST **************/
	new_trick_x.setAttribute("src",WWW+"/images/icons/x_9_red.gif");
	new_trick_x.setAttribute("class","sortable_x_img");
	new_trick_x.setAttribute("onclick","this.parentNode.parentNode.removeChild(this.parentNode); rebuildSelectedTricksList('selected_tricks_sortable'); return false;");
 	
 	/** APPEND TRICK NAME AND X IMAGE TO LIST ****************************/
	new_trick.appendChild(new_trick_x);
	new_trick.appendChild(new_trick_text);
	
	/** APPEND NEW TRICK TO TRICKS LIST **********************************/
	tricks_list.appendChild(new_trick);

	/** REBUILD TRICK LIST ***********************************************/
	rebuildSelectedTricksList(tricks_list.id);
}

/** REBUILD SELECTED TRICK LIST **********************************************/
function rebuildSelectedTricksList(tricks_list){
	
	//alert('tricks_list = '+tricks_list);
	
	tricks_list = document.getElementById(tricks_list);

	var wildcard_present = false;
	
	/** GRAB HIDDEN FORM FIELD HOLDING ARRAY AND DELETE IT ***************/
	var hidden_field = document.getElementById('selected_tricks_list_hidden');
	if(hidden_field !== null)
		hidden_field.parentNode.removeChild(hidden_field);
	
	/** RECREATE HIDDEN FIELD ********************************************/
	var hidden_field = document.createElement("input");
	hidden_field.setAttribute("type","hidden");
	hidden_field.setAttribute("id","selected_tricks_list_hidden");
	hidden_field.setAttribute("name","selected_tricks_list_hidden");
	
	/** ITERATE LIST ITEMS AND POPULATE HIDDEN FIELD *********************/
	var elements = tricks_list.getElementsByTagName('li');
	var id_list = '';
	var title_list = '';
	for(var i=0; i< elements.length; i++){
		id_list += elements[i].id + ',';
		title_list += elements[i].title + ',';
		
		if(elements[i].id == wildcard_trick_id){
			wildcard_present = true;
		}
	}
	
	/** FAILSAFE WILDCARD TRICK ******************************************/
	if(wildcard_present == true){
		
		var len = elements.length;
		if(len > 1 || window.force_wildcard_trick_alert == true){
			alert('If you select the wildcard (** SEE BATTLE DESCRIPTION **), it needs to be the ONLY item in the selected tricks list,  you must choose WIN / LOSS SCORING, and you must choose TRICKS (not trick types)');

			var cell = document.getElementById('selected_tricks_sortable');

			if ( cell.hasChildNodes() )
			{
			    while ( cell.childNodes.length >= 1 )
			    {
				cell.removeChild( cell.firstChild );       
			    } 
			}

			/** RETURN OUR FLAG VARIABLE TO FALSE ****************/
			window.force_wildcard_trick_alert = false;
			
			/** ADD WILDCARD BACK TO SELECTED TRICK LIST *********/
			addSelectedTrickToList('trick_'+wildcard_trick_id,'** SEE BATTLE DESCRIPTION **');
									
		}

		/** SWITCH TRICK TYPES TO TRICKS *********************/
		$("#tricks_or_types option[value='tricks']").attr('selected', 'selected');
		$('#trick_types_container').hide(500);

		/** SWITCH SCORING METHOD TO WIN / LOSS **************/
		$("#b_bsm_id option[value='3']").attr('selected', 'selected');

	}
	
	//alert('list = '+id_list);
	/** UPDATE CAPTION ***************************************************/
	var caption = document.getElementById('selected_featured_tricks_caption');
	switch(elements.length){
	
		case 0:
			window.battle_trick_or_combo = '';
			caption.innerHTML = '* Awaiting trick selection...';
			break;
		
		case 1:
			window.battle_trick_or_combo = 'trick';
			caption.innerHTML = '* Battling this trick:';
			break;
		
		default:
			window.battle_trick_or_combo = 'combo';
			caption.innerHTML = '* Battling this combo (drag tricks to change order):';
			break;
			
	}		
	
	/** TRIM COMMAS FROM LIST ********************************************/
	var id_list = id_list.replace(/(^,)|(,$)/g, "")
	var title_list = title_list.replace(/(^,)|(,$)/g, "")
	
	/** GLOBALIZE TRICK NAMES LIST FOR FACEBOOK STREAM PUBLISH ***********/
	window.battle_trick_names = title_list;

	/** ADD NEWLY CREATED LIST TO HIDDEN FIELD VALUE *********************/
	hidden_field.setAttribute("value",id_list);
	
	/** APPEND HIDDEN FIELD TO FORM **************************************/
	document.getElementById('form').appendChild(hidden_field);
	
	//alert(window.battle_trick_names);
	//alert(title_list);
	//alert(id_list);
}

/** ADD SELECTED BATTLE TRICK TYPE TO TRICK TYPES LIST ***********************/
function addSelectedTrickTypeToList(trick_type_id,trick_type_name){
	
	//alert('id='+trick_type_id+' -- name='+trick_type_name);
		
	/** PARSE ID FROM STRING - WILL BE COMING AS 'trick_125' and we just need the 125 */
	var arr = trick_type_id.split("trick_type_");
	trick_type_id = arr[1];
	
	/** DEFINE LIST BOX **************************************************/
	trick_types_list = document.getElementById("selected_trick_types_sortable");
	var new_trick_type = document.createElement("li");
	new_trick_type.setAttribute("id",trick_type_id);
	new_trick_type.setAttribute("title",trick_type_name);
	
	/** DEFINE TRICK TYPE TEXT GOING INSIDE THE <li> *********************/
	var new_trick_type_text = document.createTextNode(trick_type_name);
	var new_trick_type_x = document.createElement("img");
	
	/** DEFINE THE X IMAGE WHICH WILL REMOVE ITEM FROM LIST **************/
	new_trick_type_x.setAttribute("src",WWW+"/images/icons/x_9_red.gif");
	new_trick_type_x.setAttribute("class","sortable_x_img");
	new_trick_type_x.setAttribute("onclick","this.parentNode.parentNode.removeChild(this.parentNode); rebuildSelectedTrickTypesList('selected_trick_types_sortable'); return false;");
 	
 	/** APPEND TRICK NAME AND X IMAGE TO LIST ****************************/
	new_trick_type.appendChild(new_trick_type_x);
	new_trick_type.appendChild(new_trick_type_text);
	
	/** APPEND NEW TRICK TO TRICKS LIST **********************************/
	trick_types_list.appendChild(new_trick_type);

	/** REBUILD TRICK LIST ***********************************************/
	rebuildSelectedTrickTypesList(trick_types_list.id);
}

/** REBUILD SELECTED TRICK TYPES LIST ****************************************/
function rebuildSelectedTrickTypesList(trick_types_list){
	
	//alert('trick_types_list = '+trick_types_list);
	
	trick_types_list = document.getElementById(trick_types_list);
	
	//alert('trick_types_list = '+trick_types_list);
	
	/** GRAB HIDDEN FORM FIELD HOLDING ARRAY AND DELETE IT ***************/
	var hidden_field = document.getElementById('selected_trick_types_list_hidden');
	hidden_field.parentNode.removeChild(hidden_field);
	
	/** RECREATE HIDDEN FIELD ********************************************/
	var hidden_field = document.createElement("input");
	hidden_field.setAttribute("type","hidden");
	hidden_field.setAttribute("id","selected_trick_types_list_hidden");
	hidden_field.setAttribute("name","selected_trick_types_list_hidden");
	
	/** ITERATE LIST ITEMS AND POPULATE HIDDEN FIELD *********************/
	var elements = trick_types_list.getElementsByTagName('li');
	var id_list = '';
	var title_list = '';
	for(var i=0; i< elements.length; i++){
		id_list += elements[i].id + ',';
		title_list += elements[i].title + ',';
	}
	
	/** UPDATE CAPTION ***************************************************/
	var caption = document.getElementById('selected_featured_trick_types_caption');
	switch(elements.length){
	
		case 0:
			window.battle_trick_or_combo = '';
			caption.innerHTML = '* Awaiting trick type selection...';
			break;
		
		case 1:
			window.battle_trick_or_combo = 'trick';
			caption.innerHTML = '* This trick type should match your selected trick:';
			break;
		
		default:
			window.battle_trick_or_combo = 'combo';
			caption.innerHTML = '* These trick types should match your selected tricks:';
			break;
			
	}		
	
	/** TRIM COMMAS FROM LIST ********************************************/
	var id_list = id_list.replace(/(^,)|(,$)/g, "")
	var title_list = title_list.replace(/(^,)|(,$)/g, "")

	/** GLOBALIZE TRICK TYPES LIST FOR FACEBOOK STREAM PUBLISH ***********/
	window.battle_trick_type_names = title_list;

	/** ADD NEWLY CREATED LIST TO HIDDEN FIELD VALUE *********************/
	hidden_field.setAttribute("value",id_list);
	
	/** APPEND HIDDEN FIELD TO FORM **************************************/
	document.getElementById('form').appendChild(hidden_field);
	
	//alert(hidden_field.value);

}

/** REBUILD FILTERED USERS ARRAY *********************************************/
function rebuildFilteredUsersArray(){

	var user_list = window.USER_ID;
	
	user_list += ',' + $("#b_private_judges_hidden").val();
	user_list += ',' + $("#b_opponent_id").val();
	
	/** TRIM COMMAS FROM LIST ********************************************/
	var user_list = user_list.replace(/(^,)|(,$)/g, "")

	window.filteredUsersArray = user_list.split(',');
	window.filteredUsers = user_list;
	
	//alert(user_list);
		
}

/** RESET FILTERED USERS ARRAY (BUG FIX FOR UNFINISHED BATTLE CREATIONS WHEN 
YOU CLOSE THE DASHBOARD AND RETURN *******************************************/
function resetFilteredUsersArray(){

	var user_list = window.USER_ID;
	
	window.filteredUsersArray = user_list.split(',');
	window.filteredUsers = user_list;
			
}

/** CHECKS PROVIDED USER AGAINST FILTERED USERS (OPPONENT, JUDGES, ETC) ******/
function checkAgainstFilteredUsersArray(user){
			
	for(var i=0; i< window.filteredUsersArray.length; i++){
		if(window.filteredUsersArray[i] == user)
			return false;
	}
	
	return true;

}

/** REBUILD PRIVATE JUDGING PANEL ********************************************/
function rebuildPrivateJudgeList(){
	
	
	/** GRAB HIDDEN FORM FIELD HOLDING ARRAY AND DELETE IT ***************/
	var hidden_field = document.getElementById('b_private_judges_hidden');
	hidden_field.parentNode.removeChild(hidden_field);
	
	/** RECREATE HIDDEN FIELD ********************************************/
	var hidden_field = document.createElement("input");
	hidden_field.setAttribute("type","hidden");
	hidden_field.setAttribute("id","b_private_judges_hidden");
	hidden_field.setAttribute("name","b_private_judges_hidden");
	
	/** ITERATE LIST ITEMS AND POPULATE HIDDEN FIELD *********************/
	var elements = document.getElementsByClassName('private_judge');
	var id_list = '';
	for(var i=0; i< elements.length; i++){
		if(elements[i].value)
			id_list += elements[i].value + ',';
	}
	
	/** TRIM COMMAS FROM LIST ********************************************/
	var id_list = id_list.replace(/(^,)|(,$)/g, "")

	/** ADD NEWLY CREATED LIST TO HIDDEN FIELD VALUE *********************/
	hidden_field.setAttribute("value",id_list);
	
	/** APPEND HIDDEN FIELD TO FORM **************************************/
	document.getElementById('form').appendChild(hidden_field);
	
	rebuildFilteredUsersArray();

}

/** REBUILD PRIVATE OPPONENT PANEL *******************************************/
function rebuildPrivateOpponentList(){
	
	
	/** GRAB HIDDEN FORM FIELD HOLDING ARRAY AND DELETE IT ***************/
	var hidden_field = document.getElementById('b_private_opponents_hidden');
	hidden_field.parentNode.removeChild(hidden_field);
	
	/** RECREATE HIDDEN FIELD ********************************************/
	var hidden_field = document.createElement("input");
	hidden_field.setAttribute("type","hidden");
	hidden_field.setAttribute("id","b_private_opponents_hidden");
	hidden_field.setAttribute("name","b_private_opponents_hidden");
	
	/** ITERATE LIST ITEMS AND POPULATE HIDDEN FIELD *********************/
	var elements = document.getElementsByClassName('private_opponent');
	var id_list = '';
	for(var i=0; i< elements.length; i++){
		if(elements[i].value)
			id_list += elements[i].value + ',';
	}
	
	/** TRIM COMMAS FROM LIST ********************************************/
	var id_list = id_list.replace(/(^,)|(,$)/g, "")

	/** ADD NEWLY CREATED LIST TO HIDDEN FIELD VALUE *********************/
	hidden_field.setAttribute("value",id_list);
	
	/** APPEND HIDDEN FIELD TO FORM **************************************/
	document.getElementById('form').appendChild(hidden_field);
	
	rebuildFilteredUsersArray();

}


/*
*
* jQuery listnav plugin (USED FOR TRICK SELECTION)
* Copyright (c) 2009 iHwy, Inc.
* Author: Jack Killpatrick
*
* Version 2.1 (08/09/2009)
* Requires jQuery 1.3.2, jquery 1.2.6 or jquery 1.2.x plus the jquery dimensions plugin
*
* Visit http://www.ihwy.com/labs/jquery-listnav-plugin.aspx for more information.
*
* Dual licensed under the MIT and GPL licenses:
*   http://www.opensource.org/licenses/mit-license.php
*   http://www.gnu.org/licenses/gpl.html
*
*/

(function($) {
	$.fn.listnav = function(options) {
		var opts = $.extend({}, $.fn.listnav.defaults, options);
		var letters = ['_', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '-'];
		var firstClick = false;
		opts.prefixes = $.map(opts.prefixes, function(n) { return n.toLowerCase(); });

		return this.each(function() {
			var $wrapper, list, $list, $letters, $letterCount, id;
			id = this.id;
			$wrapper = $('#' + id + '-nav'); // user must abide by the convention: <ul id="myList"> for list and <div id="myList-nav"> for nav wrapper
			$list = $(this);

			var counts = {}, allCount = 0, isAll = true, numCount = 0, prevLetter = '';

			function init() {
				$wrapper.append(createLettersHtml());

				$letters = $('.ln-letters', $wrapper).slice(0, 1); // will always be a single item
				if (opts.showCounts) $letterCount = $('.ln-letter-count', $wrapper).slice(0, 1); // will always be a single item

				addClasses();
				addNoMatchLI();
				if (opts.flagDisabled) addDisabledClass();
				bindHandlers();

				if (!opts.includeAll) $list.show(); // show the list in case the recommendation for includeAll=false was taken

				// remove nav items we don't need
				//
				if (!opts.includeAll) $('.all', $letters).remove();
				if (!opts.includeNums) $('._', $letters).remove();
				if (!opts.includeOther) $('.-', $letters).remove();

				$(':last', $letters).addClass('ln-last'); // allows for styling a case where last item needs right border set (because items before that only have top, left and bottom so that border between items isn't doubled)
				
				if ($.cookie && (opts.cookieName != null)) {
					var cookieLetter = $.cookie(opts.cookieName);
					if (cookieLetter != null) opts.initLetter = cookieLetter;
				}

				// decide what to show first
				//
				if (opts.initLetter != '') {
					firstClick = true;
					$('.' + opts.initLetter.toLowerCase(), $letters).slice(0, 1).click(); // click the initLetter if there was one
				}
				else {
					if (opts.includeAll) $('.all', $letters).addClass('ln-selected'); // showing all: we don't need to click this: the whole list is already loaded
					else { // ALL link is hidden, click the first letter that will display LI's
						for (var i = ((opts.includeNums) ? 0 : 1); i < letters.length; i++) {
							if (counts[letters[i]] > 0) {
								firstClick = true;
								$('.' + letters[i], $letters).slice(0, 1).click();
								break;
							}
						}
					}
				}
			}

			// positions the letter count div above the letter links (so we only have to do it once: after this we just change it's left position via mouseover)
			//
			function setLetterCountTop() {
				$letterCount.css({ top: $('.a', $letters).slice(0, 1).offset({ margin: false, border: true }).top - $letterCount.outerHeight({ margin: true }) }); // note: don't set top based on '.all': it might not be visible
			}

			// adds a class to each LI that has text content inside of it (ie, inside an <a>, a <div>, nested DOM nodes, etc)
			//
			function addClasses() {
				var str, firstChar, firstWord, spl, $this, hasPrefixes = (opts.prefixes.length > 0);
				$($list).children().each(function() {
					$this = $(this), firstChar = '', str = $.trim($this.text()).toLowerCase();
					if (str != '') {
						if (hasPrefixes) {
							spl = str.split(' ');
							if ((spl.length > 1) && ($.inArray(spl[0], opts.prefixes) > -1)) {
								firstChar = spl[1].charAt(0);
								addLetterClass(firstChar, $this, true);
							}
						}
						firstChar = str.charAt(0);
						addLetterClass(firstChar, $this);
					}
				});
			}

			function addLetterClass(firstChar, $el, isPrefix) {
				if (/\W/.test(firstChar)) firstChar = '-'; // not A-Z, a-z or 0-9, so considered "other"
				if (!isNaN(firstChar)) firstChar = '_'; // use '_' if the first char is a number
				$el.addClass('ln-' + firstChar);

				if (counts[firstChar] == undefined) counts[firstChar] = 0;
				counts[firstChar]++;
				if (!isPrefix) allCount++;
			}

			function addDisabledClass() {
				for (var i = 0; i < letters.length; i++) {
					if (counts[letters[i]] == undefined) $('.' + letters[i], $letters).addClass('ln-disabled');
				}
			}

			function addNoMatchLI() {
				$list.append('<li class="ln-no-match" style="display:none">' + opts.noMatchText + '</li>');
			}

			function getLetterCount(el) {
				if ($(el).hasClass('all')) return allCount;
				else {
					var count = counts[$(el).attr('class').split(' ')[0]];
					return (count != undefined) ? count : 0; // some letters may not have a count in the hash
				}
			}

			function bindHandlers() {

				// sets the top position of the count div in case something above it on the page has resized
				//
				if (opts.showCounts) {
					$wrapper.mouseover(function() {
						setLetterCountTop();
					});
				}

				// mouseover for each letter: shows the count above the letter
				//
				if (opts.showCounts) {
					$('a', $letters).mouseover(function() {
						var left = $(this).position().left;
						var width = ($(this).outerWidth({ margin: true }) - 1) + 'px'; // the -1 is to tweak the width a bit due to a seeming inaccuracy in jquery ui/dimensions outerWidth (same result in FF2 and IE6/7)
						var count = getLetterCount(this);
						$letterCount.css({ left: left, width: width }).text(count).show(); // set left position and width of letter count, set count text and show it
					});

					// mouseout for each letter: hide the count
					//
					$('a', $letters).mouseout(function() {
						$letterCount.hide();
					});
				}

				// click handler for letters: shows/hides relevant LI's
				//
				$('a', $letters).click(function() {
					$('a.ln-selected', $letters).removeClass('ln-selected');

					var letter = $(this).attr('class').split(' ')[0];

					if (letter == 'all') {
						$list.children().show();
						$list.children('.ln-no-match').hide();
						isAll = true;
					} else {
						if (isAll) {
							$list.children().hide();
							isAll = false;
						} else if (prevLetter != '') $list.children('.ln-' + prevLetter).hide();

						var count = getLetterCount(this);
						if (count > 0) {
							$list.children('.ln-no-match').hide(); // in case it's showing
							$list.children('.ln-' + letter).show();
						}
						else $list.children('.ln-no-match').show();

						prevLetter = letter;
					}

					if ($.cookie && (opts.cookieName != null)) $.cookie(opts.cookieName, letter);


					$(this).addClass('ln-selected');
					$(this).blur();
					if (!firstClick && (opts.onClick != null)) opts.onClick(letter);
					else firstClick = false;
					return false;
				});
			}

			// creates the HTML for the letter links
			//	
			function createLettersHtml() {
				var html = [];
				for (var i = 1; i < letters.length; i++) {
					if (html.length == 0) html.push('<a class="all" href="#">ALL</a><a class="_" href="#">0-9</a>');
					html.push('<a class="' + letters[i] + '" href="#">' + ((letters[i] == '-') ? '...' : letters[i].toUpperCase()) + '</a>');
				}
				return '<div class="ln-letters">' + html.join('') + '</div>' + ((opts.showCounts) ? '<div class="ln-letter-count" style="display:none; position:absolute; top:0; left:0; width:20px;">0</div>' : ''); // the styling for ln-letter-count is to give us a starting point for the element, which will be repositioned when made visible (ie, should not need to be styled by the user)
			}

			init();
		});
	};

	$.fn.listnav.defaults = {
		initLetter: '',
		includeAll: true,
		incudeOther: false,
		includeNums: true,
		flagDisabled: true,
		noMatchText: 'No matching entries',
		showCounts: true,
		cookieName: null,
		onClick: null,
		prefixes: []
	};
})(jQuery);




/** TOOL TIPS ****************************************************************/
this.sliderTooltip = function(e,v){

	/* CONFIG */		
		xOffset = 60;
		yOffset = -20;		
		// these 2 variable determine popup's distance from the cursor
		// you might want to adjust to get the right result		
	/* END CONFIG */
									  
	$("body").append("<p id='slidertooltip'>"+ v +"</p>");
	$("#slidertooltip")
		.css("top",(e.pageY - xOffset) + "px")
		.css("left",(e.pageX + yOffset) + "px")
		.fadeIn("fast");		
	
			
};

this.tooltip = function(){

	/* CONFIG */		
		xOffset = 10;
		yOffset = 20;		
		// these 2 variable determine popup's distance from the cursor
		// you might want to adjust to get the right result		
	/* END CONFIG */
	
	/** REGULAR ANCHOR TOOL TIPS WITH i ICON **/
	$("a.tooltip").hover(function(e){											  
		this.t = this.title;
		this.title = "";									  
		$("body").append("<p id='tooltip'>"+ this.t +"</p>");
		$("#tooltip")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px")
			.fadeIn("fast");		
	},
	function(){
		this.title = this.t;		
		$("#tooltip").remove();
	});
	
	$("a.tooltip").mousemove(function(e){
		$("#tooltip")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px");
	});
	
};



// starting the script on page load
$(document).ready(function(){
	tooltip();
});


/*
 * Url preview script 
 * powered by jQuery (http://www.jquery.com)
 * 
 * written by Alen Grakalic (http://cssglobe.com)
 * 
 * for more info visit http://cssglobe.com/post/1695/easiest-tooltip-and-image-preview-using-jquery
 *
 */
 
this.imgtooltip = function(){	
	/* CONFIG */
		
		xOffset = 10;
		yOffset = 30;
		
		// these 2 variable determine popup's distance from the cursor
		// you might want to adjust to get the right result
		
	/* END CONFIG */
	$("a.imgtooltip").hover(function(e){
		this.t = this.title;
		this.title = "";	
		var c = (this.t != "") ? "<br/>" + this.t : "";
		$("body").append("<p id='imgtooltip'><img src='"+ this.rel +"' alt='No Photo' />"+ c +"</p>");								 
		$("#imgtooltip")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px")
			.fadeIn("fast");						
	},
	function(){
		this.title = this.t;	
		$("#imgtooltip").remove();
	});	
	$("a.screenshot").mousemove(function(e){
		$("#imgtooltip")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px");
	});			
};

// starting the script on page load
$(document).ready(function(){
	imgtooltip();
});












/*
 * Metadata - jQuery plugin for parsing metadata from elements
 *
 * Copyright (c) 2006 John Resig, Yehuda Katz, J?örn Zaefferer, Paul McLanahan
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * Revision: $Id: jquery.metadata.js 4187 2007-12-16 17:15:27Z joern.zaefferer $
 *
 */

/**
 * Sets the type of metadata to use. Metadata is encoded in JSON, and each property
 * in the JSON will become a property of the element itself.
 *
 * There are three supported types of metadata storage:
 *
 *   attr:  Inside an attribute. The name parameter indicates *which* attribute.
 *          
 *   class: Inside the class attribute, wrapped in curly braces: { }
 *   
 *   elem:  Inside a child element (e.g. a script tag). The
 *          name parameter indicates *which* element.
 *          
 * The metadata for an element is loaded the first time the element is accessed via jQuery.
 *
 * As a result, you can define the metadata type, use $(expr) to load the metadata into the elements
 * matched by expr, then redefine the metadata type and run another $(expr) for other elements.
 * 
 * @name $.metadata.setType
 *
 * @example <p id="one" class="some_class {item_id: 1, item_label: 'Label'}">This is a p</p>
 * @before $.metadata.setType("class")
 * @after $("#one").metadata().item_id == 1; $("#one").metadata().item_label == "Label"
 * @desc Reads metadata from the class attribute
 * 
 * @example <p id="one" class="some_class" data="{item_id: 1, item_label: 'Label'}">This is a p</p>
 * @before $.metadata.setType("attr", "data")
 * @after $("#one").metadata().item_id == 1; $("#one").metadata().item_label == "Label"
 * @desc Reads metadata from a "data" attribute
 * 
 * @example <p id="one" class="some_class"><script>{item_id: 1, item_label: 'Label'}</script>This is a p</p>
 * @before $.metadata.setType("elem", "script")
 * @after $("#one").metadata().item_id == 1; $("#one").metadata().item_label == "Label"
 * @desc Reads metadata from a nested script element
 * 
 * @param String type The encoding type
 * @param String name The name of the attribute to be used to get metadata (optional)
 * @cat Plugins/Metadata
 * @descr Sets the type of encoding to be used when loading metadata for the first time
 * @type undefined
 * @see metadata()
 */

(function($) {

$.extend({
	metadata : {
		defaults : {
			type: 'class',
			name: 'metadata',
			cre: /({.*})/,
			single: 'metadata'
		},
		setType: function( type, name ){
			this.defaults.type = type;
			this.defaults.name = name;
		},
		get: function( elem, opts ){
			var settings = $.extend({},this.defaults,opts);
			// check for empty string in single property
			if ( !settings.single.length ) settings.single = 'metadata';
			
			var data = $.data(elem, settings.single);
			// returned cached data if it already exists
			if ( data ) return data;
			
			data = "{}";
			
			if ( settings.type == "class" ) {
				var m = settings.cre.exec( elem.className );
				if ( m )
					data = m[1];
			} else if ( settings.type == "elem" ) {
				if( !elem.getElementsByTagName )
					return undefined;
				var e = elem.getElementsByTagName(settings.name);
				if ( e.length )
					data = $.trim(e[0].innerHTML);
			} else if ( elem.getAttribute != undefined ) {
				var attr = elem.getAttribute( settings.name );
				if ( attr )
					data = attr;
			}
			
			if ( data.indexOf( '{' ) <0 )
			data = "{" + data + "}";
			
			data = eval("(" + data + ")");
			
			$.data( elem, settings.single, data );
			return data;
		}
	}
});

/**
 * Returns the metadata object for the first member of the jQuery object.
 *
 * @name metadata
 * @descr Returns element's metadata object
 * @param Object opts An object contianing settings to override the defaults
 * @type jQuery
 * @cat Plugins/Metadata
 */
$.fn.metadata = function( opts ){
	return $.metadata.get( this[0], opts );
};

})(jQuery);

