// demo code is at bottom of file 

$(function(){	
	$('.box_grey').css('visibility', 'visible');
	$('.form input').css('visibility', 'visible');
	// setup label.inside to dissapear on input focus
	$('input').focus(function(e){
		var id = $(this).attr('id');
		$('label.inside[for="'+ id +'"]').css('visibility', 'hidden');
	}).blur(function(e){
		var id = $(this).attr('id');
		if ($(this).val().length == 0 || $(this).val() == ' '){
			$('label.inside[for="'+ id +'"]').css('visibility', 'visible');
		}
	});
	// check to see it label.inside should be hidden on refresh
	$('input').each(function(){
		if ($(this).val().length > 0 && $(this).val() != ' '){
			var id = $(this).attr('id');
			$('label.inside[for="'+ id +'"]').css('visibility', 'hidden');
		}
	});
	// set callouts to same height
	var calloutHeight = 0;
	var bigDiv = '';
	$('div#callouts div.box div.content div.inside div.box_content_div').each(function(){
		//if ($(this).height() > calloutHeight) calloutHeight = $(this).height();
		if($(this).outerHeight() > 225){
			bigDiv = $(this).get(0);
			bigDiv.style.overflowY = 'scroll';
			bigDiv.style.width = '266px';
			bigDiv.style.height = '167px';
		}
		calloutHeight = 232;
	});
	$('div#callouts div.box div.content div.inside').height(calloutHeight);
	
	// set home add/remove destinations (traveling to) currently just duplicates first traveling_to select 
	$('a#visabox_add_destination').click(visaAddDestination);
	$('a#visabox_remove_destination').click(visaRemoveDestination);
	// adjust div#intro height for div.visa
	setTimeout(adjustIntroHeight, 100); // use settimeout because of IE6
	// passport multiple destinations
	$('ul.multiple a').click(function(){
		$('ul.multiple a').parent('li').removeClass('current');
		$('div.multiple').removeClass('current');
		$(this).parent('li').addClass('current');
		$('div.multiple.'+ $(this).attr('class') +'').addClass('current');
		return false;
	});
	// passport document rollovers
	$('ol.documents li span').simpletip({
		fixed: true,
		hideTime: 1,
		offset: [15, 15],
		showTime: 1,
		boundryCheck: true,
		onBeforeShow: function(e){
			var name = this.getParent().parent().attr('class');
			// pulls content from div with same class
			var content = $('div.tooltips div.'+ name).html();
			this.update(content);
		}
	});
	//ETA countries rollover
	$('.countries span').simpletip({
		fixed: false,
		hideTime: 1,
		offset: [15,-100],
		showTime: 1,
		onBeforeShow: function(e){
			var name = this.getParent().parent().attr('class');
			// pulls content from div with same class
			var content = $('div.tooltips div.'+ name).html();
			this.update(content);
		}
	});
	//cibt-emad 7/26/10
	$('.whatsthis span').simpletip({
			fixed: false,
			hideTime: 1,
			offset: [-150,-250],
			showTime: 1,
			onBeforeShow: function(e){
				var name = this.getParent().parent().attr('class');
				// pulls content from div with same class
				var content = $('div.tooltips div.'+ name).html();
				this.update(content);
			}
	});
	//cibt-emad 7/19/10 for office dropdown
	$("#office").change(function(){
			var selectedOfficeCode = this.options[this.selectedIndex].value;
			location.href="http://www.cibt.com/Router.aspx?SetRoute=" + selectedOfficeCode;
	});
	
	changeCurrentLink();
	
	$( '.login_link' ).click( function( e )
	{
		e.preventDefault();
		e.stopPropagation();
		
		// Show the user login form
		showUserLoginForm();
	} );
	
	if ($.browser.msie && $.browser.version.substr(0,1) <= 9)//IE9 fix for wrapping of debtor description for siemens-debtor with long text
	{
		$( '#header div.office #account_logout' ).css( 'width', '275px' );
	}
	
});

// select disabling/enabling - make sure to use these functions as the forms.js file adds in the necessary "pretty" calls

function toggleSelect(div, enable){
	// div = containing div for select
	var select = div.children('select');
	if (enable) enableSelect(select);
	else disableSelect(select);
}

function enableSelect(select){
	select.removeAttr('disabled');
}

