/** Copyright 2009 TN20, Inc. All rights reserved.
* $Author: jari $
* $Date: 2009-07-16 12:43:24 +0200 (to, 16 jul 2009) $
* $Revision: 17435 $
* $Id: AboutGroupJwc.java 17435 2009-07-16 10:43:24Z jari $
*/ 
var isIE = false;
var isSaf = false;
var thebrowserName = navigator.appName;
if ( thebrowserName == "Microsoft Internet Explorer" )
	isIE = true;
else if ( navigator.vendor == "Apple Computer, Inc." )
	isSaf = true;
function replaceOnmouseover(link,newAction){
	if(!(isIE||isSaf)){
	if( tacos.requestsInFlight>0) {
		dojo.debug("INFO:" +"requests flying");
	
	}
		dojo.debug("INFO:" +"Waiting for othe calls");
		dojo.io.XMLHTTPTransport.watchInFlight();
		dojo.debug("INFO:" +"Removing onmouseover");
		link.attributes[2].nodeValue=newAction;
	}
}



function niy () {
	alert("Not implemented yet. Sorry.");}

	// Removes leading whitespaces
function LTrim( value ) {
	
	var re = /\s*((\S+\s*)*)/;
	return value.replace(re, "$1");
	
}

// Removes ending whitespaces
function RTrim( value ) {
	
	var re = /((\s*\S+)*)\s*/;
	return value.replace(re, "$1");
	
}

// Removes leading and ending whitespaces
function trim( value ) {
	
	return LTrim(RTrim(value));
	
}

function evaluateAction(elem) {



	elem = byId( elem );
	var theForm = getFirstParentofType( elem, 'form' );
	var myOption = document.getElementById('selectedOption');
	if( selectedCount <= 0 ) { 
		showDialog( 'di_select' );
		return false;
	
	}  else if(theForm.elements['successmsg'].value == '1' ) { 
		document.getElementById('selectedOption').value = '1';
//		return false;
		theForm.submit();
	}  else if(theForm.elements['successmsg'].value == '10' ) { 
		document.getElementById('selectedOption').value = '10';
//		return false;
		theForm.submit();
	} else if( theForm.elements['successmsg'].value == '2' ) { 
		document.getElementById('selectedOption').value = '2';	
		showDialog( 'di_remove' );
		return false;
	} else if( theForm.elements['successmsg'].value == '3' ) {
		document.getElementById('selectedOption').value = '3';	
		showDialog( 'di_ban' );
		return false;
	} else if( theForm.elements['successmsg'].value == '4' ) {
		document.getElementById('selectedOption').value = '4';	
		showDialog( 'di_addtogroups' );
		return false;
	} else if( theForm.elements['successmsg'].value == '5' ) {
		document.getElementById('selectedOption').value = '5';	
		showDialog( 'di_removefromgroups' );
		return false;
	} else if( theForm.elements['successmsg'].value == '6' ) {
		document.getElementById('selectedOption').value = '6';
		theForm.submit();
		return true;
	} else if( theForm.elements['successmsg'].value == '7' ) {
		document.getElementById('selectedOption').value = '7';	
		showDialog( 'di_emailsettings' );
		return false;
	} else if( theForm.elements['successmsg'].value == '8' ) {
		document.getElementById('selectedOption').value = '8';
		theForm.submit();
		return true;
	}	 else if( theForm.elements['successmsg'].value == '11' ) {
				document.getElementById('selectedOption').value = '11';	
				showDialog( 'di_limitmembership' );
				return false;
	} else {
		theForm.submit();
	}
			
}

/****** for the Member Invitation module (email validation)  ****/


function checkInviteMessage(elem) {

	elem = byId( elem ); 
	var theForm = getFirstParentofType( elem, 'form' );
	theField = byId( 'actOnSelected');
//	var size = document.getElementById('selections').value;
//	if( size == 0 ) { 
//		theForm.submit();
//	} else 
	if( selectedCount <= 0 ) { 
		document.getElementById('selectedOption').value = '0';
		theForm.submit();
	} else
	if( theField.value == "0") { 
		document.getElementById('selectedOption').value = '0';
		theForm.submit();
	} else if( theField.value == "1" ) { //&& activeDialog == null) { // if the selected action = invite, and no dialog is open
	// 	alert( "theField.value =" + theField.value  );
		document.getElementById('selectedOption').value = theField.value;
		showDialog('di_invitationMsg');
		return false;
	} else {
		document.getElementById('selectedOption').value = theField.value;
		theForm.submit();
	}
}

