// Common JavaScript Library
// By Bradley Stec and Ben Rimbey, January 2006
// For Books and Manuscripts LLC

//
// Initialize Common Variables
//

var i = 0;

// General Date String Support
var jsDow = new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");
var jsMoy = new Array("January","February","March","April","May","June","July","August","September","October","November","December");
var jsMonth = new Array('January','February','March','April','May','June','July','August','September','October','November','December');
var jsDays = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
var jsShortDow = new Array('Sun','Mon','Tue','Wed','Thu','Fri','Sat');

// Create Some Basic Date Objects for General Use
var jsToday = new Date();
var jsTodayDay = jsToday.getDate()+1;
var jsTodayMonth = jsToday.getMonth()+1;
var jsTodayYear = jsToday.getFullYear();
if(jsTodayYear < 2000) { jsTodayYear = jsTodayYear + 1900; }

// Create Some Nicely Formatted Strings For General Use
// This string will read out in long form on the display.
end = "th";
if (jsTodayDay==1 || jsTodayDay==21 || jsTodayDay==31) end="st";
if (jsTodayDay==2 || jsTodayDay==22) end="nd";
if (jsTodayDay==3 || jsTodayDay==23) end="rd";
jsTodayDay+=end;

var jsDow = jsDow[jsToday.getDay()];
var jsDate = (jsMoy[jsToday.getMonth()]+" "+jsTodayDay+", "+jsTodayYear);

// StartTime is a TimeStamp That Can Be Used to Calculate Load and Run Time
// You just need to Create an End TimeStamp and do a calculation for elapsed time.
var jsStartTime = new Date();

// Email Address Build Variables To Hide Them From Spam Target Harvesters
// Use these variables and JavaScript to dynamically build email addresses 
// at runtime so that harvesters can't find them.
var emDomain="booksandmanuscripts";
var emSuffix="com";
var emContact="request";
var nmContact="Requests";
var ContactEmail="<a href='mailto:" + emContact + "@" + emDomain + "." + emSuffix + "'>" + nmContact + "</a>";

// Default Browser Status Bar
window.defaultStatus = "";

jsLeavingSiteMsg = "Note: By clicking this link you'll be leaving the site.";

//
// Shared Low-Level Functions
//

function selectDropDownIndex(id, valueToCheck) {
	if (valueToCheck != "") {
		for (i = 1; i <= document.getElementById(id).length; i++) {
			if (document.getElementById(id).options[i].value == valueToCheck) {
				document.getElementById(id).options[i].selected = true;
				break;
			}
		}
	}
}



// Validate Month Value and Fix Two Digits
// Valid Numbers are 01 to 12
function validMonth(x) {
	// Confirm All Digits
	var errString = "";
	var n=eval(x.value);
	if ( n < 1 || n > 12 ) {
		errString="Please enter a month between 1 and 12.";
		n=jsTodayMonth;
	}
	if ( n < 10 ) {
		x.value = "0" + n;
	} else {
		x.value = n;
	}
	if (errString != "") {
		alert(errString);
		x.select(0);
		x.focus();
	}
}

// Validate Year Value and Fix Four Digits
// Valid Numbers are between 1980 and 2099
function validYear(x) {
	// Confirm All Digits
	var errString = "";
	var n=eval(x.value);
	if ( n < 1980 || n > 2099) {
		errString="Please enter a year between 1980 and 2099.";
		n=jsTodayYear;
		x.value=jsTodayYear.toString();
		alert(errString);
		x.select(0);
		x.focus();
	}
}

