var hiddenAsText = false;
var lastDefId = null;
var have_ids = null;
var share_jh = null;
var OW = 0;
try { share_jh = new jayhawk('sharepage_jayhawk.php', true); } catch (ex) { }
var general_jh = null;
try { general_jh = new jayhawk('general_jayhawk.php', true); } catch (ex) { }

function shareThis() {
	//window.alert(current_page);
	var msg = 'PHAgc3R5bGU9J3dpZHRoOjQwMHB4Jz5Zb3UgY2FuIGVtYWlsIHRoaXMgcGFnZSB0byBzb21lb25lIHlvdSBrbm93LiBKdXN0IHN1cHBseSB5b3VyIG5hbWUgYW5kIHRoZWlyIGVtYWlsIGFkZHJlc3MuDQo8L3A+DQo8dGFibGU+DQoJPHRyPg0KCQk8dGQ+PGI+WW91ciBOYW1lOjwvYj4gPC90ZD4NCgkJPHRkPjxpbnB1dCB0eXBlPSd0ZXh0JyBuYW1lPSdzaGFyZXJfbmFtZScgaWQ9J3NoYXJlcl9uYW1lJyBzaXplPScyNicgLz48L3RkPg0KCTwvdHI+DQoJPHRyPg0KCQk8dGQgdmFsaWduPSd0b3AnPjxiPkZyaWVuZCdzIEVtYWlsOjwvYj48L3RkPg0KCQk8dGQ+PGlucHV0IHR5cGU9J3RleHQnIG5hbWU9J2VtYWlsX2xpc3QnIGlkPSdlbWFpbF9saXN0JyBzaXplPScyNicgLz48L3RkPg0KCTwvdHI+DQoJPHRyPg0KCQk8dGQgdmFsaWduPSd0b3AnPjxiPk1lc3NhZ2U6PC9iPjwvdGQ+DQoJCTx0ZD48dGV4dGFyZWEgaWQ9J3NoYXJlX21zZycgY29scz0nMzAnIHJvd3M9JzQnPjwvdGV4dGFyZWE+PC90ZD4NCgk8L3RyPg0KCTx0cj4NCgkJPHRkIGNvbHNwYW49JzInIGFsaWduPSdjZW50ZXInPjxici8+PGlucHV0IG9uY2xpY2s9J3NoYXJlVGhpc19zZW5kKCknIHR5cGU9J2J1dHRvbicgbmFtZT0nc2VuZF9zaGFyZScgaWQ9J3NlbmRfc2hhcmUnIHZhbHVlPSdTZW5kJyAvPiZuYnNwOyZuYnNwOyZuYnNwOzxpbnB1dCBvbmNsaWNrPSdzaGFyZVRoaXNfY2FuY2VsKCknICB0eXBlPSdidXR0b24nIGlkPSdjYW5jZWxfc2hhcmUnIG5hbWU9J2NhbmNlbF9zaGFyZScgdmFsdWU9J0NhbmNlbCcgLz4NCgk8L3RyPg0KPC90YWJsZT4=';
	fakePopUp('sharing_is_good',decode64(msg) ,'#4D618B','white',280,425,'deadcenter',null,false,3,'Email This Page');
	
}

function shareThis_done(errs) {
	shareThis_close()
	//doToggle('sharing_is_good');
	window.alert(errs);
}

function addIds(parent_id) {
	var p = document.getElementById(parent_id);
	var child_count = p.childNodes.length;
	var children = p.childNodes;
	
	for (var i=0; i < child_count;i++) {
		var tmp = children[i];
		if ( tmp.name != null && tmp.name.length > 0 && tmp.id.length == 0 ) {
			tmp.id = tmp.name;  
		}
	}
}

function shareThis_send() {	
	
	var current_page = window.location.href;
	var sender_name = document.getElementById('sharer_name_cloned');
	var email_list = document.getElementById('email_list_cloned');
	var share_msg = document.getElementById('share_msg_cloned');
	
	if ( sender_name.value.length > 0 && email_list.value.length > 0 && share_msg.value.length > 0 ) {
		//go do sent
		var email_list_new = email_list.value;
		//email_list_new = email_list_new.replace(/@/g, "+");
		share_jh.call_php_function('share_page',current_page,sender_name.value,email_list_new,share_msg.value);
		//share_page($page_url,$from_name,$email_list,$msg)
	} else {
		window.alert('Please complete the form.')
	}
}

