/**
 * @author VW Solutions
 * @mail solutions.vw@gmail.com
 * 
 * This code was developed by VW Solutions, 2008.
 * Please write to 'solutions.vw@gmail.com' for more
 * information on how can we assist you in your web
 * development needs.
 */


Element.addMethods('tbody', {
	addRow: function (element, caption, input, bold) {
		t = $(element);
		tr = new Element('tr');
		if (bold) tr.setStyle({fontWeight:'bold'});
		td1 = new Element('td').update(caption + (caption.blank() ? '' : ':'));
		if (bold) td1.setStyle({textAlign:'right'});
		td2 = new Element('td');
		if (input.splice) for (i=0; i<input.length; i++) td2.insert(input[i]);
		else td2.insert(input);
		tr.insert(td1).insert(td2);
		t.insert(tr);
		return t;
	},
	addHeader: function (element, header) {
		t = $(element);
		tr = new Element('tr');
		tr.insert(new Element('td', {colspan:'2'}).update(header).setStyle({fontWeight:'bold',textAlign:'center',paddingTop:'8px'}));
		t.insert(tr);
		return t;
	},
	addButtons: function (element, buttons) {
		t = $(element);
		tr = new Element('tr');
		td = new Element('td', {colspan:'2'}).setStyle({textAlign:'center',paddingTop:'8px'});
		for (i=0; i<buttons.length; i++) td.insert(buttons[i]).insert("&nbsp;&nbsp;");
		t.insert(tr.insert(td));
		
		return t;
	}
});

function quoteDetails(firstTime, serviceValue) {
	new Ajax.Request('service_options.php', {
		requestHeaders: {Accept: 'application/json'},
		onSuccess: function(transport){
			opts = transport.responseText.evalJSON(true);
			
			t = new Element('tbody');
		
			if (firstTime) {
				t.addHeader('Select Service Type');			
				for (i=0; i < opts.serviceTypes.length; i++) {
					s = new Element('input', {type:'radio', name:'service_type_radio', id:'service_type_radio', value: i });
					t.addRow(opts.serviceTypes[i].name, s);
				}
									
				t.addButtons([new Element('input', {type:'submit', value:'Select Service', name:'selSubmit'}), new Element('input', {type:'reset', name:'resetSubmit'})]);
			} else {
				// remove service type
				$('quoteDetails1').remove();
			
				// show selected service
				t.addHeader('Service Type: ' + opts.serviceTypes[serviceValue].name);	
				
				s = new Element('select', {name:'service_type', id:'service_type'});
				for (i=0; i<opts.serviceTypes.length; i++) s.insert(new Element('option', {value: i}).update(opts.serviceTypes[i].name));
				//t.addRow('Type of Service',s);
				s.value = serviceValue;
				t.addRow('',s);				
				s.toggle();

				s = new Element('select', {name:'service_method', id:'service_method'});
				for (i=0; i<opts.serviceMethods.length; i++) s.insert(new Element('option', {value: i}).update(opts.serviceMethods[i].name));
				t.addRow('Method of Service',s);
				
				s = new Element('select', {name:'writ_type', id:'writ_type'});
				for (i=0; i<opts.writTypes.length; i++) s.insert(new Element('option', {value: i}).update(opts.writTypes[i].name));
				t.addRow('Type of Paper',s);

				t.addHeader('Serve/Delivery Information');
				t.addRow('Address',new Element('input', {type:'text', name:'address1', id:'address1', size:'30'}));
				t.addRow('',new Element('input', {type:'text', name:'address2', id:'address2', size:'30'}));
				t.addRow('City',new Element('input', {type:'text', name:'city', id:'city', size:'15'}));
				t.addRow('State',new Element('input', {type:'text', name:'state', id:'state', size:'2', maxlength:'2'}));
				t.addRow('Zip',new Element('input', {type:'text', name:'zip', id:'zip', size:'5'}));
					
				//t.addButtons([new Element('input', {type:'submit', value:'Calculate Quote', name:'quoteSubmit'}), new Element('input', {type:'reset'}), new Element('input', {type:'button', value:'Back'})]);
				
				b = new Array();
				b[0] = new Element('input', {type:'submit', value:'Calculate Quote', name:'quoteSubmit'});
				b[1] = new Element('input', {type:'reset'});
				b[2] = new Element('input', {type:'button', value:'Back'});
				Event.observe(b[2],'click',backToIni);
				t.addButtons(b);
				
				Event.observe(b[2],'click',backToQuoteDetails);
			}
			
			if (firstTime) {
				f = new Element('form', {name:'quote2', action:'javascript: validateServiceSel();'}).insert(new Element('table').insert(t));
			} else {
				f = new Element('form', {name:'quote', action:'javascript: validateForm1();'}).insert(new Element('table').insert(t));
			}
			
			if (firstTime) {
				div_id = 'quoteDetails1';
			} else {
				div_id = 'quoteDetails';
			}
			while ($(div_id) != null) div_id += 'x';
			settings.quoteDetails_id = div_id;
			var div = new Element('div', {id:div_id}).insert(f);
			$(settings.div_id).insert(div);
		}
	});
}

