var carrier,
	DID = '17608600220',
	programmed_status,
	pilotNumber,
	programNumber,
	unprogramNumber,
	element,
	emailPattern = new RegExp(/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i),
	stripPhoneno = new RegExp(/\(|\)|-|\s/g),
	phonePattern = new RegExp(/^(1|\+1)?\d{10}\b/),
	pageTracker;
	
var OSName="Unknown OS";
if (navigator.appVersion.indexOf("Win")!=-1) OSName="Windows";
if (navigator.appVersion.indexOf("Mac")!=-1) OSName="MacOS";
if (navigator.appVersion.indexOf("X11")!=-1) OSName="UNIX";
if (navigator.appVersion.indexOf("Linux")!=-1) OSName="Linux";


var createJS = function(src) {
	return $(document.createElement('script')).attr('src', src).attr('type', 'text/javascript');
}

var loadLiveChat = function() {
	if(typeof bt_showChatHTML == 'undefined')
		setTimeout('loadLiveChat();',400);
	else if(new String(bt_showChatHTML).search(/document\.write\(bt_available\)/) != -1) {
		$('.livechat_link').show();
		$('#bt_LIVECHAT').html('Live Chat!');
	}
}

var load_activalive = setInterval(function() {
	if(!$('[id^="__ALC_BADGE"]:visible').size())
		return;

	$('.livechat_link').show();

	clearInterval(load_activalive);
}, 500);

var loadGoogleAnalytics = function() {
	if(typeof _gat == 'undefined')
		setTimeout('loadGoogleAnalytics();',400);
	else {
		pageTracker = _gat._getTracker("<?= Zend_Registry::get('config')->google_tracker_key ?>");
		pageTracker._trackPageview();
	}
}

