$(function(){;
	doclear();
	messageLength();
	selectAll();
	buyPage();
	format();
	getCallCost();
	help();
	triggerGetStatus();
	twitterShare();
	frontTestimonials();
});

function frontTestimonials() {
	if ($('#testimonials').length != 0) {
			$('#testimonials').innerfade({
				animationtype: 'fade',
				speed: 750,
				timeout: 7000,
				type: 'sequence',
				containerheight: 'auto'
			});
	}
}

// open the twitter share window in a greybox
function twitterShare(){
	$('#twitterShare').click(function(){
		GB_show('Share us on Twitter', '/twitterShare.php', '260', '400');
	});
}

// handle input with default values
function doclear(){
	$('.doclear').each(function(){
		$(this).val($(this).attr('title'));
		
		// clear the $(this) on focus if default value
		$(this).focus(function(){
			if ($(this).val() == $(this).attr('title')) {
				$(this).val('');
			}
		});
		
		// reset the $(this) on blur if blank
		$(this).blur(function(){
			if ($(this).val() == '') {
				// populate the input with the default text
				$(this).val($(this).attr('title'));
			}
		});
	});
}

// triggered on keypress in the to call field on the prank page
function getCallCost(){
	// if logged in
	if ($('#reguser').length == 1) {
		// run on keyup pranks
		$('#phone1, #phone2').keyup(function(){
			// get the callcost box
			var callCost = $('#callcost');
			var phone1 = $('#phone1').val()

			if(phone1 != 1) {
				$('#checkcbutton').fadeOut('medium');
				$('#uscarriers').slideUp('fast');
				$('#intcarriers').slideDown('medium');
			} else {
				$('#checkcbutton').fadeIn('medium');
				$('#uscarriers').slideDown('medium');
				$('#intcarriers').slideUp('fast');
			}
			
			if (callCost.length != 0) {
				// get the values
				var phone1 = $('#phone1').val();
				var phone2 = unformat($('#phone2').val());

				// if the area code is set, run ajax
				if ( (phone1.length + phone2.length) >= 4 && phone2 != 'area+phone') {
					// set the query data
					var queryString = "?phone1=" + phone1 + "&phone2=" +  phone2;

					$.ajax({
						url: "/application/callcost.php" + queryString,
						success: function(data) {
							callCost.html(data);
							callCost.css('display', 'block');
						}
					});
				} else {
					callCost.css('display', 'none');
				}
			}
		});
	}
}

// populates the faq
function help(){
	$('.helpLink').click(function(){
		$('#helpContent').html($(this).next('.helpAnswers').html());
	});
}

// message characters left
function messageLength() {
	if ($('#message').length == 1) {
		var characters = $('#messageMax').html();

		setRemainingCharacters();

		$('#message').keyup(function(){
			setRemainingCharacters()
		});
	}
}

// counts the length of a textarea and sets the remaining chars
function setRemainingCharacters(){
	var length = $('#messageMax').html() - $('#message').val().length;
	if (length < 0) {
		length = 0;
		$('#messageError').html('Your message is too long!').fadeIn('medium');
		
		if ($('#commentsForm').length == 1) {
			$('#commentsSubmit').attr('disable', true);
		}
	} else {
		$('#messageError').fadeOut('medium');
		if ($('#commentsForm').length == 1) {
			$('#commentsSubmit').removeAttr('disable');
		}
	}
	$('#charsLeft').html(length);
}

// when you click in an input with class="selectAll", all the contents are selected
function selectAll(){
	if ($('.selectAll').length != 0) {
		$('.selectAll').click(function(){
			$(this).select();
		});
	}
}

// buy page interaction
function buyPage(){
	if ($('.tokencontainer').length != 0) {
		// onload, clear email and tokens
		$('#email, #email1, #tokens1').val('');

		$('#email').change(function(){
			$('#email1').val($('#email').val());
		});

		// when you select a tokens package
		$('.buy_pack').click(function(){
			// unhightlight all the boxes
			$('.buy_pack').removeClass('selectedbuyt');
		
			// set the hightlighted box
			$(this).addClass('selectedbuyt');
;
			// set the you have chosen text
			tokens = $(this).attr('id');
			output = "You have chosen: " + tokens + ' token';
			if (tokens > 1) {
				output += 's';
			}

			// output the text
			$('#youHaveChosen').html(output);

			// set the hidden fields
			$('#tokens1').val(tokens);
			$('#paypalTokens').val(tokens);
		});
		
		// slidedown credit and hide paypal
		$('#getCreditOptions').click(function(){
			// hide a paypal validation error
			$('#buyPaypalError').fadeOut('medium');

			
			// show the credit card options
			$('#creditOptions').slideDown('medium');
		});
		
		// on paypal click, hide credit
		$('#paypal').click(function(){
			$('#creditOptions').slideUp('medium', function(){
				$('#buyCreditError').fadeOut('medium');
			});
		});
	}
}

