// ineedaprayer.org javascripts

// global variables
var INP = {};

// get a handle to the global framework
var INPFramework = top.INPFramework;

// test the framework handle.  If "INPFramework" is undefined, the framework has not been attached.
if (INPFramework == undefined) {
	// redirect the window to the framework.
	window.location = "http://www.ineedaprayer.org";
}

INP.popupKeepOpen = true;

INP.popTimer = '';

INP.thePop = '';

INP.theElement = '';

// popup components
INP.prayerBody = "<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\"><tr><td align=\"left\" valign=\"middle\" nowrap=\"nowrap\" class=\"popup_itemBG\" onmouseover=\"INP.popupItemEnter(this); INP.setNoPropogate(window.event);\" onmouseout=\"INP.popupItemExit(this); INP.setNoPropogate(window.event);\" onclick=\"window.location='http://www.ineedaprayer.org/phpbb/viewforum.php?f=1';\">Read prayer requests </td></tr><tr><td nowrap=\"nowrap\" class=\"popup_itemBG\" onMouseOver=\"INP.popupItemEnter(this); INP.setNoPropogate(window.event);\" onMouseOut=\"INP.popupItemExit(this); INP.setNoPropogate(window.event);\" onclick=\"window.location='http://www.ineedaprayer.org/phpbb/posting.php?mode=newtopic&f=1';\">Post prayer request </td></tr><tr><td nowrap=\"nowrap\" class=\"popup_itemBG\" onMouseOver=\"INP.popupItemEnter(this); INP.setNoPropogate(window.event);\" onMouseOut=\"INP.popupItemExit(this); INP.setNoPropogate(window.event);\" onclick=\"window.location='http://www.ineedaprayer.org/subscribe.php';\">Subscribe </td></tr><tr><td nowrap=\"nowrap\">&nbsp;</td></tr></table>";

INP.testimonyBody = "<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\"><tr><td align=\"left\" valign=\"middle\" nowrap=\"nowrap\" class=\"popup_itemBG\" onmouseover=\"INP.popupItemEnter(this); INP.setNoPropogate(window.event);\" onmouseout=\"INP.popupItemExit(this); INP.setNoPropogate(window.event);\" onclick=\"window.location='http://www.ineedaprayer.org/phpbb/viewforum.php?f=2';\">Read testimonies   </td></tr><tr><td nowrap=\"nowrap\" class=\"popup_itemBG\" onMouseOver=\"INP.popupItemEnter(this); INP.setNoPropogate(window.event);\" onMouseOut=\"INP.popupItemExit(this); INP.setNoPropogate(window.event);\" onclick=\"window.location='http://www.ineedaprayer.org/phpbb/posting.php?mode=newtopic&f=2';\">Post a testimony  </td></tr><tr><td nowrap=\"nowrap\" class=\"popup_itemBG\" onMouseOver=\"INP.popupItemEnter(this); INP.setNoPropogate(window.event);\" onMouseOut=\"INP.popupItemExit(this); INP.setNoPropogate(window.event);\" onclick=\"window.location='http://www.ineedaprayer.org/subscribe.php';\">Subscribe </td></tr><tr><td nowrap=\"nowrap\">&nbsp;</td></tr></table>";

INP.communityBody = "<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\"><tr><td align=\"left\" valign=\"middle\" nowrap=\"nowrap\" class=\"popup_itemBG\" onmouseover=\"INP.popupItemEnter(this); INP.setNoPropogate(window.event);\" onmouseout=\"INP.popupItemExit(this); INP.setNoPropogate(window.event);\" onclick=\"window.location='http://www.ineedaprayer.org/phpbb/privmsg.php?folder=inbox';\">My Inbox </td></tr><tr><td nowrap=\"nowrap\" class=\"popup_itemBG\" onMouseOver=\"INP.popupItemEnter(this); INP.setNoPropogate(window.event);\" onMouseOut=\"INP.popupItemExit(this); INP.setNoPropogate(window.event);\" onclick=\"window.location='http://www.ineedaprayer.org/phpbb/index.php';\">Discussion Forums   </td></tr><tr><td nowrap=\"nowrap\" class=\"popup_itemBG\" onMouseOver=\"INP.popupItemEnter(this); INP.setNoPropogate(window.event);\" onMouseOut=\"INP.popupItemExit(this); INP.setNoPropogate(window.event);\" onclick=\"window.location='http://www.ineedaprayer.org/chatrooms.php';\">Chat rooms</td></tr><tr><td nowrap=\"nowrap\" class=\"popup_itemBG\" onMouseOver=\"INP.popupItemEnter(this); INP.setNoPropogate(window.event);\" onMouseOut=\"INP.popupItemExit(this); INP.setNoPropogate(window.event);\" onclick=\"window.location='http://www.ineedaprayer.org/phpbb/members.php';\">Members</td></tr><tr><td nowrap=\"nowrap\">&nbsp;</td></tr></table>";

