function log(message) {
    if (!log.window_ || log.window_.closed) {
        var win = window.open("", null, "width=400,height=200," +
                              "scrollbars=yes,resizable=yes,status=no," +
                              "location=no,menubar=no,toolbar=no");
        if (!win) return;
        var doc = win.document;
        doc.write("<html><head><title>Debug Log</title></head>" +
                  "<body></body></html>");
        doc.close();
        log.window_ = win;
    }
    var logLine = log.window_.document.createElement("div");
    logLine.appendChild(log.window_.document.createTextNode(message));
    log.window_.document.body.appendChild(logLine);
}

function navro(obj, state) {
	$(obj).className = (state == 'on') ? 'nav-highlight' : 'nav';
}

function uploadButton(btnS,imgS,frmS){
	var theButton=document.getElementById(btnS);
	var theImage=document.getElementById(imgS);
	var theForm=document.getElementById(frmS);
	theButton.disabled=true;
	theForm.submit();
	setTimeout("document.images['"+imgS+"'].src='/share/img/loading.gif'",200);
	return true;
}

function openHelp(topic){
	myFloater = window.parent.open('','Help','resizable=no,scrollbars=yes,width=500,height=500');
	myFloater.location.href = '/help/'+topic+'.php';
	myFloater.focus();
}

function advPreview(where){
	document.previewForm.data.value = where.value;
	myFloater = window.parent.open('','Preview','resizable=no,scrollbars=yes,width=550,height=400');
	document.previewForm.target='Preview';
	document.previewForm.action='/preview.php';
	document.previewForm.submit();
	myFloater.focus();
}

function showConfirm(msg,href) {
    if (confirm(msg))
        window.location.href = href;
}

function togglePanel(p) {
	if ($(p).hasClassName('collapsed')) { // expand it
		$$('#'+p+' div.panelTitle').each(function(e) {
			e.setStyle({backgroundImage:'url(/share/img/arrowDownPadded.gif)'});
			});
		$$('#'+p+' div.panelContent').each(function(e) {
			e.show();
			});
		$$('#'+p+' div.c3').each(function(e) {
			e.setStyle({visibility:'hidden'});
			});
		$(p).removeClassName('collapsed');
		$(p).addClassName('expanded');
	} else { // collapse it
		$$('#'+p+' div.panelTitle').each(function(e) {
			e.setStyle({backgroundImage:'url(/share/img/arrow.gif)'});
			});
		$$('#'+p+' div.panelContent').each(function(e) {
			e.hide();
			});
		$$('#'+p+' div.c3').each(function(e) {
			e.setStyle({visibility:'visible'});
			});
		$(p).addClassName('collapsed');
		$(p).removeClassName('expanded');
	}
	return;
}

function setupPanel(p) {
	if ($(p).hasClassName('collapsed')) {
		$$('#'+p+' div.panelTitle').each(function(e) {
			e.setStyle({backgroundImage:'url(/share/img/arrow.gif)'});
			});
		$$('#'+p+' div.panelContent').each(function(e) {
			e.hide();
			});
	} else {
		$$('#'+p+' div.c3').each(function(e) {
			e.setStyle({visibility:'hidden'});
		});
	}
	return;
}

//------------------------------
// MHCode Helper Textarea Buttons
//------------------------------

function addText(myField,what) {
        if (what=='href') { tagstart="[link=insert address here]"; tagend="[/link]"; }
        else if (what=='email') { tagstart="[email]"; tagend="[/email]"; }
        else if (what=='strong') { tagstart="[b]"; tagend="[/b]"; }
        else if (what=='em') { tagstart="[i]"; tagend="[/i]"; }
        else if (what=='img') { tagstart="[img]"; tagend="[/img]"; }
        else if (what=='center') { tagstart="[center]"; tagend="[/center]"; }
        else if (what=='left') { tagstart="[left]"; tagend="[/left]"; }
        else if (what=='right') { tagstart="[right]"; tagend="[/right]"; }
        else if (what=='fontS') { tagstart="[size=9]"; tagend="[/size]"; }
        else if (what=='fontL') { tagstart="[size=16]"; tagend="[/size]"; }
        else if (what=='red') { tagstart="[color=red]"; tagend="[/color]"; }
        else if (what=='u') { tagstart="[u]"; tagend="[/u]"; }
        else if (what=='ul') { tagstart="[list]\n[*]"; tagend="\n[/list]"; }
        else if (what=='columns') { tagstart="[columns]\n[column]\n"; tagend="\n[/column]\n[column]\n\n[/column]\n[/columns]"; }

        //IE
        if (document.selection) {
                myField.focus();
                sel = document.selection.createRange();
                sel.text = tagstart+sel.text+tagend;
        }
        //MOZILLA/NETSCAPE
        else if (myField.selectionStart || myField.selectionStart == '0') {
				myField.focus();
                var startPos = myField.selectionStart;
                var endPos = myField.selectionEnd;
                myField.value = myField.value.substring(0, startPos)
                + tagstart + myField.value.substring(startPos,endPos) + tagend
                + myField.value.substring(endPos, myField.value.length);
				myField.selectionStart = startPos;
				myField.selectionEnd = endPos+tagend.length+tagstart.length;
        } else { //OPERA, SAFARI
				myField.focus();
                myField.value += tagstart+tagend;
        }
}

