// sponsor send
$(function() {
	$('#sponsor_request_button').click(function() {
		$('#sponsor_send_response').html('Loading&hellip;');
		$('#sponsor_send_response').load('/ajax/sendSponsorRequest.php', {sponsor_name: $('#sponsor_name').val(), sponsor_email: $('#sponsor_email').val(), sponsor_msg: $('#sponsor_msg').val()});
	});
});
// activity viewer
$(function() {
	var isShowing = true;
	$('#toggle_curr_tile_stats').click(function() {
		if(isShowing) {
			$('#current_tile_summary').slideUp();
			$('#quick-upload').slideUp();
			isShowing = false;
			$('#toggle_curr_tile_stats').fadeOut('normal', function() {
				$('#toggle_curr_tile_stats').html('Show Current Tile Stats &darr;').fadeIn();
			});
		}
		else {
			$('#current_tile_summary').slideDown();
			$('#quick-upload').slideDown();
			isShowing = true;
			$('#toggle_curr_tile_stats').fadeOut('normal', function() {
				$('#toggle_curr_tile_stats').html('Hide Current Tile Stats &uarr;').fadeIn();
			});
		}
	});
	
	// view more you activites
	$('#view_more_you_activities').click(function() {
		var viewMoreLink = $(this);
		var newPageNum = parseInt($('#curr_you_page_num').val()) + 1;
		$.get('/ajax/get_activities.php', 
			{activity_cat: 'you', page_num: newPageNum, page_size: 15},
			function(text, textStatus, XmlHttpReq) {
				if(text != 'end') {
					viewMoreLink.parent().remove();
					$('#curr_you_page_num').val(newPageNum);
					$('#you_activity_list').append(text);
					if(parseInt($('#curr_you_page_num').val()) >= parseInt($('#you_page_max').val()))
						viewMoreLink.parent().remove();
					else
						viewMoreLink.parent().appendTo($('#you_activity_list'));
				} else {
					viewMoreLink.parent().fadeOut();
				}
			});
	});
	
	// view more stalkee activites
	$('#view_more_stalkee_activities').click(function() {
		var viewMoreLink = $(this);
		var newPageNum = parseInt($('#curr_stalkee_page_num').val()) + 1;
		$.get('/ajax/get_activities.php', 
			{activity_cat: 'stalkee', page_num: newPageNum, page_size: 15},
			function(text, textStatus, XmlHttpReq) {
				if(text != 'end') {
					viewMoreLink.parent().remove();
					$('#curr_stalkee_page_num').val(newPageNum);
					$('#stalkee_activity_list').append(text);
					if(parseInt($('#stalkee_you_page_num').val()) >= parseInt($('#stalkee_page_max').val()))
						viewMoreLink.parent().remove();
					else
						viewMoreLink.parent().appendTo($('#stalkee_activity_list'));
				} else {
					viewMoreLink.parent().fadeOut();
				}
			});
	});
});

