 var web_user_validator;
 var oneMinute = 60 * 1000  // milliseconds in a minute
 var oneHour = oneMinute * 60
 var oneDay = oneHour * 24
 var oneWeek = oneDay * 7

//Ajimon KS fm_Call related
 var requestError="";
 var help_desk_form_values="";
 var help_desk_form_action="";


//Ajimon Validatior varibales for common use
var v;
var a_fields;
var o_config

function getDateStr( dateValue ){
	var year, month, day;
	var result;
	year = "" + dateValue.getFullYear();
	month = "" + (dateValue.getMonth()+1);
	if ( month.length == 1 )
		month = "0" + month;
	day = "" + dateValue.getDate();
	if ( day.length == 1 )
		day = "0" + day;
	result = year + "-" + month + "-" + day;
	return result;
}

function validateSearchDate(frm) {
	var from = frm.fromdatedisp.value;
	var to = frm.todatedisp.value;
	if ( from != null && from != ""  && to != null && to != "" )
	{
		if ( Date.parse(from) > Date.parse(to))
		{
			alert( "From date must be before To date.  Please re-enter.");
			//frm.toDate.focus();
			return false;
		}

	}

	// format the dates into format required
	// by search stored procedure
	if ( from.length > 0 )
	{
		var fromDate = new Date(from);
		from = getDateStr( fromDate );
		frm.fromdate.value = from;
	}
	if ( to.length > 0 )
	{
		var toDate = new Date(to);
		to = getDateStr( toDate );
		frm.todate.value = to;
	}
	return true;
}


function oldvalidateSearch(frm) {
	
	var input = frm.quicksearch.value;

	/* Trim input string */
	input = input.replace(/^\s*(.*)/, "$1");
	input = input.replace(/(.*?)\s*$/, "$1");


	if (  input == "<Enter search here>" || input.length == 0 )
	{
		/* Nothing specified so don't invoke search */
		if (frm.fromdatedisp) {
			input = frm.fromdatedisp.value;
			/* Trim input string */
			input = input.replace(/^\s*(.*)/, "$1");
			input = input.replace(/(.*?)\s*$/, "$1");
			if ( input.length == 0 )
			{
				input = frm.todatedisp.value;
				/* Trim input string */
				input = input.replace(/^\s*(.*)/, "$1");
				input = input.replace(/(.*?)\s*$/, "$1");
				if ( input.length == 0 )
					return false;

			}

			frm.quicksearch.value = " ";

		}
		else
			return false; 
	
	}
	return validateSearchDate(frm);
}

function validateSearch(frm) {
	
	var input = frm.quicksearch.value;

	/* Trim input string */
	input = input.replace(/^\s*(.*)/, "$1");
	input = input.replace(/(.*?)\s*$/, "$1");


	if (  input == "<Enter search here>" || input.length == 0 )
	{
		frm.quicksearch.value = " ";
	}
	return validateSearchDate(frm);
}


function validatePassword(frm) {

	$('p.p_pass label').removeClass('tfvHighlight');
	//var input = frm.password.value;//WEX15189
	var input = $("#password").val();//WEX15189

	/* Trim input string */
	input = input.replace(/^\s*(.*)/, "$1");
	input = input.replace(/(.*?)\s*$/, "$1");
	if ( input.length == 0 )
	{
		alert("Please enter a password.");
		$("#password").focus()//WEX15189
		//frm.password.focus();//WEX15189
		$('#t_password').addClass('tfvHighlight');
		return false;
	}
	if ( input.length > 100 )
	{
		alert("Value for password must be no longer than 100 characters.");
		$("#password").focus()//WEX15189
		//frm.password.focus();//WEX15189
		$('#t_password').addClass('tfvHighlight');
		return false;
	}

	if (enforce_strong_password== 'Y')
	{
		if(! (validateStrongPassword(input) ) ){
		$("#password").focus()//WEX15189
		//frm.password.focus();//WEX15189
		$('#t_password').addClass('tfvHighlight');
		return false;
		}
	}


	//if ( frm.password.value != frm.password2.value ){	//WEX15189
	if ( $("#password").val() != $("#password2").val() ){	//WEX15189
		alert( "Password mismatch.");		
		
		$("#password2").focus()//WEX15189
		//frm.password2.focus();//WEX15189

		$('#t_password2').addClass('tfvHighlight');
		return false;	
	}

	return true;
}


