/**
* School Finder functionality - Ajax calls to pull in city/school list
*/
(function($){
$.fn.schoolFinder = function(options) {

	// Set plugin default variables
	var defaults = {
	  	selectSet			: '.select-set',
		styledSelect		: '.styled-select',
		stateSelect			: '.state-select',
		citySelect			: '.city-select',
		schoolSelect		: '.school-select',
		
		schoolTypeID		: 'school-type',
		schoolTypeInputName	: 'school type',
		schoolSearch		: '.school-search',
		schoolSearchID		: 'school-search-newsletter',
		schoolSearchInputName:'school-search',
		schoolID			: 'school-id',
	
		stateValID			: 'state-val',
		cityValID			: 'city-val',
		
		changeLink			: '#change-school',
		callout				: '.callout',
		radioSet			: '.set',
		step1				: '.step1',
		step2				: '.step2',
		errorHolder			: '.error-msg',
		
		schoolFindMenu		: '#school-find-menu',
		schoolSetMenu		: '.school-set-menu',
		
		stateListURL		: 'ajax/state.php',
		schoolSearchURL		: 'ajax/school.php',
		
		newsletterHolder	: '.newsletter-holder',
		stateInputName		: 'state-name',
		cityInputName		: 'city-name',
		schoolInputName		: 'school-name',
		
		submitForm			: true
	},
	opts = $.extend({}, defaults, options);

	this.each(function() {
		var $this = $(this);
		//now use $this instead of $(this), makes jQuery do less work
		
		
		// start my this.each() series of fn
		
		var searchField = $this.find(opts.schoolSearch).parent().html();
		
		// Clickoutside Plugin Implementation
    	$this.unbind().bind('clickoutside', function() { initClickOutside(); });
    	
    	formSet();
    		
    	// SchoolType selected
    	$this.find('.radio-set .set').unbind().bind('click' , function() {
    		$this.find(opts.step2).children('.text-set:first').html('');
    		
    		$this.find(opts.styledSelect).resetSS();
    		$this.find(opts.errorHolder).addClass('hidden');

    		// Set schoolTypeVal
    		$this.find('#'+opts.schoolTypeID).remove();
			$this.find('form').append('<input id="'+ opts.schoolTypeID +'" type="hidden" name="'+ opts.schoolTypeInputName +'" value="'+ $(opts.step1).find('input:checked').val() +'" />');
            var type = $('#school-type').val();

			_gaq.push(['_trackEvent','SchoolFinder','SchoolType',type]);

			setStates();
			
			initStyledSelect.initSelectReset();
			initStyledSelect.initStateSelect();

			showStep2();

    		$this.find(opts.step2).find('.fieldset:first').append(searchField);
    		//$this.find('.as-selections, .as-results').remove();
    		step2AutoSuggest.initSuggest();
    	});    	
		
    	$this.find(opts.schoolSearch).live('focus', function() {
    		if($this.find('#'+opts.schoolTypeID).length){} else {
    			$this.find(opts.errorHolder).removeClass('hidden').children('p').html('Please select a type of school.');
    		}    		
    		if($this.find('#'+opts.schoolTypeID).val() == 'undefined' || ''){
    			$this.find(opts.errorHolder).removeClass('hidden').children('p').html('Please select a type of school.');
    		}
    	});
    	
    	// On State Select - Ajax call to load cities
    	$this.find(opts.stateSelect).bind('change' , function() {
    		// ADD city and school select hide
    		//onStateSelect();
    		step2Selects.onStateSelect();
    	});
		
    	// On City Select - Ajax call to load schools
    	$this.find(opts.citySelect).bind('change' , function() {
    		//onCitySelect();
    		step2Selects.onCitySelect();
    	});
    	
    	// On School Select - Submit form
    	$this.find(opts.schoolSelect).bind('change' , function() {
    		//onCitySelect();
    		step2Selects.onSchoolSelect();
    		//step2Selects.setSelectedSchool();
    	});
    	
    	// Change School
    	$this.find(opts.changeLink).unbind().bind('click', changeSchool);
    	
    	$this.find('.change-school').live('click', function() {
    		setStates();
    		$this.find(opts.citySelect).parent().addClass('offscreen');
    		$this.find(opts.schoolSelect).parent().addClass('offscreen');
    		$this.find(opts.step2).removeClass('hidden offscreen');
    		$this.find(opts.schoolSetMenu).addClass('hidden');
    		return false;
    	});
    	
    	function showStep2() {
			$this.find(opts.step2).removeClass('offscreen');
			$this.find(opts.stateSelect).parent().removeClass('offscreen');
			$this.find(opts.callout).addClass('offscreen');
		}
    	
		function setStates() {
			$.ajax({
				url: baseUrl+opts.stateListURL,
				global: false,
				dataType: 'json', 
				type: 'get',
				success: function(data){
				    var option = '';
				    for (var i = 0; i < data.length; i++) {
				    	option += '<option value="' + data[i].id + '">' + data[i].name + '</option>';
			    	}
			    	$this.find(opts.stateSelect).html('<option value="0">Select your state</option>' + option);
			    	$this.find(opts.stateSelect).parent().siblings('.error-msg').addClass('hidden');
			    	$this.find(opts.stateSelect).parent().removeClass('loading');
			    	//initStyledSelect.initSelectReset();
					initStyledSelect.initStateSelect();
			    },
			    error: function(req,error){
			    	$this.find(opts.stateSelect).parent().siblings('.error-msg').removeClass('hidden').children('p').html('Apologies, the school finder is temporarily unavailable. Please check back soon.');
			    	$this.find(opts.stateSelect).parent().addClass('offscreen');
			    	//$this.find(opts.schoolSearch).parent().addClass('offscreen');
			    	$this.find(opts.stateSelect).parent().siblings('.fieldset, p').addClass('offscreen').hide();
		    	},
		    	complete: function() {		  
		    		$this.find(opts.stateSelect).parent().removeClass('loading');  		    	
		    	}
	    	});
		}
		
		var step2AutoSuggest = {
			/* 
			*  Initialize autoSuggest feature
			*  jquery.autoSuggest.js plugin needed - code.drewwilson.com/entry/autosuggest-jquery-plugin
			*  Using Version 1.4
			*/
			initSuggest: function() {		
		    	$this.find(opts.schoolSearch).autoSuggest(
					baseUrl + opts.schoolSearchURL,
					{
						startText: 'Type the name of your school', minChars: 3, queryParam: 'search', extraParams: '&type='+ $('#school-type').val(),
						selectedItemProp: "name", //name of object property
						selectedValuesProp: "id", //name of object property
						searchObjProps: "name",
						selectionLimit: 0,
						emptyText: 'Sorry, we can\'t seem to find your school. <br /><br />If you are sure the information entered is correct, please contact us at 1-800-BALFOUR (1-800-225-3687), so we may help you further.',
						selectionClick: function(elem){ elem.remove(); },
						selectionAdded: function(elem){ elem.remove(); },
						selectionRemoved: function(elem){ elem.remove(); },
						resultClick: function(data){

							// -- workaround for defect [DE2021] - JP 12-15-10
							$(".as-values").val(data.attributes.id);
							
							$this.find('.as-selections').addClass('loading');
							$this.find('as-results').hide();
							
							$this.find('#'+opts.schoolID).remove();
							$this.find('#'+opts.schoolSearchID).remove();
							$this.find('form').append('<input id="'+ opts.schoolID +'" type="hidden" name="school-id" value="'+ $this.find('.as-values').val().replace(",", "") +'" />');
							$this.find('form').append('<input id="'+ opts.schoolSearchID +'" type="hidden" name="'+ opts.schoolSearchInputName +'" value="'+ $(this).text() +'" />');

							if(opts.submitForm == true) {
								$this.find('form').submit();
								$this.find(opts.schoolSelect).parent().addClass('loading');
							} else {
								$this.find(opts.step2).addClass('hidden');
								$this.find(opts.schoolSetMenu).html('').removeClass('hidden').append('<p>'+$(this).text()+'</p><a class="change-school" href="#" title="Change School">Change School</a>');
								$this.find(opts.step2).find('.loading').removeClass('loading');
								return false;
							}
						}
					}
				);
		    }
		}		
		
		
		var step2Selects = {
			onStateSelect: function() {
				var stateVal 	= $this.find(opts.stateSelect).val();
				
				if($this.find("#"+opts.schoolTypeID).length == 0) {
					$this.find(opts.errorHolder).removeClass('hidden').children('p').html('Please select a type of school.');
					$this.find(opts.stateSelect).children('option:first-child').attr('selected' , 'selected');
				    //$this.find(opts.stateSelect).resetSS();
					//resetForm();
				} else {
					$this.find(opts.stateSelect).parent().addClass('loading');
					$this.find(opts.citySelect).parent().addClass('offscreen');
					$this.find(opts.schoolSelect).parent().addClass('offscreen');
					$.ajax({
						url: baseUrl+'ajax/city.php?state='+stateVal,
						global: false,
						dataType: 'json', 
						type: 'get',
						success: function(data){
						    var option = '';
						    for (var i = 0; i < data.length; i++) {
						    	option += '<option value="' + data[i].city + '">' + data[i].city + '</option>';
					    	}
					    	$this.find(opts.citySelect).html('<option value="0">Select your city</option>' + option);
					    	$this.find(opts.stateSelect).parent().siblings('.error-msg').addClass('hidden');
					    	$this.find(opts.stateSelect).parent().removeClass('loading');
					    },
					    error: function(req,error){
					    	$this.find(opts.stateSelect).parent().siblings('.error-msg').removeClass('hidden').children('p').html('Sorry, there are no cities available for this state.');
					    	$this.find(opts.citySelect).parent().addClass('offscreen');
				    	},
				    	complete: function() {		  
				    		$this.find(opts.stateSelect).parent().removeClass('loading');  	
					    	if(stateVal != 0) {
								$this.find(opts.citySelect).parent().removeClass('offscreen');
					    		
					    		$this.find('#'+opts.stateValID).remove();
								$this.find('form').append('<input id="'+ opts.stateValID +'" type="hidden" name="selected state" value="'+ stateVal +'" />');
					    		
								var selStateVal = $this.find(opts.stateSelect).val();
								
					    		$( $this.find(opts.citySelect) , $this.find(opts.schoolSelect) ).siblings('.newListSelected').remove();
					    		$this.find(opts.schoolSelect).parent().addClass('offscreen');
						    	$this.find(opts.citySelect).parent().removeClass('offscreen');
						    	initStyledSelect.initCitySelect();
							} else {
								$( $this.find(opts.citySelect) , $this.find(opts.schoolSelect) ).parent().addClass('offscreen');
								$this.find(opts.stateSelect).parent().siblings('.error-msg').removeClass('hidden').children('p').html('Please select a state from the menu below.');
							}		    	
				    	}
			    	});
			    }
			    //return selStateVal;
			},
			onCitySelect: function() {
				var stateVal		= $this.find('#state-val').val(),
		    		cityVal			= $this.find(opts.citySelect).val(),
		    		schoolTypeVal 	= $this.find('#'+opts.schoolTypeID).val();
		    	
		    	if($this.find(opts.schoolType) == "0") {
					$this.find(opts.errorHolder).removeClass('hidden').children('p').html('Please select a type of school.');
					$this.find(opts.citySelect).children('option:first-child').attr('selected' , 'selected');
				    $this.find(opts.citySelect).resetSS();
					//resetForm();
				} else {	
					$this.find(opts.citySelect).parent().addClass('loading');	
					$this.find(opts.schoolSelect).parent().addClass('offscreen');
					$.ajax({
						url: baseUrl+'ajax/school.php?state='+stateVal+'&city='+cityVal+'&type='+schoolTypeVal,
						global: false,
						dataType: 'json', 
						type: 'get',
						success: function(data){
						    var option = '';
						    for (var i = 0; i < data.length; i++) {
						    	option += '<option value="' + data[i].id + '">' + data[i].name + '</option>';
					    	}
					    	$this.find(opts.schoolSelect).html('<option value="0">Select your school</option>' + option);
					    	$this.find(opts.schoolSelect).siblings('.newListSelected').remove();
					    	$this.find(opts.schoolSelect).sSelect({ddMaxHeight: '200px'}).parent().removeClass('offscreen');
					    	$this.find(opts.citySelect).parent().siblings('.error-msg').addClass('hidden');
					    },
					    error: function(req,error){
					    	$this.find(opts.citySelect).parent().siblings('.error-msg').removeClass('hidden').children('p').html('Sorry, there are no schools available for this city.');
					    	$this.find(opts.schoolSelect).parent().addClass('offscreen');
				    	},
				    	complete: function() {	
				    		$this.find(opts.citySelect).parent().removeClass('loading');
				    		if(cityVal != 0) {
								$this.find(opts.schoolSelect).parent().removeClass('offscreen');								
					    		$this.find('#'+opts.stateValID).val(stateVal);
					    		
					    		$this.find('#'+opts.cityValID).remove();
								$this.find('form').append('<input id="'+ opts.cityValID +'" type="hidden" name="selected city" value="'+ cityVal +'" />');
					    		
					    		//alert(cityVal+' , '+stateVal);
							} else {
								$this.find(opts.schoolSelect).parent().addClass('offscreen');
								$this.find(opts.citySelect).parent().siblings('.error-msg').removeClass('hidden').children('p').html('Please select a city from the menu below.');
							}
							
							var schoolItems = $this.find(opts.schoolSelect).children();
							if(schoolItems.length == 1 ) {
								$this.find(opts.citySelect).parent().siblings('.error-msg').removeClass('hidden').children('p').html('Sorry, there are no schools available for this city.');
								$this.find(opts.schoolSelect).parent().addClass('offscreen');
							}
				    		
				    	}
			    	});
			    }		
			},
			onSchoolSelect: function() {
				var schoolType 		= $this.find(opts.schoolType),
		    		schoolSelect 	= $this.find(opts.schoolSelect),
		    		schoolTypeVal	= $this.find(opts.schoolType).val(),
		    		schoolID		= $this.find(opts.schoolID),
		    		finderForm		= $this.find('form');

		    	$this.find('#'+opts.schoolID).remove();
				$this.find('form').append('<input id="'+ opts.schoolID +'" type="hidden" name="school-id" value="'+ $this.find(opts.schoolSelect).val() +'" />');
				
				//$this.find(opts.schoolID).val($this.find(opts.schoolSelect).val());
				if($this.find('#'+opts.schoolID).val() > 0 ) {
					if(opts.submitForm == true) {
						finderForm.submit();
						$this.find(opts.schoolSelect).parent().addClass('loading');
					} else {
						$this.find(opts.step2).addClass('hidden');
						$this.find(opts.schoolSetMenu).html('').removeClass('hidden').append('<p>'+$this.find(opts.schoolSelect).children('option:selected').html()+'</p><a class="change-school" href="#" title="Change School">Change School</a>');
						$this.find(opts.step2).find('.loading').removeClass('loading');
						return false;
					}
				} else {
					$this.find(opts.schoolSelect).parent().siblings('.error-msg').removeClass('hidden').children('p').html('Please select a school from the menu below.');
				}
			}
		}
		
		
		// External Plugin Dependant - stylish-select.js
		var initStyledSelect = {
			initStateSelect: function() {
				$this.find(opts.stateSelect).siblings('.newListSelected').remove();
				$this.find(opts.stateSelect).sSelect({ddMaxHeight: '200px'});
			},
			initCitySelect: function() {
				$this.find(opts.citySelect).siblings('.newListSelected').remove();
				$this.find(opts.citySelect).sSelect({ddMaxHeight: '200px'});
			},
			initSchoolSelect: function() {
				$this.find(opts.schoolSelect).siblings('.newListSelected').remove();
				$this.find(opts.schoolSelect).sSelect({ddMaxHeight: '200px'});
			},
			initGlobalSelect: function() {
				$this.find(opts.styledSelect).siblings('.newListSelected').remove();
				$this.find(opts.styledSelect).sSelect({ddMaxHeight: '200px'});
			},
			initSelectReset: function() {
				$this.find(opts.styledSelect).siblings('.newListSelected').remove();
				$this.find(opts.stateSelect).resetSS();
				$this.find(opts.citySelect).resetSS();
				$this.find(opts.schoolSelect).resetSS();
				$this.find(opts.stateSelect).parent().addClass('offscreen');
				$this.find(opts.citySelect).parent().addClass('offscreen');
				$this.find(opts.schoolSelect).parent().addClass('offscreen');
				resetForm.selectReset();
			}
		}
    	
    	// External Plugin Dependant - jquery.clickoutside.js
		function initClickOutside() {
			defaultFormView(); 
			//resetForm.init();
			
			return true;
		}
		
		
		/* 
		*  Reset Form
		*/
		var resetForm = {
			init:function() {	
				resetForm.radioReset();
				resetForm.selectReset();
			},
			radioReset:function() {
				//reset radion btns
				$('.radio-set input').attr('checked' , ''); 
			},
			selectReset:function() {
				//reset select box
			    $('select').each(function() {
			    	$('option:first-child').attr('selected' , 'selected');
			    });
			}
		}; 
		
		
		/* 
		*  Default Form View
		*/
		function defaultFormView() {
			// Resets form to default view (as per first visit)
			if($this.find(opts.schoolSetMenu).hasClass('offscreen')) {
				$this.find(opts.step1).removeClass('offscreen');
				$this.find(opts.callout).removeClass('offscreen');
				$this.find(opts.step2).addClass('offscreen');
				$this.find(opts.selectSet).addClass('offscreen');
				$this.find(opts.styledSelect).siblings('.newListSelected').remove().resetSS();
				
				$this.find('.radio-set input').attr('checked', '');
				$this.find('span.radio').css('background-position', '0 0');
			}
			
			return false;
		} 
		
		/* 
		*  Change School
		*/
		function changeSchool() {
			var schoolFindMenu	= opts.schoolFindMenu,
				schoolSetMenu	= opts.schoolSetMenu,
				step1			= opts.step1,
				step2			= opts.step2;
				
			// On click of change school the form comes back and menu hides
			resetForm.init();
			$this.find(opts.schoolSetMenu).addClass('offscreen');
			$this.find(opts.errorHolder).addClass('offscreen');
			$this.find(opts.schoolFindMenu).removeClass('offscreen');
			
			return false;
		} 
    	
		
		
		
		// Newsletter Specific - setting options for Campaign Monitor account
		function formSet() {
			var newsletterHolder = opts.newsletterHolder;
			
			$this.find('.radio-set .set').bind('click' , function() {
				$this.find('#'+opts.schoolTypeID).remove();
				if($(this).children('input').val() == 'k12' ) {
					$this.find('form').append('<input id="'+ opts.schoolTypeID +'" type="hidden" name="'+ opts.schoolTypeInputName +'" value="K12" />');
				}
				if($(this).children('input').val() == 'college' ) {
					$this.find('form').append('<input id="'+ opts.schoolTypeID +'" type="hidden" name="'+ opts.schoolTypeInputName +'" value="College" />');
				}
			});
			
			
			$this.find(opts.stateSelect).bind('change' , function() {
				var selectVal = $(this).val();
				$this.find('#'+opts.stateValID).remove();
				$this.find('form').append('<input id="'+ opts.stateValID +'" type="hidden" name="'+ opts.stateInputName +'" value="'+ selectVal +'" />');
				
				//alert(selectVal);
			});
			
			$this.find(opts.citySelect).bind('change' , function() {
				var selectVal = $(this).val();
				$this.find('#'+opts.cityValID).remove();
				$this.find('form').append('<input id="'+ opts.cityValID +'" type="hidden" name="'+ opts.cityInputName +'" value="'+ selectVal +'" />');
				//alert(selectVal);
			});
			
			$this.find(opts.schoolSelect).bind('change' , function() {
				var selectVal = $(this).val();
				
				$this.find('#'+opts.schoolID).remove();
				$this.find('form').append('<input id="'+ opts.schoolID +'" type="hidden" name="school-id" value="'+ selectVal +'" />');
				//alert(selectVal);
				
				$this.find(opts.schoolSelect).children('option').each(function() {
					if($(this).val() == selectVal) {
						//alert(selectVal);
						$this.find('#'+opts.schoolID).remove();
						$this.find('form').append('<input id="'+ opts.schoolID +'" type="hidden" name="'+ opts.schoolInputName +'" value="'+ $(this).html() +'" />');
					}
				});
			});
			
			//newsletterHolder.find('.checkbox-set').click(function() {
			//	alert('check');
			//	$(this).find('input[type=checkbox][checked]').each( function() {   
			//		alert('checked' + $(this).parent().find('label').html());
			//	});  
			//});
			
			
		};
		
		
		
    	
		// end this.each() series of fn
		
		
	});

	return this;
}
})(jQuery);


