// JQuery based hover menu
$(document).ready(function(){

	// Get the source directory of this script
	scriptSrc = $('script[@src$=jquery.js]').attr('src').replace('js/jquery.js', '');
	

	// General hover image function
	$('.hoverimage').hover(
		function(){
			var thisItem = $(this);
			if (thisItem.is("img")) {
				thisItem.attr("src", thisItem.attr("src").replace(/_out./, "_over."));
			}else if (thisItem.is("a")){
				thisItem.css("background-image", thisItem.css("background-image").replace(/_out./, "_over."));
			}
		},
	  	function(){
			var thisItem = $(this);
			if (thisItem.is("img")) {
				thisItem.attr("src", thisItem.attr("src").replace(/_over./, "_out."));
			}else if (thisItem.is("a")){
				thisItem.css("background-image", thisItem.css("background-image").replace(/_over./, "_out."));
			}
		}
	);

	// Initialise the menu
	initMenu();

	if ($('#miGenerate').length) {
		$('#miGenerate').click(function(){
			var thisForm = $(this).parents("form");
			var thisLink = $("input[@type=radio]:checked",thisForm).val();
			$("textarea",thisForm).val(thisLink);
		});
	}

	if ($('.miLinkTo')) {
		$('.miLinkTo').click(function(){
			$(".miLinkToText").val($(this).val());
    	});
	}

	// Initialise options
	if($('#details').length){
		initDetailPage();
	}
	
	if($('.projectlist').length){
		initListActions();
	}

	// subinfo close and open
	$("#leftbar .info .sub strong").not('a').toggle(function(){
			$(this).parent().removeClass("closed");
		},function(){
			$(this).parent().addClass("closed");
		}
	);

	initHovers();

	// Submit to favourites
	if($('div.favbuttons').length){
		initFavClick();
	}

	// Now load the iframe on load only
	if($('#print').length){
		$('#print').click(function() {
			window.print();
		});
	}

	// Now load the iframe on load only
	if($('#mapiframe').length){
		initMap();
	}

	// Load rating if it's here
	if($('.rating').length && !$('span#alreadyrated').length) {
		initRating();
	}

	if($('#browseForm').length){
		$('#popularCities').change(function() {
			document.location.href = $('#browseForm').attr('action')+$('option:selected',this).val();
		});
	}

	if($('#linktome').length){
		$('#linktome').focus(function(){
			$(this)[0].select();
		});
	}
	
	if($('#content_right h4').length){
		initFaq();
	}
	
	if($('#guideForm').length){
		initGuideForm();
	}
	
	if($('#activatebuttons').length){
		initButtonSelect();
	}

});



// Initialise the menu
function initMenu(){
	$('div#menu_holder').addClass("none");

	// Remove title tags: they break the link hover...
	$('div#menu_holder a').attr("title","");

	$('div#menu_holder > ul#menulist').hover(
		function(){
			menuOver($('div#menu_holder'));
		},
		function() {
			menuOut($('div#menu_holder'));
		}
	);

	$('ul#menulist li').hover (
		function() {
			var thisItem = $(this);
			$("li a", thisItem).css({ color: "#000000"});
			$("div a", thisItem).css({ color: "#FFFFFF"});
		},
		function() {
			var thisItem = $(this);
			$("li a", thisItem).css({ color: "#706F75"});
			$("div a", thisItem).css({ color: "#BBBBBB"});
		}
	);
	$('ul#menulist ul li a').hover (
			function() {
				$(this).css({ color: "#98E355"});
			},
			function() {
				$(this).css({ color: "#000000"});
	});
}

// function for sliding the menu out
function menuOver(thisItem){
	if(thisItem.is('.up')){
		thisItem.attr('class', 'down');
	}else if(thisItem.is('.none')){
		thisItem.attr('class', 'down');
		thisItem.animate({ height: 240 }, 'slow', function(){
			if(thisItem.is('.up')){
				thisItem.attr('class', 'out');
				menuOut(thisItem);
			}else{
				thisItem.attr('class', 'out');
			}
		});
	}
}