function shareThis_cancel() {
	var sender_name = document.getElementById('sharer_name_cloned');
	var email_list = document.getElementById('email_list_cloned');
	var share_msg = document.getElementById('share_msg_cloned');
	
	if ( sender_name.value.length > 0 || email_list.value.length > 0 || share_msg.value.length > 0 ) {
		if ( window.confirm("Click OK to cancel your message.\n\nYou will lose what you have typed so far") ) {
			shareThis_close();
		}
	} else { //haven't filled anything out so we can cancel with out them like totally freaking out ! OMG!
		shareThis_close();
	}
	
}

function shareThis_close() {
	box.close($('fakepopup_links_share_this'));
}



function checkStateChange(stFld,otherHolderId) {
	if ( stFld.value=='ZZ' ) { //ZZ is the abbrev for Other
		document.getElementById(otherHolderId).style.display='block';
	} else { 
		document.getElementById(otherHolderId).style.display='none';
	}
	
	if ( stFld.value=='MO' ) {
		// unhide school district list...
		document.getElementById('school_district').style.display = 'block';
		document.getElementById('sd_label').style.display = 'block';
	} else {
		document.getElementById('school_district').style.display = 'none';
		document.getElementById('sd_label').style.display = 'none';
	}
	
}

function escapeReplace(str) {
	if ( str == null) return
	return str.replace(/%26/g,'&').replace(/%27/g,"'").replace(/%09/g,"\t").replace(/%0A/g,"\n").replace(/%22/g,'"');
}

function getCheckedValue(radioObj) {
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}

function openWindow(url, width, height) {
	window.open(url, "solution" + (++OW),
		"width="+width+",height="+height+",location=0,menubar=1,resizable=1,scrollbars=1,status=0,titlebar=0,toolbar=0"
	);
}

function createInput(type,name,id,checked) {
	if (hiddenAsText && type == "hidden")
		type = "text";
	var elm;
	if (id == null)
		id = name;
	if (checked == null)
		checked = false;
	if (type == "select") {
		try {
			elm = document.createElement('<select name="' + name + '" id="' + id + '">');
		} catch (e) { }
		if (!elm || elm.nodeName != type.toUpperCase()) {
			elm = document.createElement('select');
			elm.name = name;
			elm.id = id;
		}
	} else if (type == "textarea") {
		try {
			elm = document.createElement('<textarea name="' + name + '" id="' + id + '">');
		} catch (e) { }
		if (!elm || elm.nodeName != type.toUpperCase()) {
			elm = document.createElement('textarea');
			elm.name = name;
			elm.id = id;
		}
	} else {
		try {
			if (checked)
				elm = document.createElement('<input type="' + type + '" name="' + name + '" id="' + id + '" checked="checked">');
			else
				elm = document.createElement('<input type="' + type + '" name="' + name + '" id="' + id + '">');
		} catch (e) { }
		if (!elm || elm.nodeName != "INPUT") {
			elm = document.createElement('input');
			elm.type = type;
			elm.name = name;
			if (checked)
				elm.checked = true;
			elm.id = id;
		}
	}
	return elm;
}

function showShareWithOthers(uid) {
	var ta = document.getElementById('share_text' + uid);
	var dadiv = document.getElementById('share_div' + uid);
	dadiv.style.display = 'block';
	ta.focus();
}

function sendShareWithOthers(share_id,uid,user_id) {
	var ta = document.getElementById('share_text' + uid);
	var dadiv = document.getElementById('share_div' + uid);
	//alert(share_id + '|' + uid);
	var answer = ta.value;
	
	//do ajax junk
	ajax = new ajaxRequest;
	ajax.send("userside_ajax.php?action=shareSend", "share_id=" + share_id + "&user_id=" + user_id + "&answer=" + answer, "doneShareWithOthers", "'" + uid +"'") ;
}

function doneShareWithOthers(dom, uid) { //,uid) {
	var ta = document.getElementById('share_text' + uid);
	var dadiv = document.getElementById('share_div' + uid);
	ta.style.display = 'none';
	dadiv.style.color = 'green';
	dadiv.innerHTML = '<br/><br/><br/>Sent!';
}

function addEvent( obj, type, fn ) {
	if (obj.addEventListener) {
		obj.addEventListener( type, fn, false );
		EventCache.add(obj, type, fn);
	}
	else if (obj.attachEvent) {
		obj["e"+type+fn] = fn;
		obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
		obj.attachEvent( "on"+type, obj[type+fn] );
		EventCache.add(obj, type, fn);
	}
	else {
		obj["on"+type] = obj["e"+type+fn];
	}
}

