﻿
var contactEdit_Win;
var contactSearch_Win;
var firstNameField2;
var lastNameField2;
var emailAddressField2;
var commentField2;
var contactId;
var contactEdit_Form;

function showContactGroupEditPopupNew() {
	if (groupStore == null) {
		groupStore = new Ext.data.SimpleStore({
			fields: [
           	{ name: 'id' },
		    { name: 'displayName' },
			{ name: 'firstName' },
    		{ name: 'lastName' },
	    	{ name: 'primaryEmail' }
    ]
		});
	}
	else {
		groupStore.removeAll();
	}

	var oContactRecord = Ext.data.Record.create([
       	{ name: 'id' },
		{ name: 'displayName' },
		{ name: 'firstName' },
		{ name: 'lastName' },
		{ name: 'primaryEmail' }
 ]);

	groupName = undefined;
	groupDescription = undefined;
	groupId = null;

	var newContactRecord;
	var m;
	var numMembers;
	var rindex;

	updateAction = "Update";

	var request = new Zapproved.Request({
		url: '/Services/ContactGroup/Get',
		scope: this,
		errorSubject: 'GetContactGroup Failed',
		params: { contactId: sel_Row, tz: tz, tza: tza },
		successCallback: function(result) {

			groupName = result.data.displayName;
			groupDescription = result.data.comment;
			groupId = result.data.id;

			if (result.data.contacts)
				numMembers = result.data.contacts.length;
			else
				numMembers = 0;
			for (m = 0; m < numMembers; m++) {
				rindex = contactStore.find("id", result.data.contacts[m].id)
				if (rindex == -1) {
					newContactRecord = new oContactRecord({
						id: result.data.contacts[m].id,
						displayName: result.data.contacts[m].displayName,
						firstName: result.data.contacts[m].firstName,
						lastName: result.data.contacts[m].lastName,
						primaryEmail: result.data.contacts[m].primaryEmail
					});
					groupStore.add(newContactRecord);
				}
				else {
					groupStore.add(contactStore.getAt(rindex));
				}
			}

			updateAction = "Update";
			showContactGroupUpdatePopup();
		},

		failureCallback: function(result) {
			updateAction = "";
		}

	});
	
	request.doRequest();

}

function deleteContactNew(button) {

	//	var selectionModel = contactGrid.getSelectionModel();
	//    var numRecords;

 

    if (checkBoxCount == 1) {
        Ext.MessageBox.confirm('Confirm', 'Are you sure you want to delete the contact "' + document.getElementById("DisplayName_" + sSelectedContacts.replace("|","")).innerHTML + '"?', deleteContactResult);
        return;
    }
    
    if(checkBoxCount > 1)
    {
        var selContactsArray = sSelectedContacts.split("|");
        var sShowSelectedContactsToDelete = "";
        var sConfirmMessage = "";
        if (checkBoxCount < 20) {
            for (var x = 0; x < selContactsArray.length; x++) {
                if (selContactsArray[x] != "")
                    sShowSelectedContactsToDelete += document.getElementById("DisplayName_" + selContactsArray[x]).innerHTML.replace("<br>", "") + "<br>";
            }
            sConfirmMessage = 'Are you sure you want to delete the contacts:<br><br> ' + sShowSelectedContactsToDelete.replace("<BR>","");
        } else {
            var chkCount = checkBoxCount + 1
            sConfirmMessage = 'Are you sure you want to delete ' + chkCount + ' contacts?';
        }
        Ext.MessageBox.confirm('Confirm',sConfirmMessage , doBatchDelete);
        return;
    }
    
	if (sel_Row == null) {
		Ext.MessageBox.alert('Error', 'You need to select a row before clicking delete.');
		return;
	}

	Ext.MessageBox.confirm('Confirm', 'Are you sure you want to delete the contact "' + document.getElementById("DisplayName_" + sel_Row).innerHTML + '"?', deleteContactResult);

}