function validateStrongPassword(pw){
		var errHeading="The new password entered does not conform to the minimum required. Please ensure that the password contains:\n";
		var errItems="";
		var minPassLength=8;
		var upperRegExp=/[A-Z]/g
		var	numericRegExp= /[0-9]/g
		var	specialCharecterRegExp=/[\W_]/g
		//var	specialCharecterRegExp=/[&\'{([-_@)]}$*% !:/ ;.,\;\"]/g
		if(pw.length < minPassLength ){
			errItems="\tMinimum of 8 characters\n";
		}
		var matches = pw.match(new RegExp(upperRegExp));//Uppercase
		if(matches==null){
			errItems=errItems+"\tMinimum of 1 uppercase character (A-Z) \n";
		}
		matches = pw.match(new RegExp(numericRegExp));//Uppercase
		if(matches==null || matches.length < 2 ){
			errItems= errItems+ "\tMinimum of 2 characters to be numeric (0-9)\n";
		}
		matches = pw.match(new RegExp(specialCharecterRegExp));//non alphanumeric 
		if(matches==null){
			errItems=errItems+ "\tMinimum of 1 non-alphanumeric character(&'{([-_@)]}$*% !:/\;.,\")";
		}
		if(errItems.length >0){
			alert(errHeading+errItems);
			return false;
		}else{
			return true;
		}
}



function validateWebUser(frm)
{
	return web_user_validator.exec();
}


function validate(frm) {
	var input = $("#password").val();
	if ( input.length == 0 )
	{
		alert("Please enter a password.");
		$("#password").focus();
		return false;
	}

	
	if ( $("#password").val() != $("#password2").val() )
	{
		alert( "Password mismatch.");
		$("#password2").focus();			
		return false;
	}
	return true;
}			







function initForm() {
	var form_name;
	if ( document.forms.length > 0 )
	{
		var frm = document.forms[0];
	
		if ( frm.name == 'webUser' ) 
		{
			initWebUserForm(frm.name);
	
		}	
	}
}

function initWebUserForm(frm_name)
{
	// form fields description structure	var a_fields = {		'login_id': {		'l': 'Name',  // label		'r': true,    // required		'f': 'name',  // format (see below)		't': 't_login_id',// id of the element to highlight if input not validated				'm': null,     // must match specified form field		'mn': 4,       // minimum length		'mx': 10       // maximum length		},		'web_user_name': {		'l': 'Name',  // label		'r': false,    // required		'f': 'name',  // format (see below)		't': 't_web_user_name',// id of the element to highlight if input not validated				'm': null,     // must match specified form field		'mn': 2,       // minimum length		'mx': 40       // maximum length	},	'email':{'l':'Email','r':false,'f':'email','t':'t_email'},	'phone':{'l':'Telephone Number','r':false,'f':'phone','t':'t_phone'}	},	o_config = {		'to_disable' : ['submit'],		'alert' : 1	}	// validator constructor call	web_user_validator = new validator(frm_name, a_fields, o_config);	// init form	web_user_validator.init();
}


function xxx_setFormFocus()

{

	if ( document.forms.length > 0 )
	{
		var frm = document.forms[0];
		if ( frm.elements.length > 0 )
		{

			frm.elements[0].focus();
			if ( frm.elements[0].tagName.toUpperCase() == 'INPUT' )
				frm.elements[0].select();
		}
	}

}


function ignoreSpaces(string) {
var temp = "";
string = '' + string;
splitstring = string.split(" ");
for(i = 0; i < splitstring.length; i++)
temp += splitstring[i];
return temp;
}


function wordCap(inputStr) {
	var index;
	var tmpStr;
	var tmpChar;
	var preString;
	var postString;
	var strlen;
	
	tmpStr = inputStr.toLowerCase();
	strLen = tmpStr.length;
	if (strLen > 0)  {
		for (index = 0; index < strLen; index++)  {
			if (index == 0)  {
				tmpChar = tmpStr.substring(0,1).toUpperCase();
				postString = tmpStr.substring(1,strLen);
				tmpStr = tmpChar + postString;
			}
			else {
				tmpChar = tmpStr.substring(index, index+1);
				if (tmpChar == " " && index < (strLen-1))  {
					tmpChar = tmpStr.substring(index+1, index+2).toUpperCase();
					preString = tmpStr.substring(0, index+1);
					postString = tmpStr.substring(index+2,strLen);
					tmpStr = preString + tmpChar + postString;
			         }
			}
		}
	}
	return inputStr;
}

