function confirmDelete() { return confirm("Are you sure you want to delete this item?"); }
function confirmJobDelete() { return confirm("Are you sure you want to delete this job?\nAll documents and quotes will be removed from the system."); }
function confirmContactDelete() { return confirm("Are you sure you want to remove this contact from this job?"); }
function confirmDocDelete() { return confirm("Are you sure you want to delete this document?"); }

function format_date(field)
{
	if (!isNaN(field))
	{
		if (field.length == 6)
			return field.substring(0,2)+'/'+field.substring(2,4)+'/20'+field.substring(4,6);
		else if (field.length == 8)
			return field.substring(0,2)+'/'+field.substring(2,4)+'/'+field.substring(4,8);
	}
	return field;
}

/* jobSummaryUpdate functions for edit job summary summing */
function jobSummaryUpdate_init()
{
	$$('#jobSummaryTable tbody tr').invoke('select','td').invoke('last').invoke('down','input').invoke('observe', 'blur', jobSummaryUpdate_blurListener);
}

function jobSummaryUpdate_blurListener()
{
	if (this.value.blank())
		this.value = 0;
	
	if (valid.validate())
	{
		//remove possible commas and $
		this.value = this.value.replace(/^\$|,/g, "");
		
		if (this.value.blank())
			this.value = 0;

		//add cents
		this.value = parseFloat(this.value).toFixed(2);

		//format number with thousand seperators
		var regx = /(\d+)(\d{3})/;
		
		while (regx.test(this.value))
			this.value = this.value.replace(regx, '$1' + ',' + '$2');
			
		//add dollar sign
		this.value = '$' + this.value
		
		var acc = 0;
		//sum fields
		acc = $$('#jobSummaryTable tbody tr').invoke('select','td').invoke('last').invoke('down','input').inject(0, function(acc, n) {
			var num = n.value.replace(/^\$|,/g, "");
			return acc + parseFloat(num);
		});
		acc = acc.toFixed(2)
		while (regx.test(acc))
			acc = acc.replace(regx, '$1' + ',' + '$2');
			
		$$('#jobSummaryTable tfoot tr').invoke('select','td').invoke('last').invoke('update','$'+acc);
	}
}



/* jobSummaryUpdate functions for edit job summary summing */
function jobSubmittal_init()
{
	$$('#submittalForm table tbody tr').invoke('select','td').invoke('last').invoke('down','input').each(function (obj) {
		try {
			obj.observe('blur', jobSubmittal_blurListener);
		} catch (err) {};
	});
	$$('.validate-date').invoke('observe', 'blur', jobSubmittal_blurDateListener);
}

function jobSubmittal_emailPopup()
{
	if (valid.validate())
	{
		new FlipStudios.Popup({
			url: '/ebids/submittal_emailPrompt.html',
			cancelbtn: true
		});
	}
	
	return false;
}

function jobSubmittal_updateEmail()
{
	var popup_valid = new Validation('submittalEmail');
	
	if (popup_valid.validate())	{
		$('emailTo').setValue($F('email_address'));
		
		$$('a.popup_closebtn')[0].onclick();
		$('submittalForm').submit();
	}
}

function jobSubmittal_blurDateListener()
{
	valid.validate();
}

function jobSubmittal_blurListener()
{
	if (this.value.blank())
		this.value = 0;
	
	if (valid.validate())
	{
		//remove possible commas and $
		this.value = this.value.replace(/^\$|,/g, "");
		
		if (this.value.blank())
			this.value = 0;

		//add cents
		this.value = parseFloat(this.value).toFixed(2);

		//format number with thousand seperators
		var regx = /(\d+)(\d{3})/;
		
		while (regx.test(this.value))
			this.value = this.value.replace(regx, '$1' + ',' + '$2');
			
		//add dollar sign
		this.value = '$' + this.value
		
		var acc = 0;
		//sum fields
		acc = $$('#submittalForm table tbody tr').invoke('select','td').invoke('last').invoke('down','input').inject(0, function(acc, n) {
			var num = n.value.replace(/^\$|,/g, "");
			return acc + parseFloat(num);
		});
		acc = acc.toFixed(2)
		while (regx.test(acc))
			acc = acc.replace(regx, '$1' + ',' + '$2');
			
		$$('#submittalForm table tfoot tr').invoke('select','td').invoke('last').invoke('update','$'+acc);
	}
	
}




