// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

Ajax.Responders.register({
	onCreate: function() {
		if (Ajax.activeRequestCount > 0)
			Element.show('spinner');
	},
	onComplete: function() {
		if (Ajax.activeRequestCount == 0)
			Element.hide('spinner');
	}
})

function popUp(URL) {
day = new Date();
id = day.getTime();
eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=800,height=600,left = 320,top = 150');");
}

function revealLinks(elementName)
{
    $$("#"+elementName + " a").each(function(element){ element.toggle();})
}

function replaceFromOption(elementID, option, name)
{
  $$('#'+elementID+" #"+name).first().update(option.readAttribute(name));
}

function filterQuotes()
{
  var filterValue=$('status').value;
  $$('.list tbody').each(function(element){
    if (element.hasClassName(filterValue) || filterValue=='all' || element.hasClassName('embedded'))
      element.show();
    else
      element.hide();
  });
}

function updateActual(select)
{
	var rate_id=select.previous().value;
	var element=select.parentNode.descendants().find(function(e){
		return e.id=="detail_rate_actual";
	});
	if(element != null)
		element.value=ratesHash.get(rate_id).get("rate_entries").get(select.value).get("amount")
}

function updateRates(select)
{
	var descendants=select.parentNode.parentNode.descendants();
	var rate=ratesHash.get(select.value) ;
	var latestEntry = rate.get("rate_entries").get(rate.get("latest_entry_id"))
	var optionHTML=rate.get("rate_entries").values().map(function(re){
			var option ="<option value=\""+re.get("id")+"\" rate_id=\""+select+"\"";
			if (re==latestEntry)
				option += " selected=\"selected\"";
			return option+">"+re.get("info")+"</option>";
  }).join("\n");	
	
	if (select.next().id =~ '_rate_id')
	{
		element=select.next();
	  element.update(optionHTML) ;
		updateActual(element) ;
	}
}

function updateAttachments()
{
	updateOpenerField("attachments_updated");
}

function updateFinance()
{
	updateOpenerField("child_updated");
}

function updateRental()
{
	updateOpenerField("rental_updated");
	updateMainWindow();
}

function updateStatus()
{
	updateOpenerField("status_updated");
}

function updateMainWindow()
{
	updateFinance();
}

function updateOpenerField(fieldName)
{
	var flagField=window.opener.document.getElementById(fieldName);
	if(flagField !=null)
		flagField.value=new Date();
}

function greyRows(){
	var last=true;
	$$('tr').each(function(element){
	if (last==false)
	{
		last=true;
		element.addClassName('greyed');
	}
	else
	{
		last=false;
	}
})	
}

function clearNextZip(field, selected)
{
	var zipField=field.nextSiblings().find(function(e){
		return e.id =~"address_zip" && e.type == 'text';
	});
	zipField.value='*';
}

function selectRentalTripDriver(trip_id, driver_id)
{
	$('rental_driver_id').value=driver_id;
	$('rental_trip_id').value=trip_id;
}

function adjustAbsenceVisibility(selectElement, parentID)
{
	$$('#'+parentID+' .ADCAbsence').each(function(element){element.hide();});
	$$('#'+parentID+' .PersonalAbsence').each(function(element){element.hide();});
	$$('#'+parentID+' .'+selectElement.value).each(function(element){element.show();});
}

function adjustRateActual(select_element, element)
{
	if (select_element.value=='12')
      element.show();
	else
	  element.hide();
}

function addTo(checkbox, url) 
{
	if(checkbox.checked==true)
		new Ajax.Request(url, {
			method: 'get',
			parameters: {format: 'json'},
		  onSuccess: function(transport) {
			  var tripInfo=JSON.parse(transport.responseText);
				tripsInfo.set(tripInfo.id, tripInfo);
				$('invoice_data_table').insert({bottom: "<tr class=\"" + tripInfo.name+"\">"+
																										"<th>"+tripInfo.name+"</th>"+
																										"<th colspan=\"7\"> Quoted: "+formatAsMoney(tripInfo.quote.grand_total)+"</th>"+
																								 "</tr>" });
				tripInfo.invoice_data.each(function(invoice_data){
						values=[invoice_data.po, formatAsMoney(invoice_data.amount), invoice_data.invoice, invoice_data.date, invoice_data.pickup, invoice_data.dropoff, invoice_data.vin, (invoice_data.co_code||'')]
						cells=values.map(function(value){ return "<td>"+value+"</td>";	}).join('');
					 $('invoice_data_table').insert({bottom: "<tr class=\""+ tripInfo.name+" trip_row\">"+cells+"<tr/>"} )
				});
				$('invoice_data_table').insert({bottom: "<tr class=\""+ tripInfo.name+"\">"+
																										"<td class=\"numeric\">Total:</td>"+
																										"<td>"+formatAsMoney(totalInvoiceData(tripInfo.invoice_data))+"</td>"+
																										"<td class=\"numeric\">Truck Total:</td>"+
																										"<td>"+formatAsMoney(totalAssignedTrucks(tripInfo.assigned_trucks))+"</td>"+
																								"</tr>"});
		  },
		 onComplete: function(){
			setGrandTotal();
			checkForSubmitButtons();
		}
		});
	else
	{
		var selector='.'+tripsInfo.get(checkbox.value).name;
		$$(selector).each(function(element){
			element.remove();
		})
		tripsInfo.unset(checkbox.value);
		checkForSubmitButtons();
		setGrandTotal();
	}
}