INP.setSigninStatus = function() {
	// if a secue state exists, modify the signin pane to contain signout information instead
		var theSignInBlock = top.document.getElementById('signInBlock').value;
		
		if (INPFramework.secure == true) {
			// a secure session exists
			
			// call to set the 'sign in' header element to 'sign out'
			INPFramework.setHeaderLogElement('in');
			
			// inject the busy spinner into the targetted block
		    document.getElementById('INPSignInBlock').innerHTML = INPFramework.blockSpinnerAssembly;
				
			// we do not load if the framework object for the signin panel is already populated
			// instead we just use its content
			if (theSignInBlock == "") {
				// sign in block has not yet been retrieved
				document.getElementById('INPSignInBlock').innerHTML = INPFramework.blockSpinnerAssembly;
		
				// get a random number to defeat caching
				var theRan = INPFramework.randomNumber;
				var theAccessor = "http://www.ineedaprayer.org/signInBlock.php?anticache=" + theRan;
				INPFramework.getAsynchContent(theAccessor, document.getElementById('INPSignInBlock'), top.document.getElementById('signInBlock'));
			
			} else {
				// signin block has been retrieved already
				// document.getElementById('INPSignInBlock').innerHTML = theSignInBlock;
				
				// get a random number to defeat caching
				var theRan = INPFramework.randomNumber;
				var theAccessor = "http://www.ineedaprayer.org/signInBlock.php?anticache=" + theRan;
				INPFramework.getAsynchContent(theAccessor, document.getElementById('INPSignInBlock'), top.document.getElementById('signInBlock'));
				
				// but we do need to update the message number, so we get it via ajax
				// get a random number to defeat caching
				// var theRan = INPFramework.randomNumber;
				// var theAccessor = "http://www.ineedaprayer.org/getNumMessages.php?anticache=" + theRan;
				// INPFramework.getContent(theAccessor, document.getElementById('INPNumMessages'), 'none');
			}
		
				
		}  else {
			// reset the signin block
			top.document.getElementById('signInBlock').value = "";
			document.getElementById('INPSignInBlock').innerHTML = INPFramework.signedOutBlock;
			
			// call to set the 'sign in' header element to 'sign in'
			INPFramework.setHeaderLogElement('out');
		}
		
		INPFramework.hideSpinner();
		
		// size the main container also
		// fix for missing scroll bar
		INPFramework.sizeMain();
}

INP.noSpinner = function() {
	INPFramework.hideSpinner();
}

INP.displayRadio = function() {
	// display INP radio if appropriate
	
	INPFramework.displayRadio();
}

INP.setNewStuff = function() {
	// if a secue state exists, modify the signin pane to contain signout information instead
		
	if (INPFramework.secure == true) {
		// a secure session exists
		var theRan = INPFramework.randomNumber;
		INPFramework.getAsynchContent("http://www.ineedaprayer.org/ajax/INPNewStuff.php?anticache=" + theRan, document.getElementById('INPNotMember'), true); 
		
	}
	
}

INP.getGeneralContent = function() {
	// ajax the content desired for the INPGenContent area
	
	var theRan = INPFramework.randomNumber;
	INPFramework.getAsynchContent("http://www.ineedaprayer.org/ajax/INPGenContent.php?anticache=" + theRan, document.getElementById('INPGenContent'), true); 
	
}