// messaging functions
$(function()
{
	var userToUserMsgFormShowing = true;
	$('#toggle_msg_form_link').click(function() {
		if(userToUserMsgFormShowing)
		{
			$('.writeMessage').slideUp();
			userToUserMsgFormShowing = false;
			$('#toggle_msg_form_link').fadeOut('normal', function() {
				$('#toggle_msg_form_link').html('Show Form &darr;').fadeIn();
			});
		}
		else
		{
			$('.writeMessage').slideDown();
			userToUserMsgFormShowing = true;
			$('#toggle_msg_form_link').fadeOut('normal', function() {
				$('#toggle_msg_form_link').html('Hide Form &uarr;').fadeIn();
			});
		}
	});
	
	$('#send_msg_button').click(function() {
		$('.writeMessage').toggle('fast', null);
	});
	
	var clearField = true;
	$('#msg_subject').click(function() {
		if(clearField) {
			clearField = false;
			$('#msg_subject').val('');
		}
	});
	
	// sending a message from profile
	$('#msg_submit_button').click(function() {
		if($('#msg_subject').val() == '')
		{
			alert('A subject is required.');
			return;
		}
		$('#msg_status').html('Loading...');
		$('#msg_status').show();
		$('#msg_status').load('/ajax/send_message.php', 
			{target_userid: $('#uid').val(), subject: $('#msg_subject').val(), 
			body: $('#msg_body').val(), target_mid: $('#current_mid').val(), format: 'plain'},
			function() {
				$('#msg_body').val('');
				$('#msg_subject').val('');
				$('#msg_status').attr('class', 'error');
				setTimeout("$('#msg_status').fadeOut(3000)", 3000);
			});
		
	});
	
	// sending a message from user-to-user page
	$('#user_to_user_submit').click(function() {
		if($('#msg_subject').val() == '')
		{
			alert('A subject is required.');
			return;
		}
		$.get('/ajax/send_message.php', {target_userid: $('#recipient_userid').val(),
			subject: $('#msg_subject').val(), body: $('#msg_body').val(), target_mid: 0, format: 'site_html'},
			function(text, textStatus, XMLHttpReq) {
				if(text != 'failed' && text != 'error')
				{
					$('#msg_subject').val('');
					$('#msg_body').val('');
					var item = $(text).hide();
					item.prependTo($('#msgs_list')).slideDown();
				}
				else {
					$('#msg_status').html('Loading...');
					$('#msg_status').show();
					$('#msg_status').html('Could not send message.');
					$('#msg_status').attr('class', 'error');
					setTimeout("$('#msg_status').fadeOut(3000)", 3000);
				}
			});
	});
		
	var clickedLink;
	$('.msg_delete_link').click(function() {
		clickedLink = $(this);
		if(confirm('Really delete this message? This cannot be undone.')) {
			$.get('/ajax/delete_message.php', {msg_id: $(this).attr('id')},
			function(text, textStatus, XMLHttpReq) {
				clickedLink.parent().parent().parent().slideUp();
			});
		}
	});
});

function blockMessagesFromUser(userid)
{
	var doBlock = 1;
	if($('#block_'+userid).html() == 'Un-Block')
		doBlock = 0;
	$.get('/ajax/block_message_sender.php', {user_id: userid, do_block: doBlock},
	function(text, textStatus, XMLHttpReq) {
		var linkText = (doBlock) ? 'Un-Block':'Block'
		$('#block_'+userid).fadeOut('normal', function() { $(this).html(linkText).fadeIn(); });
	});
}
// simple site stats function
$(function()
{
	function SiteStatsCB(data, textStatus)
	{
		$('#footer_tile_count').html($(data).find('tile_count').text());
		$('#footer_view_count').html($(data).find('view_count').text());
		$('#footer_caption_count').html($(data).find('caption_count').text());
		$('#footer_user_count').html($(data).find('user_count').text());
	}
	$.get('/ajax/siteStats.php', SiteStatsCB); 
});

// search toggle
$(document).ready(function() {
	$('#searchBtn').click(function() { 
		$('#search').slideToggle();
	});
});

// Tile stats
$(function()
{
	if($('#starting_mid').val() == 0)
	{
		// hide the stats
		$('.tileStats').toggle();
		//$('.tilePrev').toggle();
	}
});

// Stash functions
// Remove from stash-dashboard
function StashRemoveDashboard(mid)
{
	if(confirm("Do you really want to remove this Momentile from your stash?"))
	{
		$.get('/ajax/stashUpdate.php', { remove: 1, 
										 uname: $('#logged_in_username').val(), 
										 mid: mid }, StashDashboardRemoveCB);
	}
}
function StashDashboardRemoveCB()
{
	window.location.reload();
}

function UpdateStashUI(isStashed)
{
	if(isStashed == 1)
	{
		$('#stashTab').attr('class', 'tabStash stashed');
		$('#stashTab').attr('title', 'This Momentile is already in your stash.');
		$('#is_stashed').val(isStashed);
	}
	else
	{
		$('#stashTab').attr('class', 'tabStash');
		$('#stashTab').attr('title', 'Remove this Momentile from your stash.');
		$('#is_stashed').val(isStashed);
	}
}

