/**
 * Form erase
 */
var formErase = function(el) {
	var mEl = $(el);
	var origVal = mEl.getProperty('value');
		mEl.set('value','');
		mEl.addEvent('blur', function() {
			if(mEl.getProperty('value') == '') {
				mEl.set('value', origVal);
			};
		}
	);
};
window.addEvent('domready', function() {
	$('wrapper').getElements('input.formerase').addEvent('focus', function() {
	    formErase(this);
	});
	if ($('loginlink')) {
		$('loginlink').addEvent('click', function(event) {
			event.stop();
			loginModal('refresh');
		});
	}
});
/**
 * Modal functions
 */
function alignModal(width, height) {
	var modal = $('modalBox');
	modal.setStyle('width', width + 'px');
	modal.setStyle('height', height + 'px');
	
	var scroll = window.getScroll();
	var size = window.getSize();
	modal.setStyle("top", scroll.y + ((size.y - modal.getHeight()) / 2));
	modal.setStyle("left", scroll.x + ((size.x - modal.getWidth()) / 2));
	$('modalUnderlay').setStyles({left: 0, top: 0, right:0, height: $('wrapper').getHeight(), opacity: .5});
}

/* Hide for use by close button and any other element that needs to close it */
function hideModal() {
	$('modalUnderlay').setStyle('display', 'none');
	$('modalBox').setStyle('display', 'none');
	$('modalContent').innerHTML = "";
	if ($('cfAuthIframe')) {
		$('cfAuthIframe').destroy();
	}
	modalLoading(false);
}
function showModal(width, height) {
	$('modalUnderlay').setStyle('display', 'block');
	$('modalContent').innerHTML = "";
	$('modalBox').setStyle('display', 'block');
	alignModal(width, height);
	modalLoading(true);
}
function modalLoading(isLoading) {
	if (isLoading) {
		$('modalContentLoading').setStyle('display', 'block');
		$('modalContentLoading').setStyle('opacity', '.5');
	} else {
		$('modalContentLoading').setStyle('display', 'none');
	}
}
function injectModal(content) {	
	if (typeof content == "string") {
		$('modalContent').innerHTML = content;
	} else {
		$(content).injectInside($('modalBox'));
	}
}
var authR = null; // return page
/**
 * Auth window and modal
 */
var authWindow = function(href, width, height) {
	var newAuthWindow = window.open(href,'_CFauthWindow','toolbar=0,scrollbars=0,location=1,statusbar=1,menubar=0,resizable=0,width='+width+',height='+height);
	newAuthWindow.focus();
	return false;
};
/**
 * Login modal
 */
var loginModal = function(action) {
	// authR stores where user is trying to go after authentication
	authR = action;
	showModal(576, 440);
	var loginContent = new Request.HTML({
		url: cfBase + '/login/modal',
		method: 'GET',
		onSuccess: function(html) {
			injectModal(this.response.html);
			modalLoading(false);
			/* fixes the enter button problem in IE */
			$('loginModalForm').getElements('input').addEvent('keydown', function(event) {
				if (event.key == 'enter') {
					loginModalSubmit(action,event);
				}
			});
			$('modalAuthWinFacebook').addEvent('click', function(event) {
				event.stop();
				authWindow(cfBase + '/auth/facebook-login',940,410);
			});
			$('modalAuthWinTwitter').addEvent('click', function(event) {
				event.stop();
				authWindow(cfBase + '/auth/twitter-login',850,380);
			});
			$('modalAuthWinLive').addEvent('click', function(event) {
				event.stop();
				authWindow(cfBase + '/auth/live-login',850,480);
			});
			/* normal submit addevent on the login form */ 
			$('loginModalForm').addEvent('submit', function(event) {
				loginModalSubmit(action,event);
			});
			/* handle lost pw click */
			$('loginModalLostpw').addEvent('click', function(event) {
				event.stop();
				lostpwModal(action);
			});
			/* handle join link to passoff return url */
			$('loginModalJoinLink').addEvent('click', function(event) {
				event.stop();
				var joinhref = cfBase + '/join';
				if (action == 'refresh') {
					joinhref = joinhref + '?r=' + escape(unescape(window.location.pathname));
				} else if (action.href) {
					joinhref = joinhref + '?r=' + escape(action.href);
				}
				window.location.href = joinhref;
				return;
			});
			/* focus username */
			$('loginModal_login').focus();
		}
	}).send();
	return false;
};
var loginModalSubmit = function(action,event) {
	event.stop();
	modalLoading(true);
	var loginProcessRequest = new Request.JSON({
		method: 'POST',
		url: $('loginModalForm').action,
		onComplete: function(response) {
			if (response.success) {
				if (action.href) {
					window.location.href = action.href;
				} else {
					window.location.href = unescape(window.location.pathname);
				}
				return false;
			} else {
				$('loginModalErrors').innerHTML = response.error;
				$('loginModal_login').focus();
			}
			modalLoading(false);
		}
	}).post($('loginModalForm'));
	return false;
};
/**
 * Lostpw modal
 */
