//////////////////////////////////////////////////////
// GLOBAL VARIABLES
//////////////////////////////////////////////////////

var copystartverse = 0;
var copyendverse = 100000;


//////////////////////////////////////////////////////
// CUSTOM EVENTS
//////////////////////////////////////////////////////

Element.Events.keyenter = {
	base: 'keyup',
	condition: function(e){
		// We can basically put any logic here.
		// In this example we return true, when the pressed key is the
		// Enter-Button so the keyenter event gets fired.
		return e.key=='enter';
	}
};



//////////////////////////////////////////////////////
// WINDOW EVENTS
//////////////////////////////////////////////////////

window.addEvent('domready', function(){

	if ($('bible_searchbox'))
	{
		$('bible_searchbox').addEvent('keyenter', function(e){
			location.href='/salt_searcher_results.php?q=' + $('bible_searchbox').value;
		});
	}

	if ($('bible_searchbox_sm'))
	{
		$('bible_searchbox_sm').addEvent('keyenter', function(e){
			location.href='/salt_searcher_results.php?q=' + $('bible_searchbox_sm').value;
		});
	}
	
});



//////////////////////////////////////////////////////
// GENERAL FUNCTIONS
//////////////////////////////////////////////////////

function URLEncode(clearString) {
	var output = '';
	if (!clearString) return '';
	var x = 0;
	clearString = clearString.toString();
	var regex = /(^[a-zA-Z0-9_.]*)/;
	while (x < clearString.length) {
	var match = regex.exec(clearString.substr(x));
	if (match != null && match.length > 1 && match[1] != '') {
		output += match[1];
	  x += match[1].length;
	} else {
	  if (clearString[x] == ' ')
		output += '+';
	  else {
		var charCode = clearString.charCodeAt(x);
		var hexVal = charCode.toString(16);
		output += '%' + ( hexVal.length < 2 ? '0' : '' ) + hexVal.toUpperCase();
	  }
	  x++;
	}
	}
	return output;
}

function URLDecode(encodedString) {
  var output = encodedString;
  var binVal, thisString;
  var myregexp = /(%[^%]{2})/;
  while ((match = myregexp.exec(output)) != null
             && match.length > 1
             && match[1] != '') {
    binVal = parseInt(match[1].substr(1),16);
    thisString = String.fromCharCode(binVal);
    output = output.replace(match[1], thisString);
  }
  return output;
}


//////////////////////////////////////////////////////
// BIBLE FUNCTIONS
//////////////////////////////////////////////////////

function switchBible(bv) {

    var xml = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
    var qstring = "action=switchBible&bv=" + bv;
    xml.open('POST', 'ajax.php', true);
    xml.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xml.onreadystatechange = function()
    {
    	if (xml.readyState == 4) {
	    	var rtext = xml.responseText;
			if (rtext == "done") {
				ccHideModalWindow();
				showContext();
			}
			else {
				alert("There was a problem.");
			}
    	}
    }
    xml.send(qstring)

}

function setCopyPoint(vnum) {

	var backel = "copytext" + vnum;
	var boxel = "cbox" + vnum;

	if (copystartverse == 0 && copyendverse != vnum) {
		if (vnum > copyendverse) {
		    copystartverse = copyendverse;
		    copyendverse = vnum;
		} else {
			copystartverse = vnum;
		}
		$(backel).set('class', 'bverseline mozrounded bcopyhilight');
		$(backel).onclick = function() {copyVerses()}
		$(backel).style.cursor = "pointer";
		$(boxel).checked = true;
	}
	else if (copyendverse == 100000 && copystartverse != vnum) {
		if (vnum < copystartverse) {
		    copyendverse = copystartverse;
		    copystartverse = vnum;
		} else {
			copyendverse = vnum;
		}
		$(backel).set('class', 'bverseline mozrounded bcopyhilight');
		$(backel).onclick = function() {copyVerses()}
		$(backel).style.cursor = "pointer";
		$(boxel).checked = true;
	}
	else if (copyendverse == vnum) {
		fillCopyIcons("blank", copystartverse, copyendverse);
		copyendverse = 100000;
		$(backel).set('class', 'bverseline mozrounded');
		$(backel).onclick = null;
		$(backel).style.cursor = null;
		$(boxel).checked = false;
	}
	else if (copystartverse == vnum) {
		fillCopyIcons("blank", copystartverse, copyendverse);
		copystartverse = 0;
		$(backel).set('class', 'bverseline mozrounded');
 		$(backel).onclick = null;
 		$(backel).style.cursor = null;
		$(boxel).checked = false;
		}
	// if click outside of selected boxes then clear the selection
	else if ((vnum < copystartverse || vnum > copyendverse) && (copyendverse != 100000 && copystartverse != 0)) {
		clearCopyIcons();
		$(boxel).checked = false;
	}

	if (copystartverse != 0 && copyendverse != 100000) {

		fillCopyIcons("fill", copystartverse, copyendverse);

	}

}