function disableSelect(select){
	select.attr('disabled', 'disabled');
}

// home add/remove destinations (traveling to)

var limitTravelingTo = 3;

function visaAddDestination(e){
		var totalTravelingTo = 0;
	
	for(i=0;i<3;i++){
		var div = $("div.visa div#traveling_to_"+i).get(0);
		if(div.style.display != 'none'){
			totalTravelingTo++;
		}
	}
	
	$( '#traveling_toSelect0' ).css( 'margin', '15px 0px 0px 0px' );
	
	$(".one_destination_text").hide();
	$(".multiple_destination_text").show();
	$(".extra_destination_labels").show();
	$(".extra_destinations").show();
	
	if (totalTravelingTo <= limitTravelingTo){
		$('a#visabox_remove_destination').show();
				
		$("div.visa div#traveling_to_"+(totalTravelingTo)).show();
		$("div.visa label#traveling_to_label_"+(totalTravelingTo)).show();
		$("div.visa div#traveling_for_"+(totalTravelingTo)).show();
		$("div.visa label#traveling_for_label_"+(totalTravelingTo)).show();
		
		if (typeof(replaceForms) == 'function') replaceForms();
		
		if (totalTravelingTo == limitTravelingTo - 1) $('a#visabox_add_destination').hide();
		adjustIntroHeight();
	}
	if (typeof(adjustVirginHeight) == 'function') adjustVirginHeight();
	return false;
}

function visaRemoveDestination(e){
		
	var totalTravelingTo = 0;
	
	for(i=0;i<3;i++){
		var div = $("div.visa div#traveling_to_"+i).get(0);
		if(div.style.display != 'none'){
			totalTravelingTo++;
		}
	}
	
	$( '#traveling_toSelect0' ).css( 'margin', '0' );
		
	if(totalTravelingTo == 2){
		$('a#visabox_remove_destination').hide();
		$(".one_destination_text").show();
		$(".multiple_destination_text").hide();
		$(".extra_destination_labels").hide();
		$(".extra_destinations").hide();
	}
	
	if(totalTravelingTo > 1 ){
	var select = $("#traveling_toSelect"+(totalTravelingTo - 1)).get(0);
	select.selectedIndex = 0;
	
	var select = $("#traveling_forSelect"+(totalTravelingTo - 1)).get(0);
	select.selectedIndex = 0;
	
	
	if (typeof(replaceForms) == 'function') replaceForms();
	
	$("div.visa div#traveling_for_"+(totalTravelingTo - 1)).hide();
	$("div.visa label#traveling_for_label_"+(totalTravelingTo - 1)).hide();
	$("div.visa div#traveling_to_"+(totalTravelingTo - 1)).hide();
	$("div.visa label#traveling_to_label_"+(totalTravelingTo - 1)).hide();
	
	$('a#visabox_add_destination').show();
	adjustIntroHeight();
	if (typeof(adjustVirginHeight) == 'function') adjustVirginHeight();
	}
	return false;
}

function resetVisaSearchBox()
{
	var totalTravelingTo = 0;
	for(i=0;i<3;i++){
		var div = $("div.visa div#traveling_to_"+i).get(0);
		if(div.style.display != 'none'){
			totalTravelingTo++;
		}
	}
	visaRemoveDestination();
	visaRemoveDestination();
	
	$('select#traveling_toSelect0').find('option:first').attr('selected', 'selected');
	for(i=0;i<totalTravelingTo;i++){
		var forDiv = $("div.visa div#traveling_for_"+i);
		forDiv.find('select').children('option:not(:first)').remove();
		var toDiv = $("div.visa div#traveling_to_"+i);
		toDiv.find('option:first').attr('selected', 'selected');
	}
}