/* quote form initialization */
function modifyQuoteForm_init()
{
	var blankrows = $$('.modify-quote tbody').invoke('select', 'tr').invoke('reverse').invoke('slice',0,1).invoke('reduce');
	blankrows.invoke('down', 'input').each(modifyQuoteForm_addListeners);
	blankrows.invoke('select', 'button').invoke('reduce').invoke('remove');
	
	$$('.modify-quote tbody button').invoke('observe', 'click', modifyQuoteForm_removeRow);
	$$('.modify-quote tfoot button').invoke('observe', 'click', modifyQuoteForm_removeLot);
	$$('.modify-quote caption a').invoke('observe', 'click', modifyQuoteForm_modifyLotPrompt);
	$$('.modify-quote tfoot input.validate-currency-dollar').invoke('observe', 'blur', modifyQuoteForm_updateTotal);

	//using tinymce's built in init function on textareas causes the event listeners in this function to fail.
	//so instead we loop through our textareas and initialize the textareas using the api.
	$$('.modify-quote tfoot textarea').each(function (i) {
		tinyMCE.execCommand('mceAddControl', false, i.identify());
	});

}

/* function called from add lot popup to add a new lot table with fields from popup */
function modifyQuoteForm_buildLot()
{
	var popup_valid = new Validation('quoteAddLot');

	if (popup_valid.validate()) {

		var cat_select = $('sub_category');
		var category_id = cat_select.value;
		var category_desc = $('category_description').value;
		var category_name = cat_select.childElements()[cat_select.selectedIndex].innerHTML;
		var lot_field = $('lot_field').value;

		$$('a.popup_closebtn')[0].onclick();
		
		$$('p#no_lots_found').invoke('remove');
		
		if (lot_field.empty())
		{

			var lot_num = $F('count');
			lot_num = parseInt(lot_num) + 1;
			$('count').setValue(lot_num);
			
			var tableTemplate = new Template('<table class="modify-quote"><caption><span class="captionLarger" id="caption_cat_#{num}">#{new_cat_name}</span><a href="#">Modify</a><br /><span id="caption_name_#{num}">#{new_desc}</span></caption>' +
			'<thead><tr><th class="product-id">Product ID</th><th class="qty">Qty</th><th class="desc">Description</th><th class="size">Size</th><th>&nbsp;</th></tr></thead>' +
			'<tfoot><tr><td colspan="3">Lot Price</td><td><input type="text" name="lotprice_#{num}" value="$0.00" class="validate-currency-dollar"></td><td>&nbsp;' +
			'<input type="hidden" name="category_description_#{num}" id="category_description_#{num}" value="#{new_desc}" /><input type="hidden" name="category_id_#{num}" id="category_id_#{num}" value="#{new_id}" />' +
			'<input type="hidden" name="lot_id_#{num}" id="lot_id_#{num}" value="" /><input type="hidden" name="lot_num[]" id="lot_num_#{num}" value="#{num}" /></td></tr><tr><td colspan="4"><textarea name="notes_#{num}" id="notes_#{num}" class="mcdEditor"></textarea></td><td><button type="button">Remove Lot</button></td></tr></tfoot><tbody>' +
			'<tr><td><input type="text" name="product_#{num}[]" class="flipstudios_suggest" value=""></td><td><input type="text" name="qty_#{num}[]" value="" class="item_qty"></td>' +
			'<td><textarea name="description_#{num}[]" class="item_desc"></textarea></td><td><input type="text" name="size_#{num}[]" value="" class="item_size"></td><td><button type="button">Remove</button></td></tr>' +
			'</tbody></table>');

			$('lotControls').insert({
				'before': tableTemplate.evaluate({
					num: lot_num,
					new_cat_name: category_name,
					new_desc: category_desc,
					new_id: category_id
				})
			});
			
			var lastrow = $$('.modify-quote tbody').last().select('tr').reverse().slice(0, 1);
			lastrow.invoke('down', 'input').each(modifyQuoteForm_addListeners);
			lastrow.reduce().select('button').reduce().remove();
			
			$$('.modify-quote tfoot button').last().observe('click', modifyQuoteForm_removeLot);
			$$('.modify-quote caption a').last().observe('click', modifyQuoteForm_modifyLotPrompt);
			$$('.modify-quote tfoot input.validate-currency-dollar').last().observe('blur', modifyQuoteForm_updateTotal);
			
			//initialize the textarea with a tinymce using an api call.
			tinyMCE.execCommand('mceAddControl', false, 'notes_'+lot_num);
			
			new FlipStudios.Suggest([$$('.flipstudios_suggest').pop()]);
						
		}
		else
		{
			$('caption_cat_'+lot_field).update(category_name);
			$('caption_name_'+lot_field).update(category_desc);
			$('category_description_'+lot_field).setValue(category_desc);
			$('category_id_'+lot_field).setValue(category_id);
		}
		
	}
}

