/**
 *  ESLDiretcory Specific JS functions
 *  should be comprassed in PRODUCTION
 */ 

var relative_base_path = ( isProduction() ) ? 'http://www.esldirectory.com/' : 'http://dev.internationalstudentloan.com/esldirectory.com/';

/**
 *  Determines whether the site is running in production or not
 *  by searching the contents of the host string
 */
function isProduction()
{
    productionHost = 'www.esldirectory.com';

    return ( window.location.host.search(productionHost) >= 0 );
}

/**
 *	this loads at the beginning, so we have the default values  
 *	for the ADMIN table
 *
 */
function loadSettingsForProgramAdmin()
{
	TableKit.options.editAjaxURI = relative_base_path + 'ajax/activateprogramadmin.php';
	
	TableKit.Editable.selectInput('progadmin_status', {}, [
			['active','1'],
			['not-active','0']
		]);
}

/**
 * 
 * @param {Object} field_obj
 * @param {Object} max_count
 */
function updateCounter( field_obj, max_count )
{
	counter_field = 'char_counter_for_' + field_obj.id;
	current_count = max_count - field_obj.value.length;
	
	if( current_count < 10 )
	{
		$(counter_field).style.color = "#f00";
	}
	else
	{
		$(counter_field).style.color = "#999";
	}
	
	$(counter_field).update( current_count );
	
	return false;
}

/**
 * 
 */
function loadSettingsForPrograms()
{
	TableKit.options.editAjaxURI = relative_base_path + 'ajax/approveprogram.php';
	
	TableKit.Editable.selectInput('approve_program', {}, [
			['yes','1'],
			['no','0']
		]);
}

/**
 * regular ajax login, not from the top
 */
function login()
{
	var url = relative_base_path + encodeURIComponent('loginviaajax.php');
	
	// notice the use of a proxy to circumvent the Same Origin Policy.

	new Ajax.Request(url, {
	  parameters: $('loginForm').serialize(true),
	  method: 'post',
	  onSuccess: function(transport) 
	  {
		var notice = $('notice');
		
		if( transport.responseText == 'success' )
		{
			$( 'loginFormPanel' ).hide();
			$( 'email_address' ).innerHTML = $('username').value;
			$( 'ajax_status' ).hide();
			$( 'user_info_panel' ).show();
		}
		else
		{
			$( 'ajax_status' ).removeClassName( 'ajax_success' );			
			$( 'ajax_status' ).addClassName( 'ajax_error' );
			$( 'ajax_status' ).innerHTML = transport.responseText;
			$( 'ajax_status' ).show();			
		}
		
	  }
	});
}

/**
 * ajax login from the top
 */
function loginFromTop()
{
	var url = relative_base_path + encodeURIComponent('loginviaajax.php');
	// notice the use of a proxy to circumvent the Same Origin Policy.

	new Ajax.Request(url, {
	  parameters: $('topLoginForm').serialize(true),
	  method: 'post',
	  onSuccess: function(transport) 
	  {
		var notice = $('notice');
		
		if( transport.responseText == 'success' )
		{
			/* $( 'top_login_panel' ).hide();
			$( 'email_address' ).innerHTML = $('username').value;
			$( 'ajax_status' ).hide();
			$( 'user_info_panel' ).show(); */
			location.href = relative_base_path + "dashboard.php";
		}
		else
		{
			$( 'ajax_status' ).removeClassName( 'ajax_success' );
			$( 'ajax_status' ).addClassName( 'ajax_error' );
			$( 'ajax_status' ).innerHTML = transport.responseText;
			$( 'ajax_status' ).show();
			$( 'forgot_password').show();
		}
		
	  }
	});
}

/**
 *	sends a form to the school contact
 */
function contactSchool()
{
	$('schoolContactFormPanel').style.display = 'none';
	var url = relative_base_path + 'ajax/contactschool.php';

	new Ajax.Request(url,{
		parameters: $('schoolContactForm').serialize(true),
		method: 'post',
		onSuccess: function( transport )
		{
			if( transport.responseText == 'success' )
			{
				$('fail_ajax').style.display = 'none';
				$('success_ajax').style.display = 'block';
                                setTimeout( 'pop.close()', 4000 );
				$('info_and_contact_block').hide();
			}
			else
			{
				$('success_ajax').style.display = 'none';
				$('fail_ajax').style.display = 'block';				
				$('schoolContactFormPanel').style.display = 'block';
			}
		}
	});
}