function open_excel(pageName, entityName, query ) {

excelwin = window.open( 'exportxls.jsp?page='+pageName+'&entity='+entityName+'&query='+query,'WebExecExport','resizable=yes,top=150,left=150,width=480,height=400');
if (!excelwin.opener) excelwin.opener = self;
}

function getBrowserName(){
		if ($.browser.msie) return "msie";
		if ($.browser.mozilla) return "mozilla";
		if ($.browser.opera) return "opera";
		var userAgent = navigator.userAgent.toString().toLowerCase();
		if ((userAgent.indexOf('safari') != -1) && !(userAgent.indexOf('chrome') != -1)) {
			return "safari";
		}else{
			return "chrome";
		}
}

function open_admin_help(user_type){
	helpwin = window.open('adminhelplist.jsp?user_type='+user_type,'PMAHelp','resizable=yes,top=150,left=150,location=no,scrollbars=yes,width=700,height=550');
	if (!helpwin.opener) helpwin.opener = self;

}



function open_help(formName, columnName) {
	var browser =getBrowserName();

	var winheight = "500";
	var winwidth ="520";
	if(formName=='dw_fm_call_single_item'){
		if (document.dw_fm_call_single_item.call_linked_to!=null){
			//document.dw_fm_call_single_item.call_linked_to[0].checked=true;
			if(columnName=='b_client_ref') {populateRadioButtonValue(document.dw_fm_call_single_item.call_linked_to,'client'); winwidth = "650px";}
			if(columnName=='b_property_ref') {populateRadioButtonValue(document.dw_fm_call_single_item.call_linked_to,'property'); winwidth = "850px";}
			if(columnName=='b_property_amenity_amenity_type_code') {populateRadioButtonValue(document.dw_fm_call_single_item.call_linked_to,'property amenity'); winheight = "550px"; winwidth = "780px";}
			if(columnName=='b_unit_ref') {populateRadioButtonValue(document.dw_fm_call_single_item.call_linked_to,'unit'); winheight = "650px"; winwidth = "940px";}
			if(columnName=='b_unit_amenity_amenity_type_code') {populateRadioButtonValue(document.dw_fm_call_single_item.call_linked_to,'unit amenity');winwidth = "950px";}
			if(columnName=='b_fm_asset_uri') {populateRadioButtonValue(document.dw_fm_call_single_item.call_linked_to,'Asset'); winwidth = "940px";}
			if(columnName=='b_creditor_uri') {populateRadioButtonValue(document.dw_fm_call_single_item.call_linked_to,'Creditor'); winwidth = "850px"; winheight = "650px";}
			if(columnName=='b_debtor_uri') populateRadioButtonValue(document.dw_fm_call_single_item.call_linked_to,'Debtor');
			if(columnName=='b_property_amenity_uri') populateRadioButtonValue(document.dw_fm_call_single_item.call_linked_to,'Property Amenity');
			if(columnName=='b_unit_amenity_uri') populateRadioButtonValue(document.dw_fm_call_single_item.call_linked_to,'Unit Amenity');
			if(columnName=='b_debtor_account_no') {populateRadioButtonValue(document.dw_fm_call_single_item.call_linked_to,'Debtor'); winwidth = "850px";winheight = "500px";}
		}
	}
	if (formName=='dw_web_user_relation_single_item' && columnName=='b_sector_code'){
		winheight = "300";
	}
	if (formName=='dw_web_user_relation_single_item' && columnName=='b_property_ref'){
		winwidth = "600";
	}

	if (formName=='dw_web_user_relation_single_item'){
		if (columnName=='b_client_ref'  ||  columnName=='b_tenant_ref' || columnName=='b_property_ref' || columnName=='b_user_ref' ){
			winheight="550";
		}
		
		if(columnName=='b_client_ref'){
			if( browser=="msie" ) winwidth = "600";
			if( browser=="safari" ) winwidth = "480";
			if( browser=="chrome" ) winwidth = "469";

			if( browser=="mozilla" ) {
				winwidth = "550";
				winheight="475";
			}
			if( browser=="opera" ){
				winwidth = "595";
				winheight="475";
			}
		}
	/*
		if(columnName=='b_tenant_ref'){
			if( browser=="msie" ){
				winwidth = "520";
				winheight = "550";
			}
			if( browser=="safari" ) {
				winwidth = "450";
				winheight = "550";
			}

		}*/


	}

	

	//helpwin = window.open('getHelpList?form_name='+formName+'&column_name=' + columnName,'PMAHelp','resizable=yes,top=150,left=150,width='+winwidth+',height='+ winheight);
	helpwin = window.open('getHelpList?form_name='+formName+'&column_name=' + columnName,'PMAHelp','resizable=yes,top=150,left=150,location=no,scrollbars=yes,width='+winwidth+',height='+ winheight);
	if (!helpwin.opener) helpwin.opener = self;


}


