$(document).ready(function() {

	$('li.hasSub-menu').bind('mouseover', submenuShow);
	$('li.hasSub-menu').bind('mouseout', submenuHide);

	// Code for alternating tables. Use class 'stripeMe' for it.
		$('.stripeMe tr:even').addClass("alt");

		$('.dollar').each(function(i) {
			tempVal = this.value;
			replacedVal = tempVal.replace('$', '');
			this.value = '$' + replacedVal;

		});

		$('.dollarS').each(function(i) {
			tempVal = this.value;
			replacedVal = tempVal.replace('$', '');
			this.value = '$' + replacedVal;
		});

		// Mouse over and out
		$('.highLightMe tr').mouseover(function() {
			$(this).addClass('over');
		});
		$('.highLightMe tr').mouseout(function() {
			$(this).removeClass('over');
		});

		$('#strEmail').change(function() {
			$('#strConfirmEmail').val("");
		});

		$('#strNewPassword').change(function() {
			$('#strConfirmPassword').val("");
			$('#strConfirmPassword').attr("disabled", "");
			$('#strPassword').attr("disabled", "");
		});

	});

jQuery.fn.stripTags = function() {
	return this.replaceWith(this.html().replace(/<\/?[^>]+>/gi, ''));
};

function stripTags(strCommentText) {
	return strCommentText.replace(/<\/?[^>]+>/gi, '');
}

//================================== for  sub-menu module [SUM] ===========================
var timeOut = 300;
var hideTrigger = 0;
var currItem = 0;
var menuObj = 0;

function cancelTimer() {

	if (hideTrigger) {
		window.clearTimeout(hideTrigger);
		hideTrigger = null;
	}
}

function hideExe() {
	if (currItem) {
		currItem.css('display', 'none');
		menuObj.removeClass('onHoverLarge').removeClass('onHoverSmall');
	}
}

function submenuShow() {

	cancelTimer();
	hideExe();
	menuObj = $(this).find('a');

	if (menuObj.hasClass('large')) {
		menuObj.addClass('onHoverLarge');
	}
	if (menuObj.hasClass('small')) {
		menuObj.addClass('onHoverSmall');
	}

	currItem = $(this).find('ul').css('display', 'block');
}

function submenuHide() {

	hideTrigger = window.setTimeout(hideExe, timeOut);
}

//  ends sub menu script........//

function showLogin() {

	if (document.getElementById('loginbox').style.display == 'none') {

		$('#loginbox').slideDown(600);
	} else {
		$('#loginbox').slideUp(600);
	}
	setTimeout(function() { $('#strEmailLogin').focus(); }, 1000);
}

function showDisclosureForm() {

	if (document.getElementById('disclosureForm').style.display == 'none') {

		$('#disclosureForm').animate( {
			opacity : 100,

			height : 'toggle'
		}, 300, function() {
		});

		$('#disclosureLinkId').text('Close disclosure form.');
		// $('#disclosureForm').animate({opacity: '100'}, 300);

		// $('#disclosureForm').toggle().show('slow');
		// $('#disclosureForm').slideDown(600);
	} else {

		$('#disclosureForm').animate( {
			opacity : 0.0,

			height : 'toggle'
		}, 300, function() {

		});
		$('#disclosureLinkId').text(
				'Click here to see the mortgage calculator disclosure form.');
		// $('#disclosureForm').toggle().hide('slow');
		// $('#disclosureForm').slideUp(600);
	}
}

function openReply(replyBoxId) {

	// reset other boxes
	$('.postarea').html('');
	$('.replyButton').removeAttr("disabled");
	$('.replyButton').attr("src", "/images/replybuttonactive.jpg");

	htmls = '<p>Add Title</p><input type="text" class="replytitle" name="strTitle" id = "strTitle"/><textarea name="strComment" id="strComment" class="reply tinymce"></textarea><div class="buttonregion"><a href="#"><img src="/images/postreplybutton.jpg" width="94" height="30" alt="PostReply" onClick= "postReply('
			+ replyBoxId
			+ '); return false;"/></a><a href="#"><img src="/images/cancelbutton.jpg" width="69" height="30" alt="Cancel" onclick="closeReply('
			+ replyBoxId + '); return false;" /></a></div>';
	$('#replyBox-' + replyBoxId).html(htmls);
	$('#replyBox-' + replyBoxId).slideDown(600);

	initializeMCE();

	$('#replyButton-' + replyBoxId).attr("disabled", "disabled");
	$('#replyButton-' + replyBoxId).attr("src",
			"/images/replybuttondisabled.png");

}

function initializeMCE() {

	$('textarea.tinymce')
			.tinymce(
					{
						// Location of TinyMCE script
						script_url : '/javascript/tiny_mce/tiny_mce.js',
						mode : "textareas",
						theme : "advanced",
						plugins : "spellchecker,paste",
						theme_advanced_buttons1 : "bold,italic,underline,link,unlink,bullist,blockquote,undo,spellchecker,numlist,pastetext,pasteword,selectall",
						/*
						 * theme_advanced_buttons1 :
						 * "bold,italic,underline,link,unlink,bullist,blockquote,undo,spellchecker",
						 */
						theme_advanced_buttons2 : "",
						theme_advanced_buttons3 : "",
						spellchecker_languages : "+English=en",
						paste_auto_cleanup_on_paste : true,
						paste_preprocess : function(pl, o) {
							// Content string containing the HTML from the clipboard

					},
					paste_postprocess : function(pl, o) {
						// Content DOM node containing the DOM structure of the clipboard

					}

					});
}

function closeReply(replyBoxId) {

	$('#replyBox-' + replyBoxId).slideUp(600);
	$('#replyButton-' + replyBoxId).removeAttr("disabled");
	$('#replyButton-' + replyBoxId)
			.attr("src", "/images/replybuttonactive.jpg");
}