function setGrandTotal(){
	$('grand_total').update(formatAsMoney(getGrandTotal()));
}

function getGrandTotal(){
	return tripsInfo.values().inject(0, function(total, tripInfo){
		return total+totalInvoiceData(tripInfo.invoice_data);
	});	
}

function formatAsMoney(mnt) {
    mnt -= 0;
    mnt = (Math.round(mnt*100))/100;
    return '$'+((mnt == Math.floor(mnt)) ? mnt + '.00' 
              : ( (mnt*10 == Math.floor(mnt*10)) ? 
                       mnt + '0' : mnt));
}

function totalAssignedTrucks(assignedTrucks){
	return assignedTrucks.inject(0, function(total, assignedTruck){
	 return total+parseFloat(assignedTruck.price);
	});	
}

function totalInvoiceData(invoice_data){
	return invoice_data.inject(0, function(total, row){
	 return total+parseFloat(row.amount);
	});	
}

function checkForSubmitButtons(){
	if($$('#invoice_data_table', 'tr.trip_row').length>1)
		$('submit_buttons').show();
	else
	  $('submit_buttons').hide();	
}

function setTripIDs() {
	$('trip_ids').value=tripsInfo.values().map(function(tripInfo){return tripInfo.id});
}
function setInvoiceForm(newWindow, preview){
	target= (newWindow==true) ? '_new' : '_self'
  $('invoices_form').target=target;
  $('preview').value=preview;
}

function evaluatePrices()
{
  notEqual=tripsInfo.values().findAll(function(tripInfo){
    return tripInfo.quote.grand_total != totalAssignedTrucks(tripInfo.assigned_trucks)
  });
	trips=notEqual.map(function(tripInfo){
		return tripInfo.name+': ' + formatAsMoney(tripInfo.quote.grand_total) + '<>' + formatAsMoney(totalAssignedTrucks(tripInfo.assigned_trucks))
	}).join("\n");
  return notEqual.length==0 || confirm("The quote value does not match the total of truck prices.\n"+trips+".\nAre you sure you want to continue?");
}

function checkUncheckAllTrucks(allElement, list)
{
	list.getElementsByClassName('assigned_truck_box').each(function(element){
		element.checked=allElement.checked;
	});
}

function evaluateChargeBack(input, div, hidePO)
{
  if (input.value.length>0 && parseFloat(input.value) > 0)
	{
    div.show();
		if(hidePO)
			$('expense_requested_po').disable();
		else
			$('expense_requested_po').enable();
	}
  else
    div.hide();
}

function showNav(toShow)
{
	$$('.nav_content').each(function(element){element.hide();});
	toShow.show();
}

function hideNav(toHide)
{
	$$('.nav_content').each(function(element){element.show();});
	toHide.hide();
}

function handleOpenExpenses(tripName, url)
{
	window.open(url, tripName+": Expenses','height=740, width=800, scrollbars=1");
}

function showConflictingJumpToCustomerElements(){
	$('open_customer_jump_link').show() ;
	$('report_stuff').show();
	$('miles_query').show();
	$('your_account_link').show();
	$('logout_link').show();
	
}

function hideConflictingJumpToCustomerElements(){
	$('open_customer_jump_link').hide() ;
	$('report_stuff').hide();
	$('miles_query').hide();
	$('your_account_link').hide();
	$('logout_link').hide();
}

function jumpToCustomerKeyPress(event){
	jumpToKeyPress(event, verifyAndJumpToCustomer, function(){
		showConflictingJumpToCustomerElements();
		$('customer_jump_content').hide();
	});
}

function jumpToTripKeyPress(event){
	jumpToKeyPress(event, verifyAndJumpToTrip, function(){
		$('open_trip_jump_link').show() ;
		$('trip_jump_content').hide();
	});
}