INP.getContent = function(theContentSource) {
	// ajax some content for a specific container
	
	// set up a request object.  We have to do this so it degrades gracefully for IE6
	if (window.XMLHttpRequest) {
		// this is IE7, safari, etc.
		var xmlhttp =  new XMLHttpRequest();

	} else {
		// this is probably IE6, so see if we can instantiate an activeX obejct
		if (window.ActiveXObject) {
     		var xmlhttp = new ActiveXObject('MSXML2.XMLHTTP.3.0');

  		}
	}

	//xmlhttp.overrideMimeType('text/xml');
	xmlhttp.open('GET', theContentSource, false);
	xmlhttp.send(null);
	var theReturn = xmlhttp.responseText;
	
	return theReturn;
}

INP.getSpotlightBody = function() {
	// get the body of the spotlight request
	var theSpotlight = document.getElementById('spotlightToGet').value;
	
	var theContentSource = "/phpbb/viewtopic_inp2.php?t=" + theSpotlight;
	
	//alert(theContentSource);
	
	var xmlhttp =  new XMLHttpRequest();

	//xmlhttp.overrideMimeType('text/xml');
	xmlhttp.open('GET', theContentSource, false);
	xmlhttp.send(null);
	
	document.getElementById('spotlightBody').innerHTML = xmlhttp.responseText;
}

INP.hitForum = function() {
	toURL = document.getElementById("postTo").value + document.getElementById("tID").value;
	//alert(toURL);
	location.href = toURL;
}

INP.popupItemEnter = function(theItem) {
	// handle mouse entry to a popup item
	
	var theItem; // the item moused
	
	// set the keepOpen variable to ensure that the popup will not close
	INP.popupKeepOpen = true;
	
	// set the className
	theItem.className = "popup_itemBGmoused";
	
	// cancel the bubble so this won't cause the popup to close
	// first figure out if this is IE and set the cancelBubble property
	if (!e) {
		try {
			var e = window.event;
			e.cancelBubble = true;
		} catch(err) {
		}
	}
	
	// if it isn't IE stopPropagation
	try {
		if (e.stopPropagation) e.stopPropagation();
	} catch(err) {
	}
	
	// try to force the popup to remain displayed
	document.getElementById('popupLayer').style.display='block';
	
}

INP.popupItemExit = function(theItem) {
	// handle mouse exit from a popup item
	
	var theItem; // the item exited
	
	// set the keepOpen variable to ensure that the popup will not close
	INP.popupKeepOpen = true;
	
	// set the className
	theItem.className = "popup_itemBG";
	
	// cancel the bubble so this won't cause the popup to close
	// first figure out if this is IE and set the cancelBubble property
	if (!e) {
		try {
			var e = window.event;
			e.cancelBubble = true;
		} catch(err) {
		}
	}
	
	// if it isn't IE stopPropagation
	try {
		if (e.stopPropagation) e.stopPropagation();
	} catch(err) {
	}
	
	// try to force the popup to remain displayed
	document.getElementById('popupLayer').style.display='block';

}

INP.GetElementLeft = function(eElement) {
    var nLeftPos = eElement.offsetLeft;          // initialize var to store calculations
    var eParElement = eElement.offsetParent;     // identify first offset parent element  
    while (eParElement != null)
    {                                            // move up through element hierarchy
        nLeftPos += eParElement.offsetLeft;      // appending left offset of each parent
        eParElement = eParElement.offsetParent;  // until no more offset parents exist
    }
    return nLeftPos;                             // return the number calculated
}

INP.displayPop = function(thePop, theElement) {
	// display the popup for this item
	
	var thePop; // the popup to display
	var theElement; // the element moused
	
	INP.thePop = thePop;
	INP.theElement = theElement;
	
	// set a timer that will pop the display after 400 MS unless it gets cancelled
	// by a mouse out event.
	
	INP.popTimer = setInterval('INP.displayPopShow();', 400);
	
}