function backToIni() {
	// refresh page
	var sURL = unescape(window.location.pathname);
	window.location.href = sURL;
}

function validateServiceSel() {
	f = $H($(document.forms.quote2).serialize(true));
	invalid = '';
		
	f.each(function (x) {
		if (x.key == 'service_type_radio') {
			if (x.value == 0) {
				// redirect to details page
				quoteDetails(false, x.value);	
			} else {
				// redirect to end page
				quoteProcess(f,'',-1, x.value);
			}
		}
	});
	
}

function validateForm1() {
	f = $H($(document.forms.quote).serialize(true));
	invalid = '';
	
	f.each(function (x) {
		if (x.key != 'address2' && (x.value == undefined || x.value.blank())) {
			invalid += (x.key.startsWith('address') ? 'Address' : x.key.capitalize()) + ', ';
			return false;
		}
	});
	
	if (invalid != '') {
		invalid = invalid.slice(0,-2);
		alert('Please fill out all the fields ('+invalid+')');
		return;
	}
	
	f = f.toObject();
	address = new Object();
	address.address = f.address1.strip() + (f.address2.blank() ? '' : ' ' + f.address2.strip());
	address.city = f.city.strip();
	address.state = f.state.strip().toUpperCase();
	address.zip = f.zip.strip();
	address.full = address.address + ' ' + address.city + ', ' + address.state + ' ' + address.zip;
	calculateDistance(address,f);
}

function calculateDistance(address, form) {
  if (GBrowserIsCompatible()) {	
	dir = new GDirections();
	dir.load('from: ' + settings.from_address + ' to: ' + address.full);
	
	var tries = 0;
	
	var updateDistance = function () {
		code = dir.getStatus().code;
		
		if (code == 500) {
			tries++;
			if (tries >= 10 * settings.distance_timeout) {
				clearInterval(timer);
				addressFailure(form,address,code);
			}
		}
		else if (code == 200) {
			clearInterval(timer);
			dist = dir.getDistance().meters / 1609;
			GUnload();
			quoteProcess(form,address,dist, -1);
		}
		else {
			clearInterval(timer);
			addressFailure(form,address,code);
		}
	};
	
	timer = setInterval(updateDistance,100);
  }
}

function addressFailure (form,address,code) {
	m = "Mileage can't be calculated based on the address given ("+code+").\n\n";
	m += address.full + "\n\n";
	m += "Please check that the address you entered is correct, and try again.\n\n";
	m += "If you see this message again, please email for a quote.\n";
	m += "Do you want to send an email request for a quote now?\n ";
	email = confirm(m);
	if (email) quoteProcess(form,address,-1, -1);
}