function populateRadioButtonValue(radioObj, valuetocomapre) {

	clearValuesOfExistingFileds();

	//alert( $("input[@name="+valuetocomapre]+"") );


//if(!radioObj)return;
//alert(valuetocomapre);
	
	var radioLength = radioObj.length;
	if(radioLength ==undefined) return;
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].value.toLowerCase()== valuetocomapre.toString().toLowerCase()) {
			radioObj[i].checked = true;
		}
	}
}

function clearValuesOfExistingFileds(){
	if($("#client_ref").length > 0) $("#client_ref").val("");
	if($("#client_name").length > 0) $("#client_name").val("");
	if($("#client_uri").length > 0) $("#client_uri").val("");
	if($("#property_ref").length > 0) $("#property_ref").val("");
	if($("#property_name").length > 0) $("#property_name").val("");
	if($("#property_uri").length > 0) $("#property_uri").val("");
	if($("#property_amenity_amenity_type_code").length > 0) $("#property_amenity_amenity_type_code").val("");
	if($("#property_amenity_type_uri").length > 0) $("#property_amenity_type_uri").val("");
	if($("#unit_ref").length > 0) $("#unit_ref").val("");
	if($("#unit_name").length > 0) $("#unit_name").val("");
	if($("#unit_uri").length > 0) $("#unit_uri").val("");
	if($("#fm_asset_property_amenity_uri").length > 0) $("#fm_asset_property_amenity_uri").val("");
	if($("#unit_amenity_amenity_type_code").length > 0) $("#unit_amenity_amenity_type_code").val("");
	if($("#unit_amenity_uri").length > 0) $("#unit_amenity_uri").val("");
	if($("#fm_asset_ref).length") > 0) $("#fm_asset_ref").val("");
	if($("#fm_asset_short_name").length > 0) $("#fm_asset_short_name").val("");
	if($("#fm_asset_uri").length > 0) $("#fm_asset_uri").val("");
	if($("#creditor_account_no").length > 0) $("#creditor_account_no").val("");
	if($("#creditor_name").length > 0) $("#creditor_name").val("");
	if($("#creditor_uri").length > 0) $("#creditor_uri").val("");
	if($("#debtor_account_no").length > 0) $("#debtor_account_no").val("");
	if($("#debtor_billing_name").length > 0) $("#debtor_billing_name").val("");
	if($("#debtor_uri").length > 0) $("#debtor_uri").val("");
		
}


function calculateTargetDate( priority )  {
	var noOfDays = 10;
	priority = priority.toLowerCase();
	if ( priority == "urgent" ){
		noOfDays = 0;
	}else if ( priority == "high" ){
		noOfDays = 3;
	}else if ( priority == "medium"){
		noOfDays = 5;
	}else{
		noOfDays = 10;
	}
	var today = new Date()
	var dateInMS = today.getTime() + oneDay * noOfDays
	var targetDate = new Date(dateInMS)
	return targetDate;
}

function get_element (s_id) {
	return (document.all ? document.all[s_id] : (document.getElementById ? document.getElementById(s_id) : null));
}


function setTargetDate( priority, targetDateControlId ){
		var targetDate;
		targetDate = calculateTargetDate( priority );
		var dtControl = get_element(targetDateControlId);
		targetDate = formatDate( targetDate, "d-MM-yyyy");

		if(priority==''){
			dtControl.value="";
		}else{
			dtControl.value = targetDate;
			chkdate(dtControl,'EU');
		}
	

}


function setFormFocus(){
	if ( document.forms.length > 0 ){
		var o_form = document.forms[0];
		for (i = 0; i < o_form.length; i++) {
			if ((o_form.elements[i].type == "text") || (o_form.elements[i].type == "textarea") || (o_form.elements[i].type.toString().charAt(0) == "s")) {
				if ( !o_form.elements[i].disabled && !o_form.elements[i].readOnly){
					o_form.elements[i].focus();
					if ( o_form.elements[i].tagName.toUpperCase() == 'INPUT' )
						o_form.elements[i].select();
					break;
				}
			}
		}
	}
}