var EventCache = function(){
	var listEvents = [];
	return {
		listEvents : listEvents,
		add : function(node, sEventName, fHandler){
			listEvents.push(arguments);
		},
		flush : function(){
			var i, item;
			for(i = listEvents.length - 1; i >= 0; i = i - 1){
				item = listEvents[i];
				if(item[0].removeEventListener){
					item[0].removeEventListener(item[1], item[2], item[3]);
				};
				if(item[1].substring(0, 2) != "on"){
					item[1] = "on" + item[1];
				};
				if(item[0].detachEvent){
					item[0].detachEvent(item[1], item[2]);
				};
				item[0][item[1]] = null;
			};
		}
	};
}();
addEvent(window,'unload',EventCache.flush);

function textCounter_old( field, maxlimit, countfield ) {
	if ( field.value.length > maxlimit ){
		field.value = field.value.substring( 0, maxlimit );
		alert( 'Textarea value can only be ' + maxlimit + ' characters in length. Current character amount is ' + field.value.length);
		return false;
	}
	else{
		dif = maxlimit - field.value.length;
		eval("document." + field.form.name + "." + countfield + ".value = " + dif);
	} 
  	return true;
}

function textCounter( field, maxlimit, countfieldid ) {
	if ( field.value.length > maxlimit ){
		field.value = field.value.substring( 0, maxlimit );
		alert( 'Textarea value can only be ' + maxlimit + ' characters in length. Current character amount is ' + field.value.length);
		return false;
	}
	else{
		dif = maxlimit - field.value.length;
		//eval("document." + field.form.name + "." + countfield + ".value = " + dif);
		document.getElementById(countfieldid).value = dif;
	} 
  	return true;
}

function getElementsByClass(searchClass,node,tag) {
	var classElements = new Array();
	if ( node == null )
		node = document;
	if ( tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}

function validateForm(form, userFunc) {
	var dontSubmit = false;
	var requireds = getElementsByClass("required");
	for (var i = 0; i < requireds.length; i++) {
		var elm = requireds[i];
		var found = false;
		var elmId = elm.id;
		var elmName = elmId.substring(0, elmId.lastIndexOf('_'));
		var names = document.getElementsByName(elmName);
		
		if (elm.className.indexOf("dependsonuserfunc") == -1) {
			for (var j = 0; j < names.length; j++) {
				if (names[j].type == "radio" || names[j].type == "checkbox") {
					if (names[j].checked)
						found = true;
				} else if (names[j].nodeName == "SELECT") {
					found = (names[j].value != "" && names[j].value != "-1");
				} else {
					found = (names[j].value != "");
				}
			}
		} else {
			found = true;
		}
		if (!found) {
			dontSubmit = true;
			requireds[i].style.color = "#f00";
		} else {
			requireds[i].style.color = "#000";
		}
	}
	if (userFunc != null) {
		var tempDont = eval(userFunc);
		dontSubmit = (dontSubmit || tempDont);
	}
	
	if (dontSubmit == true) {
		if (document.getElementById("form_error_msg"))
			document.getElementById("form_error_msg").style.display = "block";
		scroll(0,0);
		return false;
	}
	
	form.submitBtn.value = "Submitting...";
	form.submitBtn.disabled = true;
	return true;
}

function openPopup() {
	var newWindow = window.open(this.href, 'transco_popup', 'width=400,height=500,location=0,menubar=1,resizable=1,scrollbars=0,status=0,titlebar=0,toolbar=0');
	newWindow.focus();
	return false;
}

function openNewWindow() {
	var newWindow = window.open( this.href , 'transco_new_window');
	return false;
}


function changePopupLinks() {
	var links = document.getElementsByTagName("a");
	for (var i = 0; i < links.length; i++) {
		var link = links[i];
		if (link.rel == "pop") {
			link.onclick = openPopup;
		} else if (link.rel == "new") {
			//link.onclick = openNewWindow; //ie does not like this...
			link.target = '_blank';
		}
	}
}

var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

function encode64(input) {
   var output = "";
   var chr1, chr2, chr3;
   var enc1, enc2, enc3, enc4;
   var i = 0;

   do {
      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 + keyStr.charAt(enc1) + keyStr.charAt(enc2) + 
         keyStr.charAt(enc3) + keyStr.charAt(enc4);
   } while (i < input.length);
   
   return output;
}

function decode64(input) {
   var output = "";
   var chr1, chr2, chr3;
   var enc1, enc2, enc3, enc4;
   var i = 0;

   // remove all characters that are not A-Z, a-z, 0-9, +, /, or =
   input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

   do {
      enc1 = keyStr.indexOf(input.charAt(i++));
      enc2 = keyStr.indexOf(input.charAt(i++));
      enc3 = keyStr.indexOf(input.charAt(i++));
      enc4 = 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);
      }
   } while (i < input.length);

   return output;
}