/*
 *	saving a program to a user
 *
 */
var saveProgram = function( link_obj, program_id )
{
	$( link_obj ).hide();	
	$( 'ajax_loader_for_review' ).show();
	
	var url = relative_base_path + 'ajax/saveprogram.php?id=' + program_id;
	new Ajax.Request(url,{
		method: 'get',
		onSuccess: function( transport )
		{
			if( transport.responseText != 'success' )
			{
				$( link_obj ).show();
			}
                        else
                        {
                            $('success_green_box').show();
                            setTimeout( '$("success_green_box").hide()', 4000 );
                        }
			
			$( 'ajax_loader_for_review' ).hide();
		}
	});
}


/**
 *
 *
 */
function register_student()
{
	if (humanValidator()) 
	{
		var url = relative_base_path + encodeURIComponent('registerviaajax.php');
		
		$('studentRegistrationFormPanel').hide();
		$('please_text').show();

		new Ajax.Request(url, {
			parameters: $('registrationForm').serialize(true),
			method: 'post',
			onSuccess: function(transport){
				var notice = $('notice');
				
				if (transport.responseText == 'success') 
				{
					$('reg_email_address').innerHTML = $('reg_username').value;
/*					$('registrationFormPanel').hide(); */
					$('reg_status').removeClassName('ajax_error');
					$('reg_status').addClassName('ajax_success');
/*					$('reg_status').innerHTML = 'registered'; */
					$('please_text').hide();
					$('regi_note').show();					
				}
				else {
					$('please_text').hide();
					$('studentRegistrationFormPanel').show();
					$('reg_status').removeClassName('ajax_success');
					$('reg_status').addClassName('ajax_error');
					$('reg_status').innerHTML = transport.responseText;
				}
				
				$('reg_status').show();
			}
		});
	}
}

/**
 *
 *
 */
function registerViaPopup_old()
{
    var url = relative_base_path + encodeURIComponent( 'registerviaajax.php' );
    new Ajax.Request( url, {
        parameters: $('registerForm').serialize(true),
        method:'post',
        onSuccess: function( transport )
        {
            if( transport.responseText == 'success' )
            {
                // well, we shouldn't be here because PHP was supposed to
                // send us to the login page !!?!?!?
                var form = new Element('form',{
                    method: 'post', action: relative_base_path + encodeURIComponent('login.php')});
                    form.insert(new Element('input',{name: 'username', value: $('reg_username').value, type: 'hidden'}));
                    form.insert(new Element('input',{name: 'password', value: $('reg_password').value, type: 'hidden'}));
                    form.insert(new Element('input',{name: 'autocontact', value: 'true', type: 'hidden'}));
                    form.insert(new Element('input',{name: 'url', value: $('url').value, type: 'hidden'}));
                    $(document.body).insert(form);
                    form.submit();
            }
            else
            {
                $('ajax_loader').hide();
                $('formSubmit').show();
                $('fail_ajax').update( transport.responseText );
                $('fail_ajax').show();
            }
        }
    });
}

function registerOrLoginViaPopup(action)
{
    var url;
    var actionSuccessful = false;

    // we have to decide here if the user is just trying to login
    // or trying to register ...
    if( action == 'login' )
    {
        // Clear any old error messages
        $('fail_ajax').update().hide();

        // Disable the submit button to prevent multiple submissions
        $('loginFormSubmit').writeAttribute({disabled: true});

        url = relative_base_path + encodeURIComponent( 'loginviaajax.php' );

        new Ajax.Request( url, {
            parameters: $('loginForm').serialize(true),
            method: 'post',
            onSuccess: function( xhr ) {
                if( xhr.responseText == 'success' ) {
                    displayMessageForm('You are now logged in. Type your message below.');
                } else {
                    $('fail_ajax').update( xhr.responseText ).show();

                    // Scroll to make the error messages visible
                    moveTo('MB_content', 'fail_ajax');

                    $('loginFormSubmit').writeAttribute({disabled: false});
                    Modalbox.resizeToContent();
                }
            }
        });
    }

    if( action == 'register' )
    {
        // Clear any old error messages
        $('fail_ajax').hide().update();

        // Disable the submit button to prevent multiple submissions
        $('registrationFormSubmit').writeAttribute({disabled: true});

        url = relative_base_path + encodeURIComponent( 'registerviaajax.php' );

        new Ajax.Request( url, {
            parameters: $('registrationForm').serialize(true),
            method: 'post',
            onSuccess: function( xhr ) {
                if( xhr.responseText == 'success' ) {
                    displayMessageForm('You are now registered. Type your message below.');
                } else {
                    $('fail_ajax').update( xhr.responseText ).show();

                    // Scroll to make the error messages visible
                    moveTo('MB_content', 'fail_ajax');

                    // Re-enable the submit button
                    $('registrationFormSubmit').writeAttribute({disabled: false});

                    Modalbox.resizeToContent();
                }
            }
        });
    }

    if( action != 'login' && action != 'register' ) {
        $('fail_ajax').update('Something went wrong.');
    }
}