function adjustVisaText(){
	var totalTravelingTo = 0;
	
	for(i=0;i<3;i++){
		var div = $("div.visa div#traveling_to_"+i).get(0);
		if(div.style.display != 'none'){
			totalTravelingTo++;
		}
	}
	
	$('a#visabox_add_destination').show();
	$('a#visabox_remove_destination').show();
	
	if(totalTravelingTo > 1){
		$(".one_destination_text").hide();
		$(".multiple_destination_text").show();
		$(".extra_destination_labels").show();
		$(".extra_destinations").show();
		
		if(totalTravelingTo == 3){
			$("div.visa div#traveling_to_2").show();
			$("div.visa label#traveling_to_label_2").show();
			$("div.visa div#traveling_for_2").show();
			$("div.visa label#traveling_for_label_2").show();
			$('a#visabox_add_destination').hide();
		}
		
		$("div.visa div#traveling_to_1").show();
		$("div.visa label#traveling_to_label_1").show();
		$("div.visa div#traveling_for_1").show();
		$("div.visa label#traveling_for_label_1").show();
		
	}else{
		$(".one_destination_text").show();
		$(".multiple_destination_text").hide();
		$(".extra_destination_labels").hide();
		$(".extra_destinations").hide();
		$('a#visabox_remove_destination').hide();
	}
	
	if (typeof(adjustVirginHeight) == 'function') adjustVirginHeight();
}

function adjustIntroHeight(){
	var offset = 20;

	var fourofour = document.getElementById( 'fourofourMessage' );
	var fourofourVisible = $( fourofour ).outerHeight() > 0; 
	if( fourofourVisible )
	{
		if( $.browser.msie )
			offset += 45;
		else
			offset += 65;
	}// End if

	$('div#intro').height($('div.visa').outerHeight() + offset);
	
	if( fourofourVisible && $.browser.msie )
		$('div#intro').css( 'margin-top', '-10px' );
}

// simple debug function so using firebug console doens't error in other browsers
function debug(d){
	if (typeof(console) != 'undefined') console.debug(d);
	else alert(d);
}

// function to extract query strings
$.urlParam = function(name){
	var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
	if (!results) { return 0; }
	return results[1] || 0;
}

/* ---- DEMO CODE - for demo/testing purposes ----- */
$(function(){
	// home submit shows lightbox example
	$('#needAVisaSubmit').click(function(){
		
		//we want to be able to show the lightbox potentially again on results page if they do a new search 
		//... (meaning they click on this submit button which opens up a visa search box)
		eraseCookie('lightbox');
		
		var formData = $('#needAVisa').serialize();
		formData = formData.replace('%5B','[');
		formData = formData.replace('%5D',']');

		$.fn.colorbox({ //changed to click function (instead of load) to allow sending of form data
			href: "/ajax/ajax.visaPopup.php?"+formData,
			transition: 'none',
			speed: 100,
			width: 610,
//			height: 340,
			innerWidth: '0px',
//			innerHeight: '340px',
			initialWidth: '430px',
			initialHeight: '0px',
			opacity: 0.7,
			scrolling: false,
			onLoad: function()
			{
				// Hide the scrollbars in IE
				$( '#cboxLoadedContent' ).hide();
			},
			onComplete: function(){
				$( '#cboxLoadedContent' ).show();
				$(this).colorbox.resize();
				if (typeof(replaceForms) != 'undefined') replaceForms();
				$('div#cboxLoadedContent input[type="submit"]').click(function(){
					//window.location.href = 'requirements.php';
					$("#moreVisaInfoRequired").submit();
					return false;
				});
			}
		}).resize();
	});
	
	$('#forgotMyCIBTAccount').click(function(){
		$.fn.colorbox({ //changed to click function (instead of load) to allow sending of form data
			href: "/ajax/ajax.forgotCIBTAccount.php",
			width: 550,
			height: 350,
			opacity: 0.7
		});
	});
	
	// home quick visa
	$('div.quick_check_search').hide();
	$('select.quick_check').change(function(e){
		//$(".quick_check_search").load('/ajax/ajax.visaQuickSearch.php?text='+$(this).val());
		window.location = '/visa-quick-check.php#'+$(this).val();
		$('div.quick_check_initial').html('<img src="' + window.getResourcePath() + '/images/colorbox/loading.gif" alt="" />');
		//$('div.quick_check_initial').hide();
		//$('div.quick_check_search').show();
		//$('div#quick_check_search span.country').text($(this).val());
	});
	
	$('a.quick_check_again').click(function(){
		$('div.quick_check_initial').show();
		$('div.quick_check_search').hide();
		return false;
	});
	
	// visa_step1 passport radio buttons
	$('input[name="passport"]:checked').each(function(){
		var div = $(this).parents('div')[0];
		div = $(div);
		toggleSelect(div, true);
	});
	$('input[name="passport"]').change(function(e){
		var div = $(this).parents('div')[0];
		div = $(div);
		toggleSelect(div, true);
		$('input[name="passport"]:not(:checked)').each(function(){
			var div = $(this).parents('div')[0];
			div = $(div);
			toggleSelect(div, false);
		});
	});
});

 $(document).ready(function() {
	$( '.multiple_email_instructions_link' ).click( function()
	{
		$( this.parentNode ).find( '.multiple_email_instructions' ).show();
		$( this ).hide();
	} );

    $(".calendar_date_selector").datepicker({
	    showOn: 'both',
		buttonImage: window.getResourcePath() + '/images/icons/calendar.gif',
		buttonImageOnly: true,
		buttonText: ''
//		dateFormat:'dd-mm-yy'
    });
    
	$( '.status_indicator' ).click( function( e )
	{
		var breakTag = document.createElement( 'br' );
		$(this.parentNode).append(breakTag);
		
		var imgTag = $("#loadingRedCircle").html();
		$(this.parentNode).append(imgTag);

		return true;
	} );
    
    $( '.single_click' ).click( function()
    {
    	$( this ).unbind( 'click' ).click( function( e )
    	{
    		e.stopPropagation();
    		e.preventDefault();
    		return false;
    	} );
    	return true;
    } );
	
	// Plug into our pdf links
	$( '.pdflink' ).click( function( e )
	{
		// Stop the click event's default behaviour
		e.stopPropagation();
		e.preventDefault();
		
		// Get the href and create a new window/tab that will show the loading
		// page and the pdf
		window.open( '/kit-download.php?t=' + this.href );
	} );
 });


