/*---------------------------------------------------------------------------*/
function submitQuestion(how)
{
 with(this.document.eForm)
 {
  qobj = (typeof(finalquestion) != 'undefined')?finalquestion:question;

  if(stripWS(qobj.value).length <= 0 || qobj.value == jsMessages['330818'])
  {
   alert(jsMessages['330817']);
   qobj.value = jsMessages['330818'];
  }
  else if(typeof(preferredspecialty) != 'undefined' && preferredspecialty.selectedIndex <= 0)
  {
   alert(jsMessages['330819']);
  }
  else
  {
   if(typeof(username) != 'undefined')
   {
    username.value = '';
	password.value = '';
   }

   // action = '/questions/';
   submit();
  }
 }
}


/*---------------------------------------------------------------------------*/
function getQuestion(that)
{
 that.value = '';
 that.focus();
}


/*---------------------------------------------------------------------------*/
function setQuestion(that)
{
 if(stripWS(that.value).length <= 0)
 {
  that.value = jsMessages['330818'];
 }
}


/*---------------------------------------------------------------------------*/
function clearQuestion()
{
	if(confirm('Click OK to confirm that you really want to cancel this question?')){
		with(this.document.eForm)
		{
			question.value = clearMarker;
			submit();
		}
	}
}


/*---------------------------------------------------------------------------*/
function submitQuestion()
{
    $("#questionForm").submit();
}


/*---------------------------------------------------------------------------*/
function nextPage(page)
{
	
 with(this.document.getForm)
 {
  pagenumber.value = page;
  submit();
 }
}



/*---------------------------------------------------------------------------*/
function addToCart(controlNumber)
{
 with(this.document.eForm)
 {
  cartItem.value = controlNumber;
  submit();
 }
}


/*---------------------------------------------------------------------------*/
function login(myForm, isButton) {
	if (myForm.username.value.search(/^\s*$/) == -1 &&
	myForm.password.value.search(/^\s*$/) == -1) {
		if(isButton){
			myForm.submit();
		}else{
			return true;
		}
	} else {
		alert('You must fill in both a username and password. Please try again.');
		return false;
	}
}


function nonpopLogin(f){
	//f is the nonpopup login form.
	var userVal = f.elements['nonpop_username'].value;
	var passVal = f.elements['nonpop_password'].value;
		
	if(userVal != '' && userVal != 'User Name' &&
	   passVal != '' && passVal != 'Password') {
		document.forms['lForm'].elements['username'].value = userVal;
		document.forms['lForm'].elements['password'].value = passVal;
		login(document.forms['lForm'], true);
	}
	return false;
}

/*
 * These are for the input boxes changing there value when people click in them.
 */
function focusInputText(inputBox, defaultText){
	var value=inputBox.value;
	if(value == defaultText){
		inputBox.value='';
		inputBox.style.color = '#444444';
		if(defaultText == 'Password' || defaultText == 'Confirm Password'){
			togglePasswordText(true, inputBox, defaultText);
			//I have to do this here because if not then IE doesn't focus on it.
			document.getElementById(inputBox.id).focus();
		}
	}
}

function blurInputText(inputBox, defaultText){
	value=inputBox.value;
	if(value==''){
		inputBox.value = defaultText;
		inputBox.style.color = '#7D7D7D';
		if(defaultText == 'Password' || defaultText == 'Confirm Password'){
			togglePasswordText(false, inputBox, defaultText);
			document.getElementById(inputBox.id).value = defaultText;
		}
	}
}

function togglePasswordText(switchToPassword, inputBox, defaultText){
	if(switchToPassword){
		var newInput = createNewInput('PASSWORD', inputBox.name, inputBox.id,inputBox.className);
	}else{
		var newInput = createNewInput('TEXT', inputBox.name, inputBox.id, inputBox.className);
	}
	
	newInput.onblur = inputBox.onblur;
	newInput.onfocus = inputBox.onfocus;
	//do not remove these onblur and onfocus set to null. Safari neds this because when replaceChild is called safari will call the inputBox's onBlur.
	inputBox.onblur = null; 
	inputBox.onfocus = null;
	
	inputBox.parentNode.replaceChild(newInput,inputBox);
	if(switchToPassword){
		document.getElementById(newInput.id).focus();
	}
	
}

function createNewInput(type, name, id, theClassName){
	var input = document.createElement('INPUT');
	input.type = type;
	input.className = theClassName;
	input.id = id;
	input.name = name; 
	return input;
}


