$(function(){
	twitterShare();
	indexTabs();
	indexRollover();
	indexCookie();
	mobile();
	triggerPrankCount();
	siteDown();
	tooltipsHandler();
	doclear();
	getCallCost();
	triggerGetStatus();
	help();
	messageLength();
	triggerEvilOperatorStatus();
	selectAll();
	ringEmailExpand();
	triggerRingStatus();
	commentsPopup();
	buyPage();
	paypalRedirect();
	dateTime();
	format();
	refreshPhoneBook();
	viewContactsBox();
});

// open the twitter share window in a greybox
function twitterShare(){
	$('#twitterShare').click(function(){
		GB_show('Share us on Twitter', '/twitterShare.php', '260', '400');
	});
}

// fetaured and popular rollover on index
function indexTabs(){
	$('#hover').mouseover(function(){
		$(this).removeClass('prank_tab2').addClass('prank_tab1');
	}).mouseout(function(){
		$(this).removeClass('prank_tab1').addClass('prank_tab2');
	});
}

function indexRollover(){
	// add the shadows
	$('.prank_pic, .prank_pic2').each(function(){
		$(this).before('<img class="prank_shadow" src="/images/prankShadow.png">');
	});
	
	// change the positioning for the shadows and pics
	$('.prank_shadow').css('position', 'absolute').css('top', '0px');
	$('.prank_pic, .prank_pic2').css('top', '-3px').css('right', '3px');
	
	// only rollover on the index page, more page, and listen page
	if ($('.indexPrankContainer').length != 0 || $('#more').length != 0 || $('#hotPranksContainer').length != 0) {
		$('.prank, .listenPrank').mouseover(function(){
			$(this).children('.prank_pic, .prank_pic2').stop().animate({top: '0px', right: '0px'}, 200);
		}).mouseout(function(){
			$(this).children('.prank_pic, .prank_pic2').stop().animate({top: '-3px', right: '3px'}, 200);
		});
	}
}

// handle showing the index top info and setting cookies
function indexCookie(){
	if (location.pathname == '/' || location.pathname == '/index.php') {
		// hide the intro
		$('#indexHide').click(function(){
			// fade out the promo
			$('#indexPromo').slideUp('medium', function(){
				$('#indexOpen').fadeIn('medium');
			});

			// set the cookie state
			$.cookie("intro", "hide", { expires: 7 });
		});
		
		// show the intro
		$('#indexShow').click(function(){
			// fade out the show link
			$('#indexOpen').fadeOut('fast', function(){
				// fade the promo elements in
				$('#indexPromo').slideDown('medium');
			});
			
			// set the cookie stat
			$.cookie("intro", "show", { expires: 7 });
		});
		
		// index expand hover
		$('#indexShow').mouseover(function(){
			$(this).children('div').removeClass('indexExpandOff').addClass('indexExpandOn');
		}).mouseout(function(){
			$(this).children('div').removeClass('indexExpandOn').addClass('indexExpandOff');
		});

		// index close hover
		$('#indexHide').mouseover(function(){
			$(this).children('div').removeClass('indexCloseOff').addClass('indexCloseOn');
		}).mouseout(function(){
			$(this).children('div').removeClass('indexCloseOn').addClass('indexCloseOff');
		});
	}
}

function removePromo() {
	$('#indexPromo').slideUp('medium', function(){
		$('#indexOpen').fadeIn('medium');
	});
}

function mobile(){
	// show the android greybox
	$('#mobileAndroid').click(function(){
		GB_show('Download for Android', '/application/android.php', '400', '650');
		removePromo();
	});
	
	// show the blackberry greybox
	$('#mobileBlackberry').click(function(){
		GB_show('Download for Blackberry', '/application/blackberry.php', '400', '650');
		removePromo();
	});

	// show the blackberry greybox
	$('#mobileApple').click(function(){
		GB_show('Download for Apple iPhone/iPod/iPad', '/application/iphoneipod.php', '400', '750');
		removePromo();
	});

	// show the email form
	$('#clickEmail').click(function() {
		$('#showEmail').slideDown('medium');
		return false;
	});
}

// start updating number of pranks
function triggerPrankCount(){
	if ($('#prankcounter').length != 0) {
		// get the on load number of calls
		var initialCount;

		$.ajax({
			url: "/application/prankCounter.php",
			success: function(data) {
				// initialize the odometer with the returned data
				odometer = $('#prankcounter').odometer({
					counterStart: data,
					heightNumber: 50,
					widthNumber: 37
				});
				
				// trigger an update every two seconds
				getCounterInterval = setInterval("getPrankCount()", 2000);
			}
		});        
	}
}