/* function called from add lot popup to populate the second drop down after a selection is made in the first */
function updateDropDown()
{
	var id = $F('parent_category');
	var list = $('sub_category');
	list.update();
	
	var obj = new Element('option', {value: ''});
	
	obj.text = 'Loading ...';
	obj.update('Loading ...');
	
	list.insert({'bottom': obj});
	
	new Ajax.Request(location.href, {
		method: 'post',
		postBody: 'get_categories=' + id,
		onComplete: function (response) {
			var resp = response.responseText.evalJSON();

			list.update();
			
			var obj = new Element('option', {value: ''});
			
			obj.text = 'Select Lot Category';
			obj.update('Select Lot Category');
			
			list.insert({'bottom': obj});
			
			for (id in resp)
			{
				var obj = new Element('option', {value: id});
				
				obj.text = resp[id]['name'];
				obj.update(resp[id]['name']);
				
				list.insert({'bottom': obj});
			}
		}
	});
	
	return false;
}

/* function to sum all of the lot price fields, called when any lot price field is blurred */
function modifyQuoteForm_updateTotal(event)
{
	if (this.value.blank())
		this.value = 0;

	if (valid.validate())
	{
		//remove possible commas and $
		this.value = this.value.replace(/^\$|,/g, "");
		
		if (this.value.blank())
			this.value = 0;

		//add cents
		this.value = parseFloat(this.value).toFixed(2);

		//format number with thousand seperators
		var regx = /(\d+)(\d{3})/;
		
		while (regx.test(this.value))
			this.value = this.value.replace(regx, '$1' + ',' + '$2');
			
		//add dollar sign
		this.value = '$' + this.value
		
		modifyQuoteForm_sumTotal();
	}
	
	Event.stop(event);
}

function modifyQuoteForm_sumTotal()
{
		var acc = 0;
		//sum fields
		acc = $$('.modify-quote tfoot input.validate-currency-dollar').inject(0, function(acc, n) {
			var num = n.value.replace(/^\$|,/g, "");
			return acc + parseFloat(num);
		});
		acc = acc.toFixed(2)
		var regx = /(\d+)(\d{3})/;
		while (regx.test(acc))
			acc = acc.replace(regx, '$1' + ',' + '$2');
			
		$$('#lotControls dd').invoke('update','$'+acc);
}

/* process form save request and submit form */
function modifyQuoteForm_quoteSave(saveType)
{
	if (saveType == false)
		$('new').setValue('yes');

	$('modifyQuoteForm').submit();
}

function modifyQuoteForm_nameAddendum(quote, editlink)
{
	try {
		if (quote != undefined)
			quote = '?quote=' + quote;
		else
			quote = '';

	} catch (err) {quote=''};
	
	var popup = $$('.popup_window');
	if (popup.length == 0)
	{
		new FlipStudios.Popup({
				url: 'modifyQuote_saveAddendum.php' + quote,
				cancelbtn: true,
				objref: $(editlink)
		});
		
			
		return false;
	}
	else
	{
		popup[0].data.loadNewURL('modifyQuote_saveAddendum.php' + quote);
	}
}