$(function() {
	loadGoogleAnalytics();

	$('head').append(createJS((('https:'==document.location.protocol)?'https:':'http:')+'//cbi.boldchat.com/aid/930308239417203001/bc.cbhs?wdid=4276441152216771569'));

	// LOAD LIVE CHAT WHEN AVAILABLE
	loadLiveChat();

	var a2a_linkname="TrapCall.com";
	var a2a_linkurl="http://www.trapcall.com";

	if(document.location.protocol != 'https:')
		$('head').append(createJS('http://static.addtoany.com/menu/page.js'));

	$("#confirmationcode").mask("9999",{placeholder:""});
	$("#pin").mask("9999",{placeholder:""});
	$("#phoneno, input[name='phoneno']").mask("(999) 999 - 9999",{placeholder:"  "});

	$('#login_required').dialog({
		autoOpen	: false,
		draggable	: false,
		modal		: true,
		resizable	: false
	});

	/**
	 * Nickname Caller
	 *
	 * - Bind the nickname caller div to a dialog box, and handle
	 * - the submit event of the form. Ensure that the ExtJS data store
	 * - is only refreshed if it exists are a global variable.
	 */
	$('#nickname_caller').dialog({
		autoOpen	: false,
		buttons		: {
			'Nickname'	: function() {
				$(this).submit();
			}
		},
		modal		: true,
		resizable	: false,
		width		: 300
	}).submit(function(event) {
		event.preventDefault();

		var dialog = this;

		nickname_caller($(this).attr('caller_id'), $('[name="nickname"]', this).val(), function(response) {
			if(typeof store == 'object')
				store.reload();

			$(dialog).dialog('close');
		});
	});

	/**
	 * TelTech Inline Labels
	 *
	 * - Bind the relative events for our labels. This includes
	 * - focus, blur, keyup, and keypress events.
	 */
	$('label.teltech_inline input').focus(function(event) {
		if($(this).val())
			$('span', $(this).parents('.teltech_inline')).stop().fadeTo('normal', 0);
		else
			$('span', $(this).parents('.teltech_inline')).stop().fadeTo('normal', .4);
	});

	$('label.teltech_inline input').blur(function(event) {
		var parent_label = $(this).parents('.teltech_inline');

		if($(this).val())
			return $('span', parent_label).stop().fadeTo('fast', 0);

		$('span', parent_label).stop().fadeTo('normal', 1);
	});

	$('label.teltech_inline input').keyup(function(event) {
    		if(!$(this).val())
    			return $('span', $(this).parents('.teltech_inline')).stop().fadeTo('fast', 0.5);
    	}).keypress(function(event) {
    		$('span', $(this).parents('.teltech_inline')).stop().fadeTo('fast', 0);
    	});
    
    $('tbody tr').live('click', function(event) {
        if(event.target.tagName == 'INPUT')
            return true;
            
        var checkbox = $(':checkbox', this);
        
        checkbox.attr('checked', !checkbox.attr('checked'));
    });
    
    $('thead :checkbox').live('change', function() {
        $('tbody :checkbox', $(this).parents('table:first')).attr('checked', $(this).attr('checked'));
    });

	/**
	 * Quick Dialog Trigger
	 *
	 * - If a link has the dialog class and a dialog
	 * - is discovered by it's href, open the associated
	 * - dialog.
	 */
	$('a.dialog').live('click', function(event) {
		event.preventDefault();
		
		var identifier = $.browser.msie ? '#' + $(this).attr('href').split('#')[1] : $(this).attr('href');
		
		if($(identifier).size())
			$(identifier).dialog('open');
	});

	/**
	 * Centered Dialog
	 *
	 * - I think this will need a little more attention for larger 
	 * - pages, however, this currently attaches the dialog to the 
	 * - center of the page, instead of the window.
	 */
	$('*').bind('dialogopen', function(event, ui) {
		$('object, .object_container').hide();
		if(!$('#page').size())
			return true;

		if($(window).height() > $('#page').height())
			$(this).dialog('option', 'position', ['center', Math.round(($('#page').height() / 2) - ($(this).parents('.ui-dialog:first').height() / 2))]);
	}).bind('dialogclose', function(event, ui) {
		$('object, .object_container').show();
	});

	$('.nickname_caller').live('click', function(event) {
		$('#nickname_caller').attr('caller_id', $(this).attr('caller_id'));
	});

	$('.livechat_link').live('click', function(event) {
		event.preventDefault();

		$('#bt_LIVECHAT, a[id^="__ALC_BADGE"]:visible').trigger('click');
	});

	/**
	 * Final load events, placed here to ensure the required events have been
	 * bound successfully.
	 */
	if(window.location.hash == '#login_required')
		$('#login_required').dialog('open');

	if(window.location.hash == '#forgot_pin') {
		$('.signin').trigger('click');

		$('.forgot a:visible').trigger('click');

		$('#forgotpin [name="phoneno"]').focus();
	}

	$('#signin, #login, form.login').submit(function(event) {
		event.preventDefault();

		log_in({
			phoneno		: $('[name="phoneno"]', this).val(),
			pin			: $('[name="pin"]', this).val(),
			remember_me	: $('[name="remember_me"]', this).attr('checked') ? 1 : 0
		}, function(response) {
			if(response.error) {
				$('input[name="pin"]').val('').focus();
				
				return alert(response.error);
			}

			window.location = response.redirect;
		});
	});

	$('#forgotpin').submit(function(event) {
		event.preventDefault();

		remind_pin($('[name="phoneno"]', this).val(), function(response) {
			if(response.error) {
				$('#forgotpin input[name="phoneno"]').val('').focus();

				return alert(response.error);
			}

			alert('We have sent an email and a SMS with your PIN!');
			$('#forgotpin a.toggle').click();
			$('#signin input[name="pin"]').val('').focus();
		});
	});

	$('#signin_menu .toggle').click(function(event) {
		event.preventDefault();

		$('#signin_menu form').toggle();
		$('#signin input[name="phoneno"]').val($('#forgotpin input[name="phoneno"]').val());
	});

	$(".signin").click(function() {
		$("fieldset#signin_menu").toggle();
		$(".signin").toggleClass("menu-open");
	});

   	$('.tc-button').hover(
   		function(){ $(this).removeClass('ui-state-default').addClass('ui-state-focus'); },
		function(){ $(this).removeClass('ui-state-focus').addClass('ui-state-default'); }
	);

	$('body').click(function(event) {
		if($(event.target).parents('.signin').size() || $(event.target).parents('#signin_menu').size())
			return;

		$('#signin_menu').hide();
		$(".signin").removeClass("menu-open");
	});

	$('.teltech_inline span').live('click', function() {
		if($.browser.msie) {
			var span = this;

			setTimeout(function() {
				$(span).parents('.teltech_inline').find(':input:first').focus();
			}, 300);
		}
	});
	
	$('#navigation *').hover(function() {
		$(this).addClass('hover active');
	}, function() {
		$(this).removeClass('hover active');
	})
});










/**
 * Predefined Functions
 *
 * - These functions are used as shortcuts for ajax
 * - calls throughout the website to provide a direct
 * - gateway for functionality.
 */