// the actuall prank count updater
function getPrankCount(){
	odometer.trigger('advanceCounter');
}

// proxy check and redirect
function siteDown(){
	if (location.pathname == "/pranks.php" || location.pathname == "/pranktext.php" || location.pathname == "/prankring.php" || location.pathname == "/prankevil.php") {
		var locationstr = location.href;
		var locationwhere = locationstr.indexOf('http://www.prankdial.com');
		if (locationwhere != 0) {
			// window.location = "/temporarydown.html";
		}
	}
}

// handles calling the hover tooltips
function tooltipsHandler(){
	if ($('#header').length != 0) {
		$('#logoquestion').mouseover(function(){
			tooltip('Prankdial: Calling people with the intention to prank them', $(this));
		}).mouseout(function(){
			tooltip('');
		});
	}
	
	// token tooltip
	if ($('#tokenTooltip').length != 0) {
		$('#tokenTooltip').mouseover(function(){
			tooltip('Tokens make PrankDial more awesome. Click on the Buy button for more info.', $(this));
		}).mouseout(function(){
			tooltip('');
		});
	}
	
	// // shop tooltip
	// if ($('a.shopLink').length != 0) {
	// 	$('a.shopLink').mouseover(function(){
	// 		tooltip('<span style="color: #f00;"><b>NEW!</b></span> Now you can shop for other cool pranks like fart machines!', $(this));
	// 	}).mouseout(function(){
	// 		tooltip('');
	// 	});
	// }

	// international notice tooltip
	if ($('#internationalNotice').length != 0) {
		$('#internationalNotice').mouseover(function(){
			tooltip('We\'re still testing this (in alpha), if there are any problems, please contact us!', $(this));
		}).mouseout(function(){
			tooltip('');
		});
	}

	// buy tokens info on prank page
	if ($('a#prankBuyTokens').length != 0) {
		$('a#prankBuyTokens').mouseover(function(){
			tooltip('Prank whenever you want, as much as you want with PrankDial tokens. No more restrictions on pranking, click for more info.', $(this));
		}).mouseout(function(){
			tooltip('');
		});
	}
	
	// free tokens tooltip
	if ($('a#earnFreeTokens').length != 0) {
		$('a#earnFreeTokens').mouseover(function(){
			tooltip('Earn free tokens by simply filling out offers or you can even purchase them with your cell phone.', $(this));
		}).mouseout(function(){
			tooltip('');
		});
	}
	
	// robotdial tooltips
	
	// voice type
	if ($('#voiceTypeTooltip').length != 0) {
		$('#voiceTypeTooltip').mouseover(function(){
			tooltip('Choose from an array of voices, whether it be a girl or a guy, a person with an accent or just a normal voice, choose how you want the computer to sound!', $(this));
		}).mouseout(function(){
			tooltip('');
		});
	}
	
	// voice speed
	if ($('#voiceSpeedTooltip').length != 0) {
		$('#voiceSpeedTooltip').mouseover(function(){
			tooltip('How fast do you want the voice to talk?', $(this));
		}).mouseout(function(){
			tooltip('');
		});
	}
	
	// voice pitch
	if ($('#voicePitchTooltip').length != 0) {
		$('#voicePitchTooltip').mouseover(function(){
			tooltip('Do you want the computer\'s voice ridiculously high like a chipmunk or low like Darth Vader.', $(this));
		}).mouseout(function(){
			tooltip('');
		});
	}
	
	// voice effect
	if ($('#voiceEffectTooltip').length != 0) {
		$('#voiceEffectTooltip').mouseover(function(){
			tooltip('Lots of cool voice effects to give your prank an extra flare.', $(this));
		}).mouseout(function(){
			tooltip('');
		});
	}
}

// tooltip function
// to show, pass a message (i.e., 'your message') and the object that you want the message next to (i.e., $('#indexTooltip'))
// to hide, pass a blank message ('')
function tooltip(msg, object) {
	if (msg == '') { // if no arguments are passed then hide the tootip
		$('#tooltip').css('display', 'none');
	} else { // show
		// get the position of the object
		position = object.position();
		height = object.height();
		$("#tooltip").html(msg).css('left', position.left).css('top', position.top + height + 10).css('display', 'block');
	}
}

// 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');

			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();
		});
	}
}

