function jsProductChange() {
	//
	// Show/hide subcategory <divs> when a product category is selected
	//
	if (g_lastSubCatSelected == '') g_lastSubCatSelected = "All";

	var theForm = jsGetElement("search_form");

	//
	// Test first if product type is valid for selected format
	//
	/*if (!jsTestProductTypeForFormat(theForm)) {
		return;
	}*/

	var olddivName = "subcat_" + g_lastSubCatSelected;
	var olddiv = jsGetElement(olddivName);
	olddiv.style.display = "none";

	var selectedValue = theForm.category.options[theForm.category.selectedIndex].value;
	var newdivName = "subcat_" + selectedValue;
	var newdiv = jsGetElement(newdivName);
	newdiv.style.display = "block";

	//
	// Un-check any checkboxes for previously selected
	//
	for (var i = 0; i < olddiv.children.length; i++) {
		try {
			olddiv.children[i].children[0].children[0].checked = false;
		} catch(e) {
		}
	}

	//
	// Update formats based on current publication type
	//
	var saveFormat = '';
	if(theForm.format.options.length > 0)
	    saveFormat = theForm.format.options[theForm.format.selectedIndex].value;
	theForm.format.options.length = 0;
	var arrayValueName = "arr_value_" + selectedValue;
	var arrayTextName = "arr_text_" + selectedValue;
	var arrayLength = eval(arrayValueName + ".length");
	var selectFirstOption = true;

	for (var i = 0; i < arrayLength; i++) {
		try {
			var thisValue = eval(arrayValueName + "[" + i + "]");
			var thisText = eval(arrayTextName + "[" + i + "]");
			theForm.format.options[i] = new Option(thisText, thisValue);
			//
			// Test if this is what was previously selected format
			//
			if (thisValue == saveFormat)
			{
				theForm.format.options[i].selected = true;
				selectFirstOption = false;
			}
		} catch(e) {
		}
	}

	//
	// if previously selected format no longer exists, select first option
	//
	var searchDiv = jsGetElement("search_availableFormats");
	if(theForm.format.options.length == 0)
	{
	    searchDiv.style.display = "none";
	}
	else
	{
	    searchDiv.style.display = "block";
		if (selectFirstOption) theForm.format.options[0].selected = true;
	}

	//
	// Display the DL promo
	//
	if (arr_dlpromo[theForm.category.selectedIndex] == true) {
		var dlpromodiv = jsGetElement("dlpromo");
		if (dlpromodiv != null) dlpromodiv.style.display = "block";
	}

	//
	// Save last selected pub type
	//
	g_lastSubCatSelected = selectedValue;
}

function jsFormSubmitResearchPapers() {
	var theForm = jsGetElement("search_form");

	if (!jsMonthAndYearSpecified(theForm.month_from.selectedIndex, theForm.year_from.selectedIndex)) return false;
	if (!jsMonthAndYearSpecified(theForm.month_to.selectedIndex, theForm.year_to.selectedIndex)) return false;
	jsTestForYearOnly(theForm);
	jsTestForSingleMonthYear(theForm);
	return true;
}

function jsFormSubmitPubsAdvancedSearch() {
	var theForm = jsGetElement("search_form");

	if (!jsMonthAndYearSpecified(theForm.month_from.selectedIndex, theForm.year_from.selectedIndex)) return false;
	if (!jsMonthAndYearSpecified(theForm.month_to.selectedIndex, theForm.year_to.selectedIndex)) return false;
	jsTestForYearOnly(theForm);
	jsTestForSingleMonthYear(theForm);
	return true;
}

function jsMonthAndYearSpecified(p_monthIndex, p_yearIndex) {
	if (p_monthIndex > 0 && p_yearIndex == 0)
	{
		alert("Please specify a year as well as a month.");
		return false;
	}
	return true;
}

