// ShopElsevier.com - Modals
// © 2010 MBS Direct
// 06.17.2010 dh

$(document).ready(function(){

	// initialize sign in actions
	if ($("#sign-in-page").length)
		initializeSignInModul();

	// This automatically closes modal if the user clicks outside the modal or presses the "ESC" key
	$("#modal-focus, .close-modal").click(function(){  
		closeModal(false);
		return false;
	});
	$(document).keypress(function(e){  
		if (e.keyCode==27 && modalStatus==1)
			closeModal(false);  
	});

	// fixup sign in links
	$(".do-sign-in").live("click",function(){
		invokeSignIn($(this), 'normal', '');
		return false;
	});

	// fixup sign out links
	$(".do-sign-out, #AH_logoutNote3").live("click",function(){
		return packageConfirmLogout();
	});

	// fixup new account links
	$(".do-new-account").live("click",function(){
		invokeSignIn($(this), 'new', '');
		return false;
	});

	// fixup checkout links
	$(".do-checkout").live("click",function(){
		// see if logged in
		if ($("#account-navigation-login").find(".do-sign-in").length) {
			invokeSignIn($(this), 'checkout', 'checkout');
			return false;
		}

		// see if we need to collect extra customer info
		else if ($("#account-navigation-login").find(".need-update").length) {
			invokeSignIn($(this), 'update', 'checkout');
			return false;
		}
	});

	// fixup sign in links
	$(".learn-about-pageburst").click(function(){
		invokeLearn();
		return false;
	});

	// add incremental searches
	$(".smart-drop").SmartDrop();

});

/* ==================================================
               M O D A L   S E T U P
================================================== */

var modalStatus = 0; // disabled

/* ================================
 Invoke Modal "Focus"
================================ */

function invokeFocus(){ 
	if (modalStatus==0) {
		$("#modal-focus").css({"opacity": "0.55"});
		$("#modal-focus").fadeIn("slow");
		modalStatus = 1;
	}
}

/* ================================
 Close Modal
================================ */

function closeModal(isChild){
	if (isChild) {
		if (parent.modalStatus == 1) {
			parent.$(".modal").fadeOut("slow");
			parent.$("#modal-focus").fadeOut("slow");
			parent.$(".modal").removeClass("in-focus");
			parent.modalStatus = 0;
		}
	}
	else {
		if (modalStatus == 1) {
			$(".modal").fadeOut("slow");
			$("#modal-focus").fadeOut("slow");
			$(".modal").removeClass("in-focus");
			modalStatus = 0;
		}
	}
}

/* ================================
 Center Modal
================================ */

function centerModal(){
	var winW = $(window).width();
	var winH = $(window).height();
	var modalH = $(".in-focus").height();
	var modalW = $(".in-focus").width();	
	$(".in-focus").css({"position": "fixed","top": winH/2-modalH/2-20, "left": winW/2-modalW/2});
}

/* ==================================================
                   S I G N   I N
================================================== */

function invokeSignIn(thisEl, signInType, continueTo){
	var frameURL = loginURL + '&type=' + signInType;
	if (frameURL.match(/^https?:/))
		frameURL += '&redirect=Y';
	if (continueTo != '')
		frameURL += '&continueTo=' + encodeURIComponent(continueTo);

	loadingID++;
	ajaxShowLoading(thisEl, loadingID);
	$('#sign-in-frame').attr("src", frameURL).load(function(){
		ajaxHideLoading(loadingID);
		startSignIn();
	});
}

/* ==================================================
                     L E A R N
================================================== */

function invokeLearn(){
	$("#learn-modal").addClass("in-focus");
	centerModal();
	invokeFocus();
	$("#learn-modal").fadeIn("slow");
}


/* ---------------------------------------------------------------------------------------------- */
/* -- AZ: new code below ------------------------------------------------------------------------ */
/* ---------------------------------------------------------------------------------------------- */

