var PHREETINGS_URL, PHREETING_NAME;

(function(){

// for Safari Mobile, wire up clicking -> selection, skipping dragging and preview
if (/Mobile.*Safari/.test(navigator.userAgent)) {
	Photo.prototype.appendTo = function(el){
		var me = this;

		if (!me.visible) return;

		me.preload();
		
		me.container
			.click(function(){
				select_photo(this);
			})
			.append(me.image)
			.appendTo(el);
	};
	
	// and hide instructions
	$(function(){
		$('div.instructions').remove();
		$('#flickr-radio').click();
		$('div.source-select').hide();
	})
}

var photo_id, photo_url, photo_owner, photo_source, card_id, card_url, card_search,
	card_color = 'FFFFFF', save_timer, ajax_request, orig_card_text, orig_photo_text;

$(function(){
	set_url_name();
	
	$('div.source-select input').click(set_url_name);

	if (location.href.indexOf('dev') != -1) PHREETINGS_URL += 'dev/';
	
	var orig_card_text = $('#card-text').val(),
		orig_photo_text = $('#card-photo').html();

	$('#cardui').Droppable({
		accept: 'photo',
		hoverclass: 'hover',
		tolerance: 'intersect',
		ondrop: function(pic){
			select_photo(pic);
		}
	});

	$('#card-text, #card-search')
	.focus(function(){
		if (this.value == this.title)
			this.value = '';
	})
	.blur(function(){
		if (this.value.replace(/^[\s\n]*$/,'') == this.title)
			this.value = this.title;
	});

	$('#card-color td').click(function(){
		$('#card-color td').removeClass('selected');
		$(this).addClass('selected');
		
		card_color = $(this).attr('id').split('_')[1];
		
		$('#cardui')[0].className = 'color-' + card_color;
	})

	$('#card-new').click(function(){
		card_id = null;
		$('#card-photo').removeClass('has-photo').html(orig_photo_text);
		$('#card-url').css('visibility', '')
		$('form#cardui')[0].reset();
		$('#card-send').addClass('disabled');
		
		// save the card (blank) to get a new key
		save_card();
		
		reset_save_timer();
		
		return false;
	});

/*
	$('#card-save').click(save_card);

	$('#card-preview')
		.addClass('disabled')
		.click(function(){
			if (card_url && !$(this).is('.disabled')) {
				save_card();
				window.open(card_url);
			}
		});
*/

	$('#card-send')
		.addClass('disabled')
		.click(function(){
			if (!$(this).is('.disabled')) {
				$(this).addClass('disabled');
				save_card(click_send);
			}
		});

	$('form#cardui').submit(function(){
		return false;
	});

	reset_save_timer();

	// save the card (blank) to get a new key
	save_card();
});

function set_url_name(){
	VREETING = ($('div.source-select input:checked')[0].id == 'youtube-radio');

	if (VREETING) {
		SEARCH_FUNCTION = youtube_search;
		SINGLE_SEARCH = 'youtube';
		PHREETINGS_URL = 'http://footagesandbox.com/card/';
		PHREETING_NAME = '"vreeting" (video + greeting)';

		$('#card-search').show();
	} else {
		SEARCH_FUNCTION = FLICKR_SEARCH;
		SINGLE_SEARCH = 'flickr';

		PHREETINGS_URL = 'http://phreetings.com/',
		PHREETING_NAME = '"phreeting" (photo + greeting)';

		$('#card-search').hide();
	}
	
	save_card();
}


function click_send() {
	if (window.FACEBOOK) {
		top.location = 'http://apps.facebook.com/phreetings/preview.php?p=' + card_id;
	}
}
	
function save_card(callback) {	
	if (ajax_request) ajax_request.abort();

	var msg = $('#card-text').val();
	if (msg == orig_card_text) msg = '';

	ajax_request = $.post('save.php', {
		card_id: card_id || '',
		photo_id: photo_id || '',
		photo_url: photo_url || '',
		photo_owner: photo_owner || '',
		photo_source: photo_source || '',
		card_search: $('#card-search').val() || '',
		color: card_color || 'FFFFFF',
		message: msg,
		fbid: window.FB_USER || ''
	}, function(code){
		card_id = code;
		
		$('#card-send')
			.removeClass('disabled')
		
		if (!window.FACEBOOK) {
			card_url = PHREETINGS_URL + code;

			$('#card-send').attr('href', 'mailto:?subject='
				+ encodeURIComponent('someone has sent you a ' + PHREETING_NAME)
				+ '&body='
				+ encodeURIComponent(card_url)
				+ encodeURIComponent("\r\n\r\nclick the link above or copy+paste it into your browser\r\n\r\n_______________________________________\r\n")
				+ encodeURIComponent("make your own " + PHREETING_NAME + "\r\nfrom millions of " + (VREETING ? 'videos' : 'photos') + " at " + PHREETINGS_URL)
			);
		} else {
			card_url = 'http://apps.facebook.com/phreetings/card.php?p=' + code;
		}
		
		$('#card-preview').removeClass('disabled');
		
		$('#card-url')
			.css('visibility', 'visible')
			.val(card_url);

		ajax_request = null;
		
		if (callback) callback();
	});
}

function reset_save_timer() {
	clearInterval(save_timer);
	save_timer = setInterval(function(){
		// don't save empty cards
		if (!photo_id && $('#card-text').val() == orig_card_text) return;

		save_card(function(){
			$('#card-notify').html('auto-saved').css({
				visibility: 'visible',
				opacity: 1
			});
			setTimeout(function(){
				$('#card-notify').animate({
					opacity: 0
				}, 'slow', function(){
					$(this).css('visibility', 'hidden');
				});
			}, 5000)
		});
	}, 20 * 1000); // every 20 seconds
}

function get_med_size(photo) {
	var d = photo.data.flickr;
	return 'http://farm'+d.farm+'.static.flickr.com/'+d.server+'/'+d.id+'_'+d.secret+'.jpg';
}

function select_photo(pic) {
	if (VREETING) {
		photo_id = pic.id.substring('video_'.length)
		photo_url = $('img', pic).attr('src');
		photo_source = 'youtube';
		
		$('#card-search').val($('#text').val());
	}
	else {
		if (!SEARCHES || !SEARCHES[0]) 
			return;
		var photo = SEARCHES[0].find_pic(pic);
		if (!photo) 
			return;
		
		photo_id = photo.data.id;
		photo_url = get_med_size(photo);
		photo_owner = photo.data.flickr.ownername;
		photo_source = 'flickr';
	}
	
	$('#card-photo').addClass('has-photo').empty().append('<img src="' + photo_url + '"/>');
	
	// if it was a preview, remove
	$('body > div.preview').remove();	
}

})();