function format(){
	// set masking on fields with class format
	$('.format').focus(function(){
		if ($(this).prev('input').val() == '1') {
			$(this).unmask();
			$(this).mask('(999) 999-9999');
		}
	});
	

	// for fields with international calling, mask or unmask depending on what country you're running
	$('#phone1, #callid1').keyup(function(){
		if ($(this).val() == '1') {
			$(this).next('input').unmask();
			$(this).next('input').mask("(999) 999-9999");
		} else {
			$(this).next('input').unmask();
			
			// get the phone number's value
			var value = $(this).next('input').val();
			
			// make the default text go away, or unformat the phone numer
			if (value == 'area + phone') {
				$(this).next('input').val('');
			} else {
				$(this).next('input').val(unformat(value));
			}
		}
	});

}

function iframeDone(){
	// get the background color
	bgColor = $('#GB_window').css('backgroundColor');

	// set the background to the color (to remove the loading gif)
	$('#GB_frame').css('background', bgColor);

	// fade in the iframe
	$('#GB_frame').fadeIn('medium', function(){
		// if the code input is there, focus
		if ($('#GB_frame').contents().find('#code').length == 1) {
			$('#GB_frame').contents().find('#code').focus();
		}
	});
}

function unformat(value){
	value = value.replace(/\(/, '');
	value = value.replace(/\)/, '');
	value = value.replace(/ /g, '');
	value = value.replace(/\-/, '');
	value = value.replace(/_/g, '');
	
	return value;
}

// ===================
// = Validation Code =
// ===================



// called from token login on index
// make sure the input isn't null and has no spaces,
// then launch the captcha
function validateLogin() {
	var tokenlogin = $('#tokenLogin').val();

	if (tokenlogin == "") {
		$('#menu').css('height', '60px');
		$('#loginError').html("Please enter your token id.").fadeIn('medium');
	} else if (tokenlogin != '' && tokenlogin.match(/ /)) {
		$('#menu').css('height', '60px');
		$('#loginError').html("Please enter your token id correctly.").fadeIn('medium');
	} else {
		$('#loginError').fadeOut('medium');
		$('#menu').css('height', '36px');
		GB_show('Are you a robot? Hope not.', 'application/captcha.php?tokenlogin=' + tokenlogin + '&url=' + location.pathname, '220', '300');
	}

	return false;
}

//validate free tokens
// validation from the tokens_free page
function validateFreeTokens() {
	error = false;
	var mail = $('#email').val();

	// validate email
	validateReqEmail();

	if (!error) {
		return true;
	} else {
		return false;
	}
}


// forgot token validation
function validateForgot(){
	error = false;

	// email validation
	validateReqEmail();
	var email = $('#email').val();
	if (!error) {
		$.ajax({
			url: "/application/forgot.php?email=" + email,
			success: function(data) {
				switch (data) {
					case '0':
						$('#forgotMsg').removeClass('notice').addClass('error').html('that email does not exist in our database.').fadeIn('medium');
						break;
					case '1':
						$('#forgotMsg').removeClass('error').addClass('notice').html('we have sent your token id(s) to ' + email).fadeIn('medium');
						break;
				}
			}
		});
	}

	return false;
}


