// adds an ajax check to the email field for when the user is not logged in but is submitting a photo/ad to check if the email already exists
function setupEmailField() {
	var emailField = $('#emailField');
	emailField.blur(function() {
		$.get('/register/check_email', {email: emailField.val()}, function(ret, status) {
			if(ret == 'inuse') {
				$('#emailInUse').show().highlight(3000);
			} else {
				$('#emailInUse').hide();
			}
		});
	});
}
function setupPhotoForm() {	
	if($('#photoNewForm').length > 0) {
		$('#photoFileUpload').fileUpload ({
			uploader: '/uploadify.swf',
			script: '/photo/ajax_upload',
			scriptAccess: 'always',
			scriptData: {session: $('#sessionid').text()},
			cancelImg: '/images/uploadify/cancel.png',
			buttonImg: '/images/uploadify/button.jpg',
			rollover: true,
			width: 220,
			height: 27,
			auto: true,
			folder: '',
			onComplete: function(event, queue, file, response, data) {
				$('#uploadMessage').show().effect('highlight', {}, 3000);
				$('#uploadLabel').text('Change Photo to Upload:');
				var i = $('#uploadPreviewColumn img');
				i.show();
				i.attr('src', response+'?'+(new Date()).getTime());
				$('#photoNewForm input[type="submit"]').attr('disabled', false);
				$('#photoNewForm .pauseInstructions').hide();
			}, onSelectOnce: function() {
				$('#photoNewForm input[type="submit"]').attr('disabled', true);
				$('#photoNewForm .pauseInstructions').show();
			}, onInit: function() {
				$('#photoNewForm input[type="submit"]').attr('disabled', false);
			}
		});
		
		//setup tagger
		$('#photoNewForm .autocompleteTags').tagger('#photoFormTagsContainer', {ajax: {use: false}});
		$('#photoNewForm .autocompleteCompanies').tagger('#photoFormCompaniesContainer', {ajax: {use: false}});
	}
	
	if($('#photoEditPreview').length > 0) {
		// checks if the image has been uploaded yet, and if so, displays it
		var src = $('#photoEditPreview').attr('src');
		var done = false, first = true;
		var doneFunction = function() {
			if(!done) {
				if(first) {
					$('#photoEditPreviewColumn').show();
				} else {
					if($.browser.msie) {
						$('#notice').slideUp('slow');
						showFlash('#information', 'Your photo has been fully uploaded.  Refresh the page to see it.')
					} else {
						$('#photoEditPreviewColumn').css({width: 0}).show().animate({width: 200});
					}
				}
			}
			done = true;
		}
		var checkImgFunction = function() {
			var i = new Image();
			$(i).bind('load', doneFunction);
			i.src = src+'?'+(new Date()).getTime();
			
			if(!done) {
				setTimeout(function() {
					first = false;
					checkImgFunction();
				}, 1000);
			}
		}
		checkImgFunction();
		
		
		// setup tagger
		$('#photoEditForm .autocompleteTags').each(function() {
			var field = $(this);
			var id = field.attr('photoid');
			field.tagger('#photoFormTagsContainer', {ajax: {
				urlBase: '/photo/', 
				extraParams: '&photo_id='+id
			}});
		});
		
		$('#photoEditForm .autocompleteCompanies').each(function() {
			var field = $(this);
			var id = field.attr('photoid');
			field.tagger('#photoFormCompaniesContainer', {ajax: {
				urlBase: '/photo/',
				saveAction: 'add_company?text=%text',
				updateAction: 'edit_company?oldText=%oldText&text=%text',
				destroyAction: 'remove_company?text=%text',
				extraParams: '&photo_id='+id
			}});
		});
	}
}
function setupWantAdForm() {
	//shows the correct text for the terms based on if they have saved or previews terms or what not
	if($('#adFileUploadContainer').length > 0) {
		var updateState = function() {
			if($('#termsOtherButton:checked').val() == 'other') {
				$('#adFileUploadContainer').show();
			} else if ($('#termsDefaultButton:checked').val() == 'default') {
				$('#adFileUploadContainer').hide();
			} else if ($('termsLinkText').html().length > 0) {
				$('#adFileUploadContainer').show();
			} else {
				$('#adFileUploadContainer').hide();
			}
		}
		$('#termsDefaultButton, #termsOtherButton').parent().find('a').click(updateState);
		updateState();
	}
	$('#adFileUpload').fileUpload ({
		uploader: '/uploadify.swf',
		script: '/want-ad/ajax_upload',
		scriptAccess: 'always',
		scriptData: {session: $('#sessionid').text()},
		cancelImg: '/images/uploadify/cancel.png',
		buttonImg: '/images/uploadify/adButton.jpg',
		rollover: true,
		width: 184,
		height: 27,
		auto: true,
		folder: '',
		onComplete: function(event, queue, file, response, data) {
			$('#termsLinkText').show().html(response).effect('highlight', {}, 3000);
			$('.adForm input[type="submit"]').attr('disabled', false);
			$('.pauseInstructions').hide();
		}, onSelectOnce: function() {
			$('.adForm input[type="submit"]').attr('disabled', true);
			$('.pauseInstructions').show();
		}, onInit: function() {
			$('.adForm input[type="submit"]').attr('disabled', false);
		}
	});
	
	// setup tagger
	$('#adNewForm .autocompleteTags').tagger('#adFormTagsContainer', {ajax: {use: false}});
	$('#adEditForm .autocompleteTags').each(function() {
		var field = $(this);
		var id = field.attr('adid');
		field.tagger('#adFormTagsContainer', {ajax: {
			urlBase: '/want-ad/',
			extraParams: '&ad_id='+id
		}});
	});
}

