//------------
//	On Load
//------------
$(function() {
	var currentStep = 0;  //current step to start load 0 = step 1, 1 = step 2 ....
	$(document).ajaxError(function(){
		if (window.console && window.console.error) {
			//console.error(arguments);
		}
	});
	loadStep(currentStep);//Start advanced search on the first step
	loadDivStepEvents(currentStep);//load events for first step

});

//------------
//	Main function for controlling all events and loading of a step.
//------------
	var loadStep = function(currentStep){
		$('#buttonNext').attr('disabled',true);
		loadProgressBar(currentStep);	//load progress bar 
		displayDivStep(currentStep);	//display proper step div 
		loadDivFootControls(currentStep);
	}
//------------
//	Load progress bar and proper images for current step and non current steps as well as events, starting at 0 - 5, 0 = step 1...
//------------
	var loadProgressBar = function(currentStep){
		var literalStep =currentStep+1;
		// unbind all events from progress images
		// set each progress bar image to non selected version
		$('.imgStep').unbind().each(
			function(i){
				$(this).attr('style', '');//remove cursor pointer from all images in progress
				if(i < currentStep)				
					$(this).attr('src', glob.file_path+'images/progress_step' + (i+1) + '.gif'); // change image to non selected
				else
					$(this).attr('src', glob.file_path+'images/progress_step' + (i+1) + '_locked.gif'); // change image to non selected			
			}
		);
		
		//set cursor pointer for all image steps less the current step, and bind on click event
		$('.imgStep:lt('+currentStep+')').each(
			function(i){
				$(this).attr('style', 'cursor: pointer');
				$(this).bind('click', 
					function(e){
						loadStep(i);
						$('#buttonNext').attr('disabled',false);
					}
				);
			}
		);		
		//set current step image to selected
		$('.imgStep:eq('+currentStep+')').attr('src', glob.file_path+'images/progress_step' + literalStep + '_selected.gif');
	}
//------------
//	Hide all step divs except the current step, starting at 0 - 5, 0 = step 1...
//------------
	var displayDivStep = function(currentStep){
		$('.step').hide();
		$('.step:eq('+currentStep+')').show();	
	}
	
//------------
//	Add to select box
//------------
	var adYears = function(evt) {
		var d = $(evt.target);
		var dParent = d.parent().attr('parent');//the parent element has an attribute 'parent' with a value of true
		if(dParent){
			d = $(evt.target).parent();
		}//set d to be whole list element 
		d.unbind('click');
		$('a',d).html('Remove [-]');
		$('#ulSelectedYearsList').append(d);
		d.bind('click', rmYears);
		$('#buttonNext').attr('disabled',false);
		return false;
	}

//------------
//	Remove from select box
//------------
	var rmYears = function(evt) {
		var d = $(evt.target);
		var dParent = d.parent().attr('parent');
		if(dParent){
			d = $(evt.target).parent();
		}
		d.unbind('click');
		$('a',d).html('Add [+]');
		$('#ulAvailableYearsList').append(d);
		d.bind('click', adYears);
		if($('#ulSelectedYearsList>li').length ==0)
			$('#buttonNext').attr('disabled',true);
		return false;
	}
//------------
//	Add all years
//------------
	var addAllYears = function() {
		$('li','#ulAvailableYearsList').each(
			function(e){
				$('#ulSelectedYearsList').append(this);
				$('a', this).html('Remove [-]');
				$(this).unbind().bind('click', rmYears);
			}
		);
		$('#buttonNext').attr('disabled',false);
		return false;
	}
//------------
//	Remove all years
//------------
	var removeAllYears = function() {
		$('li','#ulSelectedYearsList').each(
			function(e){
				$('#ulAvailableYearsList').append(this);
				$('a',this).html('Add [+]');
				$(this).unbind().bind('click', adYears);
			}
		);
		$('#buttonNext').attr('disabled',true);
		return false;
	}
//------------
//	Add to select box
//------------
	var adMun = function(evt) {
		var d = $(evt.target);
		var dParent = d.parent().attr('parent');//the parent element has an attribute 'parent' with a value of true
		if(dParent){
			d = $(evt.target).parent();
		}//set d to be whole list element 
		
		//check if element already exists in selected list, this can occure when using the filter...
		if($('#ulSelectedMun>li[skhdid='+ d.attr('skhdid')+']').length ==0 ){
			d.unbind('click');
			$('a',d).html('Remove [-]');
			$('#ulSelectedMun').append(d);
			d.bind('click', rmMun);
			$('#buttonNext').attr('disabled',false);
		}
		else{
			$(d).remove()	
		}

		var m = $('#ulSelectedMun>li').length;		
		$('#spanSelectedMunNo').text(m);
		
		var x = 200/numberOfYears;
		x = Math.round(x);
		$('#spanMaxMun').text(x);
		$('#spanSelectedMunNo').text(m);
		
		if(x >= m)
			$('#buttonNext').attr('disabled',false);
		else
			$('#buttonNext').attr('disabled',true);
		
		
		return false;
	}