// Validate Month Value and Fix Two Digits
// Valid Numbers are 01 to 31
// Months 1,3,5,7,8,10,12 have 31 days
// Months 4,6,9,11 have 30 days
// Month 2 has 28 days.  
//     29 in leap years starting with 2004.
function validDay(x,pMonth,pYear) {
	// Max Number Is?
	var maxDays = 0;
	var leapYear = 0;
	var intYear = 0;
	var intMonth = 0;
	var intMonth = eval(pMonth.toString());
	var intYear = eval(pYear.toString());
	// Identify Leap Year
	switch (intYear) {
		case 1980 :
		case 1984 :
		case 1988 :
		case 1992 :
		case 1996 :
		case 2000 :
		case 2004 :
		case 2008 :
		case 2012 :
		case 2016 :
		case 2020 :
		case 2024 :
		case 2028 :
		case 2032 :
		case 2036 :
		case 2040 :
		case 2044 :
		case 2048 :
		case 2052 :
		case 2056 :
		case 2060 :
		case 2064 :
		case 2068 :
		case 2072 :
		case 2076 :
		case 2080 :
		case 2084 :
		case 2088 :
		case 2092 :
		case 2096 :
			leapYear = 1;
			break;
		default :
			leapYear = 0;
	}

	// Identify Month
	switch (intMonth) {
		case 1 :
		case 3 :
		case 5 :
		case 7 :
		case 8 :
		case 10 :
		case 12 :
			maxDays = 31;
			break;
		case 2 :
			maxDays = 28;
			if ( leapYear == 1 ) {
				maxDays = 29;
			}
			break;
		default :
			maxDays = 30;
	}

	var errString = "";
	var n=eval(x.value);
	if ( n < 1 || n > maxDays ) {
		errString="Invalid Day. Valid is 1 to " + maxDays.toString();
		n=1;
	}
	if ( n < 10 ) {
		x.value = "0" + n;
	} else {
		x.value = n;
	}
	if (errString != "") {
		alert(errString);
		x.select(0);
		x.focus();
	}
}
// Special Method of Calling Upload Tool Pop Up Box
function uploadTool($content,$prefix) {
	// NOTE: Do not use + signs in the passed arguments (it won't be unescaped properly)
	popSealedWindow("/includes/upload_tool.php?type=" + $content + "&prefix=" + $prefix,375,200,"uploadWindow");
}

// Pop Up A Locked Browser Window
// This one only allows scrolling within it's document.
function popSealedWindow(url,setwidth,setheight,windowname) {
	// If browser is greater than level 3 we can center the pop up window
	// Browser Safety Width
	setwidth = setwidth - 26;
	// Browser Safety Height
	setheight = setheight - 20;
	// Centering Window
	var wide = 0;
	var high = 0;
	var doit = "";
	wide = ((screen.width-setwidth)/2)
	high = ((screen.height-setheight)/2)
	if ( windowname=="") {
		windowname = "popSealed"
	}
    //doit = "window.open(\""+url+"\",\""+windowname+"\",\"toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=0,resizable=0,width=" + setwidth + ",height=" + setheight + ",top=" + high + ",left=" + wide + "\");";
	doit = "window.open(\""+url+"\",\""+windowname+"\",\"toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=0,resizable=0,width=" + setwidth + ",height=" + setheight + ",top=" + high + ",left=" + wide + "\");";
	var win = eval(doit); 
    win.focus();
}

// Pop Up A Locked Browser Window
// This one only allows scrolling within it's document.
function popScrollWindow(url,setwidth,setheight,windowname) {
	// If browser is greater than level 3 we can center the pop up window
	// Browser Safety Width
	setwidth = setwidth - 26;
	// Browser Safety Height
	setheight = setheight - 20;
	// Centering Window
	var wide = 0;
	var high = 0;
	var doit = "";
	wide = ((screen.width-setwidth)/2)
	high = ((screen.height-setheight)/2)
	if ( windowname=="") {
		windowname = "popSealed"
	}

	doit = "window.open(\""+url+"\",\""+windowname+"\",\"toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=0,width=" + setwidth + ",height=" + setheight + ",top=" + high + ",left=" + wide + "\");";
	eval(doit);
}

