// hold the F1 Name space
var F1CMS = Class.create({
	initialize: function(mainbody, sidebar){
	  this.mainBody = mainbody;
	  this.sideBar = sidebar;
	},
	addObject: function(objname,myclass) {
		if (arguments.length==1) {
			eval('this.' + objname + '= new ' + objname + '()');
		}
		else {
			eval('this.' + objname + '= new ' + myclass + '()');
		}
		eval('this.'+objname+'.app= this') ;
	},
	Data: {}
}) ;


F1 = new F1CMS('bodyContents','coolmenu');

F1UI=Class.create({
	ShowDelay: function(target) {
		if (arguments.length==1) {
			$(target).update('<p align="center"><img border="0" src="images/ajax-loading.gif"></p>');
		}
		else {
			$(F1.mainBody).update('<p align="center"><img border="0" src="images/ajax-loading.gif"></p>');
		}
	},
	UpdateContent: function(tcDocument,tcDate) {
		// Hide Modalbox if present. Testing for it's presence can generate 
		// errors. 
		try {
			Modalbox.hide();
		}
		catch(error) { 
			// ingore any errors 
		}
	
		this.ShowDelay();
		window.location='index.afp#'+escape(tcDocument);
		new Ajax.Updater(F1.mainBody,'showcontent.afp?doc=' + escape(tcDocument));
		window.location.hash = tcDocument;
		this.GetSideBar(tcDocument);
		document.F1CMSContentId=tcDocument;
		// pageTracker is a Google analytics object. This call alerts google to the Ajax hit.
		pageTracker._trackPageview(tcDocument);
	},
	GetSideBar: function(tcDocument){
		new Ajax.Updater(F1.sideBar,'getsidebar.afp?doc=' + escape(tcDocument));
	},
	Calendar: function(startdate){
		this.ShowDelay();
		new Ajax.Request("updatecalendar.afp?startdate=" + startdate, { 
			method:'get',
			onSuccess: function(transport) {
	  			$("bodyContents").update(transport.responseText);
			},
			onFailure: function() { 
				alert('Error contacting server. Please try the link again...');
			} 
		});
		// pageTracker is a Google analytics object. This call alerts google to the Ajax hit.
		pageTracker._trackPageview("updatecalendar.afp?startdate=" + startdate);
	},
	AddLinkTitle: function(linkType) {
		F1.UI.UpdateContent('Upload');
	},
	editContent: function(tcDocument,tcDate) {
		window.location="edittopic4.afp?doc="+ escape(document.F1CMSContentId);	
	}, 
	addContent: function() {
		window.location="edittopic4.afp" ;
	},
	deleteContent: function(tcDocument) {
		if (confirm('Delete topic?'))
		{
			uc();
			// Ajax request top delete the document here.
		}
	},
	cancelChanges: function() {
		if (confirm('Cancel changes?')) 
		{ 
			history.go(-1);
		}
	},
	saveContent: function() {
		var errorDisplay = $("errorDisplay");
		errorDisplay.update('&nbsp;');
		var frmTopic = $('frmTopic');
		tinymce.triggerSave();
		frmTopic.request({ 
			method: 'post',
			onSuccess: function(transport) {
				var updateResult = null ;
				try {
					updateResult = transport.responseText.evalJSON();
				}
				catch(error) {
					updateResult = null ;
				}
				if (updateResult !== null && updateResult.Rows[0].errormessage!=-'') {
					alert(updateResult.Rows[0].errormessage);
				}
				else {
					alert('Topic has been saved');
				}
			},
			onFailure: function() {
				alert('Update failed to contact the server. Please try again...') ;
			} 
		});
	},
	showHelp: function() {
		uc();
	}, 
	siteSearch: function() {
		try {
			 Modalbox.hide(); 
		}
		catch(error) { 
			// ignore any errors 
		}
		var searchString = $F('txtSearch') ;
		
		if (searchString === '' || searchString === 'Enter search text') {
			alert('No search text specified.');
			return false;
		}

		this.ShowDelay();
		var frmSearch = $('frmSearch');
		frmSearch.request({ 
			method: 'post',
			onSuccess: function(transport) {
				$(F1.mainBody).update(transport.responseText);
				// pageTracker is a Google analytics object. This call alerts google to the Ajax hit.
				pageTracker._trackPageview('Search: ' + searchString);
			},
			onFailure: function() {
				alert('Update failed to contact the server. Please try again...') ;
			} 
		});
		// return false prevents the default form submission performed by the browser.
		return false;
	},
	sendMail: function() {
		F1.FormHandler.delegate('frmSendMail') ;
	}	
});

