/* js-tabs.js
 *
 * Created by       : LHK
 *         for      : MZA Associates Corporation
 * Project          : Website Development
 * First Deployed   : June 2009
 *
 * Functions        : setTabHeights()
 *                    clearAllTabs()
 *                    selectCurrentTab(newA)
 *                    printPage()
 *                    searchF(input)
 *                    scrollToCurrentContent()
 *                    showObfuscatedText()
 *                    postAll() - UC
 *
 *                    execSearch(t, e)
 *
 *                    changeImage()
 *                    changeImageBack()
 *                    handleMDown()
 *                    handleMUp()
 *                    removeVPNNotice()
 */




function changeImage() {
	document.images["jsbutton"].src= "images/x-on.png";
	return true;
}
function changeImageBack() {
	document.images["jsbutton"].src = "images/x.png";
	return true;
}
function handleMDown() {
	document.images["jsbutton"].src = "images/x-down.png";
	return true;
}
function handleMUp() {
	changeImage();
	return true;
}
function removeVPNNotice() {
	document.getElementById('VPNWarn').style.display = 'none';
	setTabHeights();
	selectCurrentTab();
	scrollToCurrentContent(false);
}


var bool = false;

function debug(msg) {
    if (bool) {
        alert(msg);
    }
}

//
// Layout height of items, based on viewport height.
//
function setTabHeights() {
    debug("setTabHeights");
	// Browser detection
	var browser = navigator.appName;
	
	// Version Detection
	var nVer = navigator.appVersion;
    var nAgt = navigator.userAgent;
    var browserName  = navigator.appName;
    var fullVersion  = ''+parseFloat(navigator.appVersion); 
    var nameOffset,verOffset,ix;

    // In MSIE, the true version is after "MSIE" in userAgent
    if ((verOffset=nAgt.indexOf("MSIE"))!=-1) {
        browserName = "Microsoft Internet Explorer";
        fullVersion = nAgt.substring(verOffset+5);
    
    // In Firefox, the true version is after "Firefox" 
    } else if ((verOffset=nAgt.indexOf("Firefox"))!=-1) {
        browserName = "Firefox";
        fullVersion = nAgt.substring(verOffset+8);
    }

    // trim the fullVersion string at semicolon/space if present
    if ((ix=fullVersion.indexOf(";"))!=-1) fullVersion=fullVersion.substring(0,ix);
    if ((ix=fullVersion.indexOf(" "))!=-1) fullVersion=fullVersion.substring(0,ix);

    var bVersionFloat = parseFloat(fullVersion);
    //alert(bVersionFloat);

	var viewportwidth;
	var viewportheight;

 	// the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
	if (typeof window.innerWidth != 'undefined'){ 
	     viewportwidth = window.innerWidth,
	     viewportheight = window.innerHeight
		 
	// IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
	} else if (typeof document.documentElement != 'undefined'
	    && typeof document.documentElement.clientWidth !=
	    'undefined' && document.documentElement.clientWidth != 0) {
	      viewportwidth = document.documentElement.clientWidth,
	      viewportheight = document.documentElement.clientHeight
 
	// older versions of IE
	} else {
	      viewportwidth = document.getElementsByTagName('body')[0].clientWidth,
	      viewportheight = document.getElementsByTagName('body')[0].clientHeight
	}
    
    
    // compensate for the scrollbar that will appear at the bottom
    // of the viewport when the viewport is smaller than 670px
    if (browser == "Netscape" && viewportwidth < 670) {
        viewportheight = viewportheight - 18;
    }
    
    
    // collect some useful elements
    var tabfolder = document.getElementById('tabfolder');	
    var divs = tabfolder.getElementsByTagName('div');
    var iframes = tabfolder.getElementsByTagName('iframe');
    var footer = document.getElementById('footer');
    var header = document.getElementById('header');
    var tabfolderH1 = document.getElementById('tabfolderHelper1');
	var tabfolderH2 = document.getElementById('tabfolderHelper2');
	var tabfolderH3 = document.getElementById('tabfolderHelper3');
	var tabfolderH4 = document.getElementById('tabfolderHelper4');
		
   	// Find height of footer and header
	var footerheight = footer.offsetHeight;
	var headerheight = header.offsetHeight;

    // set heights and widths
    var tabfolderwidth = viewportwidth - 20;    // subtract 20px, because of the 10px borders on either side of the tabfolder
	var tabfolderheight = viewportheight - (footerheight + headerheight);
	var historybarheight = document.getElementById('hBarMould').offsetHeight;

    var tabheight = (tabfolderheight) - historybarheight;
        
	tabfolder.style.top = headerheight + "px";
	tabfolder.style.height= tabfolderheight + "px";
	tabfolder.style.width= tabfolderwidth + "px";
    
	tabfolderH1.style.top = headerheight + "px";
	tabfolderH1.style.height = tabfolderheight + "px";
	tabfolderH1.style.width = (tabfolderwidth) + "px";
    
	tabfolderH2.style.top = headerheight + "px";
	tabfolderH2.style.height = tabfolderheight + "px";
	tabfolderH2.style.width = (tabfolderwidth) + "px";
		
	tabfolderH3.style.top = headerheight + "px";
	tabfolderH3.style.height = (tabfolderheight) + "px";
	tabfolderH3.style.width = (tabfolderwidth) + "px";
        
	footer.style.top = (headerheight + tabfolderheight)+ "px";
	footer.style.width = (tabfolderwidth) + "px";
 
 	tabfolderH4.style.top = headerheight + "px";
	tabfolderH4.style.height = (tabfolderheight) + "px";
 	// -10 because of the +5px on each side from the padding
	tabfolderH4.style.width = (tabfolderwidth - 10) + "px"; 
	 	   
	// Set all relevant divs to the correct width.
    // TODO: make navmenu resize back to normal width
    
    //alert(tabfolderwidth);
    var div;
	if (tabfolderwidth < 950) {
	    if (tabfolderwidth < 750) {
	        for(c=0;c<divs.length;c++) {
	           	div = divs[c];
	            switch(div.className.toString()) {
	                case "tab".toString():
           		        div.style.width = 735 + "px";
           		        break;
		            case "homepar".toString():
	                    div.style.width = 220 + "px";
	                    break;		                
	                case "centerpar".toString():
	                    div.style.width = 400 + "px";
	                    break;
	                case "navMenu".toString():
	                    div.style.width = 185 + "px";
	                    break;
	            }
	        }
	    // 650px < tabfolderwidth < 950px  
	    } else {		    
   		    for(c=0;c<divs.length;c++) {
   		    	div = divs[c];
	            switch(div.className.toString()) {
	            case "tab".toString():
	            	div.style.width = (tabfolderwidth - 15) + "px";
           		    break;
	            case "homepar".toString():
                    div.style.width = (tabfolderwidth - 525) + "px";
                    break;
	            case "centerpar".toString():
                    div.style.width = (tabfolderwidth - 350) + "px";
                    break;
                case "navMenu".toString():
	                div.style.width = "auto";
	                break;
	            }
	        }
	    }
	// tabfolderwidth > 950px
	} else {
		for (c=0;c<divs.length;c++) {
			div = divs[c];
			switch(div.className.toString()) {
			    case "tab":
				    div.style.width = (tabfolderwidth - 15) + "px";
                    break;
                case "centerpar".toString():
                    div.style.width = "50em";
                    break;
                case "homepar".toString():
                    div.style.width = "35em";
                    break;
                case "navMenu".toString():
	                div.style.width = "auto";
	                break;
		    }
		}
    }
    
   for(c=0;c<iframes.length;c++) {
        iframes[c].style.height = (tabheight - 13) + "px";
        if (iframes[c].className.toString() == "content") {
      	    if (tabfolderwidth < 950) {
	            if (tabfolderwidth < 750) {
	                iframes[c].style.width = 500 + "px";
	            } else {
	                iframes[c].style.width = (tabfolderwidth - 280) + "px";
	            }
	        } else {
       	        iframes[c].style.width = (tabfolderwidth - 280) + "px";
	        }
	    }

   }
    
	// Set all relevant divs to the correct height.
	for(c=0;c<divs.length;c++) {
       	div = divs[c];
        genHeight = tabheight;
        switch(div.className.toString()) {
            case "tabfolder".toString():
            	div.style.height = (genHeight - 10) + "px";
                break;
            case "tab".toString():
             	div.style.height = (genHeight - 10) + "px";
      		    break;
            case "content".toString():
               	div.style.height = (genHeight - 10) + "px";
                break;
            case "contentPar".toString():
              	div.style.height = (genHeight - 10) + "px";
	            break;
	        case "homeContentPar".toString():
                div.style.height = (genHeight - 10) + "px";
		        break;
	        case "centerpar".toString():
	            div.style.paddingBottom = (genHeight - 40) + "px";
	            break;
	        case "navMenu".toString():
	         	div.style.height = (genHeight - 20) + "px";
	            break;
	    }
	}
    

	// All the heights and widths are set correctly now, so we can show the website
	document.getElementById('container').style.visibility = 'visible';
}