MH_autocomplete_selector_old = function(instance) {
	var ret       = []; // Beginning matches
	var partial   = []; // Inside matches
	var entry     = instance.getToken();
	var count     = 0;

	for (var i = 0; i < instance.options.array.length &&  
		ret.length < instance.options.choices ; i++) { 
		
		var text = instance.options.array[i];
		var indexOfDivide = text.indexOf('#');
		var numMatches = text.substring(0, indexOfDivide);
		var elem = text.substr(indexOfDivide+1);
		var numMatches = "<span class='numTypeMatches'>("+numMatches+" matches)</span>";

		var foundPos = instance.options.ignoreCase ? 
		elem.toLowerCase().indexOf(entry.toLowerCase()) : 
		elem.indexOf(entry);

		while (foundPos != -1) {
			if (foundPos == 0 && elem.length != entry.length) { 
				ret.push("<li><strong>" + elem.substr(0, entry.length) + "</strong>" + 
				elem.substr(entry.length) + numMatches + "</li>");
				break;
			} else if (entry.length >= instance.options.partialChars && 
				instance.options.partialSearch && foundPos != -1) {
				if (instance.options.fullSearch || /\s/.test(elem.substr(foundPos-1,1))) {
					partial.push("<li>" + elem.substr(0, foundPos) + "<strong>" +
					elem.substr(foundPos, entry.length) + "</strong>" + elem.substr(
					foundPos + entry.length) + numMatches + "</li>");
					break;
				}
			}

			foundPos = instance.options.ignoreCase ? 
			elem.toLowerCase().indexOf(entry.toLowerCase(), foundPos + 1) : 
			elem.indexOf(entry, foundPos + 1);

		}
	}
	if (partial.length)
		ret = ret.concat(partial.slice(0, instance.options.choices - ret.length))
	return "<ul>" + ret.join('') + "</ul>";
}

MH_autocomplete_selector = function(instance) {
	var ret       = []; // Beginning matches
	var partial   = []; // Inside matches
	var entry     = instance.getToken();
	var count     = 0;

	for (var i = 0; i < instance.options.array.length &&  
		ret.length < instance.options.choices ; i++) { 
		
		var text = instance.options.array[i];
		var indexOfDivide = text.indexOf('#');
		var numMatches = text.substring(0, indexOfDivide);
		var elem = text.substr(indexOfDivide+1);
		var numMatches = "<div class='numTypeMatches'><span class='informal'>"+numMatches+" matches</span></div>";

		var foundPos = instance.options.ignoreCase ? 
		elem.toLowerCase().indexOf(entry.toLowerCase()) : 
		elem.indexOf(entry);

		while (foundPos != -1) {
			if (foundPos == 0 && elem.length != entry.length) { 
				ret.push("<li class='suggestEntry'><div class='left'><strong>" + elem.substr(0, entry.length) + "</strong>" + 
				elem.substr(entry.length) + "</div>" + numMatches + "</li>");
				break;
			} else if (entry.length >= instance.options.partialChars && 
				instance.options.partialSearch && foundPos != -1) {
				if (instance.options.fullSearch || /\s/.test(elem.substr(foundPos-1,1))) {
					partial.push("<li class='suggestEntry'><div class='left'>" + elem.substr(0, foundPos) + "<strong>" +
					elem.substr(foundPos, entry.length) + "</strong>" + elem.substr(
					foundPos + entry.length) + "</div>" + numMatches + "</li>");
					break;
				}
			}

			foundPos = instance.options.ignoreCase ? 
			elem.toLowerCase().indexOf(entry.toLowerCase(), foundPos + 1) : 
			elem.indexOf(entry, foundPos + 1);

		}
	}
	if (partial.length)
		ret = ret.concat(partial.slice(0, instance.options.choices - ret.length))
	return "<ul>" + ret.join('') + "</ul>";
}

