var carrier;
var DID = '17608600220'
var programmed_status;
var pilotNumber;
var programNumber;
var unprogramNumber;
var element;
var emailPattern = new RegExp(/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i);
var stripPhoneno = new RegExp(/\(|\)|-|\s/g);
var phonePattern = new RegExp(/^(1|\+1)?\d{10}\b/);
jQuery(function($){
	$("#confirmationcode").mask("9999",{placeholder:""});
	$("#pin").mask("9999",{placeholder:""});
	$("#phoneno, input[name='phoneno']").mask("(999) 999 - 9999",{placeholder:"  "});
	//$("#pilotNumber").mask("(999) 999 - 9999",{placeholder:"  "});
});

$(document).ready(function() {
});

jQuery.fn.extend({
	alert: function(message) {
		if(message)
			this.html(message);
		this.fadeIn('slow');
		setTimeout("$('#"+this.attr('id')+"').fadeOut('slow')",2000);
	},
	toggleUserOption: function() {
		switch(this.attr('id')) {
			case 'vmail_notify_via_sms':
			case 'vmail_attach_via_email':
				$('#voicemailAlertChange').alert();
			break;
			case 'vmail_notify_via_email':
				if($(this).attr('checked'))
					$('#vmail_attach_via_email_container').css('visibility','visible');
				else
					$('#vmail_attach_via_email_container').css('visibility','hidden');
				$('#voicemailAlertChange').alert();
			break;
			case 'cnam_via_sms':
			case 'transcriptions_via_email':
			case 'transcriptions_via_sms':
				$('#notificationsChange').alert();
			break;
			case 'transcribe_voicemails':
				$('#transcriptionsChange').alert();
			break;
		}

		$.post('/user/update',{field:this.attr('id'),value:this.attr('checked')});
	},
	updateField: function(user_phoneno) {
		switch(this.attr('id')) {
			case 'pin':
				if(this.val().length != 4) {
					digitsNeeded = 4 - this.val().length;
					append = (digitsNeeded == 1) ? '' : 's';
					$('#pinError').html(digitsNeeded+' more digit'+append+' required!');
					$('#pinError').css('display','inline');
					return;
				}
			break;
			case 'email':
				if(!emailPattern.test(this.val())) {
					$('#emailError').html('Invalid email!');
					$('#emailError').css('display','inline');
					return;
				}
			break;
		}
		$('#'+this.attr('id')+'Edit').css('display','none');
		$('#'+this.attr('id')+'View').css('display','block');

		var elementId = this.attr('id');

		$.post('/user/update',{field:this.attr('id'),value:this.val()},function(data) {
			$('#'+elementId+'Display').html(data);
			if(elementId == 'carrier')
				$('#currentCarrierDisplay').html($('#'+elementId+'Display').html());
		},'text');

		programmed_status = 'Unprogrammed!';
		pilotNumber = 'Immediate Action Required! <input type="button" value="fix" onClick="animatedcollapse.show(\'pilot2\');" />';
		switch(this.attr('id')) {
			case 'carrier':
				programCodes(this.val(),true,user_phoneno);
				$('#currentCarrier').val(this.val());
				$('#programmed_statusDisplay').css('color','#FF0000');
				$('#programmedIt').css('display','block');
			break;
			case 'email':
				$('#personalinfoChange').alert();
			break;
			case 'pilotNumber':
				if($(this).validate('notEmpty')) {
					handleNotifications(-1);
					$('#pilot2').fadeOut();
				}
				programCodes($('#currentCarrier').val(),false,user_phoneno);
				$('#programmed_statusDisplay').css('color','#FF0000');
				$('#programmedIt').css('display','block');
			break;
			case 'pin':
			case 'tz':
				$('#accountsettingsChange').alert();
			break;
			case 'programmed_status':
				handleNotifications(-1);
				pilotNumber = $('#pilotNumberDisplay').html();
				programNumber = $('#programNumber').html();
				programmed_status = 'Programmed';
				unprogramNumber = $('#unprogramNumber').html();
				$('#programmed_statusDisplay').css('color','#006600');
			break;
		}
		$('#pilotNumberDisplay').html(pilotNumber);
		$('#programNumber').html(programNumber);
		$('#unprogramNumber').html(unprogramNumber);
		$('#programmed_statusDisplay').html(programmed_status);
	},
	// User Field Editor
	UFE : function() {
		fieldID = this.attr('id');
		return {
			cancel : function() {
				$('#'+fieldID+'Edit').css('display','none');
				$('#'+fieldID+'View').css('display','block');
			},
			clear : function() {
				$('#'+fieldID).css('borderColor','#090');
				$('#'+fieldID+'Container').css('color','#CCC');
				$('#'+fieldID+'Status').css('backgroundPosition','0px 200px');
				$('#'+fieldID+'Error').css('display','none');
			},
			edit : function() {
				$('#'+fieldID+'Edit').css('display','block');
				$('#'+fieldID+'View').css('display','none');
			},
			update : function(user_phoneno) {
				// user_phoneno is only required when selecting verizon as a carrier
				$('#'+fieldID).updateField(user_phoneno);
			}
		};
	},
	validate: function(validator) {
		switch(validator) {
			case 'email':
				var isValid = emailPattern.test(this.val());

				$('#'+this.attr('id')).css('borderColor','#CCC');
				$('#'+this.attr('id')).validate('notEmpty');

				if($('#'+this.attr('id')+'Container').size()) {
					bgPos = (isValid) ? '-95px' : '5px';
					display = (isValid) ? 'none' : 'block';
					color = (isValid) ? 'CCC' : '900';
					updateStatus(this.attr('id'),bgPos,display,color);
				}

				return isValid;
			break;
			case 'notEmpty':
				var isValid = (this.val()) ? true : false;

				$('#'+this.attr('id')).css('borderColor','#CCC');

				if($('#'+this.attr('id')+'Container').size()) {
					bgPos = (isValid) ? '-95px' : '5px';
					display = (isValid) ? 'none' : 'block';
					color = (isValid) ? 'CCC' : '900';
					updateStatus(this.attr('id'),bgPos,display,color);
				}

				return isValid;
			break;
			case 'phoneno':
				setTimeout(function(element) {
					$(element).validate('notEmpty');
				},200,this);
			break;
		}
	}
});