function jsTestForYearOnly(p_theForm) {
	//
	// If only a year is entered for either "from" or "to", search is Jan-Dec of that year.
	//
	if (p_theForm.month_from.selectedIndex == 0 && 
		p_theForm.month_to.selectedIndex == 0)
	{
		if (p_theForm.year_from.selectedIndex > 0 && p_theForm.year_to.selectedIndex == 0)
		{
			p_theForm.month_from.selectedIndex = 1;
			p_theForm.month_to.selectedIndex = 12;
			p_theForm.year_to.selectedIndex = p_theForm.year_from.selectedIndex;
		}
		else if (p_theForm.year_from.selectedIndex == 0 && p_theForm.year_to.selectedIndex > 0)
		{
			p_theForm.month_from.selectedIndex = 1;
			p_theForm.month_to.selectedIndex = 12;
			p_theForm.year_from.selectedIndex = p_theForm.year_to.selectedIndex;
		}
	}	
}

function jsTestForSingleMonthYear(p_theForm) {
	//
	// If either "from" or "to" month and year is specified, set the other to the same (single month search)
	//
	if (p_theForm.month_from.selectedIndex > 0 && p_theForm.year_from.selectedIndex > 0 &&
		p_theForm.month_to.selectedIndex == 0 && p_theForm.year_to.selectedIndex == 0)
	{
		p_theForm.month_to.selectedIndex = p_theForm.month_from.selectedIndex;
		p_theForm.year_to.selectedIndex = p_theForm.year_from.selectedIndex;
	}
	else if (p_theForm.month_from.selectedIndex == 0 && p_theForm.year_from.selectedIndex == 0 &&
		p_theForm.month_to.selectedIndex > 0 && p_theForm.year_to.selectedIndex > 0)
	{
		p_theForm.month_from.selectedIndex = p_theForm.month_to.selectedIndex;
		p_theForm.year_from.selectedIndex = p_theForm.year_to.selectedIndex;
	}
}

function jsTestProductTypeForFormat(p_theForm) {
	var selectedPubType = p_theForm.category.options[p_theForm.category.selectedIndex].value;
	var selectedFormat = p_theForm.format.options[p_theForm.format.selectedIndex].value;
	var arrayValueName = "arr_value_" + selectedPubType;
	var arrayLength = eval(arrayValueName + ".length");
	var intFound = -1;

	if (selectedFormat == 'All') return true; // Don't test for "All"

	for (var i = 0; i < arrayLength; i++)
	{
		try {
			var thisFormat = eval(arrayValueName + "[" + i + "]");
			if (selectedFormat == thisFormat) intFound = i;
		} catch(e) {

		}
	}

	if (intFound < 0) {
		var selectedPubTypeDisplay = p_theForm.category.options[p_theForm.category.selectedIndex].text;
		var selectedFormatDisplay = p_theForm.format.options[p_theForm.format.selectedIndex].text;
		alert(selectedPubTypeDisplay + " are not available in " + selectedFormatDisplay + " format.");
		return false;
	}
	return true;
}

function jsToggleStateMenus(p_selectedCountry) {
	//
	// Update state dropdown for individual and corporate member search
	//
	var objState = jsGetElement('state');
	var arrayLength = eval("arr_countries.length");
	var blnStates = false;
	var selectedCountry = removeSpaces(p_selectedCountry);

	if (selectedCountry.length > 0) {	// If all countries selected, value will be empty string
		for (i = 0; i <= arrayLength; i++) {
			if (arr_countries[i] == selectedCountry) {
				blnStates = true;
			}
		}
	}

	objState.options.length = 0;
	if (blnStates) {
		//
		// A country with a states dropdown was selected
		//
		objState.disabled = false;
		var arrayValueName = "arr_value_" + selectedCountry;
		var arrayTextName = "arr_text_" + selectedCountry;
		arrayLength = eval(arrayValueName + ".length");

		for (var i = 0; i < arrayLength; i++) {
			try {
				var thisValue = eval(arrayValueName + "[" + i + "]");
				var thisText = eval(arrayTextName + "[" + i + "]");
				objState.options[i] = new Option(thisText, thisValue);
			} catch(e) {
			}
		}
	} else {
		//
		// A country without a states dropdown was selected
		//
		objState.disabled = true;
	}
}