var blacklist_caller = function(caller_id, callback) {
	callback = define_callback(callback);
	
	$.post('/blacklist/json',{
		request		: 'blacklist_caller',
		caller_id	: caller_id
	}, callback, 'json');
}

var blacklist_phonenumber = function(phone_number, callback) {
	callback = define_callback(callback);
	
	$.post('/blacklist/json',{
		request		: 'blacklist_phonenumber',
		phoneno		: phone_number
	}, callback, 'json');
}

var cancel_account = function(callback) {
	callback = define_callback(callback);

	$.post('/account/json', {
		request	: 'cancel_account'
	}, callback, 'json');
}

var delete_calls = function(calls, callback) {
	callback = define_callback(callback);

	if(typeof calls == 'object')
		calls = $.toJSON(calls);

	$.post('/controlpanel/json',{
		request	: 'delete_calls',
		calls	: calls
	}, callback, 'json');
}

var define_callback = function(callback) {
	if(typeof callback != 'function')
		callback = function() {};
	
	return callback;
}

var remind_pin = function(phoneno, callback) {
	callback = define_callback(callback);

	$.post('/user/json/',{
		request	: 'remind_pin',
		phoneno	: phoneno
	}, callback, 'json');
}

var login = function(phoneno, pin, callback) {
	callback = define_callback(callback);

	$.post('/user/json/', {
		request	: 'login',
		phoneno	: phoneno,
		pin		: pin
	}, callback, 'json');
}

var log_in = function(data, callback) {
	$.post('/user/json', $.extend(data, {
		request	: 'login'
	}), callback, 'json');
}

var nickname_caller = function(caller_id, nickname, callback) {
	callback = define_callback(callback);

	$.post('/controlpanel/json', {
		request		: 'nickname_caller',
		caller_id	: caller_id,
		nickname	: nickname
	}, callback, 'json');
}

var program_phone = function(callback) {
	callback = define_callback(callback);

	$.post('/account/json', {
		request	: 'program_phone'
	}, callback, 'json');
}

var purchase_package = function(data, callback) {
	callback = define_callback(callback);

	if(typeof data != 'object')
		data = {};

	data.request = 'purchase_package';

	$.post('/premium/json', data, callback, 'json');
}

store_reprogram_attempt = function(callback) {
	callback = define_callback(callback);

	$.post('/controlpanel/json', {
		request	: 'store_reprogram_attempt'
	}, callback, 'json');
}

var submit_feedback = function(feedback, callback) {
	callback = define_callback(callback);

	$.post('/account/json', {
		request		: 'submit_feedback',
		feedback	: escape(feedback)
	}, callback, 'json');
}

var update_billing_info = function(data, callback) {
	callback = define_callback(callback);

	if(typeof data != 'object')
		data = {};

	data.request = 'update_billing_info';

	$.post('/premium/json', data, callback, 'json');
}

var update_carrier = function(carrier_id, callback) {
	callback = define_callback(callback);

	$.post('/account/json', {
		request		: 'update_carrier',
		carrier_id	: carrier_id
	}, callback, 'json');
}

var update_user = function(user_data, callback) {
	callback = define_callback(callback);

	if(typeof user_data == 'object')
		user_data = $.toJSON(user_data);

	$.post('/account/json', {
		request		: 'update',
		user_data	: user_data
	}, callback, 'json');
}


