// ---------------------------------------------------------------------------
// PNet home pages
// Copyright (c) Apricon AB 2006
// Original filename: index.js
// @author        Erik Schölander
// @created       2006-04-02
// @version       1.0.0
// @desc   Generic JavaScript functions for the home page.
// @usage  Shall be included in the head section of index.asp. 
//
// @change  2006-05-03  ESR  internal_link updated
// @change  2007-01-04  ESR  New function getXMLHTTPRequest
// @change  2007-06-19  ESR  Most functions from js_end.inc moved here
//                           sendLoginAjax, sendLoginCallback, logger added. check_login changed
// @change  2008-05-08 ESR   Fix for Firefox 3 in sendLoginAjax
// @change  2008-05-13 ESR   Disabling login form during wait
// @change  2009-03-11 ESR   check_login, sendLoginAjax
// @change  2009-12-12 ESR   using logger.asp in /asp3/home
// @change  2010-02-26 ESR   check_login()
// @change  2011-06-22 ESR   logger()
// @change  2011-07-07 ESR   New function open_teamviewer()
// @--------------------------------------------------------------------------

var logfile =      '/asp3/home/logger.asp';              //path to log file
var loginrequest = '/system1/login.jsp';                 //address to call for security handle
var nextpage =     '/Asp3/ProjPage/MyProjectsMain.asp';  //where to go after requiring a SEC

//----------------------------------------------------------------------------
//@desc  Checks the data fields of the login form before login.
//       Also calls logger.asp (HTTPrequest) to log system information
//
//@return  True if the fields of the login form are correctly filled in
//
// @change  2007-06-19  ESR  Login to Picnic 3 possible
// @change  2009-03-11  ESR  Login to Picnic 3 only option.
// @change  2010-02-26  ESR  Login prohibited if browserStatus is 'bad'
//@---------------------------------------------------------------------------
var counter;
function check_login()
{
	try {
		if (document.login_form.USER.value == '') {
			alert(txtErrEnterUID+'!');
			document.forms.login_form.USER.focus();
			return(false);
		}
		if (document.login_form.TEMPPASS.value == '') {
			alert(txtErrEnterPass+'!');
			document.forms.login_form.TEMPPASS.focus();
			return(false);
		}
		if (browserStatus == 'bad') {
			alert(txtErrBrowserBad+'!');
			return(false);
		}
		deleteCookie("PersInfoCookie");  //Remove some old junk that interfers
		deleteCookie("LangCookie");
		setCookie("UserName", document.login_form.USER.value);
		document.login_form.REALPASS.value = document.login_form.TEMPPASS.value;
		document.login_form.TEMPPASS.value = '';             //Prevents the password from beeing stored by the browser
		//Use a HTTPrequest (AJAX) call to login.jsp to initialize a CaraDoc session
		//Abort the submit. sendLoginAjax will redirect.
		disable_loginform();
		counter=0;
		sendLoginAjax(document.login_form);
		logger();   //Use a HTTPrequest (AJAX) call to logger.asp to log system information
	} catch(e) {
		alert('Programming error on login')
		enable_loginform();
	}
	return(false);
}


//----------------------------------------------------------------------------
//@desc  Disable the fields in the login form.
//@since 2008-05-07
//@---------------------------------------------------------------------------
function disable_loginform() {
	document.forms.login_form.USER.setAttribute('disabled', true);
	document.forms.login_form.TEMPPASS.setAttribute('disabled', true);
	document.forms.login_form.loginbtn.value = txtWait+'...';
	document.forms.login_form.loginbtn.setAttribute('disabled', true);
}

//----------------------------------------------------------------------------
//@desc  Enable the fields in the login form.
//@since 2008-05-07
//@---------------------------------------------------------------------------
function enable_loginform() {
	document.forms.login_form.USER.setAttribute('disabled', false);
	document.forms.login_form.TEMPPASS.setAttribute('disabled', false);
	document.forms.login_form.loginbtn.setAttribute('disabled', false);
	document.forms.login_form.USER.removeAttribute('disabled');  
	document.forms.login_form.TEMPPASS.removeAttribute('disabled');  
	document.forms.login_form.loginbtn.removeAttribute('disabled');  
	document.forms.login_form.loginbtn.value = txtLogin;
	document.forms.login_form.TEMPPASS.focus();
}


// ---------------------------------------------------------------------------
// @desc  This function change the address for the current window to a specific
//        page and subpage or newsid of the Pnet home page.
// @usage Use this for internal links in all information pages, so that they can 
//        work in the project page in Pnet as well.
//
// @change  2006-05-03  ESR  New argument newsid. Function can be called with 
//                           either page/subpage or newsid.
// @--------------------------------------------------------------------------
function internal_link(page,subpage,lang,newsid) {
	var url = 'index.asp';
	var delim = '?';

	if(page!=undefined && page!='') {
		url = url + delim + 'page=' + page;
		delim = '&';
	}
	if(subpage!=undefined && subpage!='') {
		url = url + delim + 'subpage=' + subpage;
		delim = '&';
	}
	if(lang!=undefined && lang!='') {
		url = url + delim + 'lang=' + lang;
		delim = '&';
	}
	if(newsid!=undefined && newsid!='') {
		url = url + delim + 'newsid=' + newsid;
		delim = '&';
	}
	location.href = url;
}

