function validateEmail(email) {
	var invalidChars = " /:;,";
	if (email == "") { return false; } 
	for (var k=0; k < invalidChars.length; k++) {
		var badChar = invalidChars.charAt(k);
		if (email.indexOf(badChar) > -1) { return false; }
	}
	var atPos = email.indexOf("@", 1);
	if (atPos == -1) { return false; }
	if (email.indexOf("@", atPos+1) != -1) { return false; }
	var periodPos = email.indexOf(".",atPos);
	if (periodPos == -1) { return false; }
	if (periodPos+3 > email.length) { return false; }
	return true;
}

function RegisterAPI(options) {
	//options expect some or all of {email:email,fullname:fullName,password:_password,autologin:true}
	this.Params = { //also used as defaults
			email : "",
			fullname : "",
			password : "",
			/*sex:"",
			b_month:"",
			b_day:"",
			b_year:"",*/
			autoLogin : false
	}
	
	this.baseURL = "";
	$.extend(this.Params, options); //rewrite defaults if needed
	//console.log("Params: "+this.Params.email+","+this.Params.fullname+","+this.Params.password+","+this.Params.autoLogin);
	
	if (baseURL != "undefined" && (typeof baseURL) != "undefined") {
		this.baseURL = GetBaseURL();
	}
	
	//console.log(baseURL);
	//this.init();
}

RegisterAPI.prototype.init = function() {
	//some init stuff
	//console.log('Register INIT runnign');
	this.processRegister();
}

RegisterAPI.prototype.processRegister = function() {
	this.getMessagingServer();
	if (this.messagingServer == undefined || this.version == undefined) { return false; }//if missing any one of these
	var requestFile = this.baseURL + "proxy/" +this.messagingServer+'/messages_'+this.version+'/process/registerUserFromBanner.php';
	var obj = this; //for scope
	var ciphertext = des(userKey, this.Params.password, 1, 0);
	pass = userKey + stringToHex(ciphertext);
	
	var dataObj = {fullname: this.Params.fullname,
			username: this.Params.email,
			/*sex: this.Params.sex,
			b_month: this.Params.b_month,
			b_day: this.Params.b_day,
			b_year: this.Params.b_year,*/
			pwd: pass };
	if(this.Params.args!=undefined)
		dataObj.args = this.Params.args;
	
	$.ajax({
		url: requestFile,
		type: "POST",
		async: false,
		data: dataObj,
		error: function (xhr, textStatus, errorThrown) {
			if (xhr.responseText.indexOf("</WResult>") > 0) { //catch xml errors again - stupid IE.
					xmlDoc = obj.loadXML(xhr.responseText); 
					x = xmlDoc.childNodes[0].childNodes;
					errorCode = x[1].childNodes[0].firstChild.nodeValue; //code
					errorDescription = x[1].childNodes[1].firstChild.nodeValue; //description
					obj.onRegisterError(errorCode, errorDescription, this.Params );
			} else {
				obj.onError(xhr, textStatus);
			}
			
		},		
		success: function(responseText) {
			if (((typeof responseText) == 'xml') || (((typeof responseText) == 'string') && (responseText.indexOf("</WResult>") > 0))) {
				xmlDoc = obj.loadXML(responseText);
				x = xmlDoc.childNodes[0].childNodes;
				//type node x[1].nodeName;
				responseType = x[0].firstChild.nodeValue //should be error
				if (responseType == 'Error') {
					errorCode = x[1].childNodes[0].firstChild.nodeValue;
					errorDescription = x[1].childNodes[1].firstChild.nodeValue;
					obj.onRegisterError(errorCode, errorDescription, this.Params );
				} else {
					//alert("Unexpected Response Type: "+responseType);
				}
			} else if (responseText == "0") {
						if (obj.Params.autoLogin) {
							login.login({username: obj.Params.email, password: obj.Params.password});
						}
						obj.onRegister( this.Params ); //trigger event
			} else {
				alert("Unexpected Return Value: "+responseText);
				return false;
			}
		}
	});
	
}

RegisterAPI.prototype.getMessagingServer = function() {
	var obj = this; //scope
	$.ajax({
		async: false,
		cache: false,
		dataType: "json",
		type: "POST",
		data: { user: 'none' },
		success: function(data, textStatus) {
			if (data['error'] == undefined) {
				obj.messagingServer = data['server'];
				obj.version = data['version'];
			} else {
				obj.onLoginFailed(0, 'Couldn\'t find user');
			}
		},
		error: function(XHR, textStatus, errorThrown) {
			obj.onError(XHR, textStatus);
		},
		url: this.baseURL + "ajax/getUserLoginServer.php"
	});
}


//event function
RegisterAPI.prototype.onRegister = function( params ) {
	//if (console) console.log("onRegister event triggered");
	watchitoo_OnRegister( params );
}

RegisterAPI.prototype.onError = function(xhr, text) {
	watchitoo_OnError(text);
}

RegisterAPI.prototype.onRegisterError = function(errorCode, errorDesciption, params) {
	watchitoo_OnRegisterError(errorCode, errorDesciption, params);
}

//Helper functions
RegisterAPI.prototype.loadXML = function(text) {
	try { //Internet Explorer  
		xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
		xmlDoc.async="false";
		xmlDoc.loadXML(text);
	} catch(e) {
		try { //Firefox, Mozilla, Opera, etc.
			parser=new DOMParser();
			xmlDoc=parser.parseFromString(text,"text/xml");
		} catch(e) {alert(e.message)}
	}
	return xmlDoc;
}

//Below - Validation is now done via flex

RegisterAPI.prototype.validate = function(form) {
	var bPassed = false;
	var fullname = form.fullname.value;
	var username = form.email.value;
	var password = form.password.value;
	var password2 = form.password_confirm.value;
	

	if (!this.validEmail(username)) {
		$('#errorMessage').text("Username must be a valid email address");
	} else if (fullname == "") {
		$('#errorMessage').text("Please enter a Full Name");
	} else if (password == "") {
		$('#errorMessage').text("Please enter a password");
	} else if (password2 != password) {
		$('#errorMessage').text("Passwords do not match");
	} else {
		bPassed = true;
	}
	
	if (bPassed) {
		this.Params.fullname = fullname;
		this.Params.email = username; //actualy his email
		this.Params.password = password;
		this.processRegister();
	}

	return false;
}

RegisterAPI.prototype.validEmail = function(email) {
	var invalidChars = " /:;,";
	if (email == "") { return false; } 
	for (var k=0; k < invalidChars.length; k++) {
		var badChar = invalidChars.charAt(k);
		if (email.indexOf(badChar) > -1) { return false; }
	}
	var atPos = email.indexOf("@", 1);
	if (atPos == -1) { return false; }
	if (email.indexOf("@", atPos+1) != -1) { return false; }
	var periodPos = email.indexOf(".",atPos);
	if (periodPos == -1) { return false; }
	if (periodPos+3 > email.length) { return false; }
	return true;
}