if(jQuery){
	//Area to customize jquery
	jQuery.extend( jQuery.expr[ ":" ], {
		parents: function(a,i,m){ return jQuery(a).parents(m[3]).length; },
		reallyvisible: function(a){ return !jQuery(a).parents().add(a).filter(function(){return $(this).is(':hidden') || $(this).css('visibility') == 'hidden';}).length }
		//Add :selectors here
		});
	}
function URLencode(sStr) {
    return escape(sStr).
             replace(/\+/g, '%2B').
                replace(/\"/g,'%22').
                   replace(/\'/g, '%27').
                     replace(/\//g,'%2F').
			replace(/\&/g,'%26');
  }

/*
function autofocus(field, limit, next, evt)
	{
	evt = (evt) ? evt : event;
	var charCode = (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode : ((evt.which) ? evt.which : 0));
	if (charCode > 31 && field.value.length == field.maxLength)
		{
		field.form.elements[next].focus();
		}
	}
*/

/* Form Error Messages & Validation Calls */
$('.auform').live('focusout',function(e){
	var id = $(e.target).attr('id').replace(/\//g,'\\\/');
	var cont = $('.' + id + '_container');
	cont.removeClass('sffocus');
	setTimeout(function(){
		if(!cont.hasClass('sffocus'))
			validate(e.target);
		},0);
	});
$('.auform').live('focusin', function(e){
	var id = $(e.target).attr('id').replace(/\//g,'\\\/');
	$('.' + id + '_container').addClass('sffocus');
	});

/* DoubleClick Block */
var submit=1; var timerid=0;
var reset = function() {
        submit=1;
        clearTimeout(timerid);
        timerid  = 0;
        };
var doubleclick = function(self) {
	if(typeof(self) == "undefined")
		self = this;
	if(typeof(self.get) == "undefined")
		self = $(self);
	if(submit==1){
		submit=0;
		timerid=setTimeout("reset()",3000);
		if(self.attr('disableme') == 1){
			self.attr('disabled','disabled');
			setTimeout(function(){self.removeAttr('disabled')},1);
			}
		return 1;
		}
	return 0;
	};
$(function() {
        submit=1;
        $('.doubleclick').live('click',doubleclick);
        } );
var pageloaded=0;
var qstring="";
/* Validator */
function validate(i)
	{
	if(typeof(i)!='object'){
		i=$('#'+i);
		}
	if(typeof($(i).attr('name'))!='string' || typeof($(i).attr('id')) != 'string'){
		//Object is not real element
		return;
		}
	//Create namespaces so we don't change the elements
	var name=$(i).attr('name');
	var value=$(i).val();
	if($(i).attr('type')=='radio'){
		if($('[name='+name+']',$(i).parent().parent()).is(':checked')){
			value=$('[name='+name+']:checked',$(i).parent().parent()).val();
			}
		else{
			value='';
			}
		}
	$('.validation').filter('[value*=conditional=' + name + ']').each(function(){
		var nname=$(this).attr('name').match('^v:(.*)$')[1];
		$('#' + nname).blur();
		});
	var parent_name = name.split("/");
	if(parent_name === undefined){
		parent_name = [name];
		}
	parent_name = parent_name[0];
	var validator = 'v:' + parent_name;
	if( typeof(defaultpageloaded) == "undefined" || (!pageloaded && parent_name==get_pagelast() || ( typeof(defaultpageloaded) != "undefined" && defaultpageloaded==1))){
		pageloaded=1;
		}
	else{
		pageloaded=defaultpageloaded;
		}
	var names=[];
	var hiddenfield = $(i).parents('.' + parent_name + '_container').find('.validation#v\\:' + parent_name);
	if(hiddenfield.length == 0)
		return;
	var pars=validator + '=' + hiddenfield.val();
	names.push(name);
	if($(i).hasClass('multifield')){
		var vals="";
		var new_parent=parent_name.replace('_international','');
		$('.' + parent_name + '_container [name][name^="'+new_parent+'"]:visible').each(function(){
			if($(i).attr('type')=='checkbox'){
				if($(this).is(':checked')){
					vals+="1";
					}
				}
			else if($(i).attr('type')=='radio'){
				if($('[name='+name+']').is(':checked')){
					vals=$('[name='+name+']:checked').val();
					pars += '&' + $(this).attr('name') + '=' + vals;
					}
				}
			else{
				pars += '&' + $(this).attr('name') + '=' + $(this).val();
				}
			});
		if($(i).attr('type')=='checkbox'){
			pars += '&' + $(i).attr('name') + '=' + vals;
			}
		}
	else{
		$(names).each(function(){
			var name=this;
			var vals="";
			$('[name=' + name + ']').each(function(){
				if($(i).attr('type')=='checkbox'){
					if($(this).is(':checked')){
						vals+="1";
						}
					}
				else if($(i).attr('type')=='radio'){
					if($(this).is(':checked')){
						pars += '&' + $(this).attr('name') + '=' + $('[name='+name+']:checked').val();
						}
					}
				else{
					pars += '&' + $(this).attr('name') + '=' + $(this).val();
					}
				});
			if($('[name=' + name + ']:checkbox').size()){
				pars += '&' + name + '=' + vals;
				}
			});
		}
	if(validator.match( /Phone/ ) && !validator.match( /Type|Temporary/ )){
		var new_parent=parent_name.replace('_international','');
		pars += '&' + 'v:' + new_parent +'_Type' + '=' + $('#v\\:'+ new_parent + '_Type').val();
		}

	var valval=hiddenfield.val()
	if(typeof(valval) != "undefined" && valval.match('conditional')){
		var args=valval.match('conditional=([^,]+)')[1];
		var field=$('#' + args);
		pars += '&' + args + '=';
		if(!field.is(':checkbox') || field.is(':checked')){
			pars += field.val();
			}
		}
	if(valval != ''){
		if(pageloaded || qstring.length > 4000){
			if(qstring != ""){
				pars +=qstring;
				qstring="";
				}
			$.get( '/VALIDATE?' + pars,function(data){show_errors(data,i);});
			}
		else{
			qstring +='&' + pars;
			}
		}
	}
function show_errors(request,field)
	{ 
	$.each(request.split("\n"),
		function (i,response)
			{
			// alert('Index:' + i + ' response: ' + response);
			var items = response.split(':');
			if ( items[0] == '' )
				{
				return true;
				}
			if ( items[1] == 'OK' )
				{
				var i=$('#'+items[0]);
				var val=i.val();
				var ok=0;
				if(items[0].match( "Country" )){
					if(val!='0')
						ok=1;
					}
				else if(i.attr('type')=='radio'){
					if(i.is(':checked') && val != 'No')
						ok=1;
					}
				else if(i.attr('type')=='checkbox'){
					if(i.is(':checked')){
						ok=1;
						}
					}
				else {
					if(val!=''){
						ok=1;
						}
					}
				if(ok){
					$('.' + items[0]+"_container [name][name^='"+items[0]+"']").addClass('ok').removeClass('error');
					}
				else{
					$('.' + items[0]+"_container [name][name^='"+items[0]+"']").removeClass('ok').filter(':not(.servererror)').removeClass('error');
					}
				}
			else{
				var container='.' + items[0] + '_container';
				$(container + ' [name][name^="'+items[0]+'"], ' + container + ' [name][name^="'+items[0]+'\/"]').addClass('error').removeClass('ok');
				}
			set_container(items[0] + '_container',field);
			return true;
			}
		);
	/*
	var block = $(field).parents('.repeatable:first');
	if(block.length){
		if(blocks.contents().is('.ok')){
			$('#'+repeat+'_empty_error').removeClass('error');
			}
		}
	*/
	}
function get_pagelast(){
	//return $('input, select, textarea').filter(':last').attr('id');
	var elem = $(null);
	if(document.forms.length > 0)
	elem = $(document.forms[document.forms.length-1].elements).filter(':not(:hidden, :submit, :image)').filter(':reallyvisible:last');
	return (elem.size()) ? elem.attr('id').match('^([^/]*)')[1] : '';
	}
function get_blocklast(field){
	if(	typeof(field) != "undefined" &&
		typeof(field.get) != "undefined" &&
		 $(field).length > 0
		 ){ 
		var id = $(field).parents('.repeatable:first').find('*').filter(function(){
			return $(this).filter('input, select, textarea').is(':not(:hidden, :submit, :image)');
			})
			.filter(':last').attr('id');
		if(typeof(id) != 'undefined')
			return id.match('^([^/]*)')[1];
		}
	return '';
	}
function set_container(container,field){
	var pagelast=get_pagelast();
	var blocklast=get_blocklast(field);
	var block = $(field).parents('.repeatable:first');
	if(block.length > 0){
		if(container.match( pagelast ) || container.match( blocklast ) || pageloaded ){
			set_blocks(block);
			}
		return true;
		}
//	var child=$(container).children();
	container=$('.'+container.replace(/\//g,'\\\/'));
	if(typeof($(container).attr('class'))=="undefined") return true;
	if($('.error', container).size()){
		$(container).addClass('error').removeClass('ok');
		}
	else{
		$(container).removeClass('error');
		if($('.ok', container).size()){
			$(container).addClass('ok');
			}
		else{
			$(container).removeClass('ok');
			}
		}
	return true;
	}
function set_blocks(block){
	var list = block.find('input:not(.validation), select, textarea').filter(':reallyvisible');
	var badlist=list.filter('.error');
	var goodlist=list.filter(':not(.error)');
	var goodcontlist=[];
	var goodcontcheck=[];
	$(goodlist).each(function(){
		var cont = $(this).parent().attr('class');
		cont = cont.replace(' ok','').replace(' error','').replace(' servererror','').replace(' multifield','').replace('generic_element','').replace('date','').replace(/ +/g,'.').replace(/ +$/,'').replace(/^ +/,'').replace(/\.$/,'').replace(/^ *\./,'');
		if(goodcontcheck[cont]!=1){
			goodcontcheck[cont]=1;
			goodcontlist.push(cont);
			}
		return true;
		});
	var str = "badlist:\n";
	badlist.each(function(i,f){
		str += f.name + ' = ' + f.value + "\n";
		return true;
		});
	str += "goodcontlist\n" + goodcontlist.join("\n");

	$.each(goodcontlist,function(i,v){ //Add oks to the containers that have oks in them ...
		set_container(v);
		return true;
		});
	if(goodlist.size()){
		$(badlist).each(function(){ //Add errors to a block because there is one good element in it...
			$('.'+$(this).attr('name')+'_container').addClass('error').removeClass('ok');
			return true;
			});
		}
	else{ // Remove errors to the block because there are no finished blocks in it...
		$(badlist).each(function(){
			$('.'+$(this).attr('name')+'_container.error').removeClass('error');
			return true
			});
		}
	return true;
	}

var login_check_interval;
var last_login_cookie;
function ping (simple) {
	simple = (typeof simple == 'undefined') ? 0 : simple;
        $.ajax({
                type: 'GET',
                url: '/PING',
                cache: false,
                success: function(data,status){
                        setTimeout("ping('" + simple + "');", 10000);
                        if ( data.match('OK') ){
				show_logged_in();
                                }
			else if( data == '' ){
				
				}
                        else{
                                if ( ! $('iframe#loggedout').length )
                                        {
					$('<div class="loggedout" style="background-color:#000; top:0px; left:0px; width:100%; height:100%; position:fixed; z-index:20;"></div>').fadeTo('fast',0.70).appendTo('body');
					if ( simple )
						{
                                        	$('<iframe style="border:5px solid #cccccc; position:absolute; top:40%; left:40%; background-color:#fff; z-index:1000; overflow:hidden; box-shadow:0px 0px 30px #333;" width=300 height=225 src="/login?_login_popup=simple&_login_inactivity=1&service=https://www.andrews.edu/login/success" id="loggedout"></iframe>').appendTo('body');
						}
					else
						{
                                        	$('<iframe style="border:5px solid #cccccc; position:absolute; top:40%; left:40%; background-color:#fff; z-index:1000; overflow:hidden; box-shadow:0px 0px 30px #333;" width=700 height=350 src="/login?_login_popup=1&_login_inactivity=1&service=https://www.andrews.edu/login/success" id="loggedout"></iframe>').appendTo('body');
						}
                                        // Start checking for authentication cookie changes
                                        $('body').append("<script src='/code/js/cookies.js'></script>");

                                        last_login_cookie = $.cookie('CHOCOLATE_CHIP');
                                        login_check_interval = setInterval('check_login_cookie()', 1000);
                                        }
                                }
                        },
                error: function(){
                        setTimeout("ping('" + simple + "');", 10000);
                        }
                });
        }
function show_logged_in(){
	//If there is a login iframe there
	if( $('iframe#loggedout').length )
		{
		// Remove the iframe
		$('iframe#loggedout').remove();
		// Fade the rest of the page back to 100%
		$('.loggedout').remove();
		}
	}

function zeroFill( number, width )
{
	width -= number.toString().length;
	if ( width > 0 ) return new Array( width + (/\./.test( number ) ? 2 : 1) ).join( '0' ) + number;
	return number;
}
function check_login_cookie()
        {
        // If the cookie changes
        if ( $.cookie('CHOCOLATE_CHIP') != '' && $.cookie('CHOCOLATE_CHIP') != last_login_cookie )
                {
                clearInterval(login_check_interval);
		// We are logged in
		// Stop checking if we've logged back in...

		// Display page since we are logged in again
		show_logged_in();
                }
        }