// contact form validation
function validateContact(){
	error = false;
	
	var name = $('#name').val();
	var email = $('#email').val();
	var topic = $('#topic').val();
	var comments = $('#contents').val();
	var tokenid = $('#contactTokenid').val();

	// name empty
	if (name == '') {
		error = true;
		$('#nameError').html('please enter your name.').fadeIn('medium');
	} else {
		$('#nameError').fadeOut('medium');
	}
	
	// validate email
	validateReqEmail();
	
	// comment
	if (comments == '') {
		error = true;
		$('#commentError').html('don\'t you want to tell us something?').fadeIn('medium');
	} else {
		$('#commentError').fadeOut('medium');
	}
		
	if (!error) {
		// get the user's browser and os info
		var BrowserDetect = {
			init: function () {
				this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
				this.version = this.searchVersion(navigator.userAgent)
					|| this.searchVersion(navigator.appVersion)
					|| "an unknown version";
				this.OS = this.searchString(this.dataOS) || "an unknown OS";
			},
			searchString: function (data) {
				for (var i=0;i<data.length;i++)	{
					var dataString = data[i].string;
					var dataProp = data[i].prop;
					this.versionSearchString = data[i].versionSearch || data[i].identity;
					if (dataString) {
						if (dataString.indexOf(data[i].subString) != -1)
							return data[i].identity;
					}
					else if (dataProp)
						return data[i].identity;
				}
			},
			searchVersion: function (dataString) {
				var index = dataString.indexOf(this.versionSearchString);
				if (index == -1) return;
				return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
			},
			dataBrowser: [
				{
					string: navigator.userAgent,
					subString: "Chrome",
					identity: "Chrome"
				},
				{ 	string: navigator.userAgent,
					subString: "OmniWeb",
					versionSearch: "OmniWeb/",
					identity: "OmniWeb"
				},
				{
					string: navigator.vendor,
					subString: "Apple",
					identity: "Safari",
					versionSearch: "Version"
				},
				{
					prop: window.opera,
					identity: "Opera"
				},
				{
					string: navigator.vendor,
					subString: "iCab",
					identity: "iCab"
				},
				{
					string: navigator.vendor,
					subString: "KDE",
					identity: "Konqueror"
				},
				{
					string: navigator.userAgent,
					subString: "Firefox",
					identity: "Firefox"
				},
				{
					string: navigator.vendor,
					subString: "Camino",
					identity: "Camino"
				},
				{		// for newer Netscapes (6+)
					string: navigator.userAgent,
					subString: "Netscape",
					identity: "Netscape"
				},
				{
					string: navigator.userAgent,
					subString: "MSIE",
					identity: "Explorer",
					versionSearch: "MSIE"
				},
				{
					string: navigator.userAgent,
					subString: "Gecko",
					identity: "Mozilla",
					versionSearch: "rv"
				},
				{ 		// for older Netscapes (4-)
					string: navigator.userAgent,
					subString: "Mozilla",
					identity: "Netscape",
					versionSearch: "Mozilla"
				}
			],
			dataOS : [
				{
					string: navigator.platform,
					subString: "Win",
					identity: "Windows"
				},
				{
					string: navigator.platform,
					subString: "Mac",
					identity: "Mac"
				},
				{
					string: navigator.userAgent,
					subString: "iPhone",
					identity: "iPhone/iPod"
			    },
				{
					string: navigator.platform,
					subString: "Linux",
					identity: "Linux"
				}
			]

		};
		BrowserDetect.init();
		
		browserInfo = 'Submitted from: ' + BrowserDetect.browser + ' ' + BrowserDetect.version + ' on ' + BrowserDetect.OS;

		$.ajax({
			url: "/application/contact.php?name=" + name + "&email=" + email + "&topic=" + topic + "&comment=" + comments + "&tokenid=" + tokenid + '&browserInfo=' + browserInfo,
			success: function(data) {
				switch (data) {
					case '0':
						$('#contactMsg').removeClass('notice').addClass('error').html('there was an error.').fadeIn('medium');
						break;
					case '1':
						$('#contactMsg').removeClass('error').addClass('notice').html('email sent! we will contact you shortly.').fadeIn('medium');
						break;
				}
			}
		});
	}
	
	return false;
}