function modifyQuoteForm_quoteSaveAddendum()
{
	// if this form isn't found, then we're editing an addendum in a popup
	if ($('modifyQuoteForm') == null)
	{
		$('quoteSaveAddendumForm').request({
			onComplete: function () {
				
				var theTD = $$('div.popup_window')[0].data.args.objref.up('td').previous('td');
				theTD.select('p').invoke('remove');
				
				var newAddendum = $$('form#quoteSaveAddendumForm label > *').pluck('value');
				if (!newAddendum[0].empty())
					newAddendum[0] = '<p style="display:none"><strong>Addendum Name:</strong> ' + newAddendum[0] + '</p>';
				if (!newAddendum[1].empty())
					newAddendum[1] = '<p style="display:none"><strong>Addendum Notes:</strong> ' + newAddendum[1] + '</p>';
				
				theTD.insert(
					newAddendum.without('').join('')
				);
				
				
				$$('div.popup_window a.popup_closebtn')[0].onclick();

			}
		});
	}
	else
	{
		// if the addendum fields already exist, remove them
		$$('#modifyQuoteForm input[name^=addendum_]').invoke('remove');
	
		// create the addendum fields, grabbing the values from the popup's form
		$('modifyQuoteForm').insert(
			new Element('input', {
				name: 'addendum_name',
				type:'hidden'
			}).setValue(
					$$('#quoteSaveAddendumForm input[name=addendum_name]').pop().value
			)
		);
		
		$('modifyQuoteForm').insert(
			new Element('input', {
				name: 'addendum_notes',
				type:'hidden'
			}).setValue(
					$$('#quoteSaveAddendumForm textarea[name=addendum_notes]').pop().value
			)
		);
	
		// finally, save this info!
		modifyQuoteForm_quoteSave(false);
	}
}

/* opens save dialog popup called from bottom of quote edit page */
function modifyQuoteForm_savePrompt(viewpdf)
{
	$('viewpdf').value = Number(viewpdf == true);
	
	new FlipStudios.Popup({
		url: '/ebids/modifyQuote_savePrompt.html',
		cancelbtn: true
	});
	
	return false;
}

/* opens add lot popup called from bottom of quote edit page */
function modifyQuoteForm_addLotPrompt()
{
	new FlipStudios.Popup({
		url: '/ebids/modifyQuote_addLotPrompt.html',
		cancelbtn: true
	});
	
	return false;
}

/* opens add lot popup called from modify link found in every lot */
function modifyQuoteForm_modifyLotPrompt(event)
{
	var urlString = Form.serializeElements(this.up('table').down('tfoot').select('tr').slice(0,1).reduce().select('td').last().select('input'));

	new FlipStudios.Popup({
		url: '/ebids/modifyQuote_addLotPrompt.html?'+urlString,
		cancelbtn: true
	});
	
	Event.stop(event);
}

/* removes a single line item from a lot */
function modifyQuoteForm_removeRow(event)
{
	if (confirm("Are you sure you want to remove this product from the lot?"))
		this.up('tr').remove();
	Event.stop(event);
}

/* removes an entire lot table from the quote */
function modifyQuoteForm_removeLot(event)
{
		tinyMCE.execCommand('mceRemoveControl', false, this.up('tr').select('textarea').reduce().identify()); 
	if (confirm("Are you sure you want to remove this lot from the quote?"))
	{
		// we have to remove the tinymce control from the textarea before removing the element!
		tinyMCE.execCommand('mceRemoveControl', false, this.up('tr').select('textarea').reduce().identify()); 

		this.up('table').remove();		
		
		if ($$('.modify-quote').length == 0) {
			$('modifyQuoteForm').insert({top: new Element('p',{'id':'no_lots_found'}).update('No lots have been created for this job yet. Click below to Add Lot.')});
		}

		modifyQuoteForm_sumTotal();
	}	
	Event.stop(event);
}

/* adds listeners for suggest and line item fields */
function modifyQuoteForm_addListeners(obj)
{
	obj.emptyText = 'New item here';
	obj.addClassName('displayHelperText');

	obj.stopObserving('blur', modifyQuoteForm_blurListener_helperText);

	obj.observe('focus', modifyQuoteForm_focusListener);
	obj.observe('blur', modifyQuoteForm_blurListener_newRow);

	obj.observe('Suggest:itemSelected', modifyQuoteForm_newSelectionListener);

	obj.value = obj.emptyText;
}

/* updates the line item fields */
function modifyQuoteForm_newSelectionListener(ev)
{
	// grab the 3 textboxes to the right of product id
	/*
	var inputs = Event.element(ev).up('tr').select('td').slice(1, 4).invoke('down', 'input');
	var description = Event.element(ev).up('tr').select('textarea').reduce();
	*/
	
	//try {
		var inputs = ev.memo['field'].up('tr').select('td').slice(1, 4).invoke('down', 'input');
		var description = ev.memo['field'].up('tr').select('textarea').reduce();

	// populate desc and size
	if (ev.memo['description'] && description.value.length == 0)
		description.value = html_entity_decode(ev.memo['description']);
	if (ev.memo['size'] && inputs[2].value.length == 0)
		inputs[2].value = html_entity_decode(ev.memo['size']);
	
	// set focus to qty if empty
	if (inputs[0].value.empty())
	{
		inputs[0].value = '0';
		inputs[0].focus();
		inputs[0].select();
	}
	

	//} catch (err) { modifyQuoteForm_newSelectionListener.delay(.1,ev); }
}

