 $(document).ready(function(){
	// rOLLOVERS					   
	$(".rollover").hover(
	 function() {
	  curr = $(this).find("img").attr("src");
	  overlen = curr.length;
	  over = curr.substr(0, overlen-4);
	  extArr = curr.split('.');
	  ext = extArr[extArr.length-1];
	  over = over+'_o.'+ext;
	  $(this).find("img").attr({ src: over});
	 },
	 function() {
	  $(this).find("img").attr({ src: curr});
	 }
	)
	
	$(".rollover").find("img").each(function(i) {
	  temp = this.src;
	  prelen = temp.length;
	  pre = temp.substr(0, prelen-4);
	  extArr = temp.split('.');
	  ext = extArr[extArr.length-1];
	  pre = pre+'_o.'+ext;
	  preload_image_object = new Image();
	  preload_image_object.src = pre;
	});
	
	// Any roundme
	//$("*[name='roundme']").corner({autoPad: true});
});


function showFieldHelper(element){
	var el = $('div#'+element+'h');
	el.fadeIn();
}

function hideFieldHelper(element){
	var el = $('div#'+element+'h');
	el.fadeOut('fast',function(){
		$(this).hide();							   
	});
}

function confirmDelete(delUrl, msg) {
  if (confirm(msg)) {
    document.location = delUrl;
  }
}

function resized(){
	// Dummy
}

function popUpWindow(url, id, width, height) {
	window.open(url, id, "toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=1,width="+width+",height="+height);
}

function fbShare() {
	var shareUrl = document.location.href;
	var fbUrl = "http://www.facebook.com/sharer.php?u=" + escape(shareUrl);
	pageTracker._trackPageview("/fb-share/"+escape(shareUrl)); 
	popUpWindow(fbUrl, 'fb_share', 620, 440);
}

// Facebook
var tagMode = false;
var fbFriendsLoaded = false;
var fbFriendsLoading = false;
var friendsJson = null;
var showingSelector = false;
var curX = null;
var curY = null;
var cleanList = null;
var idSelected = null;
var gotTagsFlag = false;
var tagsJson = null;
var photoMouseMoveStarted = false;
var inCanvas = false;
var newSesUrl = null;
var fbSesKey = '';
var fbUid = null;
var picId = null;

function setCookies(){
	$.post('ajax/set_cookies.php', {}, setCookiesCallback);
	return false;
}
function setCookiesCallback(status){
	$('#fb-form').submit();
}
function startTagging(){
	tagMode = true;
	// Show Instructions
	$('.tagging_instructions').show();
	// Show Crosshair
	$('#photo').css('cursor', 'crosshair');
	return false;
}
function nextPhoto(e){
	if (tagMode){
		return false;
	} else {
		// Redirect to next photo
		return true;
	}
}
function photoClick(e){
	if (tagMode){
		if (!fbFriendsLoaded && !fbFriendsLoading){
			fbFriendsLoading = true;
			// Get Friends
			$.getJSON("http://4devents.ca/ajax/fb_friends_get.php", {fb_id: fbUid}, gotFacebookFriends);
		}
		showSelector(e.pageX, e.pageY);
	}
}

