var widget = {
	verification_number : 0,
	getUserDetails : function () {
		var isValid = false;
		var url = '/widget/UserDetails';
		var val = "";
		var idx2;
		var nodes = $('#idx').val().split(',');
		var userId = 0;
		if($('#phone').length > 0) {
			if($('#phone').val().length > 9 && widget.validatePhone($('#phone').val())){
				type = "phone";
				val = $('#phone').val();
				isValid = true;
			}
		}
		if($('#email').length > 0) {
			if(!isValid && widget.validateEmail($('#email').val())){
				type = "email";
				val = $('#email').val();
				isValid = true;
			}
		}
		if($('#landline').length > 0) {
			if($('#landline').val().length > 9 && widget.validatePhone($('#landline').val())){
				type = "landline";
				val = $('#landline').val();
				isValid = true;
			}
		}
		sList = $('#idx').val();
		if(isValid) {
			var id = 0;
			$.ajax({
				url: url,
				data: { oaddress : val,
						type: type },
				type: 'POST',
				dataType: 'json',
				beforeSend: function () { showProcessing(); },
				success: function (response) {
					user = response.user;
					if(user['id'] && user['id'] != "") {
						id = user['id'];
					}
					if($('#fname').length > 0 && $('#fname').val() == "") {
						$('#fname').val(user['fname']);
					}
					if($('#lname').length > 0 && $('#lname').val() == "") {
						$('#lname').val(user['lname']);
					}
					if($('#email').length > 0 && $("#email").val() == "") {
						if(user['email'] != null && user['email'].length > 2) {
							$('#email').val(user['email']);
						}
					}
					if($('#phone').length > 0) {
						$('#phone').val(user['phone']);
					}
				},
				complete: function () {
					if(id != 0 && sList.length > 1) {
						widget.getUserSubscriptions(id, sList);
					}
					closeProcessing();
				}
			});
		}
	},
	getUserSubscriptions : function(id,list) {
		if(id != '' && id > 0) {
			url = "/widget/UserSubscriptions";
			$.ajax({
				url: url,
				data: { userId : id,
						sList : list },
				type: 'POST',
				dataType: 'html',
				beforeSend: function () { showProcessing(); },
				success: function (response) {
					$('#subscriptions').html(response);
				},
				complete: function () { closeProcessing(); }
			});
		}
	},
	inArray : function(obj, value) {
		for(i = 0; i < obj.length; i++) {
			if(value == obj[i]) {
				return true;
			}
		}
	},
	verifyPhone : function (action) {
		$("#validate_button").attr('disabled', true);
		$("#subscribe_button").hide();
		var idx = $('#idx').val();
		var idx2 = "";
		var list = "";
		var phone = $('#phone').length > 0 ? $('#phone').val() : '';
		var landline = $('#landline').length > 0 ? $('#landline').val() : '';
		var email = $('#email').length > 0 ? $('#email').val() : '';
		var keyword = $('#keyword').length > 0 ? $('#keyword').val() : '';
        var customField = $('#customField').length > 0 ? $('#customField').val() : '';
        var privateCode = $('#privateCode').length > 0 ? $('#privateCode').val() : '';

		if(phone == '' && landline == '' && email == '') {
			alert("You must provide a contact number or email.");
			$("#validate_button").attr('disabled', '');
			return false;
		}

		if($('#idx2').length > 0) {
			idx2 = $('#idx2').val();
		}

		if(action == 1) {
			nlist = idx.split(',');
			for(i = 0; i < nlist.length ; i++) {
				str = '#node_' + nlist[i];
				if($(str).length > 0 && $(str).attr('checked')) {
					list += "," + $(str).val();
				}
			}
		} else if(action == 0) {
			tmp = idx2.split(':');
			nlist = tmp[1].split(',');
			for(i=0; i< nlist.length; i++) {
				str = '#sub_'+nlist[i];
				if($(str).length > 0 && $(str).attr('checked')) {
					list += "," + $(str).val();
				}
			}
		}
		list = list.substring(1, list.length);

		if(list == '' && privateCode == '') {
			alert("Please select a group to subscribe to.");
			$("#validate_button").attr('disabled', '');
			return false;
		}

		//assumption of the shortest phone number we'll receive
		if($('#phone').val().length > 7) {
			var url = '/widget/verify';
			$.ajax({
				url: url,
				data: { phone : phone,
						nodes : list,
						action : action,
						keyword : keyword,
                        custom_field : customField,
                        privateCode : privateCode },
				type: 'POST',
				dataType: 'json',
				beforeSend: function () { showProcessing(); },
				success: function (response) {
					if(response.result) {
						if(response.reserved) {
							$("#subscribe_button").show();
							$("#validate_button").hide();
							$('#verficiation_reserve_label').hide();
							$('#verficiation_number_label').hide();
							$('#verficiation_number_input').hide();
							alert(response.message);
						} else if(!response.reserved && response.verification_number != '') {
							var verification_number = response.verification_number;
							widget.verification_number = verification_number;
							$("#subscribe_button").show();
							$("#validate_button").hide();
							$('#verficiation_reserve_label').hide();
							$('#verficiation_number_label').show();
							$('#verficiation_number_input').show();
							alert(response.message);
						} else {
							widget.doSubscription(action);
						}
					} else {
						alert(response.error_message);
					}
				},
				complete: function () {
					$("#validate_button").attr('disabled', false);
					closeProcessing();
				}
			});
		} else {
			widget.doSubscription(action);
		}
	},
	doSubscription : function(action) {
		$("#subscribe_button").attr('disabled', true);
		var idx = $('#idx').val();
		var idx2 = "";
		var list = "";
		if($('#idx2').length > 0) {
			idx2 = $('#idx2').val();
		}
		var list = "";
		if(action == 1) {
			nlist = idx.split(',');
			for(i = 0; i < nlist.length ; i++) {
				str = '#node_'+nlist[i];
				if($(str).length > 0 && $(str).attr('checked')) {
					list += "," + $(str).val();
				}
			}
		}
		if(action == 0) {
			tmp = idx2.split(':');
			nlist = tmp[1].split(',');
			for(i=0; i< nlist.length; i++) {
				str = '#sub_'+nlist[i];
				if($(str).length > 0 && $(str).attr('checked')) {
					list += "," + $(str).val();
				}
			}
		}
		list = list.substring(1, list.length);
		var url = '/widget/Subscribe';
		var fname = $('#fname').length > 0 ? $('#fname').val() : '';
		var lname = $('#lname').length > 0 ? $('#lname').val() : '';
		var phone = $('#phone').length > 0 ? $('#phone').val() : '';
		var phoneVisible = $('#phone').length > 0 ? true : false;
		var landline = $('#landline').length > 0 ? $('#landline').val() : '';
		var landlineVisible = $('#landline').length > 0 ? true : false;
		var email = $('#email').length > 0 ? $('#email').val() : '';
		var emailVisible = $('#email').length > 0 ? true : false;
		var customField = $('#customField').length > 0 ? $('#customField').val() : '';
		var privateCode = $('#privateCode').length > 0 ? $('#privateCode').val() : '';
		var keyword = $('#keyword').length > 0 ? $('#keyword').val() : '';
		var verifyEntered = $('#verify_entered').length > 0 ? $('#verify_entered').val() : '';
		var verifyEnteredVisible = $('#verify_entered').length > 0 ? true : false;
		var message = "";
		var messagePrefix = "";
		var messageBody = "";
		var messageSuffix = "";
		var fullMessage =  "";

		if(phoneVisible && phone == "") {
			if(emailVisible && email == "") {
				if(landlineVisible && landline == "") {
					alert("Please enter a valid mobile number, email, or landline number.");
					return;
				}
			} else {
				if(emailVisible &&email.length <= 3 && !widget.validateEmail(email)) {
					alert("Please enter a valid email.");
					return;
				}
			}
		} else if (phoneVisible && phone != "") {
			if(phone.length <= 10 && !widget.validatePhone(phone)) {
				alert("Please enter a valid mobile number");
				return;
			}
		} else if(emailVisible && email == "") {
			if(landlineVisible && landline == "") {
				alert("Please enter a valid email or landline.");
				return;
			}
		} else if (emailVisible && email != "") {
			if(email.length <= 3 && !widget.validateEmail(email)) {
				alert("Please enter a valid email.");
				return;
			}
		} else if(verifyEnteredVisible && verifyEntered == "") {
			alert("Please enter a the verification number the was sent to you via sms.");
			return;
		} else if (verifyEnteredVisible && verifyEntered != "") {
			if(verifyEntered.length != 7) {
				alert("The verification number is a seven digit number.  Please enter a valid verification number.");
				return;
			}
		} else if (landlineVisible && landline == "") {
			alert("Please enter a valid landline.");
			return;
		} else {
			alert("Please Enter Valid Contact Information");
			return;
		}

		$.ajax({
			url: url,
			data: { phone : phone,
					email : email,
					landline : landline,
					fname : fname,
					lname : lname,
					nodes : list,
					action : action,
					customField : customField,
					privateCode : privateCode,
					keyword : keyword,
					vn : widget.verification_number,
					entered_number : verifyEntered },
			type: 'POST',
			dataType: 'json',
			beforeSend: function () { showProcessing(); },
			success: function (response) {
				result = response.result;
				group = response.group;
				code = response.code;
				stopMessage = response.stopMessage;
				helpMessage = response.helpMessage;

				if(result == 'true') {
					alert("Subscription(s) created.");
					widget.getUserDetails();
					$('#verficiation_reserve_label').hide();
					$('#verficiation_number_label').hide();
					$('#verficiation_number_input').hide();
				} else {
					alert("Unable to create subscription(s)\n" + response.errorMsg);
				}
			},
			complete: function () {
				$("#subscribe_button").attr('disabled', false);
				closeProcessing();
			}
		});
	},
	validateEmail : function(str) {
		if(str.match(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i) ) {
			return true;
		} else {
			return false;
		}
	},
	validatePhone : function(str) {
		if(str.replace(/[^0-9]/g, '').length == 10) {
			return true;
		} else {
			return false;
		}
	},
	getAddressType : function() {
		var type = "";
		var phone = $('#phone').val();
		var email = $('#email').val();
		if(widget.validateEmail(email)) {
			type = 'email';
		} else {
			var oaddress = emailPhone.replace(/[^0-9]/g,'');
			if(oaddress.length == 10) {
				type = 'phone';
			}
		}
		return type;
	},
	toggleView : function() {
		if($('#sAnchor').html() == 'Unsubscribe') {
			$('#subscribe').show();
			if($('#idx2').length > 0) {
				vars = $('#idx2').val().split(':');
				widget.getUserDetails(vars[0], $('#idx').val());
			}
			$('#subscriptions').show();
			$('#sAnchor').html('Subscribe');
		} else {
			$('#subscriptions').hide();
			$('#subscribe').show();
			$('#sAnchor').html('Unsubscribe');
		}
	}
};
