var RESULTS = {};
var TOTAL_NB_RESULTS = 0;
var SUCCESS_NB_RESULTS = 0;

var ua = navigator.userAgent.toUpperCase();
var av = parseFloat(navigator.appVersion.substring(0,4));
var am = (navigator.appMinorVersion) ? navigator.appMinorVersion.toUpperCase() : '';
var an = navigator.appName;
var bld = 0;/* Gecko or AppleWebKit Build */
var rv = 0;/* Gecko rv: Or MSIE JScript Version */
var lc = 0;
var isDOM = (document.getElementById) ? true : false;/* DOM Use */
var isWinXPSP2 = false;/* WinXP-SP2 and IE 6.0 SP2 */
var versionwmp = null; /* for WMP version */

/* Browser boolean flag */
var isWinIE = false;/* IE 4 - 6 or IE Compatible (for Windows) */
var isMacIE = false;/* IE 4 - 5.2x (for Machintosh) */
var isNN4 = false;/* Netscape 4 - 4.8 */
var isGEC = false;/* Netscape 6 - 7.1 or Gecko Compatible */
var isOPE = false;/* Opera 6 - 7.x */
var isKDE = false;/* Safari 1.0 - 1.1, Omniweb 4.5, Konqueror */

/* Operating System */
var os = 'Other';
var plt = (navigator.platform) ? navigator.platform : 'Other';
var isWin = (plt.indexOf("Win") != -1) ? true : false;
var isMac = (plt.indexOf("Mac") != -1) ? true : false;
var isX11 = (plt.indexOf("X11") != -1 || ua.indexOf("LINUX") != -1 || ua.indexOf("BSD") != -1) ? true : false;

var ajax = false;

var color_bit = screen.colorDepth;

var isOK = '<img style="vertical-align: middle;" src="../../images/checks/vert.gif" /> ';
var isNotOK = '<img style="vertical-align: middle;" src="../../images/checks/rouge.gif" /> ';

if(isWin){
				if(ua.indexOf("WINDOWS NT 6.1") != -1 || ua.indexOf("WINDOWS SEVEN") != -1){ os = "Windows 7";
	}else if(ua.indexOf("WINDOWS NT 6.0") != -1 || ua.indexOf("WINDOWS VISTA") != -1){ os = "Windows Vista";
	}else if(ua.indexOf("NT 5.2") != -1 || ua.indexOf("WS 2003") != -1){ os = "Windows 2003";
	}else if(ua.indexOf("NT 5.1") != -1 || ua.indexOf("WS XP") != -1){ os = "Windows XP";
	}else if(ua.indexOf("NT 5.0") != -1 || ua.indexOf("WS 2000") != -1){ os = "Windows 2000";
	}else if(ua.indexOf("WIN 9x 4.90") != -1 || ua.indexOf("WS ME") != -1){ os = "Windows Me";
	}else if(ua.indexOf("WIN98") != -1 || ua.indexOf("WS 98") != -1){ os = "Windows 98";
	}else if(ua.indexOf("NT 4.0") != -1 || ua.indexOf("WINNT4") != -1){ os = "Windows NT4";
	}else if(ua.indexOf("WIN95") != -1 || ua.indexOf("WS 95") != -1){ os = "Windows 95";
	}else if(ua.indexOf("WS CE") != -1){ os = "Windows CE";
	}else if(ua.indexOf("WS NT") != -1 || ua.indexOf("WINNT") != -1){ os = "Windows NT";
	}else if(ua.indexOf("WS 3.1") != -1){ os = "Windows 3.1";
	}else{ os = plt;}
}else if(isMac){
	os = (ua.indexOf("MAC OS X") != -1 || ua.indexOf("IE 5.2") != -1) ? "MacOSX" : plt;
}else{ os = plt;}

