/**
 * @author Paul
 */
var tnTax = 0.095;
var duration = 8000;
var testimonials, testimonialPics;
var testimonialNum = 0;
var itemAdded = 0;
var cartHasClosed = false;
var $_GET = getFromSearch();

$(document).ready(function($){
	testimonials = $('.testimonials .quote');
	testimonialPics = $('.testimonials .pic');
	homeTest = $('.libCustomers .customer');
	
	testimonials.hide();
	testimonialPics.hide();
	$(testimonials[0]).show();
	$(testimonialPics[0]).show();
	
	testimonialTrans(5000);
	/*
	$('#checkoutLink').click(function() {
		$('#passCookie').submit();
		return false;
	});
	*/
	
	
	
	$('a.whatItis div').hide();
                
    $('a.whatItis').hover(function(){
        $(this).find('div').show();
    },function() {
		$(this).find('div').hide();
	});
	
	setupCartEvents();
	setupFaqQsAndAs();
	
	/*
	$('[name=mediaLink]').click(function() {
		var _urlLink = $(this).attr('href');
		
		DHTMLSound(_urlLink);
		return false;
	});
	*/
	
	$('.testimonials .next').click(function() {	
		lastNum = testimonialNum;	
		testimonialNum++;
		if (testimonialNum >= testimonials.length) testimonialNum = 0;
		
		$(testimonials[lastNum]).fadeOut(400);
		$(testimonialPics[lastNum]).fadeOut(400, function() {
			$(testimonials[testimonialNum]).fadeIn();
			$(testimonialPics[testimonialNum]).fadeIn();
		});
		
		
		
	});
	
	$('.testimonials .prev').click(function() {
		lastNum = testimonialNum;
		testimonialNum--;
		if (testimonialNum < 0) testimonialNum = testimonials.length - 1;
		
		$(testimonials[lastNum]).fadeOut(400);
		$(testimonialPics[lastNum]).fadeOut(400, function() {
			$(testimonials[testimonialNum]).fadeIn();
			$(testimonialPics[testimonialNum]).fadeIn();
		});
		
	});
	
	$('[name=useBillingAddress]').change(function() {
		var _parent = $(this).parent().parent().parent();
		
		if (this.checked) {
			_parent.find('select, input:not([name=useBillingAddress])').attr('disabled','disabled');
		}
		else {
			_parent.find('select, input:not([name=useBillingAddress])').removeAttr('disabled');
		}
	});
	
	
	
	/*
	 * Decided not to use, but may add later if needed
	if ($('[name=billState]').val().toUpperCase() == 'TN') {
		var _subtotal = parseFloat($('#currentOrder tfoot .subtotal').html().replace('$',''));
		var _taxFieldObj = $('#currentOrder tfoot .tax');
		var _totalObj = $('#currentOrder tfoot .total');
		var _tax = _subtotal * tnTax;
		var _total = parseFloat(_totalObj.html().replace('$','')) + _tax;
		
		_taxFieldObj.html('$'+commaFormat(currencyFormat(_tax)));
	}
	
	// Change Tax Amount Based on State
	$('[name=billState]').change(function() {
		var _val = $(this).val();
		var _subtotal = parseFloat($('#currentOrder tfoot .subtotal').html().replace('$',''));
		var _taxFieldObj = $('#currentOrder tfoot .tax');
		var _totalObj = $('#currentOrder tfoot .total');
		var _tax = _subtotal * (_val.toUpperCase() == 'TN' ? tnTax : 0) ;
		var _total = parseFloat(_totalObj.html().replace('$','')) + _tax;
		
		_taxFieldObj.html('$'+commaFormat(currencyFormat(_tax)));
		_totalObj.html('$'+commaFormat(currencyFormat(_total)));
		
	});
	*/
	
	
	
	var shippingObj = $('#currentOrder tfoot .shippingPrice');
	var totalObj = $('#currentOrder tfoot .total');
	
	if (shippingObj.length > 0 && totalObj.length > 0) {
		var shippingPrice = parseFloat((shippingObj.html()).replace("$", ""));
		var totalPrice = parseFloat((totalObj.html()).replace("$", ""));
		
		if ($('[name=rushShipping]').length > 0) {
			if ($('[name=rushShipping]')[0].checked && shippingPrice < 14) {
				shippingPrice += 7;
				totalPrice += 7;
			}
			else if (shippingPrice > 7) {
				shippingPrice -= 7;
				totalPrice -= 7;
			}
		}
		
		shippingObj.html('$'+commaFormat(currencyFormat(shippingPrice)));
		totalObj.html('$'+commaFormat(currencyFormat(totalPrice)));
	}
	
	$('[name=rushShipping]').change(function() {
		//var _parent = $(this).parent().parent().parent();
		
		/*
		var _totalObj = _parent.find('.total');
		var _shippingObj = _parent.find('.shippingPrice');
		
		var _shippingPrice = parseFloat((_shippingObj.html()).replace("$", ""));
		var _totalPrice = parseFloat((_totalObj.html()).replace("$", ""));
		*/
		
		
		if (this.checked && shippingPrice < 14) {
			shippingPrice += 7;
			totalPrice += 7;
		}
		else if (shippingPrice > 7 ){
			shippingPrice -= 7;
			totalPrice -= 7;
		}
		
		shippingObj.html('$'+commaFormat(currencyFormat(shippingPrice)));
		totalObj.html('$'+commaFormat(currencyFormat(totalPrice)));
		
	});
	
	$('.link-shoppingCart').click(function() {
		
		var _path = location.pathname;
		var _fileName = _path.substring((_path.length - 9), _path.length);
		
		if (_fileName == 'order.php') {
			$.post('shoppingCart.php', function ($data) {
				$('#vs_engineAreaDiv').fadeOut().html($data).slideDown(msgSlideDownSpd);
				setupCartEvents();
			});
		}
		else window.location = 'http://www.liberatorfuelsaver.com/order.php?getCart=1';
		
		
		return false;
	});
	
	if ($_GET['getCart']) 
		$('.link-shoppingCart').trigger('click');
	else if ($_GET['make']) {
		getLiberatorData();
	}
	
	
	
});