// show the email field when you've got record checked and vv
function ringEmailExpand() {
	if ($('#thering').length != 0) {
		// show the email on load if record is checked
		if ($('#dorec').attr('checked') == true) {
			$('#ringEmail').css('display', 'block');
		}

		// toggle show states with recording checkbox
		$('#dorec').click(function(){
			// show or hide the email div
			if ($(this).attr('checked') == true) {
				$('#ringEmail').fadeIn('medium');
			} else {
				$('#ringEmail').fadeOut('medium');
			}
		});
	}
}

// submitting a prank recording from the listenIndividual page
function submitRecording(){
	// get the hidden variables from the page
	var shortname = $('#listenShortname').val();
	var title = $('#listenTitle').val();
	var id = $('#listenID').val();
	var auth = $('#listenAuth').val();
	var yourName = $('#yourName').val();

	var queryString = "shortname=" + shortname + "&title=" + title + "&id=" + id + "&auth=" + auth + "&yourname=" + yourName;

	$.ajax({
		url: "/application/submitRecording.php?" + queryString,
		success: function(data) {
			switch (data) {
				case '0':
					$('#submitRecordingMsg').removeClass('notice').addClass('error').html('Your name is too long.').fadeIn('medium');
					break;
				case '1':
					$('#submitRecordingMsg').removeClass('notice').addClass('error').html('Something is missing!').fadeIn('medium');
					break;
				case '2':
					$('#submitRecordingMsg').removeClass('notice').addClass('error').html('Invalid Submission.').fadeIn('medium');
					break;
				case '3':
					$('#submitRecordingMsg').removeClass('notice').addClass('error').html('You already submitted this prank!').fadeIn('medium');
					break;
				case '4':
					$('#submitRecordingMsg').removeClass('error').addClass('notice').html('Thanks for your submission!').fadeIn('medium');
					break;
			}
		}
	});
	
	return false;
}

// open the comments in a greybox
function commentsPopup(){
	$('.commentsLink').click(function(){
		// get the variables
		var contentID = $('#commentContentID').html();
		var title = $('#commentTitle').html();
		var scco = $('#commentSCCO').html();
		
		// show the comments box
		GB_show('&nbsp;', '/application/comments.php?contentid=' + contentID + '&title=' + title + '&scco=' + scco, '600', '400');
	});
}

// buy page interaction
function buyPage(){
	if ($('.tokencontainer').length != 0) {
		// onload, clear email and tokens
		$('#email, #email1, #tokens1').val('');

		//new additions
		$('#email').change(function(){
			$('#email1').val($('#email').val());
		});

		// when you select a tokens package
		$('.bin1').click(function(){
			// unhightlight all the boxes
			$('.bin1').removeClass('bin1on');
			
			// set the hightlighted box
			$(this).addClass('bin1on');
			
			// 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');
			
			// clear all form elements in cc
			$('#creditOptions .field2 input').val('');
			
			// show the credit card options
			$('#creditOptions').slideDown('medium');
		});
		
		// on paypal click, hide credit
		$('#paypal').click(function(){
			$('#creditOptions').slideUp('medium', function(){
				$('#buyCreditError').fadeOut('medium');
			});
		});
	}
}

// if you're on the paypal redirect page, submit the form automatically
function paypalRedirect(){
	if ($('#paypalRedirect').length == 1) {
		$('#paypalRedirect').submit();
	}
}

// string for input background
var inputBG = 'transparent url(/images/bg_input.gif) repeat-x center top';

// handle datepicker and time disable on prank pages
function dateTime(){
	if ($('#date').length != 0) {
		// get the year, month, and day
		today = new Date();
		year = today.getFullYear();
		month = today.getMonth();
		date = today.getDate();
		
		// initialize the date picker
		$("#date").datepicker({minDate: new Date(year, month, date)});
		
		// set todays date
		var myDate = new Date();
		var prettyDate =(myDate.getMonth()+1) + '/' + myDate.getDate() + '/' + myDate.getFullYear();
		$("#date").val(prettyDate);
		
		
		// set the half based on the current time
		currentHour = new Date().getHours();
		if (currentHour > 11) {
			$('#half').val('pm');
			half = 'pm';
		} else {
			half = 'am';
		}
		
		// set the hours
		$('#hour').html(timeString('hour', half, 'load'));

		// set the minutes
		$('#minute').html(timeString('minute', half, 'load'));
		
		// reset the hours on changing the half
		$('#half').change(function(){
			$('#hour').html(timeString('hour', $(this).val()));
		});

		// see if schedule is checked
		var schedule = $('#scheduleCheckbox').attr('checked');

		// expand the schedule if checked
		if (schedule) {
			$('#schedule').css('display', 'block');
		}
		
		$('#scheduleCheckbox').click(function(){
			if ($(this).attr('checked') == true) {
				$('#schedule').fadeIn('medium');
			} else {
				$('#schedule').fadeOut('medium');
			}
		});
	}
}

