///////  Domain parsing function
function getDomain(useFrames)
{
    var documentDomain = "";
   
    if (useFrames)
    {
        documentDomain = window.frames.location.host.split(':');
    }
    else
    {
        documentDomain = window.location.host.split(':');
    }

	if (documentDomain.length > 1)
	{
		documentDomain = documentDomain[0];
	}
	else
	{
		if (useFrames)
		{
			documentDomain = window.frames.location.host;
		}
		else
		{
			documentDomain = window.location.host;
		}
	}
	
    if (documentDomain.length > 0)
    {
        var documentDomainSplit = documentDomain.split('.'); 

        if (documentDomain.search(/\.com.*$/i) >= 0)
        {
            documentDomain = documentDomainSplit[documentDomainSplit.length - 2] + '.' + documentDomainSplit[documentDomainSplit.length - 1];
        } 
    }

	return documentDomain;
}

///////  Variation parsing function
function getVariation(useFrames)
{
	// return united states english by default
	var currentVariation = "en-US";
	var variationTest = "";
	
	if (useFrames)
	{
	    variationTest = window.location.href.split('/')[3];
	}
	else
	{
	    variationTest = window.frames.location.href.split('/')[3];
	}
	
	// check the variation to make sure it's formed correctly
	if (/((?:[a-zA-Z][a-zA-Z]+))(-)((?:[a-zA-Z][a-zA-Z]+))/.test(variationTest))
	{
		currentVariation = variationTest;
	}

	return currentVariation;
}

///////  Country Control handler functions
function changeCountry(ddowncontrol) 
{ 
    var fields = window.location.href.split('/');
    var dropDown = ddowncontrol;
    var selIndex = dropDown.selectedIndex;
    var newvariation = dropDown.options[selIndex].value;
    var newURL = "";
    
    if (newvariation.length > 0)
    {
        if ( newvariation.substring(0,4) == 'www.' )
        {
            window.location.href = 'http://' + newvariation;
        }
        else
        {
            if ( newvariation.indexOf('/') >= 0 )
            {
                // replaces the new variation AND remaining path
                for(i = 0; i <= VariationNode; i++)
                {
                    if ( i != 0 )
                        newURL = newURL + "/";
                    if ( i != VariationNode )    
                        newURL = newURL + fields[i];
                    else
                        newURL = newURL + newvariation;
                }
            }
            else
            {
                // plug the new variation into the ith field of the URL
                for(i = 0; i < fields.length; i++)
                {
                    if ( i != 0 )
                        newURL = newURL + "/";
                    if ( i != VariationNode )    
                        newURL = newURL + fields[i];
                    else
                        newURL = newURL + newvariation;
                }
            }
            
            window.location.href = newURL;
        }
    }
} 
////////  End Country Control handler functions

////////  Start of Search Button and Search TextBox functions
    function initSearch()
    {
        // when window first builds... set the search text box
        srchCriteriaBox = document.getElementById('txt_search').value = 'enter search';
    }

    function srchBtnClicked()
    {
        if ( document.forms[0].txt_search.value.length > 0 &&
             document.forms[0].txt_search.value != 'enter search' )
        {
            // if something was entered in the search box, go do the search
            window.location.href='/' + getVariation(false) + '/Search/results.aspx?k=' + document.forms[0].txt_search.value + '&s=' + getVariation(false);
        }
    }

    function srchBoxEntered(id)
    {
        // when they enter the search text box, clear out anything there
        document.getElementById(id).value = "";
    }
    
    function srchBoxTextEntering(e)
    {
        if (window.event)
        {
            // ie
            if ( window.event.keyCode == 13 )
            {
                window.event.returnValue = false;
                window.event.cancel;
                srchBtnClicked();
            }        
        }
        else
        {
            // firefox
            if (e.which == 13 )
            {
                e.returnValue = false;
                e.cancel;
                srchBtnClicked();
            }
        }
    }
////////  End of Search Button and Search TextBox functions

/// Menu stuff
/* timers */
var timer1;
var timer2;

/*list of top level tier elements for timer tracking */
var tierLists;
var tier2Lists;

ns4 = document.layers;
ie4 = document.all;
nn6 = document.getElementById && !document.all; 

