var theLeft;
var theTop;
var theHeight;
var dropMenuId;
var theLinkWidth;

var p=0;
var pagesArray = new Array();
var nextUrl;
var theTitle;
var placeHolder;
var searchTerm;
var theOutput='';
var boxIsFocused;
var newDivHeight;

var _gaq = _gaq || [];

function init() {
    ga = document.createElement('script');
	ga.type = 'text/javascript';
	ga.async = true;
    ga.src = 'http://www.google-analytics.com/ga.js';
    document.body.appendChild(ga);

    callGoogle();

	if(document.URL.match('search-results.php')){
		requestFiles();
	}

	if(document.getElementById('right')){
		newDiv = document.createElement('div');
		newDiv.id = 'printDiv';
		newDiv.style.paddingBottom = '10px';
		newDiv.style.textAlign = 'right';
		if(document.URL.match('/fr/')){
			newDiv.innerHTML = '<a onclick="printThisPage();" href="#null"><img alt="" src="../images/print-icon.gif" /></a> &nbsp;&nbsp;&nbsp; <a href="#" onclick="letterSize(1)"><img alt="" src="../images/fontsize1.gif" /></a> <a href="#" onclick="letterSize(2)"><img alt="" src="../images/fontsize2.gif" /></a> <a href="#" onclick="letterSize(3)"><img alt="" src="../images/fontsize3.gif" /></a> &nbsp;&nbsp;&nbsp; <input id="searchBox" onfocus="boxFocus()" onblur="boxBlur()" type="text" value="Recherche" /><a onclick="doSearch()" href="#"><img src="../images/search.png" alt="submit" /></a>';
		}else{
			newDiv.innerHTML = '<a onclick="printThisPage();" href="#null"><img alt="" src="images/print-icon.gif" /></a> &nbsp;&nbsp;&nbsp; <a href="#" onclick="letterSize(1)"><img alt="" src="images/fontsize1.gif" /></a> <a href="#" onclick="letterSize(2)"><img alt="" src="images/fontsize2.gif" /></a> <a href="#" onclick="letterSize(3)"><img alt="" src="images/fontsize3.gif" /></a> &nbsp;&nbsp;&nbsp; <input id="searchBox" onfocus="boxFocus()" onblur="boxBlur()" type="text" value="Search" /><a onclick="doSearch()" href="#"><img src="images/search.png" alt="submit" /></a>';
		}
		theRight = document.getElementById('right');
		firstRight = theRight.firstChild;
		theRight.insertBefore(newDiv,firstRight);
	}

	document.onkeyup = function(e){
					if (!e) var e = window.event;
					if(e.keyCode == 13){
						if(boxIsFocused == 'true'){
							doSearch();
						}
					}
				}

	if(document.getElementById('nav')){
		theMainMenu = document.getElementById('nav');
	}else{
		theMainMenu = document.getElementById('navfr');
	}

	mainMenuItems = theMainMenu.childNodes;
	mn=0;
	for(i=0;i<mainMenuItems.length;i++){
		if(mainMenuItems[i].className == 'dropItem'){			
			mainMenuItems[i].onmouseover = function(){
								dropMenuId = this.innerHTML;
								theHeight = this.offsetHeight;
								theLinkWidth = this.offsetWidth;
								theTop = this.offsetTop;
								theLeft = this.offsetLeft;
								theParent = this.offsetParent;
								while(theParent){
									theTop = theTop + theParent.offsetTop
									theLeft = theLeft + theParent.offsetLeft;
									theParent = theParent.offsetParent;
								}
								dropMenu();
							}
			mainMenuItems[i].onmouseout = raiseMenu;
			mn++;
		}
	}
	dropMenus = document.getElementById('theDropMenus');
	dropMenuItems = dropMenus.childNodes;
	for(i=0;i<dropMenuItems.length;i++){
		if(dropMenuItems[i].id){			
			dropMenuItems[i].onmouseover = function(){
								stay(this.id);
							}
			dropMenuItems[i].onmouseout = raiseMenu;
		}
	}

    changeHead();
	addPhone();
	fixHeight();
}

window.onload=init;