INP.cancelDisplayPop = function() {
	// display the popup for this item
	
	clearInterval(INP.popTimer);
	
}

INP.displayPopShow = function() {
	// display the popup for this item
	
	var thePop = INP.thePop; // the popup to display
	var theElement = INP.theElement; // the element moused
	
	// get the true left position of the element
	var theLeftPos = INP.GetElementLeft(theElement);
	
	// get the top position of the element
	var theTopPos = INP.GetElementTop(theElement);
	
	// set the popup to the proper location
	document.getElementById("popupLayer").style.top = theTopPos - 30 + 'px';
	document.getElementById("popupLayer").style.left = theLeftPos + 12 + 'px';
	document.getElementById("popupLayer").style.zindex = '34';
	
	// replace the popupBody
	document.getElementById('popupBody').innerHTML = eval('INP.' + thePop + 'Body');
	
	// set the outer and inner classes as appropriate
	document.getElementById('pLeft').className = "popup_midLft" + thePop;
	document.getElementById('pRight').className = "popup_midRt" + thePop;
	document.getElementById('pMid').className = "popup_midMid" + thePop;
	 
	// make it visible
	document.getElementById("popupLayer").style.display = 'block';
}

INP.GetElementTop = function(eElement) {
    var nTopPos = eElement.offsetTop;            // initialize var to store calculations
    var eParElement = eElement.offsetParent;     // identify first offset parent element  
    while (eParElement != null)
    {                                            // move up through element hierarchy
        nTopPos += eParElement.offsetTop;        // appending top offset of each parent
        eParElement = eParElement.offsetParent;  // until no more offset parents exist
    }
    return nTopPos;                              // return the number calculated
}

INP.exitPopup = function() {
	// close the popup window if appropriate
	
	// if the popupKeepOpen variable is true, set it false but then break 
	// in order to keep the popup from closing
	// Otherwise, close the popup
	if (INP.popupKeepOpen == true) {
		// we do nothing
	} else {
		document.getElementById('popupLayer').style.display = 'none';
	}
}

INP.setNoPropogate = function(theEvent) {
	// cancel the bubble so this won't cause the popup to close
	var theEvent; // the event fired
	
	// first figure out if this is IE and set the cancelBubble property
	try {
		theEvent.cancelBubble = true;
	
		// if it isn't IE stopPropagation
		if (theEvent.stopPropagation) {
			//alert('this is firefox');
			theEvent.stopPropagation();
		}
	} catch(err) {
	}
}

INP.handleRadioClick = function() {
	// handle clicks to the INP radio badge
	
	if (INPFramework.radioState == 'stopped') {
		// INP radio is stopped, so we direct the iframe to load the player
		INPFramework.loadRadioPlayer();
		
		// change the badge state to playing
		document.getElementById('inpradioImage').src = "http://www.ineedaprayer.org/images/inpRadioBadgeAnim.gif";
		
	} else {
		INPFramework.stopPlayer();
		
		// change the badge state to playing
		document.getElementById('inpradioImage').src = "http://www.ineedaprayer.org/images/inpRadioBadge.gif";
	}
}

INP.goInsecure = function() {
	// switch to an insecure state
	INPFramework.goInsecure();
	
}

// ------- directory functions -------

INP.directory = {}; // directory namespace

INP.directory.setStateCode = function(theValue) {
	// set the state code form variable for church directory when the user chooses a state
	document.getElementById('stateCode').value = theValue;
}

// ------- legacy scripts -------

// bbCode control by
// subBlue design
// www.subBlue.com

// Startup variables
var imageTag = false;
var theSelection = false;

// Check for Browser & Platform for PC & IE specific bits
// More details from: http://www.mozilla.org/docs/web-developer/sniffer/browser_type.html
var clientPC = navigator.userAgent.toLowerCase(); // Get client info
var clientVer = parseInt(navigator.appVersion); // Get browser version

var is_ie = ((clientPC.indexOf("msie") != -1) && (clientPC.indexOf("opera") == -1));
var is_nav = ((clientPC.indexOf('mozilla')!=-1) && (clientPC.indexOf('spoofer')==-1)
                && (clientPC.indexOf('compatible') == -1) && (clientPC.indexOf('opera')==-1)
                && (clientPC.indexOf('webtv')==-1) && (clientPC.indexOf('hotjava')==-1));