function showonlyone(thechosenone) {
      var country = document.getElementsByTagName("div");
            for(var x=0; x<country.length; x++) {
                  name = country[x].getAttribute("name");
                  if (name == 'country') {
                        if (country[x].id == thechosenone) {
                        country[x].style.display = 'block';
                  }
                  else {
                        country[x].style.display = 'none';
                  }
            }
      }
}



function changeLang(lang){
	$.ajax({
	   type: "GET",
	   url: "/ajax/ajax.changeLang.php",
	   data: "lang="+lang,
	   dataType: 'json',
	   success: function(msg)
	   {
		if ( msg.url == '' || msg.url == null || msg.url == undefined)
			location.reload(true);
		else
			window.location = msg.url;
	   }
 	});
}

function logout(){
	$.ajax({
	   type: "POST",
	   url: "/ajax/ajax.logout.php",
	   data: "",
	   success: function(msg){
	     window.location = '/index.php?logout';
	   }
 	});
}

function fillPassportStates(countryCode,codeType){
 	$.ajax({
 	  type: "POST",	
	  url: "/ajax/ajax.fillStates.php",
	  data: "countryCode="+countryCode+"&codeType="+codeType,
	  dataType: 'script',
	  success: function(msg){
	     fillDestCountries(countryCode,codeType)
	  }
	});
}

function fillDestCountries(countryCode,codeType){
 	//$("#jsBox").load("/ajax/ajax.fillDestinations.php", "countryCode="+countryCode+"&codeType="+codeType);
	$.ajax({
 	  type: "POST",	
	  url: "/ajax/ajax.fillDestinations.php",
	  data: "countryCode="+countryCode+"&codeType="+codeType,
	  dataType: 'script'
	});
}

function fillPurposes(id,startCountry,localCode,destination,nationality){
	var container = $( '#' + id );
	$.ajax({
 	  type: "POST",	
	  url: "/ajax/ajax.fillPurposes.php",
	  data: "id="+id+"&startCountry="+startCountry+"&localCode="+localCode+"&destination="+destination+"&nationality="+nationality,
	  dataType: 'script',
	  success: function()
		{
			container.parent().next().children().find('select').enableSelection();
			container.parent().next().children().find('select').parent().children('#loadingImage').remove();
		}
	});
	container.parent().next().children().find('select').disableSelection();
	var loadingHTML = $('#main #loadingDiv').html();
	container.parent().next().children().find('select').parent().append(loadingHTML);
}