/**
 *
 */
function initializeSignInModul(){

	// init which section we are looking at
	initializeSectionFocus();

	// init back links/actions
	initializeBackOptions();

	// init the sign in section
	initializeSignInOptions();

	// init the forgot password section
	initializeForgotPasswordOptions();

	// init the new account section
	initializeNewAccountOptions();

	// init the update account section
	initializeUpdateAccountOptions();

}

/**
 *
 */
function initializeSectionFocus(){

	// if we have a successful return, try and update the parent window displays
	var success = getUrlVar(window.location.search, 'success');
	switch (success) {
		case 'new':
		case 'update':
		case 'normal':
			successUpdateDisplays(success, successData);
			return;
			break;
	}

	// focus on the given section
	switch (getUrlVar(window.location.search, 'type')) {
		case 'new':
			$('#clipping').animate({scrollTop: '+500px'}, 1);
			$('#create-account').find("input[name='create-step']").attr("value", 1);
			break;
		case 'update':
			$('#clipping').animate({scrollTop: '+1750px'}, 1);
			$('#update-account-form').find("input[name='update-step']").attr("value", 1);
			break;
		default:
			$('#clipping').animate({scrollTop: '+250px'}, 1);
	}
}

/**
 * Back a Step
 */
function initializeBackOptions(){

	$(".action-step-back").hover(function(){
		$(this).animate({opacity: 0.8});
	}, function() {
		$(this).animate({opacity: 0.2});
	});

	$("#forgot-password .action-cancel, #forgot-password .action-step-back, #create-account-email .action-step-back").click(function(){
		$('#clipping').animate({scrollTop: '+250px'}, 1000);
		return false;
	});	

	$("#create-account-name .action-step-back").click(function(){
		$('#clipping').animate({scrollTop: '+500px'}, 1000);
		$('#create-account').find("input[name='create-step']").attr("value", 1);
		return false;
	});

	$("#create-account-password .action-step-back").click(function(){
		$('#clipping').animate({scrollTop: '+750px'}, 1000);
		$('#create-account').find("input[name='create-step']").attr("value", 2);
		return false;
	});

	$("#create-account-role .action-step-back").click(function(){
		$('#clipping').animate({scrollTop: '+1000px'}, 1000);
		$('#create-account').find("input[name='create-step']").attr("value", 3);
		return false;
	});

	$("#create-account-institution .action-step-back").click(function(){
		$('#clipping').animate({scrollTop: '+1250px'}, 1000);
		$('#create-account').find("input[name='create-step']").attr("value", 4);
		return false;
	});

	$("#update-account-role-field .action-step-back").click(function(){
		$('#clipping').animate({scrollTop: '+1750px'}, 1000);
		return false;
	});

	$("#update-account-institution-field .action-step-back").click(function(){
		$('#clipping').animate({scrollTop: '+2000px'}, 1000);
		$('#update-account-form').find("input[name='update-step']").attr("value", 1);
		return false;
	});
}

/**
 * Sign In
 */