var is_moz = 0;

var is_win = ((clientPC.indexOf("win")!=-1) || (clientPC.indexOf("16bit") != -1));
var is_mac = (clientPC.indexOf("mac")!=-1);

// Helpline messages
b_help = "{L_BBCODE_B_HELP}";
i_help = "{L_BBCODE_I_HELP}";
u_help = "{L_BBCODE_U_HELP}";
q_help = "{L_BBCODE_Q_HELP}";
c_help = "{L_BBCODE_C_HELP}";
l_help = "{L_BBCODE_L_HELP}";
o_help = "{L_BBCODE_O_HELP}";
p_help = "{L_BBCODE_P_HELP}";
w_help = "{L_BBCODE_W_HELP}";
a_help = "{L_BBCODE_A_HELP}";
s_help = "{L_BBCODE_S_HELP}";
f_help = "{L_BBCODE_F_HELP}";

// Define the bbCode tags
bbcode = new Array();
bbtags = new Array('[b]','[/b]','[i]','[/i]','[u]','[/u]','[quote]','[/quote]','[code]','[/code]','[list]','[/list]','[list=]','[/list]','[img]','[/img]','[url]','[/url]');
imageTag = false;

// Shows the help messages in the helpline window
function helpline(help) {
	document.post.helpbox.value = eval(help + "_help");
}


// Replacement for arrayname.length property
function getarraysize(thearray) {
	for (i = 0; i < thearray.length; i++) {
		if ((thearray[i] == "undefined") || (thearray[i] == "") || (thearray[i] == null))
			return i;
		}
	return thearray.length;
}

// Replacement for arrayname.push(value) not implemented in IE until version 5.5
// Appends element to the array
function arraypush(thearray,value) {
	thearray[ getarraysize(thearray) ] = value;
}

// Replacement for arrayname.pop() not implemented in IE until version 5.5
// Removes and returns the last element of an array
function arraypop(thearray) {
	thearraysize = getarraysize(thearray);
	retval = thearray[thearraysize - 1];
	delete thearray[thearraysize - 1];
	return retval;
}


function checkForm() {

	formErrors = false;    

	if (document.post.message.value.length < 2) {
		formErrors = "{L_EMPTY_MESSAGE}";
	}

	if (formErrors) {
		alert(formErrors);
		return false;
	} else {
		bbstyle(-1);
		//formObj.preview.disabled = true;
		//formObj.submit.disabled = true;
		return true;
	}
}

function emoticon(text) {
	var txtarea = document.post.message;
	text = ' ' + text + ' ';
	if (txtarea.createTextRange && txtarea.caretPos) {
		var caretPos = txtarea.caretPos;
		caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ? caretPos.text + text + ' ' : caretPos.text + text;
		txtarea.focus();
	} else {
		txtarea.value  += text;
		txtarea.focus();
	}
}

function bbfontstyle(bbopen, bbclose) {
	var txtarea = document.post.message;

	if ((clientVer >= 4) && is_ie && is_win) {
		theSelection = document.selection.createRange().text;
		if (!theSelection) {
			txtarea.value += bbopen + bbclose;
			txtarea.focus();
			return;
		}
		document.selection.createRange().text = bbopen + theSelection + bbclose;
		txtarea.focus();
		return;
	}
	else if (txtarea.selectionEnd && (txtarea.selectionEnd - txtarea.selectionStart > 0))
	{
		mozWrap(txtarea, bbopen, bbclose);
		return;
	}
	else
	{
		txtarea.value += bbopen + bbclose;
		txtarea.focus();
	}
	storeCaret(txtarea);
}