function callGoogle(){
	_gaq.push(['_setAccount', 'UA-23271687-15']);
	_gaq.push(['_trackPageview']);
}

function dropMenu(){
	screenWidth = document.body.clientWidth;
	theMenu = document.getElementById(dropMenuId);
	theMenu.style.display = 'block';
	theMenu.style.top = theTop + theHeight + 'px';
	theWidth = theMenu.clientWidth;

	if(theWidth < theLinkWidth){
		theWidth = theLinkWidth;
		theMenu.style.width = theLinkWidth - 8 + 'px';
	}

    if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)){
		ieversion=new Number(RegExp.$1);

		if ((ieversion >= 6) && (ieversion < 7)){
			jerrysKids = theMenu.childNodes;

			for(i=0;i<jerrysKids.length;i++){
				if(jerrysKids[i].style){
					jerrysKids[i].style.width = theWidth - 20 + 'px';
				}
			}
		}
	}

	if((theLeft + theWidth) > screenWidth){
		reduceLeft = (theLeft + theWidth) - screenWidth;
		theMenu.style.left = theLeft - reduceLeft - 2 + 'px';
	}else{
		theMenu.style.left = theLeft + 'px';
	}

}

function stay(thisId) {
	document.getElementById(thisId).style.display = 'block';
}

function raiseMenu(){
	theMenus = document.getElementById('theDropMenus');
	theMenus = theMenus.childNodes;
	for(i=0;i<theMenus.length;i++){
		if(theMenus[i].style){
			if(theMenus[i].style.display == 'block'){
				theMenus[i].style.display = 'none';
			}
		}
	}	
}

function changeHead(){
	docUrl = document.URL;
	x = docUrl.lastIndexOf('.');
	y = docUrl.lastIndexOf('/');
	pageUrl = docUrl.slice(y + 1,x);

	if(document.getElementById('header-image')){
        theHeader = document.getElementById('header-image');

        if(docUrl.match('/fr/')){
			thePath = '../images/';
		}else{
			thePath = 'images/';
		}

		if((pageUrl == 'about') || (pageUrl == 'mission') || (pageUrl == 'promise') || (pageUrl == 'quality') || (pageUrl == 'news')){
			theHeader.src = thePath + 'header-about.jpg';
		}else if((pageUrl == 'imaging_services') || (pageUrl == 'medical_services')){
			theHeader.src = thePath + 'header-services.jpg';
		}else if((pageUrl == 'mri')){
			theHeader.src = thePath + 'header-mri.jpg';
        }else if((pageUrl == 'ultrasound')){
			theHeader.src = thePath + 'header-ultrasound.jpg';
        }else if((pageUrl == 'ct-scan') || (pageUrl == 'virtual-colonoscopy')){
			theHeader.src = thePath + 'header-ct-scan.jpg';
        }else if((pageUrl == 'blood-tests')){
			theHeader.src = thePath + 'header-blood-tests.jpg';
        }else if((pageUrl == 'travel-vaccines')){
			theHeader.src = thePath + 'header-vaccines.jpg';
        }else if((pageUrl == 'nursing') || (pageUrl == 'careers')){
			theHeader.src = thePath + 'header-careers.jpg';
        }else if((pageUrl == 'physician')){
			theHeader.src = thePath + 'header-physician.jpg';
        }else if((pageUrl == 'patient') || (pageUrl == 'app-prep') || (pageUrl == 'exam-prep') || (pageUrl == 'mri-prep') || (pageUrl == 'ct-scan-prep') || (pageUrl == 'ultrasound-prep') || (pageUrl == 'ekg-prep') || (pageUrl == 'csst') || (pageUrl == 'saaq')){
			theHeader.src = thePath + 'header-patient.jpg';
        }else if((pageUrl == 'contact')){
			theHeader.src = thePath + 'header-contact.jpg';
		}else{
			theHeader.src = thePath + 'header-inside.jpg';
		}

        if((document.getElementsByTagName('h1')[0].innerHTML == 'Service d\'imagerie') || (document.getElementsByTagName('h1')[0].innerHTML == 'Imaging Services')){
			document.getElementById('header').style.background = 'url(' + thePath + 'logo-imaging.gif) no-repeat';
		}
	}
}