/* Browser UserAgent */
if(window.opera){
	isOPE = true; an = "Opera"; lc = ua.indexOf("OPERA"); av = parseFloat(ua.substring(lc+6,lc+10));
}else if(ua.indexOf("APPLEWEBKIT") != -1 || ua.indexOf("KONQUEROR/") != -1){
	lc = ua.indexOf("APPLEWEBKIT/");
	if(lc > 0){
		bld = parseInt(ua.substring(lc+12,lc+15));
		if(ua.indexOf("SAFARI") != -1){
			an_S = 'SF'; an = "Safari";
			// if(bld >= 100){ av = 1.1;}else if(bld >= 73){av = 1.0;}
		}else if(ua.indexOf("OMNIWEB") != -1){ an = "OmniWeb"; an_S = 'OMN';
		}else{ an = "AppleWebKit";}
	}else {	an = "Konqueror";}
}else if(ua.indexOf("ICAB") != -1){
	an = "iCab";
}else if(ua.indexOf("PLANETWEB") != -1){
	an = "Planetweb";
}else if(ua.indexOf("NETFRONT") != -1){
	an = "NetFront";
}else if(ua.indexOf("DREAMPASSPORT") != -1 && !isWinIE){
	an = "DreamPassport"; os = "DC"; plt = "DC";
}else if(an == "Microsoft Internet Explorer"){
	lc = ua.indexOf("MSIE ");
	if(lc != -1) av = parseFloat(ua.substring(lc+5,lc+9));
}else if(isWinIE){
	an = "Internet Explorer Compatible ("+an+")";
	if(rv >= 5.6){ av = 6;}else if(rv >= 5.5){ av = 5.5;}else if(rv >= 5.1){ av = 5.01;}else if(rv >= 5){ av = 5;}else if(rv >= 3){ av = 4;}
}else if(document.layers && an == "Netscape"){
	isNN4 = true;
}else if(navigator.product && navigator.product == "Gecko" && an == "Netscape"){
	bld = parseInt(navigator.productSub); lc = ua.indexOf("RV:"); isGEC = true;
	if(lc != -1){
		rv = (ua.charAt(lc+6) == ".") ? parseInt(ua.charAt(lc+7)) : 0;
		rv += parseInt(ua.substring(lc+3,lc+6) * 100);
		if(rv != 0) rv = rv / 100;
	}
	if(navigator.vendorSub && ua.indexOf("NETSCAPE") != -1){/* Netscape 6-7 */
		av = parseFloat(navigator.vendorSub.substring(0,3) + navigator.vendorSub.substring(4,5));
	}else{/* Gecko Compatible */
		if(rv >= 1.7){ av = 7.2;}else if(rv >= 1.4){ av = 7.1;}else if(rv >= 1.0){ av = 7;}else if(rv >= 0.94){ av = 6.2;}else if(rv >= 0.92){ av = 6.1;}else{ av = 6.0;}
	}
}