function quoteProcess(form,address,distance, servTypeRowId) {
	div_id = 'quoteProcess';
	while ($(div_id) != null) div_id += 'x';
	settings.quoteProcess_id = div_id;
	var div = new Element('div', {id:div_id});
	
	qok = distance >= 0;
	
	t = new Element('tbody');
	
	t.addHeader('Quote Amount');
	if (servTypeRowId != -1) {
		t.addRow('Type of Service',['$' + opts.serviceTypes[servTypeRowId].price + ' - ' + opts.serviceTypes[servTypeRowId].name, new Element('input', {type:'hidden', name:'service_type', value:opts.serviceTypes[servTypeRowId].id})]);
	} else {
		t.addRow('Type of Service',['$' + opts.serviceTypes[form.service_type].price + ' - ' + opts.serviceTypes[form.service_type].name, new Element('input', {type:'hidden', name:'service_type', value:opts.serviceTypes[form.service_type].id})]);
		t.addRow('Type of Paper',['$' + opts.writTypes[form.writ_type].price + ' - ' + opts.writTypes[form.writ_type].name, new Element('input', {type:'hidden', name:'writ_type', value:opts.writTypes[form.writ_type].id})]);
		t.addRow('Method of Service',['$' + opts.serviceMethods[form.service_method].price + ' - ' + opts.serviceMethods[form.service_method].name, new Element('input', {type:'hidden', name:'service_method', value:opts.serviceMethods[form.service_method].id})]);
	}
		
	// if not Service Process TotalPrice = Service price and mileage = 0
	if (servTypeRowId != -1) {
		total = opts.serviceTypes[servTypeRowId].price;
		
		t.addRow('',['', new Element('input', {type:'hidden', name:'mileage', value:0})]);
		t.addRow('Total',['$' + total, new Element('input', {type:'hidden', name:'total', value:total})],true);	
	} else {	
		if (qok) {
			var mileage = new Object();
			if (settings.mileage_decimals < 0) settings.mileage_decimals = 0;
			mileage.distance = distance.toFixed(settings.mileage_decimals);
			mileage.cost = (mileage.distance * settings.mile_cost).toFixed(2);
			if (mileage.cost < 16) mileage.cost = 16;
			total = (+opts.serviceTypes[form.service_type].price + +opts.serviceMethods[form.service_method].price + +opts.writTypes[form.writ_type].price + +mileage.cost).toFixed(2);
			
			t.addRow('Mileage',['$' + mileage.cost + ' - ' + mileage.distance + ' miles', new Element('input', {type:'hidden', name:'mileage', value:mileage.distance})]);
			t.addRow('Total',['$' + total, new Element('input', {type:'hidden', name:'total', value:total})],true);
		}
	}
	
	s = new Element('select', {name:'delivery_method', id:'delivery_method'});
	for (i=0; i<opts.deliveryMethods.length; i++) s.insert(new Element('option', {value: opts.deliveryMethods[i].id}).update(opts.deliveryMethods[i].name));
	t.addRow('Delivery Method',s);
	
	t.addHeader('Client Information');
	t.addRow('Name', new Element('input', {type:'text', name:'c_name', id:'c_name', size:'30'}));
	t.addRow('Company', new Element('input', {type:'text', name:'c_company', id:'c_company', size:'30'}));
	t.addRow('Email Address', new Element('input', {type:'text', name:'c_email', id:'c_email', size:'30'}));
	t.addRow('Address', new Element('input', {type:'text', name:'c_address', id:'c_address', size:'30'}));
	t.addRow('City', new Element('input', {type:'text', name:'c_city', id:'c_city', size:'15'}));
	t.addRow('State', new Element('input', {type:'text', name:'c_state', id:'c_state', size:'2'}));
	t.addRow('Zip', new Element('input', {type:'text', name:'c_zip', id:'c_zip', size:'5'}));
	t.addRow('Phone', new Element('input', {type:'text', name:'c_phone', id:'c_phone', size:'12'}));
	t.addRow('Cell', new Element('input', {type:'text', name:'c_cell', id:'c_cell', size:'12'}));
	t.addRow('Fax', new Element('input', {type:'text', name:'c_fax', id:'c_fax', size:'12'}));
	t.addHeader('Subject Information');
	t.addRow('Name(s)', new Element('input', {type:'text', name:'s_name', id:'s_name', size:'30'}));
	t.addRow('Physical Description', new Element('textarea', {name:'s_physical_desc', id:'s_physical_desc', rows:'2', cols:'30'}));
	t.addRow('Company', new Element('input', {type:'text', name:'s_company', id:'s_company', size:'30'}));
	// only add Address information if Service Process
	if  (servTypeRowId == -1) {
		t.addRow('Address', [new Element('span').setStyle({fontWeight:'bold'}).update(address.address), new Element('input', {type:'hidden', name:'s_address', id:'s_address', value:address.address})]);
		t.addRow('City', [new Element('span').setStyle({fontWeight:'bold'}).update(address.city), new Element('input', {type:'hidden', name:'s_city', id:'s_city', value:address.city})]);
		t.addRow('State', [new Element('span').setStyle({fontWeight:'bold'}).update(address.state), new Element('input', {type:'hidden', name:'s_state', id:'s_state', value:address.state})]);
		t.addRow('Zip', [new Element('span').setStyle({fontWeight:'bold'}).update(address.zip), new Element('input', {type:'hidden', name:'s_zip', id:'s_zip', value:address.zip})]);
	}
	t.addRow('Phone', new Element('input', {type:'text', name:'s_phone', id:'s_phone', size:'12'}));
	t.addRow('Cell', new Element('input', {type:'text', name:'s_cell', id:'s_cell', size:'12'}));
	t.addRow('Fax', new Element('input', {type:'text', name:'s_fax', id:'s_fax', size:'12'}));
	t.addRow('Best time to find him', new Element('input', {type:'text', name:'s_best_time', id:'s_best_time', size:'12'}))
	t.addRow('Additional Pertinent Info', new Element('textarea', {name:'s_additional_info', id:'s_additional_info', rows:'2', cols:'30'}));
	t.addHeader('Case Information');
	t.addRow('Case Number', new Element('input', {type:'text', name:'case_number', id:'case_number', size:'8'}));
	s = new Element('select', {name:'court_name_sel', id:'court_name_sel'}).insert(new Element ('option', {value: 0, defaultSelected: true}).update('Other (specify)'));
	for (i=0; i<opts.courtNames.length; i++) s.insert(new Element('option', {value: opts.courtNames[i].name}).update(opts.courtNames[i].name));
	Event.observe(s,'change',combobox);
	t.addRow('Court Name', [s, new Element('br'), new Element('input', {type:'text', name:'court_name_specify', id:'court_name_specify', size:'30'})]);
	t.addRow('Court Date (mm-dd-yyyy)',[
		new Element('input', {type:'text', name:'court_date_m', id:'court_date_m', size:'2', maxlength:'2'}), ' - ',
		new Element('input', {type:'text', name:'court_date_d', id:'court_date_d', size:'2', maxlength:'2'}), ' - ',
		new Element('input', {type:'text', name:'court_date_y', id:'court_date_y', size:'4', maxlength:'4'})]);
	
	if (!qok && (servTypeRowId == -1)) {
		t.addHeader('Quote Request Email');
		t.addRow('Your e-mail address',  new Element('input', {type:'text', name:'e_email', id:'e_email', size:'30'}));
		t.addRow('Comments', new Element('textarea', {name:'e_comments', id:'e_comments', rows:'4', cols:'30'}));
	}
	
	b = new Array();
	// if not Service Procees, then allways submit and pay
	if (servTypeRowId != -1) {
		b[0] = new Element('input', {type:'submit', value:'Submit Request and Pay'});
	} else {
		if (qok) {
			b[0] = new Element('input', {type:'submit', value:'Submit Request and Pay'});
		} else {
			b[0] = new Element('input', {type:'submit', value:'Request Quote'});
		}
	}
	b[1] = new Element('input', {type:'reset'});
	b[2] = new Element('input', {type:'button', value:'Back'});
	Event.observe(b[2],'click',backToQuoteDetails);
	t.addButtons(b);
	
	f = new Element('form', {name:'process', action:'javascript: validateForm2();'}).insert(new Element('table').insert(t));
	
	// if not Service Procees, then allways auto
	if (servTypeRowId != -1) {
		f.insert(new Element('input', {type:'hidden', name:'quote_type', value:'auto'}));
	} else {
		if (qok) {
			f.insert(new Element('input', {type:'hidden', name:'quote_type', value:'auto'}));
		} else {
			f.insert(new Element('input', {type:'hidden', name:'quote_type', value:'email'}));
		}
	}
	
	div.insert(f);
	$(settings.quoteDetails_id).hide().insert({after: div});
}