function deleteTagTarget(action, target, id){
	var url = 'http://missionexchange.net/ajax.php';
	var pars = 'action='+action+'&target='+target+'&id='+id;
	var myAjax = new Ajax.Updater(target, url, {method: 'post', parameters: pars, evalScripts:true});
}

function addTagTarget(action, target, resourceid, type, name){
	var url = 'http://missionexchange.net/ajax.php';
	var pars = 'action='+action+'&target='+target+'&resourceid='+resourceid+'&name='+name;
	var myAjax = new Ajax.Updater(target, url, {method: 'post', parameters: pars,  evalScripts:true});
}

function deleteTag(id){
	deleteTagTarget('deleteTag', 'taggingArea', id);
}

function addTag(resourceid, type, name){
	addTagTarget('addTag', 'taggingArea', resourceid, type, name);
}

function deleteTagFromList(target, id){
	deleteTagTarget('deleteTagFromList', target, id);
}

function addTagFromList(target, resourceid, type, name){
	addTagTarget('addTagFromList', target, resourceid, type, name);
}

function getVideo(target, panelId, targetItemNum){
	registerIndicator('videoIndicator');
	var url = 'http://missionexchange.net/ajax.php';
	var pars = 'action=video&targetItemNum='+targetItemNum+'&panelId='+panelId;
	var myAjax = new Ajax.Updater(target, url, {method: 'post', parameters: pars});
}

function registerIndicator(id){
	var myGlobalHandlers = {
		onCreate: function(){
			Element.show(id);
		},

		onComplete: function() {
			if(Ajax.activeRequestCount == 0){
				Element.hide(id);
			}
		}
	};
	Ajax.Responders.register(myGlobalHandlers);
}

function showResponse(originalRequest){
	alert(originalRequest.responseText);
}

function validateFlickrUsername(target,uname){
	var url = 'http://missionexchange.net/ajax.php';
	var pars = 'action=validateFlickr&uname='+uname;
	var myAjax = new Ajax.Updater(target, url, {method: 'post', parameters: pars});
}

function toggleDisability(id){
	$(id).disabled=!$(id).disabled;
}
function isBlank(obj){
	return (obj == null || obj == undefined || obj == '');
}

// Overlay functions
function hideSelectBoxes(){
	selects = document.getElementsByTagName("select");
	for (i = 0; i != selects.length; i++) {
		selects[i].style.visibility = "hidden";
	}
}
function showSelectBoxes(){
	selects = document.getElementsByTagName("select");
	for (i = 0; i != selects.length; i++) {
		selects[i].style.visibility = "visible";
	}
}

function showOverlay(){
	// stretch overlay to fill page and fade in
	var arrayPageSize = getPageSize();
	Element.setHeight('overlay', arrayPageSize[1]);
	new Effect.Appear('overlay', { duration: 0.2, from: 0.0, to: 0.7 });
	hideSelectBoxes();
}
function hideOverlay(){
	new Effect.Fade('overlay', { duration: 0.2});
	showSelectBoxes();
}
function getPageSize(){
	
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}

	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}

Object.extend(Element, {
	getWidth: function(element) {
	   	element = $(element);
	   	return element.offsetWidth; 
	},
	setWidth: function(element,w) {
	   	element = $(element);
    	element.style.width = w +"px";
	},
	setHeight: function(element,h) {
   		element = $(element);
    	element.style.height = h +"px";
	},
	setTop: function(element,t) {
	   	element = $(element);
    	element.style.top = t +"px";
	},
	setSrc: function(element,src) {
    	element = $(element);
    	element.src = src; 
	},
	setHref: function(element,href) {
    	element = $(element);
    	element.href = href; 
	},
	setInnerHTML: function(element,content) {
		element = $(element);
		element.innerHTML = content;
	}
});