/*---------------------------------------------------------------------------*/
function changeCaptcha()
{
 with(this.document.eForm)
 {
  captcha.value = '__change__';
  submit();
 }     
}


/*---------------------------------------------------------------------------*/
function autoRenewal()
{
 with(this.document.eForm)
 {
  optout.checked = true;
  submit();
 }
}

/*
 * This function will take you to the page you send to it.
 * VOID mesGo ( STRING path )
 * 
 */

function mesGo(path){
	window.location = path;
}
/*
 * This handles the listentome popup.
 *
 */

function listenToMe(episode)
{
 episodeLocation = '/audio/listen/' +episode+ '/';

 rWin = window.open(episodeLocation
                   ,'rWin'
                   ,'height=470,width=595,resizable');
}
/*
 * This handles any other popup
 *
 */

function openPopUp(location,width,height)
{
 rWin = window.open(location
                   ,'rWin'
                   ,'height='+height+',width='+width+',resizable');
}


/*
 * The function will toggle an element's display
 * VOID toggleDisplay ( HTMLELEMENT element) 
 */

function toggleDisplay(element){
	if(element.style.display == 'none'){
		element.style.display = 'block';
	}else{
		element.style.display = 'none';
	}
}


function setSorting(sortColumn, sort){
	//if sort is true that means we are sorting 
	//if it is false then we want to take it out of the sorting.
	var f = document.forms['getForm'];
	//add the sort to the form.
	if(sort){
		var newInput = document.createElement('INPUT');
		newInput.setAttribute('type', 'hidden');
		newInput.name = 'sort[]';
		newInput.value = sortColumn;
		f.appendChild(newInput);
	}else{
		//if sort is false that means that they have already added it to the form so we have to go and delete it.
		for(var i = 0; i < f.elements.length; i++){
			if(f.elements[i].name == 'sort[]' && f.elements[i].value == sortColumn){
				f.elements[i].parentNode.removeChild(f.elements[i]);
			}
		}
	}
	document.forms['getForm'].submit();
}

function addToGetForm(name, value){
	var f = document.forms['getForm'];
	if(f.elements[name]){
		f.elements[name].value = value;
	}else{
		var newInput = document.createElement('INPUT');
		newInput.setAttribute('type', 'hidden');
		newInput.name = name;
		newInput.value = value;
		f.appendChild(newInput);
	}
}

function displaySubgroupDropdown(id){
	var parentDiv = document.getElementById('groupDDContainer');
	if(id == 'null'){
		parentDiv.style.display = 'none';
		return;
	}
	
	var spanToDisplay = document.getElementById('subclientDD' + id);
	
	var spans = parentDiv.getElementsByTagName('SPAN');
	for(var i = 0; i < spans.length; i++){
		spans[i].style.display = 'none';
		var selects = spans[i].getElementsByTagName('SELECT');
		for(var a = 0; a < selects.length; a++){
			selects[a].value = null;
		}
	}
	
	var spanToDisplaySelect = spanToDisplay.getElementsByTagName('SELECT');
	if(!spanToDisplaySelect.length){
		parentDiv.style.display = 'none';
	}else{
		parentDiv.style.display = 'block';
	}
	
	spanToDisplay.style.display = 'inline';
}


function SAMLformSubmit(formID, formPath, SAML_field, SAML_data) {
    var formID;
    var frm = eval('document.' + formID);
	    document.getElementById(formID).action = formPath;
	    document.getElementById(SAML_field).value = base64decode(SAML_data);
	    frm.submit();
 }

if (typeof showTreeView != 'undefined') {
	$(document).ready(function(){
	
	  $("#side-tree").treeview({
					collapsed: true,
					animated: "slow",
					unique: true,
					persist: "cookie",
					cookieId: "side-tree"
	  });
	 })
}


/* 	Home page rotating Banner.
*	The variables numSlide and totalSlides
*	are defined in home.unsigned.skin
*/
var delay = 8000;	
var isgoing = true;
var timer;
var current;