function postReply(intMessageId) {

	$('#comment-response-box').removeClass('error');
	$('#comment-response-box').removeClass('success');
	$('#comment-response-box-' + intMessageId).html('Posting comment...');

	var strComment = $('#strComment').serialize();
	var strCommentText = $('#strComment').html();

	var strTitle = $('#strTitle').val();

	if (stripTags(strCommentText).length > 0) {
		$
				.ajax( {
					type : "POST",
					url : "/addCompanyComment",
					data : "strTitle=" + strTitle + "&" + strComment
							+ "&intMessageId=" + intMessageId,
					success : function(response) {
						if (response == 'Disallowed Key Characters.') {
							$('#comment-response-box-' + intMessageId)
									.addClass('error');
							$('#comment-response-box-' + intMessageId)
									.html(
											"Failed to post the comment. Disallowed Key Characters. Please try again.");
						}
						var json = eval('(' + response + ')');
						if (json.error == '') {
							// Clear the form fields.
							$('#strCommentTitle').val('');
							$('#strComment').html('');
							// Set the response message and class.
							$('#comment-response-box-' + intMessageId)
									.addClass('success');
							$('#comment-response-box-' + intMessageId)
									.html(
											'Your reply to this comment has been posted.');

							closeReply(intMessageId);

						} else {

							// Set the error message and class
							$('#comment-response-box-' + intMessageId)
									.addClass('error');
							$('#comment-response-box-' + intMessageId).html(
									json.message);
						}

					},
					error : function() {

						$('#comment-response-box-' + intMessageId).addClass(
								'error');
						$('#comment-response-box-' + intMessageId)
								.html(
										"Failed to post the comment. Please try again.");
					}

				});
	} else {
		if (strComment.length == 0) {
			strError = 'Please enter a comment before posting. '
		} else {
			strError = "Comment message was too short."
		}

		$('#comment-response-box-' + intMessageId).addClass('error');
		$('#comment-response-box-' + intMessageId).html(strError);
	}
}

function addComments() {

	$('#comment-response-box').removeClass('error');
	$('#comment-response-box').removeClass('success');
	$('#comment-response-box').html('Posting comment...');
	var strTitle = $('#strTitle').val();
	var strComment = $('#strComment').serialize();
	var strCommentText = $('#strComment').html();
	var strSessionId = $('#hidSessionId').val();
	var intLoanId = $('#hidLoanId').val();
	var strIpAddress = $('#hidIpAddress').val();
	var intToUserId = $('#hidToUserId').val();
	var intInReplyToId = $('#hidInRepyToId').val();

	if (stripTags(strCommentText).length > 0) {
		$
				.ajax( {
					type : "POST",
					url : "/addcomments",
					data : "strTitle=" + strTitle + "&" + strComment
							+ "&intLoanId=" + intLoanId + "&strSessionId="
							+ strSessionId + "&strIpAddress=" + strIpAddress
							+ "&intInReplyToId=" + intInReplyToId
							+ "&intToUserId=" + intToUserId,
					success : function(response) {
						if (response == 'Disallowed Key Characters.') {
							$('#comment-response-box').addClass('error');
							$('#comment-response-box')
									.html(
											"Failed to post the comment. Disallowed Key Characters. Please try again.");
						}
						var json = eval('(' + response + ')');
						if (json.error == '') {
							// Clear the form fields.
							$('#strCommentTitle').val('');
							$('#strComment').html('');

							// Add comment box with contents
							strCommentBox = '<div class="commentbox" id="'
									+ json.arrComment['intMessageId']
									+ '" style="display:none;"><div  class="bluebar" >  <h3>'
									+ json.arrComment['strMessageTitle']
									+ '</h3>  <p>Posted on '
									+ json.arrComment['strSentOn']
									+ '</p></div><div class="commentregion  '
									+ json.arrComment['strClass']
									+ '">  <div class="identity">   <p>'
									+ json.arrComment['strName'] + '</p>'
									+ json.arrComment['strImage']
									+ '</div><div class="comment"><p>'
									+ json.arrComment['strMessageContent']
									+ '</p></div></div></div>';
							$('#comments_list').append(strCommentBox);
							$('#' + json.arrComment['intMessageId']).slideDown(
									600);

							// Set the response message and class.
							$('#comment-response-box').addClass('success');
							$('#comment-response-box').html(
									'Your comment has been posted.');

						} else {

							// Set the error message and class
							$('#comment-response-box').addClass('error');
							$('#comment-response-box').html(json.message);
						}

					},
					error : function() {

						$('#comment-response-box').addClass('error');
						$('#comment-response-box')
								.html(
										"Failed to post the comment. Please try again.");
					}

				});
	} else {
		if (strComment.length == 0) {
			strError = 'Please enter a comment before posting. '
		} else {
			strError = "Comment message was too short."
		}

		$('#comment-response-box').addClass('error');
		$('#comment-response-box').html(strError);
	}
}

function addCompanyComments() {

	$('#comment-response-box').removeClass('error');
	$('#comment-response-box').removeClass('success');
	$('#comment-response-box').html('Posting comment...');
	var strTitle = $('#strCommentTitle').val();
	var strComment = $('#strComment').serialize();
	var strCommentText = $('#strComment').html();
	var strSessionId = $('#hidSessionId').val();
	var strIpAddress = $('#hidIpAddress').val();
	var intToUserId = $('#hidToUserId').val();
	var intInReplyToId = $('#hidInRepyToId').val();

	if (stripTags(strCommentText).length > 0) {
		$
				.ajax( {
					type : "POST",
					url : "/addCompanycomments",
					data : "strTitle=" + strTitle + "&" + strComment
							+ "&strSessionId=" + strSessionId
							+ "&strIpAddress=" + strIpAddress
							+ "&intInReplyToId=" + intInReplyToId
							+ "&intToUserId=" + intToUserId,
					success : function(response) {

						if (response == 'Disallowed Key Characters.') {
							$('#comment-response-box').addClass('error');
							$('#comment-response-box')
									.html(
											"Failed to post the comment. Disallowed Key Characters. Please try again.");
						}
						var json = eval('(' + response + ')');
						if (json.error == '') {
							// Clear the form fields.
							$('#strCommentTitle').val('');
							$('#strComment').html('');

							// Add comment box with contents
							strCommentBox = '<div class="commentbox" id="'
									+ json.arrComment['intMessageId']
									+ '" style="display:none;"><div  class="bluebar" >  <h3>'
									+ json.arrComment['strMessageTitle']
									+ '</h3>  <p>Posted on '
									+ json.arrComment['strSentOn']
									+ '</p></div><div class="commentregion  '
									+ json.arrComment['strClass']
									+ '">  <div class="identity">   <p>'
									+ json.arrComment['strName'] + '</p>'
									+ json.arrComment['strImage']
									+ '</div><div class="comment"><p>'
									+ json.arrComment['strMessageContent']
									+ '</p></div></div></div>';
							$('#comments_list').append(strCommentBox);
							$('#' + json.arrComment['intMessageId']).slideDown(
									600);

							// Set the response message and class.
							$('#comment-response-box').addClass('success');
							$('#comment-response-box').html(
									'Your comment has been posted.');

						} else {

							// Set the error message and class
							$('#comment-response-box').addClass('error');
							$('#comment-response-box').html(json.message);
						}

					},
					error : function() {

						$('#comment-response-box').addClass('error');
						$('#comment-response-box')
								.html(
										"Failed to post the comment. Please try again.");
					}

				});
	} else {
		if (strComment.length == 0) {
			strError = 'Please enter a comment before posting. '
		} else {
			strError = "Comment message was too short."
		}

		$('#comment-response-box').addClass('error');
		$('#comment-response-box').html(strError);
	}
}