function jumpToQuoteKeyPress(event){
	jumpToKeyPress(event, verifyAndJumpToQuote, function(){
		$('open_quote_jump_link').show() ;
		$('quote_jump_content').hide();
	});
}

function jumpToKeyPress(event, verifyAndJump, resetFunction){
  if (event.which==Event.KEY_RETURN || event.which==Event.KEY_ESC) {
    if (event.which==Event.KEY_RETURN){
       verifyAndJump();
    }
		event.element.value='';
		resetFunction() ;
  }	
}

function verifyAndJumpToTrip() {
	verifyAndJumpTo('/trips/verify', jumpToTrip, $('jump_to_trip_id'))
}

function verifyAndJumpToQuote() {
	verifyAndJumpTo('/quotes/verify', jumpToQuote, $('jump_to_quote_id'))
}

function verifyAndJumpToCustomer() {
	new Ajax.Request('/customers/verify', {asynchronous:true, 
																			evalScripts:true, 
																			method:'get', 
																			onFailure:function(request){alert('There is no customer for the name you provided.')}, 
																			onSuccess:function(request){
																				jumpToCustomer(request.responseText);
																			}, 
																			parameters:'name='+encodeURIComponent($('customer_name').value)});
  return false;
}

function verifyAndJumpTo(url, jumpToTrip, idField){
	new Ajax.Request(url, {asynchronous:true, 
																			evalScripts:true, 
																			method:'get', 
																			onFailure:function(request){alert('There is nothing for the ID you provided.')}, 
																			onSuccess:function(request){jumpToTrip()}, 
																			parameters:'id='+idField.value.gsub(/\D/, '')});
  return false;
}

function jumpToTrip(){
	tripNum=$('jump_to_trip_id').value.gsub(/\D/, '');
	this.href='/trips/'+tripNum+'/jump_to';
	window.open(this.href, 'Trip: '+tripNum);
	return false;
}

function jumpToQuote(){
	quoteNum=$('jump_to_quote_id').value.gsub(/\D/, '');
	href='/quotes/'+quoteNum;
	window.open(href, 'Quote: '+quoteNum);
	return false;
}

function jumpToCustomer(customerID){
	// customerName=$('jump_to_customer_name').value.gsub(/\D/, '');
	href='/customers/'+customerID;
	window.open(href, 'Customer: '+customerID);
	return false;
}

function postAttachmentUpload(url, parentDivID){
	new Ajax.Updater(parentDivID, url, {asynchronous:true, evalScripts:true, method:'get'}); 
	return false;	
}

function lockForUpload(){
	$$("div#attachments form input[type=submit]").each(function(element){
		element.disable();
	});
	$$('div#attachments form a').each(function(element){
		element.hide();
	});
	return true;
}

function checkForDragDrop(){
	if (!($$('body').first().hasAttribute('_dragdropupload')))
	{
		alert('You may now upload multiple files by dragging and dropping multiple files to file text box.')
		alert('To enable this, the browser will now install the necessary plugin.')
		window.location.href="https://addons.mozilla.org/en-US/firefox/downloads/file/26401/dragdropupload-1.6.7-fx.xpi";
	}
}

function setupDateSlider()
{
	// window.onload=function(){ 
	dateSlider=new Control.Slider('date_window_handle', 'date_window_track', { sliderValue: 1.3, 
																																	onSlide: showContent,
																																	// onChange: showContent,
																																	handleImage: "/images/slider-images-handle.png",
																																	maximum:630, 
																																	range: $R(1,15)});
																																// }
}

function setDateSlider(value, ds)
{
	adjust=value<7 ? 0.3 : 0.48 ;
	dateSlider.setValue(value+adjust);
	showContent(value);
}

function showContent(value)
{
	var reference=Math.floor(value);

	$$('table#priority_customer_list tbody tr').each(function(element){
		daysOut=parseInt(element.readAttribute('days_out'));
		if (daysOut<=reference)
			element.show();
		else
			element.hide();
	})
}

function addTripToFuelPurchase(tripID){
	new Ajax.Updater('fuel_purchases', '/quotes/-1/trips/'+tripID+'/fuel_purchases/add_trip', {asynchronous:true, 
																																									evalScripts:true, 
																																									insertion:Insertion.Top,
																																									method:'get'});
  $('option_'+tripID).remove();
}

function toggleInvoiceNames(select, attribute)
{
	updateElementsWithAttribute(select.select('option'), attribute)
	updateElementsWithAttribute($$('a.trip_link'), attribute)
}

function updateElementsWithAttribute(elements, attribute)
{
	elements.each(function(element){
		element.update(element.readAttribute(attribute));
	});
}

