var basePrice = 0;
var tableName = '';
var hasTaxCredit = false;

$(document).ready(function () {
	
	// get value of table name and store it for later use
	tableName = $('#my_notebook .options h3 span.name').text();
	// set initial form notebook json object
	setFormNotebookJSON();
	// init form
	$('#notebook_form').ajaxForm( { target: '#notebook_form', beforeSubmit: validateNotebookForm, success: onNotebookFormSuccess } ); 
	// init notebook auto-scroll
	$(function() {
	        var offset = $("#my_notebook").offset();
			var leftColHeight = $('#left_column').height() + $('#left_column').offset().top;
	        var topPadding = 30;
	
	        $(window).scroll(function() {
	            if ($(window).scrollTop() > offset.top) {
	                $("#my_notebook").stop().animate({
	                    marginTop: Math.min($(window).scrollTop() - offset.top + topPadding, leftColHeight - ($('#my_notebook').height() + offset.top))
	                });
	            } else {
	                $("#my_notebook").stop().animate({
	                    marginTop: 0
	                });
	            };
	        });
	    });
	// init pretty photo
	$("a[rel^='prettyPhoto']").prettyPhoto();
		
	$('.options li').click(function () {
			
		var text = $(this).children('p.meta');

		if (text.is(':hidden')) {
			text.slideDown(200);
			$(this).children('span').not('.price').html('-');		
		} else {
			text.slideUp(200);
			$(this).children('span').not('span.price').html('+');		
		}

	});
	
	$('input#send_to_hill').click(
		function()
		{
			var fields = $('ul#additional_info');
			
			if (fields.is(':hidden')) 
			{
				fields.slideDown(400);
			}
			else
			{
				fields.slideUp(400);
			}
		}
	)
	
	$('#left_column input:checkbox').click(function() {
		var optionsList = $('#my_notebook .options ul');
		
		optionsList.children('li.total, li.sub-total, li.tax-credit').remove();
		
		if ($(this).attr('checked'))
		{
			var desc = $(this).siblings('p').not('p.meta').text();
			var price = $(this).siblings('span.price').text();

			optionsList.append('<li id="' + $(this).attr('name') + '"><p class="desc">' + desc + '</p><span class="price option">' + price + '</span></li>');
		}
		else
		{
			$('#my_notebook ul li[id="' + $(this).attr('name') + '"]').remove();
		}
		
		calcAndDisplayTotals();
		
		setFormNotebookJSON();
	})
	
	function calcAndDisplayTotals()
	{
		var optionsList = $('#my_notebook .options ul');
		
		var total = getTotalCost();
		
		if (hasTaxCredit)
		{
			var subTotal = total;
			var taxCredit = Math.min((subTotal - 250) * .5, 5000);
			total = subTotal - taxCredit;
			
			optionsList.append('<li class="sub-total">TOTAL<span class="price">$' + subTotal.toFixed(2) +'</span></li>');
			optionsList.append('<li class="tax-credit"><a href="/Tax-Credit-Information.php" target="_blank">ADA TAX CREDIT*</a><span class="price">-$' + taxCredit.toFixed(2) +'</span></li>');
		}
		else
		{
			optionsList.append('<li class="total">TOTAL<span class="price">$' + total.toFixed(2) +'</span></li>');
		}
	}
	
	// init notebook totals
	calcAndDisplayTotals();
	
	// init email notebook click function
	$('#email_notebook_btn').click(
		function()
		{
			$('#notebook_form').slideDown(700);
			$('#notebook_form #close_btn').fadeIn(200);
			return false;
		}
	);
	
	$('#notebook_form #close_btn').click(
		function()
		{
			$(this).fadeOut(150);
			$('#notebook_form').slideUp(700);
			return false;
		}
	);
	
	//init print notebook click function
	$('#print_notebook_btn').click(printNotebook);
	
	// leasing calculator
	if (parseFloat(stripDollarSign($('#leasing_calculator input').attr('value'))) > 0) calculateTotals();
	$('#leasing_calculator input').keypress(
		function(event)
		{
			if ($(this).attr('value').length >= 7 && event.keyCode != 8) event.preventDefault();
		}
	);
	$('#leasing_calculator input').keyup(calculateTotals);
});

function calculateTotals()
{
	var total = parseFloat(stripDollarSign($('#leasing_calculator input').attr('value')));
	
	var oneYearMonthly = getOneYearMonthly(total).toFixed(2);
	$('#one_year .monthly span').text('$' + oneYearMonthly);
	$('#one_year .down span').text('$' + oneYearMonthly);
	
	var twoYearMonthly = getTwoYearMonthly(total).toFixed(2);
	$('#two_year .monthly span').text('$' + twoYearMonthly);
	$('#two_year .down span').text('$' + (twoYearMonthly * 2).toFixed(2));

	var threeYearMonthly = getThreeYearMonthly(total).toFixed(2);
	$('#three_year .monthly span').text('$' + threeYearMonthly);
	$('#three_year .down span').text('$' + (threeYearMonthly * 2).toFixed(2));
}

function getOneYearMonthly(total)
{
	if (isNaN(total)) return 0;
	
	return total * .088;
}

function getTwoYearMonthly(total)
{
	if (isNaN(total)) return 0;
	
	return total * .048;
}

function getThreeYearMonthly(total)
{
	if (isNaN(total)) return 0;
	
	return total * .034;
}

function stripDollarSign(value)
{
	if (!value) return;
	return value.replace("$", "");
}

function getTotalCost()
{
	var total = basePrice;
	
	$('#my_notebook .options ul span.option').each(
		function() 
		{
				total += parseFloat(stripDollarSign($(this).text()));
		}
	);
	
	return total;
}