//------------
//	Remove from select box
//------------
	var rmMun = function(evt) {

		var d = $(evt.target);
		var dParent = d.parent().attr('parent');
		if(dParent){
			d = $(evt.target).parent();
		}
		d.unbind('click');
		$('a',d).html('Add [+]');
		$('#ulAvailableMun').append(d);
		d.bind('click', adMun);
		
		var m = $('#ulSelectedMun>li').length;		
		$('#spanSelectedMunNo').text(m);
		
		var x = 200/numberOfYears;
		x = Math.round(x);
		$('#spanMaxMun').text(x);
		$('#spanSelectedMunNo').text(m);
		
		if(x >= m)
			$('#buttonNext').attr('disabled',false);
		else
			$('#buttonNext').attr('disabled',true);
		
		return false;
	}
//------------
//	Add all municipalities
//------------
	var addAllMun = function() {
	
		$('li','#ulAvailableMun').each(
			function(e){
				if($('#ulSelectedMun>li[skhdid='+ $(this).attr('skhdid')+']').length ==0 ){
					$('#ulSelectedMun').append(this);
					$('a', this).html('Remove [-]');
					$(this).unbind();
					$(this).bind('click',rmMun);
				}
				else
					$(this).remove();
			}
		);
		var m = $('#ulSelectedMun>li').length;		
		$('#spanSelectedMunNo').text(m);
		
		var x = 200/numberOfYears;
		x = Math.round(x);
		$('#spanMaxMun').text(x);
		$('#spanSelectedMunNo').text(m);
		
		if(x >= m)
			$('#buttonNext').attr('disabled',false);
		else
			$('#buttonNext').attr('disabled',true);

		return false;
	}
//------------
//	Remove all municipalities
//------------
	var removeAllMun = function() {
		$('li','#ulSelectedMun').each(
			function(e){
				$('#ulAvailableMun').append(this);
				$('a',this).html('Add [+]');
				$(this).unbind();
				$(this).bind('click',adMun);
			}
		);
		$('#buttonNext').attr('disabled',true);
		var m = $('#ulSelectedMun>li').length;		
		$('#spanSelectedMunNo').text(m);
		return false;
	}
//------------
// Validate step 3 page
//------------
	var validateStep3 = function(){
		if($('#radioYesPop').attr('checked')){
			var deltaPop = $('#textTo').val() - $('#textFrom').val();
			if(	deltaPop > 0 && $('#selectPopulationYear').val() !=0 && $('#ulStatusTypes>li>input:checked').length!=0)
				return true;
			else
				return false;
		}
		else
			if($('#ulStatusTypes>li>input:checked').length!=0)//check status textboxes if none are empty
				return true;
		
		/*if(	$('#textFrom').val().length !=0 && $('#textTo').val().length !=0 && 
			$('#selectPopulationYear').val() !=0 && $('#ulStatusTypes>li>input:checked').length!=0)
				return true;
				
		*/
		return false;
	}
//------------
// FLTR stakeholders
//------------	
	$.fn.search = function() {
		$('#divStep4Load').show();
	  	$(this).keyup(
			function(e){
				var searchString = $(this).val();
				var tempMunArr = jQuery.grep(superArr, function(n,i){
					return (n.LEGALNAME.match( RegExp(searchString, 'i')));
				});
				
				var skhdNames = [];
				$('#ulSelectedMun>li').each(
					function(i){
						skhdNames[i]= ' ' + $(this).attr('skhdid');
					}
				);
				
				
				//add muncs based on search string
				$('#ulAvailableMun').empty();
				var ul = $('#ulAvailableMun');
					$.map(tempMunArr, 
						function(g){
							ul.append('<li class="date" parent="true" skhdId="'+ g.MUNCODE +'" skhdName="'+ g.LEGALNAME +'" skhdType="'+ g.TYPE +'"><a>Add [+]</a><span>'+g.MUNCODE +'  </span>'+g.LEGALNAME+'</li>');	
						}
				);//end map
				
				//add events to muncs
				$('#ulAvailableMun>li').unbind('click');
				$('#ulAvailableMun>li').each(
					function(e){
						$(this).bind('click',adMun);
					}
				);						
				
			}
		);//end keyup
		$('#divStep4Load').hide();
	}
//------------
// Drop element into proper container assign events
//------------
	var reportSetup =function(bomb, target){
			var currentElement = target;	 	 // element that is the container recieving the drop
			var dropElement = bomb;				// element being dropped
	
			//clear container
			$("ul",currentElement).empty();
			
			//add to containter
			$("ul",currentElement).append('<li class="droppedOption">'+dropElement.text()+' </li>');
	
			//remove from Items list
			$(dropElement).remove();
	
			//add event to [-]
			$("span",currentElement).unbind();
			$("span",currentElement).bind('click', 
				function(){
					//add item to Items list
					$('#listSelectOptions').append('<li class="selectedOption" id="' + dropElement.attr('id') + '">' + dropElement.text() + '</li>');						
					
					//re-enable container
					$(currentElement).droppable("enable");
					
					//remove item from container	
					$("li",currentElement).remove();
					
					//make moved item in Items draggable again
					var newId = '#' + dropElement.attr('id');
					$(newId).draggable({helper: 'clone',zindex: '500'});
					if($('#listSelectOptions>li').length == 0)
						$('#buttonComplete').attr('disabled', false); 
					else
						$('#buttonComplete').attr('disabled', true); 
				}
			);
		}
