﻿/*
VERSION
1.1.1	05/12/2010		Fixed a bug when retrieving cities where the formpost key was incorrect. Fixed some minor issues with caching.
1.1.0	01/02/2010		Update to make this a step-by-step form, instead of 1-page linear.
1.0.0	10/14/2009		Beginning version
*/
/* shared form functions */
function BidForm(formName, url, apiUrl) {
this.f = document.forms[formName];
this.f.action = url;
this.apiUrl = apiUrl;
this.ptype = this.f.ptype[this.f.ptype.selectedIndex].value;
this.validators = [];
this.maxNoteLength = 500;
this.currentStep = 0;
this.steps = [];
this.cj = []; //cache for ajax retrieved cities
this.addValidator = function(callback) {
	this.validators.push(callback);
}

this.calcNotesLength = function(charCode) {
	var len = (this.f.notes.value+'').length;

	if(charCode != 8 && len > this.maxNoteLength) {
		this.f.notes.value = this.f.notes.value.substring(0, this.maxNoteLength);
		$('#nchar').text(this.maxNoteLength);
		return false;
	} else if(charCode == 8) {
		len--;
	} else if(charCode) {
		len++;
	}
	$('#nchar').text(len);
	return true;
};

this.checkDup = function() {
	var bool = null;
	var _this = this;
	$.ajax({
		url : _this.apiUrl,
		data : { 'sub' : 'isDuplicateAcctInfo', 'email' : _this.f.email.value, 'username' : _this.f.username.value },
		dataType : 'text',
		type : 'POST',
		cache : false,
		async : false,
		success : function(dups) {
			var errs = [];
			if(String.trim(dups) == '') { return false; }
			try {
				eval('dups = ' + dups + ';');
			} catch(e) {
				alert('There was a problem with the returned checkDup value: ' + e.message);
				return false;
			}
			if(Math.convert(dups['email']) > 0) {
				errs.push('-- The E-mail "' + _this.f.email.value + '" is not unique. If you already have an account, please login.\n');
				_this.setHilite(_this.f.email);
			}
			if(Math.convert(dups['username']) > 0) {
				errs.push('-- The Username "' + _this.f.username.value + '" is not unique. If you already have an account, please login. Otherwise, choose another Username.');
				_this.setHilite(_this.f.username);
			}
			if(errs.length >0) {
				alert('' + errs.join('\n'));
				bool = false;
			} else {
				bool = true;
			}
		},
		error : function(response, status, error) {
			
		}
	});
	return bool;
};
this.checkLogin = function() {
	var bool = null;
	var _this = this;
	$.ajax({
		url : _this.apiUrl,
		data : { 'sub' : 'isValidWebUser', 'username' : _this.f.un.value, 'password' : _this.f.pw.value },
		dataType : 'text',
		type : 'POST',
		cache : false,
		async : false,
		success : function(js) {
			var errs = [];
			if(String.trim(js) == '') { return false; }
			try {
				eval('js = ' + js + ';');
			} catch(e) {
				alert('There was a problem with the returned value checkLogin: ' + e.message);
				return false;
			}
			if(Math.convert(js['username']) == 0) {
				errs.push('-- The Username "' + _this.f.email.value + '" was not found.\n');
				_this.setHilite(_this.f.un);
			} else if(Math.convert(js['password']) == 0) {
				errs.push('-- The Password was incorrect.');
				_this.setHilite(_this.f.pw);
			}
			if(errs.length >0) {
				alert('' + errs.join('\n'));
				bool = false;
			} else {
				bool = true;
			}
			
		},
		error : function(response, status, error) {
			alert(response.responseText);
		}
	});
	return bool;
};
this.clearHilites = function() {
	$('.hilite').removeClass('hilite');
};
this.doSubmit = function() {
	if(this.validate() && confirm('Are you sure you wish to submit this project for bid?')) {
		this.f['sub'].value = 'createBid';
		$('#btnSubmit').html('Please Wait... <img src="' + this.f.tplpath.value + 'icons/clock.png" alt="" border="0" width="16" height="16" class="valign" />').click(function() { return false; });
		this.f.submit();
	}
};
this.populateRegions = function(regions, regionID) {
	if(Math.isNumeric(regionID)) {
		setCookie('defregion', regionID, 3);
	} else {
		regionID = getCookie('defregion');
	}
	var n = regions.length;
	var sel, reg;
	this.f.region.options.length = 0;
	for(var i = 0; i < n; i++) {
		reg = regions[i];
		sel = regionID+'' == reg.id+'';
		this.f.region.options[this.f.region.options.length] = new Option(reg.label + ', ' + reg.state, reg.id, sel, sel);
	}
	if(!Math.isNumeric(regionID)) {
		regionID = this.f.region[this.f.region.selectedIndex].value;
	}
	this.populateCity(regionID);
};
this.populateCity = function(region) {
	var cityID = getCookie('defcity');
	var sel, cit;
	this.f.city.options.length = 0;
	if(!region) { this.f.city.options[0] = new Option('<--', ''); return false; }
	this.f.city.options[0] = new Option('loading...', '');
	var cities = this.retrieveCities(region);
	if(!cities) { this.f.city.options[0].text = 'no cities found...'; return false; }
	var n = cities.length;
	this.f.city.options[0] = new Option('Select your city...', '');
	for(var i = 0; i < n; i++) {
		cit = cities[i];
		sel = cityID+'' == cit.id+'';
		this.f.city.options[this.f.city.options.length] = new Option(cit.city, cit.id, sel, sel);
	}
};
this.retrieveCities = function(region) {
	if(this.cj['id'+region] !== undefined) {
		return this.cj['id'+region];
	}
	var _this = this;
	var output = [];
	$.ajax({
		url : _this.apiUrl,
		data : { 'sub' : 'getCitiesJSON', 'region' : region, 'state' : '' },
		dataType : 'text',
		type : 'POST',
		cache : false,
		async : false,
		success : function(resp) {
			if(resp.indexOf('error') > -1) {
				alert(resp);
				return false;
			}
			eval('output = ' + resp + ';');
			_this.cj['id'+region] = output; //cache it
		},
		error : function(response, status, error) {
			alert(response.responseText);
		}
	});
	return output;
};
this.populateLogin = function(oAcct) {
	if(Math.isNumeric(oAcct['id'])) {
		//user is logged
		$('#accountinfo').hide(0);
		$('#logininfo').hide(0);
		var a = [];
		a.push('<div style=""><br /><span><b>Name:</b> ' + acct.firstname + ' ' + acct.lastname + '</span><br /><br />');
		$('#loggeditems').html(a.join('\n'));
		$('#loggedinfo').show(0);
	}
};
this.populatePType = function(pType) {
	if(Math.isNumeric(pType)) { selectOption(this.f.ptype, pType); }
};
this.setHilite = function(elem) {
	if(elem && elem['className']) {
		elem.className += elem.className.indexOf('hilite') == -1 ? ' hilite' : '';
	}
};
this.validate = function() {
	this.clearHilites();
	var n = this.validators.length;
	for(var i = 0; i < n; i++) {
		if(!this.validators[i](this.f, this)) {
			$('.alert').remove();
			$('#stepbar').after('<div class="alert"><div class="caution">Please review your bid request and correct any hilighted areas before continuing.</div></div>');
			for(var i = 0; i < this.steps.length; i++) {
				if(this.steps[i].find('.hilite').length > 0) { this.currentStep = i; i = this.steps.length + 1; }
			}
			this.showCurrentStep();
			return false;
		}
	}
	return true;
};
this.validateLogin = function(f, _this) {
	if(Math.isNumeric(acct['id'])) {
		f.logintype.value = 0;
		return true;
	} else {
		//not logged, so validate account forms
		var v = new Validation(f);
		if(f.un.value.trim() == '' && f.pw.value.trim() == '') {
				f.logintype.value = 1;
				v.addItem('email', '-- Account E-mail', 'email');
				v.addItem('email1', '-- E-mail Addresses do not match', function(e) { return e.value == f.email.value; });
				v.addItem('firstname', '-- Account First Name');
				v.addItem('lastname', '-- Account Last Name');
				v.addItem('username', '-- Username (at least 5 char)', function(e) { return e.value.length >= 5; });
				v.addItem('password', '-- Password');
				v.addItem('password1', '-- Passwords do not match', function(e) { return e.value == f.password.value; });
			
				if(v.validate() && _this.checkDup()) {
					return true;
				}
		} else {
				f.logintype.value = 2;
				v.addItem('un', '-- Your Username');
				v.addItem('pw', '-- Your Password');
				if(v.validate() && _this.checkLogin()) {
					return true;
				}
		}
		return false;
	}
};
this.next = function() {
	if(this.currentStep < this.steps.length-1) {
		this.currentStep++;
		this.showCurrentStep();
	}
};
this.prev = function() {
	if(this.currentStep > 0) {
		this.currentStep--;
		this.showCurrentStep();
	}
};
this.goTo = function(n) {
	if(!isNaN(n) && n >= 0 && n < this.steps.length) {
		this.currentStep = n;
		this.showCurrentStep();
	}
};
this.showCurrentStep = function() {
	$('#stepbar td').removeClass('active');
	var s;
	for(var i = this.steps.length-1; i >= 0; i--) {
		s = this.steps[i];
		if(i != this.currentStep) {
			s.fadeOut(0);
		} else {
			s.show(0);
			$('#stepbar td:eq('+i+')').addClass('active');
		}
	}
	if(this.currentStep < this.steps.length-1) {
		$('#btnSubmit').parent().hide();
		$('#btnNext').parent().show();
	} else {
		$('#btnSubmit').parent().show();
		$('#btnNext').parent().hide();
	}
	if(this.currentStep > 0) {
		$('#btnPrev').parent().show();
	} else {
		$('#btnPrev').parent().hide();	
	}
	this.steps[this.currentStep].find('.textbox:first').select();
};
this.createStepBar = function() {
	var n = this.steps.length;
	var wid =  Math.floor(100/n);
	var tbl = ['<div id="stepbar" ><div class="capleft"></div><table><tbody><tr>'];
	var islast;
	for(var i = 0; i < n; i++) {
		islast = i == this.steps.length -1;
		tbl.push('<td onclick="mybidform.goTo(' + i + ');" title="Go to Step ' + (i+1) + '" class="' + (i != this.currentStep ? '' : 'active') + (!islast ? '' : ' last') + '" style="' + (i>0?'width:'+wid+'%;' : '') + '">');
		tbl.push('<div>');
		tbl.push(!islast ? 'Step ' + (i+1) : 'Finish');
		tbl.push('</div></td>');
	}
	tbl.push('</tr></tbody></table><div class="capright"></div></div>');
	$('#bidform h4').after(tbl.join('\n'));
};
this.init = function() {
	var _this = this;
	var f = _this.f;
	$('#btnSubmit').parent().hide(0);
	$('#formarea fieldset').each(function(i, e) {
		_this.steps.push($(e));
		_this.steps[i].children('legend').html('Step ' + (i+1) + ': ' + _this.steps[i].children('legend').html());
		//_this.steps[i].find('.fieldset:odd').addClass('alt');
	});
	_this.createStepBar();
	_this.showCurrentStep();
	
	this.addValidator(this.validateLogin);
	
	$('#btnSubmit').click(function() { _this.doSubmit(); });
	$('#btnNext').click(function() { _this.next(); });
	$('#btnPrev').click(function() { _this.prev(); });

	f.region.onchange = function() {
		_this.populateCity(this.value);
		setCookie('defregion', this.value+'', 3);
	};
	f.city.onchange = function() {
		setCookie('defcity', this.value, 1);
	};
	f.ptype.onchange = function() {
		if(window.confirm('Are you sure you wish to change the Project Type?\n\nThe form will re-load and you will lose any progress.')) {
			f['sub'].value = '';
			f.submit();
		}
		selectOption(this, _this.ptype);
		return false;
	};
	if(f['phone']) {
		f.phone.onchange = function() { this.value = Renderer.phone(this.value); }
	}
	if(f['notes']) {
		f.notes.onkeypress = function(evt) {
			evt = evt || window.event;
			var ccode = !evt['keyCode'] ? evt.charCode : ((evt.which) ? evt.which : evt.keyCode);
			return _this.calcNotesLength(ccode);
			var len = (this.value+'').length;
		}
		f.notes.onblur = function() {
			_this.calcNotesLength();
		}
		this.calcNotesLength();
	}
	$('.textbox.number').each(function(i, e) {
		e.onblur = function() { if(!Math.isNumeric(this.value) || this.value < 0) { this.value = 0; } else { this.value = Math.floor(this.value); } };
	});
};

}; //end BidForm