function initializeSignInOptions(){

	// fixup password input
	var pwClear = $("#sign-in-account-password-clear");
	var pwEncrypt = $("#sign-in-account-password");
	initializePasswordInputs(pwClear, pwEncrypt);

	// fixup the sign in submit action
	$("#sign-in").submit(function(){
		var thisEl = $(this);
		var emailInput = thisEl.find("input[name='sign-in-account-email']");
		var emailDefault = (emailInput.attr("alt") != '') ? emailInput.attr("alt") : emailInput.attr("defaultValue");
		var passwordInput = thisEl.find("input[name='sign-in-account-password']");

		// client side validation
		if ($.trim(emailInput.val()) == '' || emailInput.val() == emailDefault) {
			$("#sign-in-account .alert-error").html(emailDefault).css({'left':'39px'}).fadeIn();
		 	return false;
		}
		else if (!$.isEmail(emailInput.val())) {
			$("#sign-in-account .alert-error").html('Your email must be a valid email address').css({'left':'39px'}).fadeIn();
		 	return false;
		}

		if ($.trim(passwordInput.val()) == '') {
			$("#sign-in-account .alert-error").html('Enter your password').css({'left':'308px'}).fadeIn();
		 	return false;
		}
		else if (!$.isVBPassword(passwordInput.val())) {
			$("#sign-in-account .alert-error").html('Your password must be 5-10 letters or digits').css({'left':'308px'}).fadeIn();
		 	return false;
		}

		// make ajax request
		$.ajax({
			type: 'POST',
			url: webservice,
			data: ({
				'ACTION':'sign_in_user',
				'email':emailInput.val(),
				'password':passwordInput.val()
			}),
			dataType: 'xml',
			success: function(data) {
				commonSuccessDisplay(thisEl, data);
				successSignIn(data);
			},
			error: commonErrorDisplay,
			loadingID: loadingID++,
			thisEl: thisEl
		});

		return false;
	});

	$("#sign-in-account-email, #sign-in-account-password-clear, #sign-in-account-password").mouseup(function(){
		$("#sign-in-account .alert-error").fadeOut();
	}).focus(function(){
		$("#sign-in-account .alert-error").fadeOut();
	});
}

/**
 * Forgot Password
 */
function initializeForgotPasswordOptions(){

	$("#sign-in-account .action-forgot-password").click(function(){	
		$('#clipping').animate({scrollTop: '+0px'}, 1000);
		return false;
	});

	$("#forgot-password").submit(function(){

		var thisEl = $(this);
		var emailInput = thisEl.find("input[name='forgot-password-email']");
		var emailDefault = (emailInput.attr("alt") != '') ? emailInput.attr("alt") : emailInput.attr("defaultValue");

		// client side validation
		if ($.trim(emailInput.val()) == '' || emailInput.val() == emailDefault) {
			$("#forgot-password .alert-error").html(emailDefault).fadeIn();
		 	return false;
		}
		else if (!$.isEmail(emailInput.val())) {
			$("#forgot-password .alert-error").html('Your email must be a valid email address').fadeIn();
		 	return false;
		}

		// make ajax request
		$.ajax({
			type: 'POST',
			url: webservice,
			data: ({
				'ACTION':'forgot_password',
				'email':emailInput.val()
			}),
			dataType: 'xml',
			success: function(data) {
				commonSuccessDisplay(thisEl, data);
				successForgotPassword(data);
			},
			error: commonErrorDisplay,
			loadingID: loadingID++,
			thisEl: thisEl
		});

		return false;
	});

	$("#forgot-password-email").mouseup(function(){
		$("#forgot-password .alert-error").fadeOut();
	}).focus(function(){
		$("#forgot-password .alert-error").fadeOut();
	});
}

/**
 * New Account
 */
function initializeNewAccountOptions(){

	$("#create-account-begin .action-continue").click(function(){	
		$('#clipping').animate({scrollTop: '+500px'}, 1000);
		$('#create-account').find("input[name='create-step']").attr("value", 1);
		return false;
	});

	// fixup password input
	var pwClearNew1 = $("#new-account-password-clear");
	var pwEncryptNew1 = $("#new-account-password");
	initializePasswordInputs(pwClearNew1, pwEncryptNew1);

	// fixup password confirm input
	var pwClearNew2 = $("#new-account-password-confirm-clear");
	var pwEncryptNew2 = $("#new-account-password-confirm");
	initializePasswordInputs(pwClearNew2, pwEncryptNew2);

	$('#create-account').submit(function(){

		var step = $(this).find("input[name='create-step']").val();

		switch (step) {
			case '2':
				regCheckName();
				break;
			case '3':
				regCheckPassword();
				break;
			case '4':
				regCheckRole();
				break;
			case '5':
				regCheckInstitution();
				break;
			case '1':
			default:
				regCheckEmail();
		}

		return false;
	});

	$("#new-account-email, #new-account-first-name, #new-account-last-name, #new-account-password, #new-account-password-clear, #new-account-password-confirm, #new-account-password-confirm-clear, #new-account-role, #new-account-institution").click(function(){
		$("#create-account .alert-error").fadeOut();
	}).focus(function(){
		$("#create-account .alert-error").fadeOut();
	});

}