// Pop Up A Browser Window
// This one is an entirely new browser window with full functions.
function popFreeWindow(url,setwidth,setheight,windowname) {
	// If browser is greater than level 3 we can center the pop up window
	// Browser Safety Width
	setwidth = setwidth - 26;
	// Browser Safety Height
	setheight = setheight - 20;
	// Centered
	var wide = 0;
	var high = 0;
	var doit = "";
	wide = ((screen.width-setwidth)/2)
	high = ((screen.height-setheight)/2)
	if ( windowname=="") {
		windowname = "popFreed"
	}
	doit = "window.open(\""+url+"\",\""+windowname+"\",\"toolbar=1,location=1,directories=1,status=1,menubar=1,scrollbars=1,resizable=1,width=" + setwidth + ",height=" + setheight + ",top=" + high + ",left=" + wide + "\");";
	eval(doit);
}

// Pop Up An External Site Browser Windowm with warning.
// This one is an entirely new browser window with full functions.
function popFreeExternalWindow(url,setwidth,setheight,windowname) {
	//if ( confirm("This link will take you to a different web site.") ) {
	if ( confirm(jsLeavingSiteMsg) ) {
		// If browser is greater than level 3 we can center the pop up window
		// Browser Safety Width
		setwidth = setwidth - 26;
		// Browser Safety Height
		setheight = setheight - 20;
		// Centered
		var wide = 0;
		var high = 0;
		var doit = "";
		wide = ((screen.width-setwidth)/2)
		high = ((screen.height-setheight)/2)
		if ( windowname=="") {
			windowname = "popExternal"
		}
		doit = "window.open(\""+url+"\",\""+windowname+"\",\"toolbar=1,location=1,directories=1,status=1,menubar=1,scrollbars=1,resizable=1,width=" + setwidth + ",height=" + setheight + ",top=" + high + ",left=" + wide + "\");";
		eval(doit);
	}
}

// Test: Invalid Email Address (true = not a valid email address)
function isInvalidEmail(strTest) {
	locAt = strTest.indexOf("@",0);
	if (locAt > -1) {
		locDot = strTest.indexOf(".",locAt);
	}
	if ( locAt == -1 || locDot == -1 || locDot < locAt ) {
		return 1;
	}
	return 0;
}

// Test: Invalid Web URL (true = not a valid url)
function isInvalidHttpUrl(strTest) {
	locStr = strTest.indexOf("http",0);
	if (locStr > -1) {
		return 0;
	}
	return 1;
}

// Test: String Is Null (true = yes)
function isNullString(strTest) {
	if ( strTest.length < 1 ) {
		return 1;
	}
	return 0;
}

// Test: String Is Numeric (true = yes)
function isNumber(strTest) {
	if ( isNullString(strTest) ) {
		return 0;
	}
	if ( isNaN(strTest) ) {
		return 0;
	}
	return 1;
}

// Basic String Trimming Function
function trim(s) {
	while (s.substring(0,1) == ' ') {
		s = s.substring(1,s.length);
	}
	while (s.substring(s.length-1,s.length) == ' ') {
		s = s.substring(0,s.length-1);
	}
	return s;
}

// Remove Backslashes (String Cleaning Tool)
function stripSlashes(s) {
	for (i=0; i<s.length; i++) {
		s = s.replace("\\","");
	}
	return s;
}

// Convert Single Quotes Into Double Quotes (String Cleaning Tool)
function swapSingleQuotes(s) {
	for (i=0; i<s.length; i++) {
		s = s.replace("\'","\"");
	}
	return s;
}

// Remove Single Quotes (String Cleaning Tool)
function stripSingleQuotes(s) {
	for (i=0; i<s.length; i++) {
		s = s.replace("\'","");
	}
	return s;
}


//takes a string and removes all alpha-characters from it.  ie:  250,000 returns 250000
function stripAlpha(str) {
	var returnString = "";
	for (i = 0; i < str.length; i++) {
		var S = str.substring(i, i + 1);
		if (S == "0" || S == "1" || S == "2" || S == "3" || S == "4" || S == "5" || S == "6" || S == "7" || S == "8" || S == "9" || S == "10") {
			returnString += S;
		}
	}
	return returnString;
}