/* removes listener - apparently used for switching between helper and suggest listeners */
function modifyQuoteForm_removeListeners(obj)
{
	obj.stopObserving('blur', modifyQuoteForm_blurListener_newRow);
}

/* removes helper text */
function modifyQuoteForm_focusListener(ev)
{
	var obj = Event.element(ev);
	obj.removeClassName('displayHelperText');
	if (obj.value == obj.emptyText)
		obj.value = '';
}

/* displays helper text */
function modifyQuoteForm_blurListener_helperText(obj)
{
	if (obj == undefined)
	{
		obj = Element.extend(this);
	}
	else if (obj.value == undefined) try
	{
		obj = Event.element(obj);
	} catch (err) {return;};

	if (obj.value.empty())
	{
		obj.addClassName('displayHelperText');
		obj.value = obj.emptyText;
	}
}

/* adds a new empty row after a line item is added */
function modifyQuoteForm_blurListener_newRow()
{
	var obj = Element.extend(this);
	
	if (!obj.value.empty())
	{
		obj.up('tr').select('input').each(modifyQuoteForm_removeListeners);
		obj.observe('blur', modifyQuoteForm_blurListener_helperText);
		
		var newRow = obj.up('tr').cloneNode(true);
		obj.up('tr').insert({after: newRow});
		newRow.select('input, textarea').each(function (i) {
			i.value='';
			i.removeAttribute('id');
			//i.name = i.name.replace(/[0-9]+/, 1+Number(i.name.match(/[0-9]+/)) );
		});
		
		try { newRow.down('td').select('input ~ *').invoke('remove'); } catch (err) {  }
		
		modifyQuoteForm_addListeners(newRow.down('input'));
		
		new FlipStudios.Suggest([newRow.down('input')]);
		
		obj.up('tr').select('td').last().update(new Element('button', {}).update('Remove'));
		obj.up('tr').select('button').invoke('observe', 'click', modifyQuoteForm_removeRow);
	}
	else
	{
		modifyQuoteForm_blurListener_helperText(this);
	}
}

function html_entity_decode(str) {
  var ta=document.createElement("textarea");
  ta.innerHTML=str.replace(/</g,"&lt;").replace(/>/g,"&gt;");
  return ta.value;
}


// attach listener for add customer to quote... once we've selected someone, perform
// actions specific to this page
function addCustomerToQuote_addListeners()
{	
	try {
		
	$('addcustomer').resultsDiv.observe('Suggest:listPopulated', function () {

		var lis = $('addcustomer').resultsDiv.select('li'), twocolumn = (lis.length > 10);

		lis.each(function (obj) {
			
			var id = Number(obj._id);
			if (id < 0)
			{
			  obj.addClassName('company_without_contacts');
			  var company_name = obj.select('.company_name')[0].innerHTML;
			  obj.update();

			  obj.appendChild(
				new Element('span').addClassName('company_name').update(company_name)
			  );

			  obj.appendChild(
				new Element('span').update('Click here to enter new contact.')
			  );
			}
		
		});
		
		
		$('addcustomer').resultsDiv.setStyle({'width':((twocolumn) ? '801':'400')+'px'});

		if (twocolumn)
		{
			lis.invoke('setStyle', {'width':'380px', 'height':'24px', 'borderRight': '1px dotted #CCCCCC'}).slice(10).each(function(obj, index) {
				obj.setStyle({'position':'absolute', 'right': '0px', 'top':((34*index)+[0,index-1].max())+'px', 'borderRight':'0'});
			});
		}
																		   
	});
	
	$('addcustomer').observe('Suggest:itemSelected', addCustomerToQuote_addRow);
	
	}
	catch (err) {
		addCustomerToQuote_addListeners.delay(.1);
	};
}

function addCustomerToQuoteView_addListener()
{
	try {
		
	$('addcustomer').resultsDiv.observe('Suggest:listPopulated', function () {

		$('addcustomer').resultsDiv.select('li').each(function (obj) {
			
			var id = Number(obj._id);
			if (id < 0)
			{
			  obj.addClassName('company_without_contacts');
			  var company_name = obj.select('.company_name')[0].innerHTML;
			  obj.update();

			  obj.appendChild(
				new Element('span').addClassName('company_name').update(company_name)
			  );

			  obj.appendChild(
				new Element('span').update('Click here to enter new contact.')
			  );
			}
		
		});
																		   
	});
	
	$('addcustomer').observe('Suggest:itemSelected', addCustomerToQuoteView_addRow);
	
	}
	catch (err) {
		addCustomerToQuoteView_addListener.delay(.1);
	};
}