/**
 *
 */
function initializePasswordInputs(pwClear, pwEncrypt){
	pwClear.parent().show();
	pwEncrypt.parent().hide();
	pwClear.focus(function(){
		pwClear.parent().hide();
		pwEncrypt.parent().show();
		pwEncrypt.focus();
	});
	pwEncrypt.blur(function(){
		if (pwEncrypt.val() == '') {
			pwEncrypt.parent().hide();
			pwClear.parent().show();
		}
	});
}

/**
 *
 */
function regCheckEmail(){

	var thisEl = $("#create-account-email");
	var emailInput = thisEl.find("input[name='new-account-email']");
	var emailDefault = (emailInput.attr("alt") != '') ? emailInput.attr("alt") : emailInput.attr("defaultValue");

	// client side validation
	if ($.trim(emailInput.val()) == '' || emailInput.val() == emailDefault) {
		$("#create-account .alert-error").html(emailDefault).css({'top':'640px', 'left':'160px'}).fadeIn();
		return false;
	}
	else if (!$.isEmail(emailInput.val())) {
		$("#create-account .alert-error").html('Your email must be a valid email address').css({'top':'640px', 'left':'160px'}).fadeIn();
		return false;
	}

	// make ajax request
	$.ajax({
		type: 'POST',
		url: webservice,
		data: ({
			'ACTION':'reg_check_email',
			'email':emailInput.val()
		}),
		dataType: 'xml',
		success: function(data) {
			commonSuccessDisplay(thisEl, data);
			successRegCheckEmail(data);
		},
		error: commonErrorDisplay,
		loadingID: loadingID++,
		thisEl: thisEl
	});

	return false;
}

/**
 *
 */
function regCheckName(){

	var thisEl = $("#create-account-name");

	var firstName = thisEl.find("input[name='new-account-first-name']");
	var firstNameValue = $.trim(firstName.val());
	var firstNameDefault = (firstName.attr("alt") != '') ? firstName.attr("alt") : firstName.attr("defaultValue");
	var lastName = thisEl.find("input[name='new-account-last-name']");
	var lastNameValue = $.trim(lastName.val());
	var lastNameDefault = (lastName.attr("alt") != '') ? lastName.attr("alt") : lastName.attr("defaultValue");

	// client side validation
	if (firstNameValue == '' || firstNameValue == firstNameDefault || firstNameValue.length > 11) {
		$("#create-account .alert-error").html('Enter your first name (1 to 11 characters)').css({'top':'890px', 'left':'63px'}).fadeIn();
		return false;
	}
	if (lastNameValue == '' || lastNameValue == lastNameDefault || lastNameValue.length > 18) {
		$("#create-account .alert-error").html('Enter your last name (1 to 18 characters)').css({'top':'890px', 'left':'315px'}).fadeIn();
		return false;
	}

	$('#clipping').animate({scrollTop: '+1000px'}, 750);
	$('#create-account').find("input[name='create-step']").attr("value", 3);
	return false;
}

/**
 *
 */