F1.addObject('UI','F1UI');

F1Security=Class.create({
	Login: function() {
		$("loginerror").update('');
		var loginform = $('LoginForm');
		loginform.Security=this;
		loginform.app=this.app;
		loginform.request({ 
			method: 'post',
			onSuccess: function(transport) {
				var loginResult = transport.responseText.evalJSON();
				if (loginResult.Rows[0].errormessage!=='') {
					loginform.Security.Logout(true);
					$("loginerror").update('<p class="formerror">'+loginResult.Rows[0].errormessage + '</p>');
					$('txtUserName').focus();
				}
				else {
					loginform.app.Cookies.set('username',loginResult.Rows[0].username,1);
					loginform.app.Cookies.set('userid',loginResult.Rows[0].userid,1);
					loginform.Security.UserGreeting();
					if (loginResult.Rows[0].admin) {
						loginform.Security.app.UI.UpdateContent('admin');
					}
					else {
						loginform.Security.app.UI.UpdateContent('newsfeed');
					}
				}
			},
			onFailure: function() {
				alert('Login failed to contact the server. Please try again...') ;
			} 
		});
		// return false prevents the default form submission performed by the browser.
		return false;
	},
	Logout: function(logout) {
		if (arguments.length===0) {
			logout=confirm("Log out?");
		}
		if (logout){
			this.app.Cookies.remove('username');
			this.app.Cookies.remove('userid');
			if (arguments.length===0) {
				this.app.UI.UpdateContent('home');
			}
			this.UserGreeting();
		}
	},
	SendReminder: function(control) {
		if (typeof control=='object') {
			control.disable();
		}
		this.app.UI.ShowDelay("reminderresult");
		var emailAddress = $F('txtEmail');
		var results = $("reminderresult");
	
		if (F1.Validate.Validate(emailAddress,'Email','reminderresult')) {
			results.update('');
			new Ajax.Request("callfunction.afp?f=SendReminder", { 
				method:'post', 
				parameters: $('ReminderForm').serialize(),
				onSuccess: function(transport) {
					results.update(transport.responseText);
				},
				onFailure: function() {
					alert('Failed to contact the server. Please try again...') ;
				} 
			});
		}
		if (typeof control=='object') {
			control.enable();
		}
	},
	UserGreeting: function() {
		var userName = this.getUserName();
		var userGreeting = '<p class="UserGreeting"> Welcome ';
		if (! isNull(userName)) {
			userGreeting += userName + ' ' + 
			'<a href="javascript:F1.UI.UpdateContent(\'profile\')">Your Profile</a> ' +
			'<a href="javascript:F1.Security.Logout()">(Logout)</a>' ;
		}
		else {
			userGreeting += 'Guest <a href="javascript:F1.UI.UpdateContent(\'Login\')">(Login)</a>';
		}
		userGreeting +='</p>';
		$('usergreeting').update(userGreeting);
	},
	getUserName: function() { 
		return this.app.Cookies.get('username'); 
	},
	getUserId: function() { 
		return this.app.Cookies.get('userid'); 
	}
})

F1.addObject('Security','F1Security');