$(function ()
{	
	if($('#is_stashed').val() == 1)
	{
		$('#stashTab').attr('title', 'Remove this Momentile from your stash.');
	}
	
	if($('#starting_mid').val() == 0)
	{
		$('#stashTab').attr('style', "display:none;");
		$('#tilePrevLi').attr('class', 'tilePrevDisabled');
		$('#captionTab').attr('style', "display:none;");
	}
	else if($('#logged_in_uid').val() == 0)
	{
		$('#stashTab').attr('title', "You must be logged in to stash Momentiles.");
	}
	
	function StashUpdateAddCB(data, textStatus)
	{
		$('#stashTab').attr('class', 'tabStash stashed');
		$('#stashTab').attr('title', 'This Momentile has been stashed. Click again to remove it.');
		$('#is_stashed').val(1);
		var tileMetaData = globalTileMetaDataArray[globalCurrentIndex];
		tileMetaData.stashCount++;
		tileMetaData.isStashed = 1;
		globalTileMetaDataArray[globalCurrentIndex] = tileMetaData;
		updateTileData(tileMetaData);
	}
	function StashUpdateRemoveCB(data, textStatus)
	{
		$('#stashTab').attr('class', 'tabStash');
		$('#stashTab').attr('title', 'Stash this Momentile');
		$('#is_stashed').val(0);
		var tileMetaData = globalTileMetaDataArray[globalCurrentIndex];
		tileMetaData.stashCount--;
		tileMetaData.isStashed = 0;
		globalTileMetaDataArray[globalCurrentIndex] = tileMetaData;
		updateTileData(tileMetaData);
	}
	
	$('#stashTab').click(function()
		{
			// remove or stash?
			if($('#starting_mid').val() != 0 && $('#logged_in_uid').val() != 0)
			{
				if($('#is_stashed').val() == 1)
				{
					$.get('/ajax/stashUpdate.php', { remove: 1, 
													 uname: $('#logged_in_username').val(), 
													 mid: $('#current_mid').val() }, StashUpdateRemoveCB, 'xml');
				}
				else
				{
					$.get('/ajax/stashUpdate.php', { add: 1, 
													 uname: $('#logged_in_username').val(), 
													 mid: $('#current_mid').val() }, StashUpdateAddCB, 'xml');
				}
			}
		});
});
///// End Stash Functions //////////

// Forgot password functions
$(document).ready(function() 
{
		$('#forgot_pass_link').click(function() 
		{ 
			$.get('/ajax/forgotPassword.php', { email: $('#email').val() }, ForgotPassCB); 
		});
		
		function ForgotPassCB(data, textStatus)
		{
			$('#forgot_pass_response').html(data);
			$('#forgot_pass_response').fadeIn(800);
		}
});
/////// End Forgot password functions ////
//////////////////////////////////////////
// Mailing list
$(function()
{
	$('#mlist_button').click(function()
	{
		$('#mlist_response').load('/ajax/mailing_list_add.php?email=' + $('#mlist_email').val());
	});
});
/////////////////////////////////////////

// Abuse functions
$(function() {
	$('#report_tile_link').click(function() {
		$.get('/ajax/reportAbuse.php', {mid: $('#current_mid').val()}, function(text, textStatus, XMLReq) {
			if(text == 'Success') {
				$('#report_tile_link').html('Tile Reported!');
			}
		});
	});
});
// End Abuse functions

// Remove acct functions
$(document).ready(function() {
	$('#really_remove_acct').click(function() { $('#remove_span').load('/removeAcct.php?doIt=1'); } );
	$('#really_remove_acct').confirm({wrapper:'<span id="remove_span"></span>', msg:'Do you really want to hurt me?', dialogShow:'fadeIn', timeout:4000});
});
// End remove acct functions

// BigAssBox functions
$(document).ready(function(){
	$('#bigAssBox').animate({opacity: 1.0}, 3000);
	$('#bigAssBox').fadeOut(3500);
});
// END BigAssBox functions