function showObject(divLayer) {
  var y_offset = -76; 
  var x_offset = -15; 
  if (ns4) {
     document.divLayer.visibility = "show";
     document.divLayer.display = "block";
  }
  else if (ie4) {
     document.all[divLayer].style.visibility = "visible";
     document.all[divLayer].style.display = "block";
  }
  else if (nn6) {
     document.getElementById(divLayer).style.visibility = "visible";
     document.getElementById(divLayer).style.display = "block";
  }
}


function hideObject(divLayer) {
  if (ns4) {
     document.divLayer.visibility = "hide";
     document.divLayer.display = "none";
  }
  else if (ie4) {
     document.all[divLayer].style.visibility = "hidden";
     document.all[divLayer].style.display = "none";
  }
  else if (nn6) {
     document.getElementById(divLayer).style.visibility = "hidden";
     document.getElementById(divLayer).style.display = "none";
  }
}

		
$(document).ready(function() 
{

	tierLists = $(".tier_nav");
	for(var i in tierLists)
		tierLists[i].index = i;

	tier2Lists = $(".tier2_nav");
	for(var j in tier2Lists)
		tier2Lists[j].index = j;

	/* nav level fade handlers */
	$(".tier_nav").hover
	(
		function()
		{
			//hide any straggler lists that may persits
			$(".tier_nav").children("ul").css("display","none");
			//$(this).children("ul").fadeIn("fast");		
			timer1 = setTimeout("showTier("+this.index+")",100);
		},
		function()
		{
			$(this).children("ul").css("display","none");
			clearTimeout(timer1);
		}		
	);

	/* second level nav level fade handlers */
	$(".tier2_nav").hover
	(
		function()
		{
			//hide any straggler lists that may persits
			$(".tier2_nav").children("ul").css("display","none");
			//$(this).children("ul").fadeIn("fast");
			timer2 = setTimeout("showTier2("+this.index+")",200);
		},
		function()
		{
			$(this).children("ul").css("display","none");
			clearTimeout(timer2);
		}		
	);
	
	/* hide persistant menus when hover over a primary nav link that does not have sub levels */
	$("#home, #contact_us, #form_search").mouseover
	(
		function ()
		{
			$(".tier_nav").children("ul").css("display","none");
		}
	);
	
	// this initialises the demo scollpanes on the page.
	$('.scroll-pane').jScrollPane({showArrows:true, scrollbarWidth: 15, arrowSize: 16});
	
});

function showTier(listIndex)
{
	//$(tierLists[listIndex]).children("ul").fadeIn("fast");
	$(tierLists[listIndex]).children("ul").css("display","block");
}

function showTier2(listIndex)
{
//$(tier2Lists[listIndex]).children("ul").fadeIn("fast");
	$(tier2Lists[listIndex]).children("ul").css("display","block");
}
/// End menu stuff

/// Email stuff
$(document).ready(function() 
{
	var $email_popup_container = $("#popup_container").remove();
	$email_popup_container.insertBefore("#wrapper");
});

function fadeBackgroundTo(opacity)
{
	$("#wrapper").fadeTo("slow", opacity);
}

function openEmailPage()
{
	fadeBackgroundTo(0.2);
	$("#popup_container").fadeIn("slow");
	$("#email_page").fadeIn("slow");
}
function closeEmailPage()
{
	$("#email_page").fadeOut("slow");
	$("#popup_container").fadeOut("slow");
	fadeBackgroundTo(1);
}

/// End email stuff

/// Job stuff
$(document).ready(function() 
{
	var $popup_container = $("#popup_container").remove();
	$popup_container.insertBefore("#wrapper");
});
function openJob(jobID)
{
	fadeBackgroundTo(0.2);
	$("#"+jobID).centerInClient();	
	$("#popup_container").fadeIn("slow");
	$("#"+jobID).fadeIn("slow");
}
function closeJob(jobID)
{
	$("#"+jobID).fadeOut("slow");
	$("#popup_container").fadeOut("slow");
	fadeBackgroundTo(1);
}
/// End job stuff