/** DELETE CALL LOGS **/
var toggleStatus = false;
var toggleAll = function(elements) {
	toggleStatus = !toggleStatus;
	var newToggle = (toggleStatus) ? 'on' : 'off';

	for(key in elements) {
		$('#delete_'+key).val(newToggle);
		$('#deleteButton_'+key).attr('checked',toggleStatus);
	}
	var text = (toggleStatus) ? 'Unselect' : 'Select All';
	$('#toggleAllTop').html(text);
	$('#toggleAllBottom').html(text);
}

var toggleDeleteRequest = function(delete_id) {
	var newValue = ($('#'+delete_id).val() == 'off') ? 'on' : 'off';
	$('#'+delete_id).val(newValue);
}

var deleteSelected = function(zendAction) {
	var filter = function() {
		// Only return if the associated form is relevant
		return this.form.id == 'deleteRequests';
	}

	var url = '/controlpanel/'+zendAction+'?actionRequest=delete&fields=';
	var requested = 0;

	$.each($(":input[type='hidden']").filter(filter),function() {
		if($(this).val() == 'on') {
			url += $(this).attr('name')+',';
			requested++;
		}
	});

	if(requested) {
		var plural = (requested == 1) ? '' : 's';
		var confirmation = confirm('Are you sure you would like to delete\n'
			+ 'the ' + requested + ' selected call log'+plural+'? Please note that any data\n'
			+ 'associated with selected entries will also be deleted!');
		if(confirmation)
			window.location = url;
		else {
			toggleStatus = true;
			toggleAll(elements);
		}
	} else
		alert('You must select at least one call log!');
}
/** DELETE CALL LOGS END **/