/////////////////////////////////////////////
// Stalk button functions
$(document).ready(function() {
	$('#stalk_button').bind('click', StalkButtonClicked);
	$('#stalk_button_sms').bind('click', StalkSMSButtonClicked);
	$('#event_stalk_button').bind('click', StalkButtonClicked);
});

function StalkerAddCB(data, textStatus)
{
	var resultStatus = $(data).find('status').text();
	if(resultStatus == 0)
	{
		$('#stalk_button').attr('title', 'Stop Stalking '+$('#profile_owner_name').val());
		$('#stalk_button').html('Stop Stalking ' + $('#profile_owner_name').val());
		$('#is_stalkee').val(1);
		// add the sms button
		$('#stalkButtonsContainer').prepend('<a href="#" id="stalk_button_sms" title="Enable SMS Updates">Enable SMS Updates</a>&nbsp;');
		$('#stalk_button_sms').bind('click', StalkSMSButtonClicked);
	}
}

function StalkerRemoveCB(data, textStatus)
{
	if($(data).find('status').text() == 0)
	{
		$('#is_stalkee').val(0);
		// clobber the buttons
		$('#stalkButtonsContainer').html('');
		// re add the stalkbutton
		$('#stalkButtonsContainer').append('<a href="#" id="stalk_button" title="Stalk '+$('#profile_owner_name').val()+'">Stalk '+$('#profile_owner_name').val()+'</a>');
		$('#stalk_button').bind('click', StalkButtonClicked);
	}
}

function StalkerEnableDeviceUpdatesCB(data, textStatus)
{
	var resultStatus = $(data).find('status').text();
	if(resultStatus == 0)
	{
		$('#stalk_button_sms').attr('title', 'Disable SMS Updates');
		$('#stalk_button_sms').html('Disable SMS Updates');
		$('#device_updates_on').val(1);
	}
}

function StalkerDisableDeviceUpdatesCB(data, textStatus)
{
	var resultStatus = $(data).find('status').text();
	if(resultStatus == 0)
	{
		$('#stalk_button_sms').attr('title', 'Enable SMS Updates');
		$('#stalk_button_sms').html('Enable SMS Updates');
		$('#device_updates_on').val(0);
	}
}

function StalkSMSButtonClicked(event)
{
	var isEvent = false;
	if($('#eid').val() > 0)
		isEvent = true;
		
	if($('#device_updates_on').val() == 0 && !isEvent)
	{
		// turn device updates on
		$.get('/ajax/stalkUpdate.php', {enable_device_updates: 1, sr: $('#logged_in_username').val(), se_id: $('#uid').val()}, StalkerEnableDeviceUpdatesCB, 'xml'); 
	}
	else if($('#device_updates_on').val() == 1 && !isEvent)
	{
		// turn them off
		$.get('/ajax/stalkUpdate.php', {disable_device_updates: 1, sr: $('#logged_in_username').val(), se_id: $('#uid').val()}, StalkerDisableDeviceUpdatesCB, 'xml');
	}
	else if($('#device_updates_on').val() == 0 && isEvent)
	{
		// turn device updates on
		$.get('/ajax/stalkUpdate.php', {enable_event_device_updates: 1, sr: $('#logged_in_username').val(), se_id: $('#eid').val()}, StalkerEnableDeviceUpdatesCB, 'xml'); 
	}
	else if($('#device_updates_on').val() == 1 && isEvent)
	{
		// turn them off
		$.get('/ajax/stalkUpdate.php', {disable_event_device_updates: 1, sr: $('#logged_in_username').val(), se_id: $('#eid').val()}, StalkerDisableDeviceUpdatesCB, 'xml');
	}
}