// we've clicked on a guy, now we need to 1) tell the db, 2) create new row in the
// table, 3) clear out textbox in prep for the next addition
function addCustomerToQuote_addRow(ev)
{	
	if (ev.memo['id'] < 0)
	{
		$$('#customerRecQuote ~ form')[0].reset();
		window.open('/admin/customercontact/' + ev.memo['id'].replace(/[^0-9]/g, '') + '/add/');
		return;
	}
	
	$$('#customerRecQuote ~ form')[0].setStyle({'visibility':'hidden'});

	new Ajax.Request(location.href, {
		method: 'post',
		postBody: 'addCustomer=' + ev.memo['id'],
		onComplete: function (resp) {

			$$('tr.no-results-found').invoke('remove');
			
			var pref = ev.memo['quote_destination'];

			if (pref == 'BOTH')
				pref = 'Email + Fax';
			else
				pref = pref.capitalize();

			var row = new Element('tr');
			
			row.appendChild( new Element('td').update(ev.memo['company_name'])							);
			row.appendChild( new Element('td').update(ev.memo['user_name'])							);
			row.appendChild( new Element('td').update(ev.memo['faxno'])								);
			row.appendChild( new Element('td').update(ev.memo['sales_name'])							);
			row.appendChild( new Element('a', {'href':'/ebids/change-contact-pref.html?contact='+resp.responseText,'target':'_blank'}).update(pref).observe('click', function (ev) {
					modifyContactPrefsPopup(Event.element(ev));
					Event.stop(ev);
			} ).wrap('td')	);
			
			if ($$('.not-priced-yet').length > 0)
			{
				row.appendChild( new Element('td').update(' ') );
				row.appendChild( new Element('td').update(' ') );
			}
			else
			{
				row.appendChild(
					new Element('button', {}).update('Email').observe('click', function () {
						var callback = function() { addCustomerToQuote_createSentIcon(row, 'Email'); };
						manuallySendQuote($('quote_id').value,'email', resp.responseText, false, callback);
					}).wrap('td')
				);
				row.appendChild(
					new Element('button', {}).update('Fax').observe('click', function () {
   						var callback = function() { addCustomerToQuote_createSentIcon(row, 'Fax'); };
						manuallySendQuote($('quote_id').value,'fax', resp.responseText, false, callback);
					}).wrap('td')
				);
				
				/*
				var callback = function() {
					
					var d = new Date();
					var text = 'Last sent ' + String(d.getMonth()+1) + '/' + String(d.getDate()) + '/' + String(d.getFullYear());
					text += ' at ' + String( (d.getHours()%12 + (!(d.getHours() % 12) * 12)) ) + ':';
					text += String(d.getMinutes()) + ((d.getHours() >= 12) ? 'PM':'AM');
					text += ' ('+pref+')';
					
					row.select('td')[7].update().insert(
						new Element('img', {src:'/images/icon-email-sent.png', alt:text, title:text})
					);
				};
				*/
			
				callback = function() { addCustomerToQuote_createSentIcon(row, pref); };
				manuallySendQuote($('quote_id').value,'newcustomer', resp.responseText, false, callback);
			}
			
			row.appendChild( new Element('td').update('&nbsp;') );
			
			row.appendChild( new Element('a', {'href':'/ebids/remove-contact.html?contact='+resp.responseText}).observe(
				'click', function (ev) { if (!confirmContactDelete()) { Event.stop(ev); } }
			).update('Remove').wrap('td')	);

			$('customerRecQuote').down('tbody').appendChild(row);
			$$('#customerRecQuote ~ form')[0].setStyle({'visibility':'visible'}).reset();

		}
	});
}

function addCustomerToQuote_createSentIcon(row, pref)
{	
	var d = new Date();
	var text = 'Last sent ' + String(d.getMonth()+1) + '/' + String(d.getDate()) + '/' + String(d.getFullYear());
	text += ' at ' + String( (d.getHours()%12 + (!(d.getHours() % 12) * 12)) ) + ':';
	text += String(d.getMinutes()) + ((d.getHours() >= 12) ? 'PM':'AM');
	text += ' ('+pref+')';
	
	$(row).select('td')[7].update().insert(
		new Element('img', {src:'/images/icon-email-sent.png', alt:text, title:text})
	);
}