// Function for sliding the menu back up
function menuOut(thisItem){
	if(thisItem.is('.down')){
		thisItem.attr('class', 'up');
	}else if(thisItem.is('.out')){
		thisItem.attr('class', 'up');
		thisItem.animate({ height: 27 }, 'slow', function(){
			var thisItem = $(this);
			if(thisItem.is('.down')){
				thisItem.attr('class', 'none');
				menuOver(thisItem);
			}else{
				thisItem.attr('class', 'none');
			}
		});
	}
}

// Initialise elements that need hovering
function initHovers(){
	$(".birdbutton").hover(
		function(){ $(this).addClass("birdhover"); },
		function(){ $(this).removeClass("birdhover"); }
	);
	
	$(".arrowbutton").hover(
		function(){ $(this).addClass("arrowhover"); },
		function(){ $(this).removeClass("arrowhover"); }
	);
}

// Things to do with the map
function initMap(){
	$('#mapiframe').attr('src', $('#mapiframe').attr('rel'));

	// map click function
	$("#mapbar").click(
		function(){
			if(document.getElementById('mappush').style.display == 'block'){
				document.getElementById('mapbar').src = scriptSrc + 'img/map_hidden.gif';
				$('#mapbar').addClass('hiddenmap');
				$('.pusher').removeClass('bigpusher');
				$('#mappush').hide();
			}else{
				document.getElementById('mapbar').src = scriptSrc + 'img/map_showing.gif';
				$('#mapbar').removeClass('hiddenmap');
				if($('#mappush').is('.iframelarge')){
					$('.pusher').addClass('bigpusher');
				}
				$('#mappush').show();
			}
		}
	);

	// Expand or collapse the map
	$("#expandmap .expand").toggle(function(){
			$('.pusher').addClass('bigpusher');
			$('#mappush').addClass('iframelarge').removeClass('iframesmall');
			$('#expandmap .expand').html('close full size map');
			$('#expandmap .showfavbes').show();
			if($('#expandmap .showall .checkall').attr('checked')){
				var disType = '';
			}else{
				var disType = 1;
			}
			setTimeout("frames['mapiframe'].window.refreshMarkers(0,"+disType+")",1500);
		},function(){
			$('.pusher').removeClass('bigpusher');
			$('#mappush').addClass('iframesmall').removeClass('iframelarge');
			$('#expandmap .expand').html('full size map');
			$('#expandmap .showfavbes').hide();
		}
	);

	// Show or hide all results
	$('#expandmap .showall .checkall').click(function(){
		if($(this).attr('checked')){
			frames['mapiframe'].window.refreshMarkers(0,0);
		}else{
			frames['mapiframe'].window.refreshMarkers(0,1);
		}
	});

	$('a.mapfabe').click(function(){
		var thisItem = $('img',this);
		if($('#expandmap .showall .checkall').attr('checked')){
			var disType = '';
		}else{
			var disType = 1;
		}

		if(thisItem.attr('src').match('_out.')) {
			thisItem.attr('src', thisItem.attr('src').replace(/_out./, '_over.'));
			$(this).siblings('a.mapfabe').each(function(){
				var thisItem = $('img',this);
				if(thisItem.length){
					if(thisItem.attr('src').match('_over.')) {
						thisItem.attr('src', thisItem.attr('src').replace(/_over./, '_out.'));
					}
				}
			});

			if($(this).attr('id') == 'showFavorites'){
				$('input#fabe').val(1);
				frames['mapiframe'].window.refreshMarkers(0,disType);
			}else{
				$('input#fabe').val(2);
				frames['mapiframe'].window.refreshMarkers(0,disType);
			}

		}else{
			thisItem.attr('src', thisItem.attr('src').replace(/_over./, '_out.'));
			$('input#fabe').val(0);
			frames['mapiframe'].window.refreshMarkers(0,disType);
		}
	});
}

