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

/*
function set_button_styles() {
  // Set all of the button classes and mouse events so that we can style them easily 
  $$('input[type="button"]').each(function(item) {        
    if (item.disabled) {
      item.className = 'button-style disabled-button';
    }
    else {
      item.className = 'button-style';
      item.onmouseover = function() { this.className = 'button-hover-style' };
      item.onmouseout = function() { this.className = 'button-style' };
    }          
  }); 
  
  // Set all of the submit tag classes and mouse events so that we can style them easily
  $$('input[type="submit"]').each(function(item) {
    if (item.disabled) {
      item.className = 'button-style disabled-button';
    }
    else {
      item.className = 'button-style';
      item.onmouseover = function() { this.className = 'button-hover-style' };
      item.onmouseout = function() { this.className = 'button-style' };
    }
  });
}
*/

function disable_input() {
  $$('input').each(function(item) {
  	if ((item.type != 'button') && (item.type != 'submit')) {
      item.disabled = true;
  	}
  });
}

function toggle_row_visibility(limit_id) {
	tr_elements = document.getElementsByTagName('tr');
	for (var i = 0; i < tr_elements.length; i++) {
		one_tr = tr_elements[i];
		if (one_tr.id.indexOf(limit_id) == 0 && one_tr.className == 'hidable') {
			if (one_tr.style && one_tr.style.display == '') {
				one_tr.style.display = 'none';
				$(limit_id + '_toggle_link').innerHTML = 'Show Detail';			
				if ($(limit_id + 'disqual_0')) {
					$(limit_id + '_disqual_0').style.borderTop = '0';
				}
				if ($(limit_id + '_disqual_4')) {
					$(limit_id + '_disqual_4').style.borderTop = '1px solid black';				
				}
			}
			else if (one_tr.style && one_tr.style.display == 'none') {
				one_tr.style.display = '';
				$(limit_id + '_toggle_link').innerHTML = 'Hide Detail';
				if ($(limit_id + 'disqual_0')) {				
					$(limit_id + '_disqual_4').style.borderTop = '0';
				}
				if ($(limit_id + '_disqual_4')) {					
					$(limit_id + '_disqual_0').style.borderTop = '1px solid black';				
				}
			}
		}	
	}
}

function calc_expiration_date(effective_date_field, quote_create_date_string, expiration_date_field) {
	if (! effective_date_field.value) {
		expiration_date_field.value = '';
		return;
	}
	
	//Parse date
	results = effective_date_field.value.match(/^([0]?[1-9]|[1][0-2])[-\/]([0]?[1-9]|[1-2]\d|[3][0-1])[-\/](\d{2}|\d{4})$/)
	if (! results) {
		alert("The effective date is either invalid or incorrectly formatted.  Valid formats include M/D/YY, M/D/YYYY, M-D-YY, or M-D-YYYY (e.g. '11/5/06', '3-4-2007')");		
		expiration_date_field.value = '';
		return;
	}
	
	//Handle two digit dates
	if (results[3] < 100) {
		results[3] = new Number(results[3]) + 2000;
	}			

	effective_date = new Date(results[3], results[1] - 1, results[2]);	
	//Validate that effective date is today or later
	today = new Date();
	today.setHours(0, 0, 0, 0);	
	
	if (effective_date.getTime() < today.getTime()) {
		alert("The effective date cannot be before today");		
		expiration_date_field.value = '';
		return;
	}
	
	//Validate that effective date is before 30 days + quote creation date
	results = quote_create_date_string.match(/(\d{4})\/(\d{2})\/(\d{2})/)
	quote_create_date = new Date(results[1], results[2] - 1, results[3]);
	threshold_date = new Date(quote_create_date.getTime() + (1000*60*60*24*30));
	formatted_threshold_date = (threshold_date.getMonth() + 1).toString() + "/" + threshold_date.getDate().toString() + "/" + threshold_date.getFullYear().toString();
	if (effective_date.getTime() >= threshold_date) {
		alert("The effective date cannot be later than " + formatted_threshold_date + ", which is 30 days after the quote creation date");	
		expiration_date_field.value = '';
		return;
	}
	
	//Everything's ok - calculate and return expiration date
	effective_date_field.value = (effective_date.getMonth() + 1).toString() + "/" + effective_date.getDate().toString() + "/" + effective_date.getFullYear().toString();
	if ((effective_date.getMonth() == 1) && (effective_date.getDate() == 29)) {
		expiration_date = new Date(effective_date.getFullYear() + 1, 2, 1);
	}
	else {
		expiration_date = new Date(effective_date.getFullYear() + 1, effective_date.getMonth(), effective_date.getDate());
	}
	expiration_date_field.value = (expiration_date.getMonth() + 1).toString() + "/" + expiration_date.getDate().toString() + "/" + expiration_date.getFullYear().toString();
	
	return;
}