function validateForm2() {
	
	f = $H($(document.forms.process).serialize(true));
	invalid = '';
	
	required = new Array('c_name','c_email','c_address','c_city','c_state','c_zip','c_phone','s_name','s_physical_desc','e_email');
	
	f.each(function (x) {
		if ( (x.value == undefined || x.value.blank()) && required.indexOf(x.key)!=-1  ) {
			y = x.key.charAt(1) == '_' ? x.key.slice(2) : x.key;
			invalid += y.replace('_',' ').capitalize() + ', ';
			return false;
		}
	});
	
	if (invalid != '') {
		invalid = invalid.slice(0,-2);
		alert('Please fill out all the fields ('+invalid+')');
		return;
	}
	
	f = $(document.forms.process);
	
	v = f.court_name_specify.disabled ? f.court_name_sel.options[f.court_name_sel.selectedIndex].value : f.court_name_specify.value;
	f.insert(new Element('input', {type:'hidden', name:'court_name', value:v}));
	$(f.court_name_specify).disable();
	$(f.court_name_sel).disable();
	
	d = f.court_date_y.value + '-' + f.court_date_m.value + '-' + f.court_date_d.value;
	f.insert(new Element('input', {type:'hidden', name:'court_date', value:d}));
	$(f.court_date_m).disable();
	$(f.court_date_d).disable();
	$(f.court_date_y).disable();

	processRequest();
}