// Submit the form in the my favourites page
function initFavClick(){
	$('div.favbuttons a').click(function(){
		var thisItem = $(this);
		var thisTitle = thisItem.attr('title');
		if(!(thisItem.is('.ignore'))){
			var thisForm = $('form#favform');
			if(thisTitle.match('Remove guide')){
				if(!confirm('Are you sure you want to delete this guide?')){
					return false;
				}
			}else if(thisTitle.match('Remove user')){
				if(!confirm('Are you sure you want to remove this user?')){
					return false;
				}
			}
			$('input[@name=action]', thisForm).val(thisItem.attr('title'));
			$('input[@name=project_id]', thisForm).val(thisItem.parent().attr('id'));
			thisForm[0].submit();
			return false;
		}
	});

}

// Functions for the project detail page
function initDetailPage(){
	$('#imagery .thumb').hover(
		// Mouseover function
		function(){
			var imLink = '#i_' + $(this).id();
			$(this).parent().children('#bigims').children('.detail').hide();
			$(this).parent().children('#bigims').children(imLink).show();
			$(this).parent().children('#bigims').children('.detail').children('.iminfo').show();
			$(this).parent().children('#bigims').children('.detail').children('.imcopy').hide();
		},
		// Mouseout function
		function(){
			$(this).parent().children('#bigims').children('.detail').children('.iminfo').hide();
		}
	);

	$('#imagery .detail').hover(
		// Mouseover function
		function(){
			var thisItem = $(this);
			thisItem.children('.iminfo').show();
			thisItem.children('.imcopy').hide();
		},
		// Mouseout function
		function(){
			$(this).children('.iminfo').hide();
		}
	);

	$('#imagery img').bind("contextmenu",function(){
		return false;
	});

	$('#imagery .images').mousedown(function(){
		var thisItem = $(this);
		thisItem.children('#bigims').children('.detail').children('.iminfo').hide();
		thisItem.children('#bigims').children('.detail').children('.imcopy').show();
	});
	
	$('#miinformation a').click(function() {
		var thisItem = $(this);
		if (thisItem.attr("id") == "beenthere") {
			$("form#miinfo input[@name=miinfo]").val(1);
			$("form#miinfo")[0].submit();
		}
		else if (thisItem.attr("id") == "favorites") {
			$("form#miinfo input[@name=miinfo]").val(2);
			$("form#miinfo")[0].submit();
		}
	});
	
	// Make sure there's javascript before submitting a comment form
	if($('#commentsubmit').length){
		$('#commentsubmit').click(function(){
			$('#javacheck').val('1');
			if($('#commentform').length){
				$('#commentform')[0].submit();
			}else{
				$('#commentform').submit();
			}
			return false;
		});
	}
}

function initListActions(){

	// Display the optinos list
	$('#listactions').hover(function(){
		$(this).addClass('active');
	},function(){
		$(this).removeClass('active');
	});
	
	// Hover over a project block
	$(".projectblock").hover(function(){
		$(this).addClass("hovering");
	},function(){
		$(this).removeClass("hovering");
	});
	
	// Toggle the selection state
	$('.selections .select').click(function(){
		$(this).toggleClass('active');
	});
	
	$('#selectall').click(function(){
		$('.selections .select').addClass('active');
	});
	
	$('#selectnone').click(function(){
		$('.selections .select').removeClass('active');
	});
	
	// Add something to your favorites and such
	$('.selections a').click(function(){
		AddToMyList($(this));
	});
	
	// Add multiple items to your favorites and such
	$('#listactions a').click(function(){
		MultipleListActions($(this));
	});
}