if(an == 'Netscape'){
    
    an = "Firefox";
    if (/Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent)){ //test for Firefox/x.x or Firefox x.x (ignoring remaining digits);
	    var ffversion=new Number(RegExp.$1) // capture x.x portion and store as a number
     if (ffversion>=3)
      av = "3";
     else if (ffversion>=2)
      av = "2";
     else if (ffversion>=1)
      av = "1";
    }
}
var BrowserDetect = {
		init: function () {
			this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
			this.version = this.searchVersion(navigator.userAgent)
				|| this.searchVersion(navigator.appVersion)
				|| "an unknown version";
			this.OS = this.searchString(this.dataOS) || "an unknown OS";
		},
		searchString: function (data) {
			for (var i=0;i<data.length;i++)	{
				var dataString = data[i].string;
				var dataProp = data[i].prop;
				this.versionSearchString = data[i].versionSearch || data[i].identity;
				if (dataString) {
					if (dataString.indexOf(data[i].subString) != -1)
						return data[i].identity;
				}
				else if (dataProp)
					return data[i].identity;
			}
		},
		searchVersion: function (dataString) {
			var index = dataString.indexOf(this.versionSearchString);
			if (index == -1) return;
			return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
		},
		dataBrowser: [
			{
				string: navigator.userAgent,
				subString: "Chrome",
				identity: "Chrome"
			},
			{ 	string: navigator.userAgent,
				subString: "OmniWeb",
				versionSearch: "OmniWeb/",
				identity: "OmniWeb"
			},
			{
				string: navigator.vendor,
				subString: "Apple",
				identity: "Safari",
				versionSearch: "Version"
			},
			{
				prop: window.opera,
				identity: "Opera"
			},
			{
				string: navigator.vendor,
				subString: "iCab",
				identity: "iCab"
			},
			{
				string: navigator.vendor,
				subString: "KDE",
				identity: "Konqueror"
			},
			{
				string: navigator.userAgent,
				subString: "Firefox",
				identity: "Firefox"
			},
			{
				string: navigator.vendor,
				subString: "Camino",
				identity: "Camino"
			},
			{		// for newer Netscapes (6+)
				string: navigator.userAgent,
				subString: "Netscape",
				identity: "Netscape"
			},
			{
				string: navigator.userAgent,
				subString: "MSIE",
				identity: "Explorer",
				versionSearch: "MSIE"
			},
			{
				string: navigator.userAgent,
				subString: "Gecko",
				identity: "Mozilla",
				versionSearch: "rv"
			},
			{ 		// for older Netscapes (4-)
				string: navigator.userAgent,
				subString: "Mozilla",
				identity: "Netscape",
				versionSearch: "Mozilla"
			}
		],
		dataOS : [
			{
				string: navigator.platform,
				subString: "Win",
				identity: "Windows"
			},
			{
				string: navigator.platform,
				subString: "Mac",
				identity: "Mac"
			},
			{
				   string: navigator.userAgent,
				   subString: "iPhone",
				   identity: "iPhone/iPod"
		    },
			{
				string: navigator.platform,
				subString: "Linux",
				identity: "Linux"
			}
		]

	};
	BrowserDetect.init();

/**
 * Return the name of the os
 * 
 * @return string OS name
 */
function os_result(operatingSystemId)
{
	var osTd = $(operatingSystemId);
	if (osTd)
	{
		osTd.innerHTML = os;
		RESULTS.os = os;
	}
}

var r_os = 0;
if (os == "Windows XP" || os == "Windows 2000" || os == "Windows Me" || os == "Windows 98"){
	r_os = 1;
}

function screen_result(screenResultId)
{
	TOTAL_NB_RESULTS++;
	
	var screenTd = $(screenResultId);
	
	if (screenTd)
	{
		if(screen.width >= 1024 && screen.height >= 768)	
		{
			screenTd.innerHTML = isOK + screen.width + 'x' + screen.height;
			RESULTS.screen_resolution = 1;
			SUCCESS_NB_RESULTS++;
		}
		else
		{
			screenTd.innerHTML = isNotOK + screen.width + 'x' + screen.height;
			RESULTS.screen_resolution = 0;
		}
		RESULTS.screen_height = screen.height;
		RESULTS.screen_width = screen.width;
	}
}

var r_screen_w = 0;
if(screen.width >= 1024){
	r_screen_w = 1;
}

var r_screen_h = 0;
if(screen.height >= 768){
r_screen_h = 1;
}

var r_color = 0;
if(color_bit >= 16){
r_color = 1;
}

function java_result(javaVersionId)
{
	TOTAL_NB_RESULTS++;
	
	var javaTd = $(javaVersionId);
	
	if (navigator.javaEnabled())
	{
		javaTd.innerHTML = '<div><applet border="0" code="JavaVersionApplet.class" codebase="js" id="JavaVersionAppletId" name="JavaVersionApplet" height="0" width="0"></applet></div>';

		var version = $('JavaVersionAppletId').getVersion();
		
		RESULTS.java_installed = true;
		
		if (version > "1.4")
		{
			javaTd.innerHTML = isOK + javaVersionStr + ' ' + version;
			RESULTS.java_version = version;
			RESULTS.java = 1;
			SUCCESS_NB_RESULTS++;
		}
		else
		{
			javaTd.innerHTML = isNotOK + javaVersionTooOldStr.replace('{old_version}', version);
			RESULTS.java_version = version;
			RESULTS.java = 0;
		}
	}
	else
	{
		javaTd.innerHTML = isNotOK + javaDisabledStr;
		RESULTS.java_installed = false;
		RESULTS.java_version = 0;
		RESULTS.java = 0;
	}
}

