var currentTimeout = null;
var Recaptcha;

// USED IN GRID COMPLETE AS A TOGGLE
var selectStatus = false;

/*
var xmlPrep = function(xml) {
	if($.browser.msie && typeof xml == 'string') {
		var origXml = xml;
		xml = new ActiveXObject("Microsoft.XMLDOM");
		xml.async = false;
		xml.loadXML(origXml);
	}

	return xml;
}
*/

var LabelReaction = function() {
	var groupName = $('input:radio',this).attr('name');

	$('form#buy label:has(input[name="'+groupName+'"])').removeClass('selected').css({
		'background-image'		: "url('/images/chk_off.png')"
	});

	// STUPID IE
	if($.browser.msie)
		document.getElementById($(this).attr('for')).checked = true;

	$(this).addClass('selected');
	$(this).css({
		'background-image'		: "url('/images/chk_on.png')"
	});

	// Show next step if amout is selected
	switch(groupName) {
		case 'purchase[amount]':
			$('form#buy li#step1 div.proceed').css('visibility','visible');
		break;
		case 'billing[shipto]':
			$('label:has(input[name="billing[shipto]"]:checked)').unbind('click').click(Buy.submitAmountModifier).click();
			$('label:has(input[name="billing[shipto]"]:checked)').unbind('click').click(LabelReaction);

			if($('input[name="billing[shipto]"]:checked').val() == 'false')
				$('#shippingInfo').css({'display':'block'}).addClass('validate');
			else
				$('#shippingInfo').css({'display':'none'}).removeClass('validate');
		break;
	}
};

