$j = jQuery.noConflict(); // for prototype (or mootools or whatever) conflicts

facebookReady = 0; // initializing nice little global variable.  this is set to 1 (in /fbstuff) when facebook user is logged in & api is ready

// bust out of iframe (important for facebook apps...
/*
if (top.location != self.location) 
	{
	top.location = self.location.href
	}
*/

try{ console.clear(); } catch(e) {} // clears the IE debug console

function setCookie(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 getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
  x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
  y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
  x=x.replace(/^\s+|\s+$/g,"");
  if (x==c_name)
    {
    return unescape(y);
    }
  }
}

function deleteUser(username)
	{
	var isConfirmed = confirm('Delete user. Are you sure?');
	if (isConfirmed)
		{
		var isConfirmed = confirm('Are you really sure?');
		if (isConfirmed)
			{
			$j.get('/api/deleteUser/?username=' + username, function(response)
				{
				alert(response);
				});			
			}
		}
	else
		{
		return false;
		}
	}
	
function his(gender)
	{
	if (gender == 'male')
		{
		return 'his';
		}
	else if (gender == 'female')
		{
		return 'her';
		}
	else
		{
		return 'their';
		}

	}

function urldecode(str) {
   return decodeURIComponent((str+'').replace(/\+/g, '%20'));
}

function getUrlVars()
{
    var rock = new Object();
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
    	rock[hash[0]] = urldecode(hash[1]);
    }
    return rock;
}

function postNewProfileToWall()
	{
	fbWallDialog(me.fb_id, "","My new musician profile", me.name + ', ' + me.headline,"http://fandalism.com/" + me.username, "http://fandalism.com/images/logo-square-red-pattern.png", "Fandalism.com is the world's largest directory of good musicians");
	}
		
function showAwesomeArrow(arrowID) // make sure you set the DIV top/left attributes in /add/addDropdown
{
if (!$j('#' + arrowID).is(':visible'))
	{
	$j('#' + arrowID).height('+=200');
	$j('#' + arrowID).width('+=200');
	$j('#' + arrowID).offset({top:-100, left:-100});
	$j('#' + arrowID).show();
	debug($j('#' + arrowID).children());
	$j('#' + arrowID).children().animate(
		{
		height: '30',
		width: '96',
		top: '0',
		left: '0'
		},200)
		
	$j('#' + arrowID).animate(
		{
		height: '30',
		width: '96',
		top: '0',
		left: '0'
		},200,function()
			{
			$j('#' + arrowID).effect("shake", { distance: 5, times:3, direction:'up'}, 200);
			});
	}
else
	{
	$j('#' + arrowID).stop(true, true);
	$j('#' + arrowID).hide();
	}
}

function approveMember(username) // note to haxors: this only works if you're a slave or overlord
	{
	var originalHTML = $j('#userMembershipLevel').html();
	$j('#userMembershipLevel').html('<span class="label">Wait...</span>');
	$j.get('/api/approveMember/?username=' + username, function(data) 
		{
		if (data.SUCCESS)
			{
			$j('#userMembershipLevel').html('<span class="label success">Member</span>');
			}
		else
			{
			$j('#userMembershipLevel').html(originalHTML);
			alert('Oops, there was an error approving this user. Please let the Overlord know.');
			}
		},'JSON');
	}

function rejectAudition(username, contentid) // note to haxors: this only works if you're a slave or overlord
	{
	var answer = confirm("Are you sure you want to reject this audition?")
	if (answer)
		{
		var originalHTML = $j('#userMembershipLevel').html();
		$j.get('/api/rejectAudition/?username=' + username + '&contentid=' + contentid, function(data) 
			{
			if (data.SUCCESS)
				{
				$j('#rejectAuditionLink').replaceWith('removed');
				}
			else
				{
				alert('Oops, there was an error deleting this. Please let the Overlord know.');
				}
			},'JSON');
		}
	}