function StalkButtonClicked(event)
{
	var isEvent = false;
	if($('#eid').val() > 0)
		isEvent = true;
		
	if($('#is_stalkee').val() == 0 && !isEvent)
	{
		// add the user as a stalkee
		$.get('/ajax/stalkUpdate.php', {add: 1, sr: $('#logged_in_username').val(), se_id: $('#uid').val()}, StalkerAddCB, 'xml'); 
	}
	else if($('#is_stalkee').val() == 1 && !isEvent)
	{
		// remove the user as stalkee
		$.get('/ajax/stalkUpdate.php', {remove: 1, sr: $('#logged_in_username').val(), se_id: $('#uid').val()}, StalkerRemoveCB, 'xml'); 
	}
	else if($('#is_stalkee').val() == 0 && isEvent)
	{
		$.get('/ajax/stalkUpdate.php', {addevent: 1, sr: $('#logged_in_username').val(), se_id: $('#eid').val()}, StalkerAddCB, 'xml'); 
	}
	else if($('#is_stalkee').val() == 1 && isEvent)
	{
		$.get('/ajax/stalkUpdate.php', {removeevent: 1, sr: $('#logged_in_username').val(), se_id: $('#eid').val()}, StalkerRemoveCB, 'xml');
	}
}

// End stalk button functions

// Remove Stalkee
function RemoveStalkee(stalker, stalkee, stalkee_id)
{
	if(confirm("Do you really want to stop stalking "+stalkee+"? Afraid you'll get cooties or something?"))
	{
		window.location.replace('/ajax/removeStalkee.php?stalker='+stalker+'&stalkee_id='+stalkee_id);
	}
}
///////////////////////////////////////////////
// Remove Mtile functions
function RemoveMtile(mid, yid) {
	if(confirm('Are you sure want to delete this momentile? You cannot undo this action')) {
		window.location.replace('/ajax/removeMomentile.php?removeMid=' + mid + '&yid=' + yid);
	}
}
// End remove mtile functions

///////////////////////////////////////////////
// remove captions functions
function RemoveCaption(cid, mid) {
	if(confirm('Do you really want to delete this caption? This cannot be undone.')) {
		window.location.replace('/removeCaption.php?removeCid=' + cid + '&mid=' + mid);
	}
}
// end remove captions functions

////////////////////////////////////////////////////////////
// Invite stuff
/////////////////////

function InviteResponseCB(data) {
	//$('#invite_count').load('/ajax/invite.php?op=get_invite_count');
	$('#invite_response').animate({opacity: 1.0}, 1000);
	//$('#invite_response').fadeOut(3500);
}

$(document).ready(function() {
	$('#invite_button').click(function() {
		$('#invite_response').load('/ajax/invite.php?invitee_email=' + $('#invitee_email').val() + '&invite_msg=' + escape($('#invite_msg_text').val()), 
			InviteResponseCB);
		//$('#invite_response').toggle();
		$('#invite_response').html('<br/><span class="error">Sending...</span>');
	});
});

//////////////////////////////////////////////////////////////////
// CHAR COUNTERS
$(document).ready(function() {
	$("#twitter_msg").charCounter($("#tweet_max_len").val(), {container: "#tweet_counter"});
});

$(document).ready(function() {
	$("#motto").charCounter(128, {container: "#motto_counter"});
});

$(document).ready(function() {
	$("#caption_text").charCounter(255, {container: "#caption_counter"});
});
//////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////
// fancyzoom stuff

$(function() {
		$.fn.fancyzoom.defaultsOptions.imgDir='/themes/fancyzoom_images/legacy/'; //very important must finish with a /
		$('a.zoomer').fancyzoom({speed:450}); 
	});

//////////////////////////////////////////////////////////////////
// Events
$(document).ready(function() {
	$('#showUpload').htmlZoom({directory: '/themes/htmlZoom'});
	$('#showRulesPrizes').htmlZoom({width: 940, directory: '/themes/htmlZoom'});
});
$(document).ready(function(){
	$('#eventWinners').cycle({ 
  			fx:'scrollHorz', 
			speedIn:'1500', 
			speedOut:'3000', 
			cleartype: '1'
	});
});


/////////////////////////////////////////////////
// STORE FUNCTIONS
function LoadProductImage(type, width, height) {
	$('#prod_image').text('Loading...');
	$('#prod_image').load('/store/getProductImage.php?type='+type+'&width='+width+'&height='+height);
	$('#current_image_type').val(type);
	$('#current_image_w').val(width);
	$('#current_image_h').val(height);
}