function addAdditionalBorrower() {

	$('#intBorrowerCount').val(parseInt($('#intBorrowerCount').val()) + 1);
	if (parseInt($('#intBorrowerCount').val() > 2)) {
		$('#addAdditionalBwrId').hide();
	}
	var strBlockContent = "<div style='display:block;'><div class='clr'></div>"
			+ "<div class='highlightedbox' >"
			+ "<div class='section'>"
			+ "<div class='inputarea'>"
			+ "<label><span>*</span>List Individual Borrowers or Principals of Borrowing Entity:</label>"
			+ "<input type='text' name='strEntityName[]' value='' />"
			+ "</div>"
			+ "<div class='inputarea'>"
			+ "<label><span>*</span>Credit Rating:</label>"
			+ "<select name='strCreditRating[]'>"
			+ "<option value='select'>--Select--</option>"
			+ "<option value='excellent'>Excellent</option>"
			+ "<option value='very-good'>Very Good</option>"
			+ "<option value='good'>Good</option>"
			+ "<option value='fair'>Fair</option>"
			+ "<option value='poor'>Poor</option>"
			+ "</select>"
			+ "<div class='clr'></div>"
			+ "<span class='validationmessage'> </span>"
			+ "</div>"
			+ "<div class='inputarea'><label><span>&nbsp;</span>Per Listed Principal:</label></div>"
			+ "<div class='inputarea'>"
			+ "<label><span>*</span>Percentage of Ownership:</label>"
			+ "<input type='text' maxlength='3' name='floatOwnership[]' value=''/>"
			+ "<div class='clr'></div>"
			+ "<span class='validationmessage'> </span>"
			+ "</div>"
			+ "<div class='inputarea'>"
			+ "<label><span>*</span>Net Worth:</label>"
			+ "<input type='text'  class='dollar'  name='floatNetWorth[]' onchange='addCommas(this);' value='$'/>"
			+ "</div>"
			+ "<div class='inputarea'>"
			+ "<label><span>*</span>Liquid Assets: <br>(excluding IRA accounts)</label>"
			+ "<input type='text' class='dollar' name='floatLiquidAsset[]' onchange='addCommas(this);' value='$'/>"
			+ "</div>" + "</div>" + "</div>" + "</div>";
	$('#BorrowerContainer').append(strBlockContent);

}

function cufonLoad() {

	Cufon.replace('h1');
	Cufon.replace('label');
	Cufon.replace('input');
	Cufon.replace('li', {
		hover : true
	});
	Cufon.replace('p');
	Cufon.replace('span');
}

function setTransactionType() {

	if ($('#strTransactionType').val() != '') {
		if ($('#strTransactionType').val() == 'purchase') {
			$('#purchaseContainerId').show();
			$('#refinanceContainerId').hide();
		} else if ($('#strTransactionType').val() == 'refinance') {
			$('#refinanceContainerId').show();
			$('#purchaseContainerId').hide();
		}
	} else {
		$('#purchaseContainerId').show();
		$('#refinanceContainerId').hide();
	}
}

function selectTransactionType() {

	if ($('#strTransactionType').val() != '') {
		if ($('#strTransactionType').val() == 'purchase') {
			$('#purchaseContainerId').show();
			$('#refinanceContainerId').hide();
			$('#floatPricePaid').val('');
			$('#floatBalance').val('');
			$('#floatMaturity').val('');
			$('#floatPenaltyAmount').val('');
		} else if ($('#strTransactionType').val() == 'refinance') {
			$('#refinanceContainerId').show();
			$('#purchaseContainerId').hide();
			$('#floatPurchasePrice').val('');
		}
	} else {
		$('#purchaseContainerId').show();
		$('#refinanceContainerId').hide();
	}
}

function calendarSetup() {

	var toCal = Calendar.setup( {
		trigger : "datePurchasedId",
		inputField : "datePurchasedId",
		selectionType : Calendar.SEL_MULTIPLE,
		dateFormat : "%Y/%m/%d",
		onSelect : function() {
			this.hide()
		}
	});

	// toCal.showAt(0, 0, true);
	// toCal.popup("value_to_id", "bR/BR/Br/TR/tR");

}

function addCommas(objInput) {

	nStr = objInput.value;
	nStr = replacePattern(nStr, ',', '');
	nStr = replacePattern(nStr, '$', '');
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}

	outString = x1 + x2;
	if ($(objInput).is('.dollar')) {
		outString = '$' + outString;
	}
	if ($(objInput).is('.dollarS')) {
		outString = '$' + outString;
	}
	objInput.value = outString;
}