var Buy = {
	Accordion : {
		currentStep : 1,
		complete : function(step) {
			this.currentStep = step+1;
			$('#step'+this.currentStep).addClass('allow');
			this.goTo(this.currentStep);
		},
		goBack : function() {
			var back = new Number($('li.allow[id^="step"]').length)-1;
			this.goTo($('li.allow[id^="step"]:nth-child('+back+')').attr('id').replace(/[^\d]/g,''));
			$('li.allow[id^="step"]:last-child').removeClass('allow');
			return;
		},
		goTo : function(step) {
			this.history[this.history.length] = this.currentStep;
			this.currentStep = step;
			this.openStep(step);
		},
		history : new Array(),
		openStep : function(step) {
			if(step > this.currentStep || !$('#step'+step).hasClass('allow'))
				return;

			$('form#buy li[id^="step"]').each(function() {
				if($(this).attr('id').replace(/[^\d]/g,'') > step) {
					$(this).removeClass('allow');

					// HIDE INNER DIV
					$('div',this).css({'display':'none'});
				}
			});

			/**
			 * Bounce Back?
			 *
			 * If the user bounces a step back, change the current step so
			 * that the user MUST resubmit data on the current step to ensure
			 * that the integrity of previous data was not altered.
			 */
			this.currentStep = step;

			// Activate first entry
			var activate = true;

			$('form#buy li[id^="step"]').addClass('inactive');
			while(step > 0) {
				if($('form#buy li.allow[id="step'+step+'"]').html()) {
					/**
					 * Activate
					 *
					 * Only activate ONE tab that is permissable, the remaining tabs
					 * will then be set to "complete" and will be allowed to "Bounce Back"
					 */
					if(activate) {
						$('form#buy li.allow[id="step'+step+'"]').removeClass('inactive').removeClass('complete').addClass('allow');

						// SHOW INNER DIV
						$('form#buy li.allow[id="step'+step+'"] div').each(function() {
							if(!$(this).hasClass('stayHidden'))
								$(this).css({'display':'block'});
						});

						// UNSET ACTIVATE
						activate = false;
					} else {
						$('form#buy li.allow[id="step'+step+'"]').removeClass('inactive').addClass('complete').addClass('allow');

						// HIDE INNER DIV
						$('form#buy li.allow[id="step'+step+'"] div').css({'display':'none'});
					}
				}
				step--;
			}

			/**
			 * Trigger Recharge / New Credit Card
			 *
			 * - The currently selected option must be triggered again to 
			 * - ensure that the page displays the correct data.
			 */
			if(this.currentStep == 2 && $(':input[name="replenishRecharge"]:checked').size())
				$(':input[name="replenishRecharge"]:checked').click();
		}
	},
	calculateGrandTotal : function() {
		var amount = new Number($('input[name="purchase[amount]"]:checked').val());
		if(Buy.couponEvaluation)
			amount = eval(Buy.couponEvaluation.replace(/\?/g,amount));

		if($('form#buy input:radio[name="purchase[hardcard]"]:checked').val() == '1')
			amount += new Number('4.99');
		
		$('#grandtotal font').html('$'+amount.toFixed(2));
	},
	couponEvaluation : null,
	createOrderReview : function() {
		$(document.body).css({'cursor':'progress'});
		$('#step3 div').addClass('TelTech_loading')
			.html('Please wait while the data is collected')
			.css({
				'display'			: 'block',
				'vertical-align'	: 'top'
			});

		$.post('/buy/ajax',{
			request	: 'removeData',
			parent	: 'transaction',
			key		: 'id'
		},function(xml) {
			if($(':input[name="replenishRecharge"]:checked').size() && $(':input[name="replenishRecharge"]:checked').val() == '1') {
				$('#step3 div').load('/buy/receipt/request/recharge-preview',function() {
					$('#step3 div').removeClass('TelTech_loading');
					$(document.body).css({'cursor':'default'});
				});
			} else {
				/**
				 * Bizarre errors!
				 *
				 * These are primarily in place to ensure that the session
				 * still exists by the time they hit submit!
				 */
				if(!$('billing',xml).text()) {
					alert('Missing billing information!');
					return false;
				}

				$('#step3 div').load('/buy/receipt/request/preview',function() {
					$('#step3 div').removeClass('TelTech_loading');
					$(document.body).css({'cursor':'default'});
				});
			}
		});
	},
	hardcard : '0',
	payment_method : null,
	receiptPage : function(paymentID) {
		return '/buy/receipt/purchase/true/payment_id/'+paymentID;
	},
	resume : function(xml) {
		var amount = new Number($('purchase',xml).find('amount').text());
		if(amount > 0) {
			Buy.calculateGrandTotal();

			$('label.amount:has(input[value="'+Math.round(amount)+'"])').click();
		}

		if($('purchase',xml).find('hardcard').text() == '1')
			$('label.hardcard[for="hardcard:1"]').add('label.hardcard[for="hardcard:1"] input').click();
	},
	resumeCheck : function(xml) {
		/*
		if($('data',xml).children().length > 0 && confirm('Would you like to pick up where you left off?'))
			Buy.resume(xml);
		else
			$.post('/buy/ajax',{request:'destroy'});
		*/
		$.post('/buy/ajax',{request:'destroy'});
	},
	saveData : function() {
		var split = $(this).attr('id').match(/(.*):(.*)/);
		if(split && split.length == 3) {
			$.post('/buy/ajax',{
				request : 'addData',
				data : 'parent='+split[1]+':key='+split[2]+':value='+escape($(this).val())
			});
		}
	},
	submitAmountModifier : function() {
		if($('input:checked',this).val()) {
			var parent,value;

			// Prepare the input to a formatted result
			if($(this).hasClass('amount')) {
				parent = 'purchase';
				value = new Number($('input:checked',this).val());
				value = value.toFixed(2);
			} else if($(this).hasClass('hardcard')) {
				parent = 'purchase';
				value = $('input:checked',this).val();
			} else if($(this).hasClass('ship_option')) {
				parent = 'billing';
				value = $('input:checked',this).val();
			}

			// Split up the input and dump the data in the appropriate location
			var split = $('input:checked',this).attr('id').match(/(.*):(.*)/);
			if(split && split.length == 3) {
				$.post('/buy/ajax',{
					request : 'addData',
					data : 'parent='+parent+':key='+split[1]+':value='+escape(value)
				});
			}

			/**
			 * Add it up!
			 *
			 * When changing a box label, update the grand total
			 */
			Buy.calculateGrandTotal();
		}
	},
	ValidateCoupon : function(xml) {
		var discount, evaluation;

		if($('error',xml).text())
			return alert($('error',xml).text());

		$.post('/buy/ajax',{
			request : 'addData',
			data : 'parent=purchase:key=coupon:value='+escape($('#coupon').val())
		});

		$('#coupon_container *').css({'display':'none'});
		$('#coupon_container span').css({'display':'inline-block'}).html('Coupon : "'+$('#coupon').val()+'"');

		setTimeout("parent.top.$.fn.fancybox.close();",2000);
		parent.top.$('#couponContainer').html('Coupon "'+$('#coupon').val()+'" has been applied.');

		discount = new Number($('discount',xml).text());
		switch($('discountType',xml).text()) {
			case 'dollar':
				parent.top.Buy.couponEvaluation = '? - '+Math.abs(discount);
			break;
			case 'percent':
				parent.top.Buy.couponEvaluation = '? - (? * '+(discount/100)+')';
			break;
			default:
				alert('An error has occurred.');
			break;
		}

		var newTotal = new Number($('chargeAmount',xml).text());
		if(parent.top.Buy.hardcard == '1')
			newTotal += new Number('4.99');

		parent.top.$('#grandtotal font').html('$'+newTotal.toFixed(2));
	},
	Validate : function(step) {
		/**
		 * Blur the select elements
		 *
		 * This is a little step to blur all of the elements in the current
		 * step to ensure that the data has been submitted via ajax 
		 * appropriately.
		$('li#step'+parseFloat(step)+' select').blur();
		 */

		$('#alert').dismiss();

		switch(parseFloat(step)) {
			// Payment Method
			case 1:
				if($('input[name="purchase[amount]"]:checked').val() == undefined)
					return alert('You must select an amount!');

				Buy.payment_method = $('input[name="purchase[payment_method]"]:checked').val();

				if(!Buy.payment_method)
					return alert('Please select a payment method!');
				/**
				 * Handle the payment_method selection
				 *
				 * When a user selects a payment method, we will only need billing 
				 * information if using a creditcard. Push the user to the Order Review
				 * if paypal is selected.
				 */
				switch(parseFloat($('form#buy input:radio[name="purchase[payment_method]"]:checked').val())) {
					case AUTHORIZE_DOT_NET:
					case CARDINAL_COMMERCE:
						Buy.Accordion.complete(1);
					break;
					case PAYPAL:
						// Pop up load indicator
						$(document.body).css({'cursor':'progress'});
						$('li#step'+step+' div.proceed span').toggle();

						$.post('/buy/ajax',{
							request : 'addData',
							data : 'parent=transaction:key=method:value=setExpressCheckout'
						},function(xml) {
							$.post('/buy/ajax/',{request:'purchaseCredits'},function(xml) {
								if(!$('nextmethod, redirect, token, error',xml).text()) {
									alert('An error has occured!');
									return;
								}

								var nextMethod = $('nextmethod',xml).text();

								var redirect = $('redirect',xml).text();

								$.post('/buy/ajax',{
									request : 'addData',
									data : 'parent=transaction:key=token:value='+escape($('token',xml).text())+';parent=transaction:key=method:value='+escape(nextMethod)
								},function() {
									window.location = redirect;
								});
							});
						});
					break;
					default:
						alert('Please select a Payment Method!');
					break;
				}
			break;
			// Billing information
			case 2:
				$('input').add('select').removeClass('invalid');

				if($(':input[name="replenishRecharge"]:checked').size() && $(':input[name="replenishRecharge"]:checked').val() == '1') {
					Buy.createOrderReview();
					Buy.Accordion.complete(2);
					return;
				}

				if($('li#step2 div.validate :input').approveForm() == false)
					return;

				if(!TelTech.Validate.EmailAddress($('input[name="billing[email]"]').val())) {
					$('input[name="billing[email]"]').addClass('invalid').focus();
					return;
				} else if($('input[name="billing[email]"]').val() != $('input[name="billing[emailverify]"]').val()) {
					alert('Emails do not match!');
					$('input[name="billing[emailverify]"]').addClass('invalid').focus();
					return;
				}


				var ccnumber = $('input[name="billing[ccnumber]"]').val().replace(/[^\d]/g,'');
				var length = ccnumber.length;

				if(length < 13 || length > 19) {
					alert('Invalid credit card number!');
					return false;
				}

				var digit, sum, weight;

				sum		= 0;
				weight	= 2;

				for(i = length - 2; i >= 0; i--) {
					digit = weight * parseFloat(ccnumber.charAt(i));
					sum += Math.floor(digit / 10) + digit % 10;
					weight = weight % 2 + 1;
				}

				if ((10 - sum % 10) % 10 != ccnumber.charAt(length - 1)) {
					$.alert('Invalid credit card number!');
					$('input[name="billing[ccnumber]"]').addClass('invalid').focus();
					return false;
				}

				var d = new Date();
				var month = new String(d.getMonth()+1);
				var thisMonth = new Number(d.getFullYear()+(month.length == 1 ? '0' : '')+month);
				var ccexp = new Number($('select[name="billing[ccexpyear]"]').val()+$('select[name="billing[ccexpmonth]"]').val());
				if(thisMonth > ccexp) {
					$.alert('Invalid expiration!');
					$('select[name="billing[ccexpmonth]"]').addClass('invalid').focus();
					$('select[name="billing[ccexpyear]"]').addClass('invalid');
					return;
				}

				var dataString = '';
				$(':input',$('li#step'+parseFloat(step))).each(function() {
					if($(this).attr('name')) {
						var split = $(this).attr('id').split(':');
						if(split.length == 2)
							dataString += 'parent='+split[0]+':key='+split[1]+':value='+escape($(this).val())+';';
					}
				});

				$.post('/buy/ajax',{
					request : 'addData',
					data : dataString
				},function() {
					Buy.createOrderReview();
					Buy.Accordion.complete(2);
				});
			break;
		}
	}
}