function regCheckPassword(){

	var thisEl = $("#create-account-password");

	var password = thisEl.find("input[name='new-account-password']");
	var passwordValue = $.trim(password.val());
	var passwordDefault = (password.attr("alt") != '') ? password.attr("alt") : password.attr("defaultValue");
	var passwordConfirm = thisEl.find("input[name='new-account-password-confirm']");
	var passwordConfirmValue = $.trim(passwordConfirm.val());
	var passwordConfirmDefault = (passwordConfirm.attr("alt") != '') ? passwordConfirm.attr("alt") : passwordConfirm.attr("defaultValue");

	// client side validation
	if (passwordValue == '' || passwordValue == passwordDefault || !$.isVBPassword(passwordValue)) {
		$("#create-account .alert-error").html('Your password must be 5-10 letters or digits').css({'top':'1140px', 'left':'63px'}).fadeIn();
		return false;
	}
	else if (passwordValue != passwordConfirmValue) {
		$("#create-account .alert-error").html('Confirm your password').css({'top':'1140px', 'left':'315px'}).fadeIn();
		return false;
	}

	$('#clipping').animate({scrollTop: '+1250px'}, 750);
	$('#create-account').find("input[name='create-step']").attr("value", 4);
	return false;
}

/**
 *
 */
function regCheckRole(){

	var thisEl = $("#create-account-role");

	// check to make sure a value is stored
	if ($.trim(thisEl.find("select[name='new-account-role-select']").val()) == '') {
		$("#create-account .alert-error").html('Select what type of customer you are').css({'top':'1390px', 'left':'225px'}).fadeIn();
		return false;
	}

	if ($.trim(thisEl.find("select[name='new-account-role-select']").val()) == 'Healthcare Practitioner') {
		// submit the request
		submitCreateAccount(thisEl, 'role');
	}
	else {
		$('#clipping').animate({scrollTop: '+1500px'}, 750);
		$('#create-account').find("input[name='create-step']").attr("value", 5);
	}
	return false;
}

/**
 *
 */
function regCheckInstitution(){

	var thisEl = $("#create-account-institution");
	var parentForm = $('#create-account');

	// check to make sure a value is stored
	if ($.trim(thisEl.find("select[name='new-account-institution-select']").val()) == '') {
		$("#create-account .alert-error").html('Find your institution').css({'top':'1640px', 'left':'111px'}).fadeIn();
		return false;
	}

	// submit the request
	submitCreateAccount(thisEl, 'institution');
	return false;
}

/**
 *
 */
function submitCreateAccount(thisEl, step){

	var parentForm = $('#create-account');

	// make ajax request
	$.ajax({
		type: 'POST',
		url: webservice,
		data: ({
			'ACTION':'reg_submit',
			'email':parentForm.find("input[name='new-account-email']").val(),
			'firstName':parentForm.find("input[name='new-account-first-name']").val(),
			'lastName':parentForm.find("input[name='new-account-last-name']").val(),
			'password':parentForm.find("input[name='new-account-password']").val(),
			'role':parentForm.find("select[name='new-account-role-select']").val(),
			'school':parentForm.find("select[name='new-account-institution-select']").val()
		}),
		dataType: 'xml',
		success: function(data) {
			commonSuccessDisplay(thisEl, data);
			successRegSubmit(data, step);
		},
		error: commonErrorDisplay,
		loadingID: loadingID++,
		thisEl: thisEl
	});
}

/**
 *
 */
function initializeUpdateAccountOptions(){

	$("#update-account-begin-field .action-continue").click(function(){	
		$('#clipping').animate({scrollTop: '+2000px'}, 1000);
		$('#update-account-form').find("input[name='update-step']").attr("value", 1);
		return false;
	});

	$('#update-account-form').submit(function(){

		var step = $(this).find("input[name='update-step']").val();

		switch (step) {
			case '2':
				updateCheckInstitution();
				break;
			case '1':
			default:
				updateCheckRole();
		}

		return false;
	});

	$("#update-account-role, #update-account-institution").click(function(){
		$("#update-account-form .alert-error").fadeOut();
	}).focus(function(){
		$("#update-account-form .alert-error").fadeOut();
	});

}

/**
 *
 */