// Add multiple items to your list
function MultipleListActions(thisLink){
	var thisThing = $(thisLink);
	var thisClass = $(thisLink).attr('class');
	var thisList = '';
	
	if (thisClass == 'washere' || thisClass == 'favorite'){
		
		$('.selections .select.active').each(function(i){
			if(!$(this).siblings('.'+thisClass).eq(0).is('.active')){
				thisList = thisList + '&project_id[]='+$(this).siblings('input').val();
			}
		});
		
		if(thisList.length){
		
			$('#listactions').addClass('working');
			
			$.ajax({
				type: "POST",
				url: scriptSrc+"scripts/AddProjectToMyList.php",
				data: 'action='+thisClass+thisList,
				dataType: "html",
				success: function(msg){
					if(msg == '1'){
						$('.selections .select.active').each(function(i){
							thisItem = $(this).siblings('.'+thisClass).eq(0);
							if(!thisItem.is('.active')){
								thisItem.addClass('active');
							}
						});
					}else if(msg == '4'){
						window.location = "/log_in/?returnPath="+window.location
					}else{
						alert('An error occured, the projects can not be added.');
					}
					$('#listactions').removeClass('working');
				}
			});
			
		}else{
			alert('No projects that can be added are selected.');
		}
		
	}
}

// Add an item to your list
function AddToMyList(thisLink){
	var thisThing = $(thisLink);
	var thisClass = $(thisLink).attr('class');
	var projectId = $(thisLink).siblings('input').eq(0).val();
	if(thisThing.is('.washere') || thisThing.is('.favorite')){
		$('#listactions').addClass('working');
	
		if(thisThing.is('.favorite')){
			thisClass = 'favorite';
		}else{
			thisClass = 'washere';
		}
	
		if (thisThing.is('.active')){
			var mode = 'remove';
		}else{
			var mode = 'add';
		}
		
		$.ajax({
			type: "POST",
			url: scriptSrc+"scripts/AddProjectToMyList.php",
			data: "action="+thisClass+"&project_id="+projectId+"&mode="+mode,
			dataType: "html",
			success: function(msg){
				if(msg == '1'){
					thisThing.addClass('active');
				}else if(msg == '3'){
					thisThing.removeClass('active');
				}else if(msg == '4'){
					window.location = "/log_in/?returnPath="+window.location
				}else{
					alert('An error occured, the project can not be added.');
				}
				$('#listactions').removeClass('working');
			}
		});	
	}
}

// Guide form initialisation
function initGuideForm(){

	if($('input[@name=userID]').eq(0).val() == ''){
		window.parent.location = '/log_in/?returnPath='+window.parent.location;
	}else if($('input[@name=project_id]').eq(0).val() == 'getFromParent'){
		freshInputs = window.parent.getSelectedGuideItems();
		$('input[@name=project_id]').remove();
		$('input[@name=do]').after(freshInputs);
	}

}

// Get the selected list items in this window
function getSelectedGuideItems(){

	thisList = '';
	$('.selections .select.active').each(function(i){
		thisList = thisList + '<input type="hidden" name="project_id[]" value="'+$(this).siblings('input').val()+'" />';
	});
	
	return thisList;
}