/***** Special tag suggest without count    ****/

		function endPageRender(){
		var mikePic= byId('mike');
	//	mikePic.src="/include3/images/thumb_fergie.jpg";
		
		}
  
function tagsuggest2( TagField, suggestionbox, event ) {
		dojo.debug(" captured by suggested tags");
		TagField = byId( TagField );
		var allWords = TagField.value;
		var allWordsLength = allWords.length;
	
		var parentForm = getFirstParentofType( TagField, 'form' );
		if( tagscroll < 0  && (allWordsLength == 0 || allWords.charAt(allWordsLength-1) == " " || allWords == null ) ) { 
			hideTS(); // hide that TA menu....
			return false; // and skip this whole function.
		} else if ( tagsLoaded == false  ) { 
			hideTS(); // hide that TA menu....
			return false; // and skip this whole function.
			} else {
			;
		}
	
		globalTagsField = TagField;
		var thePopup = dojo.byId( "tagsuggestbox" );
		var suggestions = thePopup.getElementsByTagName('a');
		var suggestionsLength = suggestions.length;

		var keyPressed= getKeyCode(event);
	
		var wordArray = fieldValueToTagArray( allWords);
	
		if( keyPressed == KEY_DOWNARROW && (suggestionsLength > 0) ) { 
			if( isSaf ) { // special code to catch safari double keyup event
				if( safLockout == false ) {safLockout = true;}
				else { safLockout = false; return false;}
			}
			if( tagscroll < suggestionsLength ) {
				if( tagscroll > -1 )  
					dojo.html.removeClass( suggestions[(tagscroll)], 'active' );
				tagscroll++;
				if( tagscroll < suggestionsLength ) {
					makeActive( suggestions[(tagscroll)] );
					disableSubmit( TagField );
				} else {
					enableSubmit();
					tagscroll = -1;
				}
			}
			return true;
		} else if( keyPressed == KEY_UPARROW && (suggestionsLength > 0) ) { 
			LBselectInputLastChar(TagField); // move keyboard focus to end of selection
			if( isSaf ) { // special code to catch safari double keyup event
				if( safLockout == false ) {safLockout = true;}
				else { safLockout = false; return false;}
			}
			if( tagscroll > -1 ) {
				if( tagscroll < suggestionsLength ) dojo.html.removeClass( suggestions[(tagscroll)], 'active' );
				tagscroll--;
				if( tagscroll > -1 ) {
					makeActive( suggestions[(tagscroll)] );
					disableSubmit( TagField );
				} else {
					enableSubmit();
					}
			} else {
				tagscroll = suggestionsLength-1;
				if( tagscroll > -1 ) 
					makeActive( suggestions[(tagscroll)] );
				disableSubmit( TagField );
			}
			
			LBselectInputLastChar(TagField); // move keyboard focus to end of selection
			return true;
		
		} else if( keyPressed == KEY_SPACEBAR && (tagscroll > -1) ) { 
			TagField.value = wordArray.join(" "); // add an extra space at the end.
			if( tagscroll < suggestionsLength ) {
				completeTS( suggestions[(tagscroll)] );
			}
			return true;
		
		} else if( keyPressed == KEY_ENTER && (tagscroll > -1) ) { 
		dojo.debug("Enter pressed");
	// return/enter, with a suggestion highlighted
		/*if( tagscroll < suggestionsLength ) {
			//var theWord = suggestions[(tagscroll)].childNodes[0].innerHTML;
			//completeTS( TagField, theWord );
		}*/
		return true;
		
	} else if( keyPressed == KEY_TAB && (tagscroll > -1) ) { 
	// tab, with a suggestion highlighted
		//alert( "keyPressed = "+keyPressed+", tagscroll = "+tagscroll + ", suggestions[(tagscroll)].getAttribute('onclick') = "+ suggestions[(tagscroll)].getAttribute('onclick'));
		if( tagscroll < suggestionsLength ) {
			completeTS( suggestions[(tagscroll)] );
		}
		//return true;
		
	} else if( keyPressed == KEY_ESC && (tagscroll > -1) ) { 
	// 'esc', with a suggestion highlighted
		//alert( "keyPressed = "+keyPressed+", tagscroll = "+tagscroll);
		clearActiveSelection(); 
		hideTS();
		return true;
		
	} else { // update the suggestion menu
		clearActiveSelection(); 
		
		nameTag( TagField ); // we need to make sure this element has a name so we can reference it later.
		
		var wordCount = wordArray.length;
		var wordMatch = matchWords(wordArray, alltagArray);
		var wordMatchCount = wordMatch.length;
		if( wordMatchCount > 0 ) {
			var firstWordMatch = wordMatch[0][2]; 
			buildTagMenu2( wordMatch, thePopup, TagField );
			showBox( suggestionbox, TagField,  wordCount-1); // only executes if box isn't already showing
			var currentWord = wordArray.pop().toLowerCase(); // make the comparison case-insensitive
			firstWordMatch = firstWordMatch.toLowerCase();
			if( currentWord == firstWordMatch ) { // if the first suggestion is a perfect match
				makeActive( suggestions[0] );
				tagscroll =0;
				disableSubmit( TagField );
			}
		} else { // if there are no matches
			thePopup.innerHTML = ""; //clear the text
			hideTS(); // and hide that guy.
		}
		return true;
	}
	
}


