$(document).ready(function(){
	
	//	Print page
	$('#printbutton').click(function(){
		window.print();
		return false;
	})
	
	
	
	//	Content Overlay
		//	Preload Loading Graphic
			var loaderimg = $('<img />').attr('src', '/images/loader.gif').attr('id', 'loaderimg');
		function popUpOverlay(){
			$('body').append('<div id="fixedoverlay"><div id="overlaymatte"></div><a title="close" href="#" class="closeoverlay">Close</a><div id="overlaycontent"></div></div>');
			$('#overlaycontent').append(loaderimg);
			$('#loaderimg').show();
			$(window).keydown(function(e){
				if(e.keyCode == 27) {
					$('#fixedoverlay').remove();
				}
			})
		}
		$('#fixedoverlay .closeoverlay').live('click', function(){
			$('#fixedoverlay').remove();
			return false;
		})
	
	//	Login Overlay
		$('#header .login, .account_login .login, #sidebar a.login').click(function(e){
			e.preventDefault();
			popUpOverlay();
			$('#overlaycontent').load(this.href + " #loginpage");
		})
		
		
	//	Home Screen
		$('#my_itineraries .remove_itinerary').hide();
		$('#my_itineraries .itinerary').hover(function(){
			$(this).css('background-color', '#f5f5f5').find('.remove_itinerary').show();
			
		}, function(){
			$(this).css('background-color', '#fff').find('.remove_itinerary').hide();
		})
		
	
	//	Registration Validation
		var registrationValid = true;
		$('#user_registration #user_email').blur(function(){
			var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
			var email = $(this).val();
			if (email == "") {
				$(this).next('.notifier').addClass('error').html('<img src="/images/cancel.png" /> You must enter your email address.');
				registrationValid = $(this).attr('id');
			} else if (!emailReg.test(email)) {
				$(this).next('.notifier').addClass('error').html('<img src="/images/cancel.png" /> You must enter a valid email address.');
				registrationValid = $(this).attr('id');
			} else {
				$(this).next('.notifier').removeClass('error').html('<img src="/images/accept.png" />');
				if(registrationValid==$(this).attr('id')){
					registrationValid = true;
				}
			}
		})
		$('#user_registration #user_password').blur(function(){
			if($(this).val().length < 6){
				$(this).next('.notifier').addClass('error').html('<img src="/images/cancel.png" /> Passwords must be at least 6 characters.');
				registrationValid = $(this).attr('id');
			} else {
				$(this).next('.notifier').removeClass('error').html('<img src="/images/accept.png" />');
				if(registrationValid==$(this).attr('id')){
					registrationValid = true;
				}
			}
		})
		$('#user_registration #user_password_confirmation').blur(function(){
			if($(this).val() != $('#user_password').val()){
				$(this).next('.notifier').addClass('error').html('<img src="/images/cancel.png" /> Passwords do not match.');
				registrationValid = $(this).attr('id');
			} else {
				$(this).next('.notifier').removeClass('error').html('<img src="/images/accept.png" />');
				if(registrationValid==$(this).attr('id')){
					registrationValid = true;
				}
			}
		})
		$('#user_registration input[type="submit"]').click(function(){
			if(registrationValid != true){
				alert('Please correct all errors as marked.');
				$('#'+registrationValid).select();
				return false;
			} else if ($('#user_name').val()==''){
				alert('You must enter your name to sign up.');
				$('#user_name').focus();
				return false;
			} else if ($('#user_password').val()=='' || $('#user_password_confirmation').val()=='') {
				alert('You must enter a password to sign up.');
				$('#user_password').focus();
				return false;
			}
		})
		$('#user_registration li:contains("Login")').remove();
		$('#user_registration li:contains("Email")').text('The provided Email Address is already in use.');

	
	//	Itinerary Title Edit
		$('#itineraries .itinerary_title a').click(function(e){
			e.preventDefault();
			var theTitle = $(this).text();
			theId = $(this).attr('href').replace('/itineraries/edit/', '');
	        
			$(this).hide().before('<input type="text" id="editing_title" value="'+ theTitle +'" />');
			$('#editing_title').focus().select().blur(function(){
				$(this).remove();
				$('#itineraries .itinerary_title a').show();
				$('.itinerary_title small').text('(Click title to edit)');
			}).keydown(function(e) {
			    if(e.keyCode == 13) {
			        theTitle = $(this).val();
					$.ajax({
				   type: "POST",
				   url: "/itineraries/savetitle",
				   data: "title=" + theTitle + "&id=" + theId
				 });
					$(this).remove();
					$('#itineraries .itinerary_title a').show().find('span').text(theTitle);
					$('.itinerary_title small').text('(Click title to edit)');
			    } else if(e.keyCode == 27) {
					$(this).remove();
					$('#itineraries .itinerary_title a').show();
					$('.itinerary_title small').text('(Click title to edit)');
				}
			})			
			$('.itinerary_title small').text('(Press Enter to save changes)');
			
		})
	
	//	Itinerary Visits/Maps 
		var mapsLoaded = false;
		//	pageload tab switching
			if (window.location.hash == "#showmaps") {
				
				$('div#maps, #itinerary_tabs .map').show();
				$('div#visits, #itinerary_tabs .visit').hide();
				$('#itinerary_tabs a.maps').siblings().removeClass('active');
				$('#itinerary_tabs a.maps').addClass('active');
				if(!mapsLoaded){
					launchMaps();
					mapsLoaded = true;
				}
			}
		
		
		
		
		$('#itinerary_tabs a.visits').click(function(e){
			if (window.location.hash != "#showmaps") {
				e.preventDefault();
			}
			if(!$(this).is('.active')) {
				$('div#visits, #itinerary_tabs .visit').show();
				$('div#maps, div#travelarrangements, #itinerary_tabs .map').hide();
				$(this).siblings().removeClass('active');
				$(this).addClass('active');
			}
		})
		function launchMaps() {
			$('#maps').append('<div id="loadedMaps"></div>');
			$('#loadedMaps').append('<iframe frameborder="0" id="idTopFrame" width="645" height="'+$('#maptotal').val()*610+'" src="/itineraries/maps/'+$('#itinerary_id').val()+'" />')
			//	Some map scripting located in /itineraries/maps
		}
		
		$('#itinerary_tabs a.maps').click(function(e){
			e.preventDefault();
			if(!$(this).is('.active')) {
				$('div#maps, #itinerary_tabs .map').show();
				$('div#visits, div#travelarrangements, #itinerary_tabs .visit').hide();
				$(this).siblings().removeClass('active');
				$(this).addClass('active');
				if(!mapsLoaded){
					launchMaps();
					mapsLoaded = true;
				}
			}
		})
		$('div#add_map').hide();
		if ($('#nomaps').val() == "true") {
			$('div#add_map').show();
		}
		$('#itinerary_tabs .map').click(function(e){
			e.preventDefault();
			$('div#add_map').slideDown('fast');
		})
		$('#add_map #cancel_map').click(function(){
			$('div#add_map').slideUp('fast');
			$('#createMap')[0].reset();
		})
		$('a.removemap').click(function(){
			if (confirm('Are you sure you want to remove this map?')) { 
				var map = $(this).parent();
				$.post(this.href, { _method: "delete", authenticity_token: $('#auth_token').val() }, function(){
					map.fadeOut();
					var mapTab = window.parent.$('#itinerary_tabs .maps span');
					var maptotal = mapTab.text().replace('Map Creator (', '').replace(')', '');
					maptotal--;
					mapTab.text('Map Creator ('+maptotal+')');
				});
			};
			return false;
		})
		
		$('#itinerary_tabs a.travelarrangements').click(function(e){
			if (window.location.hash != "#showmaps") {
				e.preventDefault();
			}
			if(!$(this).is('.active')) {
				var traveltab = $('div#travelarrangements');
				$('div#travelarrangements').show().load(window.location.href + " #travelarrangements", function(){
					traveltab.find('#travelarrangements').show().unwrap();
				})
				$('div#maps, #itinerary_tabs .map').hide();
				$('div#visits, #itinerary_tabs .visit').hide();
				$(this).siblings().removeClass('active');
				$(this).addClass('active');
			}
		})
		
		
		
		
	
	//	Itinerary Sorting
		$('#visits').sortable({
			stop: function() { 
					$.post('/itineraries/sorting', { item_sort: $('#visits').sortable('serialize') });
				}
		});
		
	
	//	Itinerary Detail Tabs
		$('.detailstabs .tabs a').not('.removeschool').click(function(e){
			e.preventDefault();
			$(this).parent().find('a').removeClass('active');
			$(this).addClass('active');
			$(this).parent().next('.detailscontent').children().hide().end().children('.'+$(this).attr('href').substr(1)).show();
		})
		
	
	//	Itinerary Shadowboxes
		$('a.add_activity').live('click', function(e){
			e.preventDefault();
			popUpOverlay();
			$('#overlaycontent').load($(this).attr('href')+ ' #add_new_activity', function(){
				//	Datepickers
					$('#overlaycontent .datepicker').datepicker();
				
				$('#add_new_activity > div').not('.tabs').not(':nth-child(2)').hide();
				$('#add_new_activity .tabs a:first-child').addClass('active');
				$('#add_new_activity .activity_details').hide();
				$('#add_new_activity a.off_site').click(function(){
					var leavesite = confirm('GO SEE CAMPUS DOES NOT REGISTER YOU TO PARTICIPATE IN THIS ACTIVITY. \n\nYou must arrange this activity directly with the college. To continue on to the college\'s website, click OK. \n\nIf you have already made arrangements with the college, click CANCEL, and add the details to your trip.');
					//  \n\nGo See Campus wants visitors to get the most from their college trips. We would hate for you to show up for your activity and find out that you were never registered for it! We make things easy by connecting you to the information you need. Arrange your activity with the college, and then add the details to your trip plan on Go See Campus.
					if(leavesite){
						$(this).parent().next('.activity_details').show();
						return true;
					} else {
						$(this).parent().next('.activity_details').show();
						return false;
					}
				})
			});
			$('#add_new_activity .tabs a').live('click', function(e){
				$(this).siblings('a').removeClass('active');
				$(this).addClass('active');
				$(this).parent().siblings('div').hide();
				$('#add_new_activity div.clear').show();
				$('#'+$(this).attr('href').replace(window.location.href,'').substr(1)).show();
				return false;
			})
			
		})
		$('a.find_restaurants').live('click', function(e){
			e.preventDefault();
			popUpOverlay();
			var iframedata = $(this).attr('href');
			$('#overlaycontent').append('<iframe frameborder="0" style="display:none" id="restaurants_map" width="980" height="500"></iframe><input class="hidden" type="hidden" value="'+ $(this).parents('.itinerary_leg').attr('id') +'" name="currentDiningTab" id="currentDiningTab" />');
			$('iframe#restaurants_map').attr('src', iframedata);
			$('#loaderimg').css('padding', '50px');
			    $('iframe#restaurants_map').load(function() {
			        $(this).show();
					$('#loaderimg').hide();
			    });
		})
		
		$('#itinerary_tabs .visit').click(function(e){
			e.preventDefault();
			popUpOverlay();
			$('#overlaycontent').html('<div class="searchbar">'+$('#searchbar').html()+'</div>');
			$('#overlaycontent .searchbar input').click(function(){
				$(this).select();
			});
			$('#overlaycontent .searchbar h3').after('<p>Search for schools to add to your Trip Planner.</p>')
		})

		$('a.addtodining').live('click', function(e){
			
			$.get(this.href, function(){
				
				var currentDiningTab = window.parent.$('#currentDiningTab').val().substr(8);
				var currentItinerary = window.parent.$('#itinerary_id').val();
				window.parent.$('#location'+currentDiningTab+' .dining').load('/itineraries/'+currentItinerary+' #location'+currentDiningTab+' .dining .diningcontent', function(){
					currentDiningTab = '';
				})
				window.parent.$('#fixedoverlay').remove();
			});
			return false;
		})
		

	//	Add to Itinerary
		$('a.add_to_itinerary').not('.signup').click(function(e){
			e.preventDefault();
			popUpOverlay();
			$('#overlaycontent').load($(this).attr('href')+ ' #interstitial', function(){
				$('#interstitial li a').click(function(k){
					k.preventDefault();
					var chosenItinerary = $(this).find('span').text();
					var url = new Array();
					url = this.href.split('/');
					var itineraryURL = '/'+url[3]+'/'+url[6];
					$.get(this.href, function(){
						$('#interstitial').html('<p class="success"><strong>Great!</strong> This school has been added to your trip, which you can view here:</p><a class="go_link" href="'+itineraryURL+'">'+chosenItinerary+'</a><div class="hr-or"><hr class="or" /></div><a class="go_link return" href="#">Return to Search Results</a>');
						$('#interstitial a.return').click(function(e){
							e.preventDefault();
							$('#fixedoverlay').remove();
						})
					})
				})
			});
		})
	
	//	Travel Details
		$('form.edit_location input[type="submit"]').hide();
		$('a.find_flights, a#make_travel_arrangements').live('click', function(e){
			popUpOverlay();
			$('#overlaycontent').load($(this).attr('href')+ ' #findflights');
			return false;
		})
		$('.travelmethod_id').change(function(){
			var action = $(this).parents('form').attr('action');
			var theForm = $(this).parents('form');
			$.ajax({
				type: 		"POST",
				url: 		action,
				data: 		theForm.serialize()
			})
		})
		
	//	Date Picker
		$('.datepicker').datepicker();
		$('.datepicker').change(function(){
			var action = $(this).parents('form').attr('action');
			var theForm = $(this).parents('form');
			$.ajax({
				type: 		"POST",
				url: 		action,
				data: 		theForm.serialize()
			})
		})
		
	//	Profile page
		$('#schoolprofile dt:odd, #schoolprofile dd:odd').addClass('alt');
	
	
	//	Itinerary Activity Edit
		$('#main .itinerary_leg table .deleteactivity').hide();
		$('#main .itinerary_leg table tr').hover(function(){
			$(this).find('.deleteactivity').show();
		}, function(){
			$(this).find('.deleteactivity').hide();
		})
	
	//	Itinerary Activity Notes
		$('a.note').click(function(e){
			$('div.notes').hide(300);
			e.preventDefault();
			if($(this).siblings('div.notes').is(':visible')) {
				$(this).siblings('div.notes').hide(300);
			} else {
				$(this).siblings('div.notes').show('fast');
			}
		})
		$(window).keydown(function(e){
			if(e.keyCode == 27) {
				$('div.notes').hide(300);
			}
		})
		$('.notes .close').click(function(){
			$(this).parents('.notes').hide(300);
		})
		$('.notes form .update').click(function(){
			var parentNote = $(this).parents('.notes');
			var loaderImg = $(this).siblings('.loader');
			$(this).parents('.notes').find('.printnotes').html($(this).parents('form').find('textarea').val());
			loaderImg.show();
			$.ajax({
				type: 			"POST",
				url: 			$(this).parents('form').attr('action'),
				data: 			$(this).parents('form').serialize(),
				success: 		function(){
					parentNote.hide(300);
					loaderImg.hide();
				}
			})
			return false;
		})

	//	Signup select switcher 
		$('#email_list_label').hide();
		$('#user_user_type_id').change(function(){
			if($(this).val() > 0 && $(this).val() < 8){
				$('#email_list_label :checkbox').attr('checked','checked');
				$('#email_list_label').show();
				if($(this).val() == 6){
					$('#email_list_label span').text('Yes, I would like to receive information periodically about Go See Campus, including resources I can use to gain insight into my university and its programs.');
				} else if (($(this).val() == 5) || ($(this).val() == 4)){
					$('#email_list_label span').text('Yes, I would like to receive information periodically about Go See Campus features and resources I can share with students and parents.');
				} else {
					$('#email_list_label span').text('Yes, I would like to receive information periodically about Go See Campus and other college resources.');
				}
			} else {
				$('#email_list_label').hide();
				$('#email_list_label :checkbox').removeAttr('checked');
			}
		})
	
	
	//	ClearInput
		var fields = new Array();
		var values = new Array();

		$('.ci').each(function(i){
			$(this).removeClass('ci').addClass('ci'+i);
			fields.push('ci'+i);
			values.push($(this).val());

			$(this).focus(function(){
				if($(this).val() == values[i]) {
					$(this).val('');
				}
			});
			$(this).blur(function(){
				var valStore = values[i];
				if($(this).val()==''){
					$(this).val(valStore);
				}
			})
		});


	//	Admin AJAXiness
		$('#registered_submit').click(function(){
			var url = $(this).parents('form').attr('action');
			var data = $(this).parents('form').serialize();
			$('#registered_total').load(url+" .count", data, function(){
				$('#registered_total').effect("highlight",{},3000);
			});
			return false;
		})
		$('#logged_submit').click(function(){
			var url = $(this).parents('form').attr('action');
			var data = $(this).parents('form').serialize();
			$('#logged_total').load(url+" .count", data, function(){
				$('#logged_total').effect("highlight",{},3000);
			});
			return false;
		})
		$('#import_location_link').click(function(){
		  //show spinner
      $('#import_status').html('Importing data <img class="spinner" src="/images/spinner.gif"/>');
		  $.get('/admin/run_import', function(data){
        if(data == 'OK'){
          $('#import_status').html('Import completed successfully');
        }else{
          $('#import_status').html('Import failed. <a href="javascript:void(0);" id="import_location_link">Try again</a>');
        }
      });

    });

		
})

