function setQsize(){
	if ( navigator.userAgent.match(/MSIE/) )
		document.getElementById('q').size = 36;
	if ( navigator.userAgent.match(/Chrome/) )
		document.getElementById('q').size = 35;
}

function checkSearch() {
	if ( document.getElementById('q').value.length < 3 && document.getElementById('browsestate').options[document.getElementById('browsestate').selectedIndex].value == 'ALL' && document.getElementById('browsearchive').options[document.getElementById('browsestate').selectedIndex].value == 'ALL' ) {
		alert("Please narrow down your search by either:\n\nTyping three or more characters in the text box -or-\nSelecting a particular State, County, or Archive to browse.\n");
	} else {
		document.getElementById('stateSelect').submit();
	}
}

function getAjax(){
	var request = false;
	
	try {
		request = new XMLHttpRequest();
	} catch (trymicrosoft) {
		try {
			request = new ActiveXObject("Msxml2.XMLHTTP");
	  	} catch (othermicrosoft) {
			try {
		  		request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (failed) {
		  		request = false;
			}
	  	}
	}
	
	if (!request)
	  alert("Error initializing XMLHttpRequest!")
	  
	return request;
}

function updateCounties() {
	read = getAjax();
	
	var url = "index.php?t=counties&state=" + document.getElementById('browsestate').options[document.getElementById('browsestate').selectedIndex].value + "&type=browse&rand=" + Math.random();

	read.open('GET', url, true);
	read.onreadystatechange = readData_cb;
  	read.send(null);
}

function readData_cb() {
	if ( read.readyState == 4 ) {
		document.getElementById('countydiv').innerHTML = read.responseText;
		updateArchive();
	}
}

function updateCountiesContribute() {
	read = getAjax();
	
	var url = "index.php?t=counties&state=" + document.getElementById('pickState').options[document.getElementById('pickState').selectedIndex].value + "&type=contrib&rand=" + Math.random();

	read.open('GET', url, true);
	read.onreadystatechange = readData_contribute;
  	read.send(null);
}

function readData_contribute() {
	if ( read.readyState == 4 ) {
		document.getElementById('countydiv').innerHTML = read.responseText;
		updateArchive();
	}
}

function addCounty() {
	if ( document.getElementById('pickCounty').options[document.getElementById('pickCounty').selectedIndex].value == "ALL" ) {
		alert("Please select a specific county or choose State Archives.");
		return;
	}
	
	for ( var x = 0; x < counties.length; x++ ) {
		if ( document.getElementById('pickCounty').options[document.getElementById('pickCounty').selectedIndex].value == counties[x] ) {
			alert("That county has already been added!");
			return;
		}
	}
	
	counties[countyCount] = document.getElementById('pickCounty').options[document.getElementById('pickCounty').selectedIndex].value;
	
	document.getElementById('Counties').value = serialize(counties);

	document.getElementById('listcounties').innerHTML = document.getElementById('listcounties').innerHTML.substring(0,document.getElementById('listcounties').innerHTML.length-4);
	document.getElementById('listcounties').innerHTML += "<font style='font-size: 12px; font-weight: bold; font-family: Courier New, Times New Roman;'>" + document.getElementById('pickState').options[document.getElementById('pickState').selectedIndex].text + " - " + document.getElementById('pickCounty').options[document.getElementById('pickCounty').selectedIndex].text + "</font> (<a href='javascript:deleteCounty(" + countyCount + ");' style='font-size: 12px; font-weight: bold; font-family: Courier New, Times New Roman;'>DELETE</a>)<br><br>";
	countyCount++;
}

function deleteCounty(num) {
	counties.splice(num,1);
	countyCount--;
	
	document.getElementById('Counties').value = serialize(counties);
	
	var re = new RegExp("<font[^\\(]+\\([^\\(]+\\(" + num + "\\)[^>]+>[^>]+>[^>]+>");
		
	document.getElementById('listcounties').innerHTML = document.getElementById('listcounties').innerHTML.replace(re,"");
	
	for ( var x = num; x < counties.length + 1; x++ )
		document.getElementById('listcounties').innerHTML = document.getElementById('listcounties').innerHTML.replace("(" + x + ")","(" + (x - 1) + ")");
	
	if ( countyCount == 0 )
		document.getElementById('listcounties').innerHTML = '';
}

function fixArchiveDiv() {
	var winW = 630, winH = 460;
	var ads = document.getElementById('addArchiveDiv').style;

	winW = document.documentElement.clientWidth;
	winH = document.documentElement.clientHeight;

	ads.top = (winH - 200) / 2;
	ads.left = (winW - 350) / 2;
	ads.height = 200;
	ads.width = 350;
}

function addArchive() {
	arch = getAjax();
	
	var url = "index.php?t=addArchive&q=" + document.getElementById('newArchive').value + "&l=" + document.getElementById('newLocation').value + "&rand=" + Math.random();

	arch.open('GET', url, true);
	arch.onreadystatechange = addArchive_cb;
  	arch.send(null);
}

function addArchive_cb() {
	if ( arch.readyState == 4 ) {
		if ( arch.responseText == "BAD" ) {
			alert("There is already an archive with that name!\nPlease try again.");
			return;
		}
		
		arch = getAjax();
		
		var url = "index.php?t=getArchive&rand=" + Math.random();
	
		arch.open('GET', url, true);
		arch.onreadystatechange = getArchive_cb;
		arch.send(null);
	}
}

function getArchive_cb() {
	if ( arch.readyState == 4 ) {
		document.getElementById('archiveList').innerHTML = arch.responseText;
		alert("Archive added successfully.");
		document.getElementById('newArchive').value = '';
		document.getElementById('newLocation').value = '';
		document.getElementById('addArchiveDiv').style.display = 'none';
	}
}

function updateArchive() {	
	if ( document.getElementById('browsecounty') ) {
		arch = getAjax();

		var url = "index.php?t=archives&county=" + document.getElementById('browsecounty').options[document.getElementById('browsecounty').selectedIndex].value + "&state=" + document.getElementById('browsestate').options[document.getElementById('browsestate').selectedIndex].value + "&rand=" + Math.random();
	
		arch.open('GET', url, true);
		arch.onreadystatechange = readArchive_cb;
		arch.send(null);
	}
}

function readArchive_cb() {
	if ( arch.readyState == 4 ) {
		document.getElementById('archivediv').innerHTML = arch.responseText;
		if ( document.getElementById('mainSearchButton') )
			document.getElementById('mainSearchButton').disabled = false;
	}
}

var Base64 = {
 
	// private property
	_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
 
	// public method for encoding
	encode : function (input) {
		var output = "";
		var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
		var i = 0;
 
		input = Base64._utf8_encode(input);
 
		while (i < input.length) {
 
			chr1 = input.charCodeAt(i++);
			chr2 = input.charCodeAt(i++);
			chr3 = input.charCodeAt(i++);
 
			enc1 = chr1 >> 2;
			enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
			enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
			enc4 = chr3 & 63;
 
			if (isNaN(chr2)) {
				enc3 = enc4 = 64;
			} else if (isNaN(chr3)) {
				enc4 = 64;
			}
 
			output = output +
			this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
			this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
 
		}
 
		return output;
	},
 
	// public method for decoding
	decode : function (input) {
		var output = "";
		var chr1, chr2, chr3;
		var enc1, enc2, enc3, enc4;
		var i = 0;
 
		input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
 
		while (i < input.length) {
 
			enc1 = this._keyStr.indexOf(input.charAt(i++));
			enc2 = this._keyStr.indexOf(input.charAt(i++));
			enc3 = this._keyStr.indexOf(input.charAt(i++));
			enc4 = this._keyStr.indexOf(input.charAt(i++));
 
			chr1 = (enc1 << 2) | (enc2 >> 4);
			chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
			chr3 = ((enc3 & 3) << 6) | enc4;
 
			output = output + String.fromCharCode(chr1);
 
			if (enc3 != 64) {
				output = output + String.fromCharCode(chr2);
			}
			if (enc4 != 64) {
				output = output + String.fromCharCode(chr3);
			}
 
		}
 
		output = Base64._utf8_decode(output);
 
		return output;
 
	},
 
	// private method for UTF-8 encoding
	_utf8_encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";
 
		for (var n = 0; n < string.length; n++) {
 
			var c = string.charCodeAt(n);
 
			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}
 
		}
 
		return utftext;
	},
 
	// private method for UTF-8 decoding
	_utf8_decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;
 
		while ( i < utftext.length ) {
 
			c = utftext.charCodeAt(i);
 
			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}
 
		}
 
		return string;
	}
 
}