//
// Clears current tab selection
//
function clearAllTabs() {
    debug("clearAllTabs");

    // Find all tab links on the left (public).
	var tabs1 = document.getElementById('tabnavLeft').getElementsByTagName('a');
	for (c = 0; c < tabs1.length; c++) {
		tabs1[c].className = "off";
	}
		
	// Find all tab links on the right (private).
	var tabs2 = document.getElementById('tabnavRight').getElementsByTagName('a');
	for (c=0;c<tabs2.length;c++){
		tabs2[c].className = "off";
	}
}

//
// Selects current tab, based on <hash> in <href>
//
function selectCurrentTab(newA) {
    debug("selectCurrentTab");
	clearAllTabs();
		
	var defaultTabId = "home";
	var activeTab;
	var activeTabMenuItem;

    // Is the current tab specified? Otherwise: find out from browser url.
	if (newA) {
		activeTabMenuItem = newA;
	} else {
	    activeTab = location.hash;
			
		// Make sure that a tab is selected
	    if (activeTab != "" && activeTab != "#") {
			activeTab = activeTab.substring(1, activeTab.length);           // Chop off leading hash
			tabParts = activeTab.split('?');                                // Chop off params
			tabParts = tabParts[0].split('-');                             // Chop off sub-tabs
			activeTabId = tabParts[0].substring(0, tabParts[0].length - 3); // Chop "tab" off end
			activeTabMenuItem = document.getElementById(activeTabId);       // Find <a>-element
		
		// No tab is selected, so go to defaultTab.	
		} else {
			activeTabMenuItem = document.getElementById(defaultTabId);
			activeTab = defaultTabId + "tab";
		}
	}
    
	// Change the class of the current tab (from "off") to "on".
	if (activeTabMenuItem) {
	    activeTabMenuItem.className = "on";
	}
}