/// Event stuff
$(document).ready(function() 
{
	var $popup_container = $("#popup_container").remove();
	$popup_container.insertBefore("#wrapper");
});
function openEvent(eventID)
{
	fadeBackgroundTo(0.2);
	$("#"+eventID).centerInClient();	
	$("#popup_container").fadeIn("slow");
	$("#"+eventID).fadeIn("slow");
}
function closeEvent(eventID)
{
	$("#"+eventID).fadeOut("slow");
	$("#popup_container").fadeOut("slow");
	fadeBackgroundTo(1);
}
function openRegistration(eventId)
{
	$("#reg_form_"+eventId).fadeIn("slow");
}
function closeRegistration(eventId)
{
	$("#reg_form_"+eventId).fadeOut("slow");
}

/// End event stuff

/// JQuery extensions

$.fn.centerInClient = function(options) {
    /// <summary>Centers the selected items in the browser window. Takes into account scroll position.
    /// Ideally the selected set should only match a single element.
    /// </summary>    
    /// <param name="fn" type="Function">Optional function called when centering is complete. Passed DOM element as parameter</param>    
    /// <param name="forceAbsolute" type="Boolean">if true forces the element to be removed from the document flow 
    ///  and attached to the body element to ensure proper absolute positioning. 
    /// Be aware that this may cause ID hierachy for CSS styles to be affected.
    /// </param>
    /// <returns type="jQuery" />
    var opt = { forceAbsolute: false,
                container: window,    // selector of element to center in
                completeHandler: null
              };
    $.extend(opt, options);
   
    return this.each(function(i) {
        var el = $(this);
        var jWin = $(opt.container);
        var isWin = opt.container == window;

        // force to the top of document to ENSURE that 
        // document absolute positioning is available
        if (opt.forceAbsolute) {
            if (isWin)
                el.remove().appendTo("body");
            else
                el.remove().appendTo(jWin.get(0));
        }

        // have to make absolute
        el.css("position", "absolute");

        // height is off a bit so fudge it
        var heightFudge = isWin ? 2.0 : 1.8;

        var x = (isWin ? jWin.width() : jWin.outerWidth()) / 2 - el.outerWidth() / 2;
        var y = (isWin ? jWin.height() : jWin.outerHeight()) / heightFudge - el.outerHeight() / 2;

        if (y < 0)
	    {
	        y = 0;
	    }

        el.css("left", x + jWin.scrollLeft());
        el.css("top", y + jWin.scrollTop());

        // if specified make callback and pass element
        if (opt.completeHandler)
            opt.completeHandler(this);
    });
}

/// End JQuery extensions

/// XSLT Transformation Operations

function loadXMLDoc(fname)
{
    var xdoc;
    // code for IE
    if (window.ActiveXObject)
    {
        xdoc = new ActiveXObject("Microsoft.XMLDOM");
    }
    // code for Mozilla, Firefox, Opera, etc.
    else if (document.implementation && document.implementation.createDocument)
    {		
        if (fname.childNodes)
		{
			return fname;
		}
        else
		{
			xdoc = document.implementation.createDocument("", "", null);
		}
    }
    else
    {
        alert('Your browser cannot load XML documents.');
    }
    xdoc.async = false;
    xdoc.load(fname);
    return(xdoc);
}

function transformXMLDoc(container, xml, xsl)
{
    // code for IE
    if (window.ActiveXObject)
    {
        html = xml.transformNode(xsl);
        container.innerHTML = html;
    }
    // code for Mozilla, Firefox, Opera, etc.
    else if (document.implementation && document.implementation.createDocument)
    {
		while (container.hasChildNodes())
		{
			container.removeChild(container.childNodes[0]);
		}
		
        xsltProcessor = new XSLTProcessor();
        xsltProcessor.importStylesheet(xsl);
        html = xsltProcessor.transformToFragment(xml, document);
        container.appendChild(html);
    }
}

/// End XSLT Transformation Operations

/// Error Handling

onerror = handleError;
var errorText = "";

function handleError(message, url, line)
{
    errorText = "There was an error on this page.\n\n";
    errorText += "Error: " + message + "\n";
    errorText += "URL: " + url + "\n";
    errorText += "Line: " + line + "\n\n";
    errorText += "Click OK to continue.\n\n";
    alert(errorText);
    return true;
}

/// End Error Handling