/**
 * Return the browser name and status
 * 
 * @param browserId
 * @return string
 */
function browser_result(browserId)
{
	TOTAL_NB_RESULTS++;
	
	var browserTd = $(browserId);
	
	if (browserTd)
	{
		RESULTS.browser_name = BrowserDetect.browser ;
		RESULTS.browser_version = BrowserDetect.version;
		
		if (an == "Microsoft Internet Explorer" && av >= 6)
		{
			browserTd.innerHTML = isOK + ' ' + BrowserDetect.browser + ' ' + BrowserDetect.version;
			RESULTS.browser = 1;
			SUCCESS_NB_RESULTS++;
		} 
		else if (an == "Firefox" && av >= 2)
		{
			browserTd.innerHTML = isOK + ' ' + BrowserDetect.browser + ' ' + BrowserDetect.version;
			RESULTS.browser = 1;
			SUCCESS_NB_RESULTS++;
		}
		else
		{
			browserTd.innerHTML = isNotOK + ' ' + BrowserDetect.browser + ' ' + BrowserDetect.version;
			RESULTS.browser = 0;
		}
	}
}

var r_browser = 0;
if(an == "Microsoft Internet Explorer" && av >= 5.5){
r_browser = 1;
}

/* check Javascript */
function javascript_show()
{
	document.write(isNotOK);
}
function javascript_result()
{
	document.write(isOK);
}

/* check cookie */
var status="ok";
function cookie_result(cookieResultId)
{
	TOTAL_NB_RESULTS++;
	
	var cookieTd = $(cookieResultId);

	cookie_input();
	if (status=="ok")
	{
		cookieTd.innerHTML = isOK + allowedStr;
		RESULTS.cookie = 1;
		SUCCESS_NB_RESULTS++;
	}
	else
	{
		cookieTd.innerHTML = isNotOK + notAllowedStr;
		RESULTS.cookie = 0;
	}
}

function cookie_input()
{
	setCookie("COOKIE",status);
	status = getCookie("COOKIE");
}

function getCookie(key)
{
	tmp = document.cookie+";";
	tmp1 = tmp.indexOf(key, 0);
	if (tmp1!=-1)
	{
		tmp = tmp.substring(tmp1,tmp.length);
		start = tmp.indexOf("=",0)+1;
		end = tmp.indexOf(";",start);
		return (unescape(tmp.substring(start,end)));
	}
	return("");
}

/**
 * This function set a cookie
 * 
 * @param key name of the field
 * @param val value of the field
 */
function setCookie(key,val) 
{
	tmp = key + "=" + escape(val) + ";";
	document.cookie = tmp;
}

var r_cookie = 0;

cookie_input();

if(status == "ok")
{
	r_cookie = 1;
}

/* check flash player plug-in */
var flashVersion=false;
var nn=(navigator.appName.charAt(0)=="N");
var n6=(document.getElementById && nn) || false;
var ie=(document.all && !nn) || false;
var mac=(navigator.userAgent.indexOf("Mac")!=-1) || false;
var ver=""+navigator.appVersion;
var fno=ver.indexOf(" ");
var macChecked=0;
ver=eval(ver.substring(0,fno));

if (ie && !mac)
{
	var flashVersion=new ActiveXObject("ShockwaveFlash.ShockwaveFlash").FlashVersion();
	flashVersion=Math.floor(flashVersion / 0x10000);
 }

if (!flashVersion)
{    
	if(nn && !document.plugins)
	{
		flashVersion=false;
	}
	else if ((nn || n6) && navigator.plugins)
	{
		flashVersion=navigator.plugins["Shockwave Flash"].description.charAt(16);
		if(navigator.plugins["Shockwave Flash"].description.charAt(17)!= '.')
			flashVersion = flashVersion + navigator.plugins["Shockwave Flash"].description.charAt(17);
	}
	else
	{
		flashVersion=false;
	}
}