//------------
// this function is ran when the user enters a step for the first time	
// load current div step, starting at 0 - 5, 0 = step 1..., attach all events
//------------
	var loadDivStepEvents = function(currentStep){		
		switch(currentStep){	
			case 0:	
			//populate profiles select box	
				$.ajax({
					type:'GET',
					url:glob.file_path+'proxy.cfm/getProfiles',
					data: {},
					dataType: 'json',
					success:function(result){										
							//retrieve result and map it to an array
								$("#selectProfile").removeOption(/./);
								$("#selectProfile").addOption(0,'- Profile -',false);
								var opts = {};
								$.map(result.CONTENTS, 
									function(g){
										opts[g.TYPEDESC] = g.PROFILENAME;
									}
								);//end map
								
							// update the select
								$('#selectProfile').addOption(opts, false);
								$('#selectProfile').sortOptions();
							},
					error:  function(req, errtype, err){	
								alert('getProfiles is unavailable.');
							}
				});						

			//setup profile select box events
				$('#selectProfile').unbind();
				$('#selectProfile').bind('change',
					function(e){
						if($("#selectProfile").val() != 0){ 
							$.ajax({
								type:'GET',
								url:glob.file_path+'proxy.cfm/getProfileContents',
								data: {selectedProfileValue: $(this).val()},
								dataType: 'json',
								success: function(result){
											$('#ulProfileContents').empty();//clear profile contents
											$('#ulProfileContents2').empty();//clear profile contents
											$('#buttonNext').attr('disabled', true);
											$.map(result.CONTENTS, 
												function(g, i){
													if(i%2 != 0)
														$('#ulProfileContents2').append('<li>'+g+'</li>');
													else
														$('#ulProfileContents').append('<li>'+g+'</li>');
												}
											);
											$('#divProfileContents').show();//hide profile contents heading
											$('#buttonNext').attr('disabled',false);											
										},
								error:  function(req, errtype, err){	
											alert('getProfileContents is unavailable');
										}
							});
						}
						else{
							$('#ulProfileContents').empty();
							$('#ulProfileContents2').empty();
							$('#buttonNext').attr('disabled', true);	
						}
					}
				);
				break;
			case 1:
					//reset radio buttons to not selected
					$('input:radio', '#divStep2').each(function(){
							$(this).attr('checked', false);
						});
					$('#yrRange').hide();						
					$('#yrInd').hide();

                    //get available years
					var loadYears = function(e){
						//populate from years
						$.ajax({
							type: 'GET',
							url: glob.file_path + 'proxy.cfm/getYears',
							data: {'selectedProfileValue': $('#selectProfile').val()},
							dataType: 'json',
							async: false,
							success: function(result){
										years = result;
									},
							error: function(req, errtype, err){	
										alert('getYears is unavailable.');
									}
							});//end ajax
					};
					loadYears();

					var $fysel = $("#selectFromYear");
					var $tysel = $("#selectToYear");
					//year range
					$('#radioYearRange').unbind().bind('click', function(e){
							$('#buttonNext').attr('disabled', true);
							$('#yrInd').hide()	
							$('#yrRange').show();						
							$tysel.removeOption(/./).addOption(0, '- Year -', false);										

							//populate from years
							$fysel.removeOption(/./).addOption(0, '- Year -', false);
							$.each(years, function(i, y){$fysel.addOption(y, y, false)});
							$fysel.sortOptions();
							}
					);
					
					//re-populate to years everytime there is a change made to from years
					$('#selectFromYear').unbind().bind('change', function(e){
							$('#buttonNext').attr('disabled',true);
							$tysel.removeOption(/./).addOption(0, '- Year -', false);										
							$.each(years, function(i, y){
									if($fysel.val() <= y)
										$tysel.addOption(y, y, false);
							});
							$tysel.sortOptions();										
						});

					//set next button to true if to year selected
					$('#selectToYear').unbind().bind('change', function(e){
							if($("#selectToYear").val() != 0)
								$('#buttonNext').attr('disabled',false);
							else
								$('#buttonNext').attr('disabled',true);
						});
					
					//individual years	
					var $sylst = $("#ulSelectedYearsList");
					var $aylst = $("#ulAvailableYearsList");
					$('#radioIndividualYear').unbind().bind('click', function(e){
							$('#buttonNext').attr('disabled', true);
							$('#yrRange').hide();
							$('#yrInd').show();						

							$sylst.empty();
							$aylst.empty();
							$.each(years, function(i, y){
									$aylst.append('<li class="date" parent="true" year="'+y+'"><a>Add [+]</a>'+y+'</li>');	
								});
							//events for clicking on years
							$aylst.find('li').unbind('click').each(function(e){
									$(this).bind('click', adYears);
								});

						});

					$('#buttonAddAllYears').unbind('click').bind('click', addAllYears);
					$('#removeAllYears').unbind('click').bind('click', removeAllYears);
				break;
			case 2:
				//reset radio buttons to not selected
				$('input:radio', '#divStep3').each(
					function(){
						$(this).attr('checked', false);
					}
				);
				//reset all munc types checkboxes
				$('#ulStatusTypes>li>input').attr('checked',false);
				
				//check no selection for population radio buttons
				$('#radioNoPop').attr('checked',true);
				$('#divMuncipalPopulation').hide();
				
				//clear from to populationListYear
				$('#textTo').val('');
				$('#textFrom').val('');
				
				//events status type checkboxes, if no selected disable next else enable next (and optional No)
				$('li','#ulStatusTypes').unbind();	
				$('li','#ulStatusTypes').bind('click',
					function(e){
						if(	validateStep3())
							$('#buttonNext').attr('disabled',false);
						else
							$('#buttonNext').attr('disabled', true);					
					}
				);
				
				//events for population radio buttons
				$('#radioYesPop').unbind();
				$('#radioYesPop').bind('click',
					function(e){
						$('#divMuncipalPopulation').show();
						$('#buttonNext').attr('disabled',true);
											
					//populate list years
						$.ajax({
							type:'GET',
							url:glob.file_path+'proxy.cfm/getPopulationYears',
							data: {	'selectedProfile': $('#selectProfile option:selected').text() ,
									'selectedProfileValue':$('#selectProfile').val()},
							dataType: 'json',
							success: function(result){							
										$("#selectPopulationYear").removeOption(/./);
										$("#selectPopulationYear").addOption(0,'- Year -',false);										
										$.map(result, 
											function(g){
												$('#selectPopulationYear').addOption(g,g,false);
											}
										);//end map									
										$('#selectPopulationYear').sortOptions();										
									},
							error: function(req, errtype, err){	
										alert('getYears(population) is unavailable.');
									}
						});//end ajax
					}
				);
				
				//events radio button no
				$('#radioNoPop').unbind();
				$('#radioNoPop').bind('click',
					function(e){
						$('#divMuncipalPopulation').hide();
						if(	validateStep3())
							$('#buttonNext').attr('disabled',false);
						else
							$('#buttonNext').attr('disabled',true);
					}
				);
				
				$('#textFrom, #textTo').each(
					function(e){
						$(this).keyup(
							function(e){
								var cur = $(this).val().replace(/[^0-9]/g ,'');
								$(this).val(cur);
								if(validateStep3())
									$('#buttonNext').attr('disabled',false);
								else
									$('#buttonNext').attr('disabled',true);
							}
						);
					}
				);
				
				$('#selectPopulationYear').unbind();
				$('#selectPopulationYear').bind('change',
					function(e){
						if(	validateStep3())
							$('#buttonNext').attr('disabled',false);
						else
							$('#buttonNext').attr('disabled',true);
					}
				);
				//select all button
				$('#buttonSelectAllType').unbind();
				$('#buttonSelectAllType').bind('click',
					function(e){
						if($('#ulStatusTypes>li>input:checked').length == 8)
							$('#ulStatusTypes>li>input').attr('checked',false);
						else
							$('#ulStatusTypes>li>input').attr('checked',true);
						if(validateStep3())
							$('#buttonNext').attr('disabled',false);
						else
							$('#buttonNext').attr('disabled',true);

					}
				);
				break;
			case 3:
				//clear step 
				$('#ulAvailableMun').empty();
				$('#ulSelectedMun').empty();
				$('#textFLTRstakeholder').val('');
				//clear radio buttons
				$('#filterBy>li>input:checked').attr('checked',false); 	
			
				//get types
				var skhTypes = [];			
				$('#ulStatusTypes>li>input:checked').each(
					function(i){
						skhTypes[i] = $(this).val();
					}
				);
				
				var selectedYears = [];
				if($('#radioIndividualYear').attr('checked') == false){
					var j = 0;
					$('option', '#selectFromYear').each(
						function(i){
							var curVal = $(this).val();
							if($('#selectFromYear').val() <= curVal && $('#selectToYear').val() >= curVal){
								selectedYears[j] = curVal;
								j++;
							}
						}
					);
				}
				else{
					$('#ulSelectedYearsList>li').each(
						function(i){
							var curVal = $(this).attr('year');
							selectedYears[i] = curVal;
						}
					);
				}
				numberOfYears = 0;
				numberOfYears = selectedYears.length;
				var x = 200/numberOfYears;
				x = Math.round(x);
				$('#spanMaxMun').text(x);
				$('#spanSelectedMunNo').text('0');
							
				//sort by name
				$('#radioSortName').unbind();
				$('#radioSortName').bind('click',
					function(e){
						var aa = $.makeArray($('#ulAvailableMun').children()).sort(
							function(a, b) { 
								if( $(a).attr('skhdName') > $(b).attr('skhdName'))
									return 1;
								else return -1;
							}
						);
						$('#ulAvailableMun').empty();
						$('#ulAvailableMun').append(aa);
					//events for clicking on skhd
						$('#ulAvailableMun>li').unbind('click');
						$('#ulAvailableMun>li').each(
							function(e){
								$(this).bind('click',adMun);
							}
						);
					}//end function(e)
				);//end bind
				
				//sort by type
				$('#radioSortType').unbind();
				$('#radioSortType').bind('click',
					function(e){
						var aa = $.makeArray($('#ulAvailableMun').children()).sort(
							function(a, b) { 
								if( $(a).attr('skhdSort') > $(b).attr('skhdSort'))
									return 1;
								else return -1;
							}
						);
						$('#ulAvailableMun').empty();
						$('#ulAvailableMun').append(aa);
					//events for clicking on skhds
						$('#ulAvailableMun>li').unbind('click');
						$('#ulAvailableMun>li').each(
							function(e){
								$(this).bind('click',adMun);
							}
						);
					}//end function(e)
				);//end bind
				
				//munc code display events
				$('#checkboxDisplayMunCode').unbind();
				$('#checkboxDisplayMunCode').bind('click',
					function(e){
						if($('#checkboxDisplayMunCode').attr('checked')){
							$('#ulAvailableMun>li>span').each(
								function(e){
									$(this).show();
								}
							);	
							$('#ulSelectedMun>li>span').each(
								function(e){
									$(this).show();
								}
							);	
						}
						else{
							$('#ulAvailableMun>li>span').each(
								function(e){
									$(this).hide();
								}
							);
							$('#ulSelectedMun>li>span').each(
								function(e){
									$(this).hide();
								}
							);								
						}					
					}//end function
				);
								
				//populate Stakeholders	
				$.blockUI({  
					message: '<h1>Processing</h1>',  
					css: { 
						border: 'none', 
						padding: '15px', 
						backgroundColor: '#000', 
						color: '#fff' 
					}   ,
					overlayCSS: { backgroundColor: '#E0E0E0' }
				});
				
				$.ajax({
					type:'GET',
					url:glob.file_path+'proxy.cfm/getSKH',
					data: { 'skhType':skhTypes.join(','),
							'selectedYear':selectedYears.join(','),
							'rangeFrom':$('#textFrom').val() || -1,
							'rangeTo': $('#textTo').val() || -1 ,
							'populationListYear':$('#selectPopulationYear').val() || -1,
							'populationRange':$('#radioYesPop').attr('checked') },
					dataType: 'json',
					 async: true , //false to lock browser
					success: function(result){	
							//retrieve result and map it to an array	
								if(result.STAKEHOLDER != "isEmpty"){			
									var ul = $('#ulAvailableMun');
									$.map(result.STAKEHOLDER, 
										function(g){
											ul.append('<li class="date" parent="true" skhdSort="'+ g.SORTSTATUS+ '" skhdId="'+ g.MUNCODE +'" skhdName="'+ g.LEGALNAME +'" skhdType="'+ g.TYPE +'"><a>Add [+]</a><span style="display: none">'+g.MUNCODE+'</span> '+g.LEGALNAME+'</li>');	
										}
									);//end map
									superArr = "";
									superArr = result.STAKEHOLDER;
									
									var aa = $.makeArray($('#ulAvailableMun').children()).sort(
										function(a, b) { 
											if( $(a).attr('skhdSort') > $(b).attr('skhdSort'))
												return 1;
											else return -1;
										}
									);
									$('#ulAvailableMun').empty();
									$('#ulAvailableMun').append(aa);
									
								//events for clicking on years
									$('#ulAvailableMun>li').unbind('click');
									$('#ulAvailableMun>li').each(
										function(e){
											$(this).bind('click',adMun);
										}
									);
									$('#textFLTRstakeholder').search(); //bind search event to keyup of searchbox	
								}
								else {
									alert('Please change your search criteria; current search criteria returned no results for municipalities.');
								}
								$.unblockUI();
								
								},
					error: function(req, errtype, err){	
								//alert('getMunicipalByTypeAndYears is unavailable.');
								alert('Get Stakeholders is unavailable, please try again.');
								$.unblockUI();
							}
				});//end ajax
				
				$('#buttonAddAllMunc').unbind(); 
				$('#buttonAddAllMunc').bind('click', 
					function(e){
						$.blockUI({  
							message: '<h1>Processing</h1>',  
							css: { 
								border: 'none', 
								padding: '15px', 
								backgroundColor: '#000',  
								color: '#fff' 
							}   ,
							overlayCSS: { backgroundColor: '#E0E0E0' }
						});
						
						$.ajax({
							type:'GET',
							url:glob.file_path+'proxy.cfm/getTrue',
							data: { },
							dataType: 'json',
							success: function(result){	
									//retrieve result and map it to an array	
										addAllMun();
										$.unblockUI(); 	},
							error: function(req, errtype, err){	
										$.unblockUI;
										//alert(err + ' ' + req + ' ' + errtype);
										alert('getTrue is unavailable.');
									}
						});//end ajax					
					}
				);
				
				$('#buttonRemoveAllMunc').unbind();
				$('#buttonRemoveAllMunc').bind('click', 
					function(e){
						$.blockUI({  
							message: '<h1>Processing</h1>',  
							css: { 
								border: 'none', 
								padding: '15px', 
								backgroundColor: '#000',  
								color: '#fff' 
							}   ,
							overlayCSS: { backgroundColor: '#E0E0E0' }
						});
						
						$.ajax({
							type:'GET',
							url:glob.file_path+'proxy.cfm/getTrue',
							data: { },
							dataType: 'json',
							success: function(result){	
									//retrieve result and map it to an array	
										removeAllMun();
										$.unblockUI(); 	},
							error: function(req, errtype, err){	
										$.unblockUI;
										alert('getTrue is unavailable.');
									}
						});//end ajax					
					}
				);		
				
				break;
			case 4:
				var skhTypes = [];
				$('#ulStatusTypes>li>input:checked').each(
					function(i){
						skhTypes[i] = ' ' +$(this).attr('mun');
					}
				);
				
				var selectedYears = [];
				if($('#radioIndividualYear').attr('checked') == false){
					var j = 0;
					$('option', '#selectFromYear').each(
						function(i){
							var curVal = $(this).val();
							if($('#selectFromYear').val() <= curVal && $('#selectToYear').val() >= curVal){
								selectedYears[j] = ' ' +curVal;
								j++;
							}
						}
					);
				}
				else{
					$('#ulSelectedYearsList>li').each(
						function(i){
							var curVal = $(this).attr('year');
							selectedYears[i] = ' ' + curVal;
						}
					);
				}	
				
				var skhdNames = [];
				$('#ulSelectedMun>li').each(
					function(i){
						skhdNames[i]= ' ' + $(this).attr('skhdname');
					}
				);
				//populate step summary sections
				$('#pStep1').html('<b>Profile:</b> ' + $('#selectProfile option:selected').text());
				$('#pStep2').html('<b>Years:</b> ' + 	selectedYears.sort());	
				$('#pStep3').html('<b>Stakeholder Types:</b> ' + 	skhTypes);
				if($('#radioYesPop').attr('checked'))					  
					$('#pStep3').append('<p><b>Population From:</b> ' + $('#textFrom').val() + ' <b>Population To:</b> ' + $('#textTo').val() + ' <b>Population Year:</b> ' + $('#selectPopulationYear').val() +'</p>');
				$('#ulMuncs1, #ulMuncs2, #ulMuncs3').empty();
				var i =0;
				for(i = 0; skhdNames.length > i;){
					$('#ulMuncs1').append('<li>'+skhdNames[i]+'</li>');
					if(skhdNames.length > i+1)
						$('#ulMuncs2').append('<li>'+skhdNames[i+1]+'</li>');
					if(skhdNames.length > i+2)
						$('#ulMuncs3').append('<li>'+skhdNames[i+2]+'</li>');
					i=i+3;
				}

				break;
				
			case 5:
			//clear step
				$('#selectPopYear6').removeOption(/./);
				$('#checkboxPopYear6').attr('checked',false);
				$('#radioFormatPDF').attr('checked',true);
				$('#selectReportLayout').selectOptions('default');
				$('#buttonComplete').attr('disabled', true);				
				var myOptions = {
					"default" : "- Select Predefined Layout -",
					"1" : "Municipal Profiles Line Items by Municipality for Year",
					"4" : "Municipal Profiles Line Items by Year for Municipality"
				}
				$("#selectReportLayout").removeOption(/./);
				$("#selectReportLayout").addOption(myOptions, false);
				$('#tdContent').text('Content: ' + $('#selectProfile option:selected').text());
				
		//reset the Items list 
				$('#listSelectOptions').empty();
				$('#listSelectOptions').append('<li class="selectedOption" id="selectedOptionYears" value="1">Years</li>');			
				$('#listSelectOptions').append('<li class="selectedOption" id="selectedOptionMun" value="2">Municipalities</li>');
				$('#listSelectOptions').append('<li class="selectedOption" id="selectedOptionLI" value="3">Line Items</li>');
				$("ul",'.optionY').empty();
				$("ul",'.optionX').empty();
				$("ul",'.optionPage').empty();
				
			//poplation year in step 3 ?
				if($('#radioYesPop').attr('checked')){
					var popYear = $('#selectPopulationYear').val();
					$('#selectPopYear6').addOption(popYear, popYear);
				}
				else{
					//populate list years
					$.ajax({
						type:'GET',
						url:glob.file_path+'proxy.cfm/getPopulationYears',
						data: {	'selectedProfile': $('#selectProfile option:selected').text() ,
								'selectedProfileValue':$('#selectProfile').val()},
						dataType: 'json',
						success: function(result){							
									$('#selectPopYear6').removeOption(/./);
									$('#selectPopYear6').addOption(0,'- Year -',false);										
									$.map(result, 
										function(g){
											$('#selectPopYear6').addOption(g,g,false);
										}
									);//end map									
									$('#selectPopYear6').sortOptions();										
								},
						error: function(req, errtype, err){	
									alert('getPopulationYears(population) is unavailable.');
								}
					});//end ajax				
				}
				//pdf xls 
				$('#radioFormatPDF').bind('click', 
					function(e){
						var myOptions = {
							"default" : "- Select Predefined Layout -",
							"1" : "Municipal Profiles Line Items by Municipality for Year",
							"4" : "Municipal Profiles Line Items by Year for Municipality"
						}
						$("#selectReportLayout").removeOption(/./);
						$("#selectReportLayout").addOption(myOptions, false);
						//reset the Items list before moving them around
						$('#listSelectOptions').empty();
						$('#listSelectOptions').append('<li class="selectedOption" id="selectedOptionYears" value="1">Years</li>');			
						$('#listSelectOptions').append('<li class="selectedOption" id="selectedOptionMun" value="2">Municipalities</li>');
						$('#listSelectOptions').append('<li class="selectedOption" id="selectedOptionLI" value="3">Line Items</li>');
						$("ul",'.optionY').empty();
						$("ul",'.optionX').empty();
						$("ul",'.optionPage').empty();
						if($('#listSelectOptions>li').length == 0)
							$('#buttonComplete').attr('disabled', false);
						else
							$('#buttonComplete').attr('disabled', true);						
					}				
				);
				
				$('#radioFormatXLS').bind('click', 
					function(e){
						if($('#selectProfile').val() != "FINA" || $('#selectProfile').val() != "FIN8"){
							var myOptions = {
								"default" : "- Select Predefined Layout -",
								"1" : "Municipal Profiles Line Items by Municipality for Year",
								"2" : "Municipal Profiles Municipality by Line Items for Year",
								"4" : "Municipal Profiles Line Items by Year for Municipality",
								"3" : "Municipal Profiles Years by Line Items for Municipality"
							}
						}
						else{
							var myOptions = {
								"default" : "- Select Predefined Layout -",
								"1" : "Municipal Profiles Line Items by Municipality for Year",
								"4" : "Municipal Profiles Line Items by Year for Municipality"
							}
						}
						$("#selectReportLayout").removeOption(/./);
						$("#selectReportLayout").addOption(myOptions, false);
						//reset the Items list before moving them around
						$('#listSelectOptions').empty();
						$('#listSelectOptions').append('<li class="selectedOption" id="selectedOptionYears" value="1">Years</li>');			
						$('#listSelectOptions').append('<li class="selectedOption" id="selectedOptionMun" value="2">Municipalities</li>');
						$('#listSelectOptions').append('<li class="selectedOption" id="selectedOptionLI" value="3">Line Items</li>');
						$("ul",'.optionY').empty();
						$("ul",'.optionX').empty();
						$("ul",'.optionPage').empty();
						if($('#listSelectOptions>li').length == 0)
							$('#buttonComplete').attr('disabled', false);
						else
							$('#buttonComplete').attr('disabled', true);						
					}				
				);			
				$('#selectReportLayout').bind('click',
					function(e){
						//reset the Items list before moving them around
						$('#listSelectOptions').empty();
						$('#listSelectOptions').append('<li class="selectedOption" id="selectedOptionYears" value="1">Years</li>');			
						$('#listSelectOptions').append('<li class="selectedOption" id="selectedOptionMun" value="2">Municipalities</li>');
						$('#listSelectOptions').append('<li class="selectedOption" id="selectedOptionLI" value="3">Line Items</li>');
						$("ul",'.optionY').empty();
						$("ul",'.optionX').empty();
						$("ul",'.optionPage').empty();
						switch($(this).val()){
							case "1"://YML Page: Years, 				Columns: Municipalities, Rows: Line Items
								reportSetup($('#selectedOptionYears'),$('.optionPage'));
								reportSetup($('#selectedOptionMun'),$('.optionX'));
								reportSetup($('#selectedOptionLI'),$('.optionY'));
								break;
							case "2"://YLM Page: Years, 				Columns: Line Items, 	 Rows: Municipalities	
								reportSetup($('#selectedOptionYears'),$('.optionPage'));
								reportSetup($('#selectedOptionMun'),$('.optionY'));
								reportSetup($('#selectedOptionLI'),$('.optionX'));
								break;
							case "3"://MLY Page: Municipalities, 		Columns: Line Items, 	 Rows: Years
								reportSetup($('#selectedOptionYears'),$('.optionY'));
								reportSetup($('#selectedOptionMun'),$('.optionPage'));
								reportSetup($('#selectedOptionLI'),$('.optionX'));
								break;
							case "4"://MYL Page: Municipalities, 		Columns: Years, 		 Rows: Line Items					
								reportSetup($('#selectedOptionYears'),$('.optionX'));
								reportSetup($('#selectedOptionMun'),$('.optionPage'));
								reportSetup($('#selectedOptionLI'),$('.optionY'));
								break;
						}	
						if($('#listSelectOptions>li').length == 0)
							$('#buttonComplete').attr('disabled', false);
						else
							$('#buttonComplete').attr('disabled', true);						
					}
				);
				
				//disable droppables at start for pds, enable when xls is selected
			break;//end case 5
		}//end switch	
	}