function loadDefinition(defTitle, defText,defId) {
	var curDefId = 'definition' + defTitle;
	//this removes the last one created so that they don't double up/keep first def the whole time
	if ( lastDefId != null && lastDefId != curDefId ) {
		toggleOff(lastDefId);
	}
	
	//below can be added  to second argument to some print option
	//+ '<br/><br/><a target="_blank" href="print_def.php?def_id=' + defId + '\">Print</a>'
	
	fakePopUp(curDefId,decode64(defText) ,'#FFFFCC','black',null,500,'deadcenter',null,false,3,decode64(defTitle));
	lastDefId = curDefId;
	//+defTitle
	//return false;
}

function addCustomLink(link,link_text, fileId) {
	if (link == null)
		link = "";
	if (fileId == null)
		fileId = 0;
	doToggle("customadd",true);
	var customBox = "<form>";
	customBox += "<input type='hidden' name='custom_file_id' id='custom_file_id' value='" + fileId + "'/>";
	customBox += "Fill out this form and hit save to add this link to your My Library Custom Links section. By adding links to your library, you can quickly retrieve them at any time.";
	if (fileId == 0)
		customBox += "<div class='formwrapper'><div class='formlabel'>Link</div><div class='forminput'><input type='text' name='custom_link_href' id='custom_link_href' value='" + link + "'/></div></div>";
	customBox += "<div class='formwrapper'><div class='formlabel'>Text</div><div class='forminput'><input type='text' name='custom_text' id='custom_text'  value='" + link_text + "'/></div></div>";
	customBox += "<div class='formwrapper'><div class='formlabel'>Description</div><div class='forminput'><textarea name='custom_desc' id='custom_desc'></textarea></div></div>";
	customBox += "<div class='formwrapper'><div class='formlabel'></div><div class='forminput'><input type='button' value='Save Link' onclick='saveCustomLink();'/></div></div>";
	fakePopUp("customadd", customBox, '#ffffcc', 'black',300,500,'deadcenter',null,false,3,"Add Custom Link");
}

function saveCustomLink() {
	if (general_jh != null) {
		var linkHref = document.getElementById("custom_link_href").value;
		var fileId = document.getElementById("custom_file_id").value;
		var customText = document.getElementById("custom_text").value;
		var customDesc = document.getElementById("custom_desc").value;

                if ( linkHref.length == 0 || customText.length == 0 ) {
                    window.alert('Title and Link are required.');
                } else if ( customDesc.length > 50  ) {
                    window.alert("Please limit your description to 50 characters. Currently " + customDesc.length + " characters")
                } else {
                    if ( customDesc.length == 0  ) {
                        customDesc = 'none provided.';
                    }
                    general_jh.call_php_function('add_custom_link', linkHref, fileId, customText, customDesc);
                }
	}
}

function saveCustomLink_done(linkId, linkHref, fileId, customText, customDesc) {
	if (window.location.href.indexOf("my_library.php") != -1) {
		var ulElm = document.getElementById("usersection_custom");
		var liElm = document.createElement("li");
		liElm.id = "customlinkrow_" + linkId;
		var aElm = document.createElement("a");
		aElm.href = linkHref;
		aElm.rel = "new";
		aElm.className = "library_link";
		aElm.appendChild(document.createTextNode(customText));
		liElm.appendChild(aElm);
		var spanElm = document.createElement("span");
		spanElm.className = "library_button";
		aElm = document.createElement("a");
		aElm.href = "javascript: removeCustomFromLibrary('" + linkId + "');";
		var imgElm = document.createElement("img");
		imgElm.src = "images/icons/x.gif";
		imgElm.alt = "Remove From Library";
		imgElm.title = "Remove From Library";
		aElm.appendChild(imgElm);
		spanElm.appendChild(aElm);
		liElm.appendChild(spanElm);
		var divElm = document.createElement("div");
		divElm.setAttribute("style", "clear: both");
		liElm.appendChild(divElm);
		if (customDesc != '') {
			var pElm = document.createElement("p");
			pElm.className = "link_desc";
			pElm.appendChild(document.createTextNode(customDesc));
			liElm.appendChild(pElm);
		}
		ulElm.appendChild(liElm);
	}

	doToggle("customadd",true);
	fakePopUp("customadd", "Your custom link has been successfully added to your library.", '#ffffcc', 'black',null,300,'deadcenter',null,true,5,"Link Saved");
}