// SIGNUP CREATE ACCOUNT
	var timezone_offsets = {
		'-5'	: 'US/Eastern',
		'-6'	: 'US/Central',
		'-7'	: 'US/Mountain',
		'-8'	: 'US/Pacific'
	}

	var existing_trial_consent = <?= $this->trial_offer ? 'false' : 'true' ?>,
		purchase_success = <?= $this->user && $this->user->next_renewal ? 'true' : 'false' ?>,
		carrier_id, 
		active_form,
		verified_warnings = false,
		validated_coupon_code = '',
		validated_coupon = {};

	$(function() {
		$('label.teltech_inline input').after('<img class="exclamation" src="/images/exclamation.png" border="0" />');

		$('label.teltech_inline input').blur(function(event) {
			if($(this).val() && $(this).parents('.teltech_inline').hasClass('error'))
				$(this).parents('.teltech_inline').removeClass('error');
		})

		var timezone = timezone_offsets[new Date().getTimezoneOffset() / 60 * -1];

		if(timezone)
			$('select[name="timezone"] option[value="' + timezone + '"]').attr('selected',true);

		$('#existing_trial_consent').dialog({
			autoOpen	: false,
			buttons		: {
				'I Understand'	: function() {
					existing_trial_consent = true;

					$(this).dialog('close');

					$('#signup').submit();
				}
			},
			modal		: true,
			resizable	: false,
			width		: 500
		});

		$('*').bind('dialogclose', function() {
			$(':submit', active_form).addClass('sexyblue').attr('disabled', false);
		});

		$('#signup').submit(function(event) {
			event.preventDefault();

			$('.fix_errors').hide();

			$('label.teltech_inline.error', this).removeClass('error');

			$('.section:has(#agree) img.exclamation').hide();
			
			var payment_method = $(':radio[name="payment_method"]:checked').attr('payment_method');

			// VALIDATE NOT EMPTY
			$('label.teltech_inline :input[name]:visible', this).each(function() {
				if(validated_coupon_code && validated_coupon.creditcard_required == '0') {
					if(!$(this).val() && !$(this).parents('.creditcard_info').size())
						$(this).parents('.teltech_inline').addClass('error');
				} else {
					if(!$(this).val())
						$(this).parents('.teltech_inline').addClass('error');
				}
			});

			if($('input[name="pin"]', this).val().length != 4)
				$('[name="pin"]', this).parents('.teltech_inline').addClass('error');

			if(validated_coupon_code && validated_coupon.creditcard_required == '1') {
				if($('input[name="zip"]', this).val().length != 5)
					$('[name="zip"]', this).parents('.teltech_inline').addClass('error');
			}

			// VALIDATE EMAIL
			if(!emailPattern.test($('[name="email"]', this).val()))
				$('[name="email"]', this).parents('.teltech_inline').addClass('error');

			if(!$('#agree').attr('checked')) {
				$('.section:has(#agree) .exclamation').show();
				return $('.fix_errors').fadeIn();
			}
			
			if($('label.teltech_inline.error').size())
				return $('.fix_errors').fadeIn();

			if($('select[name="carrier"]').val() == '')
				return $('#form_error').dialog('open').html('Please select a Service Provider!');

			active_form = this;

			$('body').css('cursor', 'wait');

			$(':submit', active_form).removeClass('sexyblue').attr('disabled', true);

			$.post('/signup/json', {
				request		: 'check_existing_trial',
				phoneno		: $('input[name="phoneno"]', this).val(),
				package_id	: <?= $this->package->id ?>
			}, function(response) {
				if(response.previous_account && !existing_trial_consent) {
					$('body').css('cursor', 'default');
					return $('#existing_trial_consent').dialog('open');
				}

				$.post('/signup/json', {
					request		: 'create_account',
					phoneno		: $('input[name="phoneno"]', active_form).val(),
					firstname	: $('input[name="firstname"]', active_form).val(),
					lastname	: $('input[name="lastname"]', active_form).val(),
					pin			: $('input[name="pin"]', active_form).val(),
					carrier_id	: $('select[name="carrier_id"]', active_form).val(),
					email		: $('input[name="email"]', active_form).val(),
					package_id	: <?= $this->package->id ?>,
					timezone	: $('select[name="timezone"]', active_form).val()
				}, function(response) {
					if(response.error) {
						$('body').css('cursor', 'default');
						$('#form_error').dialog('open').html(response.error);

						return false;
					}

					carrier_id = response.user.carrier_id;

					/**
					 * Check Warnings
					 */
					if(!verified_warnings)
						verified_warnings = check_warnings(carrier_id);

					/**
					 * Stop because of unverified warnings
					 */
					if(!verified_warnings)
						return;

                    switch(payment_method) {
                        case 'creditcard':
        					if(!purchase_success) {
        						purchase_package({
        							package_id	: <?= $this->package->id ?>,
        							first_name	: $('[name="firstname"]', active_form).val(),
        							last_name	: $('[name="lastname"]', active_form).val(),
        							coupon		: validated_coupon_code,
        							address		: $('[name="address"]', active_form).val(),
        							city		: $('[name="city"]', active_form).val(),
        							state		: $('[name="state"]', active_form).val(),
        							zip			: $('[name="zip"]', active_form).val(),
        							country		: 'US',
        							card_number	: $('[name="card_number"]', active_form).val(),
        							exp_month	: $('[name="exp_month"]', active_form).val(),
        							exp_year	: $('[name="exp_year"]', active_form).val(),
        							ccv			: $('[name="ccv"]', active_form).val()
        						}, function(response) {
        							if(response.error) {
        								$('body').css('cursor', 'default');
        								return $('#form_error').dialog('open').html(response.error);
        							}
        
        							purchase_success = true;
        
/*         							check_pilot_number(carrier_id); */
        
                                    window.location.assign('/signup/complete');
        						});
                            } else {
                                window.location.assign('/signup/complete');
/*         						check_pilot_number(carrier_id); */
        					}
        				break;
        				case 'paypal':
                            $.post('/signup/json', {
                                request     : 'prepare_paypal_transaction',
                                package_id  : <?= $this->package->id ?>,
                                return_url  : 'https://<?= $_SERVER['SERVER_NAME'] ?>/signup/paypal/action/confirm',
                                cancel_url  : 'https://<?= $_SERVER['SERVER_NAME'] ?>/signup/create-account/package_id/<?= $this->package->id ?>/paypal/cancel'
                            }, function(response) {
                                if(response.error)
                                    return alert(response.error);
                                
                                window.location.assign(response.redirect);
                            }, 'json');
        				break;
        				default:
        				    return alert('An unknown processor error has occurred!');
                    }
				},'json');
			},'json');
		});
			
		$('#form_error').dialog({
			autoOpen	: false,
			buttons		: {
				'Ok'	: function() {
					$(this).dialog('close')
				}
			},
			open		: function() {
				$('body').css('cursor', 'default');
				$(':submit', active_form).addClass('sexyblue').attr('disabled', false);
			},
			modal		: true,
			resizable	: false
		});

		$('#tmobile_prepaid, #hosted_vm_warning').dialog({
			autoOpen	: false,
			buttons		: {
				'Continue'	: function() {
					$(this).submit();
				},
				'Cancel Signup'	: function() {
					$(this).dialog('close');
				}
			},
			open		: function() {
				$('body').css('cursor', 'default');
				$(':submit', active_form).addClass('sexyblue').attr('disabled', false);
			},
			resizable	: false,
			modal		: true,
			width		: 650
		}).submit(function(event) {
			event.preventDefault();

			$(this).dialog('close');

			verified_warnings = true;

			$('#signup').submit();
		});

		$('input[name="zip"]').blur(function(event) {
			if($(this).val().length < 5) {
				$('[name="city"]').val('').trigger('blur');
				$('[name="state"]').val('').trigger('blur');
				return;
			}

			$.post('/signup/json', {
				request	: 'get_zip_data',
				zip		: $(this).val()
			}, function(response) {
				var state = '';
				var city = '';

				if(response.error) {
					$('#location_container').fadeIn();
				} else {
					city = response.zip_data.city;
					state = response.zip_data.state_abbr;
				}

				$('[name="city"]').val(city).trigger('blur');
				$('[name="state"]').val(state).trigger('blur');

				$('[name="card_number"]').focus();
			}, 'json');
		});

		$('#use_coupon').submit(function(event) {
			event.preventDefault();

			$('.alert', this).hide();

			var form = this;

			$.post('/premium/json', {
				request	: 'validate_coupon',
				coupon	: $('[name="coupon_code"]', this).val()
			}, function(response) {
				if(response.error)
					return $('.error', form).fadeIn().html(response.error);

				validated_coupon = response.coupon;
				validated_coupon_code = response.coupon.code;

				if(validated_coupon.creditcard_required == '0') {
					$('.creditcard_info').fadeOut();
				} else {
					if(parseFloat(validated_coupon.charge_amount) > 0) {
						$('#trial_overview, #paid_overview').hide();

						$('#coupon_discount').show();
						$('#coupon_discount .charge_amount').html(validated_coupon.charge_amount);
						$('#coupon_discount .package_title').html(response.package.title);
						$('#coupon_discount .package_price').html(response.package.price);
						$('#coupon_discount .next_renewal').html(response.next_renewal);
					}
				}

				$(form).fadeOut();
			}, 'json');
		});
		
        $('[payment_method]').click(function() {
            $('[payment_method].selected').removeClass('selected');
            
            $(this).addClass('selected');
            
            $('[group="creditcard_info"]')[$(this).attr('payment_method') == 'paypal' ? 'hide' : 'show']();
        });
        
        $('[payment_method="creditcard"]').trigger('click');
	});

	var check_warnings = function(carrier_id) {
		switch(parseInt(carrier_id)) {
			case 6:
			case 9:
				$('#hosted_vm_warning').dialog('open');
				return false;
			break;
			case 10:
				$('#tmobile_prepaid').dialog('open');
				return false;
			break;
		}

		return true;
	}
	
// REMOVED FROM BLACKLIST PAGE ON 6/30/2010