// when you hit send call on a prank page, make sure everything's in order
function validateSendCall() {
	// set the error flag
	error = false;

	// get the phone number
	phone = $('#phone1').val() + unformat($('#phone2').val());
	countrycode = $('#phone1').val();

	// if the phone number is blank or not a number
	if (phone == "" || isNaN(phone)) {
		error = true;

		// different messages for logged in or not
		$('#phoneError').html("Please enter a proper numeric phone number.").fadeIn('medium');

		// give the phone number focus
	// if the phone number not blank and a number, but the wrong length
    } else if (phone.length < 11 && countrycode == 1) {
		error = true;
		
		// different messages for logged in or not
		$('#phoneError').html("Your friend's number needs to be the proper length.").fadeIn('medium');
		
	} else {
		$('#phoneError').fadeOut('medium');
	}

	// get the caller id
	cid_num = $('#callid1').val() + unformat($('#callid2').val());

	// if the callid number is blank or not a number
	if (cid_num == "" || isNaN(cid_num)) {
		error = true;

		// different messages for logged in or not
		$('#cidError').html("Please enter a proper numeric send from number.").fadeIn('medium');

	// if the callid number not blank and a number, but the wrong length
    } else if (cid_num.length < 11) {
		error = true;
		
		// different messages for logged in or not
		$('#cidError').html("Please enter a proper numeric send from number.").fadeIn('medium');
		
	} else {
		$('#cidError').fadeOut('medium');
	}
	
	if ($('#callcost').html() == "Wrong Dial Code!") {
		error = true;

		$('#phoneError').html("Please enter a correct dial code.").fadeIn('medium');
    }

		var msg = $('#message').val();
		
		msgMax = 160;

		if (msg == '') {
			error = true;
			$('#messageError').html('You need to enter your message!').fadeIn('medium');
		} else if (msg.length > msgMax){
			error = true;
			$('#messageError').html('Your message is too long!').fadeIn('medium');
		} else {
			$('#messageError').fadeOut('medium');
		}

/*	
	if ($('#phone1').val() == "1"){
		var carrierIsGood	=	checkCarrier();
		if ( !carrierIsGood ){
			error = true;
			$('#phoneError').html('Phone number is not supported =(').fadeIn('medium');			
		}else{			
			$('#phoneError').fadeOut('medium');
		}
	}*/
	
		
	if (!error) {
		return true;		
	} else {
		return false;
	}
}


//check carriers
function checkCarrier(){
	phone = unformat($('#phone2').val());
	if (phone == "" || isNaN(phone)) {
		alert("Enter a number!");
	} else {			
		var num		=	unformat($('#phone2').val());
		$.ajax({
			url : "application/checkCarrier.php",
			data: { num: num},
			dataType: "json",
			success: function(data){
				var valid = false;
				if(data != null) { 
					valid	=	validCarrier(data.carrier_name);
				}
				if ( !valid ){
					$('#phoneNotice').fadeOut('medium');
					$('#phoneError').fadeOut('medium');
					$('#phoneError').html(data.carrier_name+'<br />Phone number is not supported =(.<br />We maybe wrong, check the full <a href="/carrier_support" style="color:white">coverage list</a>.').fadeIn('medium');
				} else {
					$('#phoneError').fadeOut('medium');
					$('#phoneNotice').fadeOut('medium');
					$('#phoneNotice').html('Phone number is supported! :)<br />I could be wrong though').fadeIn('medium');
				}
				return valid;
			}
		});		
	}
}


function validCarrier(carrier){
	if (carrier == null)
		return false;
	//"CINGULAR","AT&T",	
	var carriers	=	new Array("T-MOBILE","OMNIPOINT","NEXTEL","CELLULAR ONE","CELLULARONE","UNICEL","VIAERO");
	var allowed		=	false;
	for ( var i = 0; i < carriers.length; i++ ){
		if ( carrier.indexOf( carriers[i] ) >= 0 ){
			allowed = true;		
		}
	}	
	return allowed;	
}


// validation from the tokens_free_status page
function validateTokenStatus() {
	error = '';
	
	var token = $('#token').val();
	
	if (token == "" || token == $('#token').attr('title')) {
		error = "Please enter your token ID.";
	}
	
	if (error != '') {
		// show error
		$('#tokenError').html(error).fadeIn('medium');
		
		return false;
	} else {
		return true;
	}
}

