var currentSpacer="";
var messageTimer;
var isIE = (navigator.appName == "Microsoft Internet Explorer");
//var oAutoComp;
//var arrTags;
var processor = getAjaxProcessor("/worshipPlan/planElementDiv.ajp");
var otherElementProcessor = getAjaxProcessor("/worshipPlan/planOtherElementDiv.ajp");
var libraryElementProcessor = getAjaxProcessor("/worshipPlan/planExistingMediaElements.ajp");

LIFEWAY.worshipplan = new function(){
	
	var dropDiv = "";
	var count=0;
	var _logged_on = "false";
	var selectForDeleteDiv;
	var sortedColumn=1;	
	var offset = 0;
	var yuiTable = null;
	var yuiDataSource = null;
	var retrievingResults = false;
	var retrievedAllRecs = false;
	var createCal;		
	var updateCal;	
	var zi = navigator.appName.toUpperCase().match(/MICROSOFT INTERNET EXPLORER/) != null ? 0 : 1000;
	
	var notes_field_text = "";
	var currentElementPosition = "";
	var currentParticipantId = "-1";
	var notesEditor;
	var currentHighlightedPos ="";
	

	var imgFalse = '/images/false.gif';
	var imgTrue = '/images/true.gif';
	
	return {
		moveElement : function(ev) 
		{		
			var temp = Sortable.serialize('planElements', {name:'ep'});
			var subs2 = temp.replace(/&/g,'');
			var subs = subs2.split('ep[]=');
			var elementPositionParams = subs.join(',').substr(1);			
			var params='elementPositions=' + elementPositionParams ;
			var url = '/processElement/reorderElements';
			sendAjaxRequest(url, 'POST', true, params, addElementSuccess, addElementFailure);
		
		},
		
		initCreateCalendar : function () { 
		    createCal = new YAHOO.widget.Calendar("createCal","createCalendar"); 
			createCal.selectEvent.subscribe(getDate, createCal, true); 
			YAHOO.util.Event.addListener('showCreateCalendar', 'click', showCreateCal); 
		},
		
		initUpdateCalendar : function () { 
		    updateCal = new YAHOO.widget.Calendar("updateCal","updateCalendar"); 
			updateCal.selectEvent.subscribe(updateDate, updateCal, true); 
			YAHOO.util.Event.addListener('showUpdateCalendar', 'click', LIFEWAY.worshipplan.showUpdateCal); 
		},
		
		showUpdateCal : function() { 
		    var xy = YAHOO.util.Dom.getXY('showUpdateCalendar'); 
		    var date = YAHOO.util.Dom.get('worshipPlanDate').innerHTML; 
		    if (date) { 
		        updateCal.cfg.setProperty('selected', date); 
				updateCal.cfg.setProperty('close', true); 
		        updateCal.cfg.setProperty('pagedate', new Date(date), true); 
		        updateCal.render(); 
		    } 
		    YAHOO.util.Dom.setStyle('updateCalendar', 'display', 'block'); 
		    xy[1] = xy[1] - 80; 
			xy[0]=730;
		    YAHOO.util.Dom.setXY('updateCalendar', xy); 
		},

		initPlanNameEditor : function () { 
			new Ajax.InPlaceEditor('worshipPlanName' , 
				'/worshipPlan/updateNameInRootNode/' , 
				{
					ajaxOptions:{onFailure:LIFEWAY.worshipplan.updatePlanNameFailure, onSuccess:LIFEWAY.worshipplan.editPlanNameSuccess},
					okButton:false,cancelLink:false,cols:25,submitOnBlur:true, highlightcolor: '#CECECE',
					callback:LIFEWAY.worshipplan.createWorshipPlanEditParams
				});
		},
		
		buildWorshipPlanOtherElementDiv : function () {
			var childList = $('planElements').getElementsByClassName("spacerContainer");
			var pos = childList.length;
			$('elementType').value = 'other';
			var params = buildGenericParams() + "&position=" + pos;		
			var url = '/processElement/addElement';
			sendAjaxRequest(url, 'POST', true, params, addElementSuccess, addElementFailure);
		}, 
		
		buildWorshipPlanOtherElementDraggableDiv : function (el, el2, ev){
			$('elementType').value = 'other';

			var divPosition = getDropElementPosition(ev.clientX, ev.clientY, 'planElements');
			hideSpacer();
			currentHighlightedPos = divPosition;
			LIFEWAY.worshipplan.doSomething(el.id, divPosition,0);
		  	
			return true;
		},
		
		buildWorshipPlanLibraryElementDraggableDiv : function (el, el2, ev){
			$('elementType').value = 'library';

			var divPosition = getDropElementPosition(ev.clientX, ev.clientY, 'planElements');
			hideSpacer();
			currentHighlightedPos = divPosition;
			LIFEWAY.worshipplan.doSomething(el.id, divPosition,0);
		  	
			return true;
		},
		
		buildWorshipPlanElementDiv : function (el, el2, ev){
			$('elementType').value = 'music';
			if ($('wp_context_help').style.display == 'block') {
				$('wp_context_help').hide();
			}

			//$('searchResultsMsg').hide();
			var divPosition = getDropElementPosition(ev.clientX, ev.clientY, 'planElements');
			hideSpacer();
			currentHighlightedPos = divPosition;
			LIFEWAY.worshipplan.doSomething(el.id, divPosition,0);
		  	
			return true;
		},
		buildPublicWorshipPlanElementDiv : function (el, el2, ev){
			$('elementType').value = 'music';
			if ($('wp_context_help').style.display == 'block') {
				$('wp_context_help').hide();
			}

			//$('searchResultsMsg').hide();
			var divPosition = getDropElementPosition(ev.clientX, ev.clientY, 'planElements');
			hideSpacer();
			currentHighlightedPos = divPosition;
			LIFEWAY.worshipplan.doSomething(el.id, divPosition,1);
		  	
			return true;
		},
		
	    doSomething : function(id, pos,pbl) {
			$('wp_context_help').hide();
			var filterType = $('elementType').value;
			var selectFunctions = {
				"video" : buildMusicVideoParams,
				"music" : buildMusicVideoParams,
				"scripture" : buildScriptureParams,
				"sermon" : buildSermonOtherParams,
				"other" : buildGenericParams,
				"library" : buildLibraryParams
			};
			
			var params = processSelectedElement(selectFunctions, filterType, id);
			params = params + "&position=" + pos;
			var url = '/processElement/addElement';
			sendAjaxRequest(url, 'POST', true, params, addElementSuccess, addElementFailure);
		},
		
		removeElementFromPlan : function (pos, checkPrompt){
			var params = "position=" + pos;
			if (_logged_on == 'true' && checkPrompt){
				if($F('promptOffBox') && $F('promptOffBox')== 'on') {
					LIFEWAY.dialog.turnOffConfirmDialog($('promptOffBox'));
				}
			}
			var url = '/processElement/removeElement/';
		   	sendAjaxRequest(url, 'POST', true, params, deleteSuccess, deleteFailure);
		}, 
		
		updateTotalDuration : function() {
			var url = '/processElement/updateTotalDuration';
		   	sendAjaxRequest(url, 'GET', true, null, updateTotalDurationDiv);
		},		
		
		updateDuration : function() {
			var url = '/processElement/updateDuration';
		   	sendAjaxRequest(url, 'GET', true, updatePlanElementDurationSuccess, updatePlanElementDurationFailure);
		},		

		deleteFromPlan : function(pos, hasNoPromptPref){
			selectForDeleteDiv = $('spacerContainer_' + (pos));
			Droppables.remove(selectForDeleteDiv);
			if (hasNoPromptPref == 'false' && LIFEWAY.dialog.isPromptOffValue()){
				var processor = getAjaxProcessor("/confirmDialogWithCheckbox.ajp");
		    	var returnedData = processor({YesSelect: 'LIFEWAY.worshipplan.removeElementFromPlan',
		    								  NoSelect: 'LIFEWAY.dialog.removeConfirmationDialog',
		    								  pos: pos,
		    								  loggedOn: _logged_on,
		    								  checkboxText: 'Do not remind me again',
		    								  confirmText : "Are you sure?" });
		    	LIFEWAY.dialog.displayDialog(returnedData,'confirmationMessage');
			}
			else{
				LIFEWAY.worshipplan.removeElementFromPlan(pos, null);
			}
		},
		
		checkForViewablePlan : function(worshipPlan, userData,flg)
		{
			if(flg==1)
			{
				processor = getAjaxProcessor("/worshipPlan/publicPlanElementDiv.ajp");
			    otherElementProcessor = getAjaxProcessor("/worshipPlan/publicPlanOtherElementDiv.ajp");
			    libraryElementProcessor = getAjaxProcessor("/worshipPlan/publicPlanExistingMediaElements.ajp");
			}
			var url = window.location.href;
			var url_parts = url.split('/');
			var domain_name_parts = url_parts[2].split(':');
			var domain_name = domain_name_parts[0];
			var port_number = domain_name_parts[1];
			var m1 ;var m0 ;var m2 ;var m3 ;var m4;
			if(isIE)
			{
				 m1 = document.createElement('<meta name="og:title" content="LifeWayWorship.com -'+worshipPlan.WorshipPlan.planName+' - '+worshipPlan.WorshipPlan.displayDate +'"/>');			
				 m0 = document.createElement('<meta name="og:type" content="songs"/>');				
				 m2 = document.createElement('<meta name="og:url" content="http://'+domain_name+'/worshipPlan/showWorshipPlan/'+worshipPlan.WorshipPlan.id+'"/>');			
				
				if(port_number != null && port_number.length>0)
				{
					m2 = document.createElement('<meta name="og:url" content="http://'+domain_name+':'+port_number+'/worshipPlan/showWorshipPlan/'+worshipPlan.WorshipPlan.id+'"/>');			
				}						
				m3 = document.createElement('<meta name="og:image" content="http://s3.amazonaws.com/worship/graphics/logo/LifewayWorshipVertical.jpg"/>');
				m4 = document.createElement('<meta name="description" content="LifeWayWorship.com -'+worshipPlan.WorshipPlan.planName+' - '+worshipPlan.WorshipPlan.displayDate +'"/>');			

			}else
			{
			 m1 = document.createElement('meta');
			 m1.setAttribute("property","og:title");
			 m1.setAttribute("content","LifeWayWorship.com -"+worshipPlan.WorshipPlan.planName+" - "+worshipPlan.WorshipPlan.displayDate);
			
			 m0 = document.createElement('meta');
			 m0.setAttribute("property","og:type");
			 m0.setAttribute("content","song");
			
			 m2 = document.createElement('meta');
			 m2.setAttribute("property","og:url");
			 var content ="http://"+domain_name+"/worshipPlan/showWorshipPlan/"+worshipPlan.WorshipPlan.id;
					
			 if(port_number != null && port_number.length>0)
			 {
				content="http://"+domain_name+":"+port_number+"/worshipPlan/showWorshipPlan/"+worshipPlan.WorshipPlan.id;
			 }			
			 m2.setAttribute("content",content);
			
			 m3 = document.createElement('meta');
			 m3.setAttribute("property","og:image");
			 m3.setAttribute("content","http://s3.amazonaws.com/worship/graphics/logo/LifewayWorshipVertical.jpg");
			
			 m4 = document.createElement('meta');
			 m4.setAttribute("property","description");
			 m4.setAttribute("content","LifeWayWorship.com -"+worshipPlan.WorshipPlan.planName+" - "+worshipPlan.WorshipPlan.displayDate);
			
			}
			
			var headhtml = document.getElementsByTagName('head').item(0);
			var titlehtml = document.getElementsByTagName('meta').item(0);
			
			headhtml.appendChild(m1);
  		    headhtml.appendChild(m0);
        	headhtml.appendChild(m2);
			headhtml.appendChild(m3);
			headhtml.appendChild(m4);
			
			//headhtml.insertBefore(m1,titlehtml);
	
			var htmlele = document.getElementsByTagName('html').item(0);
			htmlele.setAttribute('xmlns:og', 'http://ogp.me/ns#');
			
			
			
			if((location.href.indexOf("showWorshipPlan") > -1)||(location.href.indexOf("showPublicWorshipPlan")>-1))
			{
				
				var user;
				if (userData) {
					user = eval(userData);
				}
				$('planDisabled').hide();				
				setPlanTitleBar(worshipPlan.WorshipPlan.planName, worshipPlan.WorshipPlan.displayDate);
				$('planId').value = worshipPlan.WorshipPlan.id;
				loadWorshipPlan(worshipPlan, user);
			}
		},		

		editSongMap : function(position, versionId) {
			location.href = '/processElement/map/' + versionId + '?position=' + position;
		},

		createWorshipPlanEditParams : function(form, value){		
			return 'planName=' + encodeURIComponent(value);
		},

		createWorshipPlanElementEditParams : function(form, value){
			return 'planElementName=' + encodeURIComponent(value) + '&position=' + form.id.split('-')[1];
		},
		
		createWorshipPlanElementReferenceEditParams : function(form, value){
			return 'title=' + encodeURIComponent(value) + '&position=' + form.id.split('-')[1];
		},
		
		createWorshipPlanElementDurationEditParams : function(form, value){
			return 'time=' + encodeURIComponent(value) + '&position=' + form.id.split('-')[1];
		},

		editPlanNameFailure : function(oReq){
			var jsonData = eval('(' + oReq.responseText + ')');
			LIFEWAY.common.displayAlertDialog(jsonData.errorMessage);
			if(jsonData.planId) {
				$("planName_" + jsonData.planId).innerHTML = jsonData.planName;
			}
		},
		
		updatePlanNameFailure : function(oReq){
			var jsonData = eval('(' + oReq.responseText + ')');
			var error = jsonData.JSONMessageImpl.message;
			LIFEWAY.common.displayAlertDialog(error.errorMessage);
			$("worshipPlanName").innerHTML = error.planName;
		},

		updatePlanElementNameSuccess : function(oReq){
			
		},

		updatePlanElementNameFailure : function(oReq){
			var jsonData = eval('(' + oReq.responseText + ')');
			LIFEWAY.common.displayAlertDialog(jsonData.errorMessage);
			$("element-"+jsonData.position).innerHTML = jsonData.planElementName;
		},
		
		updatePlanElementReferenceSuccess : function(oReq){
			var jsonData = eval('(' + oReq.responseText + ')');
			$("details-"+jsonData.position).innerHTML = jsonData.title;
		},

		updatePlanElementReferenceFailure : function(oReq){
			var jsonData = eval('(' + oReq.responseText + ')');
			LIFEWAY.common.displayAlertDialog(jsonData.errorMessage);
			$("details-"+jsonData.position).innerHTML = jsonData.title;
		},
		
		updatePlanElementDurationSuccess : function(oReq){
			var url = '/processElement/updateTotalDuration';
		   	sendAjaxRequest(url, 'GET', true, null, updateTotalDurationDiv);
		},

		updatePlanElementDurationFailure : function(oReq){
			var jsonData = eval('(' + oReq.responseText + ')');
			LIFEWAY.common.displayAlertDialog(jsonData.errorMessage);
			$("elementDuration-"+jsonData.position).innerHTML = jsonData.duration;
		},

		editPlanNameSuccess : function(oReq){
		},

		toggleResultsLock : function(id) {
			var el = $(id);
			if(el.getAttribute("locked")){
				el.removeAttribute("locked");
				LIFEWAY.common.toggleElementWithImage(el.getElementsByTagName("img")[1], 
					"/images/filler_images/play_arrow_down.gif");
			} else {
				el.setAttribute("locked", "true");
				LIFEWAY.common.toggleElementWithImage(el.getElementsByTagName("img")[1], 
					"/images/lock.png");
			}
		},
		
		expandVersions : function(id) {
			var el = $(id);
			if(el.parentNode.getAttribute("locked") == null) { 
				Element.show(id);
				LIFEWAY.common.highlight($(el));
				LIFEWAY.common.toggleElementWithImage(el.parentNode.getElementsByTagName("img")[1], 
					"/images/filler_images/play_arrow_down.gif");
			}
		},
		
		collapseVersions : function(id) {
			var el = $(id);
			if(el.parentNode.getAttribute("locked") == null) { 
				Element.hide(id);
				LIFEWAY.common.highlight($(el));
				LIFEWAY.common.toggleElementWithImage(el.parentNode.getElementsByTagName("img")[1], 
					"/images/filler_images/play_arrow.gif");
			}
		},
		
		displayElementInformation : function(versionId) {
			var url = '/digitalAsset/elementInfo/' + versionId; // + '?t=' + new Date().getTime();
			sendAjaxRequest(url, 'POST', true, null, displayElementInformationSuccess, displayElementInformationFailure);
			
			function displayElementInformationSuccess(oReq){
				LIFEWAY.dialog.displayDialog(oReq.responseText, 'iscreen');
				//$('searchString').blur();
				//LIFEWAY.worshipplan.initTags(); 
				//LIFEWAY.worshipplan.initVersionTags(versionId);
			}
			
			function displayElementInformationFailure(oReq){
				alert("Unable to view the information at this time.");
			}
			
		},
		
		editYourTags : function(){
			$('iscreen_edittags').show();
			$('yourTagsView').hide();
			$('tagsEditBtn').hide();
			$('tagsSaveBtn').show();
			$('tagsinput').focus()
		},
		
		viewAllLyrics : function(){
//			$('iscreen').hide();
			$('displayLyrics').show();			
		},

		closeAllLyrics : function(){
			$('displayLyrics').hide();			
			//$('iscreen').show();
		},
		
		displayPrintDialog : function(canPrint){
			if (canPrint) {
				new Ajax.Request('/worshipPlan/printOptions', {
					method: 'POST',
					on200: function(oReq) { 
						LIFEWAY.dialog.displayDialog(oReq.responseText, 'popup');
						LIFEWAY.worshipplan.replaceChecks('printOptionsForm', 'print');
					},
					on206: function(oReq) { oReq.responseText.evalScripts(); }
				});
			} else {
				LIFEWAY.dialog.displayDialog($('registerToPrintDialog').innerHTML, 'registerToPrintDialog');
			}					
		},
		displayPublicPrintDialog : function(canPrint,planId)
		{
			if (canPrint) 
			{
				//alert('/worshipPlan/publicPrintOptions/'+planId);
				new Ajax.Request('/worshipPlan/publicPrintOptions/'+planId, {
					method: 'POST',
					on200: function(oReq) { 
						LIFEWAY.dialog.displayDialog(oReq.responseText, 'popup');
						LIFEWAY.worshipplan.replaceChecks('printOptionsForm', 'print');
					},
					on206: function(oReq) { oReq.responseText.evalScripts(); }
				});
			} else {
				LIFEWAY.dialog.displayDialog($('registerToPrintDialog').innerHTML, 'registerToPrintDialog');
			}					
		},
		displayElementInformationForSearchResults : function(versionId, elementTitle) {
			var processor = getAjaxProcessor("/iscreen.ajp");
			
			var multiple = false;
			var returnedData = processor({title : elementTitle,
										  versionId:  versionId,
										  multiple: multiple});
			LIFEWAY.worshipplan.showIScreen(returnedData);	
			
			//turn off the 'add to worship plan' div
			
			$('iscreen_version').innerHTML = elementTitle;
		},
		
		showIScreen : function (returnedData) {
			LIFEWAY.dialog.displayDialog(returnedData,'iscreen');
			//LIFEWAY.common.toggleVisibility('iscreen_add', false);
			LIFEWAY.common.toggleVisibility('viewLyrics', false);
			LIFEWAY.common.toggleVisibility('tagsElement', false);
			//initTags();
		},
		
		addItemsToCart : function(){
			var backgroundColor = '#ffffff';
			
			var atLeastOneSelection = false;
			var checkboxes = $$('.chex');
				checkboxes.each(function(item) {
					if(item.checked){
						atLeastOneSelection = true;
					}
				});
			if(atLeastOneSelection){
				$('configureCartForm').submit();
			}else{
				$('popupErrorMsg').show();
				//$('popupErrorMsg').style.opacity=1;
				new Effect.Fade('popupErrorMsg', {startcolor:'#FF0000', 
				endcolor:backgroundColor, restorecolor:backgroundColor, duration: 3.5, from:1.0, to:0.0});
			}
			
		},
		
		searchTags : function(queryText){
			var url = '/songTag/submitSearch';
			var params = 'queryText=' + encodeURIComponent(queryText);
		   	sendAjaxRequest(url, 'POST', true, params, searchTagsSuccess, searchTagsFailure);
			
			function searchTagsSuccess(oReq){
				return oReq.responseText;
			};
			
			function searchTagsFailure(oReq){
				LIFEWAY.common.displayAlertDialog(eval('(' + oReq.responseText + ')'));
			};
		},

		toggleAddElementLink : function(el) {
			if(el[el.selectedIndex].value != -1) {
				LIFEWAY.common.toggleVisibility('iscreen_add', false);
				LIFEWAY.common.toggleVisibility('viewLyrics', false);
				LIFEWAY.common.toggleVisibility('tagsElement', false);
				$('songVersionId').value = el[el.selectedIndex].value;
				
			} else {
				LIFEWAY.common.toggleVisibility('iscreen_add', true);
				LIFEWAY.common.toggleVisibility('viewLyrics', true);
				LIFEWAY.common.toggleVisibility('tagsElement', true);

			}
		},
		
		submitUserSongTags : function(){
			var form = document.getElementById("tagForm");
			var params = Form.serialize(form);
			var url = "/songTag/updateTag";
		   	sendAjaxRequest(url, 'POST', true, params, submitUserSongTagsSuccess, submitUserSongTagsFailure);
		},
		
		createWorshipPlan : function(){
			var params = Form.serialize($('worshipPlanForm'));
			var url = "/worshipPlan/createWorshipPlan";
			
		   	sendAjaxRequest(url, 'POST', true, params, createWorshipPlanSuccess, createWorshipPlanFailure);
		},
		
		searchForVersions : function() {
			if($F('searchString') != '') {
//				var params = encodeURIComponent(Form.serialize('worshipPlanMusicSearch'));
//				searchString
				var params = 'searchString=' + encodeURIComponent($F('searchString'));
				params = params + '&offset=' + offset;
				var url = '/search/submitSearch?';
				var divId = 'musicSearchResults';
				retrievedAllRecs = false;
				offset = 0;
				createResultsTable(divId, params, url);
			}
		},
		
		searchForExistingLibrary : function() {
			var params = 'offset=' + offset;
			var url = '/worshipPlan/existingLibrary?';
			var divId = 'librarySearchResults';
			retrievedAllRecs = false;
			offset = 0;
			createResultsTable(divId, params, url);
		},
		
		showPurchasable : function() {
			// first see if there is even anything in this plan
			var planElements = $('planElements').getElementsByClassName('spacerContainer');
			if(!planElements || planElements.length == 0) {
				LIFEWAY.common.displayErrorMessage(
					"Please add one or more music elements to your plan. Once music elements are in your plan, you can choose from available audio and print downloads for purchase.");
				return;
			}
		
			var url = '/worshipPlan/purchasableItems';
			sendAjaxRequest(url, 'GET', true, null, displayPurchasableItemsSuccess, displayPurchasableItemsFailure);	
		
		},
		
		printPreview : function() {
			var checked = false;
			for(x=0; x<document.forms['printOptionsForm'].print.length && !checked; x++){
				if(document.forms['printOptionsForm'].print[x].checked){
					checked = true;
				}
			}
			if(!checked){
				$('printErrorMsg').innerHTML = "You must select a Print Option before you can print";
				$('printErrorMsg').show();
				new Effect.Fade('printErrorMsg', {startcolor:'#FF0000', 
				endcolor:'white', restorecolor:'white', duration: 3.5, from:1.0, to:0.0});
				return false;
			}
			var params = Form.serialize($('printOptionsForm'));
			window.open("/worshipPlan/print?" + params,"printPreviewWindow","width=800, height=600, top=100, left=100, toolbar=0, menubar=1, location=0, status=0, scrollbars=1, resizable=1");
			LIFEWAY.dialog.removeDialog('popup');
		},
		
		initTags : function(){
			var url = '/songTag/findUserTags';
	   		sendAjaxRequest(url, 'POST', true, null, findUserTagsSuccess, findUserTagsFailure);
		},
		initVersionTags : function(versionId){
			var url = '/songTag/findUserTagsByVersion/' + versionId;
	   		sendAjaxRequest(url, 'POST', true, null, findUserTagsByVersionSuccess, findUserTagsByVersionFailure);
		},
				
		replaceChecks : function(formName, checkboxName) {
			var form = $(formName);
			var checkboxes = form.getInputs('checkbox', checkboxName);

			checkboxes.each(function(item, i) {
				//create a new image
				var img = document.createElement('img');
			
				//check if the checkbox is checked
				if(item.checked) {
					img.src = imgTrue;
				} else {
					img.src = imgFalse;
				}
	
				//set image ID and onclick action
				img.id = 'checkImage'+i;
				
				//set image 
				img.onclick = new Function('LIFEWAY.worshipplan.checkChange("'+ formName +'", "' + checkboxName + '", ' + i +')');
				
				//place image in front of the checkbox
				item.parentNode.insertBefore(img, item);
			
				//hide the checkbox
				item.style.display='none';
			});
		},
	
		checkChange : function(formName, checkboxName, i) {
			var form = $(formName);
			var checkboxes = form.getInputs('checkbox', checkboxName);

			if(checkboxes[i].checked) {
				$('checkImage'+i).src=imgFalse;
			} else {
				$('checkImage'+i).src=imgTrue;
			}
			
			checkboxes[i].click();
		},
		
		// notes functions
		displayNotesPopup : function(type, elementPosition ) {
		    LIFEWAY.common.toggleElements($$('select[id^=song_key]'));
			currentParticipantId = "-1";
			currentElementPosition = elementPosition;
			Element.show("notes_editor");
		},
		
		closeNotesPopup : function() {
			if(notesEditor) {
				notesEditor.destroy();
				notesEditor=null;
			}
			$("notes_editor").hide();
			$("music_notes_select").options[0].selected = 'true';
			LIFEWAY.common.toggleElements($$('select[id^=song_key]'));
			
		},
		
		storeNotesPopupData : function() {
			var noteText = notesEditor.getEditorHTML();
			storeMusicNoteData(currentElementPosition, currentParticipantId, noteText);
			LIFEWAY.worshipplan.closeNotesPopup();
		},
		
		changeParticipant : function(newParticipantId){
			if(currentParticipantId != "-1"){
				var noteText = notesEditor.getEditorHTML();
				var participantId = currentParticipantId;
				storeMusicNoteData(currentElementPosition, participantId, noteText)
			} 
			if(newParticipantId == 0) {
				$('MyTextarea_container').style.display = 'none';
			} else {
				if(currentParticipantId != "-1"){
					$('MyTextarea_container').style.display = '';
				}
			}
			currentParticipantId = newParticipantId;
			getNotesForParticipant(newParticipantId);
			
		},

		changeSelectedKey : function(songKeyId, position) {
		  var url = '/changeSongKey/selectedKey/' + songKeyId + "?position=" + position;
          sendAjaxRequest(url, 'GET', true, null, changeKeySuccess, changeKeyFailure);    
		
		},
		
		collapseElement : function( headerDiv, bodyDiv) {
			$(headerDiv).className = 'plan_inactive_head';
			$(bodyDiv).style.display = 'none'
		},
		
		expandElement : function ( headerDiv, bodyDiv) {
			$(headerDiv).className = 'plan_active_head';
			$(bodyDiv).style.display = ''
		}
		
		
	};
//********************************** Private functions **********************************	
	
	function findUserTagsByVersionSuccess(oReq){
		//alert(oReq.responseText);
		var arrTags = eval(oReq.responseText);
		$('tagsinput').value = arrTags;
		$('yourTagsView').innerHTML = arrTags;
	};
	
	function findUserTagsByVersionFailure(oReq){
		//alert(oReq.responseText);
		LIFEWAY.common.displayAlertDialog(oReq.responseText);
	};	
	function findUserTagsSuccess(oReq){
		var arrTags = eval(oReq.responseText);
		var oTagsDS = new YAHOO.widget.DS_JSArray(arrTags); 
		var oAutoComp = new YAHOO.widget.AutoComplete('tagsinput','tagscontainer', oTagsDS);
		oAutoComp.prehighlightClassName = "yui-ac-prehighlight";
		oAutoComp.delimChar = ","; 
		oAutoComp.typeAhead = true;
	    oAutoComp.useShadow = true;
	    oAutoComp.minQueryLength = 0;		
	};
	
	function findUserTagsFailure(oReq){
		//alert(oReq.responseText);
		LIFEWAY.common.displayAlertDialog(oReq.responseText);
	};	
	
	function changeKeySuccess(oReq){
	}
	
	function changeKeyFailure(){
		alert("Unable to update the song key at this time.");
	}
	
	function displayPurchasableItemsSuccess(oReq){
		LIFEWAY.dialog.displayDialog(oReq.responseText, 'popup');
		LIFEWAY.worshipplan.replaceChecks('configureCartForm','planItemsForPurchase');
	}
	
	function displayPurchasableItemsFailure(){
		alert("Unable to view the information at this time.");
	}
		
	function displayPrintInformationSuccess(oReq){
		LIFEWAY.dialog.displayDialog(oReq.responseText, 'iscreen');
	}
	
	function displayPrintInformationFailure(){
		alert("Unable to view the print preview at this time.");
	}
	
	// to make the duration 0, moves a reverted element back to original position faster.
	function revertFunc(element, top_offset, left_offset) {
		element.removeClassName("dragging");
		if (currentSpacer != "") currentSpacer.className = "worshipPlanSpacer";
	    var dur = 0;
	    new Effect.Move(element, { x: -left_offset, y: -top_offset, duration: dur,
	      queue: {scope:'_draggable', position:'end'}
		});
	};
	
	function startFunc(element)
	{
		if(!immutablePlanMessageDiaplayed)
		{
			LIFEWAY.dialog.displayAjpDialog("/worshipPlanImmutableDialog.ajp", null, "popup");
			immutablePlanMessageDiaplayed = true;
		}
		element.addClassName("dragging");
	};
	
	
	function createWorshipPlanSuccess(oReq)
	{		
		$('planDisabled').hide();
		$('publishLinkDiv').style.display = 'block';
		setPlanTitleBar($('worshipPlanForm').planName.value, $('worshipPlanForm').eventDate.value);
	}
	
	function setPlanTitleBar(name, date){
	    $('worshipPlanName').innerHTML = name;
	    $('worshipPlanDate').innerHTML = date;
	    $('worshipPlanCreateForm').hide();
	    $('worshipPlanTitle').show();	
	}
	
	function createWorshipPlanFailure(oReq)
	{
		LIFEWAY.common.displayAlertDialog(oReq.responseText);
	}
	
	function submitUserSongTagsSuccess(oReq){
		displaySuccessMessage("Saved Successfully.");
		$('yourTagsView').innerHTML = $('tagsinput').value;
		$('iscreen_edittags').hide();
		$('yourTagsView').show();
		$('tagsEditBtn').show();
		$('tagsSaveBtn').hide();
		$('tagsEditBtn').focus();
	}
	
	function displaySuccessMessage(msg){
		clearTimeout(messageTimer);
		$('tagMessage').style.display = 'block';
		$('tagMessage').innerHTML = msg;
		messageTimer = setTimeout(hideMessage, 3000);
	}
		
	function hideMessage() {
		$('tagMessage').style.display = 'none';
	}
	
	function submitUserSongTagsFailure(oReq){
		LIFEWAY.common.displayAlertDialog(oReq.responseText);
	}
	
	function getVersionId(parentNodeId) {
		var versionId;
		var childNodes = $(parentNodeId + '-body').getElementsByClassName("childNode");
		var numVersions = childNodes.length;

		var numVersions = childNodes.length;
		if (numVersions == 1) {
			versionId = childNodes[0].id.split("_")[1];
		}
		return versionId;
	};
	
	function getOptionsData(parentNodeId) {
		//var numVersions = $(parentNodeId + '-body').childNodes.length;
		var childNodes = $(parentNodeId + '-body').getElementsByClassName("childNode");
		var numVersions = childNodes.length;
		if (numVersions == 1) {
			var versionDiv = $(parentNodeId + '-body').getElementsByClassName("childNode")[0];
			$('iscreen_version').innerHTML = versionDiv.getElementsByTagName('span')[0].innerHTML;
			return null;
		}
		var optionsArray = new Array();
		for (var i = 0; i < childNodes.length; i++) {
			var versionDiv = childNodes[i];
			var productId = versionDiv.id.split("_")[1];
			var option = new Object();
			option.label = versionDiv.getElementsByTagName('span')[0].innerHTML;
			option.value = productId;
			optionsArray[i] = option;
		}
		return optionsArray;
		
	};
	
	function numberChildDivs(div) {
			return Element.childElements(div).length;
	};
	
	function getDropElementPosition (x,y, container){
		var pos = "0";
		var dropDiv;
		var childList = $(container).getElementsByClassName("spacerContainer");
		//alert(childList.length +":"+x+":"+y);
		
		for (var i=0;i<childList.length;i++){
			var within = Position.within(childList[i], x, y);
		    if(isIE) {
				var offset = childList[i].cumulativeScrollOffset();
				//Position.prepare();
				within = Position.withinIncludingScrolloffsets(childList[i], x, y);
			}
			if(within){
				dropDiv = childList[i];
			}
		}

		return dropDiv?stringAfterDelimiter(dropDiv.id, "_"):i;
	};
	
	function processSelectedElement(compareFunctions, filterType, id) {
		var methodToInvoke = compareFunctions[filterType];
		if (methodToInvoke) {
			return methodToInvoke(id);
		}	
	};
	
	function buildMusicVideoParams(id) {
		var versionId = stringAfterDelimiter(id, '_');
		return 	buildGenericParams() + "&versionId=" + versionId;
	};
	
	function buildLibraryParams(id) {
	 	var temp = stringAfterDelimiter(id, '_');
		var versionId = stringBeforeDelimiter(temp, '_');
		var elementId = stringAfterDelimiter(temp, '_');
		return 	buildGenericParams() + "&versionId=" + versionId + "&elementId=" + elementId;
	};
	
	function stringAfterDelimiter(str, delimiter){
		if (str){
			var loc = str.indexOf(delimiter) + 1;
			return str.substring(loc);
		}
	};
	
	function stringBeforeDelimiter(str, delimiter){
		if (str){
			var loc = str.indexOf(delimiter);
			return str.substring(0, loc);
		}
	};
		
	function buildScriptureParams(id) {	
		return 	buildGenericParams() + 
		"&version=" + $('scripture_version').value + 
		"&book=" + $('scripture_book').value + 
		"&chapter=" + $('scripture_chapter').value + 
		"&verse=" + $('scripture_verse').value +
		"&time=" + $('scripture_time').value;
	};
	
	function buildSermonOtherParams(id) {	
		var elementId = stringAfterDelimiter(id, '_');
		return 	buildGenericParams() + 
		"&elementId=" + elementId;
	};
	
	function buildGenericParams() {	
		var planId = $('planId').value;
		var type = $('elementType').value;
		return "elementType=" + type + "&planId=" + planId;
	};

	function deleteSuccess(oReq){
		var data = eval('(' + oReq.responseText + ')');
		var worshipPlan = data.JSONMessageImpl.message.worshipPlan;
		var user = data.JSONMessageImpl.message.user;
		//Element.remove(selectForDeleteDiv);
		loadWorshipPlan(worshipPlan, user, 1);
		LIFEWAY.dialog.removeDialog('confirmationMessage');
		var numElements = numberChildDivs($('planElements'));
		if (  numElements == 0 ) {
			Element.show('wp_context_help');
			Element.hide('plan_print');
		}
		//var hidePrompt = data ? LIFEWAY.common.hasPreference(data, 1) : "false";
		//updateElementPositions(hidePrompt);
		LIFEWAY.worshipplan.updateTotalDuration();
	};
	
	function deleteFailure(){
		LIFEWAY.dialog.removeDialog('confirmationMessage');
	};
	
	function updateElementPositions(hidePrompt){
		var deleteCells = $("planElements").getElementsByClassName("deleteCell");
		for(var i=0; i < deleteButtons.length; i++){
		  var deleteButton = "<img src=\"/images/delete.png\" " +
		                     "onclick=\"LIFEWAY.worshipplan.deleteFromPlan('" + i + 
		                     "', 'false');\" class=\"deleteIcon\" id=\"deleteIconmusic_" + i + "\"/>"
		  deleteCells[i].innerhtml = deleteButton;                   
		}
	};
	
	function getSpacer(el){
		var looper = el;
		while (looper){
			if (looper.id && looper.id.indexOf('spacerContainer_') > -1){
				break;
			}
			looper = looper.parentNode;
		}
		return $('spacer_' + looper.id.split('_')[1]);
	};
	
	function expandSpacer(draggable, div, percentage){
		if (div.id == "planElements" || percentage < .2){
			if (currentSpacer != "") currentSpacer.className = "worshipPlanSpacer";
		 	return;
		 }
		 //made a var
		var spacerDiv = $('spacer_' + div.id.split('_')[1])
		
		if (currentSpacer && currentSpacer != spacerDiv){
			currentSpacer.className = "worshipPlanSpacer";
		}
		currentSpacer = spacerDiv;
		spacerDiv.className = "worshipPlanSpacerOver";
	};
	
	function hideSpacer(){
		if (currentSpacer) currentSpacer.className = "worshipPlanSpacer";
	};
	
	function addElementSuccess(oReq){	
		var data = eval('(' + oReq.responseText + ')');
		var worshipPlan = data.JSONMessageImpl.message.worshipPlan;
		var user = data.JSONMessageImpl.message.user;
		loadWorshipPlan(worshipPlan, user, 1);
	}
	
	function addElementFailure(oReq) {
	
	}
	
	function loadWorshipPlan(wp, user, planId){
		
		if(user) {
			userPrefs = user.User.preferences;
			promptOff = LIFEWAY.common.hasPreference(userPrefs,'1');
			_logged_on = "true";
		}
		else {
			_logged_on = "false";
			promptOff = "false";
		}
		
		var elementDiv;
		var planPosition;
		var elementType;
		var elementTime;
		var elementTitle;		
		var elementPlanId;
		var planElementName;
		
		var spacerDivContainer;
		
		var spacerDiv;
		
		var returnedData;
		$('planElements').innerHTML="";
		if (document.all) { 
			Droppables.drops = [];
			Droppables.add("planElementsContainer",{onDrop:LIFEWAY.worshipplan.buildWorshipPlanElementDiv, accept:['draggable_area']});
			Droppables.add("planElementsContainer",{onDrop:LIFEWAY.worshipplan.buildWorshipPlanOtherElementDraggableDiv, accept:['other_draggable_area']});
			Droppables.add("planElementsContainer",{onDrop:LIFEWAY.worshipplan.buildWorshipPlanLibraryElementDraggableDiv, accept:['library_draggable_area']}); 
			Sortable.create("planElements", {onUpdate:LIFEWAY.worshipplan.moveElement,scroll:"planElements", tag:'div',dropOnEmpty:true,containment:["planElements"],constraint:"vertical"});
		}
		
		if(wp.WorshipPlan.elements) {
			Element.show('plan_print');
			for( var i = 0; i<wp.WorshipPlan.elements.WorshipPlanElementImpl.length; i++){
			    var worshipPlanElement = wp.WorshipPlan.elements.WorshipPlanElementImpl[i];
			    var theElement = worshipPlanElement.element.Element;
			    var songKeys = null;
			    var mode = theElement.mode;			    
			    if (theElement.songKeys != null ) {
			        songKeys = theElement.songKeys.keyDTO;
			        for (var j = 0; j < songKeys.length; j++) {
				         var keyDTO = songKeys[j];
				       	 if ('Minor' == mode) {
							keyDTO.label = keyDTO.label.toLowerCase();				         	
				       	 } else {
				       	 	keyDTO.label = keyDTO.label.toUpperCase();				         	
				         }
				         songKeys[j] = keyDTO;
			         }
			    }
				elementType = theElement.elementType;
				elementTime = worshipPlanElement.elementDuration.Duration.Time;
				if (worshipPlanElement.name && worshipPlanElement.name.length > 20 ) {
					planElementName = worshipPlanElement.name.substring(0,20) + '...';
				} else {
					planElementName = worshipPlanElement.name;
				}
				
				elementTitle = buildElementReference(wp.WorshipPlan.elements.WorshipPlanElementImpl[i].element,
						 elementType, i);
						 
				elementReference = wp.WorshipPlan.elements.WorshipPlanElementImpl[i].element.Element.reference;
				elementPlanId = wp.WorshipPlan.elements.WorshipPlanElementImpl[i].id;
				
				
				elementDiv = document.createElement('div');
				elementDiv.id="id_" + i;
				elementDiv.className = elementType + "Element";
				
				spacerDivContainer = document.createElement('div');
				spacerDivContainer.id = "spacerContainer_" + i;
				spacerDivContainer.className = "spacerContainer";
				spacerDiv = document.createElement('div');
				spacerDiv.id = "spacer_" + i;
				spacerDiv.className = "worshipPlanSpacer";
				spacerDivContainer.appendChild(spacerDiv);
				count++;	
				
				var isMappable = theElement.isMappable;
				var hasSongMap = (wp.WorshipPlan.elements.WorshipPlanElementImpl[i].songMap) ? true : false;
				var versionId = theElement.versionId;						
				var songMapId = "";
				var songMapLegend = "";
				var abbrevSongMapLegend = "";
				if(hasSongMap){
					songMapLegend = wp.WorshipPlan.elements.WorshipPlanElementImpl[i].songMap.songMap.songMapLegend;
					abbrevSongMapLegend = wp.WorshipPlan.elements.WorshipPlanElementImpl[i].songMap.songMap.abbrevSongMapLegend;
				}
				
				if(elementType == 'other') {
					var returnedData = otherElementProcessor({theCount: i,
													planId: planId,
													planElementName: planElementName,
				    								elementId: theElement.elementId,
				    								versionId: versionId,
				    								isMappable: isMappable,
													songMapLegend: songMapLegend,
													title: elementTitle,
													hasSongMap: hasSongMap,
													abbrevSongMapLegend: abbrevSongMapLegend,
				    								type: elementType, 
													duration: elementTime,
													index: i,
													elementPlanId: elementPlanId,
													showSongKeys: songKeys,
													promptOff: promptOff});		
													
					
				} else if(elementType == 'library') {
					 var returnedData = libraryElementProcessor({theCount: i,
													planId: planId,
													planElementName: planElementName,
				    								elementId: theElement.elementId,
				    								versionId: versionId,
				    								isMappable: isMappable,
													songMapLegend: songMapLegend,
													hasSongMap: hasSongMap,
													abbrevSongMapLegend: abbrevSongMapLegend,
				    								type: elementType, 
													duration: elementTime, 
													title: elementTitle, 
													index: i,
													elementPlanId: elementPlanId,
													showSongKeys: songKeys,
													promptOff: promptOff});		
				
				} else {
				    var returnedData = processor({theCount: i,
													planId: planId,
													planElementName: planElementName,
				    								elementId: theElement.elementId,
				    								versionId: versionId,
				    								isMappable: isMappable,
													songMapLegend: songMapLegend,
													hasSongMap: hasSongMap,
													abbrevSongMapLegend: abbrevSongMapLegend,
				    								type: elementType, 
													duration: elementTime, 
													title: elementTitle, 
													index: i,
													elementPlanId: elementPlanId,
													showSongKeys: songKeys,
													promptOff: promptOff});		
				}
				elementDiv.innerHTML=returnedData;
				elementDiv.setAttribute("elementId", theElement.elementId);
				spacerDivContainer.appendChild(elementDiv);		
				if (dropDiv != ""){
					$('planElements').insertAfter(spacerDivContainer, dropDiv);
				} else {
					$('planElements').appendChild(spacerDivContainer);
				}
				
				Droppables.add(elementDiv.id,{
					overlap:"vertical",
					onHover: expandSpacer,
					onDrop:LIFEWAY.worshipplan.buildWorshipPlanOtherElementDraggableDiv, 
					accept:['other_draggable_area']});
				Droppables.add(elementDiv.id,{
					overlap:"vertical",
					onHover: expandSpacer,
					onDrop:LIFEWAY.worshipplan.buildWorshipPlanElementDiv, 
					accept:['draggable_area']});
				Droppables.add(elementDiv.id,{
					overlap:"vertical",
					onHover: expandSpacer,
					onDrop:LIFEWAY.worshipplan.buildWorshipPlanLibraryElementDraggableDiv, 
					accept:['library_draggable_area']});
				
				if (songKeys != null && !hasSongMap) {
				    LIFEWAY.common.createOptionsWithSelected(theElement.selectedKey, "song_keys_"+i, 
				    songKeys, null);
				}
				initPlanElementNameEditor(i);
				if(elementType == 'other') {
				
					initPlanElementReference(i);
					initPlanElementDuration(i);
				} else {
					new YAHOO.widget.Tooltip('legendTT' + i, { context:'legend' + i, text:songMapLegend } );
				}
			}
		}		
		Sortable.create("planElements", {onUpdate:LIFEWAY.worshipplan.moveElement,scroll:"planElements", tag:'div',dropOnEmpty:true,containment:["planElements"],constraint:"vertical"});
		Position.includeScrollOffsets = true;	//The scroll position of the container will now move along 
												//when the sortable is dragged out of the viewable area
		LIFEWAY.worshipplan.updateTotalDuration();
		
		var numElements = numberChildDivs($('planElements'));
		if (numElements > 0) {
			Element.hide('wp_context_help');
		}	
	};
	
	function updateTotalDurationDiv(oReq) {
	var json = eval('(' + oReq.responseText + ')');
		$('totalWorshipPlanTime').innerHTML = json.JSONMessageImpl.message.duration;
	};
	
	function buildElementReference(json, type) {
		if(type === "scripture") {
			return json.Element.book + "&nbsp;&nbsp;" + json.Element.chapter + ":" + json.Element.verse
		} else {
			return json.Element.Title;
		}
	};
	
	function buildElementReference2(json, type, i) {
		if(type === "scripture") {
			return json.Element[i].book + "&nbsp;&nbsp;" + json.Element[i].chapter + ":" + json.Element[i].verse
		} else {
			return json.WorshipPlan.elements.WorshipPlanElementImpl[i].element.Element.Title;
		}
	};
	
	function createResultsTable(divName, params, baseUrl) {
		try{
			yuiTable = null;
			columnHeaders = null;
			yuiDataSource = null;		
			
			if(divName == 'librarySearchResults') {
				columnHeaders = buildLibraryColumnHeaders();
				yuiDataSource = buildLibraryDataSource(baseUrl);
			} else {
				columnHeaders = buildColumnHeaders();
				yuiDataSource = buildDataSource(baseUrl);
			}
			YAHOO.widget.DataTable.CLASS_EVEN = "even";
			YAHOO.widget.DataTable.CLASS_ODD = "odd";
			YAHOO.widget.DataTable.MSG_LOADING = "";
			
			var initParams = params + "&offset=" + offset;
			
			yuiTable = new YAHOO.widget.DataTable(divName, columnHeaders, yuiDataSource, 
				{initialRequest : initParams, scrollable:true});
			
		    yuiTable.doBeforeLoadData = function(sRequest, oResponse) {
				if(oResponse.error || !oResponse.results || oResponse.results.length == 0){
					if(offset == 0) {
						noResultsMessage();
					}
					oResponse.error = true;
					retrievedAllRecs = true;
					
					return false;
				} else {
					if(oResponse.results.length < 50){
						retrievedAllRecs = true;
					}
					return true;
				}	
			};
			$(divName).onscroll = scrollEvent;
			
		}catch(e){
			alert(e);
		}
	};
	
	function noResultsMessage() {
		var resultMessage = "<p class='orange' style='margin-top:36px;font-weight:bold;font-size:16px;'>I've looked everywhere, and I can't find that song right now...</p>" +
							"<p style='font-style:italic;font-weight:bold;'>We are adding songs to LifeWay Worship all the time. There is, of course, the potential you might have mistyped something. Try typing fewer words, check your spelling, or try a theme, topic or phrase from a song.</p>";
		Element.update('musicSearchResults', resultMessage);
	};	
	
	function buildColumnHeaders(){
		var myColumnHeaders = [ 
			{key:"name", label:"", formatter:formatVersion, width:"245px", className:""},
			{key:"", label:"", formatter:formatIsPurchased, width:"20px", className:""},
			{key:"", label:"", formatter:formatPlayPreview, width:"20px", className:""}
		]; 
		var columnSet = new YAHOO.widget.ColumnSet(myColumnHeaders);
		return columnSet; 
	};	
	
	function buildLibraryColumnHeaders(){
		var myColumnHeaders = [ 
			{key:"versionName", label:"", formatter:formatLibraryVersion, width:"145px", className:""},
			{key:"songMapLegend", label:"", width:"20px", className:""},
			{key:"", label:"", formatter:formatPlayPreview, width:"20px", className:""}
		]; 
		var columnSet = new YAHOO.widget.ColumnSet(myColumnHeaders);
		return columnSet; 
	};	
	
	function formatVersion(elCell, oRecord, oColumn, oData){
		var versionId = oRecord.getData('versionId');
		var divId = "dragid_" + versionId;
		var downloadableClass = oRecord.getData('isDownloadable') == 'true'?" downloadable":""; 
		var container = "musicSearchResults";
		elCell.innerHTML = 
			"<div id=\"" + divId + 
			"\" class=\"draggable_area" + downloadableClass + "\" style=\"position:relative;top:0px;zoom:100%;\">" +
			oRecord.getData('name') + "</div>";
		new Draggable(divId, {scrollcontainer:container, revert:true, ghosting:true, zindex:zi, reverteffect:revertFunc, starteffect:startFunc});
	};	
	
	function formatLibraryVersion(elCell, oRecord, oColumn, oData){
		var versionId = oRecord.getData('versionId');
		var elementId = oRecord.getData('id');
		var divId = "dragid_" + versionId+"_"+elementId;
		var container = "librarySearchResults";
		elCell.innerHTML = 
			"<div id=\"" + divId + 
			"\" class=\"library_draggable_area\" style=\"position:relative;top:0px;zoom:100%;\">" +
			oRecord.getData('versionName') + "</div>";
		new Draggable(divId, {scrollcontainer:container, revert:true, ghosting:true, zindex:zi, reverteffect:revertFunc, starteffect:startFunc});
	};	
	
	function formatPlayPreview(elCell, oRecord, oColumn, oData){
		var versionId = oRecord.getData('versionId');
		elCell.innerHTML = "<img id=\"audioBtn" + versionId + "\" src=\"/images/play.gif\" " +
							"alt=\"play preview\" onClick=\"LIFEWAY.worship.previewplayer.playPreview('" + 
							versionId + "')\"/>";
	};
	
	function formatIsPurchased(elCell, oRecord, oColumn, oData){
		var isPurchased = oRecord.getData('isPurchased');
		if (isPurchased == 'true') {
			elCell.innerHTML += "<img  src=\"/images/star.gif\" " +
							"alt=\"You own it!\"/>";
		}
	};
	
	function buildDataSource(baseUrl){
		yuiDataSource = new YAHOO.util.DataSource(baseUrl); 
		yuiDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
		yuiDataSource.connXhrMode = "queueRequests";
		yuiDataSource.connMethodPost = "true";
		yuiDataSource.responseSchema = { 
			resultsList : "NavItemMusic", 
		    fields: ["name", "typeDescription", "versionId", "isDownloadable", "isPurchased"] 
		}; 
		yuiDataSource.subscribe("requestEvent", requestEv);
		yuiDataSource.subscribe("responseEvent", responseEv);
		return yuiDataSource; 
	};
	
	function buildLibraryDataSource(baseUrl){
		yuiDataSource = new YAHOO.util.DataSource(baseUrl); 
		yuiDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
		yuiDataSource.connXhrMode = "queueRequests";
		yuiDataSource.connMethodPost = "true";
		yuiDataSource.responseSchema = { 
			resultsList : "MediaElement", 
		    fields: ["versionName", "songMapLegend", "versionId", "id"] 
		}; 
		yuiDataSource.subscribe("requestEvent", requestEv);
		yuiDataSource.subscribe("responseEvent", responseEv);
		return yuiDataSource; 
	};	
	
	function requestEv() {
		Element.show('waitingGif');
	};
	function responseEv() {
		Element.hide('waitingGif');
	};	
	
	function scrollEvent() {
	
		var Dom = YAHOO.util.Dom;
		var position = $('musicSearchResults').scrollTop; 
		var height = $('musicSearchResults').scrollHeight;
		if(!retrievedAllRecs && (Dom.getY($(getMarkerRowDivId())) < Dom.getY($('musicSearchResults')) + $('musicSearchResults').offsetHeight && !retrievingResults)) {
			retrievingResults = true;
			YAHOO.util.Event.onDOMReady(pageForward);
		}
		
	};	
	
	function getMarkerRowDivId(){
		var rowCount = yuiTable.getRecordSet().getLength();
		var rowIndex70percent = rowCount * '.7';
		var markerDiv = "yui-dt1-bdrow" + rowIndex70percent;
		return markerDiv;
		
		
	};	
	
	function pageForward() {
		var paramsForRequest = Form.serialize('worshipPlanMusicSearch');
		paramsForRequest += "&offset=" + ++offset;
		
		yuiDataSource.sendRequest(paramsForRequest,
                yuiTable.onDataReturnAppendRows, yuiTable); 
		retrievingResults = false;
		
	};
	
	function showCreateCal() { 
	    var xy = YAHOO.util.Dom.getXY('showCreateCalendar'); 
	    var date = YAHOO.util.Dom.get('eventDate').value; 
	    if (date) { 
	        createCal.cfg.setProperty('selected', date); 
	        createCal.cfg.setProperty('close', true); 
	        createCal.cfg.setProperty('pagedate', new Date(date), true); 
	        createCal.render(); 
	    } 
	    YAHOO.util.Dom.setStyle('createCalendar', 'display', 'block'); 
	    xy[1] = xy[1] + 20; 
	    YAHOO.util.Dom.setXY('createCalendar', xy); 
	}; 
	
	function hideCreateCal() { 
        YAHOO.util.Dom.setStyle('createCalendar', 'display', 'none'); 
	}; 

	function hideUpdateCal() { 
        YAHOO.util.Dom.setStyle('updateCalendar', 'display', 'none'); 
	}; 

	function getDate() { 
	    var calDate = this.getSelectedDates()[0]; 
	    calDate = (calDate.getMonth() + 1) + '/' + calDate.getDate() + '/' + calDate.getFullYear(); 
	    YAHOO.util.Dom.get('eventDate').value = calDate; 
	    hideCreateCal(); 
	}; 
	
	function updateDate() { 
	    var calDate = this.getSelectedDates()[0]; 
		calDate = (calDate.getMonth() + 1) + '/' + calDate.getDate() + '/' + calDate.getFullYear(); 
	    
		new Ajax.Request('/worshipPlan/updateDateInRootNode',	{ 
			method: 'post', parameters:'eventDate='+calDate,
			onSuccess: updateEventDateSuccess,
			onFailure: updateEventDateFailure 
		});
	}; 
	
	function updateEventDateSuccess(oReq) {
		$("worshipPlanDate").innerHTML = oReq.responseText;
	    hideUpdateCal(); 
	};
	
	function updateEventDateFailure(oReq) {
		var jsonData = eval('(' + oReq.responseText + ')');
		hideUpdateCal();
		LIFEWAY.common.displayAlertDialog(jsonData.errorMessage);
	};
	
	function initPlanElementNameEditor(planElementPosition) {
		var planElement = 'element-' + planElementPosition;
		
		var ipe = new Ajax.InPlaceEditor(planElement, 
			'/processElement/updateElementName/' , 
			{
				ajaxOptions: {
					onFailure:LIFEWAY.worshipplan.updatePlanElementNameFailure, 
					onSuccess:LIFEWAY.worshipplan.updatePlanElementNameSuccess
				},
				okButton: false,
				cancelLink: false,
				cols: 25, 
				submitOnBlur: true, 
				highlightcolor: '#CECECE', 
				highlightendcolor: '#CECECE',
				callback: LIFEWAY.worshipplan.createWorshipPlanElementEditParams
			});
		
		ipe.onEnterEditMode = function() {
			if ($(planElement).innerHTML == 'music') {
				$(planElement).innerHTML = '';
			}
		}
		
    	Event.stopObserving($(planElement), 'click', ipe.onclickListener);		
		Event.observe($(planElement), 'mousedown', ipe.onclickListener);
			
		if (planElementPosition == currentHighlightedPos) {
			$(planElement).style.background = "#CECECE";		
		}				
	};
	
	function initPlanElementReference(planElementPosition) {
		var planElementReference = 'details-' + planElementPosition;
		var ipe = new Ajax.InPlaceEditor(planElementReference, 
			'/processElement/updateElementReference/' , 
			{
				ajaxOptions: {
					onFailure:LIFEWAY.worshipplan.updatePlanElementReferenceFailure, 
					onSuccess:LIFEWAY.worshipplan.updatePlanElementReferenceSuccess
				},
				okButton: false,
				cancelLink: false,
				cols: 20, 
				submitOnBlur: true, 
				highlightcolor: '#CECECE', 
				highlightendcolor: '#CECECE',
				callback: LIFEWAY.worshipplan.createWorshipPlanElementReferenceEditParams
			});
		
				
    	Event.stopObserving($(planElementReference), 'click', ipe.onclickListener);		
		Event.observe($(planElementReference), 'mousedown', ipe.onclickListener);
			
		if (planElementPosition == currentHighlightedPos) {
			$(planElementReference).style.background = "#CECECE";		
		}				
	};
	
	function initPlanElementDuration(planElementPosition) {
		var planElementDuration = 'elementDuration-' + planElementPosition;
		var ipe = new Ajax.InPlaceEditor(planElementDuration, 
			'/processElement/updateDuration/' , 
			{
				ajaxOptions: {
					onFailure:LIFEWAY.worshipplan.updatePlanElementDurationFailure, 
					onSuccess:LIFEWAY.worshipplan.updatePlanElementDurationSuccess
				},
				okButton: false,
				cancelLink: false,
				cols: 5, 
				submitOnBlur: true, 
				highlightcolor: '#CECECE', 
				highlightendcolor: '#CECECE',
				callback: LIFEWAY.worshipplan.createWorshipPlanElementDurationEditParams
			});
		
		ipe.onEnterEditMode = function() {
			$(planElementDuration).innerHTML = '';
		}
		
    	Event.stopObserving($(planElementDuration), 'click', ipe.onclickListener);		
		Event.observe($(planElementDuration), 'mousedown', ipe.onclickListener);
			
		if (planElementPosition == currentHighlightedPos) {
			$(planElementDuration).style.background = "#CECECE";		
		}				
	};
	
	// notes functions
	function storeMusicNoteData(elementPosition, participantId, noteText){
		var params = "noteParticipantId=" + participantId + "&noteText=" + encodeURIComponent(noteText) + "&position=" + elementPosition;	
		var url = '/processElement/addNote';
		if(noteText.blank() || noteText.strip() == "<br>" || noteText.indexOf("&nbsp;") != -1){
			if(participantId != null && participantId != '') 
			{
				params = "noteParticipantId=" + participantId + "&position=" + elementPosition;	
				url = '/processElement/removeNote';
			} else {
				return;
			}
		}
   		sendAjaxRequest(url, 'POST', true, params, null, storeMusicNoteDataFailure);
	};

	function storeMusicNoteDataFailure(oReq){
		LIFEWAY.common.displayAlertDialog(oReq.responseText);
	};		

	function getNotesForParticipant(participantId){
		currentParticipantId = participantId;
		var params = "noteParticipantId=" + participantId + "&position=" + currentElementPosition;	
		var url = '/processElement/findNote';
   		sendAjaxRequest(url, 'POST', true, params, getMusicNoteSuccess, getMusicNoteFailure);
	};
	
	function getMusicNoteSuccess(oReq){
		var data = eval('(' + oReq.responseText + ')');
		var note = data == null ? " " : data.Note.text;
		$('MyTextarea').value = note;
		
		var myConfig = {
        		height: '230px',
		        width: '470px',
		        dompath: false,
		        focusAtStart: true,
		        toolbar: {
			        titlebar: false,
			        buttons: [
			            { group: 'textstyle', label: '',
			                buttons: [
			                    { type: 'push', label: 'Bold', value: 'bold' },
			                    { type: 'push', label: 'Italic', value: 'italic' },
			                    { type: 'push', label: 'Underline', value: 'underline' },
			                    { type: 'separator' },
			                    { type: 'select', label: 'Arial', value: 'fontname', disabled: false,
			                        menu: [
			                            { text: 'Arial' },
			                            { text: 'Arial Black' },
			                            { text: 'Comic Sans MS' },
			                            { text: 'Courier New' },
			                            { text: 'Lucida Console' },
			                            { text: 'Tahoma' },
			                            { text: 'Times New Roman' },
			                            { text: 'Trebuchet MS' },
			                            { text: 'Verdana' }
			                        ]
			                    },
			                    { type: 'separator' },
			                    { type: 'spin', label: '13', value: 'fontsize', range: [ 9, 75 ], disabled: true },
			                    { type: 'separator' }
			                ]
			            }
			        ]
			    }
		    };

			if(!notesEditor) {
		    	notesEditor = new YAHOO.widget.SimpleEditor('MyTextarea', myConfig);
   				notesEditor.render();
   			}
			notesEditor.setEditorHTML( note );
	};	

	function getMusicNoteFailure(oReq){
		LIFEWAY.common.displayAlertDialog(oReq.responseText);
	};	
};
