﻿"use strict";  
var XHY = {};

function genId(idLength){
	var chars="0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z";
	chars=chars.split(",");
	var min=0;
	var max=chars.length-1;
	var id="";
	for(var i=0; i<idLength;i++) {
		id+=chars[ Math.floor(Math.random()*(max - min + 1) + min) ];
	}
	return id;
}

XHY.setVisible = function (e) {
	e = document.getElementById(e);
	e.style.visibility = 'visible';
	e.style.display = 'block';
};

XHY.setHidden = function (e) {
	e = document.getElementById(e);
	e.style.visibility = 'hidden';
	e.style.display = 'none';
};
//Remove all children from its parents 
XHY.removeAllChild = function (nodeId) {
	var x = document.getElementById(nodeId);
	if (x.hasChildNodes()) {
		while (x.childNodes.length >= 1) {
			x.removeChild(x.firstChild);       
		} 
	}
};

XHY.clearCookie = function () {
	eraseCookie('id');
};

XHY.init = function () {
	eraseCookie('id');
	cookieId = genId(16);
	createCookie('CAPTCHA_ID',cookieId,1);
	var c = document.getElementById('c1');
	var i = readCookie('CAPTCHA_ID');
	c.style.backgroundImage = 'url(../cgi-bin/js_captcha.cgi?id=' +  i + ')';
	document.getElementById('t4').value = '';
};

//Initialistion functions: Add the correct CSS and JS files to the page 
XHY.addCss = function (sn) {
	var a;

	a = document.createElement("link");
	a.setAttribute("rel", "stylesheet");
	a.setAttribute("type", "text/css");
	a.setAttribute("href", 'js_files/css/' + sn + '.css');
	document.getElementsByTagName("head")[0].appendChild(a);
};

XHY.addJs = function (sn) {
	var a;

	a = document.createElement("script");
	a.setAttribute("src", 'js_files/js/' + sn + '.js');
	a.setAttribute("type", "text/javascript");
	document.getElementsByTagName("head")[0].appendChild(a);
};

// Add the css and the javascript files to the page
XHY.addCss('stylesreg'); 
XHY.addJs('thirdparty/funcs');
XHY.addJs('thirdparty/json2');

//*******************************************************************************************

XHY.alertUser = function(alertText) {
	XHY.removeAllChild('warnbox');
	document.getElementById('warnbox').appendChild(document.createTextNode(alertText));
	XHY.setHidden('ajaxwait');
	XHY.setVisible('btnzone');
}

XHY.signIn = function () {
	var a = document.getElementById('t1').value 
	var b = document.getElementById('t2').value
	if ((a === '') || (b === '')) {
		XHY.alertUser('Un des deux champs est vide');
	} else {
		XHY.reqLogin(a,b);
	}
}

XHY.registerInit = function () {
	var a = document.getElementById('t1').value 
	var b = document.getElementById('t2').value
	var c = document.getElementById('t3').value
	var d = document.getElementById('t4').value  
	
	if (b !== c) {
		XHY.alertUser('Les mots de passe ne sont pas identiques');	
	} else {
		if ((b === '') || (c === '')) {
			XHY.alertUser('Veuillez saisir un nom d\'utilisateur et un mot de passe');
		} else {
			XHY.reqRegister(a,b,d);
		}
	}
}

XHY.getData = function (str) {
	var myObject = JSON.parse(str);
	if (myObject.type === 1) {
		eraseCookie('id');
		document.cookie="id="+myObject.id;
		location.replace("http://www.xuehanyu.org/index.html");
	}
	if (myObject.type === 4) {
		XHY.alertUser('Non d\'utilisateur déjà pris');
	}
	if (myObject.type === 5) {
		XHY.alertUser('Nom d\'utilisateur ou mot de passe inconnu');
	}
	if (myObject.type === 6) {
		XHY.alertUser('Erreur');
	}
	if (myObject.type === 7) {
		XHY.alertUser('Code de sécurité non valable');
		XHY.init();
	}
}