function processRequest() {
	div_id = 'requestProcess';
	while ($(div_id) != null) div_id += 'x';
	settings.requestProcess_id = div_id;
	$(settings.quoteProcess_id).hide().insert({after: new Element('div', {id:div_id})});
	
	f = $(document.forms.process).serialize(true);
	
	new Ajax.Updater(settings.requestProcess_id, 'process_quote.php', {
		method: 'post',
		parameters: f,
		evalScripts: true,
		insertion: 'bottom'
	});
}

function backToQuoteDetails() {
	$(settings.quoteProcess_id).remove();
	settings.quoteProcess_id = undefined;
	$(settings.quoteDetails_id).show();
}

function backToQuoteProcess() {
	$(settings.requestProcess_id).remove();
	settings.requestProcess_id = undefined;
	f = $(document.forms.process);
	$(f.court_date_m).enable();
	$(f.court_date_d).enable();
	$(f.court_date_y).enable();
	if (f.court_name_sel.selectedIndex == 0) $(f.court_name_specify).enable();
	$(f.court_name_sel).enable();
	$(settings.quoteProcess_id).show();
}

function combobox() {
	i = $('court_name_sel').selectedIndex;
	if (i == 0) $('court_name_specify').enable();
	else $('court_name_specify').disable();
}

var settings;
var opts;

new Ajax.Request('webpage.php', {
	requestHeaders: {Accept: 'application/json'},
	onSuccess: function(transport){
		settings = transport.responseText.evalJSON(true);
		g = document.URL.toQueryParams();
		
		if (g.tx != undefined && g.tx.blank && !g.tx.blank()) {
			$(settings.div_id).update('Processing your checkout...');
			
			new Ajax.Updater(settings.div_id, 'checkout.php', {
				method: 'post',
				parameters: g
			});
		}
		else quoteDetails(true);
	}
});