function replacePattern(strText, replace, pattern) {

	var strReplaceAll = strText;
	var intIndexOfMatch = strReplaceAll.indexOf(replace);

	while (intIndexOfMatch != -1) {
		strReplaceAll = strReplaceAll.replace(replace, pattern)
		intIndexOfMatch = strReplaceAll.indexOf(replace);
	}
	strReplaceAll = strReplaceAll.replace('$', '');
	return strReplaceAll;
}

function loanDetailsTableToogle(objImage, objTable) {

	objTable.toggle();

	if (objImage.attr("src") == "/images/expand.jpg") {
		objImage.attr("src", '/images/compress.jpg');
	} else {
		objImage.attr("src", '/images/expand.jpg');
	}
}

function cleanString(strString) {

	return strString.replace(/(<([^>]+)>)/ig, "");
}

function toggleReimburasables() {

	if ($('#Reimbursable_chkbox').attr('checked') == true) {

		$('.expensescheckbox').removeAttr('disabled');
	} else {

		$('.expensescheckbox').attr('disabled', 'disabled');
		$('#Reimbursable_chkbox').removeAttr('disabled');
	}
}

function calculateBalance(total, prepaid) {

	balance = total - prepaid;
	balanceFormated = format_number(balance, 2);
	balanceFloat = parseFloat(balanceFormated);
	return balanceFloat;

}

function format_number(pnumber, decimals) {

	if (isNaN(pnumber)) {
		return 0
	}
	;
	if (pnumber == '') {
		return 0
	}
	;

	var snum = new String(pnumber);
	var sec = snum.split('.');
	var whole = parseFloat(sec[0]);
	var result = '';

	if (sec.length > 1) {
		var dec = new String(sec[1]);
		dec = String(parseFloat(sec[1]) / Math.pow(10, (dec.length - decimals)));
		dec = String(whole + Math.round(parseFloat(dec))
				/ Math.pow(10, decimals));
		var dot = dec.indexOf('.');
		if (dot == -1) {
			dec += '.';
			dot = dec.indexOf('.');
		}
		while (dec.length <= dot + decimals) {
			dec += '0';
		}
		result = dec;
	} else {
		var dot;
		var dec = new String(whole);
		/*
		 * dec += '.'; dot = dec.indexOf('.'); while(dec.length <= dot +
		 * decimals) { dec += '0'; }
		 */
		result = dec;
	}

	result = replacePattern(result, '.00', '');
	result = parseFloat(result);
	return result;
}

function selectCalculator() {

	getRandomTestimonial();

	var section = "";
	var imageName = '';

	if ($('#strProductType').val() == 'retail') {
		$('#retailContainerId').show();
		imageName = $('#retailCalcImageName').val();
		$('#calculatorPageImageId').attr("src", '/images/' + imageName);
		$('#multifamilyContainerId').hide();
		$('#officeContainerId').hide();
		$('#constructionContainerId').hide();
		section = 22;

	} else if ($('#strProductType').val() == 'office') {
		$('#officeContainerId').show();
		imageName = $('#officeCalcImageName').val();
		$('#calculatorPageImageId').attr("src", '/images/' + imageName);
		$('#retailContainerId').hide();
		$('#multifamilyContainerId').hide();
		$('#constructionContainerId').hide();
		section = 23;

	} else if ($('#strProductType').val() == 'construction') {
		$('#constructionContainerId').show();
		imageName = $('#constnCalcImageName').val();
		$('#calculatorPageImageId').attr("src", '/images/' + imageName);
		$('#multifamilyContainerId').hide();
		$('#retailContainerId').hide();
		$('#officeContainerId').hide();
		section = 24;
	} else {
		$('#multifamilyContainerId').show();
		imageName = $('#multifamilyCalcImageName').val();
		$('#calculatorPageImageId').attr("src", '/images/' + imageName);
		$('#officeContainerId').hide();
		$('#retailContainerId').hide();
		$('#constructionContainerId').hide();
		section = 21;
	}
	$('#intHiddenCommentId').val(section);
	getCalculatorComment(section);
}

function getRandomTestimonial() {

	$.ajax( {
		type : "POST",
		url : "/main/getTestimonialForCalculator",
		success : function(response) {
			var json = eval('(' + response + ')');

			var contText = json.strContent;
			$('#bluetext').html(contText);
			var contAuthor = json.strName + '-' + json.strOrganizationName;
			$('#author').html(contAuthor);

		},
		error : function() {

		}
	});
}

function getCalculatorComment(section) {

	$.ajax( {
		type : "POST",
		url : "/main/getCalculatorComment",
		data : "section=" + section,
		success : function(response) {
			var json = eval('(' + response + ')');
			var contText = json.strPageContent;
			$('#commentContent').html(contText);
			$('#strDescription').val(contText);

		},
		error : function() {

		}
	});
}

function stripHTML(arguments) {

	var re = /(<([^>]+)>)/gi;

	return arguments.value.replace(re, "")
}

function addCommastoOutput(nStr) {

	NanTest = nStr - 0;
	if (isNaN(NanTest)) {
		return 0;
	}

	nStr = nStr.toString();
	nStr = replacePattern(nStr, ',', '');
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}

	outString = '$' + x1 + x2;

	// /*if($(objInput).is('.dollar')) {
	// outString = '$'+outString;
	// }
	// if($(objInput).is('.dollarS')) {
	// outString = '$'+outString;
	// }*/

	return outString;
}

function uploadNews() {

	var strFileTitle = $('#fileTitle').val();
	var fileName = $('#mixAttachment').val();

	$.ajax( {
		type : "POST",
		url : "/admin/upload/doupload",
		data : "strFileTitle=" + strFileTitle + "&strFileName=" + fileName,
		success : function(response) {

		}

	});

}

function saveCalculator() {

	if ($('#strCalculatorTitle').val() == "") {
		var defaultText = 'New Calculator';
	} else {
		var defaultText = $('#strCalculatorTitle').val();
	}

	jPrompt(
			'Enter a name for the calculator:',
			defaultText,
			'Save Calculator',
			function(r) {
				if (r) {
					$('#strCalculatorTitle').val(r);
					document.calculatorForm.action = '/professional/saveCalculator';
					document.calculatorForm.submit();
				}
			});

}