function queryToObject(queryJSON) // give me a serializejson query and i'll give you a nice js object
	{
	if (queryJSON.DATA.length == 1)
		{
		var newObject = new Object();
		for (var x = 0; x < queryJSON.COLUMNS.length; x++)
			{
			newObject[queryJSON.COLUMNS[x].toLowerCase()] = queryJSON.DATA[0][x];
			}
		return newObject;
		}
	else if (queryJSON.DATA.length > 1) // did this kinda ugly because i needed backwards compatibility (queries with 1 row don't want to be in an array 
		{
		var newArray = new Array();
		for (y = 0; y < queryJSON.DATA.length; y++)
			{
			var newObject = new Object();
			for (x = 0; x < queryJSON.COLUMNS.length; x++)
				{
				newObject[queryJSON.COLUMNS[x].toLowerCase()] = queryJSON.DATA[y][x];
				// debug(newObject[queryJSON.COLUMNS[x].toLowerCase()]);
				}
			newArray.push(newObject);
			}
		return newArray;
		}
	}

function postComment(contentid,comment)
	{
	if (comment != '')
		{
		$j(document).trigger('newCommentSpinner', [comment]);
		$j.post('/api/postNewComment/',
			{
			contentid: contentid,
			comment: comment
			},function(response)
				{
				debug('comment posted');
				debug(response);
				$j(document).trigger('newComment', [comment]);
				});
		}
	}

function getViewportSize()
	{
	viewport=new Object();
	
	// the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
	
	if (typeof window.innerWidth != 'undefined')
	{
	  viewport.width = window.innerWidth,
	  viewport.height = window.innerHeight
	}
	
	// IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
	
	else if (typeof document.documentElement != 'undefined'
	 && typeof document.documentElement.clientWidth !=
	 'undefined' && document.documentElement.clientWidth != 0)
	{
	   viewport.width = document.documentElement.clientWidth,
	   viewport.height = document.documentElement.clientHeight
	}
	
	// older versions of IE
	
	else
	{
	   viewport.width = document.getElementsByTagName('body')[0].clientWidth,
	   viewport.height = document.getElementsByTagName('body')[0].clientHeight
	}
	return viewport
	}
	

function preload(image) { 
	var pic1= new Image(); 
	pic1.src = image;
}

function fbLike(objectid)
	{
		var params = {};
		// params['message'] = message;

		FB.api('/' + objectid + '/comments', 'post', params, function(response) {
		  if (!response || response.error) {
		    // alert('Error occured');
		    debug('Error liking object');
		    s(response);
		  } else {
		  	debug(response);
		    // alert('Published to stream - you might want to delete it now!');
		  }
		});
	}

function addInfluence(influence)
	{
	$j.get('/api/addUserInfluence/?influence=' + influence);
	}


function createWallCopy()
	{
	debug(content);
	var createWallCopy = new Object();
	createWallCopy.type = 'something';
	if (content.type == 'youtube')
		{
		createWallCopy.type = 'a video';
		}
	else if (content.type == 'soundclound')
		{
		createWallCopy.type = 'a song';
		}
	else if (content.type == 'lyrics')
		{
		createWallCopy.type = 'some lyrics';
		}
	else if (content.type == 'photo')
		{
		createWallCopy.type = 'a pic';
		}
	content.instrumentlist = content.instrumentlist + ''; // make sure this is converted to a string (why it'd be anything else, i've no idea)
	createWallCopy.title = titleCase(content.instrumentlist.replace(/\,/gi, ", ")) + ' by ' + titleCase(user.name);
	createWallCopy.thumbnail = content.thumbnail; // http://pics.fandalism.com/267x267-equalizer.jpg
	if (content.thumbnailspecial != '')
		{
		createWallCopy.thumbnail =  'http:' + application.s3picsurl + '/267x267-' + content.thumbnailspecial;
		}
	createWallCopy.thumbnail = toBase64(createWallCopy.thumbnail);
	createWallCopy.thumbnail = 'http://fandalism.com/play/' + createWallCopy.thumbnail + '.png';
	return createWallCopy;
	}

function makePlayThumb(thumbLowPriority, thumbHighPriority)
	{
	if ((thumbHighPriority != null) && (thumbHighPriority != ''))
		{
		var thumbnail = 'http:' + application.s3picsurl + '/267x267-' + thumbHighPriority;
		}
	else
		{
		var thumbnail = thumbLowPriority;
		}
	var thumbnail = toBase64(thumbnail);
	var thumbnail = 'http://fandalism.com/play/' + thumbnail + '.png';
	return thumbnail;
	}

