/*** Graceful degrade for non-javascript users & some event capture for livesearch ***/

window.onload = addscript; // Graceful degrade stuff for non-javascript users
document.onclick = hidelivesearch; // Onclick capturing for closing live search box

function addscript() {
	// check to see that the browser supports the getElementById method
	if (!document.getElementById) {
		return false; 
	} else {
		document.getElementById('countriesanchor').href = "#";  // Replace conventional url in countries footer link
		document.getElementById('searchfield').value= " Suche";
		document.getElementById('popupclose').innerHTML = "<a href='#' target='_self' onclick='window.close();'>close window <img src='gx_en/ui/ajaxclose.gif' border='0' alt='close window' /></a>"; //Add close window link for popup template
	}
}
	
function openpopup() {
	//window.open(linkURL,'popup','width=' + w +',height=' + h);
	window.open('popup.html','popup','width=500,height=500');
}


/*** START Primary nav hover function for IE ***/

sfHover = function() {
	if(document.getElementById("nav") != null)
	{
		var sfEls = document.getElementById("nav").getElementsByTagName("LI");
		for (var i=0; i<sfEls.length; i++) {
			sfEls[i].onmouseover=function() {
				this.className+=" sfhover";
			}
			sfEls[i].onmouseout=function() {
				this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
			}
		}
	}
}
if (window.attachEvent) window.attachEvent("onload", sfHover);

/*** START Countries selector ***/

// Preload the AJAX loading gif
ajaxgif=new Image();
ajaxgif.src="gx_en/ui/ajaxload.gif";

function countriesreveal() { // Show, hide or add to territory selector box
	document.getElementById('countriesbox').style.visibility = 'visible';
	//loadXMLDoc('territories.xml');
}

function countrieshide() { 	// Clear the contents of the box and hide the div
	document.getElementById('countriescontents').innerHTML = "";  
	document.getElementById('countriesbox').style.visibility = 'hidden';  
}
  