//------------
//	load foot controls/buttons assign proper events to buttons, event are only loaded when user clicks next button
//------------
	var loadDivFootControls = function(currentStep){
		$('.button','#divFootControls').unbind();//unbind all events from buttons
		$('.button','#divFootControls').hide();//hide all buttons
  name="skhType"
		switch(currentStep){	
			case 0:
				$('#buttonNext').show().bind('click', function(e){loadStep(1); loadDivStepEvents(1);});
				break;
			case 1:
				$('#buttonNext').show().bind('click', function(e){loadStep(2); loadDivStepEvents(2); });
				$('#buttonBack').show().bind('click', function(e){loadStep(0); $('#buttonNext').attr('disabled',false);});
				break;
			case 2:
				$('#buttonNext').show().bind('click', function(e){loadStep(3); loadDivStepEvents(3);});
				$('#buttonBack').show().bind('click', function(e){loadStep(1); $('#buttonNext').attr('disabled',false);});
				break;
			case 3:
				$('#buttonNext').bind('click', 
					function(e){
						//sort elemnts according to ssort on leaving page
						var aa = $.makeArray($('#ulSelectedMun').children()).sort(
							function(a, b) { 
								if( $(a).attr('skhdSort') > $(b).attr('skhdSort'))
									return 1;
								else return -1;
							}
						);
						$('#ulSelectedMun').empty();
						$('#ulSelectedMun').append(aa);
					//events for clicking on skhds
						$('#ulSelectedMun>li').unbind('click');
						$('#ulSelectedMun>li').each(
							function(e){
								$(this).bind('click',rmMun);
							}
						);
						
						loadStep(4); 
						loadDivStepEvents(4);
						$('#buttonNext').attr('disabled',false);
				});
				$('#buttonNext').show();
				$('#buttonBack').bind('click', function(e){loadStep(2); $('#buttonNext').attr('disabled',false);});
				$('#buttonBack').show();
				break;
			case 4:
				$('#buttonNext').attr('disabled',false);
				$('#buttonNext').bind('click', function(e){loadStep(5); loadDivStepEvents(5); });
				$('#buttonNext').show();
				$('#buttonBack').bind('click', function(e){loadStep(3); $('#buttonNext').attr('disabled',false);});
				$('#buttonBack').show();
				break;
			case 5:
				//setup data to be passed to generate report
				var skhTypes = [];			
				$('#ulStatusTypes>li>input:checked').each(
					function(i){
						skhTypes[i] = $(this).val();
					}
				);
				
				var selectedYears = [];
				if($('#radioIndividualYear').attr('checked') == false){
					var j = 0;
					$('option', '#selectFromYear').each(
						function(i){
							var curVal = $(this).val();
							if($('#selectFromYear').val() <= curVal && $('#selectToYear').val() >= curVal){
								selectedYears[j] = ' ' + curVal;
								j++;
							}
						}
					);
				}
				
				else{
					$('#ulSelectedYearsList>li').each(
						function(i){
							var curVal = $(this).attr('year');
							selectedYears[i] = curVal;
						}
					);
				}	

				var skhCodes = [];
				$('#ulSelectedMun>li').each(
					function(i){
						var curVal = $(this).attr('skhdId');
						skhCodes[i] = curVal;
					}
				);	
					
				$('#buttonComplete').bind('click', 
					function(e){
					$.blockUI({  
						message: '<h1>Processing</h1>',  
						css: { 
							border: 'none', 
							padding: '15px', 
							backgroundColor: '#000', 
							color: '#fff' 
						}   ,
						overlayCSS: { backgroundColor: '#E0E0E0' }
					});

					var frm = document.forms.AdvancedReport;
					// you should get "Save As" dialog. No need for new window
					if ($('input#radioFormatXLS').attr('checked'))
						frm.target = '';
					else
						frm.target = '_blank';
					frm.x.value = $('ul','.optionX').text();
					frm.y.value = $('ul','.optionY').text();
					frm.page.value = $('ul','.optionPage').text();
					frm.skhCode.value = skhCodes.join(',');
					frm.selectedYear.value = selectedYears.join(',');
					frm.submit();
					$.unblockUI();
					}//end function
				);
				$('#buttonComplete').show();
				$('#buttonBack').bind('click', function(e){loadStep(4)});
				$('#buttonBack').show();
				break;
		}	
	}