function attachToLoan() {

	if ($('#strCalculatorTitle').val() == "") {
		var defaultText = 'New Calculator';
	} else {
		var defaultText = $('#strCalculatorTitle').val();
	}

	jPrompt(
			'Enter a name for the calculator:',
			defaultText,
			'Attach to Loan Application',
			function(r) {
				if (r) {
					$('#strCalculatorTitle').val(r);
					document.calculatorForm.action = '/professional/attachToLoanApplication';
					document.calculatorForm.submit();
				}
			});
}

function confirmLoanUpdate(loanStatus, appraisedValue) {

	newLoanStatus = $('#strNewLoanStatus :selected').text();
	newAppraisedValue = $('#strAppraisedValue').val();
	if (confirm("Update Loan status to " + newLoanStatus
			+ " and Appraised amount to " + newAppraisedValue + " ?")) {
		$('#loanUpdateForm').submit();
	}
}

function confirmLoanQueue() {

	newLoanStatus = $('#strNewLoanStatus :selected').text()
	if (confirm("Change the loan status to " + newLoanStatus + " ?")) {

		$('#loanUpdateForm').submit()
	}

}

function updateStatus(strStatus, intUserId) {

	$('#strStatus').val(strStatus);
	$('#intUserId').val(intUserId);
	if (confirm("Change the user status to " + strStatus + " ?")) {

		$('#updateUserStatus').submit()
	}
}

function deleteUploadedNews(fileID) {

	jConfirm('Do you want to delete this uploaded news file ?', 'Delete',
			function(r) {
				if (r)
					window.location = '/admin/news/delete/' + fileID;
			});

}

function deleteUploadedGuides(fileID) {

	jConfirm('Do you want to delete this uploaded guide file ?', 'Delete',
			function(r) {
				if (r)
					window.location = '/admin/guides/delete/' + fileID;
			});

}

function gotoLoan() {

	intLoanId = $('#intLoanIdView').val();
	if (intLoanId != '') {
		window.location = '/admin/loan/' + intLoanId;
	}
}

function editOtherLabelFields(hiddenField, labelField) {

	var fieldName = $('#' + hiddenField).val();
	jPrompt('Enter a name if you want to change:', fieldName, 'Edit Field',
			function(r) {

				if (r != null) {
					r = trim(r)
				}
				;
				if (r) {
					r = replacePattern(r, ':', '')
					$('#' + hiddenField).val(r + ':');
					$('#' + labelField).html(r + ':');
				} else {
					r = replacePattern(fieldName, ':', '');
					$('#' + hiddenField).val(r + ':');
					$('#' + labelField).html(r + ':');
				}

			});

}

function trim(s) {

	var l = 0;
	var r = s.length - 1;
	while (l < s.length && s[l] == ' ') {
		l++;
	}
	while (r > l && s[r] == ' ') {
		r -= 1;
	}
	return s.substring(l, r + 1);
}

function addRatio() {

	value = $('#strDSCRatio').val() - 0;

	if (isNaN(value)) {
		jAlert(
				'Only numeric values are allowed in Debt Service Coverage Ratio',
				'Invalid value!');

	} else {
		bolAlreadyExists = false;
		$('#strDSCRatioList option').each(function(i, option) {
			if (value == $(option).val()) {

				bolAlreadyExists = true;
			}
		});
		if (bolAlreadyExists) {

			jAlert('The entered ratio already exists in the list',
					'Invalid value!');

		} else {
			key = value + " %";
			$('#strDSCRatioList').append(
					$("<option></option>").attr("value", value).text(key));

			$('#strDSCRatio').val('');

			var sortedVals = $.makeArray($('#strDSCRatioList option')).sort(
					function(a, b) {
						return ($(a).val() - 0) > ($(b).val() - 0) ? 1 : -1;
					});

			$('#strDSCRatioList').empty().html(sortedVals);
		}
	}
}

function removeRatio() {

	value = $('#strDSCRatioList').val();
	$('#strDSCRatioList :selected').each(function(i, selected) {
		value = $(selected).val();
		$("#strDSCRatioList option[value=" + value + "]").remove();
	});
}

function addVacancyPercentage() {

	value = $('#strVacancyPercentage').val() - 0;

	if (isNaN(value)) {
		jAlert(
				'Only numeric values are allowed in Debt Service Coverage Ratio',
				'Invalid value!');

	} else {
		bolAlreadyExists = false;
		$('#strVacancyPercentageList option').each(function(i, option) {
			if (value == $(option).val()) {

				bolAlreadyExists = true;
			}
		});
		if (bolAlreadyExists) {

			jAlert('The entered value already exists in the list',
					'Invalid value!');

		} else {
			key = value + " %";
			$('#strVacancyPercentageList').append(
					$("<option></option>").attr("value", value).text(key));

			$('#strVacancyPercentage').val('');

			var sortedVals = $.makeArray($('#strVacancyPercentageList option'))
					.sort(function(a, b) {
						return ($(a).val() - 0) > ($(b).val() - 0) ? 1 : -1;
					});

			$('#strVacancyPercentageList').empty().html(sortedVals);
		}
	}
}

function removeVacancyPercentage() {

	value = $('#strVacancyPercentageList').val();
	$('#strVacancyPercentageList :selected').each(function(i, selected) {
		value = $(selected).val();
		$("#strVacancyPercentageList option[value=" + value + "]").remove();
	});
}

function submitManageCalculator() {

	$('#strVacancyPercentageList option').each(function(i, option) {

		$(option).attr("selected", "selected");
	});

	$('#strDSCRatioList option').each(function(i, option) {

		$(option).attr("selected", "selected");
	});

	$('#manageCalculatorForm').submit();

}

function disableCalculator() {

	$('#calculatorForm input').each(function(i, option) {

		$(option).attr("disabled", "disabled");
	});

	$('#calculatorForm select').each(function(i, option) {

		$(option).attr("disabled", "disabled");
	});

	$('input.logindetails').removeAttr('disabled');
	$('#strProductType').removeAttr('disabled');
	$('#btnSubmit').removeAttr('disabled');
}

