function checkEnter(e){
	
	var characterCode;
	
	if(e && e.which){ //if which property of event object is supported (NN4)
		e = e;
		characterCode = e.which;
	} else {
		e = event;
		characterCode = e.keyCode;
	}
	
	if(characterCode == 13){ //if generated character code is equal to ascii 13 (if enter key)
		$('#b1').click();
	}
}

function checkLogin(pUsernameDomId, pPasswordDomId, pButtonDomId, pResponseDomDivId, pSuccessRedirectUrl) {
	
	$('#' + pResponseDomDivId).slideUp('fast');
	$('#' + pButtonDomId).val('loading');
	
	if ($('#' + pUsernameDomId).val() != '' && $('#' + pUsernameDomId).val() != '') {
		if ($('#' + pPasswordDomId).val() == $('#' + pPasswordDomId).val()) {
			
			$.ajax(
			{
				type: 'POST',
				url: 'ws/checklogin.jsp',
				data: 'username=' + $('#' + pUsernameDomId).val() + '&password=' + $('#' + pPasswordDomId).val(),
				dataType: 'xml',
				timeout: 50000,
				success: function(xml) {
				
					var statusOfResponse = $(xml).find('response').attr('status');								
					if (statusOfResponse == "response") {
						
						var isOrWasUserJustInAChatSession = $(xml).find('response').attr('success');
						var overrideRedirectUrl = $(xml).find('response').attr('redirect');
						
						if (isOrWasUserJustInAChatSession == "true") {
							if (overrideRedirectUrl != null && overrideRedirectUrl != "") {
								window.location = "/" + overrideRedirectUrl;
								$('#' + pButtonDomId).val('connecting');
							} else {
								window.location = "/" + pSuccessRedirectUrl;
								$('#' + pButtonDomId).val('connecting');
							}
						} else {
							$('#' + pResponseDomDivId).html("Login details incorrect. Please try again");
							$('#' + pResponseDomDivId).slideDown('slow');
							$('#' + pButtonDomId).val('Login');
						}
					}
				},
				error: function(XMLHttpRequest, textStatus, errorThrown) {
					console.log("textStatus : ",textStatus,"errorThrown : ",errorThrown);
					$('#' + pButtonDomId).val('Login');
				}
			});
			
		} else {
			$('#' + pResponseDomDivId).html("You must fill in both fields.");
			$('#' + pResponseDomDivId).slideDown('slow');
			$('#' + pButtonDomId).val('Login');
		}
	} else {
		$('#' + pResponseDomDivId).html("You must fill in both fields.");
		$('#' + pResponseDomDivId).slideDown('slow');
		$('#' + pButtonDomId).val('Login');
	}
}

function checkForSessionAttributes() {
	
	$.ajax(
	{
		type: 'POST',
		url: 'ws/checksessionattributes.jsp',
		data: '',
		dataType: 'xml',
		timeout: 50000,
		success: function(xml) {
		
			var statusOfResponse = $(xml).find('response').attr('status');								
			if (statusOfResponse == "response") {
				
				var isOrWasUserJustInAChatSession = $(xml).find('response').attr('isOrWasUserJustInAChatSession');
				
				if (isOrWasUserJustInAChatSession == "true") {
					closeTheFlash();
					window.location = "/index.jsp";
				}
			}
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) {
			console.log("textStatus : ",textStatus,"errorThrown : ",errorThrown);
		}
	});
}

function clearForms() {
  var i;
  for (i = 0; (i < document.forms.length); i++) {
    document.forms[i].reset();
  }
}