function homePageStuff() {

	current = $('#msg'+numSlide);
					
    timer = setTimeout("nextItem()",delay);
	
    
	/* Home Page Slider Stuff */
	$(function() {
		$("#slider1").slider({
			slide: function(event, ui) {
				$('a#feeling').focus();
			},
			stop: function(event, ui) {
				if (ui.value <= 8) {
					$('#slider1 a').css('left',0);
					$('a#feeling').attr('href','/guidedsolutions/library/happy/');
				}
				else if (ui.value <= 24) {
					$('#slider1 a').css('left','16%');
					$('a#feeling').attr('href','/guidedsolutions/library/afraid/');
				}
				else if (ui.value <= 40) {
					$('#slider1 a').css('left','32%');
					$('a#feeling').attr('href','/guidedsolutions/library/angry/');
				}
				else if (ui.value <= 55) {
					$('#slider1 a').css('left','48%');
					$('a#feeling').attr('href','/guidedsolutions/library/lonely/');
				}
				else if (ui.value <= 71) {
					$('#slider1 a').css('left','63%');
					$('a#feeling').attr('href','/guidedsolutions/library/sad/');
				}
				else if (ui.value <= 89) {
					$('#slider1 a').css('left','80%');
					$('a#feeling').attr('href','/guidedsolutions/library/stressed/');
				}
				else {
					$('#slider1 a').css('left','100%');
					$('a#feeling').attr('href','/guidedsolutions/library/worried/');
				}
			}
		});
		$("#slider2").slider({
			slide: function(event, ui) {
				$('a#help').focus();
			},
			stop: function(event, ui) {
				if (ui.value <= 15) {
					$('#slider2 a').css('left',0);
					$('a#help').attr('href','/guidedsolutions/library/life.skills/');
				}
				else if (ui.value <= 48) {
					$('#slider2 a').css('left','32%');
					$('a#help').attr('href','/guidedsolutions/library/parenting/');
				}
				else if (ui.value <= 83) {
					$('#slider2 a').css('left','65%');
					$('a#help').attr('href','/guidedsolutions/library/relationships/');
				}
				else {
					$('#slider2 a').css('left','100%');
					$('a#help').attr('href','/guidedsolutions/library/addiction/');
				}
			}
		});
	});
}

function togglePlay() {
	if (isgoing) {
		clearTimeout(timer);
		$('#toggle').css('background-position', '-39px -22px');	
		isgoing = false; 
	} else {
		nextItem();
		isgoing = true; 
		$('#toggle').css('background-position', '-26px -22px');	
	}
}

function nextItem(num) {
	if(num==null){
		num = parseInt(current.attr('id').replace('msg', ''));
		if (num == totalSlides) { 
			num = 1;
		} else {
			num += 1;
		}
	}
	clearTimeout(timer);
	
	$('.control').css('background-position', '0 -22px');
	$('#item'+num).css('background-position', '-13px -22px');
	
	current.fadeOut(500, function(){		
		current.hide();
	});
	
	$('#msg'+num).fadeIn(500, function() {
		current = $("#msg"+num)
	});
	
	
	timer = setTimeout("nextItem()",delay);
	
	if (!isgoing) {
		isgoing = true; 
		$('#toggle').css('background-position', '-26px -22px');
	}
}



/* For Login on Register Pages */
function logMeIn()
{
 with(this.document.eForm)
 {
  if(username.value.length <= 0 || password.value.length <= 0)
  {
   alert(jsMessages['330817']);
   if(username.value.length <= 0)
    username.focus();
   else
    password.focus();
  }
  else
  {
   for(i=0;i<elements.length;i++)
   {
    switch(elements[i].type)
    {
     case 'text':
     case 'password':
	  if(elements[i].name != 'password' && elements[i].name != 'username')
	   elements[i].value = '';
	 break;

	 case 'select-one':
	  elements[i].selectedIndex = 0;
	 break;

	 case 'checkbox':
	  elements[i].checked = false;
	 break;

    } // end switch(type)
   } // end for(i)

   // if(confirm('ok to submit?')) submit();
   submit();

  } // end if([populated])
 } // end with(form)
}

function registerMe()
{
	document.eForm.submit();
}

/* End of Register Page */

/* Some Modal Controls */    
function closeLoginWIndow() {
	with(this.document.eForm)
	{
	username.value = '';
	password.value = '';
	}
}
/*
function fadeLogin() {
	centerPopup();
	loadPopup();
	if(document.getElementById('login-options')) {
		document.getElementById('login-options').getElementsByTagName('input').item(0).focus();
	}
}*/
function productAdded() {
	openModal(document.getElementById('popupCart').innerHTML, 'productAdded1');
}
function subscribeNow(recordID) {
	alert('popup subscribe now window for ' +recordID);
}
/* End of Popup Controls */


/* General Eval Results Page */
function toggleContent(divToShow) {
	
	if ($("#"+divToShow).hasClass("noDisplay")) {
		$("#"+divToShow).removeClass("noDisplay");		
		$("#"+divToShow).prev().children('img').attr("src", "/themes/expo/images/global/minus_green.png");
	} else {
		$("#"+divToShow).prev().children('img').attr("src", "/themes/expo/images/global/plus_green.png");
		$("#"+divToShow).addClass("noDisplay");
	}
}