function submit_application_form(form, print_action, print_application_option) {
	params_to_pass = Form.serialize(form);
	
	//Call the passed in action
	save_succeeded = false;
	new Ajax.Request('save_application', {asynchronous: false, 
							  			  method: 'post', 
							  			  parameters: params_to_pass, 									
							  			  evalScripts: true});
	
	if (save_succeeded && print_action) {							  
		show_pdf_popup(print_action, print_application_option);
	}
	
	return false;
}

function show_pdf_popup(requested_action, print_option) {
	pdf_request = requested_action;
	
	if (print_option) {
		print_option = '/' + print_option	
	}
	else {
		print_option = '';
	}    
    
    //alert(requested_action);
    
    var reg = new RegExp("hno");
    if (reg.test(requested_action)) {
	    action_request = '/hno_pdf_display/'
	}
	else {
	    action_request = '/pdf_display/'
	}
	popup_request_url = action_request + pdf_request + print_option;
	//alert(popup_request_url);
	window.open(popup_request_url, 'popup_window', 'width=750, height=700, left=50, top=50, resizable, scrollbars=yes', true);
}

/* Callback for PDF print AJAX calls */
function redirect_to_target(request) {
	target_url = request.responseText;
	if (target_url != '/pdf_error.html') {
	  $('pdf').update('Form generation complete - please wait while your form ' +
					  'is displayed.<br/>If the form opens in ' +
					  'the Acrobat Reader application itself, ' + 
					  'then you may close this window.');
	}
	window.location.href = target_url;
}

function zip_code_is_valid(zip_code) {
	return ((zip_code.length >= 5) && zip_code.match(/^(\d{5})/) && (! zip_code.match(/[^\d-]/)));
}

function strip_unnecessary_currency_chars(field) {
	field.value = field.value.replace(/\$/g, '').replace(/,/g, '').replace(/ /g, '');
}

function set_focus_on_first_form_field(form) {      
  elems = form.elements;
  for (i = 0; i < elems.length; i++) {
    elem = elems[i];
    if ((! elem.disabled) && (elem.type != 'button') && (elem.type != 'radio') && (elem.type != 'submit') && (elem.type != 'hidden') && (elem.type != undefined)) {
      elem.focus();         
      return true;
    }
  }
  
  return false;
}

//Compare the selected quote id to the hidden string with the "non finance-able" quote ids
//Disable/enable the premium finance buttons and show/hide error message based on results.
function manage_premium_finance_buttons() {
  quote_ids = $('quote_ids_no_premium_finance').value.split(',');
  selected_quote_id = $('quote_selector').options[$('quote_selector').selectedIndex].value;  	 
  
  //Note that Array#indexOf here is a Prototype extension of Javascript Array class
  $('application_no_tria').disabled = $('application_with_tria').disabled = (quote_ids.indexOf(selected_quote_id) != -1); 
  quote_ids.indexOf(selected_quote_id) != -1 ? $('no_financing_message').show() : $('no_financing_message').hide();    		
}

//Compare the selected quote id to the hidden string with the "non finance-able" quote ids
//Disable/enable the premium finance buttons and show/hide error message based on results.
function manage_premium_finance_buttons_for_programs_with_no_tria() {
  quote_ids = $('quote_ids_no_premium_finance').value.split(',');
  selected_quote_id = $('quote_selector').options[$('quote_selector').selectedIndex].value;  	 
  
  //Note that Array#indexOf here is a Prototype extension of Javascript Array class
  $('application_no_tria').disabled = (quote_ids.indexOf(selected_quote_id) != -1); 
  quote_ids.indexOf(selected_quote_id) != -1 ? $('no_financing_message').show() : $('no_financing_message').hide();    		
}
	