/**
 * When a user logs in or registers via ajax, call this function to
 * replace the login form at the top of the page with the logged-in
 * user's info
 */
function displayUserInfoArea(username)
{
    if( !Object.isString(username) || username.empty() )
    {
        console.log('You need to pass a username to displayUserInfoArea(). The value you passed to it was empty or was not a string.');
    }

    var fullName, url=relative_base_path + 'ajax/getusername.php';

    new Ajax.Request(
        url,
        {parameters: {username: username},
        method: 'post',
        evalJS: true,
        onSuccess: function( xhr ) {
            if( ! xhr.responseJSON.fullname.empty() ) {
                var tooltip = userInfo = 'logged in as ' + xhr.responseJSON.fullname;
                var userInfoSpan = new Element('span', {'style': 'color:#000;padding-right:10px;'}).update(userInfo);
                var dashboardAnchor = new Element('a', {
                    'href': relative_base_path + 'dashboard',
                    'alt': tooltip,
                    'title': tooltip
                }).update('dashboard');
                var dashboardButton = new Element('span', {
                    'class': 'over_the_header_menu',
                    'style': "background-image: url(" + relative_base_path + "images/gray_for_top_buttons.png);"
                }).insert(dashboardAnchor);
                var logoutAnchor = new Element('a', {
                    'href': relative_base_path + 'logout',
                    'alt': tooltip,
                    'title': tooltip
                }).update('logout');
                var logoutButton = new Element('span', {
                    'class': 'over_the_header_menu',
                    'style': "background-image: url(" + relative_base_path + "images/gray_for_top_buttons.png);"
                }).insert(logoutAnchor);

                $('user_info_area')
                    .update()
                    .insert(userInfoSpan)
                    .insert(dashboardButton)
                    .insert(logoutButton);
            }
        }}
    );
}

function sendMessage()
{
    // Disable the submit button to prevent multiple submissions
    $('messageSendButton').writeAttribute({disabled: true});

    // Clear error messages from the user's previous attempts, if any
    $('fail_ajax').update();

    url = relative_base_path + encodeURIComponent( 'loginviaajax.php' );

    new Ajax.Request( url, {
        parameters: $('messageForm').serialize(true),
        method: 'post',
        onSuccess: function( xhr ) {
            if( xhr.responseText == 'success' ) {
                $('messageSection').hide();
                $('loginMessage').update('Your message to this school has been sent successfully.');
                var hideModalbox = function() {
                    Modalbox.hide();
                };
                setTimeout( hideModalbox, 2000 );
            } else {
                console.log(xhr.responseText);
                $('fail_ajax').update( 'There was a problem sending your message. Please try again later.' ).show();

                // Scroll to make the error messages visible
                moveTo('MB_content', 'fail_ajax');

                // Re-enable the submit button
                $('messageSendButton').writeAttribute({disabled: false});

                Modalbox.resizeToContent();
            }
        }
    });
}

/**
 *
 *
 */
function register_school()
{
	if (humanValidator()) 
	{
		var url = relative_base_path + encodeURIComponent('registerviaajax.php');
		
		new Ajax.Request(url, {
			parameters: $('registrationForm').serialize(true),
			method: 'post',
			onSuccess: function(transport){
				var notice = $('notice');
				
				if (transport.responseText == 'success') 
				{
					$('reg_email_address').innerHTML = $('reg_username').value;
/*					$('registrationFormPanel').hide(); */
					$('reg_status').removeClassName('ajax_error');
					$('reg_status').addClassName('ajax_success');
/*					$('reg_status').innerHTML = 'registered'; */
					$('adminRegistrationFormPanel').hide();
					$('please_text').hide();
					$('regi_note').show();					
				}
				else {
					$('reg_status').removeClassName('ajax_success');
					$('reg_status').addClassName('ajax_error');
					$('reg_status').innerHTML = transport.responseText;
				}
				
				$('reg_status').show();
			}
		});
	}
}