/** AJAX FUNCTIONS **/
function selectToggleAJAX(fieldID,carrierID) {
	switch(fieldID) {
		case 'recordcalls':
			if($('#recordcalls').val() == 1) {
				if(carrierID == 11) {
					alert('Please note that, due to the limitations of some Verizon phones, turning on call recording may prevent us from being able to provide voicemail transcriptions.');
				}
				$('#recordingsChange').alert();
				$('#recordingpromptdisplay').css('display','block');
			} else {
				$('#recordingsChange').fadeIn();
				$('#recordingpromptdisplay').css('display','none');
				setTimeout("$('#recordingsChange').fadeOut();",2000);
			}

			$.post(location.protocol+'//'+location.host+'/user/update/',{field:'recordings',value:$("#recordcalls").val()});
		break;
		case 'recordingprompt':
			if($('#recordingprompt').val() == '0') {
				alert('You have chosen to delete the warning message that informs callers that their call will be recorded.  Do you really want to do this?  TrapCall plays this warning in order to protect you from accidentally committing a crime.  Even if your state allows you to record a call without telling the caller, recording a call without telling the caller is a crime in at least a dozen states.  Some of your callers may be in those states.  We strongly urge you not to turn off this feature.  If you still want to turn the caller warning feature off enter your PIN in the following screen.');
				var confirmation = prompt('Please type your PIN if you accept the previous terms','')
				if($('#pinDisplay').html() == confirmation) {
					$('#recordingsChange').alert();
					$('#recordingprompt').attr('selectedIndex',1);
					$('#callersAlerted').css('display','none');
					$('#callersNotAlerted').css('display','block');
				} else if(!confirmation) {
					$('#recordingprompt').attr('selectedIndex',0);
					$('#callersAlerted').css('display','block');
					$('#callersNotAlerted').css('display','none');
				} else if($('#pinDisplay').html() != confirmation) {
					$('#recordingprompt').attr('selectedIndex',0);
					$('#callersAlerted').css('display','block');
					$('#callersNotAlerted').css('display','none');
					alert('The pin you entered is invalid');
				}
			} else {
				$('#recordingsChange').alert();
				$('#recordingprompt').attr('selectedIndex',0);
				$('#callersAlerted').css('display','block');
				$('#callersNotAlerted').css('display','none');
			}

			$.post(location.protocol+'//'+location.host+'/user/update/',{field:'recordingsprompt',value:$("#recordingprompt").val()});
		break;
	}
}

function programCodes(carrierID,display,user_phoneno) {
	switch(carrierID) {
		case '2': case '10':
			programNumber = '*004*'+DID+'*11#';
			unprogramNumber = '##004#';

			if(carrierID == '10') {
				handleNotifications(1);
				pilotNumber = '+18056377243';
				$('#pilot2').fadeOut();
			} else if((carrierID == '2') && (display)) {
				handleNotifications(2);
				// AT&T PILOT FORWARD
				$('#pilot2').fadeIn();
			}
		break;
		case '11':
			programNumber = '*7'+DID;
			unprogramNumber = '*73';

			pilotNumber = user_phoneno;
			$('#pilot2').fadeOut();
		break;
		default:
			pilotNumber = 'Unsupported Carrier';
		break;
	}
}

function resendInvitation(to,from,message) {
	$('#mailTo').val() = to;
	sendInvitation(to,from,message,1);
}

function sendInvitation(to,from,message,resend) {
	if(!resend)
		resend = null;

	if(emailInvitation(to,from,'Trapcall Invitation!',message,resend) == false) {
		$('#emailStatusBad').css('display','block');
		$('#emailStatusGood').css('display','none');
	} else {
		if($('#remainingInvites') && !resend) {
			var remainingInvites = parseFloat($('#remainingInvites').html());
			if(remainingInvites >= 1) {
				remainingInvites--;
				$('#remainingInvites').html(remainingInvites);
				$('#remainingInvitesNav').html(remainingInvites);
			}
		}
		$('#mailTo').focus();
		if($('#emailStatusGood')) {
			if(!resend) {
				var newInvite = '<table class="invitation" cellspacing="0">'
					+ '<tr>'
					+ '<td class="display">'
					+ to + '<font class="sent inviteStatus">sent</font>'
					+ '</td>'
					+ '<td class="resend">'
					+ '<input type="button" value="resend" onclick="resendInvitation(\''+to+'\',from,$(\'#message\').val()+referrerLink);" />'
					+ '</td>'
					+ '</tr>'
					+ '</table>';
				$('#invitesSent').html(newInvite+$('#invitesSent').html());
			}
			$('#mailTo').val('');
			$('#emailStatusGood').alert();
		}
		$('#emailStatusBad').css('display','none');
	}
}