function checkUncheckHasAccount(accountNumber){
	var yesButton = $("#account_yes").get(0);
	var noButton = $("#account_no").get(0);
	
	if($.trim(accountNumber) == ""){
		yesButton.checked = false;
		noButton.checked = true;
	}else{
		noButton.checked = false;
		yesButton.checked = true;
	}
}

function checkVisaFields(){
			
	var success = true;
	$('.selField').each(function(i,s){
		if(s.value == ""){
			success = false;
		}
	});
	if(success){
		$("#moreVisaInfoRequired").submit();
		return true;
	}else{
		alert("Please choose a value for each.");
		return false;
	}
}


function hideShowContact(checked){
	if(checked){
		$("#enterANewContact").slideUp(500);
	}else{
		$("#enterANewContact").slideDown(500);
	}
}

function enableTravelerSelect(is_checked,id,type){
	/*		
	var renew = $("#passport_renew"+id+"div .select");
	var none = $("#passport_none"+id+"div .select");
	var passport_number = $("#passport_number"+id);
	var passport_expiration = $("#passport_expiration"+id);
	
	if(type=='renew'){
		if(is_checked){
			renew.removeClass('disabled');
			none.addClass('disabled');
		}else{
			renew.addClass('disabled');
			none.removeClass('disabled');
		}
		
		passport_number.slideDown(250);
		passport_expiration.slideDown(250);
		
	}else if(type=='none'){
		if(is_checked){
			none.removeClass('disabled');
			renew.addClass('disabled');
		}else{
			none.addClass('disabled');
			renew.removeClass('disabled');
		}
		
		passport_number.slideUp(250);
		passport_expiration.slideUp(250);
		
	}else if(type == 'exist'){
		if(is_checked){
			renew.addClass('disabled');
			none.addClass('disabled');
		}else{
			renew.removeClass('disabled');
			none.removeClass('disabled');
		}
		
		passport_number.slideDown(250);
		passport_expiration.slideDown(250);
		
	}
	*/
}
	
function hideShowTravelers(amountToShow){
	if(amountToShow > window.oldAmountToShow){ //showing more
		
		for(i=window.oldAmountToShow;i<=amountToShow;i++){
			$("#traveler_div_"+i).slideDown(0);
			// $("#traveler_div_"+i).slideDown(500);
		}
	}else{ //hiding some
		for(i=window.oldAmountToShow;i>amountToShow;i--){
			$("#traveler_div_"+i).slideUp(0);
			// $("#traveler_div_"+i).slideUp(500);
		}
	}
	window.oldAmountToShow = amountToShow;
	//setTimeout('replaceSelects()',1000);
}

function logInClient(code,msg){
	if(!code){
		$("#fourofouressage").html(msg);
		return false;
	}
	
	// Break up the url into it's domain and page, and it's query string
	var urlComponents = window.location.href.split( '?' );
	var newUrl = urlComponents[0] + '?';

	// If we have a query string, add it to the login url
//	if( urlComponents[1] && urlComponents[1].length > 0 )
//		newUrl += urlComponents[1] + '&';
	
	newUrl += 'login=' + escape(code);

	// Send the user to the new url
	window.location = newUrl;
	return false;
}// End function logInClient

function changeImages() {
	for (var i=0; i<changeImages.arguments.length; i+=2) {
		document[changeImages.arguments[i]].src = changeImages.arguments[i+1];
	}
}

function vtoggle(elementID){
var target1 = document.getElementById(elementID)
if (target1.style.display == 'none') {
target1.style.display = 'block'
} else {
target1.style.display = 'none'
}
}


function emailCirRequirements( email_field_id, sender_id, container_field_id )
{
	var emailAddr = $( '#' + email_field_id )[0].value;
	var sender = $( '#' + sender_id )[0].value;
	var container = $( '#' + container_field_id );

 	$.ajax({
		type: "GET",	
		url: "/ajax/ajax.emailCirRequirements.php",
		data: "emailaddr="+emailAddr+"&sender="+sender,
		dataType: 'json',
		complete: function( data )
		{
 			container.children().show();
	 		container.children( '.loading' ).hide();
	 		recordAnalyticsConversion('CirDownloadOrEmail');
		},
		success: function( data )
		{
			container.hide();
			container.parent().children( '.finished_loading' ).show().html( data.message );
		}
	});
 	
 	container.children().hide();
 	container.children( '.loading' ).show();
 	container.parent().children( '.finished_loading' ).hide();
}// End function fillPassportStates