function doBatchDelete(button) {
    if (button != 'yes')
        return;

   // sSelectedContacts = sSelectedContacts.substring(0, sSelectedContacts.length - 2);

    Ext.Ajax.request({
        url: '/Services/Contact/DoBatchDelete',
        method: 'POST',
        params: {
        sGuids: sSelectedContacts,
            tz: tz, tza: tza
        },
        success: function(response, request) {
            if (callMask) callMask.hide();
            result = Ext.util.JSON.decode(response.responseText);
            if (result.success) {
                Ext.quickPopup.msg('Delete Contacts Succeeded', 3, result.data);
                window.location.reload();

            }
            else {
                Ext.quickPopup.msg('Delete Contacts Failed', 3, result.data);
            }
        },
        failure: function(response, request) {
            if (callMask) callMask.hide();
            Ext.quickPopup.msg('Delete Contacts Call Failed', 3, "");
        }
    });
}

function deleteContactResult(button) {
	if (button != 'yes')
		return;

	deleteContactResult_afterMask();
}

function deleteContactResult_afterMask() {
	var contactIds = new Array();
	var r;
	contactIds[0] = sel_Row;

	Ext.Ajax.request({
		url: '/Services/Contact/DeleteContacts',
		method: 'POST',
		params: {
			contactIds_json: Ext.util.JSON.encode(contactIds),
			tz: tz, tza: tza
		},
		success: function(response, request) {
			if (callMask) callMask.hide();
			result = Ext.util.JSON.decode(response.responseText);
			if (result.success) {
				Ext.quickPopup.msg('Delete Contacts Succeeded', 3, result.data);
				window.location.reload();

			}
			else {
				Ext.quickPopup.msg('Delete Contacts Failed', 3, result.data);
			}
		},
		failure: function(response, request) {
			if (callMask) callMask.hide();
			Ext.quickPopup.msg('Delete Contacts Call Failed', 3, "");
		}
	});
}


function ColumnHover(that, state) {
	that.style.backgroundColor = state == "1" ? "#E5F1CB" : "#EEE";
}

//	var sort_Dir = null;

//	prev_SortBy 
// prev_SortDir
function DoSort(that) {

	var col = that.id;
	var sortDir = null;
	col = col.replace("hdr_", "");
	col = col.replace(" ", "");

	if (prev_SortBy != null) {
		if (col == prev_SortBy)
			sortDir = prev_SortDir == "asc" ? "desc" : "asc";
		else
			sortDir = "asc";
	} else {
		sortDir = "asc";
	}

	window.location.href = "/Contacts?SortBy=" + col + "&SortDir=" + sortDir + "&View=" + curr_DataView;
}

//#BDD19D;
var sel_Row = null;
var sel_OrgBGColor = null;
var sel_Contact = null;
var row_isClicked = false;

function dataRowHover(that, state, orgBGColor) {
	if (sel_Row == that.id)
		return;

	that.style.cursor = "pointer";

	that.style.backgroundColor = state == "1" ? "#E5F1CB" : orgBGColor;
}

function rowClicked(that, cId, bgColor) {
	row_isClicked = true;
	
	if (sel_Row != null) {
		var theOldRow = document.getElementById(sel_Row);

		theOldRow.style.backgroundColor = sel_OrgBGColor;
		theOldRow.style.color = "black";
	}

	sel_Row = that.id;
	sel_OrgBGColor = bgColor;

	var theRow = document.getElementById(that.id);

	theRow.style.backgroundColor = "#BDD19D";
	theRow.style.color = "white";
	//document.getElementById(that.id).style.borderColor = "black";
	//document.getElementById(that.id).style.borderStyle = "dotted";

}

function divHover(that, state) {
	var theDiv = document.getElementById(that.id);
	//EAEEE3

	theDiv.style.backgroundColor = state == "1" ? "#EAEEE3" : "#BDD19D";
	theDiv.style.cursor = state == "1" ? "pointer" : "pointer";

}