// return hour or minute select strings. pass hour/minute and am/pm.
function timeString(type, half, load) {
	// set the default times
	if (load == 'load') {
		var currentDate = new Date();
		var currentHour = currentDate.getHours();
		
		if (currentHour > 12) {
			var currentHour = currentHour - 12;
			$('#half').val('pm');
		}

		currentMinute = currentDate.getMinutes();
	} else {
		var currentHour = $('#hour').val();
	}
	
	// handle hours disable rules
	if (type == 'hour') {
		max = 12;

		if (half == 'am') {
			// set the time restricition, only if not a token user
			if (!$('#hour').attr('class').match(/noRestriction/)) {
				disabledMin = 0;
				disabledMax = 6;
			} else {
				disabledMin = 999;
				disabledMax = 999;
			}
		} else {
			disabledMin = 999;
			disabledMax = 999;
		}
	} else {
		max = 60;
	}
	
	counter = 0;
	returnString = '';
	while (counter < max) {
		// set 0 to 12 if your in hours
		if (counter ==  0 && type == 'hour') {
			displayValue = 12;
		} else {
			displayValue = counter;
		}
		
		// if it's minutes, set the leading zero
		if (type == 'minute') {
			if (counter < 10) {
				displayValue = '0' + counter.toString();
			}
		}
		
		// open the option
		returnString += '<option value="';
		
		// set the value (add the leading zero if minutes)
		if (type == 'minute' && counter < 10) {
			returnString += '0' + counter.toString();
		} else {
			returnString += counter;
		}
		returnString += '" ';
		
		// add disabled if it's the morning
		if (type == 'hour') {
			if (counter >= disabledMin && counter <= disabledMax) {
				returnString += 'disabled="disabled"';
			}
		}
		
		// set the selected hour
		if (type == 'hour') {
			// destroy currentHour if it's in the retricted range
			if (currentHour > disabledMin && currentHour < disabledMax) {
				currentHour = 999;
			}
			
			if (counter == currentHour) {
				returnString += ' selected="selected"';
			}
		}

		// set the selected minute (only on load)
		if (load) {
			if (type == 'minute') {
				if (counter == currentMinute) {
					returnString += ' selected="selected"';
				}
			}
		}
		
		// close the option
		returnString += '>' + displayValue + '</option>';
		
		// increment the counter
		counter ++;
	}
	
	return returnString;
}

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 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, #contactphone1').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 unformat(value){
	value = value.replace(/\(/, '');
	value = value.replace(/\)/, '');
	value = value.replace(/ /g, '');
	value = value.replace(/\-/, '');
	value = value.replace(/_/g, '');
	
	return value;
}


// =====================
// = Prank Status Code =
// =====================

// call timer
index = 0;

function timer_tick() {
	index = index + 1;
	$("#timer").html(index + ' seconds');
}

timer = false;


// 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 && $('#scheduledSubmitted').length == 0) {
		getStatusInterval = setInterval("getStatus()", 1000);
	}
}

// checks the status of a current call
// for general pranks and robot dial
function getStatus(){
	// set the query data
	var callID = $('#generalPrankCallID').html();
	var recording = $('#recordingVariable').html();
	var shortname = $('#shortname').html();

	$.ajax({
		type: 'POST',
		url: "/application/prankStatus.php?callID=" + callID,
		success: function(data) {
			// set the status display
			var callStatus = $('#callStatus');
			
			// if the timer has been turned on, run the increment function
			if (timer) {
				timer_tick();
			}

			// 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('Person is hearing the prank call...');
					
					// start the timer
					$('#timer').fadeIn('medium');

					timer = true;

					// if recording, show the recording image
					if (recording != 0) {
						$('#recording').fadeIn('medium');
					}
					break;
				case "1":
					// set the status message
					callStatus.html('Person did not pick up.');
					
					// get rid of the spinner
					$('#loader').fadeOut('medium');
					
					// stop checking the status
					clearInterval(getStatusInterval);
					break;
				case "2":
					// set the status messase
					callStatus.html('Prank call ended.');
					
					// get rid of the spinner
					$('#loader').fadeOut('medium');
					
					// if there was recording, add the link to listen
					if (recording != 0) { 
						var recordingLink = $('#recordingLink').html();
						$('#recording').html("Here is the link to your recording:<br /><a class='blue' href='/listen/" + shortname + '_' + recordingLink + "'>http://" + location.host + "/listen/&#8203;" + shortname + '_' + recordingLink + "</a>");
					}

					// stop checking the status
					clearInterval(getStatusInterval);
					break;
				case "3":
					callStatus.html('Connecting your prank call...');
					break;
			}
		}
	});
}