function updateCheckRole(){

	var thisEl = $("#update-account-role-field");

	// check to make sure a value is stored
	if ($.trim(thisEl.find("select[name='update-account-role-select']").val()) == '') {

		$("#update-account-form .alert-error").html('Select what type of customer you are').css({'top':'2140px', 'left':'225px'}).fadeIn();
		return false;
	}

	if ($.trim(thisEl.find("select[name='update-account-role-select']").val()) == 'Healthcare Practitioner') {
		// submit the request
		submitUpdateAccount(thisEl, 'role');
	}
	else {
		$('#clipping').animate({scrollTop: '+2250px'}, 750);
		$('#update-account-form').find("input[name='update-step']").attr("value", 2);
	}
	return false;
}

/**
 *
 */
function updateCheckInstitution(){

	var thisEl = $("#update-account-institution-field");
	var parentForm = $('#update-account-form');

	// check to make sure a value is stored
	if ($.trim(thisEl.find("select[name='update-account-institution-select']").val()) == '') {
		$("#update-account-form .alert-error").html('Find your institution').css({'top':'2390px', 'left':'111px'}).fadeIn();
		return false;
	}

	// submit the request
	submitUpdateAccount(thisEl, 'institution');
	return false;
}

/**
 *
 */
function submitUpdateAccount(thisEl, step){
	var parentForm = $('#update-account-form');

	// make ajax request
	$.ajax({
		type: 'POST',
		url: webservice,
		data: ({
			'ACTION':'update_submit',
			'role':parentForm.find("select[name='update-account-role-select']").val(),
			'school':parentForm.find("select[name='update-account-institution-select']").val()
		}),
		dataType: 'xml',
		success: function(data) {
			commonSuccessDisplay(thisEl, data);
			successUpdateSubmit(data, step);
		},
		error: commonErrorDisplay,
		loadingID: loadingID++,
		thisEl: thisEl
	});
}

/**
 *
 */
function startSignIn(){
	$("#sign-in-modal").addClass("in-focus");
	centerModal();
	invokeFocus();
	$("#sign-in-modal").fadeIn("slow");
}

/**
 *
 */
function successForgotPassword(data){
	// return if we do NOT have a success flag
	if ($(data).find('FAILURE').text() == 'true') {
		$("#forgot-password .alert-error").html($(data).find('E_PASSWORD').text()).fadeIn();
		return false;
	}

	$("#forgot-password .alert-confirm").fadeIn().animate({opacity: 1}, 3000).fadeOut();
	$("#clipping").animate({opacity: 1}, 2000).animate({scrollTop: '+250px'}, 1000);
}

/**
 *
 */
function successSignIn(data){
	if ($(data).find('FAILURE').text() == 'true') {
		$("#sign-in-account .alert-error").html($(data).find('E_SIGNIN').text()).css({'left':'39px'}).fadeIn();
		return false;
	}

	// try to update the parent window displays
	tryUpdateDisplays('normal', data);
}

/**
 *
 */
function successRegCheckEmail(data){
	if ($(data).find('FAILURE').text() == 'true') {
		$("#create-account .alert-error").html($(data).find('E_CREATE').text()).css({'top':'640px', 'left':'160px'}).fadeIn();
		return false;
	}

	$('#clipping').animate({scrollTop: '+750px'}, 750);
	$('#create-account').find("input[name='create-step']").attr("value", 2);
}

/**
 *
 */
function successRegSubmit(data, step){
	if ($(data).find('FAILURE').text() == 'true') {
		if (step == 'role')
			var css = {'top':'1390px', 'left':'225px'};
		else
			var css = {'top':'1640px', 'left':'111px'};

		$("#create-account .alert-error").html($(data).find('E_CREATE').text()).css(css).fadeIn();
		return false;
	}

	// try to update the parent window displays
	tryUpdateDisplays('new', data);
}

/**
 *
 */
