var selectedPage = "home";

var onMs = false;
var onMs7 = false;

// ***************************************************
// 
// ***************************************************
function determineBrowser() {
    var agt = navigator.userAgent.toLowerCase();
    var pos = agt.indexOf("msie"); 
    if (pos != -1) {
        onMs = true;
        if (agt.indexOf("msie 7") != -1) {
        	onMs7 = true;
        }
    }
}

// ***************************************************
// Get the AJAX object for making requests
// ***************************************************
function getHttp() {
	var activexmodes=["Msxml2.XMLHTTP", "Microsoft.XMLHTTP"];
    if (window.ActiveXObject) {
        for (var i = 0; i < activexmodes.length; i++) {
            try {
                return new ActiveXObject(activexmodes[i]);
            } catch(e) {
                //suppress error
            }
        }
    } else if (window.XMLHttpRequest) {
        return new XMLHttpRequest();
    } else {
        return false;
    }
}

// ***************************************************
// Load a page asynchronously
// url : The url to load
// contentId : The id of the html component to fill
// pName : The id of the menu item to change
// ***************************************************
function asyncLoadPage(contentId, pName) {
	var http = getHttp();
	
	if (!http) {
        var msg = "Your Browser does not support AJAX\n"; 
        msg += "Sorry we cannot load the requested URL\n\n";
        msg += "You should upgrade your browser to the latest Mozilla, Firefox or Opera version\n\n";
        msg += "or if you really want troubles to the latest Internet Explorer...";
        alert(msg);
	} else {
        http.onreadystatechange = function () {
            insertPage(http, contentId, pName);
        }
        var parameters = "file=" + encodeURIComponent(pName);
        http.open('GET', "/content.php?" + parameters, true);
        http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        http.setRequestHeader("Content-length", parameters.length);
        http.send(null);
	}
}

// ***************************************************
// Get the page title
// pName : The id of the page
// ***************************************************
function asyncGetPageTitle(pName) {
    var http = getHttp(); 
    http.onreadystatechange = function () {
        setTitle(http);
    }
    var parameters = "title=" + encodeURIComponent(pName);
    http.open('GET', "/title.php?" + parameters, true);
    http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    http.setRequestHeader("Content-length", parameters.length);
    http.send(null);
}

// ***************************************************
// Get the sidebar contents
// pName : The id of the page
// ***************************************************
function asyncGetSidebar(pName) {
    var http = getHttp(); 
    http.onreadystatechange = function () {
        loadSideBar(http, pName);
    }
    var parameters = "file=" + encodeURIComponent(pName);
    http.open('GET', "/getsidebar.php?" + parameters, true);
    http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    http.setRequestHeader("Content-length", parameters.length);
    http.send(null);
}

// *****************************************************
// Load the sidebar from php
// http : The AJAX requestor
// *****************************************************
function loadSideBar(http, pName) {
    if (http.readyState == 4) {
        var sidebar = document.getElementById("sideBar"); 
        if (http.status == 200) {
            sidebar.innerHTML = http.responseText;
            asyncGetPageTitle(pName);            
        } else {
            sidebar.innerHTML = http.status + " - " + http.statustext;
            asyncGetPageTitle(pName);
        }
    }
}

// *****************************************************
// Set the page title by getting it from php
// http : The AJAX requestor
// *****************************************************
function setTitle(http) {
    if (http.readyState == 4) { 
        if (http.status == 200) {
            document.title = http.responseText;            
        } else {
            document.title = "Java, Corba & J2EE Solutions";
        }
    }
}

// *****************************************************
// Insert a page into a template page, set the title,
// load the corresponding side bar and change the menu 
// highlights
// http : The AJAX requestor
// contentId : The id of the html component to fill
// pName : The id of the menu item to change
// *****************************************************
function insertPage(http, contentId, pName) {
    if (http.readyState == 4) { 
        var content = document.getElementById(contentId);
        if (http.status == 200) {
            content.innerHTML = http.responseText;
            asyncGetSidebar(pName);
        } else {
            var html = "<h1>ERROR " + http.status + " - " + http.statusText + "</h1>";
            html += "<p><b>Sorry we cannot load the requested URL</b></p>";
            content.innerHTML = html;
            document.title = "HTTP ERROR";
            asyncGetSidebar(pName);
        }
        document.getElementById(selectedPage).className = "NavBarCell";
        document.getElementById(pName).className = "NavBarCellSel";
        selectedPage = pName;
        
    }
 }
 