function addPhone(){
	if(document.getElementById('left')){
		docUrl = document.URL;
		phoneDiv = document.createElement('div');
		phoneDiv.style.textAlign = 'center';
		phoneDiv.style.marginTop = '40px';
		leftDiv = document.getElementById('left');
		if(docUrl.match('/fr/')){
			if(docUrl.match('careers.php')){
				phoneDiv.innerHTML = '<a href="mailto:info@viamedica.ca"><img src="../images/sendCV-fr.gif" alt="" /></a>';
			}else{
				phoneDiv.innerHTML = '<img src="../images/callUs-fr.gif" alt="" /><p><a href="http://viamedica.blogspot.com/" target="_blank"><img src="../images/blogger-icon.png" alt="" /></a> <a href="http://www.facebook.com/pages/ViaMedica-Medical-CenterImaging-Services/119651911423029" target="_blank"><img src="../images/facebook-icon.png" alt="" /></a> <a href="http://twitter.com/#!/ViaMedica" target="_blank"><img src="../images/twitter-icon.png" alt="" /></a></p>';
			}
		}else{
			if(docUrl.match('careers.php')){
				phoneDiv.innerHTML = '<a href="mailto:info@viamedica.ca"><img src="images/sendCV.gif" alt="" /></a>';
			}else{
				phoneDiv.innerHTML = '<img src="images/callUs.gif" alt="" /><p><a href="http://viamedica.blogspot.com/" target="_blank"><img src="images/blogger-icon.png" alt="" /></a> <a href="http://www.facebook.com/pages/ViaMedica-Medical-CenterImaging-Services/119651911423029" target="_blank"><img src="images/facebook-icon.png" alt="" /></a> <a href="http://twitter.com/#!/ViaMedica" target="_blank"><img src="images/twitter-icon.png" alt="" /></a></p>';
			}
		}
		leftDiv.appendChild(phoneDiv);
	}
}

function fixHeight(){
	browserHeight = document.documentElement.clientHeight;
	docHeight = document.body.clientHeight;

	if(document.getElementById('homeright')) {
        leftHeight = document.getElementById('homeleft').clientHeight;
		rightHeight = document.getElementById('homeright').clientHeight;

		if(docHeight < browserHeight){
			document.getElementById('homeright').style.height = browserHeight - 170 + 'px';
		}

		if(rightHeight < leftHeight){
			document.getElementById('homeright').style.height = leftHeight + 'px';
		}
	}else{
        document.getElementById('left').style.height = '';
		document.getElementById('right').style.height = '';

		leftHeight = document.getElementById('left').clientHeight;
		rightHeight = document.getElementById('right').clientHeight;

		if(docHeight < browserHeight){
			document.getElementById('left').style.height = browserHeight - 212 + 'px';
			document.getElementById('right').style.height = browserHeight - 212 + 'px';
		}else{
			if(leftHeight < rightHeight){
				document.getElementById('left').style.height = rightHeight - 40 + 'px';
			}else{
				document.getElementById('right').style.height = leftHeight - 40 + 'px';
			}
		}
	}
}

function changeLang(){
	docUrl = document.URL;
	x = docUrl.length;
	y = docUrl.lastIndexOf('/');
	newUrl = docUrl.slice(y + 1,x);
	if(docUrl.match('fr/')){
		window.location = '../' + newUrl;
	}else{
		window.location = 'fr/' + newUrl;
	}
}