function fillCopyIcons(iname, fillstart, fillend) {

	if (fillstart != 0 && fillend != 100000) {

		if (fillend - fillstart > 1) {

			var fillstart = fillstart + 1;
			var fillend = fillend - 1;

			for (x=fillstart;x<=fillend;x++) {
				bel = "copytext" + x;
				box = "cbox" + x;
				if (iname == "blank") {
					$(bel).set('class', 'bverseline mozrounded');
					$(bel).onclick = null;
					$(bel).style.cursor = null;
					$(box).checked = false;
				} else {
				    $(bel).set('class', 'bverseline mozrounded bcopyhilight');
				    $(bel).onclick = function() {copyVerses()}
				    $(bel).style.cursor = "pointer";
					$(box).checked = true;
				}
			}

		}

	}

}

function clearCopyIcons() {

	var backelone = "copytext" + copystartverse;
	var backeltwo = "copytext" + copyendverse;

	var boxelone = "cbox" + copystartverse;
	var boxeltwo = "cbox" + copyendverse;

	fillCopyIcons("blank", copystartverse, copyendverse);
	copystartverse = 0;
	copyendverse = 100000;

	if ($(backelone)) {
		$(backelone).set('class', 'bverseline mozrounded');
		$(backelone).onclick = null;
		$(backelone).style.cursor = null;
		$(boxelone).checked = false;
	}

	if ($(backeltwo)) {
		$(backeltwo).set('class', 'bverseline mozrounded');
		$(backeltwo).onclick = null;
		$(backeltwo).style.cursor = null;
		$(boxeltwo).checked = false;
	}

}

function copyVerses() {

	if (copystartverse != 0) {

		var bid = $('hidden_bookID').value;
		var cid = $('hidden_chapter').value;

		var xml = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
		var qstring = "action=copyVerses&bookID=" + bid + "&chapter=" + cid + "&startverse=" + copystartverse + "&endverse=" + copyendverse;
		xml.open('POST', 'ajax.php', true);
		xml.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		xml.onreadystatechange = function()
		{
			if (xml.readyState == 4) {
				var rtext = xml.responseText;
				if (rtext != "") {
					ccShowModalWindow("Copy Verses", rtext, 500);
					selectall = function() { $('copybox').focus(); $('copybox').select(); };
					selectall.delay(500);
				}
			}
		}
		xml.send(qstring)

	}
	else {
		alert('Use the checkboxes to select some verses first.');
	}

}

function setCopyStyle(cstyle) {

    var xml = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
    var qstring = "action=setCopyStyle&cstyle=" + escape(cstyle);
    xml.open('POST', 'ajax.php', true);
    xml.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xml.onreadystatechange = function()
    {
    	if (xml.readyState == 4) {
	    	var rtext = xml.responseText;
			if (rtext != "") {
//				alert(rtext);
			}
			else {
				alert("There was a problem.");
			}
    	}
    }
    xml.send(qstring)

}