// ---------------------------------------------------------------------------
// Create an XMLHTTPRequest object
// ---------------------------------------------------------------------------
function getXMLHTTPRequest() {
	try {
		req = new XMLHttpRequest();
	} catch(err1) {
		try {
		req = new ActiveXObject('Msxml2.XMLHTTP');
		} catch(err2) {
			try {
			req = new ActiveXObject('Microsoft.XMLHTTP');
			} catch(err3) {
				req = false;
			}
		}
	}
	return req;
}


// ---------------------------------------------------------------------------
// @desc Send form data to emailFormServlet.asp that will send it by email
//
// @param  form_id      ID for the form element to send data from
// @param  progress_id  ID for the element containing a progress bar
// @param  status_id    ID for the element display status text in
// @param  ok_text      text to display when the operation went OK 
// @--------------------------------------------------------------------------
var httpForm;
function sendFormAjax(form_id,progress_id,status_id,ok_text) {
	var i;
	
	document.getElementById(status_id).innerHTML = '';
	var params = 'formid='+form_id;
	var frm = document.getElementById(form_id);
	for (i = 1; i < frm.elements.length; i++) {
		params = params+'&'+frm.elements[i].name+'='+escape(frm.elements[i].value);
	}
	
	httpForm = getXMLHTTPRequest();
	httpForm.open('POST','emailFormServlet.asp',true);
	httpForm.onreadystatechange = function() {sendFormCallback(progress_id,status_id,ok_text)};
	httpForm.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	httpForm.send(params);
}

// ---------------------------------------------------------------------------
// @desc Callback function for sendFormAjax
//
// @param  status_id  ID for the element display status text in
// @param  ok_text    text to display when the operation went OK 
// @--------------------------------------------------------------------------
function sendFormCallback(progress_id,status_id,ok_text) {
				alert('callback')
	if (httpForm.readyState == 4) {
		if (httpForm.status == 200) {
			var err = httpForm.responseXML.getElementsByTagName('err')[0];
			var errnumber = err.getElementsByTagName('number')[0].childNodes[0].nodeValue;
			if (errnumber > 0) {
				document.getElementById(status_id).innerHTML = 'Error: '+err.getElementsByTagName('description')[0].childNodes[0].nodeValue;
			}
			else {
				document.getElementById(status_id).innerHTML = ok_text;
			}
			if(progress_id!='') document.getElementById(progress_id).style.display = 'none';
		} else {
			document.getElementById('status_id').innerHTML = 'Error: '+httpForm.status+' - '+httpForm.statusText
		}
	} else {
		if(progress_id!='') document.getElementById(progress_id).style.display = '';
	}
}


// ---------------------------------------------------------------------------
// @desc Send form data to emailFormServlet.asp that will send it by email
//
// @param  form_id      ID for the form element to send data from
// @param  progress_id  ID for the element containing a progress bar
// @param  status_id    ID for the element display status text in
// @param  ok_text      text to display when the operation went OK 
//
// @change  2008-05-08 ESR   Fix for Firefox 3, adjusted call to httpLogin3.open
// @change  2008-06-24 ESR   escape() on username and password to handle special characters
// @change  2009-03-11  ESR  GET instead of POST, to handle problem with special characters in Firefox 3.
// @--------------------------------------------------------------------------
var httpLogin3;
function sendLoginAjax(frm) {
	if (location.protocol!='https:') {
		alert('Password may not be checked on an uncrypted connedtion. The page address should start with https:');
		return(false);
	}
		
	var address = '/system1/login.jsp';

	var params = 'username='+escape(frm.elements['USER'].value);
	params = params+'&password='+escape(frm.elements['REALPASS'].value);
	params = params+'&language='+frm.elements['adpt_lang'].value;
	
	httpLogin3 = getXMLHTTPRequest();
						//alert(address+'?'+params);
	httpLogin3.open('GET',address+'?'+params,true);
	httpLogin3.onreadystatechange = function() {sendLoginCallback(frm,address)};
	httpLogin3.send('');

//	httpLogin3.open('POST',address,true)
//	httpLogin3.onreadystatechange = function() {sendLoginCallback(frm,address)};
//	httpLogin3.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
//	httpLogin3.send(params);
	
	return(true);
}


