function setCookie(name, value) {
	var end = new Date();
	end.setTime( end.getTime() + 3600 * 1000 );
	var str=name+"="+escape(value)+"; expires="+end.toGMTString()+"; path=/";
	document.cookie = str;
}
function getCookie(name) {
	var debut = document.cookie.indexOf(name);
	if( debut == -1 )	return null;
	var end = document.cookie.indexOf( ";", debut+name.length+1 );
	if( end == -1 ) end = document.cookie.length;
	return unescape( document.cookie.substring( debut+name.length+1, end ) );
}

function close_important(element) {
	element.style.opacity = 0;
	setTimeout(function(){ element.parentNode.removeChild(element); }, 200);
}

/*
	Send post ajax request to url defined in action.
	Callback the function defined in the callback attribute from the submit type.
*/
function ajaxWrapper(evt){
	evt.preventDefault();
	var elems = evt.target;
	var params = "";
	// do not embed submit value (-1)
	for(i = 0; i < elems.length-1; i++){
		if(params) params += "&";
		params += encodeURIComponent(elems[i].name)+"="+encodeURIComponent(elems[i].value);
	}
	const req = new XMLHttpRequest();
	req.open("POST", evt.target.action, true);
	req.setRequestHeader('Content-Type',"application/x-www-form-urlencoded");
	req.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
	req.onreadystatechange = function(){
		if(req.readyState == 4 && (req.status == 200 || req.status == 0)){
			var fn = window[elems[elems.length-1].getAttribute("callback")];
			if(typeof fn == 'function'){
				fn(req.responseText);
			}
		}
	}
	req.send(params);
}

/*
	Add event listener on submit for all form with class with-ajax.
*/

window.onload = function(){

	var ele;
	var elems = document.getElementsByClassName('with-ajax');
	for(i = 0; i < elems.length; i++){
		ele = elems[i];
		if(ele.addEventListener){		// Normal people
			ele.addEventListener("submit", ajaxWrapper, false);
		}else if(ele.attachEvent){		// Retarded user using IE
			ele.attachEvent("onsubmit", ajaxWrapper);
		}
	}

	if(getCookie('pc_notif') == 'true')
		document.getElementsByClassName('alert')[0].parentNode.removeChild(document.getElementsByClassName('alert')[0]);
	if(getCookie('pc_notif_2') == 'true')
		document.getElementsByClassName('alert')[0].parentNode.removeChild(document.getElementsByClassName('alert')[0]);

}

function login(response){
	alert(response);
}