// onload, if you're making a call, trigger the get status every second
// just for evil operator
function triggerEvilOperatorStatus(){
	// if the callID div exists, it means that a call has been made
	// so run the get status function every second
	if ($('#evilOperatorCallID').length != 0) {
		getStatusInterval = setInterval("getEvilOperatorStatus()", 1000);
	}
}

// checks the status of a current evil operator call
// just for evil operator
function getEvilOperatorStatus(){
	// get the call data
	var callID = $('#evilOperatorCallID').html();
	var recording = $('#recordingVariable').html();
	var phone1 = $('#phone1').html();
	var phone2 = $('#phone2').html();

	// if the timer has been turned on, run the increment function
	if (timer) {
		timer_tick();
	}

	var randomnumber=Math.floor(Math.random()*500);

	$.ajax({
		url: "/application/evilOperatorStatus.php?callID=" + callID + '&random=' + randomnumber,
		success: function(data) {
			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(formatPhone(phone1) + ' did not pick up.');

					// get rid of the spinner
					$('#loader').fadeOut('medium');
					
					// stop checking the status
					clearInterval(getStatusInterval);

					break;
				case "1":
					// set the status message
					callStatus.html(formatPhone(phone2) + ' did not pick up.');
					
					// get rid of the spinner
					$('#loader').fadeOut('medium');
					
					// stop checking the status
					clearInterval(getStatusInterval);

					break;
				case "2":
					// set the status messase
					callStatus.html('Connecting your victims...');
					
					break;
				case "3":
					callStatus.html('Prank call complete.');

					// get rid of the spinner
					$('#loader').fadeOut('medium');

					if (recording != 0) { 
						var recordingLink = $('#recordingLink').html();
						$('#recording').html("Here is the link to your recording: <a class='blue' href='/listen/eviloperator_" + recordingLink + "'>http://" + location.host + "/listen/&#8203;eviloperator_" + recordingLink + "</a>");
					}

					clearInterval(getStatusInterval);
					break;
				case "4":
					callStatus.html('Your victims are chatting...');
					
					// start the timer
					$('#timer').fadeIn('medium');

					timer = true;
					
					if (recording != 0) {
						$('#recording').fadeIn('medium');
					}

					break;
			}
		}
	});
}

// onload, if you're making a call, trigger the get status every second
// just for the ring prank
function triggerRingStatus(){
	// if the callID div exists, it means that a call has been made
	// so run the get status function every second
	if ($('#ringCallID').length != 0) {
		getStatusInterval = setInterval("getRingStatus()", 1000);
	}
}

// checks the status of a current ring prank
function getRingStatus(){
	// set the query data
	var callID = $('#ringCallID').html();
	var recording = $('#recordingVariable').html();

	// if the timer has been turned on, run the increment function
	if (timer) {
		timer_tick();
	}

	$.ajax({
		url: "/application/ringStatus.php?callID=" + callID,
		success: function(data) {
			var callStatus = $('#callStatus');

			switch (data) {
				case '0':
					callStatus.html('Waiting for the person to watch the video...');
					break;
				case '1':
					callStatus.html('Person is watching the ring video...');
					break;
				case '2':
					callStatus.html('Person is hearing the prank call...');
					
					// start the timer
					$('#timer').fadeIn('medium');

					timer = true;
					
					// show the record div if recording
					if (recording != 0) {
						$('#recording').fadeIn('medium');
					}
					
					break;
				case '3':
					callStatus.html('Person did not pick up.');
					
					// get rid of the spinner
					$('#loader').fadeOut('medium');
					
					// stop checking the status
					clearInterval(getStatusInterval);

					break;
				case '4':
					callStatus.html('Prank call ended.');
					
					// get rid of the spinner
					$('#loader').fadeOut('medium');
					
					// stop checking the status
					clearInterval(getStatusInterval);
					
					if (recording != 0) { 
						var recordingLink = $('#recordingLink').html();
						$('#recording').html("Here is the link to your recording: <a class='blue' href='/listen/ringprank_" + recordingLink + "'>http://" + location.host + "/listen/&#8203;ringprank_" + recordingLink + "</a>");
					}
					
					break;
			}
		}
	});
}