// Inline File Download
// Requires an IFRAME embedded in your page labeled "download_wrapper"
// SAMPLE: <iframe name="download_wrapper" id="download_wrapper" src="" frameborder="0" width="2" height="2" scrolling="no"></iframe>
function downloadTool(type,work) {
	document.getElementById("download_wrapper").src = "/includes/download_tool.php?Type=" + type + "&Work=" + work;
}

// This function creates an args [] array and populates it with data found in the URL's search string
function getURLargs(argseek) {
	rtrnval = "";
	var argstring=window.location.search;
	if (argstring.charAt(0) != '?') {
		return;
	}
	argstring = argstring.substring(1,argstring.length);
	var argarray=argstring.split('&');
	var i;
	var singlearg;
	for (i=0; i<argarray.length; i++) {
		singlearg = argarray[i].split('=');
		if (singlearg.length != 2) {
			continue;
		}
		var key=unescape(singlearg[0]);
		var value=unescape(singlearg[1]);
		if ( trim(key) == trim(argseek) ) {
			rtrnval = value;
		}
	}
	return rtrnval;
}

//
// Common Menu System Functions
//

// These functions must be tailored to the site structure.
// Each section of the menu must have a unique ID so that
// the JavaScript can open and close them as they are clicked.

// This hides all sections of the menu.  If you want to force
// a section to be open, you need to execute a script onLoad
// which opens the section that corresponds to the page you are
// browsing.  See "showTable()" or "openSection()".
function hideAll() {
	<!--- Add A Line Just Like These For each SUBMENU (not link) --->
	<!--- The ID name (membership) must match the submenu table object ID below --->
	document.getElementById('about').style.display = 'none';
	document.getElementById('service').style.display = 'none';
	document.getElementById('articles').style.display = 'none';
	document.getElementById('register').style.display = 'none';
}

// This function mutes glowing sections.
function muteAll() {
	<!--- Add A Line Just Like These For each SUBMENU (not link) --->
	<!--- The ID name (membership) must match the submenu table ID below --->
	document.getElementById('about').style.backgroundColor = '';
	document.getElementById('service').style.backgroundColor = '';
	document.getElementById('articles').style.backgroundColor = '';
	document.getElementById('register').style.backgroundColor = '';
}

// This function shows the menu section that is requested.
function showTable(obj) {	
	if (obj.style.display == 'block') {
		obj.style.display = 'none';
	} else {
		obj.style.display = 'block';
	}
}

// This function glows the menu section that is requested.
function glowTable(obj) {	
	return 0;
	//muteAll();
	//obj.style.backgroundColor = '#9999FF';
}

// This function will detect the subdirectory that the page is loaded
// from and correspond that subdirectory to an openSection of the menu.
// If you load the proper directory names here you can use this function
// in a page onLoad event to get the menu to correspond.
function openSection() {
	hideAll();
	var strSection = "none";
	var strTemp = document.URL;
	//alert(document.URL);
	if ( document.URL.indexOf("/about/") > 0 ) { strSection = "about"; }
	if ( document.URL.indexOf("/service/") > 0 ) { strSection = "service"; }
	if ( document.URL.indexOf("/articles/") > 0 ) { strSection = "articles"; }
	if ( document.URL.indexOf("/register/") > 0 ) { strSection = "register"; }
	if ( strSection != "none" ) {
		showTable(document.getElementById(strSection));
	}
}

// This function stops someone from wandering out of a secured area without
// understanding the consequences, such as when they're working through a multi-page
// transaction.
function confirmSecureExit(url) {
	if (confirm("Are you sure you want to leave this secured page?\nYou'll lose any form data you already typed in if you do.")) {
		document.location.href = url;
	}
}

// This function validates Login Authentication
function loginForm(username,password) {
	document.btnLogin.src='/p/btnLogin_dn.gif';
	if ( isNullString(password) && isNullString(username) ) {
		// If both fields are blank, assume a new registration
		this.location.href="/register/index.php";
	} else {
		// If one or the other is not blank, do error checking
		if ( isNullString(password) ) {
			alert("You must provide a password to login.");
		}
		if ( isNullString(username) ) {
			alert("You must provide a username with your password.");
		}
	}
	document.btnLogin.src='/p/btnLogin_up.gif';
}