function setFormNotebookJSON()
{	
	var subTotal = getTotalCost();
	var taxCredit = Math.min((subTotal- 250) * .5, 5000);
	var total = hasTaxCredit ? subTotal - taxCredit : subTotal;
	
	var notebook = {
		tableName: tableName, 
		tablePrice: basePrice,
		hasTaxCredit: hasTaxCredit, 
		subTotal: subTotal.toFixed(2),
		taxCredit: taxCredit.toFixed(2),
		totalPrice: total.toFixed(2),
		options: []};
	
	var len = $('#my_notebook .options ul li').length;
	
	$('#my_notebook .options ul li').each(
		function(index) 
		{
			var cla = $(this).attr('class');
			
			if (cla != 'total' && cla != 'sub-total' && cla != 'tax-credit')
			{
				var desc = $(this).children('.desc').text();
				var price = $(this).children('.price').text();
		
				notebook.options.push( {description: desc, price: price} );
			}
		}
	);
	
	// store options in hidden form field
	$('#notebook_form #notebook_contents').attr('value', $.toJSON(notebook));
}

function setTableBasePrice(value)
{
	basePrice = value;
}

function validateNotebookForm()
{
	var notebookForm = $('#notebook_form');
	if (!notebookForm.find('input[name=e-mail]').fieldValue()[0])
	{
		alert('Please fill in your e-mail address.');
		return false;
	}
	if (notebookForm.find('input[name=send_to_hill]').attr('checked') && (!notebookForm.find('input[name=name]').fieldValue()[0] || !notebookForm.find('input[name=phone]').fieldValue()[0]))
	{
		alert('Please fill in your name and phone number.');
		return false;
	}
}

function onNotebookFormSuccess(responseText, statusText, xhr, $form)
{
	trackEmailOrPrint();
}

function trackEmailOrPrint()
{
	$('body').append('<img height="1" width="1" style="border-style:none;" alt="" src="https://www.googleadservices.com/pagead/conversion/1052743248/?label=4MNtCObZ9AIQ0Kz-9QM&amp;guid=ON&amp;script=0"/>');	
}

function printNotebook()
{
	var disp_setting="toolbar=no,location=no,directories=yes,menubar=no,"; 
	disp_setting+="scrollbars=yes,width=550, height=550, left=100, top=25"; 
	
	var content_vlue = $("#my_notebook").html();

	var docprint = window.open("","",disp_setting); 
	docprint.document.open(); 
	docprint.document.write('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">');
	docprint.document.write('<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">');
	docprint.document.write('<head><title>Print Your Notebook</title><link rel="stylesheet" href="/css/print_notebook.css" type="text/css" media="screen, print" />');
	docprint.document.write('</head><body onLoad="self.print()"><center><div id="my_notebook">');          
	docprint.document.write(content_vlue);          
	docprint.document.write('</div></center></body></html>'); 
	docprint.document.close(); 
	docprint.focus(); 
	
	trackEmailOrPrint();
}

// JSON jQuery plugin


(function($){$.toJSON=function(o)
{if(typeof(JSON)=='object'&&JSON.stringify)
return JSON.stringify(o);var type=typeof(o);if(o===null)
return"null";if(type=="undefined")
return undefined;if(type=="number"||type=="boolean")
return o+"";if(type=="string")
return $.quoteString(o);if(type=='object')
{if(typeof o.toJSON=="function")
return $.toJSON(o.toJSON());if(o.constructor===Date)
{var month=o.getUTCMonth()+1;if(month<10)month='0'+month;var day=o.getUTCDate();if(day<10)day='0'+day;var year=o.getUTCFullYear();var hours=o.getUTCHours();if(hours<10)hours='0'+hours;var minutes=o.getUTCMinutes();if(minutes<10)minutes='0'+minutes;var seconds=o.getUTCSeconds();if(seconds<10)seconds='0'+seconds;var milli=o.getUTCMilliseconds();if(milli<100)milli='0'+milli;if(milli<10)milli='0'+milli;return'"'+year+'-'+month+'-'+day+'T'+
hours+':'+minutes+':'+seconds+'.'+milli+'Z"';}
if(o.constructor===Array)
{var ret=[];for(var i=0;i<o.length;i++)
ret.push($.toJSON(o[i])||"null");return"["+ret.join(",")+"]";}
var pairs=[];for(var k in o){var name;var type=typeof k;if(type=="number")
name='"'+k+'"';else if(type=="string")
name=$.quoteString(k);else
continue;if(typeof o[k]=="function")
continue;var val=$.toJSON(o[k]);pairs.push(name+":"+val);}
return"{"+pairs.join(", ")+"}";}};$.evalJSON=function(src)
{if(typeof(JSON)=='object'&&JSON.parse)
return JSON.parse(src);return eval("("+src+")");};$.secureEvalJSON=function(src)
{if(typeof(JSON)=='object'&&JSON.parse)
return JSON.parse(src);var filtered=src;filtered=filtered.replace(/\\["\\\/bfnrtu]/g,'@');filtered=filtered.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,']');filtered=filtered.replace(/(?:^|:|,)(?:\s*\[)+/g,'');if(/^[\],:{}\s]*$/.test(filtered))
return eval("("+src+")");else
throw new SyntaxError("Error parsing JSON, source is not valid.");};$.quoteString=function(string)
{if(string.match(_escapeable))
{return'"'+string.replace(_escapeable,function(a)
{var c=_meta[a];if(typeof c==='string')return c;c=a.charCodeAt();return'\\u00'+Math.floor(c/16).toString(16)+(c%16).toString(16);})+'"';}
return'"'+string+'"';};var _escapeable=/["\\\x00-\x1f\x7f-\x9f]/g;var _meta={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'};})(jQuery);