function recordAnalyticsConversion(target) {
	//below cookie is for making sure the lightbox on the requirements page is not shown once ...
	//... they already download/email a CIR
	createCookie('lightbox','shown',0);
	//alert('we just set the lightbox cookie to shown in recordAnalyticsConversion()');
	/*
	var iframe = document.createElement("iframe");
	iframe.src = "/conversiontracker.php?target="+target;
	iframe.style.border = "0px";
	iframe.style.height = "1px";
	iframe.style.width = "1px";
	document.getElementsByTagName("body")[0].appendChild(iframe);
	*/
}

function createCookie(name,value,days) 
{
	if (days) 
	{
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) 
{
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) 
{
	createCookie(name,"",-1);
}

function changeCurrentLink(){
	$('#subnav a').each(function(i,v){
		if(v.pathname == window.location.pathname && !(v.href.search("#") > 0)){
			v.style.color = "#000";
			//v.style.fontStyle = "italic";
			v.style.cursor = "default";
			//v.innerHTML = "&nbsp;&nbsp;"+v.innerHTML;
		}
	});
}

function autoETARedirect(){
	$('#autoETAredirect').submit();
}

function addWeeklyUpdate(){
	$("#weekly_update_div").html('<img src="' + window.getResourcePath() + '/images/colorbox/loading.gif" alt="" />');
	var formData = $('#weeklyUpdateForm').serialize();
	formData = formData.replace('%5B','[');
	formData = formData.replace('%5D',']');
	$.ajax({
	   type: "POST",
	   url: "/ajax/ajax.weeklyUpdate.php",
	   data: formData,
	   success: function(msg){
	     $("#weekly_update_div").html(msg);
	   }
 	});	
 	return false;
}

function showUserLoginForm( referer )
{
	// Build the url for the user login popup
	var loginPopupUrl = '/ajax/ajax.userLoginPopup.php';
	if( referer && referer.length > 0 )
		loginPopupUrl += '?referer=' + referer;

	$.fn.colorbox({ //changed to click function (instead of load) to allow sending of form data
		href: loginPopupUrl,
		transition: 'none',
		speed: 100,
		width: 400,
		innerWidth: '0px',
		initialWidth: '400px',
		initialHeight: '0px',
		opacity: 0.7,
		scrolling: false,
		onLoad: function()
		{
			// Hide the scrollbars in IE
			$( '#cboxLoadedContent' ).hide();
		},
		onComplete: function(){
			$( '#cboxLoadedContent' ).show();
			$(this).colorbox.resize();
			if (typeof(replaceForms) != 'undefined') replaceForms();
			
			// Plug into the cancel button click
			$( '#cancel_login' ).click( function( e )
			{
				e.preventDefault();
				e.stopPropagation();
				
				// Hide the login popup
				$.fn.colorbox.close();
			} );
			
			// Plug into the login button
			$( '#submit_login' ).click( function()
			{
				submitUserLoginForm( '#user_login_form' );
			} );
		}
	}).resize();
}// End function showUserLoginForm

function submitUserLoginForm( formSelector )
{
	// Gather the data for our form
	var formData = $( formSelector ).serializeArray();
	
	// Disable all the form fields
	$( formSelector ).find( 'input, textarea, select' ).each( function()
	{
		this.disabled = "disabled";
	} ).end().find( '.status_indicator' ).show();
	
	// Gather our form data into a format that jquery ajax can use
	var ajaxData = {};
	for( var n = 0; n < formData.length; ++n )
	{
		ajaxData[formData[n].name] = formData[n].value;
	}// End for n
	
	// Get the form element and remove any error messages
	var loginForm = $( formSelector );
	loginForm.find( '.error' ).remove();

	// Send the request to the server
	$.post( '/ajax/ajax.userLoginPopup.php', ajaxData, function( data )
	{
		// Re-enable our form fields
		$( formSelector ).find( 'input, textarea, select' ).each( function()
		{
			this.disabled = '';
		} ).end().find( '.status_indicator' ).hide();

		if( ! data )
			return;

		// If we have any errors messages, show them to the user
		if( data.errors )
		{
			// Remove any existing error messages
			loginForm.find( '.error' ).remove();

			// Create the display elements for the error messages and display them
			for( var n in data.errors )
			{
				// Create the error message display
				var errorUI = document.createElement( 'div' );
				errorUI.className = 'error';
				errorUI.innerHTML = data.errors[n];
				loginForm.find( "input[name*='" + n + "']" ).each( function()
				{
					this.parentNode.appendChild( errorUI );
				} );
			}// End for n
			
			$.fn.colorbox.resize();
		}// End if errors
		else if( data.status )
		{
			if( data.status == 'success' )
			{
				// If the form has a redirect url, send the user to it
				var redirectUrl = loginForm.find( "input[name*='referer']" );
				if( redirectUrl.length > 0 && redirectUrl[0].value.length > 0 )
				{
					location.href = redirectUrl[0].value;
				}// End if
				else
				{
					// Otherwise let the user know the login worked
//					alert( 'you are now logged in' );
//					$.fn.colorbox.close();
					location.href = location.href;
				}// End else
			}// End if
			else
				alert( data.message );
		}// End else if
	}, 'json' );
}// End function submitUserLoginForm


// Show the forgot password popup to the user
function showForgotPassword()
{
	$.fn.colorbox({ //changed to click function (instead of load) to allow sending of form data
		href: '/ajax/ajax.forgotPassword.php',
		transition: 'none',
		speed: 100,
		width: 400,
		innerWidth: '0px',
		initialWidth: '400px',
		initialHeight: '0px',
		opacity: 0.7,
		scrolling: false,
		onLoad: function()
		{
			// Hide the scrollbars in IE
			$( '#cboxLoadedContent' ).hide();
		},
		onComplete: function(){
			$( '#cboxLoadedContent' ).show();
			$(this).colorbox.resize();
			if (typeof(replaceForms) != 'undefined') replaceForms();
			
			// Plug into the submit button
			$( '#submit_forgotpw' ).click( function( e )
			{
				e.stopPropagation();
				e.preventDefault();
				
				// Gather the data for our form
				var formData = $( '#forgot_password_form' ).serializeArray();
				
				// Gather our form data into a format that jquery ajax can use
				var ajaxData = {};
				for( var n = 0; n < formData.length; ++n )
					ajaxData[formData[n].name] = formData[n].value;
				
				// Get the form element and remove any error messages
				var form = $( '#forgot_password_form' );
				form.find( '.error' ).remove();

				
				// Send the request to the server
				$.post( '/ajax/ajax.forgotPassword.php', ajaxData, function( data )
				{
					if( ! data )
						return;

					// If we have any errors messages, show them to the user
					if( data.errors )
					{
						// Remove any existing error messages
						form.find( '.error' ).remove();

						// Create the display elements for the error messages and display them
						for( var n in data.errors )
						{
							// Create the error message display
							var errorUI = document.createElement( 'div' );
							errorUI.className = 'error';
							errorUI.innerHTML = data.errors[n];
							form.find( "input[name*='" + n + "']" ).each( function()
							{
								this.parentNode.appendChild( errorUI );
							} );
						}// End for n
						
						$.fn.colorbox.resize();
					}// End if errors
					else if( data.status )
					{
						if( data.status == 'success' )
						{
							$.fn.colorbox.close();
							alert( data.message );
						}// End if
						else
							alert( data.message );
					}// End else if
				}, 'json' );
			} );
			
			// Plug into the cancel button click
			$( '#cancel_forgotpw' ).click( function( e )
			{
				e.preventDefault();
				e.stopPropagation();
				
				// Hide the login popup
				$.fn.colorbox.close();
			} );
		}
	}).resize();
}// End function showForgotPassword

// Plugs into each link and button on the page so that the user will have to login before
// they can go anywhere else
function forceLogin()
{
	setTimeout( function()
	{
		$( 'a, input[type="image"]' ).each( function()
		{
			if( ! $( this ).hasClass( 'ignoreForceLogin' ) )
			{
				$( this ).unbind( 'click' ).click( function( e )
				{
					e.stopPropagation();
					e.preventDefault();
					
					// Show the popup that tells the user to login
					$.fn.colorbox( {
						html: 'You must login first.'
					} );
					
					return false;
				} );
			}// End if
		} );
	}, 1000 );
}// End function forceLogin

