/* 
uservalidation.js

This script:
	1.authenticates the user/pass on www
	2.sends response data to na
	3.updates html without refresh

Variables set in secureLogin.jsp:
	isUserLoggedIn
	displayName
	username

----------------------------------------------------------------------------*/

//init for the DWR scripts
if (document.location.href.indexOf("http://com-") > -1 && 
		document.location.href.indexOf("5p") < 0) {
    dwr.engine._defaultPath = 'https://www.blackberry.com/CorpDevZoneQA/dwr';   
    cdzHandler._path = 'https://www.blackberry.com/CorpDevZoneQA/dwr';	
} else {
    dwr.engine._defaultPath = 'https://www.blackberry.com/CorpDevZone/dwr';   
    cdzHandler._path = 'https://www.blackberry.com/CorpDevZone/dwr';
}

DWREngine.setRpcType(DWREngine.ScriptTag);

//xhr processor for na
function getXmlHttp(){
  var xmlhttp;
  try {
    xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
  } catch (e) {
    try {
      xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    } catch (E) {
      xmlhttp = false;
    }
  }
  if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
    xmlhttp = new XMLHttpRequest();
  }
  return xmlhttp;
}

function getUrl(url, cb) {
  var xmlhttp = getXmlHttp();
  xmlhttp.open("GET", url);
  xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4) {
      cb(xmlhttp.status, 
         xmlhttp.getAllResponseHeaders(), 
         xmlhttp.responseText);
      }
  }
  xmlhttp.send(null);
}

//after login, data is back from na, now update the page
function gotAuth(status, headers, response){
	if(response == "Success"){
		//clear the error
		$('error').style.display = 'none';
		//update HTML
		devLoginLoggedIn();
		isUserLoggedIn = true;
	}else{
		//update HTML
		$('error').innerHTML = response;
		//show the error
		$('error').style.display ='block';
	}
}

//after logout, update the page
function resetLogin(status, headers, response){
	try{$('devlogintxt').remove();}catch(e){}
	$('devloginform').style.display = 'block';
	if(username != null)$('id_user').value = username;
	isUserLoggedIn = false;
}


//user validation (xhr+java) method on www
function authenticateUser(){
	cdzHandler.authenticateUser(DWRUtil.getValue("id_user"), DWRUtil.getValue("id_pass"), DWRUtil.getValue("id_zone"), null, makeRequest);
}

//construct a query to send off to na to set the session variables and cookie
function makeRequest(data){
//if cdzHandler.authenticateUser is working
if (data){
	var baseUrl = 'http://'+document.location.hostname+'/secure/processResponse.do';
	var url;
	var devLoginCode = data["responseCode"];
	
	function fullString(){
		var devLoginMail = $('id_user').value;
		var devLoginRemember = $('id_remember').checked;
		//rim knows the other values available in the data array, we just need name
		var devLoginName = data["responseName"];
		//we just need the first name
		var devName = devLoginName.split(",");
		displayName = devName[0];
		if (devName.length > 1 && devName[1] != 'undefined') {
			displayName = displayName + " " + devName[1];
		}
		//query contruct
		url = baseUrl + "?status=" + devLoginCode + "&displayName=" + displayName + "&rememberMe=" + devLoginRemember + "&username=" + devLoginMail;
		//this makes an xhr call on na
		//syntax: getUrl(url to post to, function to run after response)
		getUrl(url, gotAuth);
		}
	
	function minString(){
		//query contruct
		url = baseUrl + "?status=" + devLoginCode;
		//this makes an xhr call on na
		//syntax: getUrl(url to post to, function to run after response)
		getUrl(url, gotAuth);
		}
	
	//depending on the response we get from 
	//cdzHandler.authenticateUser, construct the appropriate string
	switch (devLoginCode) {
		case "1": fullString(); break;
		case "2": minString(); break;
		case "3": minString(); break;
		case "4": minString(); break;
		case "5": loadProfileLink(); break;
		default: alert('Error, please reload the page');
		}
	}
	
	//cdzHandler.authenticateUser is NOT working
	//else{ 
	//	alert('Error, please reload the page');
	//	}
} // /makeRequest()

function loadProfileLink() {
	if (document.location.href.indexOf("http://com-") > -1 && 
			document.location.href.indexOf("5p") < 0) {
		document.location.href = "https://www.blackberry.com/CorpDevZoneQA/edit.jsp";
	} else {
		document.location.href = "https://www.blackberry.com/CorpDevZone/edit.jsp";
	}
}

//builds the html for the logged-in state
function devLoginLoggedIn(){
	//fix for the flickering if logged in and refreshing the page
	$('devloginform').style.display = 'none';
	//build the tags, sets attributes etc
	var d = document.createElement('div');
	d.setAttribute('id','devlogintxt');
	$('devlogin').appendChild(d);
	var h = document.createElement('h3');
	h.innerHTML = "Good ";
	var periodText = "Morning";
	if (new Date().getHours() > 12) {
		periodText = "Afternoon";
	}
	h.innerHTML += periodText + ", ";
	displayName == null || displayName == "null" ? h.innerHTML += "" : h.innerHTML += displayName + ".<br/><span class='spacer'></span>" + "Welcome to the BlackBerry Developer Zone!";
	$('devlogintxt').appendChild(h);
	var p = document.createElement('p');
	p.className = 'loggedInP';
	var a = document.createElement('a');
	a.setAttribute('href','#');
	a.setAttribute('id', 'logoutButton');
	
	var a2 = document.createElement('a');
	a2.setAttribute("href", "https://www.blackberry.com/CorpDevZone/edit.jsp");
	if (document.location.href.indexOf("http://com-") > -1 && 
			document.location.href.indexOf("5p") < 0) {
		a2.setAttribute("href", "https://www.blackberry.com/CorpDevZoneQA/edit.jsp");
	}
	a2.className = "editProfile";
	
	//trigger for the logout routine
	a.onclick = function(event) {
		devLoginLogOut();
		//if (document.location.href != "http://na.blackberry.com/eng/developers/") {
			document.location.href = "http://"+document.location.hostname+"/developers/?logout=true";
		//}
		if (event && event.preventDefault) event.preventDefault(); return false;
	};
	a.innerHTML = "Logout";
	p.appendChild(a);
	p.appendChild(a2);
	//inject the code
	$('devlogintxt').appendChild(p);
}

//logout routine
function devLoginLogOut(){
	var url = "http://"+document.location.hostname+"/secure/logout.do";
	//this makes an xhr call on na
	//syntax: getUrl(url to post to, function to run after response)
	getUrl(url, resetLogin);
}

//checks for logged/not-logged in, auto populates, etc...
function devLoginInit(){
	if(isUserLoggedIn){
		devLoginLoggedIn();
	}else if(username != null){
		//auto-populate the username field
		$('id_user').value = username;
		}
}

Event.onDOMReady(function(){
	devLoginInit();
});