function fbPostToWall(message,name,description,link,picture,caption)
	{
		debug('/header.js/fbPostToWall()');
		var params = {};
		params['message'] = message;
		params['name'] = name;
		params['description'] = description;
		params['link'] = link;
		params['picture'] = picture;
		params['caption'] = caption;


		$j(document).bind('okayPostToWallNow',function()
			{
			$j(document).unbind('okayPostToWallNow');
			debug('I AM POSTING TO YER WALLS');
			debug(params);
			FB.api('/me/feed?access_token=' + me.fb_accesstoken, 'post', params, function(response) {
			  if (!response || response.error) {
			    // alert('Error occured');
			    debug('Error posting to wall');
			    debug(response);
			  } else {
			  	debug(response);
			    // alert('Published to stream - you might want to delete it now!');
			  }
			});
			})
		// debug('auth response:');
		// debug(FB.getAuthResponse());
		if (FB.getAuthResponse() || (typeof me.fb_accesstoken != 'undefined')) 
			{
			$j(document).trigger('okayPostToWallNow');
			}
		else
			{
			login(''); // a blank param means "do not forward anywhere after logging in"
			FB.Event.subscribe('auth.login', function(response) {
				debug('okayPostToWallNow');
				$j(document).trigger('okayPostToWallNow');
			});
			}
	}


function fbPostToFriendsWall(to,message,name,description,link,picture,caption)
	{
		debug('PTFW ' + to);
		var params = {};
		params['message'] = message;
		params['name'] = name;
		params['description'] = description;
		params['link'] = link;
		params['picture'] = picture;
		params['caption'] = caption;


		$j(document).bind('okayPostToWallNow',function()
			{
			$j(document).unbind('okayPostToWallNow');
			debug('PTFW1');
			// debug(params);
			FB.api('/' + to + '/feed?access_token=' + me.fb_accesstoken, 'post', params, function(response) {
			  if (!response || response.error) {
			    // alert('Error occured');
			    debug('PTFW0');
			    // debug(response);
			  } else {
			  	// debug(response);
			  }
			});
			})
		// debug('auth response:');
		// debug(FB.getAuthResponse());
		if (FB.getAuthResponse() || (typeof me.fb_accesstoken != 'undefined')) 
			{
			$j(document).trigger('okayPostToWallNow');
			}
		else
			{
			login(''); // a blank param means "do not forward anywhere after logging in"
			FB.Event.subscribe('auth.login', function(response) {
				debug('okayPostToWallNow');
				$j(document).trigger('okayPostToWallNow');
			});
			}
	}

function fbWallDialog(message,name,description,link,picture,caption) {

        // calling the API ...
        var obj = {
          method: 'feed',
          link: link,
          picture: picture,
          name: name,
          caption: caption,
          description: description
        };

        function callback(response) {
          debug(response);
          // document.getElementById('msg').innerHTML = "Post ID: " + response['post_id'];
        }

        FB.ui(obj, callback);
      }