function buildTagMenu2( wordMatch, thePopup, tagField) {
		/** take the array wordMatch and create html output **/
			//var newVal = "";
			var showString = "";
			var tagFieldId = nameTag(tagField);
			//alert( "tagFieldId = "+tagFieldId);
			thePopup.innerHTML = "";
			for( var i=0; (i< matchCap) && (i < wordMatch.length); i++ ) {  //build the menu from the word matches...
				var theWord = wordMatch[i][2] ;
				var theCount = wordMatch[i][1] ;
				var theClassName ="";
				var htmlWord = fromText2Entity(theWord) ;
				var theWord = fromEntity2Text(htmlWord) ;
				showString = "<span>" + htmlWord + "</span>";
				if( wordMatch[i][0] == '1') {
					theClassName +=" mytag";
				}
				var newLink = document.createElement("a");	
				var newLinkID = nameTag(newLink);
				newLink.theWord = theWord;
				newLink.theWordHTML = htmlWord;
				newLink.tagscroller = i;
				newLink.tagFieldId = tagFieldId;
				newLink.onmousedown = function() {
						activeFlyout=true;
					}
				newLink.onmouseover = function() {
						tagscroll = this.tagscroller;
						makeActive(this);
						disableSubmit( this.tagFieldId );
					}
				newLink.onmouseup = function() {
						//alert("mousep!");
						completeTS(this);
					}
				newLink.className = theClassName;
				newLink.setAttribute('href', 'javascript:void(0);');
				newLink.innerHTML = showString;
				thePopup.appendChild( newLink );
			}
			//thePopup.innerHTML = newVal; //...and populate the html with the menu
			return true;
		}
	
	
	/*post form stuff*/
	
	
function showElement( destElem, parent ) {
	parent = dojo.byId( parent );
	if( parent.value != '' ) {
		var destRow = getFirstParentofType( parent, 'tr' );
	
		var trashCan = getFirstChildwithClass( destRow, 'disabled' );
		dojo.html.removeClass(trashCan, 'disabled');
		
		if(trashCan==null)
			return;
		var fileTable=getFirstParentofType( parent, 'tbody' );
		var nextRow= getFirstChildwithClass( fileTable, 'nodisplay' );
	
		dojo.html.removeClass(nextRow, 'nodisplay');
	}
}

function delAttachRow2( destElem ) {
	destElem = dojo.byId( destElem );
	
	var destRow = getFirstParentofType( destElem, 'tr' );

		var rowInputs = getAllChildrenwithTagname( destRow, 'input' );
		var rowInputCount = rowInputs.length;
		for( var i =0 ; i < rowInputCount; i++ ){
			rowInputs[i].value = "";
		}
		dojo.html.addClass(destRow, 'nodisplay');
}


function add2RemoveList2(id,removeList){
	var removeList=dojo.byId(removeList);
	if(removeList.value == '')
		removeList.value=id;
	else
		removeList.value=removeList.value+','+id;
}