function submitPaginationForm() {

	url = $('#strPaginationTarget').val();
	page = $('#intPageNumber').val();
	window.location = url + page;
}

function playVideo(videoName) {

	var playerContent = "<object type='application/x-shockwave-flash' data='/player/player-viral.swf' width='410' height='325'>"
			+ "<param name='movie' value='/player/player-viral.swf' />"
			+ "<param name='allowfullscreen' value='true' />"
			+ "<param name='allowscriptaccess' value='always' />"
			+ "<param name='flashvars' value='file=/uploads/videos/"
			+ videoName
			+ "&autostart=true' />"
			+ "<p><a href='http://get.adobe.com/flashplayer'>Get Flash</a> to see this player.</p>"
			+ "</object>";

	$("#players").html(playerContent);

}

function updateSiteContents() {

	jConfirm(
			'Do you want to update the page contents ?',
			'Update content',
			function(r) {
				if (r) {
					$
							.ajax( {
								type : "POST",
								url : "/admin/main/updateContents",
								data : $('#strContent').serialize()
										+ "&intConentId="
										+ $('#intHiddenContentId').val()
										+ "&strContentTitle="
										+ $('#strContentTitle').val(),
								success : function(response) {
									if (response == 'Disallowed Key Characters.') {
										$('#response-box').addClass('error');
										$('#response-box')
												.html(
														"Failed to post the comment. Disallowed Key Characters. Please try again.");
									} else {
										var json = eval('(' + response + ')');

										if (!json.bolStatus) {
											$('#response-box')
													.addClass('error');
										} else {
											$('#response-box').css('color',
													'#00477E');
											window.location = $(
													'#strHiddenPageUrl').val();
										}
										$('#response-box')
												.html(json.strMessage);
									}

								},
								error : function() {

								}

							});
				}
			});

}

function showPreview() {
	$
			.ajax( {
				type : "POST",
				url : "/admin/main/previewContents",
				data : $('#strContent').serialize() + "&intConentId="
						+ $('#intHiddenContentId').val() + "&strContentTitle="
						+ $('#strContentTitle').val(),
				success : function(response) {
					if (response == 'Disallowed Key Characters.') {
						$('#comment-response-box').addClass('error');
						$('#comment-response-box')
								.html(
										"Failed to post the comment. Disallowed Key Characters. Please try again.");
					}

				},
				error : function() {

				}

			});
}

function loadPageContentById() {

	var contentId = $('#dpSiteContainer').val();
	$('#comment-response-box').html('');
	$.ajax( {
		type : "POST",
		url : "/admin/main/getContentById",
		data : "intConentId=" + contentId,
		success : function(response) {
			var json = eval('(' + response + ')');

			if (json.bolStatus) {
				$('#intHiddenContentId').val(json.intContentId);
				$('#strContentTitle').val(json.strPageTitle);
				$('#strContent').val(json.strPageContent);
				$('#strHiddenPageUrl').val(json.strURL);
			}

		},
		error : function() {

		}

	});
}

function checkOtherFieldSelection(curObj) {

	switch (curObj.id) {
	case 'strLoanType':
		if ($(curObj).val() == "other") {
			$('#hiddenLoanText').show();
		} else {
			$('#hiddenLoanText').hide();
		}
		break;

	case 'strPropertyType':
		if ($(curObj).val() == "other") {
			$('#hiddenPropertyText').show();
		} else {
			$('#hiddenPropertyText').hide();
		}
		break;
	}
}

function addTestmonial() {

	var errorFlag = 0;
	var strName = trim($('#strName').val());
	var orgName = trim($('#strOrganizationName').val());
	var strContent = trim($('#strDescription').val());
	$('.validationmessage.alignleft.name').html("");
	$('.validationmessage.alignleft.org').html("");
	$('.validationmessage.alignleft.desc').html("");

	if (strName == "") {
		$('.validationmessage.alignleft.name').html(
				"Name  field should not be empty.");
		errorFlag = 1;
	} else {
		var pattern = "^([a-zA-Z]+[\.\']{0,1}[ ]{0,1})*$";

		if (strName.match(pattern)) {
			$('.validationmessage.alignleft.name').html("");
			errorFlag = 0;
		} else {
			$('.validationmessage.alignleft.name').html(
					"Please enter a valid name.");
			errorFlag = 1;
		}
	}
	if (orgName == "") {
		$('.validationmessage.alignleft.org').html(
				"Organization name field should not be empty.");
		errorFlag = 1;
	}
	if (strContent == "") {
		$('.validationmessage.alignleft.desc').html(
				"Content field should not be empty.");
		errorFlag = 1;
	}

	if (!errorFlag) {
		$
				.ajax( {
					type : "POST",
					url : "/admin/main/addTestmonials",
					data : $('#strDescription').serialize() + "&strName="
							+ strName + "&strOrganizationName=" + orgName,
					success : function(response) {
						var json = eval('(' + response + ')');

						if (json.bolStatus) {

							jAlert(
									"Successfully saved the testimonial into the database",
									"Saved Testimonial",
									function(r) {
										if (r) {
											window.location = '/admin/manage/testimonials';
										}
									});

						} else {
							$('.one-time-message')
									.css('color', '#be1b00')
									.html(
											'Failed to save the testimonial into the database.');
						}

					},
					error : function() {
						$('.one-time-message')
								.css('color', '#be1b00')
								.html(
										'Failed to save the testimonial into the database.');
					}

				});
	}

}

function deleteTestmonial(intTestimonialId) {

	jConfirm(
			'Do you want to delete the selected testimonial ?',
			'Delete testimonial',
			function(r) {
				if (r) {
					$
							.ajax( {
								type : "POST",
								url : "/admin/main/deleteTestimonial",
								data : "intTestimonialId=" + intTestimonialId,
								success : function(response) {
									var json = eval('(' + response + ')');

									if (json.bolStatus) {
										// $('.one-time-message').html('Successfully
										// deleted the selected testimonial from
										// database.');
										$('#commentbox_' + intTestimonialId)
												.hide();
										jAlert("Successfully deleted the selected testimonial from database");
									} else {
										// $('.one-time-message').css('color',
										// '#be1b00').html('Failed to delete the
										// testimonial from the database.');
										jAlert(
												"Failed to delete the testimonial from the database.",
												"Delete testimonial");
									}

								},
								error : function() {

									$('.one-time-message')
											.css('color', '#be1b00')
											.html(
													'Failed to delete the testimonial from the database.');
								}

							});
				}
			});
}