function DoAction(action,obj) {
	switch (action) {
		case "import":
			window.location.href = "/Report/Import";
			break;

		case "delete":
			//Ext.MessageBox.alert($resources.loginRequiredAlertTitleText, $resources.loginRequiredAlertMessageText);
			deleteContactNew(obj);
			break;

		case "add":
			showContactAddPopupNew(obj);
			break;

		case "edit":
			showContactEditPopupNew(obj);
			break;

		case "creategroup":
			showContactGroupAddPopup(obj);
			break;

		case "viewgroups":
			var btn_Label = document.getElementById("contactViewToggle_TD");
			
			if (btn_Label.innerHTML.indexOf("Groups") > -1)
				window.location.href = "/Contacts?View=Groups";
			else
				window.location.href = "/Contacts?View=";
			break;

		case "findcontact":
			DoSearchForContact(obj);
			break;
	}
}

var contactAddWin;
var addingContact = false;

function showContactAddPopupNew(parent) {
	//if (contactAddWin == null) {
		//Ext.form.Field.prototype.msgTarget = 'under';

var contactAddForm = new Ext.FormPanel({
	//		renderTo: 'loginformbox',
	labelWidth: 75,
	frame: false,
	header: false,
	border: false,
	bodyStyle: 'padding:5px 5px 0',
	width: 400,
	defaults: { width: 250 },
	defaultType: 'textfield'
});

var firstNameField = new Ext.form.TextField({
	fieldLabel: 'First Name',
	id: 'firstName',
	name: 'firstName',
	allowBlank: true,
	emptyText: '(first name)'
});

var lastNameField = new Ext.form.TextField({
	fieldLabel: 'Last Name',
	id: 'lastName',
	name: 'lastName',
	allowBlank: true,
	emptyText: '(last name)'
});

var emailAddressField = new Ext.form.TextField({
	fieldLabel: 'Email Address',
	id: 'emailAddress',
	name: 'emailAddress',
	allowBlank: false,
	emptyText: '(email address)',
	blankText: 'Email address is required'
});

var commentField = new Ext.form.TextField({
	fieldLabel: 'Comment',
	id: 'comment',
	name: 'comment',
	emptyText: '(comment)'
});

contactAddForm.add(firstNameField);
contactAddForm.add(lastNameField);
contactAddForm.add(emailAddressField);
contactAddForm.add(commentField);

var addBtn = contactAddForm.addButton({
    text: 'Add Contact',
    id: 'addBtn',
    disabled: false,
    listeners: { click: function() {
        var validEmail = true;
        var invalidEmailMsg = "It appears the Email Address that you have entered is invalid";
        var chkEmail = Ext.getCmp('emailAddress').getValue();

        if (chkEmail == "")
            validEmail = false;
        if (chkEmail.indexOf(".") == -1)
            validEmail = false;
        if (chkEmail.indexOf("@") == -1)
            validEmail = false;

        if (!validEmail) {
            Ext.MessageBox.alert("Invalid Email Address", invalidEmailMsg);
            return;
        }

        if (addingContact)
            return;
            
        addingContact = true;

        contactAddForm.getForm().submit({
            url: '/Services/Contact/Add',
            params: { tz: tz, tza: tza },
            action: 'addContact',
            waitMsg: 'Adding Contact...'
        });
    }
    }
});

var cancelBtn = contactAddForm.addButton({
	text: 'Cancel',
	id: 'cancelBtn',
	disabled: false,
	listeners: { click: function() {
		contactAddWin.close();
	}
	}
});

firstNameField.on('specialkey', function(f, event) {
	if (event.getKey() == event.ENTER) {
		addBtn.focus();
		addBtn.fireEvent("click", addBtn);
	}
}, this);
lastNameField.on('specialkey', function(f, event) {
	if (event.getKey() == event.ENTER) {
		addBtn.focus();
		addBtn.fireEvent("click", addBtn);
	}
}, this);
emailAddressField.on('specialkey', function(f, event) {
	if (event.getKey() == event.ENTER) {
		addBtn.focus();
		addBtn.fireEvent("click", addBtn);
	}
}, this);
commentField.on('specialkey', function(f, event) {
	if (event.getKey() == event.ENTER) {
		addBtn.focus();
		addBtn.fireEvent("click", addBtn);
	}
}, this);

contactAddForm.on({
	expand: function(form, action) {
		var firstNameField = Ext.get('firstName');
		firstNameField.focus();
	},
	actioncomplete: function(form, action) {
		var result = action.result;
		contactStore.load();
		//	Ext.quickPopup.msg('Contact Added!', 3, 'The contact "' + result.data + '" was added successfully! You may add another contact or exit.');
		Ext.quickPopup.msg('Contact Added!', 3, 'The contact "' + result.data + '" was added successfully!');
		form.reset();
		contactAddWin.close();
		addingContact = false;
	},
	actionfailed: function(form, action) {
		if (action.failureType == "server")
		{ window.location.href = String.format($resources.contactsPageUri); } // this window location part is a short term solution the contact add error in services.
		/*{
		var result = action.result;
		Ext.quickPopup.msg('Add Contact Failed!', 3, result.data);
		}*/
		var firstNameField = Ext.get('firstName');
		firstNameField.focus();
		addingContact = false;
		//					contactAddForm.render();
	}
});

contactAddWin = new Ext.Window({
	el: 'contactAddWindow',
	layout: 'fit',
	modal: true,
	title: 'Add Contact',
	width: 400,
	height: 300,
	closeAction: 'close',
	plain: true,

	items: contactAddForm
});

contactAddWin.show(null);

}