function add2RemoveList(id){
	var removeList=dojo.byId('removelist');
	if(removeList.value == ''){
		removeList.value=id;
	}else{
		removeList.value=removeList.value+','+id;
	}
}
	
function editReply2( elem ) {
	hideNav_now();
	//var elem = byId(elemID);
	var modCont = getFirstParentwithClass( elem, 'mod' );
	var theReply = getFirstChildwithClass( modCont, 'comp-content' );
	var theReplyEditor = getFirstChildwithClass( modCont, 'comp-editor' );
	var theAttachments = getFirstChildwithClass( modCont, 'comp-attachments' );
	var theContent = getFirstChildwithTag( modCont, 'textarea' );
	var contentID = theContent.id;
	//dojo.html.addClass(theReply, 'testHilight');
	if ( !dojo.html.hasClass( modCont, "rep_edit" ) && dojo.html.hasClass( modCont, "rep_neutral" )) {
		//theContent.focus();
		theContent.value = theReply.innerHTML;
		var newHeight = sizeWindow( modCont ); 
		flashElem( modCont );
		if( istinyMCE() ) {
			tinyMCE.execCommand('mceAddControl', false, contentID);
		}
		dojo.html.addClass( modCont, "rep_edit" );
		dojo.html.removeClass( modCont, "rep_neutral" );
		//rateNeutral( elem );

	} else if ( dojo.html.hasClass( modCont, "rep_edit" ) ){
		revertEdits( elem ) 
	} else {
		rateNeutral( elem );
	}
	
}

function storeSubmitId() {
	var now = new Date().getTime()
	document.getElementById("submitIdfield").value = now;
}


/**
 * For use in link and imnage popups 
 * @param elem
 * @return
 */
function submitForm(elem ) {

	if((elem.selectedIndex+1)==elem.length){
		document.getElementById('searchbox').style.display = "block";
		if(document.getElementById('links') !== null) {
			document.getElementById('links').style.display = "none";
		}
	}else{
		var form = document.getElementById('theForm');
	form.submit();
	}
}




function showloader(){
	dojo.lfx.html.fadeShow('morejax', (fadeInRate)).play();
	}


function showClump2( source ) {
	source = byId(source);
	var cell= getFirstParentofType( source, 'td' );
	var elem= getFirstChildwithClass( cell, 'clumpedWikiEdits2' );
	if( elem.style.display=="block" ) {
	 dojo.lfx.html.wipeOut(elem, (fadeInRate)).play();
	 } else {
	 elem.style.height="0px";
	 elem.style.display="block";
	 /*dojo.lfx.html.fadeShow(elem, (fadeInRate)).play();*/
	 dojo.lfx.html.wipeIn(elem, (fadeInRate)).play();
	 }
	}

function imageClass(fileName){
	var start =fileName.lastIndexOf('.');
	if(start == -1) return "ic_16";
	var extension= fileName.substring(start+1);
	return "ic16 f_"+extension;
}

function fileSizeAsString(size){
	if(size<1024) return ""+size+" bytes";
	if(size<(1024*1024)) return ""+((size-(size%1024))/(1024))+"KB";
	var strgMb = ""+((size)/(1024*1024));
	var dotPos= strgMb.indexOf('.');
	var res;
	if(dotPos==-1){
		res=strgMb+".0";
	}else{
		res= strgMb.substring(0,dotPos+2);
	}
	return res+"MB"
}

function storeLocalTime() {
		var nowDate = new Date();
		var nowString = "" + nowDate.getHours() + ":" + nowDate.getMinutes();
		document.getElementById("localTimeField1").value = nowString;
		}

function isLoaded(foId){
	var elem = byId(foId);
	return	getAllChildrenwithClass(elem,'flyoutLoader').length==0;
	
}

function isLinkUsed(elem){
	var link = byId(elem);
	return dojo.html.hasClass(link, 'flyoutupdated'); 
}


function markAsUsed(elem){
	var link = byId(elem);
	dojo.html.addClass(link, 'flyoutupdated');
}
	
function toggleFollow(elem) {
	var toggleElems = elem.parentNode.getElementsByTagName('a');
	for(var i = 0, len = toggleElems.length; i < len; i += 1) {
		toggleElems[i].style.display == "none" ? toggleElems[i].style.display = "" : toggleElems[i].style.display = "none";
	}
}