function setUpRefresher(url, minutes)
{
	refresher=new PeriodicalExecuter(function() {new Ajax.Updater('reports', url, {asynchronous:true, evalScripts:true, method:'get'})}, minutes*60)
}


function updateFuelPurchaseHeader(headerRowClass, url)
{
	$$('tr.'+headerRowClass).each(function(row){
		new Ajax.Updater(row, url, {asynchronous:true, evalScripts:true, insertion:Insertion.After, method:'get', onComplete:function(request){row.remove()}})
	})
}

function fuelPurchaseDestroyed(purchaseRow, headerRowClass, url)
{
	purchaseRow.remove();
	updateFuelPurchaseHeader(headerRowClass, url);
}

function updateQuarterlyURLs(base)
{
	$('ifta_excel').href= base+".csv?year="+$('year').value+"&quarter="+$('quarter').value;
	$('ifta_pdf').href= base+".pdf?year="+$('year').value+"&quarter="+$('quarter').value;
}

function updateReportURLDates(action, includeEmployee)
{
  root="/reports/"+encodeURIComponent(action);
  suffix="?starts_on="+encodeURIComponent($('starts_on').value)+"&ends_on="+encodeURIComponent($('ends_on').value);
	appendReportURLs(suffix, includeEmployee)
}

function updateReportDispatcher(action)
{
  root="/reports/"+encodeURIComponent(action);
  suffix=""
	appendReportURLs(suffix, true)
}

function updateReportURLQuarter(action, includeEmployee)
{
  root="/reports/"+encodeURIComponent(action);
  suffix="?year="+$('year').value+"&quarter="+$('quarter').value;
  // if (includeEmployee)
  // 		suffix=suffix+"&employee_id="+$('employee_id').value;
	appendReportURLs(suffix, includeEmployee)
}

function appendReportURLs(suffix, includeEmployee) {
  if (includeEmployee)
		suffix=suffix+"&employee_id="+$('employee_id').value;

  $('csv_report').href=root+".csv"+suffix;
  $('pdf_report').href=root+".pdf"+suffix;
}

function loadGoogleMap(lon, lat, text) {
  if (GBrowserIsCompatible()) {
    var map = new GMap2(document.getElementById("map"));
    map.setCenter(new GLatLng(lon, lat), 11);
    map.addControl(new GLargeMapControl());
    map.addControl(new GMapTypeControl());        
    map.openInfoWindow(map.getCenter(),
										    document.createTextNode(text));        
  }
}

function setPromisedDate() {
	document.getElementById("trip_pickup_promised_on").value = document.getElementById("trip_estimated_pickup_on").value;
	document.getElementById("trip_delivery_promised_on").value = document.getElementById("trip_estimated_delivery_on").value;
}

function toggleLastContacted() {
	$$(".contacted_yes").each(
		function(element) {
			element.up(1).toggle();
		}
	);
	return true;
}


function selectEmployee(employeeID)
{
  var css_all='table#quotes_list tbody tr';
  var css=nil
    $$(css_all).each(function(e){ e.hide();});
  if (employeeID != null)
    css = 'table#quotes_list tbody tr.employee_'+employeeID
  else
    css=css_all;
  $$(css).each(function(e){ e.show();})
}




function resetEvenOdd(parentCSS) {
	var even=true;
	$$(parentCSS+' li').each(function(e){
		e.removeClassName('odd');
		e.removeClassName('even')
		if(even)
			e.addClassName('even');
		else
			e.addClassName('odd');
		even = !even;
	})
}


function sortList(parentObject, elementType, sortAttribute)
{
		var tbodies=parentObject.select(elementType);
    tbodies.each(function(reference){
				while(reference.next() != null && reference.next().readAttribute(sortAttribute) < reference.readAttribute(sortAttribute)) {
						reference.next().insert({after: reference});
				}
   })
        
}

function highlightLinksIn(element) {
	element.select('a').each(function(e){
		new Effect.Highlight(e,{});
	})
}

function confirmCODExpense(expenseChargebackAmount){
	if (expenseChargebackAmount.value > 0)
		alert('This customer is COD. Please ensure this expense is included so we get paid, dude!');
}