function displayBillingChannel(tabDivId, boxDivId) {
	
	// Change the classes of the selected div tags
	if (tabDivId == "t1") {
		$('#t1 a').addClass('selected');
	} else {
		$('#t1 a').removeClass('selected');
	}
	
	if (tabDivId == "t2") {
		$('#t2 a').addClass('selected');
	} else {
		$('#t2 a').removeClass('selected');
	}
	
	if (tabDivId == "t3") {
		$('#t3 a').addClass('selected');
	} else {
		$('#t3 a').removeClass('selected');
	}

	if (tabDivId == "t4") {
		$('#t4 a').addClass('selected');
	} else {
		$('#t4 a').removeClass('selected');
	}
	
	// Reset the box divs
	$('#090_payment_div').hide();
	$('#sms_payment_div').hide();
	$('#cc_payment_div').hide();
	$('#threeg_payment_div').hide();
	
	// Fade in the chosen div
	$('#' + boxDivId).fadeIn('slow');
}

function preverify() {

	$('#preverify_message').slideUp('fast');

	if ($('#USERNAME1').val() != '' && $('#USERNAME2').val() != '') {
		if ($('#USERNAME1').val() == $('#USERNAME2').val()) {
			if ($('#PASSWORD1').val() != '' && $('#PASSWORD2').val() != '') {
				if ($('#PASSWORD1').val() == $('#PASSWORD2').val()) {
					if ($('#COUNTRY1').val() != '') {
						if ($('#CHECK-BOX-TANCS').attr('checked')) {
							$('form#INSERT-PROFILE').submit();
						} else {
							$('#preverify_message').html("You must agree to the Terms & Conditions.");
							$('#preverify_message').slideDown('slow');
						}
					} else {
						$('#preverify_message').html("Please select your country.");
						$('#preverify_message').slideDown('slow');
					}
				} else {
					$('#preverify_message').html("Your passwords do not match.");
					$('#preverify_message').slideDown('slow');
				}
			} else {
				$('#preverify_message').html("You must fill in all of the fields.");
				$('#preverify_message').slideDown('slow');
			}
		} else {
			$('#preverify_message').html("Your emails do not match.");
			$('#preverify_message').slideDown('slow');
		}
	} else {
		$('#preverify_message').html("You must fill in all of the fields.");
		$('#preverify_message').slideDown('slow');
	}
}

/**
 * This method calls the webservice to check whether the selected managed stream
 * has a workflow of broadcasting, and if it is registered, then create an 
 * activity record and wait until coast is clear
 */
function checktoken(token, tokenType, returnPage) {
	//callCount = callCount + 1;
	//if (callCount<11) {	
		$.ajax(
				{
					type: 'POST',
					url: 'ws/checktoken.jsp',
					data: 'tktochk=' + token + "&tokentype=" + tokenType + "&returnpage=" + returnPage,
					dataType: 'xml',
					timeout: 50000,
					success: function(xml) {
								// Check whether an error has occured looking up the token status
								var statusOfResponse = $(xml).find('response').attr('status');								
								if (statusOfResponse == "response") {
									// No error has occured so check the token status
									var userStatus = $(xml).find('response').attr('userconfirmed');									
									if (userStatus == "true") {
										// User has been confirmed return the URL to this page - refreshing itself
										var userId = $(xml).find('response').attr('userid');	
										var serviceUserId = $(xml).find('response').attr('serviceuserid');
										window.location = returnPage + "?luser=" + userId + "&losuser=" + serviceUserId + "&pm=wfb";
										
									} else {
										//To deal with the scenarios where no user information will be forth coming
										var responseCodeSet = $(xml).find('response').attr('responsecodeset');									
										if (responseCodeSet == "true") {
											var responseCode = $(xml).find('response').attr('responsecode');
											window.location = returnPage + "?pm=" + responseCode;	
										} else {
											// Try again as the user has not yet been confirmed
											setTimeout("checktoken("+token+","+tokenType+",'"+returnPage+"')", 5000);	//Javascript's delay timer for 5000 miliseconds											
										} 
									}
								} else {
									alert("An error has occured whilst processing your attempt - please refresh this page to try again.");
								}
							},
					error: function() {
						alert("An error has occured whilst processing your attempt - please refresh this page to try again.");
					}
				}
			);	
	//} else {
	//	callCount = 0;
	//	alert("We have called the checker 10 times - will call no more");
	//}
}