// email, token package, info form validation on buy page
function validateBuy(){
	var reason = "";
	var emailIsValid = false;
	reason += validateEmpty($('#firstName'), "first name");
	reason += validateEmpty($('#lastName'), "last name");
	reason += validateEmpty($('#address1'), "address");
	reason += validateEmpty($('#city'), "city");
	reason += validateNum($('#zip'), 5, "zip");
	reason += Mod10($('#creditCardNumber').val());
	reason += validateEmpty($('#cvv2Number'), "credit card card cvv");

	// get the email
	var email = $('#email').val();

	// set the hidden email fields
	$('#email1').val(email);
	
	// get the tokens
	var tokens = $('#tokens1').val();
	
	// validate email
	if (email == "") {
		reason += "Please enter your email.<br>";
	} else {
		if (echeck(email) == false) {
			email = "";
			reason += "Please enter your email in a correct format.<br>";
		} else {
			emailIsValid = true;			
		}
	}

	if (tokens == ""){
		reason += "Please select a token package.<br>";
	}
	
	// check to see if this email has made a double purchase
	if (emailIsValid) {
		$.ajax({
			url: "/application/checkDoublePurchase.php?email=" + email,
			success: function(data) {
				if (data == '1') {
					error = true;
					reason = 'Duplicate Credit Purchase - Please contact us if having trouble';
				}
			}
		});
	}

	if (reason != "") {
		// set the error div
		$('#buyCreditError').html(reason).fadeIn('medium');
		return false;
	} else {
		return confirm("Are you sure you want to buy " + tokens + " tokens with your credit card?");
		return true;
	}
}

	
// click from paypal button
function validatePaypal(){
	//Fade out CC form	
	$('.row4').fadeOut();
	
	var reason = '';

	// get the email
	var email = $('#email').val();
	var tokens	=	$('#tokens1').val();

	// set the hidden fields
	$('#paypalEmail').val(email);

	if (email == "") {
		reason += "<div class='paypalError'>Please enter your email.</div>";
	} else {
		if (!echeck(email)){
			reason += "<div class='paypalError'>Please enter your email in a correct format.</div>";
		}
	}

	if (tokens == "" || tokens	==	"Please choose a token package"){
		reason += "<div class='paypalError'>Please select a token package.</div>";
	}

	if (reason != '') {
		$('#buyPaypalError').html(reason).fadeIn('slow');

		$('#paypalButton').removeClass('loading active');

		return false;
	} else {
		$('#buyPaypalError').fadeOut('medium');

		var url	=	"tokens_buy.php?email="+email+"&tokens="+tokens+"&submit=okk";
		//Reset forms
		//$('.form').clearForm();
		
		window.location	=	url;
		return false;
	}
}

// =====================
// = Validation Pieces =
// =====================
// validation functions that you can call from master functions




// make sure email is valid (does not throw error for blank)
function validateNotReqEmail(){
	// get the email
	var email = $('#email').val();

	if (email != '') {
		if (!echeck(email)) {
			error = true;
			$('#emailError').html('Please enter a valid email address.').fadeIn('medium');
		} else {
			$('#emailError').fadeOut('medium');
		}
	} else {
		$('#emailError').fadeOut('medium');
	}
}

// make sure email is not blank or default, and valid
function validateReqEmail(){
	// get the email
	var email = $('#email').val();

	if (email == "" || email == 'enter your email') {
		error = true;
		$('#forgot_notification').fadeOut();
		$('#emailError').html("Please enter your email.").fadeIn('medium');
	} else {
		if (!echeck(email)){
			error = true;
			
			$('#forgot_notification').fadeOut();
			$('#emailError').html("Please enter your email in a correct format.").fadeIn('medium');
		} else {
			$('#emailError').fadeOut('medium');
		}
	}
}

// validate email from buy page (error handling is different)
function validateBuyEmail(){
	var email = $('#email').val();
	
	if (email == "") {
		reason += "Please enter your email.<br>";
	} else {
		if (echeck(email) == false) {
			email = "";
			reason += "Please enter your email in a correct format.<br>";
		} else {
			emailIsValid = true;			
		}
	}
}

// check that an email is in the right format
// called from the forgot email page
function echeck(str) {
	var at="@"
	var dot="."
	var lat=str.indexOf(at)
	var lstr=str.length
	var ldot=str.indexOf(dot)
	if (str.indexOf(at)==-1){
		return false;
	}
	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		return false;
	}
	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		return false;
	}
	if (str.indexOf(at,(lat+1))!=-1){
		return false;
	}
	if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		return false;
	}
	if (str.indexOf(dot,(lat+2))==-1){
		return false;
	}
	if (str.indexOf(" ")!=-1){
		return false;
	}

	return true;
}

var inputBG = '#FFF';