function resendConfirmation(phoneno){
	if(!phonePattern.test(phoneno))
		return false;
	
	$.post("/user/resendconfirmation",{phoneno:phoneno});
	alert('Voicemail Resent! Please wait...');
	return true;
}

function emailInvitation(to, from, subject, message,extraParameter){
	to = to.toLowerCase();
	from = from.toLowerCase();

	if((!emailPattern.test(to)) || (!emailPattern.test(from)))
		return false;
	
	if(to == from)
		return false;


	$.post('/user/sendinvitation',{
		email: to,
		emailFrom: from,
		subject: subject,
		message: message,
		field:extraParameter
	});

	return true;
}

function sendEmail(to, from, subject, message) {
	to = to.toLowerCase();
	from = from.toLowerCase();

	if((!emailPattern.test(to)) || (!emailPattern.test(from)))
		return false;
	
	if(to == from)
		return false;
	
	$.post('/user/sendemail',{
		email: to,
		emailFrom: from,
		subject: subject,
		message: message
	});

	return false;
}

function sendSMS(phoneno) {
}

/** AJAX FUNCTIONS END **/

/** MEDIA PLAYER MODULE ENHANCEMENTS **/
var teltechAudioPlayer = function() {
	var current;
	var prefix = 'TeltechPlayer';

	var getPrefix = function() {
		return prefix;
	}

	return {
		embed : function(id, type) {
			AudioPlayer.embed(getPrefix()+'_'+id, {
				soundFile : "/controlpanel/play/"+id+"/"+type,
				animation : 'no',
				noinfo : 'yes',
				titles : type+' #'+id
			});
		},
		open : function(id, type) {
			teltechAudioPlayer.embed(id, type);
			setTimeout("AudioPlayer.open('"+getPrefix()+"_"+id+"')",1500);
		}
	}
}();

/** MEDIA PLAYER MODULE ENHANCEMENTS END **/

/** FORM VALIDATIONS 2.0 **/
var checkForm = function(form) {
	switch(form) {
		case 'buypage':
			if($('#BI_Firstname').validate('notEmpty')
				&& $('#BI_Lastname').validate('notEmpty')
				&& $('#BI_Address').validate('notEmpty')
				&& $('#BI_City').validate('notEmpty')
				&& $('#BI_State').validate('notEmpty')
				&& $('#BI_Zip').validate('notEmpty')
				&& $('#BI_Country').validate('notEmpty')
				&& $('#CI_CCNumber').validate('notEmpty')
				&& $('#CI_CCV').validate('notEmpty'))
			return true;
		break;
		case 'login':
			if($('#phoneno').validate('notEmpty') && $('#pin').validate('notEmpty'))
				return true;
		break;
		case 'signup2':
			if($('#signup #phoneno').validate('notEmpty')
				&& $('#carrier').validate('notEmpty')
				&& $('#timezone').validate('notEmpty')
				&& checkEmail(document.getElementById('email'))
				&& checkChecked(document.getElementById('agree'))) {

				$(document.body).css('cursor','progress');
				$('#submitForm').css('cursor','default');
				$('#submitForm').attr('disabled',true);
				return true;
			} else
				return false;
		break;
		case 'signup3':
			if($('#firstname').validate('notEmpty')
				&& $('#lastname').validate('notEmpty')
				&& $('#confirmationcode').validate('notEmpty'))
				return true;
			else
				return false;
		break;
		case 'support':
			if($('#name').validate('notEmpty')
				&& $('#phoneno').validate('notEmpty')
				&& $('#phonemodel').validate('notEmpty')
				&& (checkEmail(document.getElementById('email')))
				&& $('#subject').validate('notEmpty')
				&& $('#message').validate('notEmpty')) {

				// SUPPORT FORM REQUIRES EXTRA FUNCTIONALITY
				var message = $('#name').val()+' "'+$('#phoneno').val()+'"<br />'
					+ 'Phone Model :: '+$('#phonemodel').val()+' <br /><br />'
					+ $('#message').val()+'<br /><br />'
					+ 'IP Address :: '+$('#visitorIP').val()+' <br />'
					+ 'User Agent :: '+$('#visitorAgent').val()+' <br />';
				sendEmail('Support@TrapCall.com', $('#email').val(), 'Trapcall Support - '+$('#subject').val(), message);
				$('#supportForm').css('display','none');
				$('#supportSent').css('display','block');
			}
		break;
	}
	return false;
}

