/**
 * @author	Jonathan Cochran <jono.cochran@gmail.com>
 *			COPYRIGHT (c) 2009
 * --------------------------------------------------------- */

$(document).ready(function() {
	
/**
 * QUOTES
 * --------------------------------------------------------- */
	$('#title, #scope, #timeline, #quote, .details').hide();

	// Auto focus on the next closest element
	if ( $('#quote-content').length > 0 )
		$('input, select, textarea').focusNextInputField();
	
	//Draggable "pages"...
	$(".page").draggable({
		revert : true,
		drag : function(event, ui) {
			//$('#quote-empty').stop().fadeTo(300, 0, function() { 
				//$(this).hide();
				$('#quote-empty').hide();
			//});
		},
		stop : function(event, ui) {
			var id = $(this).attr('id').replace('page-', '');
			if ( $('#'+ id, $('#quote-area')).length > 0 )
			{
				$(this).addClass('page-active').draggable('disable');
			}
		}
	});
	
	//Quote canvas area...
	$("#quote-area").droppable({
		accept : '.page',
		over : function(event, ui) {
			$(this).append('<div class="quote-insert">&nbsp;</div>');
		},
		drop: function(event, ui) {
			$('.quote-insert', $(this)).remove();
			
			//Add new quote page...
			var objPage = ui.draggable;
			var objPageId = objPage.attr('id').replace('page-', '');
			var objItem = $('#'+ objPageId).clone().addClass('quote-item-active').show();
			$(this).append(objItem);
			
			
			//Minimize & Close
			initItemControls(objItem); 
			
			//Item specific functions
			if (objPageId == "title") { initTitlePage(objItem); }
			if (objPageId == "timeline") { initTimeline(); }
			if (objPageId == "quote") { initQuote(); }
			
			//Rearrange Items...
			$("#quote-area").sortable({ handle : '.quote-item-title' });
			//$("#quote-area").disableSelection();
			
			//Scroll to the bottom...
			$(window).scrollTo( '#'+ objPageId, 300, { easing: 'easeInOutExpo' } );
			
		}
	});
	
	/**
	 * NAME OF QUOTE &
	 * MINIMIZE, MAXIMIZE, CLOSE 
	 */
	initName();
	function initName()
	{
		$('.quote-title-span, .quote-title-number').click(function() {
			$('.quote-title-span, .quote-title-number').hide();
			$('.edit-name, .edit-number').show();
		});
		
		$('.edit-name-save').click(function() {
			$('.quote-title-span').show().html($('#quote-name').val());
			$('.quote-title-number').show().html($('#quote-number').val());
			$('.edit-name, .edit-number').hide();
		});
		
		$('.edit-name-cancel').click(function() {
			$('.quote-title-span, .quote-title-number').show();
			$('.edit-name, .edit-number').hide();
		});
	}
	
	function initItemControls($objItem)
	{
		//Minimize..
		$('a.quote-minimize', $objItem).click(function() {
			( $('.quote-item-content', $objItem).is(':visible') ) ? imgSrc = "maximize" : imgSrc = "minimize";
			$('img', $(this)).attr('src', hostname +'images/button-'+ imgSrc +'.png');
			$('.quote-item-content', $objItem).slideToggle('fast');
		});
		
		//Close...
		$('a.quote-close', $objItem).click(function() {
			if ( confirm('Are you sure you want to remove this page?') )
			{
				$objItem.fadeTo(500, 0, function() {
					var id = $objItem.attr('id');
					$('#page-'+ id).removeClass('page-active').draggable('enable');
					
					$objItem.remove();
					var num = $('#title, #scope, #timeline, #quote', $('#quote-area')).length;
					if (num == "0")
					{
						$('#quote-empty').stop().show().fadeTo(500, 1);
					}
				});
			}
		});
	}
	
	function initTitlePage($objItem)
	{
		initCheckbox(); //toggles the checkbox [x]
		
		//Project Title Client & Personal Details...
		$('a.checkbox', $objItem).click(function() {
			$('.quote-item-content .details', $objItem).slideToggle();
		});
		
		//Search clients (autocomplete)...
		var $objSearch = $('input[name="input-client-name"]');	
		$objSearch.autocomplete(hostname +'index.php?c=user&m=search_people', { minChars : 2 } ).result(function(event, item) {
			item[0] = item[0].split(' (')[0];
			item[0].replace(/^\s+|\s+$/g,""); //trim
			$(this).val(item[0]);
			var company = item[1];
			$('input[name="input-client-company"]').val(company);
			//location.href = hostname +'user/clients/'+ id;
		});
		
		//Update title to match quote title
		$('#quote-name').change(function() {
			if ( $('#input-project-title').val() == "" )
			{
				$('#input-project-title').val($(this).val());
			}
		});
		
		//Update the quote name to match title if empty
		$('#input-project-title').change(function() {
			if ( $('#quote-name').val() == "Untitled Quote" )
			{
				$('#quote-name').val($(this).val());
				$('.quote-title-span').html($(this).val());
			}
		});
		
		
		//Autocomplete Locations...
		$('input[name="input-city"]').autocomplete(cities);
		$('input[name="input-state"]').autocomplete(states);
		$('input[name="input-country"]').autocomplete(countries);
	}

	function initTimeline()
	{
		initCheckbox();		
		initRemoveRow();
		initWeeksScroll();
		
		// Sortable rows...
		$(".quote-timeline-table tbody").sortable({ handle : '.sort-handle' });
		
		//Add new items...
		$('.quote-timeline-add').click(function() {
			$('.timeline-scroll-weeks').hide(); //Hide All Weeks	
			
			var clone = $('tr.quote-timeline-row:last', $('.quote-item-active')).clone(true);
			
			//clone the last row...
			clone.insertAfter('tr.quote-timeline-row:last-child', $('.quote-item-active'));
			$('.input-timeline-name', clone).val('').unbind();
			initAutocomplete( $('.input-timeline-name', clone) );
			
			// Sortable rows...
			$(".quote-timeline-table tbody").sortable({ handle : '.sort-handle' });
			
			return false;
		});
		
		//Toggle payment dates...
		$('.timeline-payment').click(function() {
			var objInputPayment = $('input', $(this).parent('td').next('td'));
			if ( $(this).hasClass('checkbox-selected') )
			{
				objInputPayment.attr('disabled', true).val('$');
			}
			else 
			{
				objInputPayment.numeric();
				objInputPayment.val('').removeAttr('disabled');
			}
		});
		
		function initAutocomplete(objInput)
		{
			//Autocomplete
			if (typeof(timelineItems) != "undefined")
			{	
				objInput.autocomplete(timelineItems, {
					max: 10,
					mustMatch: false,
					autoFill: true
				});
			}
		}
		initAutocomplete($('.input-timeline-name:visible'));
	}
	
	function initCheckbox()
	{
		$('.checkbox').live("click",function() {
			( $(this).hasClass('checkbox-selected') ) ? $(this).removeClass('checkbox-selected') : $(this).addClass('checkbox-selected'); 
			return false;
		});
	}
	
	function initRemoveRow()
	{
		$('.quote-row-close').live("click", function() {
			var iNumRows = parseInt( $('tr', $(this).parents('table:first')).length );
			--iNumRows; //Minus 1 because table header doesn't count
			
			if (iNumRows > 1)
			{
				$(this).parent('td').parent('tr').fadeTo(500,0, function() {
					$(this).remove();
					$('.input-quote-hours, .input-quote-fixed').trigger("change"); //updates the subtotal, tax, totals if present
				});
			}
			else 
			{
				alert('You must have at least 1 item');
			}
			return false;
		});
	}
	
	function initWeeksScroll()
	{
		//Select weeks... 
		var objWeeksCurrent = $('.timeline-week a');
		
		$('.timeline-scroll-weeks').hide(); //Hide All Weeks		
		objWeeksCurrent.click(function(event) {
						
			//Parent of the clicked object
			var parentTR = "";
			parentTR = $(this).parent('div').parent('td').parent('tr');
			
			var objWeeks = $('.timeline-scroll-weeks', parentTR);
			var objWeeksInner = $('.timeline-scroll-weeks-inner', parentTR);
			var objLinks = $('a', objWeeksInner);
			
			objWeeks.show();
			objLinks.click(function(e) {
				//bug using parentTR...
				$( '.timeline-week a:last', $(this).parent('div').parent('div').parent('td') ).html($(this).html()); 
				objWeeks.hide();
				return false;
			});
			return false;		
		});
		
		//Update weeks
		$('#input-timeline-weeks').live("change",function() {
			$('.timeline-scroll-weeks').hide();
			$(this).numeric();
			var newVal = parseInt($(this).val());
			//check new val is > 1...
			if (newVal < 0) { 
				alert('Must be at least 1');
				$(this).val('1');
				return false; 
			}
			if (newVal > 52) { //limit to 52 weeks due to memory limitations (goes slow....)
				alert('Max 52 weeks');
				newVal = 52;
				$(this).val(newVal);
			}
			$('.timeline-week').each(function() {
				//val = parseInt($('a', $(this)).html());
				val = $(this).find('option:selected').val();
				//update inner weeks to new count
				//$('.timeline-scroll-weeks-inner').each(function() {
					$(this).html(''); //empty the weeks out...
					for (i = 1; i <= newVal; i++)
					{
						(i == val) ? selected = ' selected' : selected = '';
						$(this).append('<option'+ selected +'>'+ i +'</option>');
						//$(this).append('<a>'+ i +'</a>');
					}
				//});
				
				//reduce selected weeks...
				if (val > newVal)
				{
					//$('a', $(this)).html(newVal);
					$(this).val(newVal);
				}
				
			});
			
			return false;
		});
	}
	
	// Edit quote only...
	function initQuote()
	{
		initRemoveRow();
		initQuoteHours();
		initCheckbox();
				
		// Quote table (active)
		var parentTable = $('table.quote-table', $('div.quote-item-active'));
		
		// Remove fixed quote row on new quotes table
		if ( $('#quote_id').val() == "0")
		{
			$('tr.quote-row-fixed:last', parentTable).remove();
		}
		// Remove fixed & hourly row on quotes table
		else
		{
			if ( $('tbody tr', parentTable).length > 1 )
			{
				$('tr.quote-row-fixed:last', parentTable).remove();
				
			}
			
			if ( $('tbody tr', parentTable).length > 1)
			{
				$('tr.quote-row:last', parentTable).remove();
			}
		}
		
		// Sortable rows...
		$(".quote-table tbody").sortable({ handle : '.sort-handle' });
			
		// Edit client & personal info confirm...
		$('.edit-link').click(function() {
			if (!confirm('If you continue, you will leave this page and might lose data if you haven\'t saved. Continue?'))
			{
				return false;
			}
		});
		
		// Date picker...
		$("#input-quote-date")
		.datePicker({
			clickInput: true, 
			startDate: '01/01/1996', 
			createButton: false
		})
		//.val(new Date().asString())
		.trigger('change');
		
		//Disable alpha characters
		$('#input-quote-rate').numeric(); 
		$('.input-quote-hours').numeric();
		$('.input-quote-fixed').numeric();
		
		// Add row items (hourly)
		$('.quote-row-add').click(function() {
			//if ( parseInt($('tr.quote-row:last', $('.quote-item-active')).length) > 0 )
			//{
				var obj = $('tbody tr.quote-row:last', $('.quote-table:last')); //$('.quote-item-active')
				var clone = obj.clone(true); //true = clone row events
				
				// clones the last row...
				clone.insertAfter('.quote-table tbody tr:last-child', $('.quote-item-active'));
				var cloneInput = $('.input-quote-name', clone);
				$('.input-quote-hours', clone).val(''); //remove hours
				cloneInput.val('').unbind(); //remove value, remove events (autocomplete)
				initAutocomplete(cloneInput);

			//} 
			$('.input-quote-hours').trigger('change');
			
			$(".quote-table tbody").sortable({ handle : '.sort-handle' });
			return false;
		});
		
		// Add row items (fixed)
		$('.quote-row-add-fixed').click(function() {
			//if ( parseInt($('.quote-table tr:last', $('.quote-item-active')).length) > 0 )
			//{
				var obj = $('tbody tr.quote-row-fixed:last', $('.quote-table:last'));
				var clone = obj.clone(true); //true = clone row events
				
				// clones the last row...
				clone.insertAfter('.quote-table tbody tr:last-child', $('.quote-item-active')).show();
				var cloneInput = $('.input-quote-name', clone);				
				
				cloneInput.unbind(); //remove value, remove events (autocomplete)
				initAutocomplete(cloneInput);
				
			//} 
			$('.input-quote-hours').trigger('change');
			
			$(".quote-table tbody").sortable({ handle : '.sort-handle' });
			return false;
		});
		
		// clear the input if val = $
		$('.input-quote-fixed').live("click", function() {
			if ( $(this).val() == currency )
				$(this).val('');
		});
		
		// Tax...
		$('#input-tax-container').numeric();
		$('.quote-tax a').click(function() {
			$('#tax-container, #input-tax-container', $('.quote-item-active')).toggle();
			$('.input-quote-hours', $('.quote-item-active')).trigger('change');
		});
		
		// Load auto complete
		function initAutocomplete(objInput)
		{
			//('.input-quote-name:visible')
			if (typeof(quoteItems) != "undefined")
			{
				objInput.autocomplete(quoteItems, {
						max: 15,
						autoFill: true,
						matchContains: "word",
						autoFill: false,
						formatItem: function(row, i, max) {
							//i + ": " +  "/" + max + ": \""
							return row.item + " (" + row.hours + " HRs)";
						},
						formatMatch: function(row, i, max) {
							return row.item + " " + row.hours;
						},
						formatResult: function(row) {
							return row.item;
						}
				})
				.result(function(result, obj) {
					var objHours = $(result.target).parent('td').next('td').children('input[type="text"]');
					if ( objHours.hasClass('input-quote-hours') )
					{
						objHours.val(obj.hours);
					}
					$('.input-quote-hours, .input-quote-fixed').trigger('change');
				});
			}
		}
		initAutocomplete($('.input-quote-name:visible'));
	}
	
	function initQuoteHours()
	{
		// Hourly rate...
		var $objHourlyRate = $('#input-quote-rate', $('.quote-item-active'));
		$objHourlyRate.live("change", function() {
			$(this).numeric();
			$('.input-quote-hours').trigger("change");
		});
		
		// Tax rate...
		$('#input-tax').live("change", function() {
			$('.input-quote-hours').trigger("change");
		});
	
		// Quote hours / rate change...
		$('.input-quote-hours, .input-quote-fixed', $('.quote-item-active')).live("change", function() {
			var $objInput = $(this);
			var bHours = $(this).hasClass('input-quote-hours');
			
			$objInput.numeric(); //accept only numeric values...
			var iHourlyRate = $objHourlyRate.val();
			var iHourlyTotal = parseFloat($objInput.val()) * iHourlyRate;
			
			if ( isNaN(iHourlyTotal) )
			{
				iHourlyTotal = "0";
			}
			
			$objInput.parent('td').next('td.summed-quote-hours').html(currency+ iHourlyTotal).formatCurrency({ symbol : currency });
			
			// Update subtotal, tax, total...
			var iHours = 0;
			var iSubTotal = 0;
			var iTax = 0;
			var iTaxRate = parseFloat( $('#input-tax').val() );			
			var iTotal = 0;
			
			// Loop quote hours
			var $objQuoteHours = $('.input-quote-hours', $('.quote-item-active'));
			for ( i = 0; i < $objQuoteHours.length; i++ )
			{
				var iHour = $($objQuoteHours[i]).val();
				if ( iHour != "" && !isNaN(iHour) )
				{
					iHours += parseFloat(iHour);
					iSubTotal += (iHour * iHourlyRate);
				}
			}
			
			// Loop fixed rates
			var $objQuoteFixed = $('.input-quote-fixed', $('.quote-item-active'));
			for ( i = 0; i < $objQuoteFixed.length; i++ )
			{
				var iFixed = $($objQuoteFixed[i]).val();
				if (iFixed == "") iFixed = 0;
				if ( !isNaN(iFixed) )
				{
					iSubTotal += parseFloat(iFixed);
				}
			}
			
			iTax = parseFloat((iTaxRate/100) * iSubTotal).toFixed(2);
			$('#hours-total').show().html(iHours).formatCurrency({ symbol : '' }).append(' Total Hours'); //1 decimal point due to common .5 increments
			$('#tax').html(currency+ iTax).formatCurrency({ symbol : currency });
			$('#subtotal').html(currency+ iSubTotal).formatCurrency({ symbol : currency });
			iSubTotal = parseFloat(iSubTotal);
			if ( ! $('#input-tax-container').is(':visible') )
			{
				iTax = 0;
			}
			iTotal = (parseFloat(iSubTotal) + parseFloat(iTax)).toFixed(2)
			$('#total').html('$'+ iTotal).formatCurrency({ symbol : currency });
			
			return false;
		});
	}
	
/**
 * LOAD QUOTE
 * --------------------------------------------------------- */	
	if ( $('#quote_id').length > 0 && $('#quote_id').val() > 0 && $('#page_order').length > 0 )
	{
		var $strPageOrder = $('#page_order').val();
		var $arPageOrder  = $strPageOrder.split(',');
		
		$('#quote-empty').hide(); //hide the canvas
		
		//Reload the quote
		for ( i = 0; i < $arPageOrder.length; i++ )
		{
			var page = $arPageOrder[i];
			
			//Disable right hand quotes
			$('#page-'+ page, $('.quote-sidebar-pages')).addClass('page-active').draggable('disable');

			//Add new quote page...
			var objItem = $('#'+ page).clone().addClass('quote-item-active').show();
			$('#quote-area').append(objItem);

			//Minimize & CLose
			initItemControls(objItem); 

			//Item specific functions
			if (page == "title") { initTitlePage(objItem); }
			if (page == "timeline") { initTimeline(); }
			if (page == "quote") { initQuote(); }
			
		}
		
		//Include tax
		if ( $('#input-tax').val() > 0 )
		{
			$('.quote-tax a', $('.quote-item-active')).trigger('click'); //buggy - triggers 4 times for some reason
			//$('#tax-container, #input-tax-container', $('.quote-item-active')).toggle();
			//$('.input-quote-hours', $('.quote-item-active')).trigger('change');
		}
		
		//Calculate totals..
		$('.input-quote-hours').trigger("change");
		
		//Rearrange Items...
		$("#quote-area").sortable({ handle : '.quote-item-title' });		
	}
	
/**
 * DELETE QUOTE
 * --------------------------------------------------------- */
	$('.delete-quote').click(function() {
		if ( !confirm('Are you sure you wish to remove this quote?') )
			return false;
		
		$.post(
			hostname +'quote/delete_quote',
			{
				quote_id : $('#quote_id').val()
			},
			function(data)
			{
				if (data == "success")
				{
					window.location.href = hostname +'user';
				}
				else
				{
					alert(data);
				}
			}
		);
	});

/**
 * SAVE QUOTE
 * --------------------------------------------------------- */
	var previewMode = false;
	var downloadPDF = false;
	$('.save-quote').click(function() {
		
		//Check to see if quote area is empty or not
		var $objQuoteArea = $('#quote-area');
		if ( $('div#quote-empty', $objQuoteArea).is(':visible') )
		{
			alert('Please drag at least one page on the canvas before saving.');
			return false;
		}
		
		//Save quote name & number if it's open...
		$('.edit-name-save').trigger('click');
		
		var objData = new Object();
		$objInputs = $("input[name^='input-'], textarea[name^='input-']", $('.quote-item-active'));
		
		//Loop all inputs...
		for ( $i = 0; $i < $objInputs.length; $i++ )
		{
			inputName = $($objInputs[$i]).attr('id').replace('input-', '').replace('-','_');
			objData[inputName] = $($objInputs[$i]).val();
		}
		
		//Timeline items...
		if ( $('#timeline').hasClass('quote-item-active') )
		{
			var objTimeline = new Object();
			var $objTimelineItems = $('.input-timeline-name', $('.quote-item-active'));
			var $objTimelineWeeks = $('.timeline-week', $('.quote-item-active'));
			var $objTimelinePayment = $('.input-timeline-amount', $('.quote-item-active'));
			$objTimelineItems.each(function(i, e) {
				//if ( $(this).val() != "" )
				//{
					objTimeline[i] = {
						'item' 	  	: $(this).val(),
						'week' 		: $($objTimelineWeeks[i]).find('option:selected').val(), //$('option', $objTimelineWeeks[i]).html(),
						'payment'	: $($objTimelinePayment[i]).val() 
					}
				//}
			});
			//if ( objTimeline.length > 0 )
				objData['objTimeline'] = objTimeline;
		}
		//return false;
		
		//Quote data / items...
		if ( $('#quote').hasClass('quote-item-active') )
		{
			var objQuote = new Object();
			var $objQuoteItems = $('.input-quote-name', $('.quote-item-active'));
			var $objQuoteHours = $('.input-quote-hours', $('.quote-item-active'));
			var $objQuoteFixed = $('.input-quote-fixed', $('.quote-item-active'));
			$objQuoteItems.each(function(i, e) {
				//if ( $(this).val() != "" )
				//{
					objQuote[i] = {
						'item' 	  : $(this).val(),
						'hours'   : $($objQuoteHours[i]).val(),
						'fixed'   : $($objQuoteFixed[i]).val(),
					}
				//}
			});
			//if ( objQuote.length > 0 )
				objData['objQuote'] = objQuote;
		}
		
		
		//Additional data to pass...
		var strOrder = "";
		$('.quote-item-active').each(function(i) {
			strOrder += $(this).attr('id') +",";
		});
		objData['name'] = $('span.quote-title-span').html();
		objData['number'] = $('span.quote-title-number').html();
		objData['order'] = strOrder.slice(0,-1); //sort of pages...
		objData['subtotal'] = $('#subtotal').html().replace(currency, '');
		objData['total'] = $('#total').html().replace(currency, '');
		objData['client_id'] = $('#client_id').val();
		if (objData['subtotal'] != objData['total'])
		{
			objData['tax'] = $('#input-tax').val(); //Tax %
		}
		else
		{
			objData['tax'] = 0;
		}
		
		//Save 
		$.post(
			hostname +'quote/save_quote',
			{
				quote_id : $('#quote_id').val(),
				data 	 : $.toJSON( objData )
			},
			function(data)
			{
				if ( !isNaN(data) )
				{
					if ( downloadPDF == true )
					{
						callIframe(hostname +'quote/generate_html/'+ data, 'download');	
						downloadPDF = false;
					}					
					else if ( previewMode == false)
					{
						redirect = hostname +'quote/edit/'+ data +'/success';
						// Save quote revision
						callIframe(hostname +'quote/generate_html/'+ data, redirect);
					}
					else
					{
						redirect = hostname +'quote/view/'+ $('#quote_id').val();
						// Save quote revision
						callIframe(hostname +'quote/generate_html/'+ $('#quote_id').val(), redirect);
					}
					
				}
				else
				{
					alert(data);
				}
			}
		);
	});
	
	// Generate iframe to output raw html and save to db
	function callIframe(url, redirect) {
	    $(document.body).append('<IFRAME id="myId" class="pdf_iframe" />');
	    $('iframe#myId').attr('src', url);

	    $('iframe#myId').load(function() 
	    {
			$('.view-pdf').removeClass('btn-med-active');
			$('img', $('.view-pdf')).attr('src', hostname +'images/pdf16x16.png');
			$('iframe#myId').ready(function() {
				var html = $('#wrap', $('#myId').contents()).html();			
	        	//console.log(html);
				saveIframeQuote(html, redirect);
				$('iframe#myID').remove();
			});
	    });
	}
	
	// Save quote revision then redirect
	function saveIframeQuote(data, redirect)
	{
		$.post(
			hostname +'quote/save_quote_revision/'+ $('#quote_id').val(),
			{
				quote_id	: $('#quote_id').val(),
				html		: data
			},
			function(data)
			{
				if ( redirect == "download" && $('#quote_id').val() != "" )
				{
					forcePDFDownload( $('#quote_id').val() );
				}
				else
				{
					window.location.href = redirect;
				}
			}
		);
	}
	
/**
 * COPY QUOTE
 * --------------------------------------------------------- */	
	$('.sidebar-copy-quote').toggle();
	$('.copy-quote').click(function() {
		$('.sidebar-copy-quote').toggle();
	});
	$('.btn-copy-quote').click(function() {		
		$('#quote_id').val('0');		
		$('.save-quote').trigger('click');
	});
	// change client id
	$('#copy-client-select').change(function() {
		$('#client_id').val($(this).val());
	});
	$('.btn-copy-cancel').click(function() {
		$('.sidebar-copy-quote').toggle();
	});
	
/**
 * PREVIEW QUOTE (not used)
 * --------------------------------------------------------- */	
	$('.preview-quote').click(function() {
		
		previewMode = true;
		
		// if (confirm('Would you like to save first?'))
		// {
			//first save
			//$('.save-quote').trigger('click');
		// }
	});
	
/**
 * GENERATE PDF FROM DB
 * --------------------------------------------------------- */	
	$('.view-pdf').click(function() {
		iQuoteId = $(this).attr('id');		
		if ( $('.save-quote').length > 0 )
		{
			// check if they want to save first...
			if (confirm('Would you like to save your changes first?'))
			{
				downloadPDF = true;
				$('.save-quote').trigger('click');
			}
			else
			{
				createRevisionOrDownload(iQuoteId);
			}
		}
		else
		{
			createRevisionOrDownload(iQuoteId);	
		}	
	});
	
	function createRevisionOrDownload(iQuoteId)
	{
		$.get(hostname +'quote/get_revision/'+ iQuoteId, function(data){
			
			// Download PDF
			if (data > 0)
			{
				forcePDFDownload(iQuoteId);
			}
			
			// Generate revision
			else
			{
				callIframe(hostname +'quote/generate_html/'+ iQuoteId, 'download');
			}
		});
	}
	
	function forcePDFDownload(iQuoteId)
	{
		window.location = hostname +'quote/revision/' +iQuoteId;
	}
	
/**
 * SEND TO CLIENT
 * --------------------------------------------------------- */
	initCheckbox();
	// Close teal boxes
	$('.close-teal-box').click(function() {
		$(this).parent('div').parent('div').hide();
	})

	// Show teal box...
	$('.send-quote').click(function() {
		$('#send-to-client').show();
	});	
	
	// Send to client...
	$('.send-client').click(function() {
		
		//if (confirm("This will email the quote to the client. Continue?"))
		//{
			$.post(
				hostname +'quote/send/'+ $('#quote_id').val(),
				{
					message		: $('#input-custom-message').val(),
					send_client	: $('.send-to1').hasClass('checkbox-selected'),
					send_copy	: $('.send-to2').hasClass('checkbox-selected')					
				},
				function(data)
				{
					if (data == 1)
					{
						$('.send-to-client-content').fadeTo(1000,0, function() {
							$('.close-teal-box').html('close');
							$(this).html('<div class="send-to-client-success">Successfully sent to client!</div>').fadeTo(1000,1);
						});
					}
					else
					{
						alert(data);
					}
				}
			);
		//}
		return false;
	});
	
	/**
	 * QUOTE OVERVIEW
	 * --------------------------------------------------------- */
	$('.quote-view-scope-more').click(function() {
		$('.quote-view-scope-full').show();
		$('.quote-view-scope-excerpt').hide();
	});
	$('.quote-view-scope-less').click(function() {
		$('.quote-view-scope-full').hide();
		$('.quote-view-scope-excerpt').show();
	});
	
	// Change quote status...
	$('.quote-status').change(function() {
		$(this).attr('disabled', true);
		$('.sidebar-change-status').css('background', 'url('+ hostname +'/images/loadinfo.net.gif) no-repeat 170px 13px');
		$.post(
			hostname +'quote/change_status',
			{
				quote_id	: $('#quote_id').val(),
				hash_id		: $('#hash_id').val(),
				status 		: $(this).val()
			},
			function(data)
			{
				if (data != 1)
				{
					alert(data);
				}
				$('.sidebar-change-status').css('background', 'none');
				$('.quote-status').removeAttr('disabled');				
			}
		
		)
	});
	
	// Deny quote...
	$('.deny-quote').click(function() {
		if (confirm('Are you sure you wish to deny this quote?'))
		{
			return true;
		}
		return false;
	});
});


/**
 * AutoFocus to next form element 
 */
$.fn.focusNextInputField = function() {
    return this.each(function() {
        var fields = $(this).parents('form:eq(0),body').find('button,input,textarea,select');
        var index = fields.index( this );
        if ( index > -1 && ( index + 1 ) < fields.length ) {
            fields.eq( index + 1 ).focus();
        }
        return false;
    });
};