//****************************************************************************************************
//Ultimate Ajax object
XHY.ajaxObject = function (url, callbackFunction) {
	var urlCall, that;
	that = this;
	this.updating = false;
	this.abort = function () {
		if (that.updating) {
			that.updating = false;
			that.AJAX.abort();
			that.AJAX = null;
		}
	};
	this.update = function (passData, postMethod) {
		if (that.updating) {
			return false;
		}
		that.AJAX = null;
		if (window.XMLHttpRequest) {
			that.AJAX = new XMLHttpRequest();
		} else {
			that.AJAX = new ActiveXObject("Microsoft.XMLHTTP");
		}
		if (that.AJAX === null) {
			return false;
		} else {
			that.AJAX.onreadystatechange = function () {
				if (that.AJAX.readyState === 4) {
					that.updating = false;
					that.callback(that.AJAX.responseText, that.AJAX.status, that.AJAX.responseXML);
					that.AJAX = null;
				}
			};
			that.updating = new Date();
			var uri;
			if (/post/i.test(postMethod)) {
				uri = urlCall + '?' + that.updating.getTime();
				that.AJAX.open("POST", uri, true);
				that.AJAX.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
				that.AJAX.setRequestHeader("Content-Length", passData.length);
				that.AJAX.send(passData);
			} else {
				uri = urlCall + '?' + passData + '&timestamp=' + (that.updating.getTime()); 
				that.AJAX.open("GET", uri, true);
				that.AJAX.send(null);
			}
			return true;
		}
	};
	urlCall = url;        
	this.callback = callbackFunction || function () { };
};

//Create the AJAX objects
XHY.ajaxLogin = new XHY.ajaxObject('cgi-bin/js_login.cgi', XHY.getData);
XHY.ajaxRegister = new XHY.ajaxObject('cgi-bin/js_register.cgi', XHY.getData);

//Functions used to send data to the server
XHY.reqLogin = function (a,b) {
	document.cookie="user="+a;
	var tempUrl = 'username=' + a + '&password=' + SHA1.hash(b);
	XHY.ajaxLogin.update(tempUrl);
	XHY.setVisible('ajaxwait');
	XHY.setHidden('btnzone');
}

XHY.reqRegister = function (a,b,d) {
	document.cookie="user="+a;
	var tempUrl = 'username=' + a + '&password=' + SHA1.hash(b) + '&captcha=' + d + '&id=' + readCookie('CAPTCHA_ID');
	XHY.ajaxRegister.update(tempUrl);
	XHY.setVisible('ajaxwait');
	XHY.setHidden('btnzone');
}














/*==========================================================================#
# * Function for adding a Filter to an Input Field                          #
# * @param  : [filterType  ] Type of filter 0=>Alpha, 1=>Num, 2=>AlphaNum   #
# * @param  : [evt         ] The Event Object                               #
# * @param  : [allowDecimal] To allow Decimal Point set this to true        #
# * @param  : [allowCustom ] Custom Characters that are to be allowed       #
#==========================================================================*/
function filterInput(filterType, evt, allowDecimal, allowCustom){
	var keyCode, Char, inputField, filter = '';
	var alpha = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
	var num   = '0123456789';
	// Get the Key Code of the Key pressed if possible else - allow
	if(window.event){
		keyCode = window.event.keyCode;
		evt = window.event;
	}else if (evt)keyCode = evt.which;
	else return true;
	// Setup the allowed Character Set
	if(filterType == 0) filter = alpha;
	else if(filterType == 1) filter = num;
	else if(filterType == 2) filter = alpha + num;
	if(allowCustom)filter += allowCustom;
	if(filter == '')return true;
	// Get the Element that triggered the Event
	inputField = evt.srcElement ? evt.srcElement : evt.target || evt.currentTarget;
	// If the Key Pressed is a CTRL key like Esc, Enter etc - allow
	if((keyCode==null) || (keyCode==0) || (keyCode==8) || (keyCode==9) || (keyCode==13) || (keyCode==27) )return true;
	// Get the Pressed Character
	Char = String.fromCharCode(keyCode);
	// If the Character is a number - allow
	if((filter.indexOf(Char) > -1)) return true;
	// Else if Decimal Point is allowed and the Character is '.' - allow
	else if(filterType == 1 && allowDecimal && (Char == '.') && inputField.value.indexOf('.') == -1)return true;
	else return false;
}