function successUpdateSubmit(data, step){
	if ($(data).find('FAILURE').text() == 'true') {
		if (step == 'role')
			var css = {'top':'2140px', 'left':'225px'};
		else
			var css = {'top':'2390px', 'left':'111px'};

		$("#update-account-form .alert-error").html($(data).find('E_CREATE').text()).css(css).fadeIn();
		return false;
	}

	// try to update the parent window displays
	tryUpdateDisplays('update', data);
}

/**
 *
 */
function successUpdateDisplays(type, data){

	// update the header displays
	parent.$("#account-institution").html(data['R_INSTITUTION']);
	parent.$("#account-greeting").html(data['R_GREETING']);
	parent.$("#account-navigation-login").html(data['R_LOGIN']);
	parent.$("#account-navigation-account").html(data['R_ACCOUNT']);

	// update checkout link
	parent.$("#cart-checkout .do-checkout").attr("href", data['R_LINKCHECKOUT']);

	// see if we need to collect extra customer information
	if (parent.$("#account-navigation-login").find(".need-update").length) {
		$('#clipping').animate({scrollTop: '+1750px'}, 1);
		$('#update-account-form').find("input[name='update-step']").attr("value", 1);
		return false;
	}

	// setup message to display
	if (type == 'new') {
		// setup account created message
		$('#clipping').animate({scrollTop: '+1500px'}, 1);
		var alertEl = $("#create-account .alert-confirm");
	}
	else if (type == 'update') {
		// setup account updated message
		$('#clipping').animate({scrollTop: '+2250px'}, 1);
		var alertEl = $("#update-account-form .alert-confirm");
	}
	else {
		// setup user logged in message
		$('#clipping').animate({scrollTop: '+250px'}, 1);
		var alertEl = $("#sign-in-account .alert-confirm");
	}

	// show message, hide the modal, then redirect if needed
	alertEl.fadeIn().animate({opacity: 1}, 2000, function() {
		closeModal(true);
	}).fadeOut(400, function(){
		var continueTo = getUrlVar(window.location.search, 'continueTo');
		if (continueTo == 'checkout')
			parent.location = data['R_LINKCHECKOUT'];
	});
}

/**
 *
 */
function tryUpdateDisplays(type, data){

	// try to update the parent window displays
	//	- if we are unable to access the parent window, redirect to same domain as parent... then update the displays
	try {
		var successData = {
			"R_INSTITUTION": $(data).find('R_INSTITUTION').text(),
			"R_GREETING": $(data).find('R_GREETING').text(),
			"R_LOGIN": $(data).find('R_LOGIN').text(),
			"R_ACCOUNT": $(data).find('R_ACCOUNT').text(),
			"R_LINKCHECKOUT": $(data).find('R_LINKCHECKOUT').text(),
			"R_LINKREDIRECT": $(data).find('R_LINKREDIRECT').text()
		};

		successUpdateDisplays(type, successData);
	}
	catch (error) {
		var redirect = $(data).find('R_LINKREDIRECT').text() + '&success=' + type;
		var continueTo = getUrlVar(window.location.search, 'continueTo');
		if (continueTo != '')
			redirect += '&continueTo=' + encodeURIComponent(continueTo);

		window.location = redirect;
	}
}