function editCommentSection() {

	if ($('#editorContainerId').css('display') == 'none') {
		$('#editorContainerId').css('display', 'block');
		$('#commentContent').hide();

		var btn = "<input type='button'  id='saveCommentButton' onclick='saveCommentSection();'  style='background-image:url(/images/save_content.png);height:30px;width:70px;border:0px;background-color:transparent;padding:0px;' />"
				+ "<input type='button'  id='cancelCommentButton' onclick='cancelUpdate();'  style='background-image:url(/images/cancelbutton.jpg);height:28px;width:70px;border:0px;background-color:transparent;padding:0px;' />";
		$('#buttonContainer').html(btn);
	}
}

function cancelUpdate() {

	$('#editorContainerId').css('display', 'none');
	$('#commentContent').show();

	var btn = "<input type='button'  class='inlineEditComment' onclick= 'editCommentSection();' style='background-image:url(/images/edit_button.png);height:24px;width:100px;float:right;margin:5px;border:0px;background-color:transparent;padding:0px;' />";
	$('#buttonContainer').html(btn);
}

function saveCommentSection() {

	jConfirm('Do you want to update this comment section ?', 'Update comment',
			function(r) {
				if (r) {
					$.ajax( {
						type : "POST",
						url : "/admin/main/updateCommentSection",
						data : $('#strDescription').serialize()
								+ "&intCommentId="
								+ $('#intHiddenCommentId').val(),
						success : function(response) {

							var json = eval('(' + response + ')');

							if (!json.bolStatus) {
								jAlert("Failed to update the contents.",
										'Update comment');
							} else {
								window.location = json.redirectURL;

							}

						},
						error : function() {

						}

					});
				}
			});

}

function editTestimonial(intTestimonialId) {

	window.location = '/admin/testimonial/edit/' + intTestimonialId;
}

function updateTestimonial(intTestimonialId) {

	var errorFlag = 0;
	var strName = trim($('#strName').val());
	var orgName = trim($('#strOrganizationName').val());
	var strContent = trim($('#strDescription').val());
	$('.validationmessage.alignleft.name').html("");
	$('.validationmessage.alignleft.org').html("");
	$('.validationmessage.alignleft.desc').html("");

	if (strName == "") {
		$('.validationmessage.alignleft.name').html(
				"Name  field should not be empty.");
		errorFlag = 1;
	} else {
		var pattern = "^([a-zA-Z]+[\.\']{0,1}[ ]{0,1})*$";

		if (strName.match(pattern)) {
			$('.validationmessage.alignleft.name').html("");
			errorFlag = 0;
		} else {
			$('.validationmessage.alignleft.name').html(
					"Please enter a valid name.");
			errorFlag = 1;
		}
	}
	if (orgName == "") {
		$('.validationmessage.alignleft.org').html(
				"Organization name field should not be empty.");
		errorFlag = 1;
	}
	if (strContent == "") {
		$('.validationmessage.alignleft.desc').html(
				"Content field should not be empty.");
		errorFlag = 1;
	}

	if (!errorFlag) {
		$
				.ajax( {
					type : "POST",
					url : "/admin/main/updateTestmonial",
					data : $('#strDescription').serialize()
							+ "&intTestimonialId=" + intTestimonialId
							+ "&strName=" + strName + "&strOrganizationName="
							+ orgName,
					success : function(response) {
						var bolStatus = response;

						if (bolStatus) {

							window.location = '/admin/manage/testimonials';

						} else {
							$('.one-time-message')
									.css('color', '#be1b00')
									.html(
											'Failed to update the testimonial into the database.');
						}

					},
					error : function() {
						$('.one-time-message')
								.css('color', '#be1b00')
								.html(
										'Failed to update the testimonial into the database.');
					}

				});
	}
}

function closeVideoPlayer() {

	$('#mask').hide();
	$('#playerContainer').hide();
	document.body.style.overflow = 'scroll';
}

function initiateFlowPlayer(intVideoFileId) {

	if (intVideoFileId != null) {
		$('#mask').show();
		$('#playerContainer').show();
		document.body.style.overflow = 'hidden';
		$
				.ajax( {
					type : "POST",
					url : "/main/displayVideo",
					data : "intVideoFileId=" + intVideoFileId,
					success : function(response) {
						var json = eval('(' + response + ')');
						$('#player').attr('href',
								'/uploads/videos/' + json.strEncryptedFileName);
						$('#scriptContainer')
								.html(
										"<script language='JavaScript'>"
												+ "flowplayer('player', '/player/flowplayer-3.2.2.swf');"
												+ "</script>")

					},
					error : function() {

					}

				});
	}

}

function editApplyCommentSection() {

	if ($('#editorContainerId').css('display') == 'none') {
		$('#editorContainerId').css('display', 'block');
		$('#commentContent').hide();

		var btn = "<input type='button'  id='saveCommentButton' onclick='saveApplyCommentSection();'  style='background-image:url(/images/save_content.png);height:30px;width:70px;border:0px;background-color:transparent;padding:0px;' />"
				+ "<input type='button'  id='cancelCommentButton' onclick='cancelApplyUpdate();'  style='background-image:url(/images/cancelbutton.jpg);height:28px;width:70px;border:0px;background-color:transparent;padding:0px;' />";
		$('#buttonContainer').html(btn);
	}
}

function cancelApplyUpdate() {

	$('#editorContainerId').css('display', 'none');
	$('#commentContent').show();

	var btn = "<input type='button'  class='inlineEditComment' onclick= 'editApplyCommentSection();' style='background-image:url(/images/small_edit.png);height:24px;width:60px;float:right;margin:5px;border:0px;background-color:transparent;padding:0px;' />";
	$('#buttonContainer').html(btn);
}