function DHTMLSound(surl) {
  document.getElementById("dummyspan").innerHTML=
    "<embed src='"+surl+"' hidden=true autostart=true loop=false>";
}

function testimonialTrans($duration) {
	
	$(homeTest[testimonialNum]).delay($duration).fadeOut('normal', function() {
		if (testimonialNum < (homeTest.length - 1)) {
			$(this).next().fadeIn('normal', function() {
				testimonialTrans($duration);
			});
			testimonialNum++;
		}
		else {
			testimonialNum = 0;
			$(homeTest[testimonialNum]).fadeIn('normal', function() {
				testimonialTrans($duration);
			});
		}
		
	});
	
	
}

function setCookie($obj, $reset) {
	var _reset = $reset || false;
	var _productData = $($obj).find('input');	
	var _items = typeof Cookies.get('shoppingCart') == 'object' && !_reset ? Cookies.get('shoppingCart') : {};
	var _item = {};
	var _itemId;
	var _itemName;
	var _libName;
	var _gasketName;
	var _itemQty;
	
	_productData.each(function() {
		_name = $(this).attr('name');
		_value = $(this).val();
		
		
		if (_name == 'engineId[]' || _name == 'engineId') 
			_itemId = _value;
		else if (_name == 'quantity'){
			_item['qty'] = _value == parseInt(_value) && _value > 0 ? parseInt(_value) : 1 ;
			if (_value != parseInt(_value) || _value < 1) $(this).val(1);
		}
		else if (_name == 'libPart'){
			_item['libPart'] = _value;
		}
	});
	
	if (_itemId) {
		//if (_items[_itemId] && _items[_itemId]['qty']) 
		//	_items[_itemId]['qty'] += _item['qty'];
		//else 
			_items[_itemId] = _item;
		
		
		Cookies.set(_items, 3, 'shoppingCart');
		//Cookies.set(_items, 7, 'shoppingCart', 'https://gator1201.hostgator.com/~stellar/liberatorfuelsaver.com/');
	}
	else {
		Cookies.set(_items, -3, 'shoppingCart');
		//Cookies.set(_items, -3, 'shoppingCart','https://gator1201.hostgator.com/~stellar/liberatorfuelsaver.com/');
		$('#shoppingCart').html('Your Shopping Cart is currently empty.');
	}
}