if (ie && mac) flashVersion=0;

/**
 * This function check if flash is
 * enable on the client browser
 * and check the flash version
 * 
 * @param flashResultId the id of the TD
 */
function flash_result(flashResultId)
{
	TOTAL_NB_RESULTS++;
	
	var flashTd = $(flashResultId);
	
	if (flashTd)
	{
		if (!flashVersion)
		{
			flashTd.innerHTML = isNotOK + flashPlayerNotInstalledStr;
			RESULTS.flash_installed = false;
		}
		else 
		{
			RESULTS.flash_installed = true;
			
			if (flashVersion >= 6) 
			{
				flashTd.innerHTML = isOK + "Flash Player " + flashVersion;
				RESULTS.flash = 1;
				SUCCESS_NB_RESULTS++;
			} 
			else 
			{
				flashTd.innerHTML = isNotOK + "Flash Player " + flashVersion;
				RESULTS.flash = 0;
			}
		}
		RESULTS.flash_version = flashVersion;
	}
}

var r_flash = 0;
if(flashVersion >= 6){
r_flash = 1;
}


/* check connection speed */
var pageSize  = 316847; 
var myDate    = new Date();
var startTime = myDate.getTime();
var tt =0 ;
var r_speed = 0;
var mes_a_1 = '';
var mes_a_2 = '';
var mes_b_1 = '';
var mes_b_2 = '';

/* Popup blocker detect */
var TestResult = false;
var myPopup = window.open("", "poptest", "width=1, height=1, left=5000, top=5000", true);
if (myPopup)
{
	myPopup.blur();
	myPopup.close();
	TestResult = true;
}

/**
 * Check if the popup blocker is
 * enabled or disable
 * 
 * @param popupId id of the td
 */
function popup_result(popupId)
{
	TOTAL_NB_RESULTS++;

    var popupTd = $(popupId);
	
    if (popupTd)
    {
		if (TestResult)
		{
			popupTd.innerHTML = isOK + popupBlockerDisabled;
			RESULTS.popup_blocker = 1;
			SUCCESS_NB_RESULTS++;
		}
		else
		{
			popupTd.innerHTML = isNotOK + popupBlockerEnabled;
			RESULTS.popup_blocker = 0;
		}
    }
}

var currentPosition;
var currentVolume;
var currentItem;

/**
 * This functionn is used to call
 * server pages using Ajax in order
 * to check DoS attack security
 * 
 * @param repeats number of repeated call
 * @return boolean true if ok
 */
function ajax_result(repeats)
{
	$('ajax_result').innerHTML = isOK + str_ajaxOK;
	
	while(repeats--)
	{
		new Ajax.Request('ping.php?distractor='+repeats, 
		{
			method: "post",
			onSuccess: function(response){
				if (response.responseText !== 'Success')
				{
					$('ajax_result').innerHTML = isNotOK + str_ajaxNotOK;
					RESULTS.ajax = 0;
					updateResults('ajax', RESULTS.ajax);
					return false;
				}
			},
			onFailure: function(response){
				$('ajax_result').innerHTML = isNotOK + str_ajaxNotOK;
				RESULTS.ajax = 0;
				updateResults('ajax', RESULTS.ajax);
				return false;
			}
		});	
	}
	return true;
}

/**
 * Update the value of flash player
 * (if user can play the flash video)
 * 
 * @param val boolean value (1/0)
 */
function updateCanPlayFlv(val)
{
	 if (val == 1)
		 updateResults('flash_player', val, 'NetworkParameterNotificationId', responseUpdatedFlashOn, '#CCF6CA');
	 else
		 updateResults('flash_player', val, 'NetworkParameterNotificationId', responseUpdatedFlashOff, '#E8CCCC');
		 
}

/**
 * Add a notification inside an html element
 * 
 * @param nodeId the id of the html element
 */