// verify a credit card number
function Mod10(ccNumb) {  // v2.0
	var valid = "0123456789"  // Valid digits in a credit card number
	var len = ccNumb.length;  // The length of the submitted cc number
	var iCCN = parseInt(ccNumb);  // integer of ccNumb
	var sCCN = ccNumb.toString();  // string of ccNumb
	sCCN = sCCN.replace (/^\s+|\s+$/g,'');  // strip spaces
	var iTotal = 0;  // integer total set at zero
	var bNum = true;  // by default assume it is a number
	var bResult = false;  // by default assume it is NOT a valid cc
	var temp;  // temp variable for parsing string
	var calc;  // used for calculation of each digit

	// Determine if the ccNumb is in fact all numbers
	for (var j=0; j<len; j++) {
		temp = "" + sCCN.substring(j, j+1);
		if (valid.indexOf(temp) == "-1") {
			bNum = false;
		}
	}

	// if it is NOT a number, you can either alert to the fact, or just pass a failure
	if (!bNum) {
		// alert("Not a Number");
		bResult = false;
	}

	// // Determine if it is the proper length 
	
	// nothing, field is blank AND passed above # check
	if ( (len == 0) && (bResult) ) {
		bResult = false;
	// ccNumb is a number and the proper length - let's see if it is a valid card number
	} else{
		if (len >= 15){  // 15 or 16 for Amex or V/MC
			for (var i=len; i > 0; i--) {  // LOOP throught the digits of the card
				calc = parseInt(iCCN) % 10;  // right most digit
				calc = parseInt(calc);  // assure it is an integer
				iTotal += calc;  // running total of the card number as we loop - Do Nothing to first digit
				i--;  // decrement the count - move to the next digit in the card
				iCCN = iCCN / 10;                               // subtracts right most digit from ccNumb
				calc = parseInt(iCCN) % 10 ;    // NEXT right most digit
				calc = calc *2;                                 // multiply the digit by two

				// Instead of some screwy method of converting 16 to a string and then parsing 1 and 6 and then adding them to make 7,
				// I use a simple switch statement to change the value of calc2 to 7 if 16 is the multiple.
				switch (calc) {
					case 10: calc = 1; break;       //5*2=10 & 1+0 = 1
					case 12: calc = 3; break;       //6*2=12 & 1+2 = 3
					case 14: calc = 5; break;       //7*2=14 & 1+4 = 5
					case 16: calc = 7; break;       //8*2=16 & 1+6 = 7
					case 18: calc = 9; break;       //9*2=18 & 1+8 = 9
					default: calc = calc;           //4*2= 8 &   8 = 8  -same for all lower numbers
				}                                               

				iCCN = iCCN / 10;  // subtracts right most digit from ccNum
				iTotal += calc;  // running total of the card number as we loop
			}  // END OF LOOP
			
			if ((iTotal%10)==0) {  // check to see if the sum Mod 10 is zero
				bResult = true;  // This IS (or could be) a valid credit card number.
			} else {
				bResult = false;  // This could NOT be a valid credit card number
			}
		}
	}
	
	var error = "";

	// change alert to on-page display or other indication as needed.
	if (!bResult) {
		error = "Your credit card number is in the wrong format or invalid.<br>";
		$('#creditCardNumber').css('background', '#FBE4E4');
	} else {
		$('#creditCardNumber').css('background', inputBG);
	}
	return error; // Return the results
}

// buy page empty field validation
function validateEmpty(fld, name) {
	var error = "";
	
	if (fld.val().length == 0) {
		fld.css('background', '#FBE4E4');
		error = "Your " + name + " is requried.<br>";
	} else {
		fld.css('background', inputBG);
	}
	return error;   
}

// buy page number verification
function validateNum(fld, length, name) {
	var error = "";
	var stripped = fld.val().replace(/[\(\)\.\-\ ]/g, '');     

	if (stripped == "") {
		error = "Your " + name + " is required.<br>";
		fld.css('background', '#FBE4E4');
	} else if (isNaN(stripped)) {
		error = "Your " + name + " contains illegal characters.<br>";
		fld.css('background', '#FBE4E4');
	} else if (!(stripped.length == length)) {
		error = "Your " + name + " is the wrong length.<br>";
		fld.css('background', '#FBE4E4');
	} else {
		fld.css('background', inputBG);
	}
	return error;
}