F1Social=Class.create({
	addLike: function(cContentId) {
		var likeCount = $('likes'+cContentId);
		new Ajax.Request("addlike.afp?cContentId="+escape(cContentId), { 
			method:'post', 
			onSuccess: function(transport) {
				likeCount.update(transport.responseText);
			},
			onFailure: function() {
				alert('Failed to contact the server. Please try again...') ;
			} 
		});
	},
	showLikes: function(cContentId) {
		var likes = $('likes'+cContentId);
		new Ajax.Request("callfunction.afp?f=NewsFeed.GetLikeList('"+escape(cContentId)+"')", { 
			method:'post', 
			onSuccess: function(transport) {
				likes.update(transport.responseText);
			},
			onFailure: function() {
				alert('Failed to contact the server. Please try again...') ;
			} 
		});
	},
	showComments: function(cContentId) {
		var comments = $('comments'+cContentId);
		new Ajax.Request("callfunction.afp?f=NewsFeed.GetComments('"+escape(cContentId)+"')", { 
			method:'post', 
			onSuccess: function(transport) {
				comments.update(transport.responseText);
			},
			onFailure: function() {
				alert('Failed to contact the server. Please try again...') ;
			} 
		});
	},
	addTweet: function(cContentId) {
		
		uc();
	},
	addComment: function(cContentId) {
		var comments= $('comments'+cContentId);
		new Ajax.Request("callfunction.afp?f=newsfeed.shareform('"+escape(cContentId)+"')", { 
			method:'post', 
			onSuccess: function(transport) {
				comments.update(transport.responseText);
			},
			onFailure: function() {
				alert('Failed to contact the server. Please try again...') ;
			} 
		});
		
	},
	facebook: function(cContentId) {
		uc();
	},
	share: function(cContentId) {
		var shareForm=$("shareform"+cContentId);
		shareForm.request( { 
			method:'post', 
			onSuccess: function(transport) {
				F1.Social.showComments(cContentId) ;
			},
			onFailure: function() {
				alert('Failed to contact the server. Please try again...') ;
			} 
		});
	}
})

F1.addObject('Social','F1Social');

//F1.Data = {} ;

F1Validate=Class.create({
	ErrorMessage: '',
	// options can be a comma delimited list of methods of the validator object or functions to call.
	// errordisplay is the HTML component to display any errors in. If it's not passed an alert is issued.
	Validate: function(ControlOrValue, options, errordisplay) {
  		var valid = true;
  		var validators = options.split(',');
  		for (var i=0;i<=validators.length-1;i++) {
  			var fnName = 'this.'+validators[i]
 			if (typeof eval(fnName) == 'function') {
 				var testValue = (typeof ControlOrValue=='object')?ControlOrValue.value:ControlOrValue;
 				valid = eval(fnName+'(testValue)');
 				if (valid===false) {
 					this.ShowError(errordisplay);
 					if (typeof ControlOrValue == 'object') {
 						ControlOrValue.focus();
 						break;
 					}
 				}
 				else {
 					this.ClearError(errordisplay);
 				}
 			}
  		}
  		return valid;
	},
	ShowError: function(errordisplay) {
		if (typeof errordisplay=='string') {
			$(errordisplay).update('<p class="formerror">'+this.ErrorMessage+'</p>');
		}
		else {
			alert(this.ErrorMessage);
		}
	},
	ClearError: function(errordisplay) {
		if (typeof errordisplay=='string') {
			$(errordisplay).update('');
		}
	},
	Email: function(testValue) {
		var valid = true
		if (testValue==='') {
			this.ErrorMessage = 'Email address cannot be empty.';
			valid = false;
		}
		else {	
			var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
			if (!filter.test(testValue)) {
				this.ErrorMessage = testValue + ' is not a valid email address.';
				valid = false;
			}
		}
		return valid
	}, 
	valueRequired: function(testValue) {
		var valid = true
		if (testValue==='') {
			this.ErrorMessage = 'Value required.';
			valid = false;
		}
		return valid
	}
	
})

F1.addObject('Validate','F1Validate')

//F1Cookies = Class.create( {
F1Cookies = Class.create( {
	set: function(name,value,expiresDays,path) {
		var cookie=name + "=" + value;
		if (expiresDays) {
			var now = new Date();
			now.setTime(now.getTime()+(expiresDays*24*60*60*1000));
			cookie+="; expires="+now.toGMTString();
		}
		if (path) {
			cookie+="; path="+path;
		}
		else {
			cookie+="; path=/";
		}
		document.cookie = cookie;
	},
	get: function(name) {
		var cookieVal=null
		name += "=";
		var cookies = document.cookie.split(';');
		for(var i=0;i < cookies.length;i++) {
			var cookie = cookies[i];
			while (cookie.charAt(0)==' ') {
				cookie = cookie.substring(1,cookie.length);
			}
			if (cookie.indexOf(name) === 0) {
				cookieVal = cookie.substring(name.length,cookie.length);
			}
		}
		return cookieVal;
	},
	remove: function (name) {
		this.set(name,"",-1);
	}
})

F1.addObject('Cookies','F1Cookies');