/**
 * 
 * @param {Object} main_menu_obj
 */
function showSubMenuFor( main_menu_obj )
{
	main_menu = main_menu_obj.id;
	sub_menu	= 'sub_' + main_menu;
	Element.clonePosition($(sub_menu),$(main_menu),{offsetTop:'3px'});
	Element.setStyle( $(sub_menu), {width:'175px',textAlign:'left',padding:'2px 3px 1px 3px', fontSize:'11px', height:'auto'} );
	$(sub_menu).show();
}

/**
 * 
 * @param {Object} form_name
 */
function eraseFormElements( form_name )
{
	var form_obj = $(form_name);
	
	for( i = 0; i<form_obj.elements.length; i++ )
	{
		if( form_obj.elements[i].type == "text" || form_obj.elements[i].type == "textarea" )
		{
			form_obj.elements[i].value = "";
		}
	}
}

/**
 * 
 * @param {Object} curr
 */
function updateCurrency( curr )
{
	currency_objs = $$('span.currency');
	
	for( i=0 ; i < currency_objs.length ; i++ )
	{
		currency_objs[i].update( curr );
	}
}

/**
 *
 */
var searchByCountry = function( country, city )
{
	$('form_field_for_state').hide();
	$('form_field_for_city').hide();

	country = country.replace( /-/, " " );
	$('display_results_in').update( ucwords( country ) );
	
	// we have multiple elemnts we have to update so
	// we need to update them ...
	elements_with_country_name = $$( 'span.display_country_name' );
	
	for( i=0; i<elements_with_country_name.length; i++ )
	{
		element = elements_with_country_name[ i ];
		element.update( ucwords( country ) );

	}
	
	switch( ucwords(country) )
	{
		case 'United Kingdom':
		case 'Australia':
		case 'Canada':
				loadCitiesFor( 'country', country, city );
				$('form_field_for_city').show();
				break;
		case 'USA':
				$('form_field_for_state').show();
				break;
	}
	
	
	//var meta;
	//if (document.createElement && ( meta = document.createElement( 'meta' ) ) )
	//{
	// set properties
	// meta = document.createElement( 'meta' )
	// meta.name = "esldirectory";
	// meta.content = country;
	
	// now add the meta element to the head
	// document.getElementsByTagName('head').item(0).appendChild(meta);
	//}
	
	// document.title = "ESLdirectory - ESL programs in " + country.capitalize();
		// if there is a city involved we have to call it differently... PATCH
	if( city.length > 0 )
	{
		updateSearchTable( 'country=' + country.toLowerCase() + '&city=' + city.toLowerCase() );
	}
	else
	{	
		updateSearchTable( 'country=' + country.toLowerCase() );
	}
}

/**
 *
 */
var searchByCountryFromSelect = function( country )
{
	location.href = relative_base_path + "esl-program-search/" + country.toLowerCase();
	return true;
}

/**
 *
 */
var searchByState = function( state, city )
{
	if( state.length > 0 )
	{
		state_obj = $('state');
		state_name_for_title = state_obj.options[state_obj.selectedIndex].text;
		// document.title = "ESLdirectory - ESL programs in " + state_name_for_title.capitalize() + ', USA';
		
		loadCitiesFor( 'state', state, city );
		$('form_field_for_city').show();
		
		// if there is a city involved we have to call it differently... PATCH
		if( city.length > 0 )
		{
			updateSearchTable( 'country=USA&state=' + state + '&city=' + city );
		}
		else
		{
			updateSearchTable( 'country=USA&state=' + state );
		}
	}
}

/**
 *	i had to create this function to reload the whole page
 * 	and look better in search engines :)
 */
var searchByStateFromSelect = function( state )
{
	location.href = relative_base_path + "esl-program-search/usa/" + state.toLowerCase();
	return true;
}

/**
 *
 */
var searchByFeatured = function()
{
		document.title = "ESLdirectory - Featured ESL programs";
		$('featured').value=1;
		updateSearchTable( 'featured=1' );
}

/**
 *
 */
var searchByName = function( name )
{
	$('form_field_for_state').hide();
	$('form_field_for_city').hide();
	$('country').options[0].selected = true;
	updateSearchTable( 'name=' + name );
}

/**
 *
 */