function numberFormat(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

function uuid() {
    var S4 = function() {
       return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
    };
    return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
}

function getParameterByName(url, name)
{
  name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
  var regexS = "[\\?&]" + name + "=([^&#]*)";
  var regex = new RegExp(regexS);
  var results = regex.exec(url);
  if(results == null)
    return "";
  else
    return decodeURIComponent(results[1].replace(/\+/g, " "));
}

function debug(str)
	{
	if (typeof console != 'undefined') { console.log(str); }
	}
				
var getKeys = function(obj){
   var keys = [];
   for(var key in obj){
      keys.push(key);
   }
   return keys;
}

// global var that helps take care of "influences" interface
allArtistsOnPageArray = new Array();
function addToAllArtistsOnPageArray(artistName)
	{
	allArtistsOnPageArray.push(artistName);	
	}
function removeFromAllArtistsOnPageArray(artistName)
	{
	var x = allArtistsOnPageArray.indexOf(artistName); // Find the index
	if(x!=-1) allArtistsOnPageArray.splice(x, 1); // Remove it if really found!
	}

function clean(str)
	{
	return str.replace(/[^a-zA-Z0-9]+/g,'');
	}

			
function logmeout()
{
  	
 
	FB.getLoginStatus(function(response) {
		if (response.authResponse) 
			{
			FB.logout(function(response) {document.location = '/signout/';});
			} 
		else 
			{
			document.location = '/signout/';
			}
		});
}

jQuery.fn.fadeThenSlideToggle = function(speed, easing, callback) {
  if (this.is(":hidden")) {
    return this.slideDown(speed, easing).fadeTo(speed, 1, easing, callback);
  } else {
    return this.fadeTo(speed, 0, easing).slideUp(speed, easing, callback);
  }
};

var removeValueFromList = function(list, value, separator) {
  var separator = separator || ",";
  var values = list.split(",");
  for(var i = 0 ; i < values.length ; i++) {
    if(values[i] == value) {
      values.splice(i, 1);
      return values.join(",");
    }
  }
  return list;
}

function removeTag(obj,rand) // for textboxlist
	{
	var tag = obj.value;
	$$('li').each(function(el){
		if ($(el).className == 'textboxlist-bit textboxlist-bit-box textboxlist-bit-box-deletable')
			{
			// alert ($(el));
			var elementText = $(el).innerHTML.replace(",","");
			elementText = $(el).innerHTML.split("<");
			var content = elementText[0];
			if (content == tag)
				{
				var $j = jQuery.noConflict();
				$j(el).remove();
				}
			}
		var myList = document.getElementById('form_tags_input_' + rand);
		myList.value = removeValueFromList(myList.value,obj.value);
	    });

	$$('input').each(function(el){
		// alert($(el).id);
		if ($(el).type != 'checkbox')
			{
			// alert($(el).id + ': ' + $(el).value);
			}
	    });

	
	}

function getMostRecentUploadURL(username, success) // used to send fb requests and such.  as seen in /add/shareFacebook
	{
	$j.getJSON('/api/getUserUploads/?max=1&username=' + me.username,function(results)
		{
		results = queryToObject(results);
		var myurl = 'http://fandalism.com/' + (results).username + '/' + numToBase64.fromNumber((results).id);
		debug('getMostRecentUploadURL() is ' + myurl)
		if (success) 
			{
			success(myurl);
			}
		});
	}

function titleCase(str)
{
    return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
}

function pressMe(e, obj, hintregex)
	{
	if(window.event) key = window.event.keyCode; //IE
	else key = e.which; //firefox      
	if ((obj.value == hintregex) && (key == 8)) // no backspace
		{
		return false;
		}	

	var re = new RegExp("^" + hintregex);
	if (obj.value.match(re))
		{
		return true;		
		}
	else
		{
		obj.value = hintregex;
		return false;
		}
	}
	
function to_end(el) {
            var len = el.value.length || 0;
            if (len) {
                if ('setSelectionRange' in el) el.setSelectionRange(len, len);
                else if ('createTextRange' in el) {// for IE
                    var range = el.createTextRange();
                    range.moveStart('character', len);
                    range.select();
                }
            }
        }

function fillyForm(obj, hintregex)
	{
		if(!((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)))) 
			{
				obj.blur();
				if (window.getSelection) 
					{
					window.getSelection().removeAllRanges();
					}
				else if (document.selection) 
					{
					document.selection.empty();
					}
				obj.value = obj.value;
				obj.focus();
				to_end(obj);
			}
			
		var re = new RegExp("^" + hintregex);
		if (!obj.value.match(re))
			{
			obj.value = hintregex;
			}
       	}