function AboutUS(){
	//window.open("about.jsp","About","resizable=no,scrollbars=no,top=150,left=150,width=450,height=363");
	window.open("about.jsp","About","toolbar=0,location=0,scrollbars=0,menubar=0,resizable=1,top=150,left=150,width=450,height=363");
}

function sendMail(){

//var agreewin=dhtmlmodal.open("agreebox", "iframe", "modalfiles/agreement.htm", "This Page's Terms of service", "width=590px,height=450px,center=1,resize=1,scrolling=0", "recal")

	 mail_win =dhtmlmodal.open('mailbox', 'iframe', 'mail.jsp', 'Send Mail', 'width=590px,height=420px,center=1,resize=0,scrolling=0',"recal");

	/*
	mail_win.onclose=function(){ 

		
		var iframedoc=this.contentDoc
		var emailForm=this.contentDoc.forms[0] 
		var to_email_address=iframedoc.getElementById("to_email_address").value; 
		var from_email_address=iframedoc.getElementById("from_email_address");
		var email_subject=iframedoc.getElementById("email_subject");
		var email_message=iframedoc.getElementById("email_message");
		alert(to_email_address);
		//alert(contentDoc.innerHTML());
		return false;
		
		if (to_email_address.value.indexOf("@")==-1){ 
			alert("Please enter a valid send to email address ")
			return false; //cancel closing of modal window
		}else{
			emailForm.submit();
			return true;
		}
	
	}*/

}

function MessageBox(user_reference,enforce_strong_password){

	if (enforce_strong_password !=null && enforce_strong_password=='Y'){

		if (usertype=='pma'){

			message_win=dhtmlmodal.open('messagebox', 'iframe', 'dhtmlmessagebox.jsp', 'Warning', 'width=400px,height=150px,center=1,resize=0,scrolling=1',"recal");
			message_win.onclose=function(){
				var theform=this.contentDoc.forms[0] 
				var action=this.contentDoc.getElementById("action") 

				if(action.value=="1"){
					window.location="dg_home.jsp?menu=pma_menu.jsp&content=web_user_edit_password.jsp&cameFrom=pma_web_users.jsp&strngpswd=y";
				}else{
					window.location="logout.jsp";
				}
				return true;
			}
		}else{
			//alert("Your current password does not fulfil the criteria for strong passwords and must be changed. Please contact your System Administrator");
		}

	}

}

function resetstatus(login_id,web_user_name){
	/*	
	var returnVal=window.showModalDialog("resetstatus.jsp?login_id="+login_id,window,"help:0;resizable:0;dialogWidth:325px;dialogHeight:150px,center:yes; scroll:no; status:no");
	if(returnVal==1){
		document.searchForm.action="ResetStatusServlet?login_id="+ login_id;
		document.searchForm.submit();

	}*/

	reset_status_win =dhtmlmodal.open('ResetStatus', 'iframe', 'resetstatus.jsp?login_id='+login_id, 'WebUser ResetStatus', 'width=350px,height=200px,center=1,resize=0,scrolling=1')
	reset_status_win.onclose=function(){
		var theform=this.contentDoc.forms[0] 
		var action=this.contentDoc.getElementById("action") 
		if(action.value=="1"){
			document.searchForm.action="ResetStatusServlet?login_id="+ login_id;
			document.searchForm.submit();
		}
		return true
	}
	
}

function setCheckBoxValue(control ){
	var controlName;
	controlName = control.name;
	controlName = controlName.substring( 5);
	var controlObject = 'document.dw_web_menu_security_full_list.' + controlName;
	var controlExists = eval(controlObject);
    if (typeof controlExists == "object"){
	var hiddenControl = eval(controlObject);
	if ( control.checked )
		hiddenControl.value = "Y";
	else
		hiddenControl.value = "N";
	}
}
function validateForm(frmName){
	if(frmName=="signonForm"){
		var object =document.getElementById('login_id');
		var value=document.getElementById('login_id').value;
		value = value.replace(/^\s*(.*)/, "$1");
		value = value.replace(/(.*?)\s*$/, "$1");	
		if (value== null || value.length ==0 ){
		alert("Please enter your login Id.");
		object.focus();
		return false;
		}
	}
	return true;
}
function checkdelete(url)
	{
		var answer = confirm("The record you have selected will be deleted.")
		if (answer){
			url = url.replace(/\&amp;/g,'&');
			window.location = url;
		}
	}

function openBrowser(url,errors){
	if(errors!= null && errors.length> 0 && errors !="null" ){
			alert(errors);
	}else{
		window.open(url, "_blank");
	}
}