function showSelector(x,y){
	if (!x || !y){
		alert("Coordinate Error. Try a different browser.");	
	}
	var frameSize = $('#tagframe').outerWidth();
	var selWidth = $('#fb_selector').width();
	var frameMargin = 10;
	var halfFrame = Math.round(frameSize/2);
	var picPos = $('#photo').offset();
	var picRight = picPos.left + $('#photo').width();
	var picBottom = picPos.top + $('#photo').height();
	
	// Too Much Left
	x = (x-halfFrame < picPos.left)? picPos.left + halfFrame : x;
	// Too Much Right
	x = (x+halfFrame > picRight )? picRight - halfFrame : x;
	// Too Much Top
	y = (y-halfFrame < picPos.top)? picPos.top + halfFrame : y;
	// Too Much Right
	y = (y+halfFrame > picBottom )? picBottom - halfFrame : y; 
	
	// Set coordinates
	curX = x - picPos.left;
	curY = y - picPos.top;
	
	// position tagframe
	$('#tagframe').css('left', x-halfFrame);
	$('#tagframe').css('top', y-halfFrame);
	$('#tagframe').show();
	
	// To the left, or to the right?
	var selX = x + halfFrame + frameMargin;
	// Correct
	selX = ((x + halfFrame + frameMargin + (selWidth/2)) > picRight)? (x - halfFrame - frameMargin - selWidth) : selX;
	var selY = y - halfFrame;
	
	$('#fb_selector').css('left', selX);
	$('#fb_selector').css('top', selY);
	$('#fb_selector').show();
	$('#name_filter_input').focus();
	if (!showingSelector && fbFriendsLoaded){
		resetSelector();
	}
	showingSelector = true;
}
function hideSelector(){
	$('#fb_selector').hide();
	$('#tagframe').hide();
	showingSelector = false;
	idSelected = null;
}
function resetSelector(){
	$('#name_filter_input').val('');
	buildFriendsList('');
}
function gotFacebookFriends(friends, status){
	fbFriendsLoading = false;
	if (status == 'success'){
		if (friends.status == 'success'){
			friendsJson = friends.data;
			fbFriendsLoaded = true;
			buildFriendsList('');
		} else if (friends.status == 'error') {
			$.jGrowl(friends.error, {theme: 'jGrowl-error'});
		} else if (friends.status == 'session') {
			invalidSession();
		}
	}
}
function buildFriendsList(filter){
	idSelected = null;
	if (filter == '' && cleanList != null){
		htmlList = cleanList;
	} else {
		var htmlList = '';
		if (filter != ''){
			var regex = new RegExp(filter,"i");
		}
		var lastId = null;
		var count = 0;
		$.each(friendsJson, function(i,item){
			var fullname = item.name;
			if (item.uid == fbUid) fullname += ' (Me)';
			var matches = true;
			if (filter != ''){
				var matches = regex.exec(fullname);
			}
			if (filter == '' || matches){
				htmlList += '<label><input type="checkbox" value="1" id="chk'+item.uid+'" onClick="tagFriend('+item.uid+', $(this))"/>'+fullname+'</label>';
				count++;
				lastId = item.uid;
			}
		});
		if (filter == '' && cleanList == null){
			cleanList = htmlList;
		}
	}
	$('#userlist').html(htmlList);
	if (count == 1){
		$('#chk'+lastId).attr('checked', 'checked');
		idSelected = lastId;
	} else if (count == 0){
		$('#userlist_all').hide();	
	} else {
		$('#userlist_all').show();	
	}
}
function filterNameChange(e){
	buildFriendsList($('#name_filter_input').val());
}
function taggingModeOff(){
	stopTagging();
	curX = null;
	curY = null;
	// Hide Crosshair
	$('#photo').css('cursor', 'pointer');
	$('.tagging_instructions').hide();
	hideSelector();
}
function stopTagging(){
	tagMode = false;
}
function tagHit(){
	if (idSelected != null){
		if ($('#chk'+idSelected).attr('checked')){
			tagFriend(idSelected);	
		}
	}
}
function chkHit(friendId, chk){
	// Make sure we didn't just uncheck it
	if (chk.attr('checked')){	
		tagFriend(friendId);
	}
}
function tagFriend(friendId){
	hideSelector();
	if (curX != null && curY != null && friendId && picId){
		var data = {fb_id: fbUid, pic_id: picId, friend_id: friendId, x:curX, y:curY}
		$.getJSON('http://4devents.ca/ajax/fb_tag_friend.php', data, tagFriendCallback);
	} else {
		$.jGrowl("Cannot save this tag. Refresh this page and try again.", {header: 'Tagging Error (js)', theme: 'jGrowl-error'});
	}
}
function tagFriendCallback(json, status){
	if (status == 'success'){
		if (json.status == 'success'){
			getTags();
			$.jGrowl("Tag saved.");
		} else if (json.status == 'error'){
			$.jGrowl(json.error, {header: 'Tagging Error', theme: 'jGrowl-error'});
		} else if (json.status == 'session') {
			invalidSession();
		}
	}
}
function getTags(){
	$('.tag_names').hide();
	$('#tag_spinner').show();
	$('#tag_space').show();
	$.getJSON('http://4devents.ca/ajax/fb_get_tags.php', {pic_id: picId, fb_id: fbUid}, gotTags);	
}
function gotTags(tags, stat){
	$('#tag_spinner').hide();
	if (stat == 'success'){
		if (tags.status == 'success'){
			gotTagsFlag = true;
			// Start mousemove on picture
			photoMouseMoveStart();
			tagsJson = tags.data;
			var tag_names = '<span class="note">In this photo:</span> ';
			var js = '<script language="javascript">\n$(document).ready(function(){\n';
			$.each(tagsJson, function(i,item){
				if (i > 0) tag_names += ', ';
				tag_names += '<span id="name_'+item.uid+'"><a href="http://www.new.facebook.com/profile.php?id='+item.uid+'" target="_blank">'+item.name+'</a>';
				tag_names += ' (<a href="http://apps.facebook.com/fourdevents/&friend='+item.uid+'" '+((inCanvas)?'target="_parent"':'target="_blank"')+'>pictures</a>';
				if (item.remove){ 
					tag_names += ', <a href="#" onclick="removeTag('+picId+', '+item.uid+'); return false;">remove</a>';
				}
				tag_names += ')</span>';
				// JS
				js += "$('#name_"+item.uid+"').hover(function(){showTag("+item.x+", "+item.y+")}, hideTag);\n";
			});
			js += '});\n</script>\n';
			tag_names += '<div class="frame_name_label"></div>\n'
			tag_names += js;
			$('.tag_names').html(tag_names);
			$('.tag_names').show();
		} else if (tags.status == 'error'){
			gotTagsFlag = false;
			$.jGrowl("Could not get tags for this photo. Try refreshing this page.", {header: 'Facebook Error', theme: 'jGrowl-error'});
		} else if (tags.status == 'no-tags') {
			// Remove tags_space
			$('#tag_space').hide();
			gotTagsFlag = false;
		} else if (tags.status == 'session') {
			invalidSession();
		}
	}
}
function photoMouseMoveStart(){
	if (!photoMouseMoveStarted){
		photoMouseMoveStarted = true;
		$('#photo').mousemove(photoMouseMove);
		$('#photo').mouseout(hideNameLabel);
	}
}
function removeTag(pic, friend){
	$.getJSON('http://4devents.ca/ajax/fb_tag_remove.php', {fb_id: fbUid, pic_id: pic, friend_id: friend}, removedTag);
}
function removedTag(json, status){
	if(window.console) {
		window.console.log("removeTag() RETURNED");
	}
	if (status == 'success'){
		if (json.status == 'success'){
			getTags();
			$.jGrowl("Tag removed");
		} else if (json.status == 'error') {
			$.jGrowl(json.error, {theme: 'jGrowl-error'});
		} else if (json.status == 'session') {
			invalidSession();
		}
	}
}
function showTag(x, y){
	var tagFrame = $('#tagframe');
	var frameSize = tagFrame.outerWidth();
	var halfFrame = Math.round(frameSize/2);
	var picPos = $('#photo').offset();
	tagFrame.css('left', x + picPos.left - halfFrame);
	tagFrame.css('top', y + picPos.top - halfFrame);
	tagFrame.show();		
}
function hideTag(){
	$('#tagframe').hide();
}
function photoMouseMove(e){
	if (gotTagsFlag && !tagMode){
		var picPos = $('#photo').offset();
		var photoX = e.pageX - picPos.left;
		var photoY = e.pageY - picPos.top;
		var frameSize = $('#tagframe').outerWidth();
		var halfFrame = Math.round(frameSize/2);
		var found = false;
		$.each(tagsJson, function(i,item){
			var thisX = parseInt(item.x);
			var thisY = parseInt(item.y);
			if (thisX > (photoX - halfFrame) && thisX < (photoX + halfFrame) && thisY > (photoY - halfFrame) && thisY < (photoY + halfFrame)){
				showNameLabel((thisX - halfFrame + picPos.left),(thisY + halfFrame + picPos.top - 20), item.name);
				found = true;
				return false;	
			}
		});
		if (!found){
			hideNameLabel();
		}
	}
}
function showNameLabel(x, y, name){
	var label = $('.frame_name_label');
	label.html('<span>'+name+'</span>');
	label.css('left',x);
	label.css('top',y);
	label.show();
}
function hideNameLabel(){
	$('.frame_name_label').hide();	
}
function invalidSession(){
	// Handle's invalid session
	if (newSesUrl){
		top.location.href = newSesUrl;
	}
}