// smart drop
(function($) {
	$.fn.SmartDrop = function(options) {

		options = $.extend(
			{
				queryClass: "smart-drop-query",
				selectClass: "smart-drop-select",
				startClass: "smart-drop-start",
				highlightClass: "highlight",
				blankClass: "smart-drop-option-blank",
				listClass: "smart-list",
				listPreId: "smart-list-option-",
				listNoteClass: "smart-list-note",
				submitClass: "smart-drop-submit",
				maxResults: 50
			},
			options || {}
		);

		// handles searching and highlighting
		var doSearch = function(obj) {

			// get the input
			var filter = $.trim(obj.find('.' + options.queryClass).attr("value").toLowerCase());

			// make sure the input has changed
			if (filter == obj.SDcache) {
				obj.SDsearch = null;
				return;
			}

			// get elements to search against
			var searchArray = obj.find('.' + options.selectClass).get(0).options;
			var searchCount = searchArray.length;

			// keep track of the results
			var resultCount = 0;
			var resultList = '';
			var resultLast = '';

			// see if our first option is a blank instruction row
			var startValue = ($(searchArray[0]).hasClass(options.blankClass)) ? 1 : 0;

			// search for any matches
			for (var i = startValue; i < searchCount && resultCount < options.maxResults; i++) {

				// do search
				if (searchArray[i].text.toLowerCase().indexOf(filter) != -1) {
					// we have a match
					resultCount++;

					// highlight any matches
					if (filter != '') {
						resultLast = searchArray[i].text.replace(new RegExp(filter, "gi"), function(match) {
							return '<span class="' + options.highlightClass + '">' + match + '</span>';
						});
					}
					else
						resultLast = searchArray[i].text;

					// save match to list
					resultList += '<li id="'+ options.listPreId + obj.SDlistKey + i + '">' + resultLast + '</li>';
				}
			}

			// check for no matches or too many matches
			if (resultCount == 0)
				resultList += '<li class="' + options.listNoteClass + '">no matches ...</li>';
			else if (resultCount >= options.maxResults)
				resultList += '<li class="' + options.listNoteClass + '">top ' + options.maxResults + ' matches ...</li>';

			// display our new list
			obj.find('.' + options.listClass).html(resultList);

			// make each item clickable
			obj.find('.' + options.listClass + ' li').click(function(){
				selectItem(obj, $(this));
			});

			// cache the input
			obj.SDcache = filter;

			// clear this search attempt, should be gone anyways...
			obj.SDsearch = null;
		};

		// hide dropdown replacement
		var initialize = function(obj) {

			// clear the timeout if needed
			if (obj.SDsearch)
				clearTimeout(obj.SDsearch);

			// focus on the input textbox
			obj.find('.' + options.queryClass).focus();

			// fill cache with dummy value
			obj.SDcache = ' ';

			// initialize the list
			doSearch(obj);

			// show the list
			obj.find('.' + options.listClass).slideDown();
		}

		// select match and copy to field
		var selectItem = function(obj, thisEl) {

			// do not select any notes
			if (thisEl.hasClass(options.listNoteClass))
				return;

			// save the text and select the option
			obj.find('.' + options.queryClass).attr("value", thisEl.text());
			obj.find('.' + options.selectClass).attr("selectedIndex", thisEl.attr("id").substring(options.listPreId.length + obj.SDlistKey.length));

			// hide the list
			obj.find('.' + options.listClass).slideUp();
			obj.find('.' + options.submitClass).fadeIn('fast');
		}

		// left pad string
		var leftPad = function(i, l, s) {
			var o = i.toString();
			if (!s)
				s = '0';
			while (o.length < l)
				o = s + o;
			return o;
		};

		// add incremental search functionality to each matching element
		this.each(function() {
			var obj = $(this);

			obj.SDcache = '';	// cache each key input
			obj.SDsearch = null;	// search timer's identifier
			obj.SDlistKey = leftPad(Math.floor(1e10 * Math.random()).toString(36), 7);	// random key for list item's id

			// add the list if needed
			if (obj.find('.' + options.listClass).length == 0)
				$('<ul></ul>').addClass(options.listClass).appendTo(obj);

			obj.find('.' + options.queryClass).keyup(function(){
				if (obj.SDsearch)
					clearTimeout(obj.SDsearch);

				// start a timer to perform the search, older browsers like IE6 have a hard time doing search
				obj.SDsearch = setTimeout(function() { doSearch(obj); }, 100);
			}).mouseup(function(){
				initialize(obj);
			});

			// Initalize drop down on start click
			obj.find('.' + options.startClass).click(function(){
				initialize(obj);
				return false;
			});

		});

		// return reference
		return this;
	};
})(jQuery);