function checkCancel(selectField, cancelValue) {
	if (selectField.value==cancelValue)
		return confirm('Are you sure you want to cancel?')
	else
		return true
		
}
function loadSWF(swf)
{
	<!--
	// Version check for the Flash Player that has the ability to start Player Product Install (6.0r65)
	var hasProductInstall = DetectFlashVer(6, 0, 65);

	// Version check based upon the values defined in globals
	var hasRequestedVersion = DetectFlashVer(requiredMajorVersion, requiredMinorVersion, requiredRevision);

	if ( hasProductInstall && !hasRequestedVersion ) {
		// DO NOT MODIFY THE FOLLOWING FOUR LINES
		// Location visited after installation is complete if installation is required
		var MMPlayerType = (isIE == true) ? "ActiveX" : "PlugIn";
		var MMredirectURL = window.location;
	    document.title = document.title.slice(0, 47) + " - Flash Player Installation";
	    var MMdoctitle = document.title;

		AC_FL_RunContent(
			"src", "playerProductInstall",
			"FlashVars", "MMredirectURL="+MMredirectURL+'&MMplayerType='+MMPlayerType+'&MMdoctitle='+MMdoctitle+"",
			"width", "100%",
			"height", "100%",
			"align", "middle",
			"id", swf,
			"quality", "high",
			"bgcolor", "#869ca7",
			"name", swf,
			"allowScriptAccess","sameDomain",
			"type", "application/x-shockwave-flash",
			"pluginspage", "http://www.adobe.com/go/getflashplayer"
		);
	} else if (hasRequestedVersion) {
		// if we've detected an acceptable version
		// embed the Flash Content SWF when all tests are passed
		AC_FL_RunContent(
				"src", "/"+swf,
				"width", "100%",
				"height", "100%",
				"align", "middle",
				"id", swf,
				"quality", "high",
				"bgcolor", "#869ca7",
				"name", swf,
				"allowScriptAccess","sameDomain",
				"type", "application/x-shockwave-flash",
				"pluginspage", "http://www.adobe.com/go/getflashplayer"
		);
	  } else {  // flash is too old or we can't detect the plugin
	    var alternateContent = 'Alternate HTML content should be placed here. '
	  	+ 'This content requires the Adobe Flash Player. '
	   	+ '<a href=http://www.adobe.com/go/getflash/>Get Flash</a>';
	    document.write(alternateContent);  // insert non-flash content
	  }
	// -->	
}

function setDefaultExpenseValues(defaults)
{
	$('expense_amount').value=defaults.get($('expense_expense_type_id').value).get('amount')
	$('expense_chargeback_amount').value=defaults.get($('expense_expense_type_id').value).get('chargeback_amount')
	
}

function checkSubmit(attachableTypeID, 
											attachableIDID, 
											billOfLadingID,
											submitTagID)
{
	 $(submitTagID).disabled=($(attachableIDID).value == null || $(attachableIDID).value == '') || 
														($(attachableTypeID).value == null || $(attachableTypeID).value == '') ||
														($(attachableTypeID).value == 'Trip' && ($(attachableIDID).value == null || $(attachableIDID).value == ''))												
}

function setAttachable(attachableTypeID, 
											attachableType, 
											attachableIDID, 
											attachableID,
											billOfLadingID,
											billOfLading
											)
{
	$(attachableIDID).value=attachableID;
	$(attachableTypeID).value=attachableType;
	$(billOfLadingID).value=billOfLading;
}

function runTruckFlash(){
  AC_FL_RunContent( 'codebase','http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,28,0','width','594','height','214','src','TDAintroV2','quality','high','pluginspage','http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash','movie','TDAintroV2' );
	
}

function hideReviewTrips()
{
	$$('#status_review .trip_div').each(function(e){e.hide()});
}


function loadTruckStatuses(parents){
	new Ajax.Updater('truck_statuses', '/report/'+parents+'/'+$('parent_id').value+'/truck_statuses', {asynchronous:true, evalScripts:true, method:'get', parameters:'date='+encodeURIComponent($('date').value)});
}


function insertContact(elementID)
{
  var date=new Date();

 var ts=date.valueOf().toString();
  var pID="delivery_contact_"+ts;
  var html="<p id=\""+pID+"\">"+
   "<label for=\"customer_delivery_contacts_attributes_"+ts+"_name\">Add. Name</label>" +
   "<input id=\"customer_delivery_contacts_attributes_"+ts+"_name\" name=\"customer[delivery_contacts_attributes]["+ts+"][name]\" size=\"30\" type=\"text\" />" +
   " <a href=\"#\" onclick=\"Element.remove('"+pID+"');\">delete</a>"
   "</p>"
   Element.insert(elementID, { after: html });
}


function displayErrors(title, request)
{
	alert(title+":\n* "+request.responseText.evalJSON().join("\n* "));
}


function clearTripifyLinks(quoteID)
{
	css="."+quoteID+" td.tripify a";
	links=$$(css)
	
	first=links.first();
	links.each(function(link){
		if(link != first)
			link.hide();
		else
			link.show();
	});
	
}