function toggleChapters(bookid) {

	var bookel = "book_" + bookid;
	var titlel = "title_" + bookid;
	var iconel = "bookicon_" + bookid;

	var thebook = $(bookel);
	var thetitle = $(titlel);
	var theicon = $(iconel);

	if (thebook.style.display == 'none') {
		thebook.style.display = 'block';
		thetitle.style.fontWeight = 'bold';
		theicon.src = 'images/_collapse.png';

	    var xml = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
	    var qstring = "action=showChapterList&bookID=" + bookid;
	    xml.open('POST', 'ajax.php', true);
	    xml.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	    xml.onreadystatechange = function()
	    {
	    	if (xml.readyState == 4) {
		    	var rtext = xml.responseText;
				if (rtext != "") {
					thebook.innerHTML = rtext;
				}
	    	}
	    }
	    xml.send(qstring)

	}
	else {
		thebook.style.display = 'none';
		thebook.innerHTML = null;
		thetitle.style.fontWeight = 'normal';
		theicon.src = 'images/_expand.png';
	}

}

function clearSearch() {

    var xml = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
    var qstring = "action=clearSearch";
    xml.open('POST', 'ajax.php', true);
    xml.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xml.onreadystatechange = function()
    {
    	if (xml.readyState == 4) {
	    	var rtext = xml.responseText;
			if (rtext != "") {
				if ($('search_container')) $('search_container').style.display = 'none';
				$('searchlimit').selectedIndex = 0;
				$('searchtype').selectedIndex = 0;
			}
    	}
    }
    xml.send(qstring)

}

function showContext(bookID, chapter, verse) {

    var xml = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
    var qstring = "action=getContext&bookID=" + bookID + "&chapter=" + chapter + "&verse=" + verse;
    xml.open('POST', 'ajax.php', true);
    xml.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xml.onreadystatechange = function()
    {
    	if (xml.readyState == 4) {
	    	var rtext = xml.responseText;
			if (rtext != "") {
//				ccShowModalWindow("Bible Context", rtext, 500);
				$("bible_container").innerHTML = rtext;
				if (verse) window.location.hash = verse;
			}
    	}
    }
    xml.send(qstring)

}





//////////////////////////////////////////////////////
// COLOR FUNCTIONS
//////////////////////////////////////////////////////

function cycleCodeColor(curID, nid) {

	if (!storedcolor[nid]) storedcolor[nid] = curID;

	var tel = "notetitle_" + nid;

    var xml = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
    var qstring = "action=cycleCodeColor&curID=" + storedcolor[nid] + "&nid=" + nid;
    xml.open('POST', 'ajax.php', true);
    xml.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xml.onreadystatechange = function()
    {
    	if (xml.readyState == 4) {
	    	var rtext = xml.responseText;
			if (rtext) {
				var r_array = rtext.split(",")
				$(tel).set('class', r_array[1]);
				storedcolor[nid] = r_array[0];
			}
			else {
				alert("Could not cycle color. There was a problem.");
			}
    	}
    }
    xml.send(qstring)

}

function d2h(d) {return d.toString(16);}
function h2d(h) {return parseInt(h,16);}

function darkenColor(color, percent) {

	color = color.replace("#", "");

	var red = h2d(color.substring(0,2));
	var green = h2d(color.substring(2,4));
	var blue = h2d(color.substring(4,6));

	red = d2h(parseInt(red - ((red / 100) * percent)));
	green = d2h(parseInt(green - ((green / 100) * percent)));
	blue = d2h(parseInt(blue - ((blue / 100) * percent)));

	if (red.length < 2) red = "0" + red;
	if (green.length < 2) green = "0" + green;
	if (blue.length < 2) blue = "0" + blue;

	newcolor = "#" + red + green + blue;

	if (newcolor.length == 7) {
		return newcolor;
	} else {
	    alert("error in color darken: " + newcolor);
	}
}

