
//  Global counter of the number of items in the Cart
//
var cart_items = 0;

function two_digit_round(x){
	return Math.round(100*x)/100;
};

//  Calculate the price for a single item.  OBVIOUSLY this
//  is validated server-side too.  We just do this here for
//  the customer's benefit.
//
//  Here 'x' is the DOM element containing the input/select
//  elements that make up a "product"
//
function item_monthly_total(x){
	var base=2, frequency=2, fs;
	fs = $(x).find('select.frequency:first').val();
	if (fs == "day") {
		//frequency=30;			
		frequency=8;
		return 15.97;			
	}else if(fs == "week"){
		frequency=4;
		return 7.97;
	}else{
		//frequency=1;
		frequency=2;
		return 3.97;
	};
	return base * frequency;	
};
function item_total(x){
	var duration=3, ds;
	ds = $(x).find('select.duration:first').val();

	duration = parseInt(ds, 10);
	return item_monthly_total(x) * duration;	
};

function duration_select_int(x){
	return parseInt($(x).val(), 10);
};

function sortNumber(a,b){
	return b - a;
};


//  Returns the total price of all the items in the Cart
//
function cart_total(){
	var total=0,
	subtotals, 
	durations = $.map($('select.duration'), duration_select_int).sort(sortNumber),
	max_duration = durations[0],
	qualifier = "";
	
	subtotals = $.map($('tr.cart-item'), item_total);
	for (var i = subtotals.length - 1; i >= 0; i--){
		total+=subtotals[i];
	};
	for (var i = durations.length - 1; i >= 0; i--){
		if (durations[i] != max_duration) {
			qualifier = "&asymp; ";
			break;
		};
	};
	
	return two_digit_round(total) + ' (<span class="monthly-price">'+qualifier+'$'+ two_digit_round(total/max_duration) +'/month</span>)';
};



//  Add a new cart item before 'selector'.  This is triggered
//  by the customer clicking 'add an item' on the page.
function add_cart_item(selector){
	cart_items+=1;
	return $(selector).before([
			'<tr class="cart-item"><td>&nbsp;</td>',
			'<td>',
			//  Add a hidden form element for attachments, which we insist on 
			//  being 'with' now.
			'<input type="hidden" name="attachments',
			cart_items,
			'" value="with" class="attachments" />',
			'<input class="number" type="text" name="item',
			cart_items,
			'" value="" id="item',
			cart_items,
			'" /></td>',
			'<td><select class="frequency" name="frequency',
			cart_items,
			'">',
			'<option value="day">daily</option>',
			'<option value="week" selected >weekly</option>',
			'<option value="month">monthly&nbsp;</option>',
			'</select></td>',
			'<td><select class="duration" name="duration',
			cart_items,
			'">',
			//'<option value="1">1 month</option>',
            // '<option value="3">3 months</option>',
			'<option value="6">6 months&nbsp;</option>',
            // '<option value="12">1 year</option>',
            // '<option value="24">2 years</option>',
            // '<option value="48">4 years</option>',
			'</select></td>',
			//'<td>',
			//'<select class="attachments" hidden="true" name="attachments',
			//cart_items,
			//'">',
			//'<option value="with">with PDFs</option>',
			//'<option value="without">without PDFs</option>',
			//'</select>',
			//'</td>',
			'<td class="item-price"></td>',
			'<td class="plus-minus"><a href="#" class="remove-a-document"><span class="plus">&times;</span></a>',
			'</td>',
			'</tr>'
		].join(''));
};