function fixHover() {
	if (document.all && document.getElementById) {
		/*var navRoot = document.getElementById("topnavul");
		liNodes = navRoot.getElementsByTagName('li');
		for (var i=0; i<liNodes.length; i++) {
			var node = liNodes[i];
			addEvent(node, 'mouseover', function() { this.className += ' over'; });
			addEvent(node, 'mouseout', function() { this.className=this.className.replace(' over', '');	});
		}*/
		var navLis = getElementsByClass('nav_row');
		for (var i=0; i<navLis.length; i++) {
			var node = navLis[i];
			addEvent(node, 'mouseover', function() { this.className += ' over'; });
			addEvent(node, 'mouseout', function() { this.className=this.className.replace(' over', '');	});
		}
	}
}

function activateTopNav() {
	if (document.all && document.getElementById && typeof document.body.style.maxHeight == "undefined") { // remove if new nav breaks
	var navRoot = document.getElementById("topnavul");
	liNodes = navRoot.getElementsByTagName('li');
	for (var i=0; i<liNodes.length; i++) {
		var node = liNodes[i];
		//if (node.className != 'topnav_piece' && node.childNodes.length != 0 && node.childNodes[0].nodeName == "A") {
			//addEvent(node, 'click', function() { window.location.href = this.childNodes[0].href; } );
		//} else if (node.className == 'topnav_piece' && node.id == active_topnav) {
//			node.childNodes[0].className += " active";
		//}
		//if (document.all && document.getElementById && typeof document.body.style.maxHeight == "undefined") {
			if (node.className == "topnav_piece") {
				addEvent(node, 'click', function() { doIEClicks(this.id); });
			} else {
				addEvent(node, 'mouseover', function() { this.className += ' over'; });
				addEvent(node, 'mouseout', function() { this.className = this.className.replace(' over', ''); });
			}
		}
	}
}

function doIEClicks(elmId, forceHide) {
	var elm = document.getElementById(elmId);
	if (elm.className.indexOf('over') == -1 && (forceHide == null || !forceHide)) {
		var allTabs = getElementsByClass('topnav_piece');
		for (var i = 0; i < allTabs.length; i++) {
			allTabs[i].className = allTabs[i].className.replace(' over', '');
		}
		elm.className += ' over';
		setTimeout("doIEClicks('" + elm.id + "',true)",4000);
	} else {
		elm.className = elm.className.replace(' over', '');
	}
}

function colorAndActivateLeftNav() {
	var groups = Array('main_nav', 'links_nav', 'portfolio_nav');
	for (var groupId = 0; groupId < groups.length; groupId++) {
		var group = document.getElementById(groups[groupId]);
		if (group) {
			var style = "light";
			for (var navId = 0; navId < group.childNodes.length; navId++) {
				var navRow = group.childNodes[navId];
				if (navRow.nodeName == "DIV") {
					if (navRow.className.indexOf('nav_row') != -1 && navRow.className.indexOf('nav_light') == -1 && navRow.className.indexOf('nav_light') == -1) {
						if (navRow.style.display != "none") {
							navRow.className += " nav_" + style;
							if (style == "light")
								style = "dark";
							else
								style = "light";
						}
						//if (navRow.getElementsByTagName('a').length > 0)
							//addEvent(navRow, 'click', function() { window.location.href = this.getElementsByTagName('a')[0].href; } );
					}
				}
			}
		}
	}
}

function init() {
	changePopupLinks();
	fixHover();
	activateTopNav();
	colorAndActivateLeftNav();
	var helps = getElementsByClass("help");
	for (var i = 0; i < helps.length; i++) {
		var elm = helps[i];
		addEvent(elm, "click", function() { getHelp(this); });
		elm.src = "../images/icons/help.png";
		elm.style.cursor = 'pointer';
	}
	var logo = document.getElementById('logo');
	if (logo != null)
		addEvent(logo,'click', function() { window.location.href = home_rel_link + "index.php"; } );
	if (active_nav != "" && document.getElementById(active_nav)) {
		document.getElementById(active_nav).className += " nav_active";	
	}
	if ( String(window.location).indexOf('admin') == -1) {
		setUpMultiBox();
	}
	return;
}

function confirmTranscertDelete(a) {
	var doDelete = window.confirm("Are you sure you want to delete this file?");
	
	if ( doDelete ) {
		window.location.href = 'delete_file.php?upload_id=' + a;
	}	
}