/**
 * Search Rows!
 *
 * Make the searching dynamic!
 */
var callHistory = {
	currentSearch : null,
	doSearch : function() {
		var search_phoneno = $('#search_phoneno').val();
		$("#callHistory").setGridParam({
			url		: "/extras/widget/request/cdrlist"
				+ "?search_phoneno="+search_phoneno
				+ "&search_spoofcid="+search_phoneno,
			page	: 1
		}).trigger("reloadGrid");
	},
	queueSearch : function() {
		if(this.currentSearch)
			clearTimeout(this.currentSearch);

		this.currentSearch = setTimeout("callHistory.doSearch()",500);
	}
};

$(document).ready(function() {
	if(!$.browser.msie)
		$('#nav_main .livechat').css({'float':'left'});

	// SET UP PURCHASE AMOUNT CLICKS
	$('#price-options li.option').click(function(event) {
		event.preventDefault();
		$(this).selectCredits();
	});
	// SELECT THE DEFAULT AMOUNT
	setTimeout("$('#price-options li.highlight').click();",2000);

	$('form#buy #autoreplenish').click(function() {
		$('form#buy #autoreplenish_settings').toggle();
	});

	$('#didSelection').change(function() {
		var did, html, key, index, surcharge;

		index = $(this).val();

		html = '<h1 style="display : inline;">'+dids[$(this).val()][0]['did']+'</h1>';
		if(dids[index].length > 1) {
			html += '&nbsp;(<a href="#" id="didsAltTrigger"><span>more</span><span style="display : none">less</span></a>)';
			html += '<div class="surcharge alert bad" style="display : none; font-size : 12px; font-weight : normal;"> </div>';
			html += '<div style="border : 1px solid #CCC; background-color : #F0F0F0; padding : 5px; display : none; margin : 20px auto -10px auto;" id="didsAlt">';
			html += 'Select a location<br />';
			html += '<select>';
			for(key in dids[index]) {
				did = dids[index][key];
				html += '<option value="'+key+'">'+did['description'].replace(',',', ')+'</option>';
			}
			html += '</select>';
			html += '</div>';
		}

		$('#didDisplay').html(html);
		$('#didsDisplay').animate({
			'height'	: '350px'
		});

		if(dids[index].length > 1) {
			$('#didsAltTrigger').unbind('click').click(function(event) {
				event.preventDefault();
				$('#didsAltTrigger span').toggle();
				$('#didsDisplay').animate({
					'height'	: $('#didsAlt').css('display') == 'none' ? '425px' : '350px'
				});
				$('#didsAlt').slideToggle();
			});
			$('#didsAlt select').unbind('change').change(function() {
				surcharge = Math.round(new Number(dids[index][$(this).val()]['surcharge']));
				if(surcharge)
					$('#didDisplay .surcharge').html('This number charges '+surcharge+' credit'+(surcharge == 1 ? '' : 's')+' per call').css({'display':'block'});
				else
					$('#didDisplay .surcharge').css({'display':'none'});

				$('#didsDisplay').animate({
					'height'	: surcharge ? '375px' : '350px'
				});

				$('#didDisplay h1').html(dids[index][$(this).val()]['did']);
				
				$('#didsAltTrigger span').toggle();
				$('#didsAlt').toggle();
			});
		}
	}).change();

	$('form#buy label.box').unbind('click').click(LabelReaction);

	$('form#buy').submit(function(event) {
		// Catch the current step and validate it if needed
		Buy.Validate(Buy.Accordion.currentStep);
		event.preventDefault();
	});

	$('#physical_card').click(function() {
		$('label:has(input[id="hardcard:1"])').click();
	}).hover(function() {
		$(this).css({'cursor':'pointer'});
	});

	// TODO CHANGED $('form#buy input:text').add('form#buy select').blur(Buy.saveData);

	// SET THE PROCESSOR
	$('form#buy label.payment_method').click(function() {
		if($('input:checked',this).val()) {
			$.post('/buy/ajax/',{
				request	: 'setProcessor',
				value	: $('input:checked',this).val()
			});
		}
	});

	// SUBMIT THE AMOUNT
	$('form#buy label.amount').add('form#buy label.hardcard').click(Buy.submitAmountModifier);

	// ORDER A HARDCARD, OR NOT
	$('form#buy label.hardcard').click(function() {
		if($('input:checked',this).val()) {
			$.post('/buy/ajax',{
				request : 'addData',
				data : 'parent=purchase:key=hardcard:value='+escape($('input:checked',this).val())
			});
		}
	});

	/**
	 * Wait! Remember Me!
	 *
	 * Allow for the previous tabs to be reopened
	 */
	$('form#buy li h4').unbind('click').click(function() {
		Buy.Accordion.goTo($('span',this).html());
	});

	// JAZZ FORM UP WITH JAVASCRIPT IF ENABLED

	// HIDE RADIO BUTTONS
	$('form#buy ul li div label input:radio').css({
		'display'	: 'none'
	});

	// HIDE SHIP TO OPTION
	$('form#buy #ship_option').css('display','none');

	// TRANSFORM LABELS
	$('form#buy ul li div label.box').css({
		'padding'				: '5px 5px 5px 30px',
		'background-image'		: "url('/images/chk_off.png')",
		'background-position'	: '5px 50%',
		'background-repeat'		: 'no-repeat',
		'width'					: '150px'
	});

	// SHOW GRAND TOTAL
	$('#grandtotal').css('display','block');

	// SHOW COUPON VALIDATOR
	$('#validate_coupon').css('visibility','visible').click(function() {
		if(!$('#coupon').val())
			return alert('Please enter a valid code!');

		$.post('/buy/ajax',{
			request	: 'validateCoupon',
			coupon	: $('#coupon').val()
		},Buy.ValidateCoupon);
	});

	// SHOW RESPECTIVE STEP IN ACCORDION
	Buy.Accordion.goTo(Buy.Accordion.currentStep);

	$('li[id^="step"]').each(function() {
		// MAKE CHANGES TO ALL BUT FIRST STEP
		var step = $(this).attr('id').replace(/[^\d]/g,'');
		$('div.proceed',this).css('visibility','visible');

		// Set Next Step! buttons to proceed after validation
		var container = this;
		$('div.proceed a.next',container).unbind('click').click(function() {
			Buy.Validate(step);
		});
	});

	$('input[type="text"]').addClass('idle')
		.focus(function() {
			$(this).removeClass('idle');
			$(this).addClass('focus');
		})
		.blur(function() {
			$(this).removeClass('focus');
			$(this).addClass('idle');
		});

	jQuery.extend({
		alert: function(message,type) {
			$('#alert').alert(message,type);
			window.location = "#alert";
		}
	});

	jQuery.fn.extend({
		alert: function(message,type) {
			$(this).html(message);

			clearTimeout(currentTimeout);

			if($(this).css('display') != 'block')
				$(this).slideDown();

			currentTimeout = setTimeout("$('#"+$(this).attr('id')+"').slideUp();",4000);
		},
		approveForm : function(errorContainer) {
			if(!errorContainer)
				errorContainer = $;

			var proceed = true;
			$(this).each(function() {
				if($(this).hasClass('ignore'))
					return;

				if(!TelTech.Validate.NotEmpty($(this).val())) {
					/**
					 * Error Message
					 *
					 * If there is an associated hidden field with an error message,
					 * display it's contents into the error.
					 */
					if($('input[type="hidden"].'+$(this).attr('name')).hasClass('errorMessage'))
						errorContainer.alert($('input[type="hidden"].errorMessage.'+$(this).attr('name')).val(),'bad');

					$(this).addClass('invalid').focus();

					proceed = false;
					return false;
				}
			});

			return proceed;
		},
		dismiss: function() {
			this.html();
		},
		iToggle: function() {
			if($(this).hasClass('toggleOn')) {
				$(this).val(0);
				if($.browser.msie)
					$(this).removeClass('toggleOn').addClass('toggleOff');
				else
					$(this).switchClass('toggleOn','toggleOff');
			} else if($(this).hasClass('toggleOff')) {
				$(this).val(1);
				if($.browser.msie)
					$(this).removeClass('toggleOff').addClass('toggleOn');
				else
					$(this).switchClass('toggleOff','toggleOn');
			}
		},
		selectCredits : function() {
			var selected = $(this);

			$('li.option',$(this).parents('#price-options')).each(function() {
				$(this).removeClass('highlight');
			});

			selected.addClass('highlight');
			$('input',selected).attr('checked',true);
			var split = $('input',selected).attr('id').match(/(.*):(.*)/);
			if(split && split.length == 3) {
				$.post('/buy/ajax',{
					request : 'addData',
					data : 'parent='+split[1]+':key='+split[2]+':value='+escape($('input:hidden',selected).val())
				});
			}
			Buy.calculateGrandTotal();
		}
	});

	$('.large').add('.medium').focus(function() {
		if($(this).val() == this.defaultValue)
			$(this).val('');

		$(this).css('color','#000');
	});
	$(':input').blur(function() {
		if($(this).val() == '')
			$(this).val(this.defaultValue);

		$(this).removeClass('invalid');
	});
});