var searchByCity = function( city )
{
	updateSearchTable( 'city=' + city + '&country=' + $('country').value );
}

/**
 *	i had to create this function to reload the whole page
 * 	and look better in search engines :)
 */
var searchByCityFromSelect = function( city )
{
	if( $('state').value != '' )
	{
		location.href = relative_base_path + "esl-program-search/usa/" + $('state').value + '/' + city.toLowerCase();
	}
	else
	{
		location.href = relative_base_path + "esl-program-search/" + $('country').value + '/' + city.toLowerCase();
	}
	return true;
}

/**
 *
 */
var searchByContinent = function( continent )
{
	continent = continent.capitalize();
	$('display_results_in').update( continent.replace( /-/, " ") );
	updateSearchTable( 'continent=' + continent );
}

/**
 *
 */
var updateSearchTable = function( params )
{
	$('ajax_loader').show();
	var url = relative_base_path + 'search/searchajax.php';
	
	if( $('featured').value == 1)
	{
		params = params + '&featured=1';
	}
	
	
	var ajax = new Ajax.Updater
	(
		{
			success: 'searchTable'
		},
		url,
		{
			method: 'get',
			parameters: params
		}
	);
	$('ajax_loader').hide();
}

/**
 *	loading all the cities for a specific COUNTRY or a STATE
 */
var loadCitiesFor = function( what_for, name, city_name )
{
	if( ! what_for )
	{
		params = 'country=' + name;
	}
	else
	{
		params = what_for + '=' + name;
	}
	
	city_obj = $( 'city' );
	
	// let's empty out the drop-down list
	for( i = city_obj.options.length - 1 ; i >= 0 ; i-- )
	{
		city_obj.remove(i);
	}
	
	new Ajax.Request( relative_base_path + 'ajax/getcitiesforselect.php',
	{
			method: 'get',
			parameters: params,
			onSuccess: function( transport )
			{
				var response = transport.responseText || 'no response';
						
				if( response != 'no response' )
				{
					var my_options = response.split( ',' );
					
					// adding an empty line to the top. hack hack hack
					var opt = document.createElement( 'option' );
					opt.text = '';
					opt.value = '';
					city_obj.options.add( opt );
					
					// dinamycally adding the options for the drop-down
					for( i=0; i<my_options.length; i++ )
					{
						var opt = document.createElement( 'option' );
						opt.text = my_options[i];
						opt.value = my_options[i].toLowerCase();
						if( opt.value== city_name )
						{
							opt.selected = true;
						}
						
						if( opt.value.length > 0 )
						{
							city_obj.options.add( opt );
						}
					}
				}
			}
		}
	)
}


/* * * * * * * *
* DELETE stuff with Ajax - delete
 * * * * * * * */
 
/**
 * delete program by anybody
 * i combined all the program deletion functions into one so
 * we have less JS to load
 */
var delProgram = function( row_id, who )
{
	var del = confirm( 'Are you sure you want to delete this program ?' );
	program_id = Number( row_id.replace( 'program_', "") );	
	
	if( del )
	{
		ajax_url = '';
		if( who == 'student' )
		{
			ajax_url = relative_base_path + 'ajax/deleteprogrambystudent.php';
		}
		else if( who == 'progadmin' )
		{
			ajax_url = relative_base_path + 'ajax/deleteprogrambyprogadmin.php';
		}
		else if( who == 'siteadmin' )
		{
			ajax_url = relative_base_path + 'ajax/deleteprogrambysiteadmin.php';
			
		}

		if( ajax_url.length > 0 )
		{
			new Ajax.Request( ajax_url,
			{
				method: 'get',
				parameters: 'pid=' + program_id,
				onSuccess: function( transport )
				{
					var response = transport.responseText || 'failed';
					if( response == 'success' )
					{
						$( row_id ).hide();
					}					
				}
			});
		}
	}
}


/**
 * user deletion for site admins
 * 
 * @param {Object} id
 * @param {Object} name
 */
function delUser( row_id, name )
{
	var del = confirm( 'Are you sure you want to delete ' + name + '?' );
	user_id = Number( row_id.replace( 'user_', "") );
	if( del )
	{
		new Ajax.Request( relative_base_path + 'ajax/deleteuser.php',
		{
			method: 'get',
			parameters: 'uid=' + user_id,
			onSuccess: function( transport )
			{
				var response = transport.responseText || 'failed';
				if( response == 'success' )
				{
					$( row_id ).hide();
				}					
			}
		});
	}
}

 /* * * * * * *
* END of deleting stuff
* * * * * * * *

/**
 * view student information and message on contact report
 */