function showContactEditPopupNew() {
	if(sel_Row == null) {
		Ext.MessageBox.alert("No Selected Contact","Please select a Contact to edit");
		return;
	};

	var sCount = 0;
	var sSelectedContactsArrayCheck = sSelectedContacts.split("|");
	for (var x = 0; x < sSelectedContactsArrayCheck.length; x++) {
	    if (sSelectedContactsArrayCheck[x] != "")
	        sCount++;
	}

	if (sCount > 1) {
	    Ext.MessageBox.alert("Edit Contact", "Please select One contact or group to edit");
	    return;
	}
	
	//showContactGroupEditPopupNew
	if (document.getElementById("PrimaryEmail_" + sel_Row).innerHTML.indexOf("contact group") > -1) {

		showContactGroupEditPopupNew();
		return;
	}
    
	//contactEdit_Form = null
	contactEdit_Form = new Ext.FormPanel({
			//		renderTo: 'loginformbox',
			labelWidth: 75,
			//		method: "post",
			//		url:'save-form.php',
			frame: false,
			header: false,
			border: false,
			//title: 'Add Contact',
			bodyStyle: 'padding:5px 5px 0',
			width: 400,
			defaults: { width: 250 },
			defaultType: 'textfield'
		});

		firstNameField2 = new Ext.form.TextField({
			fieldLabel: 'First Name',
			id: 'firstName2',
			name: 'firstName',
			//		allowBlank: false,
			emptyText: '(first name)'
		});

		lastNameField2 = new Ext.form.TextField({
			fieldLabel: 'Last Name',
			id: 'lastName2',
			name: 'lastName',
			//		allowBlank: false,
			emptyText: '(last name)'
		});

		emailAddressField2 = new Ext.form.TextField({
			fieldLabel: 'Email Address',
			id: 'emailAddress2',
			name: 'emailAddress',
			allowBlank: false,
			disabled: true,
			style: { color: '#333333' },
			emptyText: '(email address)',
			blankText: 'Email address is required'
		});

		commentField2 = new Ext.form.TextField({
			fieldLabel: 'Comment',
			id: 'comment2',
			name: 'comment',
			emptyText: '(comment)'
	});

		contactEdit_Form.add(firstNameField2);
		contactEdit_Form.add(lastNameField2);
		contactEdit_Form.add(emailAddressField2);
		contactEdit_Form.add(commentField2);

		var saveBtn = contactEdit_Form.addButton({
			text: 'Save',
			id: 'saveBtn',
			disabled: false,
			listeners: { click: function() {
				contactEdit_Form.getForm().submit({
					url: '/Services/Contact/Update',
					params: { tz: tz, tza: tza, id: contactId },
					action: 'updateContact',
					waitMsg: 'Saving Changes...'
				});
			}
			}
		});

		var cancelBtn = contactEdit_Form.addButton({
			text: 'Cancel',
			id: 'cancelBtn',
			disabled: false,
			listeners: { click: function() {
				contactEdit_Win.close();
			}
			}
		});

		firstNameField2.on('specialkey', function(f, event) {
			if (event.getKey() == event.ENTER) {
				saveBtn.focus();
				saveBtn.fireEvent("click", saveBtn);
			}
		}, this);
		lastNameField2.on('specialkey', function(f, event) {
			if (event.getKey() == event.ENTER) {
				saveBtn.focus();
				saveBtn.fireEvent("click", saveBtn);
			}
		}, this);
		emailAddressField2.on('specialkey', function(f, event) {
			if (event.getKey() == event.ENTER) {
				saveBtn.focus();
				saveBtn.fireEvent("click", saveBtn);
			}
		}, this);
		commentField2.on('specialkey', function(f, event) {
			if (event.getKey() == event.ENTER) {
				saveBtn.focus();
				saveBtn.fireEvent("click", saveBtn);
			}
		}, this);

		contactEdit_Form.on({
			expand: function(form, action) {
				var firstNameField2 = Ext.get('firstName2');
				firstNameField2.focus();
			},
			actioncomplete: function(form, action) {
				var result = action.result;
				contactStore.load();
				//					Ext.quickPopup.msg('Contact Added!', 3, 'The contact "' + result.data + '" was added successfully! You may add another contact or exit.');
				Ext.quickPopup.msg('Contact Saved!', 3, 'The contact "' + result.data + '" was updated successfully!');
				form.reset();
				contactEdit_Win.close();
			},
			actionfailed: function(form, action) {
				if (action.failureType == "server") {
					var result = action.result;
					Ext.quickPopup.msg('Update Contact Failed!', 3, result.data);
				}
				var firstNameField2 = Ext.get('firstName2');
				firstNameField2.focus();
				//					contactAddForm.render();
			}
		});

	contactEdit_Win = new Ext.Window({
		el: 'contactEdit_Window',
		layout: 'fit',
		region: 'center',
		modal: true,
		title: 'Edit Contact',
		width: 400,
		height: 300,
		closeAction: 'destroy',
		plain: true,
		items: contactEdit_Form
	});

	var email_addy = document.getElementById("PrimaryEmail_" + sel_Row).innerHTML;
	email_addy = email_addy.replace("<br>", "");
	email_addy = email_addy.replace("<BR>", "");

	var fName = document.getElementById("FirstName_" + sel_Row).innerHTML;
	fName = fName.replace("<br>", "");
	fName = fName.replace("<BR>", "");

	var lName = document.getElementById("LastName_" + sel_Row).innerHTML;
	lName = lName.replace("<br>", "");
	lName = lName.replace("<BR>", "");

	var sComment = document.getElementById("Comment_" + sel_Row).innerHTML;
	sComment = sComment.replace("<br>", "");
	sComment = sComment.replace("<BR>", ""); 
	
	
	firstNameField2.setValue(fName);
	lastNameField2.setValue(lName);
	emailAddressField2.setValue(email_addy);
	commentField2.setValue(sComment);
	
	contactId = sel_Row;

	sel_Row = null;
	contactEdit_Win.show();
}