function addNotification(nodeId, message, color)
{
	var theNotificationDiv = $(nodeId);
	if (theNotificationDiv)
	{
		// Delete previous child
		theNotificationDiv.innerHTML = '';
		
		// Add the new child
		var div = document.createElement('div');
		div.setAttribute('id', nodeId + '_child');
		div.style.padding = '5px';
		div.style.backgroundColor = color;
		div.style.border = '1px solid black';
		
		if (color == "#CCF6CA")
			div.innerHTML = isOK + ' ' + message;
		else if (color == "#E8CCCC")
			div.innerHTML = isNotOK + ' ' + message;
		else
			div.innerHTML = message;
		
		theNotificationDiv.appendChild(div);
		new Effect.Highlight(div,{});
	}
}

/**
 * Update the value of mp3
 * (if user can play mp3)
 * 
 * @param val boolean value (1/0)
 */
function updateCanPlayMP3(val)
{
	 if (val == 1)
		 updateResults('mp3', val, 'Mp3NotificationId', responseUpdatedMp3On, '#CCF6CA');
	 else
		 updateResults('mp3', val, 'Mp3NotificationId', responseUpdatedMp3Off, '#E8CCCC');
}

/**
 * Update all basic result using
 * an ajax result
 */
function saveResults()
{
	RESULTS.ajax = 1;
	RESULTS.success_control_point = SUCCESS_NB_RESULTS;
	RESULTS.total_control_point = TOTAL_NB_RESULTS;
	
	new Ajax.Request('add_config.php', 
	{
		method: "post", parameters: RESULTS, 
		onSuccess: function(response){
			ajax_result(30);
		}
	});
}

/**
 * Update a specific field with a value
 * using ajax request
 * 
 * @param name the name of the field
 * @param value the value of the field
 * @param notificationNodeId the id of the node to notify
 */
function updateResults(name, value, notificationNodeId, notificationMessage, notificationColor)
{
	RESULTS = {};
	RESULTS.candidate_guid = candidate_guid;
	RESULTS.command = 'update';
	RESULTS.id = candidate_ip;
	RESULTS[name] = value;
	
	new Ajax.Request('add_config.php', 
	{
		method: "post", parameters: RESULTS,
		onSuccess: function(response){
			if (notificationNodeId)
				addNotification(notificationNodeId, notificationMessage, notificationColor);
		}
	});
}

 /**
  * This function send a mail to candidate
  * and include 2 links (in html version
  * and text version) if the optionnal candidateGuid
  * is defined
  * 
  * @param candidateGuid optionnal candidate GUID
  * @return
  */
function sendmail(candidateGuid,  mail)
{
	// prepare parameters
	var params = new Array();
	
	if (candidateGuid && candidateGuid != '')
	{
		params['mode'] = 'logged';
		params['candidate_guid'] = candidateGuid;
		
		if (!mail || mail == '')
			mail = prompt("Enter your email please", "");
	}
	else
	{
		params['mode'] = 'anonymous';
		mail = prompt("Enter your email please", "");
	}
	
	if (!mail || mail == '')
		return;
	
	params['mail_to'] = mail;
	
	// Send ajax request to send the mail
	new Ajax.Request('send_mail.php', 
	{
		method: "post",
		parameters: params,
		onSuccess: function(response) {
				addNotification('MailNotificationId', 'Your email has been sent', '#CCF6CA');
		}
	});
}
  
function time_difference_result(nodeID)
{
	var td = $(nodeID);
	
	if (td)
	{
		var d = new Date();
		var time = Math.round(d.getTime() / 1000);
		var diffSeconds = time - serverTime;
		var diffHours = Math.floor(diffSeconds / 3600);
		var diffMinutes = Math.floor((diffSeconds - diffHours * 3600) / 60);
		
		RESULTS.time_difference = Math.floor(diffSeconds / 60);
		
		if (diffHours != 0 && diffMinutes != 0)
			td.update(hoursMinutesDifference.replace('{minute}', diffMinutes).replace('{hour}', diffHours));
		else if (diffHours != 0)
			td.update(hoursDifference.replace('{hour}', diffHours));
		else if (diffMinutes != 0)
			td.update(minutesDifference.replace('{minute}', diffMinutes));
		else
			td.update(noTimeDifference);
	}
}