// Start the AJAX stuff
var xmlhttp;
function loadXMLDoc(url) { // Open XML http request & load doc

	// Display the AJAX loading gif
	document.getElementById('countriescontents').innerHTML = '<p style="text-align: center; color: #999999; font-weight: bold;"><img src="gx_en/ui/ajaxload.gif" id="ajaxloadinggif" alt="loading options" style="margin: 50px 10px 0 0;" />Loading options</p>';
	document.getElementById('ajaxloadinggif').src=ajaxgif.src;
		
	xmlhttp=null;
	url = "gx_en/ajax/countries/" + url; // Amend to the directory where xml files are stored

	if (window.XMLHttpRequest) {// code for IE7, Firefox, Mozilla, etc.
		xmlhttp=new XMLHttpRequest();
	}
	else if (window.ActiveXObject) {// code for IE5, IE6
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	if (xmlhttp!=null) {
		xmlhttp.onreadystatechange=processXML;
		xmlhttp.open("GET",url,true);
		xmlhttp.send(null);
	}
	else {
		//alert("Your browser does not support XMLHTTP.");
		countrieshide();
		return;
	}
}

function processXML() { // Check if file is valid & if so do something with its contents
	if(xmlhttp.readyState!=4) return;
	if(xmlhttp.status!=200) {
		//alert("Problem retrieving XML data");
		countrieshide();
		return;
	}

	// Grab & display the appropriate header
	document.getElementById('countriesboxhead').innerHTML = "";
	h=xmlhttp.responseXML.documentElement.getElementsByTagName("header");
	var countriesheader="<div id='countriestitle'>" + h[0].firstChild.nodeValue + "</div><br clear='all' />";

	document.getElementById('countriescontents').innerHTML = "";
	var countriesoutput="<table border='0' id='countriestable'><tr>";


	// CONTINENTS
	y=xmlhttp.responseXML.documentElement.getElementsByTagName("continent");
	if (y.length!=0) { // Only loop through this is there are continents to process (top level XML file)
		countriesoutput=countriesoutput + "<td class='continentcell'><strong>Find by region</strong><br /><ul class='continentlist'>"
	
		for (i=0;i<y.length;i++) {
			ynames=y[i].getElementsByTagName("name");
			ycodes=y[i].getElementsByTagName("code"); {
			try {
				countriesoutput=countriesoutput + "<li><a href='#' onClick='loadXMLDoc(\"" + ycodes[0].firstChild.nodeValue +".xml\");return false;'>" + ynames[0].firstChild.nodeValue + "</a></li>";
			}
				catch (er) { countriesoutput=countriesoutput + "&nbsp;"; }
			}				
		}
		countriesoutput=countriesoutput + "</ul></td>"
	}
	
	
	// COUNTRIES
	x=xmlhttp.responseXML.documentElement.getElementsByTagName("territory");

	// Some logic to determine number of columns
	var colsize, colnums;
	if (x.length<=20) { colnums = 2; // 2 columns if 20 or less countries
	} else if (x.length<=30) { colnums = 3; // 3 columns if 30 or less countries
	} else if (x.length<=40) { colnums = 4; // 4 columns if 40 or less countries
	} else if (x.length<=50) { colnums = 5; // 5 columns if 50 or less countries
	}
	colsize = Math.round((x.length/colnums))	

	if (y.length!=0) {
    countriesoutput=countriesoutput + "<td><strong>Popular sites</strong><br /><ul class='countrylist'>"
	} else {
    countriesoutput=countriesoutput + "<td><ul class='countrylist'>"
  }
	
	for (i=0;i<x.length;i++) {
	
		// Split into further columns based on above logic
		if (colsize==i||(colsize*2)==i||(colsize*3)==i||(colsize*4)==i||(colsize*5)==i) { 
			if (y.length!=0) {
			 countriesoutput=countriesoutput + "</ul></td><td><br /><ul class='countrylist'>";
			} else {
        countriesoutput=countriesoutput + "</ul></td><td><ul class='countrylist'>";
      }
		}
		
		xnames=x[i].getElementsByTagName("name");
		xurls=x[i].getElementsByTagName("url"); {
		try {
			countriesoutput=countriesoutput + "<li><a href='" + xurls[0].firstChild.nodeValue + "'>" + xnames[0].firstChild.nodeValue + "</a></li>";
		}
			catch (er) { countriesoutput=countriesoutput + "&nbsp;"; }
		}				
	}
	countriesoutput=countriesoutput + "</ul></td></tr></table><br clear='all' />"
	
	// Finally write the output; close button, header & contents.
	document.getElementById('countriesboxclose').innerHTML = "<a href='#' onClick='countrieshide(); return false;'><img src='gx_en/ui/ajaxclose.gif' alt='Close' border='0' id='countriesclosebutton' /></a>"
	document.getElementById('countriesboxhead').innerHTML = countriesheader;
	document.getElementById('countriescontents').innerHTML += countriesoutput;
}

/*** START Live search ***/

var xmlHttp
	
function showResult(str) {
	// Clear the suggestions box when no chars
	if (str.length<=minchars) {
		document.getElementById("livesearch").innerHTML="";
		document.getElementById("livesearch").style.visibility="hidden";
		return
	}
	if (livesearchon!="true") {
		return
	}
	
	// Place the AJAX loading gif. Replaced with the clear icon after the request is complete (below)
	document.getElementById("livesearchbutton").src="gx_en/ui/ajaxload.gif";
	document.getElementById("livesearchbutton").className="";
	
	xmlhttp=null;
	url = suggestionsfile + "livesearch.xml"; // Amend to the directory where xml file is stored

	if (window.XMLHttpRequest) {// code for IE7, Firefox, Mozilla, etc.
		xmlhttp=new XMLHttpRequest();
	}
	else if (window.ActiveXObject) {// code for IE5, IE6
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	if (xmlhttp!=null) {
		xmlhttp.onreadystatechange=processsearch;
		xmlhttp.open("GET",url,true);
		xmlhttp.send(null);
	}
	else {
		//alert("Your browser does not support XMLHTTP.");
		clearlivesearch();
		return;
	}
}

function processsearch() { // Check if file is valid & if so do something with its contents

	// Take the current search string
	var str = document.getElementById("searchfield").value.toLowerCase();

	// Break the loop when http call is complete or there's an error
	if(xmlhttp.readyState!=4) return;
	if(xmlhttp.status!=200) {
		//alert("Problem retrieving XML data");
		clearlivesearch();
		return;
	}

	// Locate the link element to traverse
	x=xmlhttp.responseXML.documentElement.getElementsByTagName("link");
	var searchoutput = "";
	var searchoutputheader = "<div id='livesearchheader'>Recommended results</div>";
	var searchoutputfooter = "<div id='livesearchfooter'><a href='#'>View all results >></a></div>"; 
	if (str.length > minchars) {

		// Loop through all link elements
		for (i=0;i<x.length;i++) {

			xtitles=x[i].getElementsByTagName("title");
			xurls=x[i].getElementsByTagName("url"); {
			try {
				// The magic of string matching (must be lowercare)
				var testquery = xtitles[0].firstChild.nodeValue.toLowerCase();
				if (testquery.indexOf(str) !=-1) {
					searchoutput = searchoutput + "<a href='" + xurls[0].firstChild.nodeValue + "'>" + xtitles[0].firstChild.nodeValue + "</a><br />";
				} else {
					searchoutput = searchoutput + "";
				}
			}
				catch (er) { searchoutput = searchoutput + ""; }
			}				
		}

	}

	if (searchoutput=="") { 
		// Collapse the suggestions box when no matches & halt the ajax loading gif
		document.getElementById("livesearch").style.visibility="hidden";
		document.getElementById("livesearchbutton").src="gx_en/ui/ajaxclose.gif"; // Show the close button, replacing the ajax gif
		document.getElementById("livesearchbutton").className="livesearchclose";
	} else {
		// Return the response, only when xml http call is done. Show the close button, replacing the ajax gif
		if (xmlhttp.readyState==4 || xmlhttp.readyState=="complete") { 
			document.getElementById("livesearch").style.visibility="visible";
			document.getElementById("livesearch").innerHTML=searchoutputheader + searchoutput + searchoutputfooter;
			document.getElementById("livesearchbutton").src="gx_en/ui/ajaxclose.gif";
			document.getElementById("livesearchbutton").className="livesearchclose";
		} 
	}

}

function clearsearch() { //Clear from initial focus
	document.getElementById("searchfield").value="";
}

function clearlivesearch() { // Clear from the button & also hide the button
	document.getElementById("searchfield").value=" Suche";
	document.getElementById("livesearch").innerHTML="";
	document.getElementById("livesearch").style.visibility="hidden";
	document.getElementById("livesearchbutton").src="gx_en/ui/tran.gif";
	document.getElementById("livesearchbutton").className="";
}

// Hide the livesearch box on a click outside its div
function hidelivesearch(evt) {
    evt = evt || window.event;
    var targ = evt.target || evt.srcElement;

	// If the livesearch box is open, clear it
	if (targ.id=="livesearch" || targ.id=="livesearchheader" || targ.id=="livesearchfooter" || targ.id=="searchsubmit") {
		return;
	} else {
		if (document.getElementById("livesearch").style.visibility=="visible") {
			clearlivesearch();
		}
	}

}

/*** START JS Send & Share icons & links ***/

function writesharelink() {
	document.write("<li><a href='#' target='_self' class='shareicon' onclick='shareboxreveal(); return false;'><img src='%absCorrect%images/micro/share.gif' alt='' border='0'>Share</a></li>");
}

function writesharebox(absCorrect) {
	var sendshare = "<div id='sharebox'><div id='shareboxhead'><div id='shareboxtriangle'>&nbsp;</div></div><ul id='shareicons'><div id='shareboxclose'><a href='#' onClick='shareboxhide(); return false;'><img src='" + absCorrect + "images/micro/ajaxclose.gif' alt='Close' border='0' /></a></div>"

	// Territory, Icon, Pre-URL, Post-URL, Description & alt tag

	// Linkedin
	arr_ss [0] = new Array()
	arr_ss [0][0] = "gx";
	arr_ss [0][1] = absCorrect + "images/micro/share_linked.gif";
	arr_ss [0][2] = "http://www.linkedin.com/shareArticle?mini=true&url=" + window.location;
	arr_ss [0][3] = "";	
	arr_ss [0][4] = "Linkedin";
	
	// Facebook
	arr_ss [1] = new Array()
	arr_ss [1][0] = "gx";
	arr_ss [1][1] = absCorrect + "images/micro/share_facebook.gif";
	arr_ss [1][2] = "http://www.facebook.com/share.php?u=" + window.location;
	arr_ss [1][3] = "&title=PwC Schweiz";
	arr_ss [1][4] = "Facebook";

	// Mixx
	arr_ss [2] = new Array()
	arr_ss [2][0] = "gx";
	arr_ss [2][1] = absCorrect + "images/micro/share_mixx.gif";
	arr_ss [2][2] = "http://www.mixx.com/submit?page_url=" + window.location;
	arr_ss [2][3] = "&title=PwC Schweiz";
	arr_ss [2][4] = "Mixx";

	// Digg
	arr_ss [3] = new Array()
	arr_ss [3][0] = "gx";
	arr_ss [3][1] = absCorrect + "images/micro/share_digg.gif";
	arr_ss [3][2] = "http://digg.com/submit?phase=2&url=" + window.location;
	arr_ss [3][3] = "&title=PwC Schweiz";
	arr_ss [3][4] = "Digg";
	
	// Yahoo! Buzz
	arr_ss [4] = new Array()
	arr_ss [4][0] = "gx";
	arr_ss [4][1] = absCorrect + "images/micro/share_yahoobuzz.gif";
	arr_ss [4][2] = "http://buzz.yahoo.com/buzz?targetUrl=" + window.location;
	arr_ss [4][3] = "&title=PwC Schweiz";
	arr_ss [4][4] = "Yahoo! Buzz";	

	for (i=0;i<arr_ss.length; i++) {
		sendshare = sendshare + "<li><a href='" + arr_ss[i][2] + arr_ss[i][3] + "' target='_blank' class='shareicon'><img src='" + arr_ss[i][1] + "' border='0' alt='" + arr_ss[i][4] + "' />&nbsp;" + arr_ss[i][4] + "</a></li>"	
	}

	sendshare = sendshare + "</ul></div>";
	document.write(sendshare);
}

function shareboxreveal() { // Show, hide or add to territory selector box
	document.getElementById('sharebox').style.display = 'block';
}

function shareboxhide() { 	// Clear the contents of the box and hide the div
	document.getElementById('sharebox').style.display = 'none';  
}


/*** START Lightweight browser detection ***/

//alert(BrowserDetect.browser + ' ' + BrowserDetect.version + ' on ' + BrowserDetect.OS);

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.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();