numToBase64 = {

// http://stackoverflow.com/questions/6213227/fastest-way-to-convert-a-number-to-radix-64-in-javascript
// usage:
// numToBase64.fromNumber(x);
// numToBase64.toNumber(x);

    _Rixits :
//   0       8       16      24      32      40      48      56     63
//   v       v       v       v       v       v       v       v      v
    // "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+/",
    "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
    // You have the freedom, here, to choose the glyphs you want for 
    // representing your base-64 numbers. The ASCII encoding guys usually
    // choose a set of glyphs beginning with ABCD..., but, looking at
    // your update #2, I deduce that you want glyphs beginning with 
    // 0123..., which is a fine choice and aligns the first ten numbers
    // in base 64 with the first ten numbers in decimal.

    // This cannot handle negative numbers and only works on the 
    //     integer part, discarding the fractional part.
    // Doing better means deciding on whether you're just representing
    // the subset of javascript numbers of twos-complement 32-bit integers 
    // or going with base-64 representations for the bit pattern of the
    // underlying IEEE floating-point number, or representing the mantissae
    // and exponents separately, or some other possibility. For now, bail
    fromNumber : function(number) {
        if (isNaN(Number(number)) || number === null ||
            number === Number.POSITIVE_INFINITY)
            throw "The input is not valid";
        if (number < 0)
            throw "Can't represent negative numbers now";

        var rixit; // like 'digit', only in some non-decimal radix 
        var charCount = this._Rixits.length; // in case we're doing less than 64 chars or whatever...
        var residual = Math.floor(number);
        var result = '';
        while (true) {
            rixit = residual % charCount
            // console.log("rixit : " + rixit);
            // console.log("result before : " + result);
            result = this._Rixits[rixit] + result;
            // console.log("result after : " + result);
            // console.log("residual before : " + residual);
            residual = Math.floor(residual / charCount);
            // console.log("residual after : " + residual);

            if (residual == 0)
                break;
            }
        return result;
    },

    toNumber : function(rixits) {
        var result = 0;
        // console.log("rixits : " + rixits);
        // console.log("rixits.split('') : " + rixits.split(''));
        rixits = rixits.split('');
        for (e in rixits) {
            // console.log("_Rixits.indexOf(" + rixits[e] + ") : " + 
                // this._Rixits.indexOf(rixits[e]));
            // console.log("result before : " + result);
            result = (result * charCount) + this._Rixits.indexOf(rixits[e]);
            // console.log("result after : " + result);
        }
        return result;
    }
}


function toBase64(input, keyStr) { // make sure you send this a string, not a number.  for numbers (like contentIDs), use numToBase64()
	if (!keyStr)
		{
		var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
		}
	var ua = navigator.userAgent.toLowerCase();
	if (ua.indexOf(" chrome/") >= 0 || ua.indexOf(" firefox/") >= 0 || ua.indexOf(' gecko/') >= 0) {
		var StringMaker = function () {
			this.str = "";
			this.length = 0;
			this.append = function (s) {
				this.str += s;
				this.length += s.length;
			}
			this.prepend = function (s) {
				this.str = s + this.str;
				this.length += s.length;
			}
			this.toString = function () {
				return this.str;
			}
		}
	} else {
		var StringMaker = function () {
			this.parts = [];
			this.length = 0;
			this.append = function (s) {
				this.parts.push(s);
				this.length += s.length;
			}
			this.prepend = function (s) {
				this.parts.unshift(s);
				this.length += s.length;
			}
			this.toString = function () {
				return this.parts.join('');
			}
		}
	}
	var output = new StringMaker();
	var chr1, chr2, chr3;
	var enc1, enc2, enc3, enc4;
	var i = 0;

	while (i < input.length) {
		chr1 = input.charCodeAt(i++);
		chr2 = input.charCodeAt(i++);
		chr3 = input.charCodeAt(i++);

		enc1 = chr1 >> 2;
		enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
		enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
		enc4 = chr3 & 63;

		if (isNaN(chr2)) {
			enc3 = enc4 = 64;
		} else if (isNaN(chr3)) {
			enc4 = 64;
		}

		output.append(keyStr.charAt(enc1) + keyStr.charAt(enc2) + keyStr.charAt(enc3) + keyStr.charAt(enc4));
   }
   
   return output.toString();
}

function isie() // returns the version number (or undefined if not IE)
	{
    var undef,
        v = 3,
        div = document.createElement('div'),
        all = div.getElementsByTagName('i');
    while (
        div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->',
        all[0]
    );
    return v > 4 ? v : undef;
	};

function unhideThumbnails()
	{
	$j(".unprocessedThumbnail").each(function(x)
			{
			// if image is a perfect square, move it up a few notches
			$j(".unprocessedThumbnail").eq(x).load(function() {
				var imgWidth = $j(".unprocessedThumbnail").eq(x).width();
				var imgHeight = $j(".unprocessedThumbnail").eq(x).height();
				if (imgHeight == imgWidth)
					{
					$j(".unprocessedThumbnail").eq(x).css('margin-top','-20px');
					}
				$j(".unprocessedThumbnail").eq(x).show();
				
			}).each(function() // http://stackoverflow.com/questions/3588102/jquery-load-not-working-on-my-image
				{
				if(this.complete)
					{
					$j(this).load(); 
					}
				}); 					

			}).each(function(x)
				{
				$j(".unprocessedThumbnail").eq(x).removeClass('unprocessedThumbnail'); // this essentially marks it as "read" so we don't have to loop through it next time
				})
	}