//
// Layout page for printing
//
function printPage() {
    debug("printPage");
    
	var title = "<title>MZA Associates Corporation</title>";
    var stylesheet = '<link rel="stylesheet" type="text/css" href="stylesheets/mza-print.css" title="MZA Stylesheet A"/>'
	var topHTML = "<html><head>" + title + stylesheet  + "</head><body>";
	var bottomHTML = "</body></html>";

    var page2print = null;		
		
	var defaultTabId = "hometab";
	var activeTab = location.hash;

	if (activeTab != "" && activeTab != "#" && activeTab) {
		activeTab = activeTab.substring(1, activeTab.length); // chop off leading hash
	} else {
		activeTab = defaultTabId;
	}
    
	if (activeTab.split('-').length == 1) {
	    var bigTab = document.getElementById(activeTab);
	    var divs = bigTab.getElementsByTagName('div');
	    var c = 0;
	    while ((c < divs.length) && (page2print == null)) {
	    	if (divs[c].className == "contentPar" || divs[c].className == "homeContentPar") {
	    		page2print = divs[c];
	    	}
	    	c++;
	    }
	} else {
		page2print = document.getElementById(activeTab);
	}

   	if (page2print == null) {
	    var iframes = bigTab.getElementsByTagName('iframe');

        x = window.open(iframes[0].src,"_blank",'width=700,height=500,toolbar=yes,location=no,directories=no,status=no,menubar=yes,scrollbars=yes,copyhistory=no,resizable=yes');
//      x.print(); // cannot print iframe content
	} else {

	    var x = window.open("","printwindow",'width=700,height=500,toolbar=yes,location=no,directories=no,status=no,menubar=no,scrollbars=yes,copyhistory=no,resizable=yes');
	    var pp = x.document;
	    pp.writeln(topHTML);
	    pp.writeln(page2print.innerHTML);
	    pp.writeln(bottomHTML);
	    pp.close();
		
	
	    innerDivs = pp.getElementsByTagName('div');
        for (c=0;c<innerDivs.length;c++) {
            if (innerDivs[c].className.toString() == "centerpar".toString()) {
                innerDivs[c].style.paddingBottom = "16px";
            }
        }
		
        x.print();
	}
    return false;

}