// ===================
// = Validation Code =
// ===================

// set the global validation flag
var error = false;

// newsletter signup/unsubscribe
function newsletter() {
	var email = $('#email').val();

	// either register or unregister
	var action = $('#action').html();

	error = false;

	// validate the email
	validateReqEmail();

	if (!error) {
		$.ajax({
			url: "/application/newsletterAjax.php?email_address=" + email + "&action=" + action,
			success: function(data) {
				switch (data) {
					case '0':
						$('#newsletterError').html('that email is already signed up').css('background', '#f00')
						break;
					case '1':
						$('#newsletterError').html('thanks for signing up!').css('background', 'green');
						break;
					case '2':
						$('#newsletterError').html('that email is\'t signed up').css('background', '#f00');
						break;
					case '3':
						$('#newsletterError').html('you have been unsubscribed. thanks for reading!').css('background', 'green');
						break;
				}
				
				// show it if hidden
				if ($('#newsletterError').css('display') == 'none') {
					$('#newsletterError').fadeIn('medium');
				}
			}
		});
	}

	return false;
}

// 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 ($('#indexPromo').length != 0) {
		removePromo();
	}

	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;
}


// 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(prankName, loggedIn) {
	// set the error flag
	error = false;

	// get the phone number
	phone = $('#phone1').val() + unformat($('#phone2').val());

	// get country code
	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
		if (loggedIn) {
			$('#phoneError').html("Please enter a proper numeric phone number.").fadeIn('medium');
		} else {
			$('#phoneError').html("Please enter a 10-digit phone number.").fadeIn('medium');
		}

		// give the phone number focus
		$('#phone1').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
		if (loggedIn) {
			$('#phoneError').html("Your friend's number needs to be the proper length.").fadeIn('medium');
		} else {
			$('#phoneError').html("Your friend's number needs to be 10 digits long.").fadeIn('medium');
		}
		
		$('#phone1').focus();
	} else {
		$('#phoneError').fadeOut('medium');
	}

	// get the caller id
	cid_num = $('#callid1').val() + unformat($('#callid2').val());

	// caller id is not 1 or blank
	if (cid_num != "1" && cid_num != "" && cid_num != '1area + phone' && cid_num != '1area+phone') {
		// right length, but not a number
		if (isNaN(cid_num)) {
			error = true;

			$('#cidError').html("Caller ID needs to be a proper number.").fadeIn('medium');

			$('#callid1').focus();
		// too short
		} else if (cid_num.length < 11) {
			error = true;

			// different messages for logged in or not
			if (loggedIn) {
				$('#cidError').html("Caller ID number needs to be the proper number of digits.").fadeIn('medium');
			} else {
				$('#cidError').html("Caller ID number needs to be at least 10-digits long.").fadeIn('medium');
			}
			
			$('#callid1').focus();
		} else {
			$('#cidError').fadeOut('medium');
		}
	} else {
		$('#cidError').fadeOut('medium');
	}
	
	if ($('#callcost').html() == "Wrong Dial Code!") {
		error = true;

		$('#phoneError').html("Please enter a correct dial code.").fadeIn('medium');
    }

	// schedule validation
	validateSchedule();

	// robotdial  validation
	if (prankName == 'robotdial') {
		// if there is no message
		var msg = $('#message').val();
		
		// set the max number of characters for a message
		if (loggedIn) {
			msgMax = 220;
		} else {
			msgMax = 120;
		}
		
		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');
		}

		// did they agree to the tos?
		validateTOS();
	}

	if (!error) {
		return true;		
	} else {
		return false;
	}
}

// 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 PrankDial Do Not Call 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;
}

// validate the boxes in evil operator
function validateEvilOperator(loggedIn){
	error = false;

	var phone1 = '1' + unformat($('#phone12').val());
	var phone2 = '1' + unformat($('#phone22').val());

	// Number are the same
	if (phone1 != '1area+phone' && phone2 != '1area+phone' && phone1 == phone2) {
		error = true;

		if ($('#error').length == 0) {
			$('#sendPrankForm').before('<div id="error" class="error" style="margin: 20px 0 0 0;">You can\'t connect the same numbers!</div>');
			$('#error').fadeIn('medium');
		} else {
			$('#error').html('You can\'t connect the same numbers!').fadeIn('medium');
		}
	} else {
		$('#error').fadeOut('medium');
	}

	// Phone 1
	if (phone1 == "" || isNaN(phone1) || phone1 == '1area + phone') {
		error = true;
		$('#phone1Error').html("Please enter a number.").fadeIn('medium');
	} else if (phone1.length != 11) {
		error = true;
		$('#phone1Error').html("Please enter the right number of digits.").fadeIn('medium');
	} else {
		$('#phone1Error').fadeOut('medium');
	}

	// Phone 2
	if (phone2 == "" || isNaN(phone2) || phone2 == '1area + phone') {
		error = true;
		$('#phone2Error').html("Please enter a number.").fadeIn('medium');
	} else if (phone2.length != 11) {
		error = true;
		$('#phone2Error').html("Please enter the right number of digits.").fadeIn('medium');
	} else {
		$('#phone2Error').fadeOut('medium');
	}

	// schedule validation
	validateSchedule();

	// Terms of Service
	validateTOS();

	if (!error) {
	    return true;
	} else {
		return false;
	}
}