$(document).ready(function() {
	// Stuff to do as soon as the DOM is ready;

	//  Update all prices
	function item_price_update(){
		$('td.item-price').each(function(){
			var this_row = $(this).parent('tr');
			$(this).html('<span class="monthly-price">$'+ two_digit_round(item_monthly_total(this_row)) +' /month</span> ($'+ two_digit_round(item_total(this_row)) + ')');
			// $(this).html('$' + item_total(this_row) + ' (<span class="monthly-price">$'+ item_monthly_total(this_row) +' /month</span>)');
			// $(this).html('<span class="monthly-price">$'+ item_monthly_total(this_row) +' /month</span> ('+ item_total(this_row) +')';
		});		
	};

	//  The element before which we stick new products
	var put_before_selector = 'tr#example-input';
	
	// Bind clicking the "add" link to this set of functions
	$('a.add-a-document').click(function(){
		
		//  What were the parameters of the last item in the cart?
		var last_frequency = $('select.frequency:last').val(),
			last_duration = $('select.duration:last').val(),
			last_attachments = $('input.attachments:last').val();
			
		//  Add the new item
		add_cart_item(put_before_selector);

		//  Set its parameters same as the previous product
		$('select.frequency:last').val(last_frequency);
		$('select.duration:last').val(last_duration);
		$('input.attachments:last').val(last_attachments);
		
		//  Calculate the total for this product
		$('span#price').html(cart_total());
		
		// Bind any changes in the form to an update in prices
		$('input, select').change(function(){
			item_price_update();
			$('span#price').html(cart_total());
		});
		
		//  Bind clicking the remove link to destroying the
		//  contents of the div in which that link lives
		$('a.remove-a-document').click(function(){
			$(this).parents('tr:first').replaceWith();
			item_price_update();
			$('span#price').html(cart_total());
			return false;
		});
		
		//  Update all prices
		item_price_update();
		
		//  Put the focus on the new input element
		$('input.number:text:last').focus();
		
		return false;
	});
	
	//  Add 1 initial item
	add_cart_item(put_before_selector);

	//  Set its price
	$('span#price').html(cart_total());
	
	//  Update all prices
	item_price_update();

	
	$('input, select').change(function(){
		$('span#price').html(cart_total());
		item_price_update();
	});
	
	// On submit
	$('form#order-form').submit(function(){
		var status = true;
		
		//  Clean up and validate fields OTHER THAN the email
		$(':text[id*="item"]').each(function(){
			
			function addError(x){
				$(x).addClass('error');				
			};
			function rmError(x){
				$(x).removeClass('error');				
			};
			
			dis = $(this);
			dis.val($.trim(dis.val()));

			//  See
			//  http://appft1.uspto.gov/netahtml/PTO/help/helpflds.html#Application_Number
			if (dis.val().match(/^((0?[2-9]|10|11|12|13|29|60|90|95)\/\d{3},?\d{3}|\d{11}|(US)?[4567],?\d{3},?\d{3}|PCT\/US(\d{2}|\d{4})\/\d{5})$/)) {
				rmError(this);
			}else{
				addError(this);
				status = false;
			};
		});
		
		//  Go back and make sure the cart items are sequentially numbered.
		//  We need to do this because the customer might have added/deleted
		//  different products and they'll be numbered all screwy now.
		if (status == true) {
			var cart_rows = $('tr.cart-item');
			for (var i=0; i < cart_rows.length; i++) {
				var	x = cart_rows[i];
				var dn, ds, fs, as;
				dn = $(x).find('input.number:first');
				ds = $(x).find('select.duration:first');
				fs = $(x).find('select.frequency:first');
				as = $(x).find('input.attachments:first');
				dn.attr('name', 'item' + i);
				ds.attr('name', 'duration' + i);
				fs.attr('name', 'frequency' + i);
				as.attr('name', 'attachments' + i);
			};
		};
		
		
		//  Display an error message if we've got any problems
		if (status == false) {
			$('div#error-messages').html(['<p>',
				'Please check the format of the patent application ',
				'numbers colored in red.  It should be either an 11-digit ',
				'document number like "20081234567" or an application ',
				'number like "09/123456".',
				'</p>'
				].join(''));
				$('div#error-messages').removeClass('none');
				return false;
		};
		
		//  Validate the email address
		// var emailFilter= /^.+@.+\..{2,6}$/;
		var emailFilter = new RegExp("^[A-Za-z0-9\\._%\\+-]+@[A-Za-z0-9\\.-]+\.[A-Za-z]{2,4}$")
		var illegalChars= /[\(\)\<\>\,\;\:\\\/\"\[\]]/;
		var emailEl = $('input[id="email"]');
		var emailVal = $.trim(emailEl.val());
		var domain = ''
		if ($('#corporate_customer_domain').length > 0) {
			var domain = $.trim($('#corporate_customer_domain').html());
		}
		//  Display an error message if the email address does
		//  not appear to be valid
		if (!(emailFilter.test(emailVal)) ||
			emailVal.match(illegalChars)) {
				
			status = false;
			emailEl.addClass('error');
			var error_msg;
			if ($.trim(emailVal).length == 0) {
				error_msg = ['<p>',
				'Please enter your email address in the ',
				'box to the right.  This is the address to which ',
				'we\'ll send your documents.',
				'</p>'
				].join('');
			}else{
				error_msg = ['<p>',
					'Please check the format of your email address.  ',
					'We were unable to parse the address you entered.',
					'</p>'
					].join('');
			};
			$('div#error-messages').html(error_msg);
			$('div#error-messages').removeClass('none');
		}else{
			if ($('#corporate_customer_domain').length > 0) {
				if (emailVal.indexOf(domain) == -1) {
					status = false;
					emailEl.addClass('error');
					
					error_msg = ['<p>',
						'That is not a valid ',
						$.trim($('#corporate_customer_name').html()),
						' email address.  ',
						'</p>'
						].join('');
					
					$('div#error-messages').html(error_msg);
					$('div#error-messages').removeClass('none');					
				}else{
					// matches
					//  If it looks valid, remove any error messages
					emailEl.removeClass('error');			
				};
			}else{
				//  If it looks valid, remove any error messages
				emailEl.removeClass('error');			
			};
		};

		//  Check the Cc field
		var ccFilter = new RegExp("^[A-Za-z0-9\\._%\\+-]+@" + (domain.replace('.', '\\.') || "[A-Za-z0-9\\.-]+\\.[A-Za-z]{2,4}") + "(,\\s*[A-Za-z0-9\\._%\\+-]+@" + (domain.replace('.', '\\.') || "[A-Za-z0-9\\.-]+\\.[A-Za-z]{2,4}") + "){0,9}$")
		var carboncopiesEl = $('input[id="carboncopies"]');
		var carboncopies = $.trim(carboncopiesEl.val());
		//  Display an error message if the email addresses do
		//  not appear to be valid
		if (carboncopies && !ccFilter.test(carboncopies)) {
				
			status = false;
			carboncopiesEl.addClass('error');
			var error_msg = ['<p>',
				'Please check the format of the email addresses you want to Cc.  ',
				'We were unable to parse the addresses you entered.',
				domain ? '  Also, please note, for security, all emails must end in "' + domain +'"':'',
				'</p>'
				].join('');
			$('div#error-messages').html(error_msg);
			$('div#error-messages').removeClass('none');
		}else{
			//  If it looks valid, remove any error messages
			carboncopiesEl.removeClass('error');			
		};	
		
			
		//  Check the password
		var passwordEl = $('#password');
		if (status && passwordEl.length > 0) {
			if (passwordEl.val().length < 1) {
				status = false;
				passwordEl.addClass('error');
				error_msg = ['<p>',
					'Your subscription requires a password.  ',
					'Please enter your password in the box to the right.',
					'</p>'
					].join('');
				$('div#error-messages').html(error_msg);
				$('div#error-messages').removeClass('none');					
			}else{				
				//  If it looks valid, remove any error messages
				passwordEl.removeClass('error');			
			};
		};


		//  Check the client_code
		var client_code_el = $('#client_code');
		if (status && client_code_el.length > 0) {
			if (client_code_el.val().length < 1 && domain) {
				status = false;
				client_code_el.addClass('error');
				error_msg = ['<p>',
					'Your subscription requires a',
					$('#client_code_field_name').html(),
					'.  Please enter your ',
					$('#client_code_field_name').html(),
					' in the box to the right.',
					'</p>'
					].join('');
				$('div#error-messages').html(error_msg);
				$('div#error-messages').removeClass('none');					
			}else{				
				//  If it looks valid, remove any error messages
				client_code_el.removeClass('error');			
			};
		};



		
		//  If we've got an error, don't submit the form
		if (status == false) {
			return false;
		}
		
		//  If there's no error, remove all old error messages
		$('div#error-messages').addClass('none');
		
		
		//  Set a cookie for 5 minutes that stores the Cart's
		//  contents.  This is just in case the user returns, so
		//  they don't have to type them in again
		var d = new Date(),
			cookiename = 'psdocs',
			cookiecontents = "woot";
		d.setTime(d.getTime() + 5000);
		if ($.cookie(cookiename)) {
			$.cookie(cookiename, cookiecontents);
		}else{
			$.cookie(cookiename, cookiecontents, {expires: d});
		};
		
		
		//  Submit the form!
		return true;
	});
	
	//  Focus on the first input element when the page loads
	// $(':text[id!="email"]:first').focus();
});