//validate coupon code
function validateCoupon(){
	var coupon = $('#coupon').val();
			$.ajax({
				url: "/application/checkCoupon.php?code=" + coupon,
				success: function(data) {
					switch (data) {
						case '0':
							$("#coupon").attr("value","");
							$('#couponMsg').css('color', 'red').html('Invalid coupon code').fadeIn('medium');
							break;
						case '1':
							$("#coupon").attr("value","");
							$('#couponMsg').css('color', 'red').html('Coupon has expired :-(').fadeIn('medium');
							break;
						case '2':
							$("#coupon").attr("value","");
							$('#couponMsg').css('color', 'red').html('Coupon all used up!');
							break;
						case '3':
							$("#coupon").attr("value","");
							$('#couponMsg').css('color', 'red').html('Promotion did not start yet!');
							break;
						default:
							$('#couponMsg').css('color', '#339900').html(data).fadeIn('medium');
							$('#paypalCoupon').val(coupon);
							$('#coupon1').val(coupon);
					}
				}
			});
	
	return false;
}

function showBox(id){
	if($('#'+id).css('display') == 'none') {
		$('#'+id).fadeIn('fast');
	} else {
		$('#'+id).fadeOut('fast');
	}
}

// ==================
// = Misc Functions =
// ==================

// if a phone number starts with 1 (so it's USA), format (xxx) xxx-xxxx
function formatPhone(number){
	// if the first digit is a 1
	if (number.substring(0, 1) == '1') {
		return '(' + number.substring(1, 4) + ') ' + number.substring(4, 7) + '-' + number.substring(7, 11);
	} else {
		return number;
	}
}

function confirmMsg(msg,url) {
if(confirm(msg)) location.href = url;
}



// onload, if you're making a call, trigger the get status every second
// for general pranks and robot dial
function triggerGetStatus(){
	// if the callID div exists, it means that a call has been made
	// so run the get status function every second
	// don't run it if it's a scheduled call
	if ($('#generalPrankCallID').length != 0) {
		getStatusInterval = setInterval("getStatus()", 1000);
	}
}

var howlongisit = 0;

// checks the status of a current call
// for general pranks and robot dial
function getStatus(){
	// set the query data
	var callID = $('#generalPrankCallID').html();
	howlongisit++;
	$.ajax({
		type: 'POST',
		url: "/application/prankStatus.php?callID=" + callID,
		success: function(data) {
			// set the status display
			var callStatus = $('#callStatus');

			// change the status content if the call status changes and handle when the call ends
			switch (data) {
				case "0":
					// set the status message
					callStatus.html('<img src="/images/status_delivered.gif" />');

					// stop checking the status
					clearInterval(getStatusInterval);
					break;
				case "1":
					if(howlongisit > 120) { alert("I'm not gonna lie. This probably wasn't received. :(");  clearInterval(getStatusInterval); callStatus.html('<img src="/images/status_undeliverable.gif" />'); }
					break;
				case "9":
					// set the status messase
					callStatus.html('<img src="/images/status_undeliverable.gif" />');

					// stop checking the status
					clearInterval(getStatusInterval);
					break;
			}
		}
	});
}

// validate block my number
function validateBlock(){
	error = false;
	
	var phone1 = $('#phone1').val();
	var phone2 = $('#phone2').val();
	var phone = phone1 + phone2;


	// blank or not a number
    if (phone1 == "" || phone2 == "" || isNaN(phone)) {
		error = true;
		$('#blockMsg').removeClass('notice').addClass('error').html('Please enter a proper numeric phone number.').fadeIn('medium');
		$('#phone2').focus();
    }

	if (phone.length >= 16) {
		error = true;
		$('#blockMsg').removeClass('notice').addClass('error').html('Your number needs to be less than 16-digits long.').fadeIn('medium');
		$('#phone2').focus();
	}
	
	if (phone.length < 9) {
		error = true;
		$('#blockMsg').removeClass('notice').addClass('error').html('Your number is too short.').fadeIn('medium');
		$('#phone2').focus();		
	}

	if (!error) {
		var agree = confirm("Are you sure you want to add your number to the PrankTXT Do Not Text list?");
		if (agree) {
			$.ajax({
				url: "/application/block.php?phone1=" + phone1 + '&phone2=' + phone2,
				success: function(data) {
					switch (data) {
						case '0':
							$('#blockMsg').removeClass('notice').addClass('error').html('That number is already on the block list.').fadeIn('medium');
							break;
						case '1':
							$('#blockMsg').removeClass('error').addClass('notice').html('Your number was added successfully.').fadeIn('medium');
							break;
						case '2':
							$('#blockMsg').removeClass('notice').addClass('error').html('Please enter a country code.').fadeIn('medium');
							break;
					}
				}
			});
		}
	}
	
	return false;
}