// validation for the ring prank
function validateRing(){
	error = false;
	var phone = 1 + unformat($('#phone2').val());
	var msg = $('#message').val();
	var msgMax = $('#messageMax').html();
	var recording = $('#dorec').attr('checked');

	// validate email, only if recording
	if (recording == true) {
		validateNotReqEmail();
	}

	// message validation
	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');
	}

	// personal info
	if ($('#personal').val() == '') {
		error = true;
		$('#personalError').html("Enter a piece of personal information about your victim.").fadeIn('medium');
	} else {
		$('#personalError').fadeOut('medium');
	}

	// to phone
	if (phone == "" || isNaN(phone)) {
		error = true;
		$('#phoneError').html("Please enter a number.").fadeIn('medium');
	} else if (phone.length < 10) {
		error = true;
		$('#phoneError').html("Please enter the right number of digits.").fadeIn('medium');
	} else {
		$('#phoneError').fadeOut('medium');
	}

	// Terms of Service
	validateTOS();
	
	if (!error) {
	    return true;
	} else {
		return false;
	}
}

// make sure you don't submit an empty comment
function validateComment(){
	var message = $('#message').val();
	var messageMax = $('#messageMax').html();

	error = false;
	
	if (message == '') {
		error = true;
		$('#messageError').html('Please enter a comment.').fadeIn('medium')
	} else if (message.length > messageMax) {
		error = true;
	} else {
		$('#messageError').fadeOut('medium');
	}
	
	if (error) {
		return false;
	} else {
		return true;
	}
}

// validation from the tokens_free page
function validateFreeTokens() {
	error = false;
	var mail = $('#email').val();

	// validate email
	validateReqEmail();

	if (!error) {
		return true;
	} else {
		return false;
	}
}

// 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 on mobile form
function validateMobile(){
	error = false;

	validateReqEmail();
	
	if (!error) {
		return true;
	} else {
		return false;
	}
}

// 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 += validateEmpty($('#state'), "state");
	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(){
	var reason = '';

	// get the email
	var email = $('#email').val();

	// set the hidden fields
	$('#paypalEmail').val(email);

	if (email == "") {
		reason += "Please enter your email.<br>";
	} else {
		if (!echeck(email)){
			reason += "Please enter your email in a correct format.<br>";
		}
	}

	if ($('#tokens1').val() == ""){
		reason += "Please select a token package.<br>";
	}

	if (reason != '') {
		$('#buyPaypalError').html(reason).fadeIn('medium');
		return false;
	} else {
		$('#buyPaypalError').fadeOut('medium');
		return true;
	}
}


// =====================
// = Validation Pieces =
// =====================
// validation functions that you can call from master functions

// make sure a scheduled call is in the future
function validateSchedule(){
	// get all parts of the time (if scheduling is checked)
	if ($('#scheduleCheckbox').attr('checked') == true) {
		// get all the variables
		var date = $('#date').val().split('/');
		var month = date[0];
		var day = date[1];
		var year = date[2];
		var hour = $('#hour').val();
		var minute = $('#minute').val();
		var half = $('#half').val();
		var email = $('#email').val();
		
		// convert to 24hr time
		if (half == 'pm') {
			hour = parseInt(hour) + 12;
		}
		
		// check for blank date
		if (date == '') {
			error = true;
			$('#timeError').html('Please enter a date.').fadeIn('medium');
		} else {
			// assemble the date into a timestamp
			timestamp = month + ' ' + day + ', ' + year + ' ' + hour + ':' + minute + ':00';
			userDate = new Date(timestamp);

			now = new Date();
			
			// see if their date is in the past
			if (now > userDate) {
				error = true;
				$('#timeError').html('The call must be sent in the future.').fadeIn('medium');
			} else {
				$('#timeError').fadeOut('medium');
			}
		}

		// validate email - required if recording
		if ($('#dorec').attr('checked')) {
			validateReqEmail();
		} else {
			validateNotReqEmail();
		}
	}
}