function setTextFocus() {

    // CSS class name to use when no focus is on the input control
    var classBlur = 'input_text';

    // CSS class name to use when the input control has focus
    var classFocus = 'input_text_focus';

    // get all of the input tags on the page
    var inputElements = document.getElementsByTagName('input');
    
    for (var i = 0; i < inputElements.length; i++) {
        if (inputElements[i].className == classBlur) {

            // add the onfocus event and set it to add the on focused CSS class

            inputElements[i].onfocus = function() {
                if (this.value == 'Search') {
                    this.value = '';
                }
                if (this.className == classBlur) {
                    this.className += ' ' + classFocus;
                }
            }

            // add the onblur event and set it to remove the on focused CSS class when it loses focus

            inputElements[i].onblur = function() {
                if (this.value == '') {
                    this.value = 'Search';
                }
                this.className = this.className.replace(new RegExp(' ' + classFocus + '\\b'), '');
            }
        }
    }
}








//
// "scrollCurrentContent" is called by the module
// which keeps track of the history object
//
function scrollToCurrentContent(changeCookie) {
    debug("scrollToCurrentContent");
	var loc = document.location.hash;
	if (loc.length > 0) {
	    var activeTab = loc.substring(1);           // chop off leading hash
	    var activeTab = activeTab.split('?')[0];    // get rid of params	
	    var tabParts = activeTab.split('-');
	
	    
	    // target location is top-level tab
	    if (tabParts.length == 1) {
	        subtab = getCookie(activeTab);

            // no cookie is stored for the activeTab
		    if (subtab == null || subtab == "") {
			    var bigTab = document.getElementById(activeTab);
			    if (bigTab != null) {
			        iframes = bigTab.getElementsByTagName('iframe');
			        if (iframes.length > 0) {
			            tab2scroll2 = iframes[0].id;
			        } else {
			            tab2scroll2 = activeTab;
			        }
			    } else {
			        var errorString = "Cannot find tab '" + activeTab + "'. ";
			        var redirectingString = "Redirecting to 'home'";
			        alert("Navigation Error: " + errorString + redirectingString);
			        window.location.hash = "#hometab";
			    }
			    
			// cookie was found for activeTab
		    } else {
		        tab2scroll2 = activeTab + "-" + subtab;
		    }
		    if (tab2scroll2 != null) {
		        document.getElementById(tab2scroll2).scrollIntoView(true);
		    }
		    
		// target location is subtab
	    } else {
		    var currentLocation = window.location.hash.substring(1);
		    document.getElementById(activeTab).scrollIntoView(true);
		    if (changeCookie) {
		        setCookie(tabParts[0],tabParts[1],1);
		    }
	    }
	}
}


//
// Stores value in a cookie variable.
// ( taken from http://www.w3schools.com/JS/js_cookies.asp )
//
function setCookie(c_name,value,expiredays) {
    debug("setCookie (" + c_name + ")");
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + expiredays);
    // 'expiredays' is optional
    document.cookie = c_name + "=" + escape(value) +
        ((expiredays==null) ? "" : "; expires="+exdate.toGMTString()) +  '; path=/';
}


//
// Retrieves value from a cookie variable.
// ( taken from http://www.w3schools.com/JS/js_cookies.asp )
//
function getCookie(c_name) {
    debug("getCookie (" + c_name + ")");
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=");
        // we have found our cookie
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) { c_end = document.cookie.length};
            return unescape(document.cookie.substring(c_start,c_end));
        }
    }
    return "";
}

function delCookie(c_name) {
    var expires = new Date();
    expires.setUTCFullYear(expires.getUTCFullYear() - 1);
    document.cookie = c_name + '=; expires=' + expires.toUTCString() + '; path=/';
}


//
// Turns an alias into an email address
//
function showObfuscatedText() {
    debug("showObfuscatedText");
    var preFix = "<span class='lower'>"
    var htmlString = "</span><span class='obfuscate'>[1. replace '=ABC=' with DOT, 2. replace text in brackets with AT.]</span><img style='margin:0;padding:0;' src='images/monkey.png'/>mza<span class='obfuscate'>=ABC=</span><img style='margin:0;padding:0;' src='images/period.png' />com";

	var items = document.getElementsByTagName("span");
	var c = 0;
	while (c < items.length) {
		var u = (items[c].innerHTML);
		if (items[c].className == "generate") {
			items[c].innerHTML = preFix + u + htmlString;
		}
		c = c + 1;
	}
}



			function loadImage() {
				i = new Image();
				i.onload = function() {
					var l = document.getElementById('label2');
					l.innerHTML = 'Found VPN.';
				}
				i.onerror = function() {
					var l = getElementById("label2");
					l.innerHTML = "Cannot find VPN connection.";
				}
				i.src='http://fileserver.mza.lan/home/mzarbt.gif';
				return false;
	        }
			