// ***************************************************
// Load a part into the current page
// url : The url to load
// contentId : The id of the lement to fill
// partId : The id of the element in the loaded page 
//          to extract
// ***************************************************
function asyncLoadPart(xmlName, contentId, partId) {
	var http = getHttp();
    if (!http) {
        var msg = "Your Browser does not support AJAX\n"; 
        msg += "Sorry we cannot load the requested URL\n\n";
        msg += "You should upgrade your browser to the latest Mozilla, Firefox or Opera version\n\n";
        msg += "or if you really want troubles to the latest Internet Explorer...";
        alert(msg);
    } else {
        http.onreadystatechange = function () {
            insertPart(http, contentId);
        }
        var parameters = "file=" + encodeURIComponent(xmlName);
        parameters += "&node=" + encodeURIComponent(partId);
        http.open('GET', "/getpart.php?" + parameters, true);
        http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        http.setRequestHeader("Content-length", parameters.length);
        http.send(null);
    }
}

// *****************************************************
// Insert a part into into a specipic place in the page
// http : The AJAX requestor
// contentId : The id of the lement to fill
// partId : The id of the element in the loaded page 
//          to extract
// *****************************************************
function insertPart(http, contentId) {
    if (http.readyState == 4) { 
        var content = document.getElementById(contentId);
        if (http.status == 200) {
            content.innerHTML = http.responseText;
        } else {
            var html = "<h1>ERROR " + http.status + " - " + http.statusText + "</h1>";
            html += "<p><b>Sorry we cannot load the requested URL</b></p>";
            document.getElementById(contentId).innerHTML = html;
        }
    }
}

// ***************************************************
// Post a request with parameters
// url : The url (without parameters
// parameters : The parameter string (no leading "?" 
//              and encoded
// contentId : The id of the element to fill
// ***************************************************
function makePostRequest(url, parameters, contentId) {
	var http = getHttp();
	if (!http) {
        var msg = "Your Browser does not support AJAX\n"; 
        msg += "Sorry we cannot load the requested URL\n\n";
        msg += "You should upgrade your browser to the latest Mozilla, Firefox or Opera version\n\n";
        msg += "or if you really want troubles to the latest Internet Explorer...";
        alert(msg);
    } else {
    	http.onreadystatechange = function () {
    	    insertResponse(http, contentId);
        }
    	http.open('POST', url, true);
        http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        http.setRequestHeader("Content-length", parameters.length);
        http.setRequestHeader("Connection", "close");
        http.send(parameters);
    }
}

// ***************************************************
// Insert the response from a POST in the given 
// element
// url : The url to load
// contentId : The id of the element to fill
// ***************************************************
function insertResponse(http, contentId) {
    if (http.readyState == 4) {
        document.getElementById("running").className = "hidden";
        if (http.status == 200) {
            document.getElementById(contentId).innerHTML = http.responseText;
            document.getElementById(contentId).className = "formResult";
        } else {
            document.getElementById(contentId).innerHTML = http.responseText;
            document.getElementById(contentId).className = "formErrors";
        }
    }
}