//
// BOOKSANDMANUSCRIPTS SPECIFIC FUNCTIONS
//

// This function builds a JavaScript Array of primary book categories.
function populateTopLevelCats(main, secondary) {
	document.getElementById(main).options.length = sub_array.length;
	document.getElementById(main).options[0].text = "Select one...";
	document.getElementById(main).options[0].value = "--";
	for (i = 1; i < sub_array.length; i++) {
		document.getElementById(main).options[i].text = sub_array[i]['title'];
		document.getElementById(main).options[i].value = i;
	}
	loopSecondaryCats(main, secondary);
}

// This function builds a JavaScript sub-array of secondary book categories.
function loopSecondaryCats(main, secondary) {
	if (document.getElementById(main).selectedIndex == 0) {
		//document.getElementById(secondary).options[0].text = "--";
		//document.getElementById(secondary).options[0].value = "--";
        document.getElementById(secondary).innerHTML = "<option value='--'></option>";
        document.getElementById(secondary).selectedIndex = 0;
	} else {
		var curIndex = document.getElementById(main).options[document.getElementById(main).selectedIndex].value;
		if ( sub_array[curIndex]['node_count'] > 0 ) {
			document.getElementById(secondary).options.length = sub_array[curIndex]['node_count'];
			document.getElementById(secondary).options[0].text = "Select one...";
			document.getElementById(secondary).options[0].value = "--";
			for (i = 1; i < sub_array[curIndex]['node_count']; i++) {
				document.getElementById(secondary).options[i].text = sub_array[curIndex]['nodes'][i - 1]['title'];
				document.getElementById(secondary).options[i].value = sub_array[curIndex]['nodes'][i - 1]['value'];
			}
		} else {
			document.getElementById(secondary).options.length = 1;
			document.getElementById(secondary).options[0].text = "";
			document.getElementById(secondary).options[0].value = "";
		}
	}
}
function changeStateKeyWords()
{
    var el_OneMainCat = document.getElementById('1_MainCat');
    var el_TwoMainCat = document.getElementById('2_MainCat');
    var el_ThreeMainCat = document.getElementById('3_MainCat');
    
    if( el_OneMainCat.selectedIndex == 0 &&
        el_TwoMainCat.selectedIndex == 0 &&
        el_ThreeMainCat.selectedIndex == 0 )
    {
        var sdisplay = "none";
    }else{
        var sdisplay = "block";
    }
    
    for(var i = 1; i <= 15; i++)
    {
        var el_tmp = document.getElementById('keywords_view_' + i);
        if(el_tmp)
        {
            el_tmp.style.display = sdisplay;
        }
    }
}

// This function builds a JavaScript sub-array of secondary book categories.
function loopSearchSecondaryCats(main, secondary, setSubIndex) {
	if (document.getElementById(main).selectedIndex == 0) {
        document.getElementById(secondary).innerHTML = "<option value='--'></option>";
        document.getElementById(secondary).selectedIndex = 0;
		//document.getElementById(secondary).options[0].text = "View all manuscripts in this category";
		//document.getElementById(secondary).options[0].value = "--";
	} else {
		var curIndex = document.getElementById(main).options[document.getElementById(main).selectedIndex].value;
		if ( sub_array[curIndex]['node_count'] > 0 ) {
			document.getElementById(secondary).options.length = sub_array[curIndex]['node_count'];
			document.getElementById(secondary).options[0].text = "View all manuscripts in this category";
			document.getElementById(secondary).options[0].value = "--";
			for (i = 1; i < sub_array[curIndex]['node_count']; i++) {
				document.getElementById(secondary).options[i].text = sub_array[curIndex]['nodes'][i - 1]['title'];
				document.getElementById(secondary).options[i].value = sub_array[curIndex]['nodes'][i - 1]['value'];
			}
		} else {
			document.getElementById(secondary).options.length = 1;
			document.getElementById(secondary).options[0].text = "";
			document.getElementById(secondary).options[0].value = "";
		}
	}
	changeStateKeyWords();
	if (setSubIndex) {
		selectDropDownIndex(secondary, setSubIndex);
	}
}