function serialize (mixed_value) {
    // Returns a string representation of variable (which can later be unserialized)  
    // 
    // version: 1006.1915
    // discuss at: http://phpjs.org/functions/serialize
    // +   original by: Arpad Ray (mailto:arpad@php.net)
    // +   improved by: Dino
    // +   bugfixed by: Andrej Pavlovic
    // +   bugfixed by: Garagoth
    // +      input by: DtTvB (http://dt.in.th/2008-09-16.string-length-in-bytes.html)
    // +   bugfixed by: Russell Walker (http://www.nbill.co.uk/)
    // +   bugfixed by: Jamie Beck (http://www.terabit.ca/)
    // +      input by: Martin (http://www.erlenwiese.de/)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // -    depends on: utf8_encode
    // %          note: We feel the main purpose of this function should be to ease the transport of data between php & js
    // %          note: Aiming for PHP-compatibility, we have to translate objects to arrays
    // *     example 1: serialize(['Kevin', 'van', 'Zonneveld']);
    // *     returns 1: 'a:3:{i:0;s:5:"Kevin";i:1;s:3:"van";i:2;s:9:"Zonneveld";}'
    // *     example 2: serialize({firstName: 'Kevin', midName: 'van', surName: 'Zonneveld'});
    // *     returns 2: 'a:3:{s:9:"firstName";s:5:"Kevin";s:7:"midName";s:3:"van";s:7:"surName";s:9:"Zonneveld";}'
    var _getType = function (inp) {
        var type = typeof inp, match;
        var key;
        if (type == 'object' && !inp) {
            return 'null';
        }
        if (type == "object") {
            if (!inp.constructor) {
                return 'object';
            }
            var cons = inp.constructor.toString();
            match = cons.match(/(\w+)\(/);
            if (match) {
                cons = match[1].toLowerCase();
            }
            var types = ["boolean", "number", "string", "array"];
            for (key in types) {
                if (cons == types[key]) {
                    type = types[key];
                    break;
                }
            }
        }
        return type;
    };
    var type = _getType(mixed_value);
    var val, ktype = '';
    
    switch (type) {
        case "function": 
            val = ""; 
            break;
        case "boolean":
            val = "b:" + (mixed_value ? "1" : "0");
            break;
        case "number":
            val = (Math.round(mixed_value) == mixed_value ? "i" : "d") + ":" + mixed_value;
            break;
        case "string":
            mixed_value = Base64._utf8_encode(mixed_value);
            val = "s:" + encodeURIComponent(mixed_value).replace(/%../g, 'x').length + ":\"" + mixed_value + "\"";
            break;
        case "array":
        case "object":
            val = "a";
            /*
            if (type == "object") {
                var objname = mixed_value.constructor.toString().match(/(\w+)\(\)/);
                if (objname == undefined) {
                    return;
                }
                objname[1] = this.serialize(objname[1]);
                val = "O" + objname[1].substring(1, objname[1].length - 1);
            }
            */
            var count = 0;
            var vals = "";
            var okey;
            var key;
            for (key in mixed_value) {
                ktype = _getType(mixed_value[key]);
                if (ktype == "function") { 
                    continue; 
                }
                
                okey = (key.match(/^[0-9]+$/) ? parseInt(key, 10) : key);
                vals += this.serialize(okey) +
                        this.serialize(mixed_value[key]);
                count++;
            }
            val += ":" + count + ":{" + vals + "}";
            break;
        case "undefined": // Fall-through
        default: // if the JS object has a property which contains a null value, the string cannot be unserialized by PHP
            val = "N";
            break;
    }
    if (type != "object" && type != "array") {
        val += ";";
    }

    return val;
}