// ***************************************************
// Submit a support request
// contentId : The id of the element to fill with error
//             messages or the return test from the
//             server
// ***************************************************
function submitSupportRequest(contentId) {
    var form = document.supportRequest;
	if (validateForm(form, contentId)) {
        document.getElementById(contentId).innerHTML = "Sending support message...";
        document.getElementById(contentId).className = "formResult";
		var url = "/support.php";
		postStr = "firstName=" + encodeURIComponent(form.FirstName.value) + 
		          "&familyName=" + encodeURIComponent(form.FamilyName.value) + 
		          "&email=" + encodeURIComponent(form.Email.value) + 
		          "&subject=" + encodeURIComponent(form.Subject.value) + 
		          "&product=" + encodeURIComponent(form.Product.value) + 
                  "&priority=" + encodeURIComponent(form.Priority.value) + 
                  "&type=" + encodeURIComponent(form.Type.value) + 
		          "&message=" + encodeURIComponent(formatMailMessage(form.Message.value));
		makePostRequest(url, postStr, contentId);
		form.reset();
	}
}

// ***************************************************
// Submit a contact request
// contentId : The id of the element to fill with error
//             messages or the return test from the
//             server
// ***************************************************
function submitContact(contentId) {
    var form = document.getElementById("contactRequest");
	if (validateForm(form, contentId)) {
	    document.getElementById("running").className = "running";
	    document.getElementById(contentId).className = "formHidden";
		var url = "/contact.php"
		postStr = "firstName=" + encodeURIComponent(form.FirstName.value) + 
		          "&familyName=" + encodeURIComponent(form.FamilyName.value) + 
		          "&email=" + encodeURIComponent(form.Email.value) + 
				  "&subject=" + encodeURIComponent(form.Subject.value) + 
				  "&message=" +encodeURIComponent(formatMailMessage(form.Message.value));
		makePostRequest(url, postStr, contentId);
		form.reset();
	}
}

// ***************************************************
// validate an email string
// return: true if ok else false
// ***************************************************
function validateEmail(email) {
    var splitted = email.match("^(.+)@(.+)$");
    if (splitted == null) {
		return false;
	}
    if(splitted[1] != null ) {
      	var regexp_user=/^\"?[\w-_\.]*\"?$/;
      	if (splitted[1].match(regexp_user) == null) {
			return false;
		}
    }
    if(splitted[2] != null) {
      	var regexp_domain=/^[\w-\.]*\.[A-Za-z]{2,4}$/;
      	if(splitted[2].match(regexp_domain) == null) {
	    	var regexp_ip =/^\[\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\]$/;
	    	if (splitted[2].match(regexp_ip) == null) {
				return false;
			}
      	}// if
      	return true;
    }
	return false;
}

// ***************************************************
// Test that input is required
// return: true if ok else false
// ***************************************************
function TestRequiredInput(objValue) {
    if(eval(objValue.value.length) == 0) { 
       return false; 
    }
	return true;
}

// ***************************************************
// validate the maximum length
// return: true if ok else false
// ***************************************************
function TestMaxLen(objValue, strMaxLen) {
    if(eval(objValue.value.length) > eval(strMaxLen)) { 
       return false; 
    }//if 
	return true;
}

// ***************************************************
// validate one of the forms in the site
// form : The contact form to validate
// contentId : The id of the element to fill with error
//             messages
// return: true if ok else false
// ***************************************************
function validateForm(form, contentId) {
	var errorMsgs = new Array(0);
	if (!TestRequiredInput(form.FirstName)) {
		errorMsgs.push("Please enter your First Name")
	} else if (!TestMaxLen(form.FirstName, 50)) {
		errorMsgs.push("The maximum allowed length of First Name is 50");
	}
	if (!TestRequiredInput(form.FamilyName)) {
		errorMsgs.push("Please enter your Family Name")
	} else if (!TestMaxLen(form.FamilyName, 50)) {
		errorMsgs.push("The maximum allowed length of Family Name is 50");
	}
	if (!TestRequiredInput(form.Subject)) {
		errorMsgs.push("Please enter the Subject")
	} else if (!TestMaxLen(form.Subject, 64)) {
		errorMsgs.push("The maximum allowed length of Subject is 64");
	}
	if (!TestRequiredInput(form.Message)) {
		errorMsgs.push("Please enter a message to send")
	} else if (!TestMaxLen(form.Subject, 256)) {
		errorMsgs.push("The maximum allowed length of a message to send is 256");
	}
	if (!TestRequiredInput(form.Email)) {
		errorMsgs.push("Please enter your Email")
	} else if (!validateEmail(form.Email.value)) {
		errorMsgs.push(form.Email.value + " is not a valid email");
	}
	if (errorMsgs.length > 0) {
		var html = "";
		for (i = 0; i < errorMsgs.length;i++) {
			html += errorMsgs[i] + "<br/>";
		}
		document.getElementById(contentId).innerHTML = html;
		document.getElementById(contentId).className = "formErrors";
		return false;
	}
	document.getElementById(contentId).innerHTML = "";
	document.getElementById(contentId).className = "";
	return true;
}