F1Form = Class.create( {
	initialize: function(frmHandler) {
		if (frmHandler){
			this.frmHandler = frmHandler;
		}
	},
	delegate: function(formName) {
		myForm=$(formName);
		myForm.request({ 
			method: 'post',
			parameters: myForm.serialize(),
			onSuccess: function(transport) {
				var Result = null;
				try {
					Result = transport.responseText.evalJSON();
				}
				catch(error) {
					Result = null;
				}
				if (Result !== null && Result !=='') {
					if (varExists(Result.Rows[0].errormessage) && Result.Rows[0].errormessage !== null) {
						alert(Result.Rows[0].errormessage);
					}
					else if (varExists(Result.Rows[0].successmessage) && Result.Rows[0].successmessage !== null) {
						alert(Result.Rows[0].successmessage);
						
					}
					else if (varExists(Result.Rows[0].resultmessage) && Result.Rows[0].resultmessage !== null) {
						$(F1.mainBody).update(Result.Rows[0].resultmessage);
					}
					else {
						$(F1.mainBody).update(transport.responseText);
					}
					if (varExists(Result.Rows[0].callback) && Result.Rows[0].callback !== null) {
						eval(Result.Rows[0].callback)
					}
				}
				else {
					// add code here to look for instructions in the result variable.
					// Possible instructions: message, content, topic
					// information saved is the catch all when no instructions are provided.
					// check for an exception in the returned text as well.
					alert('Information Saved');
					$(F1.mainBody).update(transport.responseText);
				}
			},
			onFailure: function() {
				alert('Login failed to contact the server. Please try again...') 
			} 
		});
		// We are always overriding the default submission.
		return false;
	},
	bind: function(pk) {},
	render: function() {}
})

F1.addObject('FormHandler','F1Form');

function slideShow(frequency, slideFolder) {
	mySlideShow = new F1.slideShow(frequency, slideFolder);	
}

F1.slideShow = Class.create(PeriodicalExecuter,{
  initialize: function(frequency, slideFolder) {
  	F1.UI.ShowDelay();
  	this.slideFolder = slideFolder;
    this.callback = this.nextSlide;
    this.frequency = frequency;
    this.currentlyExecuting = false;
    this.images = '';
    this.registerCallback();
  	this.getSlides();    
  },
  imageCount: 0,
  nextImage: 0,

  nextSlide: function() {
  	if (this.nextImage===0) {
	  	$(F1.mainBody).update('<div id="F1slideshow" style="display:none;height:500px;"></div>')
	}
	if (this.imageCount>0) {
  		if (this.nextImage>this.imageCount-1){
		 	var finished = new Template( '<p>End of slideshow. <a href="javascript:slideShow(#{frequency},\'#{slideFolder}\');">Click here</a> to run again.</p>');
			var showMessage = finished.evaluate({frequency: this.frequency, slideFolder: this.slideFolder}) ;
  			$('F1slideshow').insert( { after:showMessage} );
  			this.stop();
  		}
  		else {		
  			var slideDiv = $('F1slideshow');
  			if (slideDiv !==null) {
		    	slideDiv.update(this.getHTML(this.nextImage));
		    	if (this.nextImage===0) {
			    	slideDiv.appear( {duration: 2} );
			    }
			    else {
	
					slideDiv.blindDown( {duration: 2 } );		    
			    }
		  		this.nextImage++; 
		  	}
		  	else {
		  		this.stop();
		  	}
	  	}
  	}
  },
  
  getSlides: function() {
  	var currentShow = this;
  	new Ajax.Request("callfunction.afp?f=slideshow.GetImageList('"+escape(this.slideFolder)+"')", { 
		method:'get',
		onSuccess: function(transport){
		  if (transport.responseText.isJSON()) {
		    // trailing spaces, carriage returns, and backslashes within the fields
		    // can cause evalJSON to fail. 			
		    currentShow.images =  transport.responseText.evalJSON().Rows;
			currentShow.imageCount = mySlideShow.images.length;
		  }
		},
		  onFailure: function(){ alert('Slideshow images failed to load...') } 
		});
  	},
  
  getHTML: function (imageNo) {
 	var HTML = '<div><img border="0" height="500" src="Slideshows\/' + this.slideFolder + '\/' + this.images[imageNo].cimage + '"></div>';
 	return HTML ;
 }
})