$(document).ready(function() {
	$('#prod_image').load('/store/getProductImage.php?type=momentiles&width='+$('#current_image_w').val()+'&height='+$('#current_image_h').val());
	$('#current_image_type').val('momentiles');
	//$('#current_image_w').val('1732');
	//$('#current_image_h').val('650');
});
//////////////////////////////////////////////////

//////////////////////////////////////////////////
// App page functions
$(document).ready(function(){
	$('#app-slideshow').cycle({ 
			fx:'scrollHorz', 
		speedIn:'1500', 
		speedOut:'3000', 
		cleartype: '1'
	});
});	
/////////////////////////////////////////////////

////////////////////////////////////////////////
// Redesign profile tab functions
$(function(){
		$('#stalkTabs').tabs({ fx: { opacity: 'toggle' } });				
});

$(function(){
	if($('#starting_mid').val() == 0)
	{
		$('#captionTab').attr('title', "You can't caption the default Momentile.");
	}
	else if($('#logged_in_uid').val() == 0)
	{
		$('#captionTab').attr('title', "You must be logged in to write captions.");
	}
	
	$('.tabYears').click(function() {
		$('#writeCaption').slideUp('slow');
		$('#tiles').slideUp('slow');
		$('#years').load('/ajax/userYears.php', {username: $('#profile_owner_name').val()}, function() { $('#years').slideToggle('slow'); } );
	});
	
	$('#captionTab').click(function()
	{
		if($('#starting_mid').val() != 0 && $('#logged_in_uid').val() != 0)
		{
			$('#years').slideUp('slow');
			$('#tiles').slideUp('slow');
			$('#writeCaption').slideToggle('slow');
		}
		return false;
	});
	
	$('.tabTiles').click(function() {
		$('#writeCaption').slideUp('slow');
		$('#years').slideUp('slow');
		if($('#eid').val() > 0)
			$('#tiles').load('/ajax/eventMtiles.php', {eventname: $('#event_name').val()}, function () { $('#tiles').slideToggle('slow'); });
		else
			$('#tiles').load('/ajax/userMtiles.php', {username: $('#profile_owner_name').val()}, function () { $('#tiles').slideToggle('slow'); });
	
		return false;
	});
	
});


////////////////////////////////////////////////
// user tile slide show, dynamic slide loading