//"Send Message" form
function showMailForm (name, id) {
	showOverlay();
	Element.update('sendMessageTo', name);
	$('sendMessageUserId').value = id;
	Element.toggle('emailForm');
	new Effect.Opacity('emailForm', { duration: 1.0, to: 0.97 });
	new Draggable('emailForm', {handle:$('sendMessageTitle'), starteffect:function (e){}, endeffect:function (e){}});
	$('fullname').focus();
}
function sendMessage(){
	registerIndicator('sendmessageindicator');
	Element.hide('sendmessagebuttons');
	var url = '/ajax.php';
	var pars = { action: 'sendMessage', id: $F('sendMessageUserId'), message: $F('message') };
	var myAjax = new Ajax.Request(url, 
					{method: 'post', parameters: $H(pars).toQueryString(), 	onComplete:sendMessageResponse});
}
function sendMessageResponse(originalRequest){
	['sendMessageInput', 'sendMessageTitle'].each(Element.hide);
	Element.update('actionResponse', originalRequest.responseText);
}
function hideEmailForm(){
	hideOverlay();
	Element.hide('emailForm');
	Element.update('actionResponse', "");
	['sendMessageInput', 'sendMessageTitle', 'sendmessagebuttons'].each(Element.show);
	$('message').value="";
}

// Comment Form

function showCommentForm () {
	showOverlay();
	Element.toggle('commentForm');
	new Effect.Opacity('commentForm', { duration: 1.0, to: 0.97 });
	new Draggable('commentForm', {starteffect:function (e){}, endeffect:function (e){}});
	$('commentText').focus();
}
function comment(){
    registerIndicator('sendmessageindicator');
	//Element.hide('sendmessagebuttons');
	var url = '/ajax.php';
	var pars = { action: 'comment', userid: $F('toid'), message: $F('commentText') };
	var myAjax = new Ajax.Request(url, 
					{method: 'post', parameters: $H(pars).toQueryString(), 	onComplete:commentResponse});
}
function commentResponse(originalRequest){
	Element.update('contentComments', originalRequest.responseText);
	hideCommentForm();
}

function hideCommentForm(){
	hideOverlay();
	Element.hide('commentForm');
	Element.update('actionResponse', "");
	['sendMessageInput', 'sendMessageTitle', 'sendmessagebuttons'].each(Element.show);
	$('commentText').value="";
}

//"Donate" form
function showDonateForm (id, name, ministryName) {
	showOverlay();
	Element.update('donateTo', name);
	Element.update('donateToMinistry', ministryName);
	$('donateToUserId').value = id;
	Element.toggle('donationFormArea');
	adjustPositionForScroll('donationFormArea');
	new Draggable('donationFormArea', {handle:$('donateTitle'), starteffect:function (e){}, endeffect:function (e){}});
	$('donateFromName').focus();
}
function hideDonationForm(){
	hideOverlay();
	Element.hide('donationFormArea');
	$('donationForm').reset();
}

//memory leak remover!
if (window.attachEvent) {
    var clearElementProps = [
        'data',
        'onmouseover',
        'onmouseout',
        'onmousedown',
        'onmouseup',
        'ondblclick',
        'onclick',
        'onselectstart',
        'oncontextmenu'
    ];

    window.attachEvent("onunload", function() {
        var ehel;
        for(var d = document.all.length;d--;){
            ehel = document.all[d];
            for(var c = clearElementProps.length;c--;){
               // ehel[clearElementProps[c]] = undefined;
            }
        }
		//var contacts = $A(document.getElementsByClassName('contactName'));
		//contacts.each(function(node){alert(node.innerHTML + ': ' + node.onclick);});
    });
}
function a(url){
	Element.show('bodyIndicator');
	var pars = 'bodyOnly=true';
	var myAjax = new Ajax.Updater('bodyContent', url, {method: 'post', parameters: pars, onComplete:aOnComplete, evalScripts:true});
}
function aOnComplete(){
	Element.hide('bodyIndicator');
	ajaxifyLinks();
}
function ajaxifyLinks(){
	var allLinks = document.getElementsByTagName('a');
	var nodes = $A(allLinks);
	nodes.each(function(node){
			if (!ajaxified(node)){
				node.href = "javascript:a('"+node.href+"')";
				node.rel = 'ajaxified';
			}
		});
}
function ajaxified(linkNode){
	return linkNode.rel == 'ajaxified';
}
function clearInviteEmail(elId){
	Element.addClassName($(elId), 'emphasis');
}
function resetInviteEmail(elId){
	Element.removeClassName($(elId), 'emphasis');
}
function notActive(){
	alert('This feature is not active yet!  Please check back in a few days.');
}