// ***************************************************
// Format a mail message for PHP mail, making sure 
// that lines are shorter than 70 chars and end with
// CRLF and that the message ends with CRLF.CRLF
// msg : The message to format
// return : The formatted message 
// ***************************************************
function formatMailMessage(msg) {
    var startStr = "";
    var la = msg.split("\n");
    var retStr = "";
    for(var i = 0; i < la.length; i++) {
        if (la[i].charAt(la[i].length - 1) != "\r") {
            startStr = la[i] + "\r\n";            
        } else {
            startStr = la[i] + "\n";
        }
        var sa = startStr.split(" ");
        var line = "";
        for(var j = 0; j < sa.length; j++) {
            line += sa[j];
            if (line.length > 70) {
                while (line.length > 70) {
                  retStr += line.substr(0, 70) + "\r\n";
                  line = line.substr(70, line.length - 70);
                }
                retStr += line + "\r\n";
            } else if (j < (sa.length - 1)) {
                if ((line.length + sa[j + 1].length) > 70) {
                    retStr += line + "\r\n";
                    line = "";              
               } else {
                   line += " ";
               }
            } else {
               retStr += line;
            }
        }
    }
  	return retStr.concat("\r\n.\r\n");
}

// ***************************************************
// Collapse a drop down menu
// menuId : The id of the menu to collapse
// ***************************************************
function collapse(menuId) {
    var d = document.getElementById(menuId);
    d.className = "dropDownHidden";
}

// ***************************************************
// Pop up a drop down menu
// parentId : The id of the menu bar item being expanded
// menuId : The id of the menu to collapse
// ***************************************************
function expand(parentId, menuId) {
    var d = document.getElementById(menuId);
    var item = document.getElementById(parentId);
    var menu = document.getElementById("menu");
    var pane = document.getElementById("pane");
    if (onMs) {
        d.className = "dropDownShownWin";
        if (onMs7) {
            d.className = "dropDownShown";
        } else {
            d.className = "dropDownShownWin";
        }
        d.style.left = menu.offsetLeft + item.offsetLeft + 14;
        d.style.top = pane.offsetTop + item.offsetHeight + 4;
    } else {
        d.className = "dropDownShown";
    }
}

// ***************************************************
// Highlight an item in a drop down menu
// td : The td element to highlight
// ***************************************************
function highLightItem(td) {
    td.className = "NavBarDDCellSel";
}

// ***************************************************
// Lowlight an item in a drop down menu
// td : The td element to highlight
// ***************************************************
function lowLightItem(td) {
    td.className = "NavBarDDCell";
}

var windowMap = {};

// ***************************************************
// OPen a link in a new window or tab. If the url has
// already been opened, the tab/window is closed and
// re-opened.
// url : The url to open
// ***************************************************
function openNewLink(url) {
    var hash = hashString(url);
    var wRef = windowMap[hash];
    if (wRef) {
    	wRef.close();
    }
    wRef = window.open(url, hash);
    windowMap[hash] = wRef;
}

// ***************************************************
// Get the hash of the url (for IE). uses the java
// hash method and prepends "win"
// str : The string to hash
// ***************************************************
function hashString(str) {
    var hash = 0;
    for (var i = 0; i < str.length; i++) {
       hash = (31 * hash) + str.charCodeAt(i);
    }
    return "win" + hash.toFixed();
}