var displayUserMessage = function( message_id )
{
	pop = new ModalWindow();
	myElem = new Element( 'modal_box' ).update( '<img src="' + relative_base_path + 'images/ajax-loader.gif" width="20px;"/>' );
	pop.show( myElem, true );
	
	new Ajax.Request( relative_base_path + 'ajax/getstudentmessage.php',
	{
		method: 'get',
		parameters: 'mid=' + message_id,
		onSuccess: function( transport )
		{
			var response = transport.responseText || 'failed';
			if( response != 'failed' )
			{
				// myElem.update( response );
				message_obj = unserialize( response );
				
				contact_date	= message_obj['contact_date'];
				message		= message_obj['message'];
				email		= message_obj['email'];
				first_name	= message_obj['first_name'];
				last_name	= message_obj['last_name'];
				city        	= message_obj['city'];
				country		= message_obj['country'];
				phone		= message_obj['phone'];
				
				myElem.update(
					      '<div style="font-size:12px;"><strong>' + email + '</strong> <span style="color:#999;font-size:10px;">' + contact_date + '</span></div>' +
					      '<div style="font-size:10px;"><i>' + city + ', ' + country + '</i><br/>' + phone + '</div>' +
					      '<br />' +
					      '<div style="font-size:10px;">' + message + '</font>'
					      );				
			}					
		}
	});
}

/**
 * view student information and message on contact report
 */
var displayProgram = function( program_id )
{
	pop = new ModalWindow();
	myElem = new Element( 'modal_box' ).update( '<img src="' + relative_base_path + 'images/ajax-loader.gif" width="20px;"/>' );
	pop.show( myElem, true );
	
	new Ajax.Request( relative_base_path + 'ajax/getprogram.php',
	{
		method: 'get',
		parameters: 'pid=' + program_id,
		onSuccess: function( transport )
		{
			var response = transport.responseText || 'failed';
			if( response != 'failed' )
			{
				// myElem.update( response );
				program_obj = unserialize( response );
				
				updated			= program_obj['updated'];
				name			= program_obj['name'];
				description 	= program_obj['description'];
				country 		= program_obj['country'];
				city 			= program_obj['city'];
				state 			= program_obj['state'];
				foreignstate 	= program_obj['foreignstate'];
				address1		= program_obj['address1'];
				address2		= program_obj['address2'];
				phone			= program_obj['phone'];
				fax				= program_obj['fax'];
				contact_name	= program_obj['contact_name'];
				contact_title	= program_obj['contact_title'];
				email			= program_obj['email'];
				tuition			= program_obj['tuition'];
				housingmeals	= program_obj['housingmeals'];
				totalcost		= program_obj['totalcost'];
				class_average	= program_obj['class_average'];
				class_max		= program_obj['class_max'];
				students		= program_obj['students'];
				housingavail	= program_obj['housingavail'];
				location_info	= program_obj['location'];
				app_info		= program_obj['app_info'];
				
				/*****************************
				 * !!! NIGHTMARE BEGINS !!!  *
				 *****************************/
				
				myElem.update(
					    '<div style="font-size:12px;"><strong>' + name + '</strong> <span style="color:#999;font-size:10px;">' + updated + '</span></div>' + 
						'<div>' + address1 + ' ' + address2 + '</div>' +
						'<div>' + city + ' ' + state + ' ' + foreignstate + ' <strong>' + country + '</strong></div>'+
						'<div style="padding-top:10px;"><strong>contact </strong>' + contact_name + ' (' + email + ') <i>' + contact_title + '</i></div>' +
						'<div><strong>tel</strong> ' + phone + ' <strong>fax</strong> ' + fax + '</div>' +
						'<div style="padding-top:10px;"><strong>description: <br /></strong>' + description + '</div>' +
						'<div style="margin-top:10px;">' + 
					  	'<span style="width:50%;float:left;">' + 
							'<div style="width:100%;margin-right:5px;"><strong>tuition </strong>' + tuition + '</div>' + 
							'<div style="margin-top:5px;margin-right:5px;width:100%;"><strong>house/meal </strong>' + housingmeals + '</div>' + 
							'<div style="margin-top:5px;margin-right:5px;width:100%;"><strong>total </strong>' + totalcost + '</div>' + 
						'</span>' + 
						'<span style="width:50%;">' + 
								'<div style="margin-left:5px;width:100%;"><strong>class avg. </strong>' + class_average +'</div>'+
								'<div style="margin-left:5px; margin-top:5px;width:100%;"><strong>class max. </strong>' + class_max +'</div>'+ 
								'<div style="margin-left:5px; margin-top:5px;width:100%;"><strong>students </strong>' + students +'</div>'+ 
						'</span>' +
						'</div>' +
						'<div style="float:left;margin-top:10px;"><strong>housing options: <br /></strong>' + housingavail + '</div>' +
						'<div style="float:left;margin-top:10px;"><strong>location info: <br /></strong>' + location_info + '</div>' +
						'<div style="float:left;margin-top:10px;"><strong>application info: <br /></strong>' + app_info + '</div>'
					      );				
			}					
		}
	});
}