function letterSize(f){
	if(f == 2){
		contentDiv = document.getElementById('right');
		h4Tags = contentDiv.getElementsByTagName('h4');
		aTags = contentDiv.getElementsByTagName('a');
		for(i=0;i<h4Tags.length;i++){
			h4Tags[i].style.font = 'bold 16px arial';
		}
		for(i=0;i<aTags.length;i++){
				aTags[i].style.font = '14px arial';
		}
		document.getElementById('right').style.font = '14px arial';
		fixHeight();
	}
	if(f == 3){
		contentDiv = document.getElementById('right');
		h4Tags = contentDiv.getElementsByTagName('h4');
		aTags = contentDiv.getElementsByTagName('a');
		for(i=0;i<h4Tags.length;i++){
			h4Tags[i].style.font = 'bold 18px arial';
		}
		for(i=0;i<aTags.length;i++){
				aTags[i].style.font = '16px arial';
		}
		document.getElementById('right').style.font = '16px arial';
		fixHeight();
	}
	if(f == 1){
		contentDiv = document.getElementById('right');
		h4Tags = contentDiv.getElementsByTagName('h4');
		aTags = contentDiv.getElementsByTagName('a');
		for(i=0;i<h4Tags.length;i++){
			h4Tags[i].style.font = 'bold 14px arial';
		}
		for(i=0;i<aTags.length;i++){
				aTags[i].style.font = '12px arial';
		}
		document.getElementById('right').style.font = '12px arial';
		fixHeight();
	}
}	

function printThisPage() {
	printWin = window.open('print.html','','');
}

function buildFlashEN() {
    //begin the OBJECT tag, which will be understood by ActiveX-capable browsers
    document.write('<object id="swflash" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0" width="105" height="105" />');
    document.write('<param name="allowScriptAccess" value="sameDomain" />');
    document.write('<param name="movie" value="butterfly.swf" />');
    document.write('<param name="wmode" value="transparent" />');
    document.write('<param name="quality" value="high" />');
    document.write('<param name="bgcolor" value="#ffffff" />');
    document.write('<embed src="butterfly.swf" wmode="transparent" quality="high" bgcolor="#ffffff" width="105" height="105" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />');
    document.write('</object>');
}

function buildFlashFR() {
    //begin the OBJECT tag, which will be understood by ActiveX-capable browsers
    document.write('<object id="swflash" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0" width="105" height="105" />');
    document.write('<param name="allowScriptAccess" value="sameDomain" />');
    document.write('<param name="movie" value="../butterfly.swf" />');
    document.write('<param name="wmode" value="transparent" />');
    document.write('<param name="quality" value="high" />');
    document.write('<param name="bgcolor" value="#ffffff" />');
    document.write('<embed src="../butterfly.swf" wmode="transparent" quality="high" bgcolor="#ffffff" width="105" height="105" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />');
    document.write('</object>');
}

function requestFiles(){
		if (window.XMLHttpRequest) {
			xmlhttp=new XMLHttpRequest();
  		}else if (window.ActiveXObject) {
  			xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  		}

		if (xmlhttp!=null) {	
  			xmlhttp.onreadystatechange=getFiles;
  			xmlhttp.open("GET","read-files.php",true);
  			xmlhttp.send(null);
  		}else{
  			alert("Your browser does not support XMLHTTP.");
  		}
}

function getFiles(){
	if (xmlhttp.readyState==4) {
		if(document.URL.match('/fr')){
			document.getElementById('search-messages').innerHTML = '<h4>Recherche...</h4><p>&nbsp;</p>';
		}else{
			document.getElementById('search-messages').innerHTML = '<h4>Searching...</h4><p>&nbsp;</p>';
		}
		fetchedFiles = xmlhttp.responseText;
		splitFiles = fetchedFiles.split("<br />");
		sortFiles = splitFiles.sort();
		n=0;
		for(z=0;z<splitFiles.length;z++) {
			readFile=sortFiles[z].search('read\-file');
			goodFile=sortFiles[z].search('\.php');
			if((goodFile != -1) && (readFile == -1)){
				cleanFile = sortFiles[z];
				pagesArray[n] = cleanFile;
				n++;
			}
		}

		nextUrl = pagesArray[p];

		pageLinks();

	}else{
		return this;
	}
}

function pageLinks(){
		if (window.XMLHttpRequest) {
			xmlhttp=new XMLHttpRequest();
  		}else if (window.ActiveXObject) {
  			xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  		}

		if (xmlhttp!=null) {	
  			xmlhttp.onreadystatechange=getLinks;
  			xmlhttp.open("GET",nextUrl,true);
  			xmlhttp.send(null);
  		}else{
  			alert("Your browser does not support XMLHTTP.");
  		}
}