function jsGetElement(p_objectId) {
	if (document.getElementById && document.getElementById(p_objectId)) {
		return document.getElementById(p_objectId);
	}
	else if (document.all && document.all(p_objectId)) {  
		return document.all(p_objectId);
	} 
	else if (document.layers && document.layers[p_objectId]) { 
		return document.layers[p_objectId];
	} 
	else {
		return false;
	}
}

function removeSpaces(p_string) {
	p_string = '' + p_string;
	return(p_string.replace( /\s/g, ""));
}

function ShowHideAbstracts()
{   
    //this method is W3CDOM-compatible only. It does not support NS4/IE5 DOMs
    var AllElements;

    var W3CDOM = (document.createElement && document.getElementById);
    if(!W3CDOM)
    {
        return;
    }
    
    AllElements = document.getElementsByTagName("div");
    
    for(i = 0; i < AllElements.length; i++)
    {    
        var CurrentElementAttribute;
        CurrentElementAttribute = AllElements[i].attributes.getNamedItem("id");
        
        if(CurrentElementAttribute != null && CurrentElementAttribute != "undefined")
        {
            if(CurrentElementAttribute.value  != null && CurrentElementAttribute.value  != '' && CurrentElementAttribute.value.length > 0)
            {
                var AttributeValue = CurrentElementAttribute.value;
                if( (AttributeValue.indexOf('abstract_') > -1) && (AttributeValue.length > 9) )
                {
                    var Element = AllElements[i];
                    if(Element != null)
                    {
                        if(Element.className == "HideAbstract")
                        {
                            Element.className = "ShowAbstract";
                        }
                        else if (Element.className == "ShowAbstract")
                        {
                            Element.className = "HideAbstract";
                        }
                    }
                }
            }
        }
    }
    return true;
}

function jsShowDivRel(divName, relatedName, hOffset, vOffset)
{
    // ------------------------------------------------------------
    // Show popup DIV
    // ------------------------------------------------------------
    var thisObject = jsGetElement(divName);
    var relObject = jsGetElement(relatedName);
    
    var tPos = vOffset, lPos = hOffset;
    while(relObject != document.body)
    {
        tPos += relObject.offsetTop;
        lPos += relObject.offsetLeft;
        relObject = relObject.offsetParent;
    }
    
    thisObject.style.visibility='visible';
    thisObject.style.display='';
    thisObject.style.position='absolute';
    thisObject.style.left = lPos + 'px';
    thisObject.style.top = tPos + 'px';
}

function jsHideDiv(divName)
{
    // ------------------------------------------------------------
    // Hide Popup DIV
    // ------------------------------------------------------------
    var thisObject = jsGetElement(divName);
    thisObject.style.visibility='hidden';
    thisObject.style.display='none';
}

// ------------------------------------------------------------
// Code to support site wide search
// ------------------------------------------------------------

function SaveSearchParams()
{
	if(document.searchform.searchtext!=undefined)
		createCookie('searchtext',document.searchform.searchtext.value.substring(0,100),'0');
}

function SelectSection(section)
{
	var list = document.searchform.section;
	for(var i = 0; i < list.options.length; ++i)
		{
		if(list.options[i].value==section)
			{
			list.options[i].selected=true;
			return;
			}
		}
}

function GetSearchParams()
{
	if(document.searchform.searchtext!=undefined && readCookie('searchtext'))
		document.searchform.searchtext.value=readCookie('searchtext');
	//GetMatches();
}

function createCookie(name,value,days) 
{
	if (days) 
		{
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
		}
	else 
		var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) 
{
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) 
		{
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
		}
	return '';
}