/**
 * updating the contacts view on the admin pages
 */
var updateContactCounts = function( year )
{
	Event.observe(window, 'load', function()
	{		
		new Ajax.Request( relative_base_path + 'ajax/updatecontactcounts.php',
		{
			method: 'get',
			parameters: 'year=' + year,
			onSuccess: function( transport )
			{
				var response = transport.responseText || 'failed';
				if( response != 'failed' )
				{
					contacts_by_month = new Array();
					contacts_by_month = unserialize( response );
					
					for( i=0; i<12;i++ )
					{
						month_display_object = 'contact_count_' + i;
						$(month_display_object).update( contacts_by_month[i] );
					} 
				}					
			}
		});
	});
}
 /* * * * * * *
* MAP sliding stuff
 * * * * * * */

var slideTheWorld = function()
{
	$( 'the_world' ).slideUp();
	$( 'the_north' ).slideDown({delay:1});
}

/* * * * * * * * * *
*
* here is an extremly simple human validator. returns TRUE if the user seems to be human
* otherwise just setsup an error message and returns FALSE
*
  * * * * * * * * */


var answer;

/**
 * generates a mathimatical multiplication or 
 */
function humanValidator()
{
	human_answer = $( "humaninput" ).value;

	if( answer != human_answer )
	{
		$( 'reg_status' ).removeClassName( 'ajax_success' );
		$( 'reg_status' ).addClassName( 'ajax_error' );
		$( 'reg_status' ).innerHTML= "not human";
		$( 'reg_status').show();
		$( "humaninput" ).value = "";
		getCaptchaQuestion();
 		return false;
	}
	else
	{
		$('reg_status').hide();
    	return true;
	}
}


function getCaptchaQuestion( field )
{
	field 		= 'captcha_question';
	leftnum     = getRandomNumber( 1, 9 );
	rightnum    = getRandomNumber( 1, 9 );
	symbol  	= getRandomSymbol();

	switch( symbol )
	{
		case "-":
			setAnswer( leftnum - rightnum );
			break;
		case "+":
			setAnswer( leftnum + rightnum );
			break;
		case "x":
			setAnswer( leftnum * rightnum );
			break;
		default:
			alert( "Script ERROR! Sorry, please reload the page and try again!" );
			return false;
	}
	$( field ).innerHTML = leftnum + " " + symbol + " " + rightnum + " = ";
}

function getRandomNumber( from, till )
{
	randugly = Math.random() * till;
	randnum = Math.floor( randugly ) + from;
	return randnum;
}

function getRandomSymbol()
{
	var symbols = new Array( "+", "x" );
//	var symbols = new Array( "-", "+", "x" );
	randnum = getRandomNumber( 0,2 );
	return symbols[randnum];
}

function setAnswer( some_value )
{
	answer = some_value;
	return true;
}


/* * * * * * * * * * * * * 
* 
* 	E N D   O F   H U M A N   V A L I D A T O R
* 
 * * * * * * * * * * * * */

/**
 *	unserializing some stuff here, thanks for the code
 */
