jQuery(document).ready(function($){

	var page=document.location.href;
	page=page.replace("#","");

	$('.pickdates').datepicker({
		inline:true,
		changeMonth:true,
		changeYear:true,
		altFormat: 'yy-mm-dd',
		onSelect:function(dateText,inst){
			$.post(page,{
			   'ajaxrequest':'displayevents',
			   'datetext':dateText
			   },
			   function(data){
					// put the calendar events for this date into the viewing pane
					$('#callist').html(data);
			   });
			},
		onChangeMonthYear:function(year,month,inst){
			$.post(page,{
			   'ajaxrequest':'displayevents',
			   'month':month,
			   'year': year
			   },
			   function(data){
					// put the calendar events for this date into the viewing pane
					$('#callist').html(data);
			   });

			}
		});

	$('.showcalendar').live('click',function(){
		var id=$(this).attr('id');
		var page=document.location.href;
		// make the db change to add the lead photo
		$.post(page,
			{
				'ajaxrequest':'displayfunctioncalendar',
				'id':id
			},
			function (data){
				$('#showcal').html(data);
			}
		);

		$.post(page,
			{
				'ajaxrequest':'displayevents',
				'id':id
			},
			function (data){
				$('#callist').html(data);
			}
		);
		$('html, body').animate({scrollTop:0}, 'fast');

	});// end showcalendar

	$('.showevents').live('click',function(){
		var id=$(this).attr('id');
		var page=document.location.href;
		page=page.replace("#","");

		// make the db change to add the lead photo
		$.post(page,
			{
				'ajaxrequest':'displayevents',
				'id':id
			},
			function (data){
				$('#callist').html(data);
			}
		);
		$('html, body').animate({scrollTop:0}, 'fast');

	});// end showevents
/*
	$('.findmembers').live('click',function(){
		$(this).val('');
		var memberid=$(this).attr('data');
		$('#' + memberid).val('');
	});
*/
	$('.show-participant-form').live('click', function(){
		/*
			when the form opens up, there 3 options for adding data, 2 for submitting
			to add data:
				user clicks Me and we add his mid and name to the corresponding fields and clear the name field.  we need to leave the attributes of the name field as read only
				user clicks Friend: remove readonly status of name field, clear value in name field, slide down div for additional information, focus on name field, clear the value in the mid field
				if user uses autocomplete value: add readonly attribute to name field, slide up div for additional information, blur name field, add suggestion name to name field, add suggestion mid to mid field
				if user doesn't use an autocomplete suggestion: wait for click on submit button.  On click of submit, add readonly attribute to name field, slide up div
		*/
		var checkboxid=$(this).attr('id');
		idarray=checkboxid.split("_");
		var memberid='#mid_' + idarray[1];// uses #  prefix because is only a getter
		var participantnameid='#participant-name_' + idarray[1];// the participant name field
		var membercheckbox="#checkbox_" + idarray[1];
		var friendcheckbox="#friend-checkbox_" + idarray[1];// the checkbox for the friend
		var gidid='#gid_' + idarray[1];
		var hoursassignedid='#hours_' + idarray[1];
		var tableid='#table_' + idarray[1];
		var createdby=$('#createdby_' + idarray[1]).val();
		var divid='participant-name_' + idarray[1] + 'div';// can be used to set a field or get infor, so cannot use #
		var processingid='#processing_' + idarray[1];
		var deleteid='#delete_' + idarray[1];// this is the delete image
		var siteuser=$('#siteuser').html();
		var instructions="#instructions";
		var page=document.location.href;
		page=page.replace("#","");

		if($(membercheckbox).is(':checked')){// deal with the member checkbox being checked
			mid=$(membercheckbox).val();// get the value of the Me checkbox
			$(participantnameid).val('');// clear the participant name field
			//add the member to the staffing plan
			$.post(page,{
				'ajaxrequest':'staffingplan',
				'mid':mid,
				'name':$(participantnameid).val(),
				'gid':$(gidid).val(),
				'hoursassigned':$(hoursassignedid).val(),
				'reference':idarray[1],
				'createdby':createdby
			},
				function(data){
					if(data=='fail'){alert('There was a problem in adding your selection.  We apologize for the inconvenience.  Please notify your webmaster of this error.');}
					else{
						$(memberid).val(mid);// assign the mid to the field in the form
						darray=data.split(":");
						if(darray[0]=='replace'){// add the name to the name field
							$(participantnameid).val(darray[2]);
							$(deleteid).css('display','inline');// show the delete image
						}
					}
				}
			);// end add the member to the staffing plan

		}

		if($(friendcheckbox).is(':checked')){// deal with the friend checkbox being checked
			$(participantnameid).val('').attr('readonly',false).focus();// clear the field, remove the read only status and put focus on the field
			$(memberid).val('');// clear the value in the mid field
			$(processingid).val(0);
			if($(instructions).html()!=""){
				alert($(instructions).html());
				$(instructions).html('');
			}
			if ( $('#' + divid).length == 0 ) {
				$(participantnameid).after("<div id=" + divid + " ></div>");
			}
		  $.post(page,{
				'ajaxrequest':'showaddform',
				'reference':idarray[1]
				},
				function(data){
					$('#' + divid).html(data).slideDown('slow');// create the form with input fields
					$("input.findmembers").autocomplete({
						//define callback to format results
						source: function(req, add){
							//pass request to server
							$.getJSON("http://satoricontentmanager.net/filelib/jquery/autocomplete-widget.php?siteuser=" + siteuser + "&callback=?", req, function(data) {
								//create array for response objects
						
								var suggestions = [];
								i=0;
									//process response
									$.each(data, function(i, val){
											suggestions[i]=val;
											i++;
										});
									add(suggestions);
							});
						},

						//define select handler
						select: function(e, ui) {
							var inputid=$(this).attr('id');// get the ids of the input elements
							var inputmid=$(this).attr('data');
							var participantname=ui.item.label;// assign the variables
							var participantid=ui.item.value;
						
							$(participantnameid).val(participantname).attr('readonly', 'readonly').blur();// assign the suggestion value to name field, set the read only status, blur the focus,
							$(memberid).val(participantid);// assign the suggestion value to the mid field
						
							$('#' + divid).slideUp('slow');// close the div for additional information
							//add the member to the staffing plan
							$.post(page,{
								'ajaxrequest':'staffingplan',
								'mid':participantid,
								'name':participantname,
								'gid':$(gidid).val(),
								'hoursassigned':$(hoursassignedid).val(),
								'reference':idarray[1],
								'createdby':createdby
								},
								function(data){
									if(data=='fail'){alert('There was a problem in adding your selection.  We apologize for the inconvenience.  Please notify your webmaster of this error.');}
									$(participantnameid).blur();// take the focus off the input field
									$(deleteid).css('display','inline');// show the delete image
								}
							);// end add the member to the staffing plan
							//	alert('adding ' + membername + ' to ' + inputid + ' and ' + memberid + ' to ' + inputmid);
								return false;
						},
						close: function() {
								$(this).removeClass("ui-corner-top").addClass("ui-corner-all");
								if($(memberid).val()==''){$('#' + divid).slideDown('slow');}// open the div for additional information
								$(participantnameid).attr('readonly','readonly');
							},
						open: function(){
								$(memberid).val('');
							}

				});

				}
			);// end post


			$('.required-field').blur(function(){// prevent the visitor from clearing the name box
				if($(this).val()==''){// if the field is blank
					alert('You must enter a name to use this option.');// display an alert
					$(membercheckbox).attr('checked',false);// uncheck the member id box
					$(friendcheckbox).attr('checked',false);// uncheck the friend id box
					$(participantnameid).val('Participant Name');// insert the default value
					$(participantnameid + 'key').val('');// clear the value in the id field
					$('#' + divid).empty();// clear out the div that was added earlier
				}
			});

			// the only other option for adding data is the submit button.  we only need to close down everything when the button is submitted
			$('.addcontactform').live('click',function()
				{
					if($(processingid).val()==0){
						$(processingid).val(1);// set the processing flag so we only submit once
						$.post(page,{
							'ajaxrequest':'modifysignupinfo',
							'name':$(participantnameid).val(),
							'mid':$(memberid).val(),
							'email':$('#add-email_' + idarray[1]).val(),
							'phone':$('#add-phone_' + idarray[1]).val(),
							'gid':$(gidid).val(),
							'hoursassigned':$(hoursassignedid).val(),
							'reference':idarray[1],
							'createdby':createdby

						   },
							function(data){
								dataarray=data.split(":");
								if(dataarray[0]=='error'){
									alert(dataarray[1]);
								}
								else{// there was no error, so close the drop down box and set the input element back to read onlyl
									darray=data.split(":");
									if(darray[0]=='replace'){// add the name to the name field
										$(memberid).val(darray[1]);
									}
									$(deleteid).css('display','inline');// show the delete image
									$(participantnameid).attr('readonly','readonly');
									$('#' + divid).slideUp('slow');
						 //			$(this).attr('disabled','disabled');
								}
							}
						);
					}
				}
			);// end addcontactform click event

		}

	});// end show-participant-form

	$('.deletecommitment').live('click',function(){
		var commitmentid=$(this).attr('id');
		var scheduleid=$(this).attr('data');
		var id=commitmentid + 'div';
		var confirmationid='deleteconfirmed' + commitmentid;
		$(this).after("<div id='" + id + "'>");// create a new div with the confirmation id
		var message="<input type='checkbox' class='deleteconfirmed' name='deleteentry' id='#" + confirmationid + "' data='" + scheduleid + "'> <b>Check box to confirm that you wish to remove this entry from the schedule.</b>";
		$('#' + id).slideDown('slow').html(message);// create an drop down for the confirmation message

	});

	$('.deleteconfirmed').live('click',function(){
		var id=$(this).attr('data');// this is the id of the scheduled item that needs to be deleted
		var page=document.location.href;
		page=page.replace("#","");

		// post this to the page
		$.post(page,{
		   'ajaxrequest':'deletecommitmentfromschedule',
		   'id':id
		   },
		   function(data){// when done, either show an alert that the delete failed or clear the radio buttons and the name field
			if(data=="success"){
				$('#checkbox_' + id).attr('checked',false);// uncheck the radio button for the member
				$('#friend-checkbox_' + id).attr('checked',false);// uncheck the friend
				$('#participant-name_' + id).val('');// clear the name
				$('#delete_' + id + 'div').slideUp('slow');// close the div
				$('#delete_' + id).css('display','none');// clear the delete image
			}
			else{
				alert('Were sorry, but something went wrong and your entry could not be deleted.  Please notify your webmaster.');
				$('#delete_' + id + 'div').slideUp('slow');// close the div
				$('#delete_' + id).css('display','none');// clear the delete image
			}

		   }
		);


	});

});// end of jquery block