function setupCartEvents() {
	var _rObjs = $('#shoppingCart .removeItem');
	
	$('#continueShopping').click(function() {
		var _path = location.search;
		var _fileName = _path.substring((_path.length - 9), _path.length);
		
		if ((location.search != '?getCart=1' && location.search != '?getCart=true') || cartHasClosed) 
			getLiberatorData();
		else {
			cartHasClosed = 1;
			$('#vs_engineAreaDiv').slideUp(msgSlideUpSpd, function(){
				$(this).html('');
			});
		}
	});
	
	$('#shoppingCart .removeItem').click(function() {
		//alert('removed');
		var _row = $(this).parent().parent().parent();
		var _cells = _row.find('.cell');
		var _price = _row.find('.price').html();
		var _totalPriceObj = _row.parent().parent().find('.totalPrice');
		var _totalPrice = _totalPriceObj.html();
		var _rowRemoved = false;
		var some;
		_price = parseFloat(_price.replace('$',''));
		
		
		_cells.slideUp('slow', function() {
			
			if (!_rowRemoved) {
				$(this).parent().parent().remove();
				_totalPrice = (parseFloat(_totalPrice.replace('$',''))) - _price;
				_totalPrice = _totalPrice > 0 ? _totalPrice : 0; 
				_totalPriceObj.html("$" + commaFormat(currencyFormat(_totalPrice)));
				
				if ($('#shoppingCart tbody tr').length)
					$('#shoppingCart tbody tr').each(function($index) {
						if ($index == 0) setCookie(this, 1);
						else setCookie(this, 0);
					});
				else setCookie($('#shoppingCart tbody', 1));
					
				
				_rowRemoved = true;
			}
		
			
		});
		
		
		return false;
		
	});
}

function setupOrderPageEvents() {
	
	$('.addToCart').click( function() {
		
		setCookie($(this).parent().parent());
		
		$('#vs_engineAreaDiv').fadeOut(300, function() {
			$.post('shoppingCart.php', function ($data) {
				$('#vs_engineAreaDiv').html($data).slideDown(msgSlideDownSpd);
				setupCartEvents();
			});
		});
		
		
		
		
		//alert(Cookies.get('shoppingCart'));
		
		return false;
	});
	
}

function setupFaqQsAndAs() {
	var _answers = $('#answers li');
	
	$('#answers li').each(function($index) {
		$(this).addClass('aws'+$index).css({'display': 'none'});
	});
	
	$('#questions li').each(function($index) {
		
		$(this).click(function() {
			
			$('#answers li').each(function() {
				
				if ($(this).hasClass('aws' + $index)) {
					$(this).css({
						'left': '0',
						'display': 'none'
					}).fadeIn('slow');
				}
				else $(this).css({'left':'9999px','display': 'none'}).fadeOut('slow');
				
			});
		});
	});
}

function getFromSearch() {
	var x = 0
	var _getObj = {}
	var _mySearch = location.search.substr(1).split("&")
	
	for (x=0;x < _mySearch.length;x++) {
		var _arr = _mySearch[x].split('=');
		_getObj[_arr[0]] = _arr[1];
	}
	
	return _getObj;
}

function setupTestimonialTransition($index) {
	
	$(testimonials[$index]).delay(duration).slideUp('slow');
	
	$index = $index >= testimonials.length - 1 ? 0 : $index+1;
	
	$(testimonials[$index]).delay(duration).slideDown('slow', function(){setupTestimonialTransition($index)});
}

function currencyFormat(amount) {
	var i = parseFloat(amount);
	if(isNaN(i)) { i = 0.00; }
	var minus = '';
	if(i < 0) { minus = '-'; }
	i = Math.abs(i);
	i = parseInt((i + .005) * 100);
	i = i / 100;
	s = new String(i);
	if(s.indexOf('.') < 0) { s += '.00'; }
	if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
	s = minus + s;
	return s;
}


function commaFormat(amount) {
	var delimiter = ","; // replace comma if desired
	var amount = amount.toString();
	var a = amount.split('.',2)
	var d = a[1];
	var i = parseInt(a[0]);
	if(isNaN(i)) { return ''; }
	var minus = '';
	if(i < 0) { minus = '-'; }
	i = Math.abs(i);
	var n = new String(i);
	var a = [];
	while(n.length > 3)
	{
		var nn = n.substr(n.length-3);
		a.unshift(nn);
		n = n.substr(0,n.length-3);
	}
	if(n.length > 0) { a.unshift(n); }
	n = a.join(delimiter);
	if(d.length < 1) { amount = n; }
	else { amount = n + '.' + d; }
	amount = minus + amount;
	return amount;
}