function unserialize(data){
    // http://kevin.vanzonneveld.net
    // +     original by: Arpad Ray (mailto:arpad@php.net)
    // +     improved by: Pedro Tainha (http://www.pedrotainha.com)
    // +     bugfixed by: dptr1988
    // +      revised by: d3x
    // +     improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Brett Zamir (http://brettz9.blogspot.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // %            note: We feel the main purpose of this function should be to ease the transport of data between php & js
    // %            note: Aiming for PHP-compatibility, we have to translate objects to arrays 
    // *       example 1: unserialize('a:3:{i:0;s:5:"Kevin";i:1;s:3:"van";i:2;s:9:"Zonneveld";}');
    // *       returns 1: ['Kevin', 'van', 'Zonneveld']
    // *       example 2: unserialize('a:3:{s:9:"firstName";s:5:"Kevin";s:7:"midName";s:3:"van";s:7:"surName";s:9:"Zonneveld";}');
    // *       returns 2: {firstName: 'Kevin', midName: 'van', surName: 'Zonneveld'}
    
    var error = function (type, msg, filename, line){throw new window[type](msg, filename, line);};
    var read_until = function (data, offset, stopchr){
        var buf = [];
        var chr = data.slice(offset, offset + 1);
        var i = 2;
        while (chr != stopchr) {
            if ((i+offset) > data.length) {
                error('Error', 'Invalid');
            }
            buf.push(chr);
            chr = data.slice(offset + (i - 1),offset + i);
            i += 1;
        }
        return [buf.length, buf.join('')];
    };
    var read_chrs = function (data, offset, length){
        var buf;
        
        buf = [];
        for(var i = 0;i < length;i++){
            var chr = data.slice(offset + (i - 1),offset + i);
            buf.push(chr);
        }
        return [buf.length, buf.join('')];
    };
    var _unserialize = function (data, offset){
        var readdata;
        var readData;
        var chrs = 0;
        var ccount;
        var stringlength;
        var keyandchrs;
        var keys;
 
        if(!offset) offset = 0;
        var dtype = (data.slice(offset, offset + 1)).toLowerCase();
        
        var dataoffset = offset + 2;
        var typeconvert = new Function('x', 'return x');
        
        switch(dtype){
            case "i":
                typeconvert = new Function('x', 'return parseInt(x)');
                readData = read_until(data, dataoffset, ';');
                chrs = readData[0];
                readdata = readData[1];
                dataoffset += chrs + 1;
            break;
            case "b":
                typeconvert = new Function('x', 'return (parseInt(x) == 1)');
                readData = read_until(data, dataoffset, ';');
                chrs = readData[0];
                readdata = readData[1];
                dataoffset += chrs + 1;
            break;
            case "d":
                typeconvert = new Function('x', 'return parseFloat(x)');
                readData = read_until(data, dataoffset, ';');
                chrs = readData[0];
                readdata = readData[1];
                dataoffset += chrs + 1;
            break;
            case "n":
                readdata = null;
            break;
            case "s":
                ccount = read_until(data, dataoffset, ':');
                chrs = ccount[0];
                stringlength = ccount[1];
                dataoffset += chrs + 2;
                
                readData = read_chrs(data, dataoffset+1, parseInt(stringlength));
                chrs = readData[0];
                readdata = readData[1];
                dataoffset += chrs + 2;
                if(chrs != parseInt(stringlength) && chrs != readdata.length){
                    error('SyntaxError', 'String length mismatch');
                }
            break;
            case "a":
                readdata = {};
                
                keyandchrs = read_until(data, dataoffset, ':');
                chrs = keyandchrs[0];
                keys = keyandchrs[1];
                dataoffset += chrs + 2;
                
                for(var i = 0;i < parseInt(keys);i++){
                    var kprops = _unserialize(data, dataoffset);
                    var kchrs = kprops[1];
                    var key = kprops[2];
                    dataoffset += kchrs;
                    
                    var vprops = _unserialize(data, dataoffset);
                    var vchrs = vprops[1];
                    var value = vprops[2];
                    dataoffset += vchrs;
                    
                    readdata[key] = value;
                }
                
                dataoffset += 1;
            break;
            default:
                error('SyntaxError', 'Unknown / Unhandled data type(s): ' + dtype);
            break;
        }
        return [dtype, dataoffset - offset, typeconvert(readdata)];
    };
    return _unserialize(data, 0)[2];
}


/**
 *	a cool ucwords for javascript
 */
function ucwords( str ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: Waldo Malqui Silva
    // +   bugfixed by: Onno Marsman
    // *     example 1: ucwords('kevin van zonneveld');
    // *     returns 1: 'Kevin Van Zonneveld'
    // *     example 2: ucwords('HELLO WORLD');
    // *     returns 2: 'HELLO WORLD'
 
    return (str+'').replace(/^(.)|\s(.)/g, function ( $1 ) { return $1.toUpperCase( ); } );
}

function hi( text )
{
	alert( text );
}