/* Alphanumeric allows you to restrict certain characters on input boxes */
eval(function(p,a,c,k,e,d){e=function(c){return(c<a?"":e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--){d[e(c)]=k[c]||e(c)}k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1};while(c--){if(k[c]){p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c])}}return p}('(2($){$.c.f=2(p){p=$.d({g:"!@#$%^&*()+=[]\\\\\\\';,/{}|\\":<>?~`.- ",4:"",9:""},p);7 3.b(2(){5(p.G)p.4+="Q";5(p.w)p.4+="n";s=p.9.z(\'\');x(i=0;i<s.y;i++)5(p.g.h(s[i])!=-1)s[i]="\\\\"+s[i];p.9=s.O(\'|\');6 l=N M(p.9,\'E\');6 a=p.g+p.4;a=a.H(l,\'\');$(3).J(2(e){5(!e.r)k=o.q(e.K);L k=o.q(e.r);5(a.h(k)!=-1)e.j();5(e.u&&k==\'v\')e.j()});$(3).B(\'D\',2(){7 F})})};$.c.I=2(p){6 8="n";8+=8.P();p=$.d({4:8},p);7 3.b(2(){$(3).f(p)})};$.c.t=2(p){6 m="A";p=$.d({4:m},p);7 3.b(2(){$(3).f(p)})}})(C);',53,53,'||function|this|nchars|if|var|return|az|allow|ch|each|fn|extend||alphanumeric|ichars|indexOf||preventDefault||reg|nm|abcdefghijklmnopqrstuvwxyz|String||fromCharCode|charCode||alpha|ctrlKey||allcaps|for|length|split|1234567890|bind|jQuery|contextmenu|gi|false|nocaps|replace|numeric|keypress|which|else|RegExp|new|join|toUpperCase|ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('|'),0,{}));

var currentPage = 0;
function showPage(divToShow) {
	
	scroll(0,0);
	
	$('.page'+currentPage).addClass('noDisplay');
	$('.tab'+currentPage).removeClass('current');
	
	if(isNaN(divToShow)) {
		if(divToShow == 'next') {
			divToShow = parseInt(currentPage) + 1;
		} else {
			divToShow= parseInt(currentPage) - 1;	
		}
	}
	
	$('.page'+divToShow).removeClass('noDisplay');
	$('.tab'+divToShow).addClass('current');
	currentPage = divToShow;
	
	if(currentPage > 0) {
		$('#prevButton').removeClass('noDisplay');
		$('#nextButton').removeClass('noDisplay');
                $('#beginButton').addClass('noDisplay');
	} else {
		$('#prevButton').addClass('noDisplay');
		$('#nextButton').addClass('noDisplay');
                $('#beginButton').removeClass('noDisplay');
	}
	
	//lastPage is defined in expo.guidedsolutions.tabs.skin
	if(currentPage == lastPage) {
		$('#nextButton').addClass('noDisplay');
	}
        
	if(get_cookie(guidedSolution)) {
		delete_cookie(guidedSolution)
	}
	set_cookie(guidedSolution, currentPage, 2030, 12, 31, '','',true);		
}

// Creates an iFrame in the location specified by whereToPut on the page
function loadModule(whereToPut, pageToLoad, lesson, workshop)
{
        whereToPut.html('');
        $('<iframe />', {
            frameborder: '0',
            scrolling: 'no',
            width: '100%',
            height: '100%',
            src: pageToLoad
        }).appendTo(whereToPut);

        if(lesson) {
            var queryParams = "?lesson=" + lesson;
            
            if (workshop)
            {
                queryParams +="&workshop=" + workshop;
            }
                
            var bob = $.get("/api/Workshop/setCurrentWorkShopLesson/" + queryParams);
        }
}

function videoControls() {
	$('.video-control').click(function() {
            var current = $(this);
            var video = $(current).siblings('.video');

		$(video).removeClass("noDisplay");
                $(video).children(".video-control").css('display','none');
		$(video).children('#SlideContent').attr({'wmode':'opaque'}); // Fix for IE close btn
	});
	
	$('.close-video').click(function() {
		$('.video').addClass("noDisplay");
		$('.video-control').removeAttr('style');
	});	
}

function checkCookie(which) {
	if(get_cookie(which)) {
		showPage(get_cookie(which));
	} else {
		$('.tab0').addClass('current');
	}
}

$('.disabledBtn').click(function() {
	openModal(document.getElementById('loginForm').innerHTML, 'login-options');
});
$('.disabled').click(function() {
	openModal(document.getElementById('loginForm').innerHTML, 'login-options');
});

/* Admin Pages */


/* Form upload javascript. Currently only used on Company Admin pages. */
// Control file-upload confirmation modal
/*
 *var submitMe;
function displayModal(formToSubmit)
{
	// Open the modal and set which form to submit
	if($('#'+formToSubmit.replace('Form',"")+"1").val()) {
		submitMe = formToSubmit;
		openModal(document.getElementById('confirmationWindow').innerHTML, 'login-options-no-join-now');
	} 
}
*/
function closeAndSubmit(submitMe) {
	// close the modal and submit the question.
	$("#"+submitMe).submit(); // submitQuestion();
}

/* This code is to control behavior for the file input styles */
function changeText(name) {
	var fileInputID = name + '1';
	var fileName = document.getElementById(fileInputID).value; // Get the file name from file input
	fileName = fileName.replace(/C:\\fakepath\\/, ""); // Remove fakepath from IE
	document.getElementById(name).innerHTML = fileName; // Replace text in visible div
}

function adminJs() {
	$('#yes').click(function() {
		$('#subGroupDropdown').removeClass("noDisplay");
	});
	$('#no').click(function() {
		$('#subGroupDropdown').addClass("noDisplay");
	});
	
	/* Control behavior to edit the group name */
	$('#editSave').click(function() {
		$('.editInfo').addClass('noDisplay');
		$('.editMe').removeClass('noDisplay');
		$('#editSave').html('');
		$('#saveNewName').attr("class", "floatRight");
	});
	
	$('#editGroup').change(
            function (){
                    $('#editGroup').submit();
            }
	);
	
	$('#companyLookup').change(function(){
		$('#companyLookupForm').submit();
	});

        $('input[name=thirdPartyRegistrationFlag]').change(function(){
            if( $('input[name=thirdPartyRegistrationFlag]').attr('checked')) {
                $('.third_party').slideDown();
            } else {
                $('.third_party').slideUp();
                $('#thirdPartyRegistrationForm input[type=text]').val('');
            }
	});

        $('.tab1').click(function() {
            $('.opt1').show();
            $('.opt2').hide();
            $('.tab2').addClass('notCurrent');
            $('.tab1').removeClass('notCurrent');
        });

        $('.tab2').click(function() {
            $('.opt2').show();
            $('.opt1').hide();
            $('.tab1').addClass('notCurrent');
            $('.tab2').removeClass('notCurrent');
            //$('input[name=iFrameUrl]').val('');
        });

        $('input[name="iFrameUrl"]').blur(function(){
            $('input[name=imageSrcUrl]').val('');
            $('input[name=imageUrl]').val('');
        });

        $('input[name="imageSrcUrl"]').blur(function(){
            $('input[name=iFrameUrl]').val('');
        });

}

/*  Makes sure the fields passed in
 *  contain http:// or https:// at the beginning
 *  of the field; if not prepend http:// 
 */
function check_url(fields) {
    var value = '';
    $.each(fields, function() {
        if($('input[name="'+this+'"]').val() != '') {
            value = $('input[name="'+this+'"]').val();
            value = value.split(' ').join('');
            if(value.indexOf("http://") == -1 && value.indexOf("https://") == -1) {
                $('input[name="'+this+'"]').val('http://'+$('input[name="'+this+'"]').val());
            }
        }
   });
}


/* Remove space from url fields. This helps for when people
 * copy and paste urls that have a space at the beginning or end.
*/
function remove_spaces(that) {
    that.value = that.value.split(' ').join('');
}

/**
* jQuery Cookie plugin
*
* Copyright (c) 2010 Klaus Hartl (stilbuero.de)
* Docs: https://github.com/carhartl/jquery-cookie/
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
*/
jQuery.cookie = function (key, value, options) {

    // key and value given, set cookie...
    if (arguments.length > 1 && (value === null || typeof value !== "object")) {
        options = jQuery.extend({}, options);

        if (value === null) {
            options.expires = -1;
        }

        if (typeof options.expires === 'number') {
            var days = options.expires, t = options.expires = new Date();
            t.setDate(t.getDate() + days);
        }

        return (document.cookie = [
            encodeURIComponent(key), '=',
            options.raw ? String(value) : encodeURIComponent(String(value)),
            options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
            options.path ? '; path=' + options.path : '',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''
        ].join(''));
    }

    // key and possibly options given, get cookie...
    options = value || {};
    var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};

/* 	todo: Verify that there are no other places the above jQuery Cookie function
* 	is being used and use the following instead 
*/ 
function set_cookie ( name, value, expires_year, expires_month, expires_day, path, domain, secure ) {
	var cookie_string = name + "=" + escape ( value );
	
	if ( expires_year ) {
		var expires = new Date ( expires_year, expires_month, expires_day );
		cookie_string += "; expires=" + expires.toGMTString();
	}	
	if ( path )
		cookie_string += "; path=" + escape ( path );
	if ( domain )
		cookie_string += "; domain=" + escape ( domain );
	if ( secure )
		cookie_string += "; secure";
	document.cookie = cookie_string;
}
function delete_cookie ( cookie_name ) {
	var cookie_date = new Date ( );  // current date & time
	cookie_date.setTime ( cookie_date.getTime() - 1 );
	document.cookie = cookie_name += "=; expires=" + cookie_date.toGMTString();
} 
function get_cookie ( cookie_name ) {
	var results = document.cookie.match ( '(^|;) ?' + cookie_name + '=([^;]*)(;|$)' );
 	if ( results )
   	return ( unescape ( results[2] ) );
  	else
   	return null;
}

function addRoundedCorners(o) {
	if(!$.browser.msie) {
		$(o).addClass('rounded');	
	}
}

function clearMe(that, msg) {
	if (that.value == msg) {
		that.value = '';
	} else if(that.value == '') {
		that.value = msg;
	}
}

function inArray(needle, haystack) {
    var length = haystack.length;
    for(var i = 0; i < length; i++) {
        if(haystack[i] == needle) return true;
    }
    return false;
}

function doAjax(formToSend, formHandlerURL, successCallBack, errorCallBack) {
	$('.serverResponse').html('');
	$(formToSend+' .loadingIcon').show();
        var data = $(formToSend).serialize();

        var rawSuccessCallBack = '';
        if ( typeof successCallBack != 'undefined') {
            rawSuccessCallBack = function (response) {
                 successCallBack(formToSend, response);
            }
        }
        else
        {
            rawSuccessCallBack = function (response) {
                $(formToSend+' .loadingIcon').fadeOut(300, function() {
                        $('.serverResponse').html(response.message)
                        .hide()
                        .fadeIn(1200);
                })
            }
        }

        var rawErrorCallBack = '';
        if ( typeof errorCallBack != 'undefined') {
            rawErrorCallBack = function (response) {
                 errorCallBack(formToSend, response);
            }
        }
        else
        {
            rawErrorCallBack = function (response) {
                $(formToSend+' .loadingIcon').fadeOut(300, function() {
                        $('.serverResponse').html(response.message)
                        .hide()
                        .fadeIn(1200);
                })
            }
        }

	return rawAjax(data, formHandlerURL, rawSuccessCallBack, rawErrorCallBack);

}

function rawAjax(data, formHandlerURL, successCallBack, errorCallBack) {
    $.ajax({
		type: "POST",
		url: formHandlerURL,
		data: data,
		dataType: 'json',
                async:true,
		success: function(response) {
            successCallBack(response);
		},
		error: function(response) {
            errorCallBack(response);
		}
	});

	return false;
}

// The jquery alphanumeric is causing crashes
// Todo: Replace all instances of the jquery alphanumeric with the following
/* code from qodo.co.uk */

// create as many regular expressions here as you need:
var digitsOnly = /[1234567890]/g;
var integerOnly = /[0-9\.]/g;
var alphaOnly = /[A-Za-z]/g;
var titles = /[A-Za-z0-9\ \(\)\:\-]/g;
var type_slugs = /[A-Za-z0-9\-\_]/g;
var notAlphaNumeric = /[^A-Za-z0-9\.]/g;

function restrictCharacters(myfield, e, restrictionType) {

	if (!e) var e = window.event
	if (e.keyCode) code = e.keyCode;
	else if (e.which) code = e.which;
	var character = String.fromCharCode(code);

        //alert("KeyCode = "+e.keyCode + ' = ' + character);

	// if they press enter, submit the form
	if (code==13) { this.blur(); return true; }

	// if they pressed esc... remove focus from field...
	if (code==27) { this.blur(); return false; }

	// ignore if they are press other keys
	// strange because code: 39 is the down key AND ' key...
	// and DEL also equals .
	// if (!e.ctrlKey && code!=9 && code!=8 && code!=36 && code!=37 && code!=38 && (code!=39 || (code==39 && character=="'")) && code!=40) {
	if (!e.ctrlKey && code!=9 && code!=8 && (code!=39 || (code==39 && character=="'"))) {
		if (character.match(restrictionType)) {
			return true;
		} else {
			return false;
		}
	}
}
/**
 * This is for processing a payment. We have to do a handful of stuff before we charge the persons credit card.
 * This function does what it needs to do. 
 * @return BOOL
 */

paymentBeingProcessedProcessCCPayment = false;

function processCCPayment(){
	if(paymentBeingProcessedProcessCCPayment){
		return;
	}
	
	var errorMessages = new Array();
	var f = document.getElementById('propayNewCCform');
	
	var itsaNewCard = isNewCard();
	
	handleBillingAddress();
	
	f.elements['CardNumber'].value = stripNonNumeric(f.elements['CardNumber'].value);
	var itsOK = checkNewCardFormForErrors();
	
	if(!itsOK){
		return;
	}
	
	if(itsaNewCard){
		handleNewCard();
	}else{
		handleKnownCard();
	}
	
	function handleNewCard(){
		submitForm();
	}
	
	//this is when we are using a save payment method
	function handleKnownCard(){
		f.action = f.elements['KnownCardFormPath'].value;
		submitForm();
	}
	
	function submitForm(){
		var html = '<div class="disableScreen"></div><h3>Processing Payment</h3> <p>Please wait...</p>';
		openModal(html, 'process_payment');
		f.submit();
		paymentBeingProcessedProcessCCPayment = true;
	}
	
	function handleBillingAddress(){
		if(!billingIsSameAsShipping()){
			f.elements['Address1'].value = f.elements['billingAddress1'].value;
			f.elements['City'].value = f.elements['billingCity'].value;
			f.elements['State'].value = f.elements['billingState'].value;
			f.elements['PostalCode'].value = f.elements['billingZipcode'].value;
		}
        
        f.elements['Address1'].value = killNonAlphaNumeric(f.elements['Address1'].value);
        f.elements['City'].value =  killNonAlphaNumeric(f.elements['City'].value);
        f.elements['PostalCode'].value = killNonAlphaNumeric(f.elements['PostalCode'].value);

	}
	
	function billingIsSameAsShipping(){
		return f.elements['sameAddresses'].checked;
	}
	
	function isNewCard(){
        var paymentCards = f.elements['paymentCards'];
		if(paymentCards.type != 'hidden' && paymentCards[0].type == 'radio'){
			for(i = 0 ; i < f.elements['paymentCards'].length; i++){
				if(f.elements['paymentCards'][i].checked){
					if(f.elements['paymentCards'][i].value == 'new'){
						return true;
					}
				}
			}
		}else{
			return true;
		}
		return false;
	}
	
	function cardMethodIsChecked(){
		 var paymentCards = f.elements['paymentCards'];
		if(paymentCards.type != 'hidden' && paymentCards[0].type == 'radio'){
			for(i = 0 ; i < f.elements['paymentCards'].length; i++){
				if(f.elements['paymentCards'][i].checked){
					return true;
				}
			}
		}else{
			//its a hidden value
			return true;
		}
		
		return false;
	}
	
	function stripNonNumeric(str){
		return str.replace(/\D/gi,'');
	}
	
	function checkNewCardFormForErrors(){
		var allgood = true;
		if(!cardMethodIsChecked()){
			errorMessages.push('You must choose a Credit Card to use for this transaction.');
			allgood = false;
		}
		
		if(isNewCard()){
			if(f.elements['CardNumber'].value.length < 12){
				errorMessages.push('The credit card number that you entered is incorrect.');
				allgood = false;
			}
			
			if(f.elements['PaymentTypeId'].value == ''){
				errorMessages.push('You must choose the credit card type.');
				allgood = false;
			}
			
			if(f.elements['ExpMonth'].value == ''){
				errorMessages.push('You must choose an expiration month.');
				allgood = false;
			}
			
			if(f.elements['ExpYear'].value == ''){
				errorMessages.push('You must choose an expiration year.');
				allgood = false;
			}
			
			if(f.elements['CVV'].value.length < 3){
				errorMessages.push('You must fill in the credit cards security code.');
				allgood = false;
			}
		}
		
		
				
		if(!billingIsSameAsShipping()){
			if(f.elements['billingAddress1'].value.length < 5){
				errorMessages.push('You must fill out the billing address');
				allgood = false;
			}
			if(f.elements['billingCity'].value.length < 4){
				errorMessages.push('you must fill out the billing city');
				allgood = false;
			}
			
			if(f.elements['billingState'].value == '__pick__'){
				errorMessages.push('You must choose a billing state.');
				allgood = false;
			}
			
			if(f.elements['billingZipcode'].value.length < 5){
				errorMessages.push('You must choose a billing zip code');
				allgood = false;
			}
		}
		
		if(!allgood){
			outputErrors();
			return false;
		}else{
			return true;
		}
	}
	
	function outputErrors(){
		var errorStr = errorMessages.join('<br/>');		
		document.getElementById('gYellowStatusMessageContents').innerHTML = errorStr;
		document.getElementById('gYellowStatusMessageContainer').className = 'errorMsg rounded';
		window.location.href = '#';
	}
}


/**
 * Checking if the password is OK
 */
function isValidPassword(password, outputCallback){
    var error = new Array();

    //check if they have at least 8 characters.
    if(password < 8){
        error.push('Passwords must have a least 8 characters');
    }
    
    //check if there is a number in the password.
    if(!(/\d/.test(password))){
        error.push('Passwords must have at least one number in them.');
    }

    if(error.length > 0){
        //call the callback to output the errors.
        //maybe instead of this we return the error array.
        if(outputCallback){
            outputCallback(error);
        }
        return false;
    }else{
        return true;
    }
}


function killNonAlphaNumeric(inputStr){
    return inputStr.replace(notAlphaNumeric, '');
}


function submitMe(form_id) {
    $('#'+form_id).submit();
}

/**
 *  Events Page stuff
 */

function eventsPage() {
    $('.tab1').click(function() {
            $('.opt1').show();
            $('.opt2').hide();
            $('.tab2').addClass('notCurrent');
            $('.tab1').removeClass('notCurrent');
    });

    $('.tab2').click(function() {
            $('.opt2').show();
            $('.opt1').hide();
            $('.tab1').addClass('notCurrent');
            $('.tab2').removeClass('notCurrent');
            //$('input[name=iFrameUrl]').val('');
    });
}

function toggle_vid(youtube_link, div_id_for_vid) {

	if($('#'+div_id_for_vid+' .youtube_video').css('display') == 'none') {
		$('#'+div_id_for_vid+' .youtube_video').css({'display':'none','height':'349px','margin-bottom':'25px'});
		$('#'+div_id_for_vid+' .youtube_video').slideDown('slow', function() {
		$('#'+div_id_for_vid+' a').text('Close Video');
		$('#'+div_id_for_vid+' .youtube_video').delay(100).html('<iframe width="560" height="345" src="'+youtube_link+'" frameborder="0" allowfullscreen></iframe>');
		});
	} else {
		$('#'+div_id_for_vid+' a').text('Watch the Webinar');
		$('#'+div_id_for_vid+' .youtube_video').html('');
		$('#'+div_id_for_vid+' .youtube_video').css({'display':'none','height':'0','margin-bottom':'0'});
	}
}


var temp_div_content = '';
function toggle_spanish(spanish_div, english_div) {
    if(temp_div_content==''){
         temp_div_content = $('.'+spanish_div).html();
    }
    if($('.spanish_button').text() == 'En EspañolEn Español'){
        $('.'+spanish_div).html($('.'+english_div).html());
        $('.spanish_button').text('In English');
    } else {
        $('.'+spanish_div).html(temp_div_content);
        $('.spanish_button').text('En Español');
    }
}

function toggle_div(class_of_div) {
    $(class_of_div).slideToggle();

}
/***
 * session timeout crap. does an ajax call to the api to see if the session has 
 * expired. If they have hit the server outside of the browser (IE flash) then it
 * won't think you are logged off. 
 * 
 * also this fixes the bug we had where it would check and see that they are still
 * actively using the site but it would still redirect them to the home page. 
 * 
 * 
 */

function checkIfSessionTimedOut(){
    //got to love this ajax call :)
    rawAjax({}, '/API/SessionTimeout/hasSessionExpired/', checkIfSessionTimedOutSuccess, function (){});
}
/**
 * success function for session timeout. redirects to the logout if they are expired.
 */
function checkIfSessionTimedOutSuccess(data){
    var sessionHasExpired = data.message;
    if(sessionHasExpired.isExpired){
        window.location = '/?logoff=timeout';
    }
    else{
        startSessionTimeoutTimer(sessionHasExpired.time);
    }
    
}


function startSessionTimeoutTimer(time){
    setTimeout(checkIfSessionTimedOut, time);
}