var lostpwModal = function(action) {
	modalLoading(true);
	var formRequest = new Request.HTML({
		url: cfBase + '/login/lostpw-modal',
		method: 'GET',
		onSuccess: function(html) {
			/* inject the login form */
			injectModal(this.response.html);
			/* fixes the enter button problem in IE */
			$('lostpwModalForm').getElements('input').addEvent('keydown', function(event) {
				if (event.key == 'enter') {
					lostpwModalSubmit(action,event);
				}
			});
			/* normal submit addevent on the login form */ 
			$('lostpwModalForm').addEvent('submit', function(event) {
				lostpwModalSubmit(action,event);
			});
			/* handle links back to login form */
			$$('.modalLinkLogin').each( function(element) {
				element.addEvent('click', function(event) {
					event.stop();
					loginModal(action);
				});
			});
			/* focus email */
			$('lostpwModal_email').focus();
			/* hide loading pane */
			modalLoading(false);
		}
	}).send();
	return false;
};
var lostpwModalSubmit = function(action,event) {
	event.stop();
	modalLoading(true);
	var lostpwProcessRequest = new Request.JSON({
		method: 'POST',
		url: $('lostpwModalForm').action,
		onComplete: function(response) {
			if (response.success) {
				$('lostpwModalErrors').innerHTML = '';
				$('lostpwModalSuccess').setStyle('display', 'block');
				$('lostpwModalSuccess').setStyle('visibility', 'visible');
			} else {
				$('lostpwModalSuccess').setStyle('display', 'none');
				$('lostpwModalSuccess').setStyle('visibility', 'hidden');
				$('lostpwModalErrors').innerHTML = response.error;
				$('lostpwModal_email').focus();
			}
			modalLoading(false);
		}
	}).post($('lostpwModalForm'));
	return false;
};
/**
 * Initialize modal
 */
var modalInit = function() {
	/* pass any links that require login thru auto modal */
	$(document.body).getElements('a.reqlogin').addEvents({
	    'click': function(event) {
	    	event.stop();
	        loginModal(this);
	    }
	});
	/* handle modal close */
	if ($('modalClose')) {
		$('modalClose').addEvent('click', function(event) {
			event.stop();
			hideModal();
		});
	}
};
window.addEvent('domready', function(){
	if ($('modalClose')) modalInit();
});
/**
 * Search from header
 */
window.addEvent('domready', function() {
	$('searchsubmit').addEvent('click', function() {
		if ($('searchterm').getProperty('value') == 'Search the CrowdFire' || $('searchterm').getProperty('value') == '') {
			$('searchterm').set('value', ' ');
			$('searchterm').focus();
			return false;
		};
		return true;
	});
	$('searchform').addEvent('submit', function() {
		if ($('searchResultsForm') && $('searchResultsSearchQuery') && !$('searchResultsFormUnbind')) {
			$('searchResultsSearchQuery').value = $('siteSearch').value;
			$('searchResultsForm').submit();
			return false;
		}
		return true;
	});
});
/**
 * Search results pagination click
 */
var searchResultsChangePage = function(pagenum) {
	$('searchResultsPage').value = pagenum;
	$('searchResultsForm').submit();
	return false;
};