function addCustomerToQuoteView_addRow(ev)
{
	if (ev.memo['id'] < 0)
	{
		$$('#customerRecQuote ~ form')[0].reset();
		window.open('/admin/customercontact/' + ev.memo['id'].replace(/[^0-9]/g, '') + '/add/');
		return;
	}
	
	$$('#customerRecQuote ~ form')[0].setStyle({'visibility':'hidden'});

	new Ajax.Request(location.href, {
		method: 'post',
		postBody: 'addCustomer=' + ev.memo['id'],
		onComplete: function (resp) {

			$$('tr.no-results-found').invoke('remove');
			
			var pref = ev.memo['quote_destination'];
			
			if (pref == 'BOTH')
				pref = 'Email + Fax';
			else
				pref = pref.capitalize();

			var row = new Element('tr');
			
			row.appendChild( new Element('td').update(ev.memo['company_name'])							);
			row.appendChild( new Element('td').update(ev.memo['user_name'])							);
			row.appendChild( new Element('td').update(ev.memo['faxno'])								);
			row.appendChild( new Element('td').update(ev.memo['sales_name'])							);
			row.appendChild( new Element('a', {'href':'/ebids/change-contact-pref.html?contact='+resp.responseText,'target':'_blank'}).update(pref).observe('click', function (ev) {
					modifyContactPrefsPopup(Event.element(ev));
					Event.stop(ev);
			} ).wrap('td')	);

			$('customerRecQuote').down('tbody').appendChild(row);
			$$('#customerRecQuote ~ form')[0].setStyle({'visibility':'visible'}).reset();
		}
	});
}


function manuallySendQuote(quote, type, user_id, suppressAlert, callback)
{
	try {
		if (suppressAlert != true)
			suppressAlert = false;
	}
	catch (err) { suppressAlert = false; };
	
	if ($('sendQuoteToAllButton') != null)
		$('sendQuoteToAllButton').disabled = true;
	
	new Ajax.Request('/ebids/pdf/?quote='+quote+'&'+type+'='+user_id,{
		onComplete: function (resp) {
			
			if ($('sendQuoteToAllButton') != null)
				$('sendQuoteToAllButton').disabled = false;
			
			if (!suppressAlert)
			{
				if (resp.responseText == '0')
					alert('Contact has no quote preference (email/fax), so quote was not sent.');
				else
					alert('The quote has been sent.');
			}
			
			if (resp.responseText == '1')
				callback();	// if no callback is passed in, this will throw an error. prototype will catch and ignore it for us.
		}
	});
}



function modifyContactPrefsPopup(atag)
{
	var popup = new FlipStudios.Popup({
		url: atag.href + '&ajax',
		cancelbtn: true
	});
	
	popup.popup.parentAtag = $(atag);
	
	return false;
}
function submitModifyContactPrefsPopup()
{
	var newPref = $F($$('.popup_window form select').pop()).capitalize();
	var newFax = $$('.popup_window input[type=text]').pop();
	var newEmail = $$('.popup_window input[type=text]').shift();
	
	$$('.popup_window form input.error').invoke('removeClassName', 'error');
	
	if ((newPref == 'Email' || newPref == 'Both') && newEmail.value.match(/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i) == null)
		newEmail.addClassName('error');
	if ((newPref == 'Fax' || newPref == 'Both') && newFax.value.replace(/[^0-9]/,'').length < 10)
		newFax.addClassName('error');
	
	if ($$('.popup_window form input.error').length > 0)
	{
		var theForm = $$('.popup_window form').pop();
		try {
			theForm.previous('div').remove();
		} catch (err) {};
		
		theForm.insert({before: new Element('div', {'class':'error'}).update('The highlighted field(s) are required.') });
		
		return false;
	}
	
	$$('.popup_window form').pop().request({
		onComplete: function () {

			if (newPref == 'Both')
				newPref = 'Email + Fax';
			

			$$('.popup_window').pop().parentAtag.up('td').previous().previous().update($F(newFax));
			
			$$('.popup_window').pop().parentAtag.update(newPref);
			$$('.popup_closebtn').pop().onclick();

		}
	});
	
	return false;
}