// This function handles showing/hiding the literary agency details on the registration form.
// Behaves simmilar to the menu hide/show functions.
function handleLitChange() {
	curState = document.getElementById("selectLitAgent").options[document.getElementById("selectLitAgent").selectedIndex].value;
    var el_results = document.getElementById('lit_agent_results');
	if (curState == "lit_agent_false") {
		showHide("litAgency_true", "hide");
		showHide("litAgency_false", "show");
        el_results.innerHTML = "<img src='../images/valid_input.png' width='15' height='15' />";
	} else if (curState == "lit_agent_true") {
		showHide("litAgency_true", "show");
		showHide("litAgency_false", "hide");
        el_results.innerHTML = "<img src='../images/valid_input.png' width='15' height='15' />";
	} else {
		showHide("litAgency_true", "hide");
		showHide("litAgency_false", "hide");
        el_results.innerHTML = "<img src='../images/invalid_input.png' width='15' height='15' />";
	}
}

function showHide(id, state) {
	if (state == "hide") {
		document.getElementById(id).style.display = "none";
	} else {
		document.getElementById(id).style.display = "block";
	}
}

function echoWorkTypeString(id) {
	for (i in workType_lkup) {
		//alert("id :: " + id + ", value :: " + workType_lkup[i]['value']);
		if (workType_lkup[i]['value'] == id) {
			//alert(workType_lkup[i]['title']);
			return workType_lkup[i]['title'];
		}
	}	
}

///////////////////////
//  functions to handle listview
///////////////////////
var checkCount = 0;
function listViewClickHandler(args) {
	checkCount += (args) ? 1 : -1;
	document.getElementById("btnDelete").disabled = (checkCount > 0) ? false : true;
	document.getElementById("btnRenew").disabled = (checkCount > 0) ? false : true;
}


// JavaScript VAR_DUMP Implementation
function jsVarDump(jsObject) {
   if(typeof jsObject == "object") {
      return "Type: "+typeof(jsObject)+((jsObject.constructor) ? "\nConstructor: "+jsObject.constructor : "")+"\nValue: " + jsObject;
   } else {
      return "Type: "+typeof(jsObject)+"\nValue: "+jsObject;
   }
}

function setTypeDisplay()
{
    var el_worktype = document.getElementById('lkup_worktype');
    var el_name = el_worktype.options[el_worktype.selectedIndex].innerHTML;
    window.location = "index.php?lkup_worktype=" + el_worktype.value + "&lkup_worktype_name=" + el_name;
    
}

function toggleDisplay(id)
{
    el = document.getElementById(id);
    if( el )
    {
        if( el.style.display == 'none' )
        {
            el.style.display = 'block';
        }else{
            el.style.display = 'none';
        }
    }
}
//toggles the search div in 'Search Manuscripts"
function display_search()
{
    var el_search = document.getElementById('search_database');
    var el_search_text = document.getElementById('search_database_text'); 
    var el_display_search = document.getElementById('display_search');
    
    if( el_search.style.display == "none" )
    {
        el_search.style.display = "block";
        el_search_text.innerHTML = "<a href=\"javascript:display_search()\"><strong>Click Here to Hide Search Options</strong></a>";
    }else{
        el_search.style.display = "none";
        el_search_text.innerHTML = "<a href=\"javascript:display_search()\"><strong>Click Here for a New Search</strong></a>";
    }  
    el_display_search.value = el_search.style.display;
    
}

function paginate_navigate(get_string)
{
    //var el_display_search = document.getElementById('display_search');
    
    window.location = "index.php?" + get_string // + "&display_search=" + el_display_search.value;
}   