function lightenColor(color, percent) {

	color = color.replace("#", "");

	var red = h2d(color.substring(0,2));
	var green = h2d(color.substring(2,4));
	var blue = h2d(color.substring(4,6));

	red = d2h(parseInt(red + ((red / 100) * percent)));
	green = d2h(parseInt(green + ((green / 100) * percent)));
	blue = d2h(parseInt(blue + ((blue / 100) * percent)));

	if (red.length < 2) red = "0" + red;
	if (green.length < 2) green = "0" + green;
	if (blue.length < 2) blue = "0" + blue;

	newcolor = "#" + red + green + blue;

	if (newcolor.length == 7) {
		return newcolor;
	} else {
	    alert("error in color lighten: " + newcolor);
	}
}




//////////////////////////////////////////////////////
// MODAL WINDOW
//////////////////////////////////////////////////////

var g_RunOnClose = null;
var modalSpeed = 250;

function ccShowModalWindow(title, data, width, givefocus, runonclose, sysmodal) {
	g_RunOnClose = runonclose;
	html = ' \
		<div class="modal_container" style="background: #D4C8AC; padding:5px; border:3px solid black;"> \
			<div class="modal_title"><img style="float:right;" onclick="ccHideModalWindow();" class="modal_icon" src="/images/salt_searcher/cross-circle-frame.png" />' + title + '</div> \
			<div class="modal_body">' + data + '</div> \
		</div>';
	makeOverlay(sysmodal);
	makeModalBox.pass([width, html, givefocus]).delay(modalSpeed);
}

function makeModalBox(mwidth, mtext, mfocus) {
	var size = window.getSize();
	var scroll = window.getScroll();
	var xcenter = (size.x / 2) + scroll.x;
	var ycenter = (size.y / 2) + scroll.y;
	var modalBox = new Element('div', {
	    'id': 'modalBox',
	    'html': mtext,
	    'styles': {
	        'display': 'block',
	        'position': 'absolute',
	        'z-index': '999',
	        'width': mwidth,
	        'opacity': '0'
	    }
	});
	modalBox.inject(document.body);
	var elsize = $('modalBox').getSize();
	var putleft = xcenter - (elsize.x / 2);
	var puttop = ycenter - (elsize.y / 2);
	$('modalBox').setStyle('top',puttop);
	$('modalBox').setStyle('left',putleft);
	if (modalSpeed == 0) {
		$('modalBox').setStyle('opacity', '1');
	}
	else {
		$('modalBox').set('tween', {duration: modalSpeed});
		$('modalBox').tween('opacity', '1');
	}
	if (mfocus) {
		var focusSelect = function(){ $(mfocus).focus(); };
		focusSelect.delay(modalSpeed*2);
	}
}

function makeOverlay(sysmodal){
	var size = window.getScrollSize();
	var overlay = new Element('div', {
	    'id': 'overlay',
	    'html': '',
	    'styles': {
	        'display': 'block',
	        'position': 'absolute',
	        'z-index': '900',
	        'background': 'black',
	        'height': size.y,
	        'width': size.x,
	        'top': '0',
	        'left': '0',
	        'opacity': '0'
	    }
	});
	overlay.inject(document.body);
	if (modalSpeed == 0) {
		$('overlay').setStyle('opacity', '0.5');
	}
	else {
		$('overlay').set('tween', {duration: modalSpeed});
		$('overlay').tween('opacity', '0.5');	
	}
	if (!sysmodal) $('overlay').addEvent('click', ccHideModalWindow);
	$$('embed').setStyle('visibility', 'hidden');
}

function ccHideModalWindow() {
	if (g_RunOnClose && g_RunOnClose != '')
	{
		eval(g_RunOnClose);
	}
	g_RunOnClose = null;
	if ($('overlay')) $('overlay').fade('out');
	disposeOverlay.delay(modalSpeed);
	if ($('modalBox')) $('modalBox').fade('out');
	disposeBox.delay(modalSpeed);
	$$('embed').setStyle('visibility', 'visible');
}

function disposeOverlay(el_overlay) {
	if ($('overlay')) $('overlay').dispose();
}

function disposeBox(el_modalbox) {
	if ($('modalBox')) $('modalBox').dispose();
}




//////////////////////////////////////////////////////
// 
//////////////////////////////////////////////////////