function eraseCookie(name) 
{
	createCookie(name,"",-1);
}


function clickinsearch()
{
	if(document.forms[0].searchtext.value=='Search SPIE.org')
		{
		document.forms[0].searchtext.value='';
		document.getElementById('searchtext').style.color='#000';
		}
}

function clickinsearchHome(fldid)
{
	if(document.getElementById(fldid).value==document.getElementById(fldid).defaultValue)
		{
		document.getElementById(fldid).value='';
		document.getElementById(fldid).style.color='#000';
		}
}

function LoadCalendar(isPageLoad)
{
	var params='';
	
	/* isPageLoad indicates the page is being loaded via an external URL. i.e., via a mega menu selection */
	if(isPageLoad) {
		var paramArray=window.location.href.split('?');
		if(paramArray.length==2) {
			params='?'+paramArray[1];
			if(paramArray[1].split('&').length==1) {
				params+='&region=all';
			}
		}
	} else {
		try {
		var type = document.getElementById('calendartype');
		var region = document.getElementById('calendarregion');
		params='?region='+region[region.selectedIndex].value+'&type='+type[type.selectedIndex].value;
		} catch(e) {}
	} 
	var request=new AJAXRequest('/app/sitesearch/calendar.cfm'+params,DisplayCalendar);
	request.send();
}

function DisplayCalendar(responseText)
{
	setInnerHTML('eventcalendar',responseText);
}

function WebAd(destinationurl,adname)
{
	dcsMultiTrack('WT.es',window.location.hostname+window.location.pathname,'WT.ac',adname);
	dcsMultiTrack('WT.es',window.location.hostname+window.location.pathname,'WT.dl','7','DCSext.navsec','Banner Rotator','WT.ac','');
	window.location.href=destinationurl;
}

function submitsearch() // DL Search
{
	dcsMultiTrack('WT.es',window.location.hostname+window.location.pathname,'WT.dl','4','WT.oss',document.getElementById('possible1').value,'WT.oss_r','1','DCSext.oss_sec','AIP_Digital_Library_Search','DCSext.oss_type','Quick')
	dcsMultiTrack('WT.es',window.location.hostname+window.location.pathname,'WT.dl','7','DCSext.navsec','DL Search','WT.oss','','WT.oss_r','','DCSext.oss_sec','','DCSext.oss_type','');
	window.open('http://spiedigitallibrary.org/search?key=SPIE_ALL&societykey=SPIE&coden=OPEGAR&q='+document.getElementById('possible1').value+'&displayid=SPIE&sortby=relevance&faceted=faceted&sortby=newestdate&CP_Style=false&alias=%2Foe&searchzone=2&q='+document.getElementById('possible1').value,'DLSearch');
}

function submitsitesearch() // Site wide search
{
	WTOptimize.conversion('ta_SPIEorg', this);
	dcsMultiTrack('WT.es',window.location.hostname+window.location.pathname,'WT.dl','7','DCSext.navsec','Sitewide Search');
	if(document.getElementById('sectionmenu').value=='exhibitors') {
		window.location.href='/app/exhibitordirectory/search.aspx?term='+document.getElementById('searchtext').value;
	} else {
		window.location.href='/app/sitesearch/index.cfm?searchtext='+document.getElementById('searchtext').value+'&section='+document.getElementById('sectionmenu').value;
	}
}

function breakStringAtLastWord(str, maxlen)
{
    if (str == null)
        return null;
    if (isNaN(maxlen) || maxlen > str.length)
        return str;
    var cutStr = str.substr(0, maxlen);
    var wordbreakindex = -1;
    var targetIndex = -1;
    do
    {
        wordbreakindex += targetIndex + 1;
        targetIndex = cutStr.substr(wordbreakindex + 1).search(/\W/);
    } while (targetIndex > -1)
    return str.substr(0, wordbreakindex);
}