function bbstyle(bbnumber) {
	var txtarea = document.post.message;

	txtarea.focus();
	donotinsert = false;
	theSelection = false;
	bblast = 0;

	if (bbnumber == -1) { // Close all open tags & default button names
		while (bbcode[0]) {
			butnumber = arraypop(bbcode) - 1;
			txtarea.value += bbtags[butnumber + 1];
			buttext = eval('document.post.addbbcode' + butnumber + '.value');
			eval('document.post.addbbcode' + butnumber + '.value ="' + buttext.substr(0,(buttext.length - 1)) + '"');
		}
		imageTag = false; // All tags are closed including image tags :D
		txtarea.focus();
		return;
	}

	if ((clientVer >= 4) && is_ie && is_win)
	{
		theSelection = document.selection.createRange().text; // Get text selection
		if (theSelection) {
			// Add tags around selection
			document.selection.createRange().text = bbtags[bbnumber] + theSelection + bbtags[bbnumber+1];
			txtarea.focus();
			theSelection = '';
			return;
		}
	}
	else if (txtarea.selectionEnd && (txtarea.selectionEnd - txtarea.selectionStart > 0))
	{
		mozWrap(txtarea, bbtags[bbnumber], bbtags[bbnumber+1]);
		return;
	}
	
	// Find last occurance of an open tag the same as the one just clicked
	for (i = 0; i < bbcode.length; i++) {
		if (bbcode[i] == bbnumber+1) {
			bblast = i;
			donotinsert = true;
		}
	}

	if (donotinsert) {		// Close all open tags up to the one just clicked & default button names
		while (bbcode[bblast]) {
				butnumber = arraypop(bbcode) - 1;
				txtarea.value += bbtags[butnumber + 1];
				buttext = eval('document.post.addbbcode' + butnumber + '.value');
				eval('document.post.addbbcode' + butnumber + '.value ="' + buttext.substr(0,(buttext.length - 1)) + '"');
				imageTag = false;
			}
			txtarea.focus();
			return;
	} else { // Open tags
	
		if (imageTag && (bbnumber != 14)) {		// Close image tag before adding another
			txtarea.value += bbtags[15];
			lastValue = arraypop(bbcode) - 1;	// Remove the close image tag from the list
			document.post.addbbcode14.value = "Img";	// Return button back to normal state
			imageTag = false;
		}
		
		// Open tag
		txtarea.value += bbtags[bbnumber];
		if ((bbnumber == 14) && (imageTag == false)) imageTag = 1; // Check to stop additional tags after an unclosed image tag
		arraypush(bbcode,bbnumber+1);
		eval('document.post.addbbcode'+bbnumber+'.value += "*"');
		txtarea.focus();
		return;
	}
	storeCaret(txtarea);
}

// From http://www.massless.org/mozedit/
function mozWrap(txtarea, open, close)
{
	var selLength = txtarea.textLength;
	var selStart = txtarea.selectionStart;
	var selEnd = txtarea.selectionEnd;
	if (selEnd == 1 || selEnd == 2) 
		selEnd = selLength;

	var s1 = (txtarea.value).substring(0,selStart);
	var s2 = (txtarea.value).substring(selStart, selEnd)
	var s3 = (txtarea.value).substring(selEnd, selLength);
	txtarea.value = s1 + open + s2 + close + s3;
	return;
}

// Insert at Claret position. Code from
// http://www.faqts.com/knowledge_base/view.phtml/aid/1052/fid/130
function storeCaret(textEl) {
	if (textEl.createTextRange) textEl.caretPos = document.selection.createRange().duplicate();
}

// ------- attach events -------
if (window.attachEvent) {
	// the executing browser is IE
	window.attachEvent("onload", INP.setSigninStatus);	
	window.attachEvent("onload", INPFramework.displayRadio);
	window.attachEvent("onload", INP.setNewStuff);	
	window.attachEvent("onload", INP.getGeneralContent);
	window.attachEvent("onunload", INPFramework.showSpinner);
	
} else {
	//the executing browser is not IE
	window.addEventListener('load', INP.setSigninStatus, false);
	window.addEventListener('load', INPFramework.displayRadio, false);
	window.addEventListener('load', INP.setNewStuff, false);
	window.addEventListener('load', INP.getGeneralContent, false);
	window.addEventListener('unload', INPFramework.showSpinner, false);
	
}