// ---------------------------------------------------------------------------
// @desc Callback function for sendLoginAjax
//
// @param  status_id  ID for the element display status text in
// @param  ok_text    text to display when the operation went OK 
// @--------------------------------------------------------------------------
function sendLoginCallback(frm,address) {
	if (httpLogin3.readyState == 4) {
		window.status = '';
		if (httpLogin3.status == 200) {
			try {
				var objSec = httpLogin3.responseXML.getElementsByTagName('sec')[0]; 
				var objErr = httpLogin3.responseXML.getElementsByTagName('error')[0]; 
			} catch(e) {
											status='no data 1';
  				alert('No readable data returned from login function');
				enable_loginform();
			}
			
			if (objSec.hasChildNodes()) {
											status='login success';
				logger();      //log system information
				//location.href = '/system1/CaraDoc.html?sec='+objSec.firstChild.data+'&language='+lang;						
				location.href = '/Asp3/ProjPage/MyProjectsMain.asp?sec='+objSec.firstChild.data;						
				//alert('/system1/CaraDoc.html?sec='+objSec.firstChild.data);						
			} else if (objErr.hasChildNodes()) {
											status='error found';
				var objErrcode = objErr.getElementsByTagName('code')[0];
				var strErrcode = "";
				if (objErrcode.hasChildNodes()) {strErrcode = objErrcode.firstChild.data;}
				var objErrcomment = objErr.getElementsByTagName('comment')[0];
				var strErrcomment = "";
				if (objErrcomment.hasChildNodes()) {strErrcomment = objErrcomment.firstChild.data;}
				
				if (strErrcode == 'EurekaExceptionSecurity') {alert(txtErrWrongPass);}
				else if (strErrcode == 'EurekaExceptionAccessError') {alert(txtErrDBAccess);}  //DOES NOT WORK!!!
				else if (strErrcode != '') {alert(strErrcode+': '+objErrcomment);}
				else {alert('ERROR: '+objErr.getElementsByTagName('raw')[0].firstChild.data);}
				enable_loginform();
			} else {
  				alert('No readable data returned from login function');
				enable_loginform();
			}
		} else {
			alert('Login function '+address+' returned status code: '+httpLogin3.status);
			enable_loginform();
		}
	} else {
		//waiting for response
	}
}


// ---------------------------------------------------------------------------
// @desc Use a HTTPrequest (AJAX) call to logger.asp to log system information %>
//
// @change  2011-06-22 ESR   No longer asynchronous call (unstable). 
// @--------------------------------------------------------------------------
function logger() {
	var http = getXMLHTTPRequest();
	if(http) {
		var requestUrl = logfile;
		requestUrl = requestUrl+'?user='+document.login_form.USER.value;
		requestUrl = requestUrl+'&browserName='+browserName;
		requestUrl = requestUrl+'&browserVersion='+browserVersion;
		requestUrl = requestUrl+'&osName='+osName;
		requestUrl = requestUrl+'&screenSize='+screenSize;

		requestUrl = requestUrl+'&rand='+parseInt(Math.random()*999999999999999);
		http.open('GET',requestUrl,false)
		http.send(null);
	}
}


// ---------------------------------------------------------------------------
// @desc Sets the value of a given cookie %>
//
// @param  name   cookie name
// @param  value  value to set
// @--------------------------------------------------------------------------
function setCookie(name, value)
{
	var exp = new Date();
	exp.setTime(exp.getTime() + 365 * 24 * 60 * 60 * 1000);

	var curCookie = name + "=" + escape(value) +
		"; expires=" + exp.toGMTString() +
		"; path=" + "/";
	document.cookie = curCookie;
}  // setCookie()


// ---------------------------------------------------------------------------
// @desc Returns the value of a given cookie %>
//
// @param  name   cookie name
// @--------------------------------------------------------------------------
function getCookie(name) 
{
			//alert(document.cookie);
	var dc = document.cookie;  
	var prefix = name + "=";
	var begin = dc.indexOf(prefix);  

	if (begin == -1)
	{
		return null;
	}
	var end = document.cookie.indexOf(";", begin);  
	if (end == -1)
	{
    	end = dc.length;  
	}
	
	return unescape(dc.substring(begin + prefix.length, end));
}  // getCookie()

// ---------------------------------------------------------------------------
// @desc Deletes a given cookie %>
//
// @param  name   cookie name
// @--------------------------------------------------------------------------
function deleteCookie(name)
{
	var exp = new Date();
	exp.setTime(exp.getTime() - 24 * 60 * 60 * 1000);
	var value = '';
	
	var curCookie = name + "=" + escape(value) +
		"; expires=" + exp.toGMTString() +
		"; path=" + "/";
	document.cookie = curCookie;
}  // deleteCookie()


// ---------------------------------------------------------------------------
// @desc Opens a new window with window.open() %>
// @--------------------------------------------------------------------------
function open_url(url,name,optstr)
{
	window.open(url,name,optstr);
}

// ---------------------------------------------------------------------------
// @desc Opens a new named window with window.open() %>
// @--------------------------------------------------------------------------
function open_named(url,name,optstr)
{
	window.open('/' + url + '&cfgset='+cfgset,name,optstr);
}

// ---------------------------------------------------------------------------
// @desc Download/open the right version of the TeamViewer program %>
// @--------------------------------------------------------------------------
function open_teamviewer(language) {
	browser_check('c3');
	if(osName=='Mac OS X') {
		location = '/util/TeamViewerQS.dmg';
	} else {
		if (language.toUpperCase()=='SV') {
			location = '/util/TeamViewerQS_sv.exe';
		} else {
			location = '/util/TeamViewerQS_en.exe';
		}
	}
}