var checkChecked = function(element) {
	var id = element.id;

	bgPos = (element.checked) ? '-95px' : '5px';
	display = (element.checked) ? 'none' : 'block';
	color = (element.checked) ? 'CCC' : '900';
	updateStatus(id,bgPos,display,color);
	
	return (element.checked) ? true : false;
}

var checkEmail = function(element) {
	var id = element.id;
	var isValid = emailPattern.test(element.value);

	$('#'+id).css('borderColor','#CCC');
	$('#'+id).validate('notEmpty');

	bgPos = (isValid) ? '-95px' : '5px';
	display = (isValid) ? 'none' : 'block';
	color = (isValid) ? 'CCC' : '900';
	updateStatus(id,bgPos,display,color);

	return isValid;
}

var checkPhoneno = function(fieldID) {
	// This allows to check other E164 fields like Pilot Number
	if(!fieldID)
		fieldID = 'phoneno';

	setTimeout("$('#"+fieldID+"').validate('notEmpty');",200);
}

var updateStatus = function(id, bgPos, display, color) {
	$('#'+id+'Status').css('backgroundPosition','0px '+bgPos);
	$('#'+id+'Error').css('display',display);
	$('#'+id).css('borderColor','#'+color);
}
/** END FORM VALIDATIONS 2.0 **/

var reminderScreen = function() {
	$('#loginStatus').html('Forgot Pin');
	$('#loginWindow').css('display','none');
	$('#reminderWindow').css('display','block');
	$('#error').css('display','none');
}

var loginScreen = function() {
	$('#loginStatus').html('Log In');
	$('#reminderWindow').css('display','none');
	$('#loginWindow').css('display','block');
}

var sendPin = function() {
	var phoneno = $('#phoneno').val();
	phoneno = phoneno.replace(stripPhoneno,'');
	if(phonePattern.test(phoneno)) {
		$.post('/user/ajax',{
			request: 'resetPin',
			phoneno: phoneno
		},function(xml) {

			if($('error',xml).text()) {
				$('#error').alert($('error',xml).text());
				return false;
			}
			// Restore login screen
			loginScreen();

			// Remove errors and display success message
			$('#error').css('display','none');
			$('#success').alert('We have sent an email and a SMS with your PIN!');

			// Erase any inputted pin and return focus to the field
			$('#pin').val('');
			$('#pin').focus();
		});
	} else {
		// Restore reminder screen if unset
		reminderScreen();

		// Notify user that phone number was unable to receive a message
		$('#error').alert('Could not send PIN!');
	}

	// Remove the waiting icon
	$('#sendingPin').css('display','none');
}

function handleNotifications(tick) {
	/**
	 * This method basically handles the view of the user notifications.
	 * A negative tick means a positive user reaction. Strange if you
	 * think of it like that. However take into consideration that if you
	 * give the total errors a negative tick it will reduce the amount
	 * of errors. You may also add errors to the counter by giving a positive
	 * tick.
	 */
	var newValue = parseFloat($('#notificationsRemaining').html())+parseFloat(tick);
	$('#notificationsRemaining').html(newValue);
	var display = (newValue > 0) ? 'block' : 'none';
	$('#notificationsDisplay').css('display',display);
}

function submitDeactivate() {
	var confirmation = confirm('Are you sure you would like to immediately downgrade?');
	if(confirmation) {
		$('#deactivateRequest').css('display','none');
		$('#deactivateSubmit').css('display','block');
		$.post('/user/deactivate');
	}
	return confirmation;
}