function checkbill(ber,chatId) {
	//callCount = callCount + 1;
	//if (callCount<11) {	
		$.ajax(
				{
					type: 'POST',
					url: 'ws/checkber.jsp',
					data: 'brtochk=' + ber,
					dataType: 'xml',
					timeout: 50000,
					success: function(xml) {
								// Check whether an error has occured looking up the token status
								var statusOfResponse = $(xml).find('response').attr('status');								
								if (statusOfResponse == "response") {
									// No error has occured so check the token status
									var berStatus = $(xml).find('response').attr('berstatus');									
									if (berStatus == "fundsallocated") {
										// User has been confirmed return the URL to this page - refreshing itself
										var userId = $(xml).find('response').attr('userid');									
										window.location = "chat.jsp?SUID=" + chatId;
									} else {
										// Try again as the user has not yet been confirmed
										setTimeout("checkbill("+ber+","+chatId+")", 5000);	//Javascript's delay timer for 5000 miliseconds
									}
								} else {
									alert("An error has occured processing payment - please refresh this page to try again.");
								}
							},
					error: function() {
						alert("An error has occured processing payment - please refresh this page to try again.");
					}
				}
			);	
	//} else {
	//	callCount = 0;
	//	alert("We have called the checker 10 times - will call no more");
	//}
}

/**
 * This method calls the webservice to check whether the selected managed stream
 * has a workflow of broadcasting, and if it is registered, then create an 
 * activity record and wait until coast is clear
 */
function pollBillingChannels(returnPage, errorPage, hasUserAlreadyBeenConfirmed, errorToken, failureCode) {		
	$.ajax(
	{
		type: 'POST',
		url: 'ws/pollBillingChannels.jsp',
		data: "returnpage=" + returnPage,
		dataType: 'xml',
		timeout: 60000,
		success: function(xml) {
					
			//Collect all of the results into local variables
			var statusOfResponse = $(xml).find('response').attr('status');
			var pollingHasFinished = $(xml).find('response').attr('finishedPolling');
			var userIsConfirmed = $(xml).find('response').attr('userConfirmed');
			var billingIsConfirmed = $(xml).find('response').attr('billingConfirmed');
			var thePollingProcessFailed = $(xml).find('response').attr('pollFailed');
			var theIntendedActionIsUnavailable = $(xml).find('response').attr('actionUnavailable');
																			
			if (statusOfResponse == "response") {
				if (pollingHasFinished == "true") {
					if (thePollingProcessFailed == true) { 
						window.location = errorPage + "?" + errorToken + "=" + failureCode;
					} else {
						if (theIntendedActionIsUnavailable == true) {
							window.location = errorPage;							
						} else {						
							//Redirect to the return page - it will recognise the session presence state and act appropriately
							window.location = returnPage;						
						}						
					}
				} else {
					//First check that we haven't already sent the signal back to the page to inform them of the user confirmation
					if (hasUserAlreadyBeenConfirmed == "false" && userIsConfirmed == "true") {
					
						//Redirect to the return page - if this state has been returned, a flag will have been set in the session											
						window.location = returnPage; 
					} else {
						//The polling process hasn't finished yet according to the jsp, so loop
						setTimeout("pollBillingChannels('"+ returnPage + "','" + errorPage + "','" + hasUserAlreadyBeenConfirmed +"','" + errorToken + "','" + failureCode + "')", 1000);
					}	
				}
			} else {
				//Need to redirect to index page - relying on the info/error code in the session to display the error message									
				window.location = errorPage;
			}
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) {

			console.log("textStatus : ",textStatus,"errorThrown : ",errorThrown);
			
			setTimeout("pollBillingChannels('"+ returnPage + "','" + errorPage + "','" + hasUserAlreadyBeenConfirmed +"','" + errorToken + "','" + failureCode + "')", 1000);
			accumlateErrorCount(errorPage);
		}
	});	
}

var errorCount = 0;

function accumlateErrorCount(errorPage) {
	errorCount++;
	
	if (errorCount == 5) {
		window.location = errorPage;
	}
}

function resetErrorCount() {
	errorCount = 0;
}