function confirmSubmit(formChild, message) {
	var form;
	
	function findForm(formChild) {
		if (formChild.tagName === 'FORM') {
			form = formChild;
		} 
		else {
			findForm(formChild.parentNode);
		}
	}
	
	findForm(formChild);
	
	if (!message || confirm(message)) {
		form.submit();
	}
}

function submitFile(formChild) {
	grabTinymceContent('detailsField');
	submitFileOrUpload(['detailsField', 'Tags'], function() {
		storeSubmitId();
		submitLockout();
		doSubmit();
	});
}



function submitUpload(formChild) {
	var fields = ['detailsField'];
	grabTinymceContent('detailsField');
	submitFileOrUpload(fields, function() {
		findParentNode(formChild, 'form').submit();
	});
}

function submitFileOrUpload(fields, callback) {
	for (var i=0, len = fields.length; i < len; i += 1) {
		if (document.getElementById(fields[i]) && document.getElementById(fields[i]).value === '') {
			alert('Please complete all required fields before submitting');
			return;
		}
	}
	callback.call(this);
}

function findParentNode(n, tag) {
	tag = tag.toUpperCase();
	if (n.tagName !== tag) {
		n = findParentNode(n.parentNode, tag);
	}
	return n;
} 


function removeComment(cid, aid) {
	if (rateCommentDelete(cid) !== false) {
		textDecrement(aid + "_commentcount");
		return true;
	}
	return false;
}

var ExistingDraftHandler = function () {
	var that = {}, my = {};
	
	that.setForm = function(formChild) {
		my.findForm(formChild);
	};
	
	that.moveDraft = function(formChild) {
		my.findHidden("existingDraftChoice");
		my.hidden.value = 'move';
		that.submitForm();
	};
	
	that.submitForm = function() {
		my.form.submit();
	};
	
	that.keapDraft = function(formChild) {
		my.findHidden("existingDraftChoice");
		my.hidden.value = 'keap';
		that.submitForm();
	}
	
	my.findForm = function(formChild) {
		if (formChild.tagName === 'FORM') {
			my.form = formChild;
		} 
		else {
			my.findForm(formChild.parentNode);
		}
	};
	
	my.findHidden = function(id) {
		var div, childNodes;
		for (var i = 0, len = my.form.childNodes.length; i < len; i++) {
			if (my.form.childNodes[i].tagName === 'DIV') {
				div = my.form.childNodes[i];
				
				if (div.getElementsByTagName) {
					childNodes = div.getElementsByTagName('input');
				}
				else {
					childNodes = div.childNodes;
				}
				
				for (var j=0; j < childNodes.length; j++) {
					if (typeof childNodes[j].id !== 'undefined') {
						if (childNodes[j].id === id) {
							my.hidden = childNodes[j];
							break;
						}
					}
				}
				break;
			}
		}
	};
	
	return that;
};

function selectBestAnswer(id, message) {
	confirmSubmit(document.getElementById(id), message);
}

function deselectBestAnswer(id, message) {
	confirmSubmit(document.getElementById(id), message);
}

function copySubjectLine(formChild) {
	var div, subjectLineCopy;
	
	function findDiv(formChild) {
		if (formChild.tagName === 'DIV') {
			div = formChild;
		}
		else {
			findDiv(formChild.previousSibling);
		}
	}
	
	findDiv(formChild);
	
	for (var i = 0, len = div.childNodes.length; i < len; i += 1) {
		if (div.childNodes[i].id === 'subjectLineCopy') {
			subjectLineCopy = div.childNodes[i];
			break;
		}
	}
	
	subjectLineCopy.value = document.getElementById('subjectline').value;
}

function scrollToElement(sNode){
	var e = sNode, wh;
	if (typeof sNode === 'string') {
		e = document.getElementById(sNode);
	}
	if (!!window.innerHeight) {
		wh = window.innerHeight;
	}
	else {
		wh = document.documentElement.clientHeight;
	}
	
	function doScroll() {
		if (e.offsetTop !== 0) {
			scrollTo(e.offsetLeft, e.offsetTop - wh/3);
		}
		else {
			setTimeout(doScroll, 1000);
		}
	}
	
	doScroll();
}