// These are used for updating meta data when actions are performed (stash, etc)
var globalTileMetaDataArray;
var globalCurrentIndex;
$(function()
{
	// custom object for holding tile metadata
	function TileMetaData(tileUrl, tileHeight, tileWidth, tileDate, viewCount, captionCount, stashCount, isStashed, mid)
	{
		this.url = tileUrl;
		this.height = tileHeight;
		this.width = tileWidth;
		this.date = tileDate;
		this.viewCount = viewCount;
		this.captionCount = captionCount;
		this.stashCount = stashCount;
		this.isStashed = isStashed;
		this.mid = mid;
	}
	
	var futureTiles = [];
	var pastTiles = [];
	var tileMetaDataArray = [];
	var startingIndex = 0;
	var currentIndex = 0;
	var startingTile = null;
	var initIndex = 1;
	globalCurrentIndex = currentIndex;
	// reset current_mid
	$('#current_mid').val($('#starting_mid').val());
	$('#caption_current_mid').val($('#starting_mid').val());
	
	if($('#eid').val() > 0)
	{
		$.get('/ajax/loadEventTilesList.php', 
			{requester_uid: $('#logged_in_uid').val(), eventname: $('#event_name').val()}, 
			StartSlideShow, 
			'xml');
	}
	else
	{
		$.get('/ajax/loadUserTilesList.php', 
			{requester_uid: $('#logged_in_uid').val(), username: $('#profile_owner_name').val()}, 
			StartSlideShow, 
			'xml'); 
	}
	function StartSlideShow(data, textStatus)
	{
		var slideCount = 0;
		var tmpArray = [];
		$(data).find('mtile').each(function() 
		{
			var tileHeight = 0;
			var tile = new TileMetaData(
				$(this).find('url_lrg').text(),
				$(this).find('height').text(), 
				$(this).find('width').text(),
				$(this).find('date').text(),
				$(this).find('numviews').text(),
				$(this).find('captioncount').text(),
				$(this).find('stashcount').text(),
				$(this).find('is_stashed').text(),
				$(this).find('mid').text());
			
			tmpArray.push($(this).find('url_lrg').text());
			tileMetaDataArray.push(tile);
			
			if($(this).find('mid').text() == $('#starting_mid').val())
			{
				startingIndex = slideCount;
				currentIndex = startingIndex;
			}
			slideCount++;
		});
		globalTileMetaDataArray = tileMetaDataArray;
		// split the tmpArray into 2 arrays, one that contains urls that are previous (past mtiles)
		// and one for next (mtiles taken after the current mid)
		for(var i = 0; i < slideCount; i++)
		{
			if(i < startingIndex)
			{
				futureTiles.push(tmpArray[i]);
			}
			else if(i > startingIndex)
			{
				pastTiles.push(tmpArray[i]);
			}
			
			if(i == startingIndex)
			{
				startingTile = tileMetaDataArray[i];
				startingTile.height = $('#slide_0').attr('height');
				startingTile.width = $('#slide_0').attr('width');
				if(startingTile.stashCount == 0)
				{
					$('#stashersLink').hide();
				}
				if(startingTile.captionCount == 0)
				{
					$('#captionLink').hide();
				}
			}
		}
		tmpArray = null;

		if(startingIndex > 0)
		{
			$('#currentTile').prepend('<img src="'+futureTiles.pop()+'" />' );
			if(startingIndex + 1 == slideCount)
				$('#tilePrevLi').attr('class', 'tilePrevDisabled');
		}
		else
		{
			$('.tileNext').hide();
			initIndex = 0;
		}
		
		if(startingIndex + 1 < slideCount)
		{
			$('#currentTile').append('<img src="'+pastTiles.shift()+'" />');
		}
			
		$('#currentTile').cycle({ 
		    fx:     'scrollHorz', 
		    speed:  1200, 
		    timeout: 0,
		    startingSlide: initIndex,
		    before: onBefore,
		   	next:   '#prevTileLink', 
		    prev:   '#nextTileLink' 
		});
		
		function onBefore(curr, next, opts, fwd)
		{
			if(!opts.addSlide)
				return;
			if(opts.slideCount == slideCount)
			{
				// handle wrapping
				if(fwd)
					++currentIndex;
				else
					--currentIndex;
				if(currentIndex >= slideCount)
					currentIndex = 0;
				else if(currentIndex < 0)
					currentIndex = slideCount;
					
				tile = tileMetaDataArray[currentIndex];
				updateTileData(tile);
				
				if(currentIndex == 0)
					$('.tileNext').fadeOut(600);
				else
					$('.tileNext').fadeIn(600);

				return;
			}
			
			// hide the overlays
			$('#tiles').slideUp('fast');
			$('#years').slideUp('fast');
			$('#writeCaption').slideUp('fast');
			
			if(fwd)
				++currentIndex;
			else
				--currentIndex;
			
			if(currentIndex + 1 == slideCount)
				$('#tilePrevLi').attr('class', 'tilePrevDisabled');
			else
				$('#tilePrevLi').attr('class', 'tilePrev');
			
			var imgSrc;
			imgSrc = fwd ?  pastTiles.shift() : futureTiles.pop();
				
			// disable arrows if we are at the beginning or end of the slides
			if(currentIndex == 0)
				$('.tileNext').fadeOut(600);
			else
				$('.tileNext').fadeIn(600);
			
				
			var tile = (currentIndex == startingIndex) ? startingTile : tileMetaDataArray[currentIndex];
			
			globalCurrentIndex = currentIndex;
			updateTileData(tile);
			
			if(imgSrc)
				opts.addSlide('<img src="'+imgSrc+'.jpg" id="slide_'+(currentIndex + 1)+'" />', fwd == false);
	
			// if on IE7 or IE8 make sure the height didn't get fucked
			if(navigator.userAgent.search('MSIE') > -1 || navigator.userAgent.search('Opera') > -1)
			{
				$('#slide_'+currentIndex).attr('cycleH', tile.height);
				$('#slide_'+currentIndex).attr('cycleW', tile.width);
				$('#slide_'+currentIndex).attr('height', tile.height);
				$('#slide_'+currentIndex).attr('width', tile.width);
				$('#slide_'+currentIndex).css({height: tile.height+'px'});
				$('#slide_'+currentIndex).css({width: tile.width+'px'});
			}
		};
	};
	
});
function updateTileData(currTile)
	{
		$('#viewCount').html(currTile.viewCount);
		$('#captionCount').html(currTile.captionCount);
		$('#stashCount').html(currTile.stashCount);
		$('#tileDateText').html(currTile.date);
		$('#current_mid').val(currTile.mid);
		$('#caption_current_mid').val(currTile.mid);
		
		//$('#permalink').attr('href', "/showMomentile/"+$('#uid').val()+"/"+currTile.mid);
		$('#permalink').attr('href', '/'+$('#profile_owner_name').val()+'/'+currTile.date.replace(/\//g, "-"));
		$('#permalink').attr('title', 'http://momentile.com'+$('#permalink').attr('href'));
		
		// reset abuse link
		$('#report_tile_link').html('Report as Abuse');
		
		if(currTile.isStashed == 1)
		{
			$('#stashTab').attr('class', 'tabStash stashed');
			$('#stashTab').attr('title', 'Remove this Momentile from your stash.');
		}
		else
		{
			if($('#logged_in_uid').val() != 0)
			{
				$('#stashTab').attr('class', 'tabStash');
				$('#stashTab').attr('title', 'Add this Momentile to your stash.');
			}
			else
			{
				$('#stashTab').attr('class', 'tabStash inactive');
				$('#stashTab').attr('title', 'You must log in to stash momentiles.');
			}
		}
		
		$('#is_stashed').val(currTile.isStashed);
		
		if(currTile.stashCount == 0)
			$('#stashersLink').hide();
		else
			$('#stashersLink').show();
		
		if(currTile.captionCount == 0)
		{
			$('#captionLink').hide();
		}
		else
		{
			$('#captionLink').show();
		}
		
		$('#currentTile').animate({height: currTile.height+"px", width: currTile.width+"px"}, 1200);
		
		// event stuff
		if($('#eid').val() > 0)
			$('#mtileCaptions').load('/ajax/loadMtileCaptions.php?mid='+currTile.mid);
	}
////////////////////////////////////////////
// profile caption link
$(function() 
{
	$('#captionLink').click(function()
	{
		$('#captionLink').attr('href', 'http://'+window.location.hostname+'/captions/'+$('#current_mid').val());
	});
});
//////////////////////////////////////////
// profile stashers link
$(function() 
{
	$('#stashersLink').click(function()
	{
		$('#stashersLink').attr('href', 'http://'+window.location.hostname+'/stashers/'+$('#current_mid').val());
	});
});
//////////////////////////////////////////
// timezone selector on change
$(function()
{
	$('#tz_selector').change(function()
	{
		$('#tz_has_changed').val(1);
	});
});

//////////////////////////////////////
// EVENTS
/////////
// CAPTIONS- DETAIL PAGE
$(function()
{
	$('#mtileCaptions').load('/ajax/loadMtileCaptions.php?mid='+$('#starting_mid').val());
});

//////////////////////////////////////////////////////////////////
// MULLIGANS
$(function() {
	$('.mulliganLink').htmlZoom({directory: '/themes/htmlZoom'});
	$('.mulliganLink').click(function() {
		var mtsId = 'mts_'+$(this).attr('id');
		$('#mulligan_date').val($('#'+mtsId).val());
	});
});