function isNull(tvVar) {
    return typeof tvVar == 'object' && !tvVar;
}


function ShowPopup(oCaller,tcDocument)
{
	var oPopup = $('Popup')
	var pos = getXY(oCaller);
	oPopup.style.display="block";
	oPopup.style.left = pos[0];
    oPopup.style.top = pos[1]+20;
   
    new Ajax.Updater("Popup","showcontent.afp?doc=" + escape(tcDocument) + "&img=off");
}


function HidePopup(oCaller)
{
	var oPopup = $('Popup')
	oPopup.hide();
}

function getXY(oObject){
	var nX = 0;
	var nY = 0;
	if (oObject.offsetParent) {
		do {
			nX += oObject.offsetLeft;
			nY += oObject.offsetTop;
		} while (oObject == oObject.offsetParent);
	}
	return [nX,nY];
}

 
F1.RotatingBanners = Class.create(PeriodicalExecuter,{
  initialize: function(target, frequency, newWindow) {
  	this.getImages();
    this.callback = this.rotateBanner;
    this.target=target;
    this.frequency = frequency;
    this.currentlyExecuting = false;
    this.bannerImages = '';
    this.registerCallback();
    this.newWindow=(arguments.length==3)?newWindow:false;
  },
  imageCount: 0,
  nextImage: Math.floor(Math.random()*11),

  rotateBanner: function() {
	if (this.imageCount>0) {
  		if (this.nextImage>this.imageCount-1){
  			this.nextImage=0;
  		}   		
    	$(this.target).update(this.getHTML(this.nextImage));
  		this.nextImage++; 
  	}
  },
  
  getImages: function() {
  	var currentBanners = this;
  	new Ajax.Request("callfunction.afp?f=getBannerImages",
	{ 
		method:'get',
		onSuccess: function(transport){
		  if (transport.responseText.isJSON()) {
		    // trailing spaces, carriage returns, and backslashes within the fields
		    // can cause evalJSON to fail. 			
		    var bannerImages = transport.responseText.evalJSON();
		    currentBanners.bannerImages = bannerImages.Rows;
			currentBanners.imageCount = rotatingBanners.bannerImages.length;
		  }
		},
		  onFailure: function(){ alert('Banner images failed to load...') } 
		});
  	},
  
  getHTML: function (imageNo) {
   	var HeightStr = '';
   	if (this.bannerImages[imageNo].nheight!==0) {
   		// need to read height value from JSON
   		HeightStr = 'height="' + this.bannerImages[imageNo].nheight + '"';
   	}
 	var HTML = '<img border="0" ' + HeightStr + ' src="' + this.bannerImages[imageNo].cimage + '">';
 	if (this.bannerImages[imageNo].ctarget!=='') {
 		if (this.newWindow) {
	 		HTML = '<a target="_blank" ' + 'href="' + this.bannerImages[imageNo].ctarget + '">' + HTML + '</a>';
 		}
 		else {
	 		HTML = '<a href="' + this.bannerImages[imageNo].ctarget + '">' + HTML + '</a>';
 		}
 	}
 	return HTML ;
 }
})

function uc() {
	alert('Under construction!');
}


function startTinyMCE() {
	tinyMCE.init({ mode : "textareas", table_inline_editing : true});
}

function startTE(cTextArea) {
	new TINY.editor.edit(cTextArea,	{	
		id:cTextArea, 
		cssclass:'te',
		controlclass:'tecontrol',
		rowclass:'teheader',
		dividerclass:'tedivider',
		controls:['bold','italic','underline','strikethrough','|','subscript','superscript','|',
			  'orderedlist','unorderedlist','|','outdent','indent','|','leftalign',
			  'centeralign','rightalign','blockjustify','|','unformat','|','undo','redo','n',
			  'font','size','style','|','image','hr','link','unlink','|','cut','copy','paste','print'],
		footer:true,
		fonts:['Verdana','Arial','Georgia','Trebuchet MS','Calibri'],
		xhtml:true,
		cssfile:'style.css',
		bodyid:'editor',
		footerclass:'tefooter',
		toggle:{text:'source',activetext:'wysiwyg',cssclass:'toggle'},
		resize:{cssclass:'resize'}
	})
}	


function clearControl(object) {
	object.value=''
}

function varExists(tvVar) {
	return typeof(tvVar) !== 'undefined';
}