// make sure terms of service is checked
function validateTOS(){
	if (!$('#tos').attr('checked')) {
		error = true;
		$('#tosError').fadeIn('medium');
	} else {
		$('#tosError').fadeOut('medium');
	}
}

// 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;
		$('#emailError').html("Please enter your email.").fadeIn('medium');
	} else {
		if (!echeck(email)){
			error = true;
			$('#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;
}

// 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');
	}
}

// ==================
// = PhoneBook Functions =
// ==================
function changePhoneContent() {
	$('#contactname').val('');
	$('#contactphone1').val(1);
	$('#contactphone2').val('');
	if ($('#addcontact').css('display') == 'none') {
		$('#phonelist').slideUp();
		$('#addcontact').slideDown();
		$("#addbutton").hide();
		$("#backbutton").show();
	} else {
		refreshPhoneBook();
		$('#phonelist').slideDown();
		$('#addcontact').fadeOut('medium');
		$("#backbutton").hide();
		$("#addbutton").show();
	}
}

function addContact() {
	var shortname = $('#listenShortname').val();
	var name = $('#contactname').val();
	var contactphone1 = $('#contactphone1').val();
	var contactphone2 = $('#contactphone2').val();
	var authcode = $('#tokenidauth').html();
	var tokenid = $('#tokenidlogin').html(); 
	
	var queryString = "name=" + name + "&phone1=" + contactphone1 + "&phone2=" + contactphone2 + "&auth=" + authcode + "&tokenid=" + tokenid + "&view=add";

		$.ajax({
		url: "/application/getPhoneBook.php?" + queryString,
		success: function(data) {
			switch (data) {
				case '0':
					$('#addContactMsg').removeClass('notice').addClass('error').html('Name is too long.').fadeIn('medium');
					break;
				case '1':
					$('#addContactMsg').removeClass('notice').addClass('error').html('Phone number is required.').fadeIn('medium');
					break;
				case '2':
					$('#addContactMsg').removeClass('notice').addClass('error').html('Phone number is too short.').fadeIn('medium');
					break;
				case '3':
					$('#addContactMsg').removeClass('notice').addClass('error').html('You already added this phone number!').fadeIn('medium');
					break;
				case '4':
					$('#addContactMsg').removeClass('notice').addClass('error').html('Invalid submission.').fadeIn('medium');
					break;
				case '5':
					alert('Phone number added!');
					changePhoneContent();
					break;
			}
		}
	});
}

function deleteContact(phone1, phone2) {
	
	var authcode = $('#tokenidauth').html();
	var tokenid = $('#tokenidlogin').html(); 
	
	var queryString = "phone1=" + phone1 + "&phone2=" + phone2 + "&auth=" + authcode + "&tokenid=" + tokenid + "&view=delete";
		$.ajax({
		url: "/application/getPhoneBook.php?" + queryString,
		success: function(data) {
			switch (data) {
				case '0':
					$('#addContactMsg').removeClass('notice').addClass('error').html('Phone number not found.').fadeIn('medium');
					break;
				case '5':
					alert('Phone number deleted!');
					refreshPhoneBook();
					break;
			}
		}
	});
}

function refreshPhoneBook() {

	var authcode = $('#tokenidauth').html();
	var tokenid = $('#tokenidlogin').html();

	var queryString = "view=list&auth=" + authcode + "&tokenid=" + tokenid;
	if ($('#phonebook').length != 0) {
			$.ajax({
			url: "/application/getPhoneBook.php?" + queryString,
			success: function(data) {
				$("#phonecontainer").hide().html(data).fadeIn('medium');
			}
		});
	}

}

function viewContactsBox(inputID){		
		xOffset = 0;
		yOffset = 0;

	if ($('#phonebook').length != 0) {
if($('#phonebookcontainer').css('display') == 'none') {
	$("a.contactsButton").click(function(e){	
		$("#inputvalue").html(inputID);				  
		$("#phonebookcontainer")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px")
			.fadeIn("fast");		
    });	
} else {
		$("#phonebookcontainer").fadeOut("fast");
}
}

};

function insertPhone (country,phone) {
	viewContactsBox();
	var input = $('#inputvalue').html();
	$("#"+input+"1").val(country);
	$("#"+input+"2").val(phone);

}


// ==================
// = 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;
}
