
/*jslint plusplus:false, evil:true, browser:true, fragment:true, white:false, eqeqeq:false */
/*global $,$$,DOMAssistant,BrowserDetect,POP,preventDefault,o,EF,LB,getAncestor,DND,GEO,TAGS,AJAXGet,escape,niceText,purge,sfHover,IE6TRICKS,GETEXTRAS,WMAIL */


// for validating forms - these o are often loaded by XHR
BBX.namespace('formtools');
BBX.formtools = function() {

	

	var o = {

		// set the default for mtype
		mtype:'user',
		
		MsgHolder:function(reg,admin) {
			this.admin = admin; // the message for admins
			this.user = reg;  // the message for normal folk
		},

	
		email_pattern:/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i,
	    email_extraction_pattern:/([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)/i,
		
		testEmail:function(eml) {
			return o.email_pattern.test(eml)
		},
		
		
		remErr:function(inputid) {
			var ipt;
			if(typeof inputid == 'string') {
				if(!$$(inputid)) {BBX.log('no '+inputid); return;}
				ipt = $$(inputid);
			} else {
				ipt = inputid;
			}
			// get the first div ancestor, (we'll remove the error from that)
			var par = BBX.traverse.getAncestorByTag(ipt,'div');
			
			if(par) {
				$(par).elmsByClass('error').remove();
				$(par).elmsByClass('valid').remove();
				$(par).elmsByClass('notice').remove();
				$(par).elmsByClass('errtext').remove();
				$(par).removeClass('ok').removeClass('haserror');
			}
			
			return par;
		},
		
		err:function(inputid,msg) {
			var par = o.remErr(inputid);
			if(par) {
			    par.addClass('haserror');
			    
			    if(par.elmsByClass('iptholder').length > 0) {
				par.elmsByClass('iptholder').first().create('span',{className:"error"},true,'!');
			    } else if(par.elmsByClass('taholder').length > 0) {
				par.elmsByClass('taholder').first().create('span',{className:"error"},true,'!');
			    } else {
				par.create('span',{className:"error"},true,'!');
			    }
			    
			    if(msg.length > 0) {
					var emsg = par.create('p',{className:"errtext"},true,msg);
					
					// this is a bit of a hack, but stops us from having problems in IE8
					if(!$('body').hasClass('accountpage')) {
						BBX.fat.fade_element(emsg,30,2000,'#FFBBBB');
					}
			    }
			}
		},
		
	    formErr:function(f,msg) {
	    	var dv = f.create('div',null,false);
	        var m = dv.create('p',{className:"errtext"},true,msg);
	        f.insertBefore(dv,f.firstChild);
	        BBX.fat.fade_element(m,30,2000,'#FFBBBB');
	    },
	    
		note:function(inputid,msg) {
			var par = o.remErr(inputid);
			if(par) {
				if(msg.length > 0) {par.create('p',{className:"notice"},true,msg);}
			}
		},
		
		
		ok:function(inputid) {
			var par = o.remErr(inputid);
	        if(par.elmsByClass('iptholder').length > 0) {
				par.elmsByClass('iptholder').first().create('span',{className:"valid"},true,BBX.langdata.getData('valid'));
			} else if(par.elmsByClass('taholder').length) {
	        	par.elmsByClass('taholder').first().create('span',{className:"valid"},true,BBX.langdata.getData('valid'));
	        } else {
	       		par.create('span',{className:"valid"},true,BBX.langdata.getData('valid'));
			}
	    },
		
		chkBnameInput:function(inputid,mtype,omitserver) {
			if(mtype === undefined) {
				mtype = o.mtype;
			}
			var ipt = $$(inputid);
			var bn = ipt.value;
			if(bn.length === 0) {
				o.err(inputid,BBX.langdata.getData('ft choose bname'));
				return false;
			} else if(!/^[-_A-Za-z0-9]+$/.test(bn)) {
	        	o.err(inputid,BBX.langdata.getData('ft invalid bname'));
	            return false;
	        } else if(omitserver !== true) {
	        	ipt.ajax({'method':'POST','url':'/apps/checkforbname.php','callback':function(res) {o.bnameSR(res,inputid,mtype);},'params':'bn='+encodeURIComponent(bn)});
				return 'wait for xhr';
			} else {
	        	return true;
	        }
		},
		
		bnameSR:function(res,inputid,mtype) {

			if(mtype === undefined) {
				mtype = o.mtype;
			}
			
			var r;
			r = eval(res);
			if(r.error == 'bonzo name already exists') {
				o.err(inputid,BBX.langdata.getData('ft bname taken'));
			} else if(r.error == 0 && r.existing == 0) {
				o.ok(inputid);
			}
		},
		
		chkEmlInput:function(inputid,checkunique,mtype) {
	//		$("debugger").value = 'check email ';
			if(mtype === undefined) {
				mtype = o.mtype;
			}
			
			var ipt = $$(inputid);
			var eml = ipt.value;
			if(!o.testEmail(eml)) {
				o.err(inputid,BBX.langdata.getData('ft invalid email'));
				return false;
			}
			
			if(checkunique) {
	//			$("debugger").value = 'check unique';
				ipt.ajax({'method':'POST','url':'/apps/checkforemail.php','params':'e='+encodeURIComponent(eml),'callback':function(res) {o.emlSR(res,inputid,mtype);}});
				return 'wait for xhr';
			} else {
				o.ok(inputid);
				return true;
			}
		},
		
		emlSR:function(res,inputid,mtype) {
			var r=eval(res);
			
			if(mtype === undefined) {
				mtype = o.mtype;
			}
			
			if(r.error==0 && r.existing==0) {
				o.ok(inputid);
				return 'verified';
			} else if(r.error=='e-mail already exists' && r.existing > 0) {
	//			alert('mtype: '+mtype+' inputid: '+inputid);
				var msg = new o.MsgHolder(BBX.langdata.getData('ft email already member'),'There is already an account with this E-mail address.');
	//			alert('mtype: '+mtype+' inputid: '+inputid);
				o.err(inputid,msg[mtype]);
				return 'already exists';
			}
		},
		
		chkEmlConf:function(inputid,initialinputid) {
			if(!$$(inputid)) {return;}
			var eml = $$(initialinputid).value;
			var ceml = $$(inputid).value;
			if(!o.email_pattern.test(ceml)) {
				o.err(inputid,BBX.langdata.getData('ft invalid email'));
				return false;
			} else if(eml != ceml) {
				o.err(inputid,BBX.langdata.getData('ft emails dont match'));
				return false;
			} else {
				o.ok(inputid);
				return true;
			}
		},
		
		chkPass:function(inputid,mtype) {
			if(!$$(inputid)) {return;}
			
			if(mtype === undefined) {
				mtype = o.mtype;
			}
			
			var p = $$(inputid).value;
			if(p.length < 6) {
				var msg = new o.MsgHolder(BBX.langdata.getData('ft pass too short'),'The password must be at least 6 characters long.');
				o.err(inputid,msg[mtype]);
				return false;
			} else {
				o.ok(inputid);
				return true;
			}
		},
		
		chkPassConf:function(inputid,initialinputid,mtype) {
			if(!$$(inputid) || !$$(initialinputid)) { return;}
			
			if(mtype === undefined) {
				mtype = o.mtype;
			}
			
			var p = $$(initialinputid).value;
			var cp = $$(inputid).value;
			if(p != cp) {
				o.err(inputid,BBX.langdata.getData('ft passes dont match'));
				return false;
			} else if(cp.length < 6) {
				var msg = new o.MsgHolder(BBX.langdata.getData('ft pass too short'),'The password must be at least 6 characters long.');
				o.err(inputid,msg[mtype]);
				return false;
			} else {
				o.ok(inputid);
				return true;
			}
		},
		
		chkFname:function(inputid,mtype) {
			if(!$$(inputid)) { return; }
			if(mtype === undefined) {
				mtype = o.mtype;
			}
			var fn = $$(inputid).value;
			if(fn.length < 1) {
				var msg = new o.MsgHolder(BBX.langdata.getData('ft enter first name'),'Please enter the user\'s first name.');
				o.err(inputid,msg[mtype]);
				return false;
			} else {
				o.ok(inputid);
				return true;
			}
		},
		
		chkLname:function(inputid,mtype) {
			if(!$$(inputid)) {return;}
			if(mtype === undefined) {
				mtype = o.mtype;
			}
			var fn = $$(inputid).value;
			if(fn.length < 1) {
				var msg = new o.MsgHolder(BBX.langdata.getData('ft enter last name'),'Please enter the user\'s last name.');
				o.err(inputid,msg[mtype]);
				return false;
			} else {
				o.ok(inputid);
				return true;
			}
		},
		
		chkAge:function(inputid,mtype) {
			if(!$$(inputid)) {return;}
			if(mtype === undefined) {
				mtype = o.mtype;
			}
			var age = $$(inputid).value;
			if(age.length < 1 || ((age*1)=='NaN')) {
				var msg = new o.MsgHolder(BBX.langdata.getData('ft enter age'),'Please enter the user\'s age in years.');
				o.err(inputid,msg[mtype]);
				return false;
			} else {
				o.ok(inputid);
				return true;
			}
		},
		
		chkSex:function(inputid,mtype) {
			if(!$$(inputid)) {return;}
			if(mtype === undefined) {
				mtype = o.mtype;
			}
			var s=$$(inputid).value;
			if(s != 'M' && s != 'F') {
				var msg = new o.MsgHolder(BBX.langdata.getData('ft enter gender'),'Please enter the user\'s gender.');
				o.err(inputid,msg[mtype]);
				return false;
			} else {
				o.ok(inputid);
				return true;
			}
		},
		
		chkAgree:function(inputid) {
			if(!$$(inputid)) {return;}
			if(!$$(inputid).checked) {
			    o.err(inputid,BBX.langdata.getData('ft must agree to policies'));
			    return false;
			} else {
			    o.remErr(inputid);
			    return true;
			}
		},
		
		chkComments:function(inputid) {
			if(!$$(inputid)) {return;}
			if($$(inputid).value.length < 5) {
				o.err(inputid,BBX.langdata.getData('ft enter a message'));
				return false;
			} else {
				o.ok(inputid);
				return true;
			}
		},
		
		chkField:function(inputid) {
			if(!$$(inputid)) {return;}
			if($$(inputid).value.length === 0) {
				o.err(inputid,BBX.langdata.getData('ft provide this information'));
				return false;
			} else {
				o.ok(inputid);
				return true;
			}
		},
		
		
		
	
		chkDate:function(minputid,dinputid,yinputid) {
			var valid = true;
			var monthLength = [31,28,31,30,31,30,31,31,30,31,30,31];	
			var x = document.forms[0].elements;
			var day = parseInt($$(dinputid).options[$$(dinputid).selectedIndex].value,10);
			var month = parseInt($$(minputid).options[$$(minputid).selectedIndex].value,10);
			var year = $$(yinputid).options[$$(yinputid).selectedIndex].value;
			
			if(year.length !== 4) {
				valid = false;
			}
			year = parseInt(year,10);
		
			if (!day || !month || !year) {
				valid = false;
			}
		
			if (year/4 == parseInt(year/4,10)) {
				monthLength[1] = 29;
			}
			if (day > monthLength[month-1]) {
				valid = false;
			}
			monthLength[1] = 28;
		
		
			var now = new Date();
			now = now.getTime(); //NN3
		
			var dateToCheck = new Date();
			dateToCheck.setYear(year);
			dateToCheck.setMonth(month-1);
			dateToCheck.setDate(day);
			var checkDate = dateToCheck.getTime();
		
			if(now < checkDate) {
				valid = false;
			}
		
			if(valid) {
				o.ok(yinputid);
				return true;
			} else {
				o.err(yinputid,BBX.langdata.getData('ft enter a valid date'));
				return false;
			}
		},
		
		setSelect:function(inputref,value) {
		// sets the select referenced in inputref to have the option with value "value" selected, if such an option exists
			var opts = inputref.options;
			for(var i=0;i<opts.length;i++) {
				if(opts[i].value == value) {
					inputref.selectedIndex = i;
					break;
				}
			}
		},
		
		
		/* Sets this form to the "working" state, shows a progress meter in place of the submit button to prevent multiple submits  */
		setWorking:function(form) {
			var f = $(form);
			f.elmsByClass('working').first().addClass('show').removeClass('working');
	        f.cssSelect('button[type="submit"]').first().disabled = true;
		},
		
		/* does the opposite of setWorking  */
		unsetWorking:function(form) {
			var f = $(form);
			f.elmsByClass('show').first().addClass('working').removeClass('show');
	        f.cssSelect('button[type="submit"]').first().disabled = false;
		}
		
		
	
	}
	
	return o;
	
}();