// popups for sending a private message to users
function setupMessageFormPopups() {
	$('a.sendMessageLink').click(function(clickEvent) {
		$('body').append('<div id="glassboxContentLoader"></div>');
		$('#glassboxContentLoader').hide();
		var u = $(this).attr('href');
		$.get(u, {}, function(html, status) {
			$('#glassboxContentLoader').html(html);
			var glassbox = $('#glassboxContentLoader').glassbox();
			var frm = glassbox.find('form');
			setupJqtransform();
			frm.submit(function(submitEvent) {
				$.get(frm.attr('action')+'?'+frm.serialize(), {}, function(data, status) {
					showFlash('#notice', data);
				}, 'html');
				
				glassbox.fadeOut('normal', function() { glassbox.remove(); });
				submitEvent.preventDefault();
				return false;
			});
		}, 'html');
		clickEvent.preventDefault();
		return false;
	});
}
function setupLoginPopups() {
	$('a.loginLink, a.requiresLoginLink').click(function(clickEvent) {
		$this = $(this);
		var u = $this.attr('href');
		
		//check if they are going 
		if($this.hasClass('requiresLoginLink') && logged_in) {
			return true;
		} else {
			u = '/login';
		}
		
		//make ajax request to load the login form
		$('body').append('<div id="glassboxContentLoader"></div>');
		$('#glassboxContentLoader').hide();
		$.get(u, {}, function(html, status) {
			$('#glassboxContentLoader').html(html);
			var glassbox = $('#glassboxContentLoader').glassbox();
			var frm = glassbox.find('form');
			setupJqtransform();
			frm.submit(function(event) {
				var data = {};
				frm.find('input[type="text"], input[type="password"], input[type="checkbox"]').each(function() {
					data[$(this).attr('name')] = $(this).val();
				});
				
				$.post(frm.attr('action'), data, function(data, textStatus) {
					// result has this form: <success/failure>,<user type>,<user id>
					bits = data.split(',');
					if(bits[0] == 'success') {
						logged_in = true;
						
						// if this was a link that was shown but required login, then redirect them to that page
						if($this.hasClass('requiresLoginLink')) {
							window.location.replace($this.attr('href'))
						} else if($this.hasClass('refreshOnLogin')) {
							var bits = (window.location+'').split('#');
							window.location.replace(bits[0]);
						} else if(bits[3].length > 0) {
							window.location.replace(bits[3]);
						} else {
							showFlash('#notice', 'You were successfully logged in.');
							glassbox.fadeOut('normal', function() { glassbox.remove(); });
							
							$('.showOnLogin').show();
							$('.hideOnLogin').hide();
							
							if(bits[1] == 'Photographer')
								$('.showOnPhotographerLogin').show();
							if(bits[1] == 'Advertiser')
								$('.showOnAdvertiserLogin').show();
								
							$('.showOn'+bits[2]+'Login').show();
							
							setupJqtransform();
						}
					} else {
						showFlash('#warning', 'Invalid email/password combination.');
						frm.find('.loginError').show();
					}
				}, 'text');
				
				//dont let the form get saved
				event.preventDefault();
				return false;
			});
		}, 'html');
		// dont let the link go through
		clickEvent.preventDefault();
		return false;
	});
}