function DoSearchForContact(obj) {

	contactSearchForm = new Ext.FormPanel({
		labelWidth: 75,
		frame: false,
		header: false,
		border: false,
		bodyStyle: 'padding:5px 5px 0',
		width: 400,
		defaults: { width: 250 },
		defaultType: 'textfield'
	});

	firstNameField2 = new Ext.form.TextField({
		fieldLabel: 'First Name',
		id: 'firstName2',
		name: 'firstName',
		//		allowBlank: false,
		text: 'Bob',
		emptyText: '(first name)'
	});

	lastNameField2 = new Ext.form.TextField({
		fieldLabel: 'Last Name',
		id: 'lastName2',
		name: 'lastName',
		//		allowBlank: false,
		emptyText: '(last name)'
	});

	emailAddressField2 = new Ext.form.TextField({
		fieldLabel: 'Email Address',
		id: 'emailAddress2',
		name: 'emailAddress',
		allowBlank: false,
		emptyText: '(email address)',
		blankText: 'Email address is required'
	});

	commentField2 = new Ext.form.TextField({
		fieldLabel: 'Comment',
		id: 'comment2',
		name: 'comment',
		emptyText: '(comment)'
	});

	contactSearchForm.add(firstNameField2);
	contactSearchForm.add(lastNameField2);
	contactSearchForm.add(emailAddressField2);
	contactSearchForm.add(commentField2);

	var saveBtn = contactSearchForm.addButton({
		text: 'Search',
		id: 'saveBtn',
		disabled: false,
		listeners: { click: function() {

			var sFirstName = Ext.getCmp("firstName2").getValue();
			var sLastName = Ext.getCmp("lastName2").getValue();
			var sEmail = Ext.getCmp("emailAddress2").getValue();
			var sComment = Ext.getCmp("comment2").getValue();

			var sTest = sFirstName + sLastName + sEmail + sComment;
			sTest = sTest.replace(" ", "");
			if (sTest == "") {
				Ext.MessageBox.alert("Error", "Please enter Search Criteria");
				return;
			}

			var srchUrl = "/Contacts?SearchParms=FirstName:" + sFirstName + "|LastName:" + sLastName + "|EmailAddress:" + sEmail + "|Comment:" + sComment;
			window.location.href = srchUrl;
		}
		}
	});

	var cancelBtn = contactSearchForm.addButton({
		text: 'Cancel',
		id: 'cancelBtn',
		disabled: false,
		listeners: { click: function() {
			contactSearchForm.close();
		}
		}
	});

	firstNameField2.on('specialkey', function(f, event) {
		if (event.getKey() == event.ENTER) {
			saveBtn.focus();
			saveBtn.fireEvent("click", saveBtn);
		}
	}, this);
	lastNameField2.on('specialkey', function(f, event) {
		if (event.getKey() == event.ENTER) {
			saveBtn.focus();
			saveBtn.fireEvent("click", saveBtn);
		}
	}, this);
	emailAddressField2.on('specialkey', function(f, event) {
		if (event.getKey() == event.ENTER) {
			saveBtn.focus();
			saveBtn.fireEvent("click", saveBtn);
		}
	}, this);
	commentField2.on('specialkey', function(f, event) {
		if (event.getKey() == event.ENTER) {
			saveBtn.focus();
			saveBtn.fireEvent("click", saveBtn);
		}
	}, this);

	contactSearchForm.on({
		expand: function(form, action) {
			var firstNameField2 = Ext.get('firstName2');
			firstNameField2.focus();
		}
	});

	contactSearchForm = new Ext.Window({
		el: 'contactEdit_Window',
		layout: 'fit',
		region: 'center',
		modal: true,
		title: 'Search Contacts',
		width: 400,
		height: 300,
		closeAction: 'close',
		plain: true,

		items: contactSearchForm
	});
	
	contactSearchForm.show(null);
	

}