function saveApplyCommentSection() {

	jConfirm('Do you want to update this section ?', 'Update', function(r) {
		if (r) {
			$.ajax( {
				type : "POST",
				url : "/admin/main/updateApplyCommentSection",
				data : $('#strTitle').serialize() + "&"
						+ $('#strDescription').serialize() + "&"
						+ $('#strQuote').serialize(),
				success : function(response) {

					var json = eval('(' + response + ')');

					if (!json.bolStatus) {
						jAlert("Failed to update the contents.",
								'Update comment');
					} else {
						window.location = '/';

					}

				},
				error : function() {

				}

			});
		}
	});

}

function storeSessionandSubmit() {

	document.borrowerForm.action = '/application/step2';
	document.borrowerForm.submit();
}

function storeSessionandGotoFirst() {
	document.propertyForm.action = '/application/step1';
	document.propertyForm.submit();
}

function submitSignUpForm() {

	if ($('#terms_check').attr('checked')) {
		if ($('#strFirstName').val() == "Enter your name") {
			$('#strFirstName').val('');
		}
		if ($('#strEmail').val() == "Enter your email address") {
			$('#strEmail').val('');
		}
		if ($('#strConfirmEmail').val() == "Enter your email address") {
			$('#strConfirmEmail').val('');
		}
		if ($('#strLocation').val() == "Enter location") {
			$('#strLocation').val('');
		}

		document.signUpForm.action = '/signup';
		document.signUpForm.submit();

	} else {
		jAlert(
				'Please accept the terms and conditions by marking the check box.',
				'Centurion Bancorp - Terms & Conditions');
	}

}

function submitProfessionalSignUp() {

	if ($('#prof_terms_check').attr('checked')) {

		if ($('#strEmail').val() == 'Enter your email address') {

			$('#strEmail').val('');
		}
		if ($('#strFirstName').val() == 'Enter your name') {

			$('#strFirstName').val('');
		}
		if ($('#strLastName').val() == 'Enter your name') {

			$('#strLastName').val('');
		}
		if ($('#strProfession').val() == 'Enter your profession') {

			$('#strProfession').val('');
		}
		if ($('#strCompanyName').val() == 'Enter your company name') {

			$('#strCompanyName').val('');
		}
		if ($('#strStreet1').val() == 'Enter your street') {

			$('#strStreet1').val('');
		}
		if ($('#strStreet2').val() == 'Enter your street') {

			$('#strStreet2').val('');
		}
		if ($('#strCity').val() == 'Enter your city') {

			$('#strCity').val('');
		}
		if ($('#strZip').val() == 'Enter zip code') {

			$('#strZip').val('');
		}

		document.professionalSignUp.action = '/professional/signup';
		document.professionalSignUp.submit();

	} else {
		jAlert(
				'Please accept the terms and conditions by marking the check box.',
				'Centurion Bancorp - Terms & Conditions');
	}
}

function setSessionForSignUp(formName, sessionType) {

	$.ajax( {
		type : "POST",
		url : "/main/setSignUpSession",
		data : $('#' + formName).serialize() + '&sessionType=' + sessionType,

		success : function(response) {

			window.location = '/termsOfUse';

		},
		error : function() {

		}

	});
}

function submitImageForm() {

	var errFlag = 0;

	if ($('#dpImages').val() == '') {
		errFlag = 1;
		$('#validationmessage').html('Please select a section.');
		$('#validationmessage').css('font-size', '13px');
	} else {
		errFlag = 0;
		$('#validationmessage').html('');
	}

	if (errFlag == 0) {
		document.imageForm.action = '/admin/manage/images';
		document.imageForm.submit();
	}
}

function showProductEditor(productId) {
	
	$('#mask').show();
	$('#pdtEditor').show();

	$.ajax( {
		type : "POST",
		url : "/admin/main/productComments",
		data : 'productId=' + productId,

		success : function(response) {

			var json = eval('(' + response + ')');

			$('#strProduct').val(json.strPageContent);
			$('#intProductBoxContentId').val(json.intContentId);
		},
		error : function() {

		}

	});

}

function cancelProductUpdate() {
	$('#mask').hide();
	$('#pdtEditor').hide();
}

function saveProductUpdateSection() {

	$.ajax( {
		type : "POST",
		url : "/admin/main/saveProductComments",
		data : 'productId=' + $('#intProductBoxContentId').val()+
				"&" +$('#strProduct').serialize(),

		success : function(response) {

		  var json = eval('(' + response + ')');

			if (json.status) {

				jAlert(
						"Successfully updated the box contents",
						"Centurian Bancorp - Update",
						function(r) {
							if (r) {
								window.location = '/';
							}
						});
				
			} else {

				jAlert("Failed to update the box contents",
						"Centurian Bancorp - Update");
			}

			cancelProductUpdate();
		

		},
		error : function() {

		}

	});
}

function deleteMGmtImage(intImageId) {
	
	$.ajax( {
		type : "POST",
		url : "/admin/upload/deleteMgmtImageUpload",
		data : 'imageId=' + intImageId,

		success : function(response) {

			var json = eval('(' + response + ')');

			if (json.status) {

				$('#imageRow-' + intImageId).hide();
				$('.one-time-message').css('color', '#00477E').html(
						"The selected file has been deleted successfully.");

			} else {

				$('.one-time-message').css('color', '#be1b00').html(
						"Failed to delete the selected file.");

			}

		},
		error : function() {

		}

	});
}

function deleteAddedFAQ(intFAQId) {
	jConfirm('Do you want to delete this Question ?', 'FAQ', function(r) {
		if (r) {
			$.ajax( {
				type : "POST",
				url : "/admin/upload/deleteFAQ",
				data : 'intFAQId=' + intFAQId,

				success : function(response) {

					var json = eval('(' + response + ')');

					if (json.status) {

						window.location = '/admin/manage/Faq';

					} else {

						jAlert("Failed to delete the selected Question",
								"Centurian Bancorp - Delete");

					}

				},
				error : function() {

				}

			});
		}

	});
}