// Initialise the rating system
function initRating(){

	// Display a neat hover when people consider their options
	$('#yourrating a').click(function(){
		var rating = $(this).attr("rel");
	
		$('#yourrating a').each(function(){
			if($(this).attr('rel') <= rating){
				$(this).addClass('active');
			}else{
				$(this).removeClass('active');
			}
		});
	
		$("form#mirating input[@name=rate]").val(rating);
	});
	
	$('#yourrating a').hover(function(){
		var rating = $(this).attr("rel");	
		$('#yourrating a').each(function(){
			rat = $(this).attr('rel');
			if(rat <= rating){
				$(this).addClass('active');
			}else{
				$(this).removeClass('active');
			}
		});
	},function(){
		var rating = $("form#mirating input[@name=rate]").val();
		$('#yourrating a').each(function(){
			if($(this).attr('rel') <= rating){
				$(this).addClass('active');
			}else{
				$(this).removeClass('active');
			}
		});
	
	});
	
	if($('#mirating').length){
		$('#gorate, .scoreholder .score, .scoreholder .noscore').click(function(){
			$('#mirating').show();
		});
		
	}
	
	$('#mirating .ratingcancel').click(function(){
		$('#mirating').hide();
	});
	
	$('#mirating #ratingsubmit').click(function(){
		$.ajax({
			type: "POST",
			url: scriptSrc+"scripts/rateProject.php",
			data: "project_id="+$('#rate_project_id').val()+"&rate="+$('#rate').val()+"&comment="+$('#ratingcomment').val(),
			dataType: "json",
			success: function(msg){
				$('.noscore').addClass('score').removeClass('noscore');
				$('.current').css('width', msg.width+'px');
				$('.votecount').html(msg.count);
				$('#mirating, #gorate').hide();
				$('<span id="alreadyrated">You already rated this project</span>').insertAfter('#gorate');
				refreshComments($('#rate_project_id').val());
			}
		});	
	});
}

// Get the comments for this page all over again
function refreshComments(id){
	$.ajax({
		type: "POST",
		url: scriptSrc+"scripts/getComments.php",
		data: "project_id="+id,
		dataType: "html",
		success: function(msg){
			$('#commentcontainer').html(msg);
		}
	});
}


// INitialise folding of faq items
function initFaq(){
	// Toggle FAQ's
	$("#content_right h4").each(function(){
		$(this).next().hide();
	});

	$("#content_right h4").toggle(function(){
		$(this).next().slideDown();
	},function(){
		$(this).next().slideUp();
	});
}

// Initialise button select
function initButtonSelect(){

	$('#activatebuttons').click(function(){
		$('#buttonselector').show();
	});
	
	$('#buttonselector a').click(function(){
		$('#buttonselector').hide();
		$('#activatebuttons img').attr('src', $('img', this).attr('src'));
		$('#linktome').val($(this).siblings('input').val());
	});

}


// check the value of an input field and empty it if it's the original
function checkInput(item, check){
	if(item.value == check){
		item.value = '';
	}
}

// Decrypt mail
function UnCryptMailto(s){
	var n = 0;
	var r = "";
	for( var i = 0; i < s.length; i++){
		n = s.charCodeAt(i);
		if(n >= 8364){
			n = 128;
		}
		r += String.fromCharCode( n - 1 );
	}
	return r;
}

function LinkToAddy(s){
	location.href=UnCryptMailto( s );
}

// Function for making sure text only uses url safe symbols
function makeSafe(thisText, allowSpace){
	var w = "!@#$%^&*()+=[]\\\';,./{}|\":<>?";
	var s = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_';
	var x = new Array('àáâãäå', 'ç', 'èéêë', 'ìíîï', 'ñ', 'ðóòôõöø', 'ùúûü', 'ýÿ', 'ÀÁÂÃÄÅ', 'Ç', 'ÈÉÊË', 'ÌÍÎÏ', 'Ñ', 'ÐÓÒÔÕÖØ', 'ÙÚÛÜ', 'ÝŸ');
	var r = new Array('a', 'c', 'e', 'i', 'n', 'o', 'u', 'y', 'A', 'C', 'E', 'I', 'N', 'O', 'U', 'Y');

	if(allowSpace){ s = s + ' '; }

	var newText = new Array();

	for (i = 0; i < thisText.length; i++){
		thisChar = thisText.charAt(i);
		if(w.indexOf(thisChar) == -1){
			if(s.match(''+thisChar+'')){
				newText[i] = thisChar;
			}else{
				for (j = 0; j < x.length; j++){
					if(x[j].match(thisChar)){
						newText[i] = r[j];
					}
				}
			}
		}
	}

	return newText.join('');
}