function printJob(job_id)
{	
	return printPage('/ebids/view-job.html?job='+job_id);
}

function printSubmittalReq()
{
	return printPage(location.href + '&print');
}

function printPage(url)
{
	var IE6 = false /*@cc_on || @_jscript_version < 5.7 @*/;

	if (IE6)
	{
		var newwin = window.open(url + '&print=ie6', 'printwin');
		return false;
	}

	var oldText = $('printjob').down('button').innerHTML;
	
	$('printjob').down('button').update('Preparing To Print...').disabled = true;
	
	var ifr = $('printIfr');
	if (ifr == null)
	{
		ifr = new Element('iframe', {'src':url + '&asdf','style':'position:absolute;left:-9000em;border:0;height:1px;width:1px;', 'name':'printIfr', 'id':'printIfr'});
		document.body.appendChild(ifr);

		ifr.observe('load', function () {
			window.frames[window.frames.length-1].focus();
			window.frames[window.frames.length-1].print();
			
			$('printjob').down('button').update(oldText).disabled = false;
		});
	}

	ifr.src=url;
	
	return false;
}

function saveEditPageForms()
{	
	$('editForm').request({
		onComplete: function () {
			$('summaryForm').request({
				onComplete: function () {
					var url = location.href;
					location.href = url;
				}
			});
		}
	});
	
	return false;
}



function addendum_init()
{
	$$('.quote_addendum_icon').invoke('observe', 'mouseover', addendum_mouseover);
	$$('.quote_addendum_icon').invoke('observe', 'mouseout', addendum_mouseout);
}
function addendum_mouseover(ev)
{
	var	icon = Event.element(ev),
		iconPos = icon.positionedOffset(),
		comments = icon.up().select('p'),
		theDiv = new Element('div', {}).addClassName('addendum_popup');
	
	comments.each(function(obj) {
		theDiv.insert( new Element('p').update(obj.innerHTML) );
	});
	
	$('content').insert(
		theDiv.setStyle({
			'right': (10 + $('content').offsetWidth - iconPos[0]) + 'px',
			'bottom': ($('content').offsetHeight - iconPos[1] - 15) + 'px'
		})
	);
}
function addendum_mouseout()
{
	$$('div.addendum_popup').invoke('remove');
}


function showDeleteQuotePopup(id, atag)
{
	var popup = new FlipStudios.Popup({
			url: '/ebids/delete-jobPrompt.php?id=' + id,
			cancelbtn: true,
			quoteRow: $(atag).up('tr')
		});
	return false;
}

function deleteQuote(performDeletion)
{
	if (!performDeletion)
	{
		$$('a.popup_closebtn')[0].onclick();
		return;
	}
	
	
	$('quoteDeleteForm').request({
		onComplete: function () {
			$$('div.popup_window')[0].data.args.quoteRow.remove();
			$$('div.popup_window form')[0].update('The quote has been deleted successfully.');
			setTimeout("$$('a.popup_closebtn')[0].onclick();", 1000);
		}
	});	
}

function showEditFollowUpPopup(id, editlink)
{
	var popup = new FlipStudios.Popup({
			url: '/ebids/edit-followup.php?id=' + id,
			cancelbtn: true,
			theTR: $(editlink).up('tr')
		});
	return false;
}

function submitCustomerFollowUpStatusForm(theForm)
{
	theForm = $(theForm);
	
	theForm.request({
		onComplete: function () {
			
			var	theTR = $$('div.popup_window')[0].data.args.theTR,
				theTDs = theTR.select('td'),
				selectbox = theForm.down('select'),
				status = selectbox.options[selectbox.selectedIndex],
				notes = theForm.down('textarea').value,
				
				// 2 = the customer summary report options page
				// 3 = edit job page
				noteTD = 3,
				currentlyViewingStatus = "";
			
			
			// customer summary report options page
			if ($$('table.summary-report-opts').length > 0 && $('filterForm') != null)
			{
				noteTD = 2;
				currentlyViewingStatus = $$('#filterForm select[name=status]')[0].value;
			}


			// if we changed the status to something that shouldn't be in this listing, refresh it
			if (currentlyViewingStatus != "" && status.value != currentlyViewingStatus)
			{
				customerSummaryOptions_loadJobs();
			}
			else
			{			
				theTDs[1].update(status.text);
				theTDs[noteTD].update(notes);
			}
			
			$$('a.popup_closebtn')[0].onclick();
			
		}
	});
	
	return false;
}