var req;//our request resource

function loadXMLDoc(url) {
    req = false;
    
    // branch for native XMLHttpRequest object
    if(window.XMLHttpRequest) {
    	try {
			req = new XMLHttpRequest();
        } catch(e) {
			req = false;
        }
    // branch for IE/Windows ActiveX version
    } else if(window.ActiveXObject) {
       	try {
        	req = new ActiveXObject("Msxml2.XMLHTTP");
      	} catch(e) {
        	try {
          		req = new ActiveXObject("Microsoft.XMLHTTP");
        	} catch(e) {
          		req = false;
        	}
		}
    }
	if(req) {
        //if is ok request the php file
		req.onreadystatechange = processReqChange;
		req.open("GET", url, true);
		req.send(null);
	}
}

function processReqChange() {
    element = document.getElementById('status');
    //waiting the php
    if (req.readyState == 1) {
        element.innerHTML = 'зареждане...моля изчакайте...';
    }
    //the XML is here
    if (req.readyState == 4) {
        if (req.status == 200) {
            check_status();
        } else {
        //fuck! some shit happened
            document.getElementById('status').innerHTML = "Възникна вътрешен проблем! моля да ни извините";
        }
    }
}

function logIn() {
    //check if the user entered username
    var user = document.getElementById('user').value;
    var pass = document.getElementById('pass').value;
    
    if(user == '')
        document.getElementById('status').innerHTML = 'моля въведете потребител!';
    //check if the user entered password
    else if(pass == '')
        document.getElementById('status').innerHTML = 'моля въведете парола!';
    //if everything is ok - proceed
    else {
        //we ask the php to check the login info
        loadXMLDoc('login.php?user='+user+'&pass='+pass);
    }
}

//parse the info given from login.php
function check_status() {
    var data = req.responseXML.getElementsByTagName("rez");
    //case the user info is incorrect 
    if(data.item(0).firstChild.nodeValue == '0')
        document.getElementById('status').innerHTML = 'грешен потребител и/или парола!';
    //case user and pass are ok
    else
        //enter the admin panel
        window.location = 'main.php';        
}