function getLinks(){
	if (xmlhttp.readyState==4) {
		searchTerm = document.URL;
		u = searchTerm.indexOf('?');
		w = searchTerm.length;
		searchTerm = ' ' + searchTerm.slice(u + 1, w) + ' ';
		searchTerm2 = searchTerm.toLowerCase();

		fetchedContent = xmlhttp.responseText;

		h = fetchedContent.indexOf('<h2');
   		h = fetchedContent.indexOf('>', h);
   		he = fetchedContent.lastIndexOf('</h2>');

        t = fetchedContent.indexOf('<h1');
   		t = fetchedContent.indexOf('>', t);
   		te = fetchedContent.lastIndexOf('</h1>');

		hTitle = fetchedContent.slice(h + 1, he);
		tTitle = fetchedContent.slice(t + 1, te);
		if(he == -1){
			theTitle = tTitle;
		}else{
			theTitle = hTitle;
		}

		placeHolder = document.getElementById('retrievedContent');

		x = fetchedContent.indexOf('<div id="right"');
   		x = fetchedContent.indexOf('>', x);    
   		y = fetchedContent.lastIndexOf('<div id="footer"'); 
   		
		newContent = fetchedContent.slice(x + 1, y);

		placeHolder.innerHTML = newContent;

		theTags = new RegExp('<(.|\n)+?>','gi');

		cleanContent = newContent.replace(theTags, ' ');
		while(cleanContent.match('  ')){
		cleanContent = cleanContent.replace('  ', ' ');
		}
		cleanContent2 = cleanContent.toLowerCase();

		foundWord = cleanContent2.search(searchTerm2);

		if(foundWord != -1){
			sLength = searchTerm.length;
			s = foundWord;
			theStart = s - 100;
			theEnd = s + sLength + 100;
			etcDots = '...'
			etcDots2 = '...'
			if(theStart < 0){
				theStart = 0;
				etcDots = ''
			}
			if(theEnd > cleanContent.length){
				theEnd = cleanContent.length;
				etcDots2 = ''
			}	
			phrase1 = cleanContent.slice(theStart, s);
			phrase2 = cleanContent.slice(s, s + sLength);
			phrase3 = cleanContent.slice(s + sLength, theEnd);
			phrase = phrase1 + ' <b>' + phrase2 + '</b> ' + phrase3;

			theOutput = '<a href="' + nextUrl + '"><b>' + theTitle + '</b></a><br />' + etcDots + phrase + etcDots2;
		}
	
		setTimeout('nextPage()', 100);
	}
}

function nextPage(){
	if(p < (pagesArray.length - 1)){
		if(theOutput != ''){
			outputDiv = document.createElement('div');
			outputDiv.id = 'displayLinks' + p;
			outputDiv.innerHTML = theOutput + '<br /><br />';
			document.getElementById('right').appendChild(outputDiv);
			newDivHeight = document.getElementById('displayLinks' + p).offsetHeight;
		}

		theOutput='';
		document.getElementById('right').style.height = '';
		rightHeight = document.getElementById('right').clientHeight;
		leftHeight = document.getElementById('left').clientHeight;
		if(rightHeight > leftHeight){
			document.getElementById('left').style.height = rightHeight + 'px';
		}
		p++;
		requestFiles();
	}else{
		finalMatch = document.getElementById('right').innerHTML.match('displayLinks.');
		if(finalMatch == null){
			if(document.URL.match('/fr')){
				document.getElementById('search-messages').innerHTML = '<h4>Il n\'y a aucun résultat trouvé.</h4>';
			}else{
				document.getElementById('search-messages').innerHTML = '<h4>There were no matches found.</h4>';
			}		
		}else{
			document.getElementById('search-messages').innerHTML = '';
		}	
	}
}

function doSearch(){
	window.location = 'search-results.php' + '?' + document.getElementById('searchBox').value;
}

function boxFocus(){
	document.getElementById('searchBox').value = '';
	document.getElementById('searchBox').style.background = '#fff';
	document.getElementById('searchBox').style.color = '#000';
	boxIsFocused = 'true';
}

function boxBlur(){
	document.getElementById('searchBox').style.background = '#eee';
	document.getElementById('searchBox').style.color = '#888';
	boxIsFocused = 'false';
}