function rebindBoxEvents() // gotta rebind events after an ajax load (make sure to unbind the first so they don't fire twice, i hear...)
	{

	$j(document).undelegate('.contentBox','mouseenter');
	$j(document).undelegate('.mouseleave','mouseenter');
	$j(document).undelegate('.mousedown','mouseenter');
	$j(document).undelegate('.mouseup','mouseenter');

	/*
	$j('.contentBox').bind('mouseenter',function()
		{
		if (!$j(this).hasClass('noHighlight'))
			{
			$j(this).fadeTo('fast',0.88);
			}
		});
	*/
	
	/*
	$j(document).delegate('.contentBox','mouseenter', function()
		{
		if (!$j(this).hasClass('noHighlight'))
			{
			// $j(this).fadeTo('fast',0.88);
			$j(this).css({ opacity: 0.88 });
			}
		})


	$j(document).delegate('.contentBox','mouseleave', function()
		{
		if (!$j(this).hasClass('noHighlight'))
			{
			$j(this).css({ opacity: 1 });
			// $j(this).fadeTo('fast',1);
			}
		});
	*/
	
	/*
	$j(document).delegate('.contentBox','mousedown', function()
		{
		if (!$j(this).hasClass('noHighlight'))
			{
			$j(this).css('opacity',1);
			}
		});


	$j(document).delegate('.contentBox','mouseup', function()
		{
		if (!$j(this).hasClass('noHighlight'))
			{
			$j(this).css('opacity',0.88);
			}
		});
	*/

	}
	
function getMoreItems(container, spinner, contentURL) // infinityScroll()
	{
	currentlyLoadingItems = 1;
	$j(spinner).show();
	var data = new Object();
	infinityScrollPage++;
	debug(data);
	data.page = infinityScrollPage;
	$j.get(contentURL,data,function(response)
		{
		currentlyLoadingItems = 0;
		var originalContent = $j(container).html();
		$j(container).append(response);
		var newContent = $j(container).html();
		if (originalContent == newContent)
			{
			$j(container).attr('doInfinityScroll',false);
			debug('No more new content...');
			}
		// $j('#mainContentHere').append('asdf<br>');
		// unhideThumbnails(); // this is in /js/contentBox.js (which is called in /footer) - slow as fuck so i commented it out
		rebindBoxEvents();
		$j(spinner).hide();
		// $j(document).trigger('scroll') // try again just to make sure we got enough
		})
	}

function isMoreListItemsNeeded(container) // infinityScroll() - this runs whenever someone scrolls or resizes the window
	{
	var scrollBuffer = 2000;
	var scrollTop = $j(window).scrollTop() + $j('#mainProfileContent').offset().top;
	var scrollBottom = scrollTop + $j('#mainProfileContent').offset().top;
	var position = $j('#mainProfileContent').height() - scrollBottom;
	if ((position > scrollBuffer) || ($j(container).attr('doInfinityScroll')) == 'false')
		{
		return(false);
		}
	else
		{
		return(true);
		}
	}

function somebodyScrolled(event, container, spinner, contentURL) // infinityScroll()
	{
	// debug(isMoreListItemsNeeded(container, event));
	if (isMoreListItemsNeeded(container, event) && (!currentlyLoadingItems))
		{
		getMoreItems(container, spinner, contentURL);
		debug('loading more items... ' + contentURL);
		}
	}

function infinityScroll(contentContainer, contentSpinner, contentURL) // see this in action at /fandalism/home/index
	{
	var container = $j('#' + contentContainer);
	var spinner = $j('#' + contentSpinner);
	if (typeof infinityScrollPage == 'undefined')
		{
		infinityScrollPage = 1;
		debug('Initializing infinityScroll, page: ' + infinityScrollPage)
		}
	$j(container).attr('doInfinityScroll',true) // when our scrolling produces no more output, turn this off to stop trying again.
	rebindBoxEvents();
	currentlyLoadingItems = 0; // global var

	$j(window).scroll(function(event) // bind to resize
		{
		somebodyScrolled(event, container, spinner, contentURL);
		});
			
	$j(window).resize(function(event) // bind to resize
		{
		somebodyScrolled(event, container, spinner, contentURL);
		});		
	}


