jQuery.url=function(){var segments={};var parsed={};var options={url:window.location,strictMode:false,key:["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],q:{name:"queryKey",parser:/(?:^|&)([^&=]*)=?([^&]*)/g},parser:{strict:/^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,loose:/^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/}};var parseUri=function(){str=decodeURI(options.url);var m=options.parser[options.strictMode?"strict":"loose"].exec(str);var uri={};var i=14;while(i--){uri[options.key[i]]=m[i]||""}uri[options.q.name]={};uri[options.key[12]].replace(options.q.parser,function($0,$1,$2){if($1){uri[options.q.name][$1]=$2}});return uri};var key=function(key){if(!parsed.length){setUp()}if(key=="base"){if(parsed.port!==null&&parsed.port!==""){return parsed.protocol+"://"+parsed.host+":"+parsed.port+"/"}else{return parsed.protocol+"://"+parsed.host+"/"}}return(parsed[key]==="")?null:parsed[key]};var param=function(item){if(!parsed.length){setUp()}return(parsed.queryKey[item]===null)?null:parsed.queryKey[item]};var setUp=function(){parsed=parseUri();getSegments()};var getSegments=function(){var p=parsed.path;segments=[];segments=parsed.path.length==1?{}:(p.charAt(p.length-1)=="/"?p.substring(1,p.length-1):path=p.substring(1)).split("/")};return{setMode:function(mode){strictMode=mode=="strict"?true:false;return this},setUrl:function(newUri){options.url=newUri===undefined?window.location:newUri;setUp();return this},segment:function(pos){if(!parsed.length){setUp()}if(pos===undefined){return segments.length}return(segments[pos]===""||segments[pos]===undefined)?null:segments[pos]},attr:key,param:param}}();

$(document).ready(function() {
	 
	 /**Header menus **/
	 $("#create-button").mouseover(function(){
	 	$("#create-menu").show();
	 });
	 $("#create-button").mouseout(function(){
	 	$("#create-menu").hide();
	 });
	 $("#header .menu li").mouseover(function(){
	 	$(this).addClass("hover");
	 });
	 $("#header .menu li").mouseout(function(){
	 	$(this).removeClass("hover");
	 });
	 $(".change-area a").click(function(){
	 	$(".change-area").addClass('hidden');
		$(".hidden-select").removeClass('hidden-select');
		return false;
	 }); 	
	 if ($.tooltip) {
	 	$('.tooltip').tooltip({
	 		bodyHandler: function(){
				var key = $(this).attr("key");
	 			return tooltips[key];
	 		},
			delay : 0,
			fade : 250
	 	});
	 }
	 
	 if ($("#elevatorPitch").length > 0) {
	 	var key = $('#elevatorPitch').attr('pitch');
		if($.cookie('yll-pitch-'+key) != null){
			$('#elevatorPitch').hide();
			$('#hiddenPitch').show();
		}
	 }

	 
	 /**Date input**/
	 
	if ($.datepicker) {
		$(".datepicker").datepicker({
			minDate: 0,
			maxDate: '+3M',
			dateFormat: "DD, d MM yy"
		});
	}
	
	/** Get venues when changing areas in /event/add **/
	
	 $(".area-select select").change(function(){
	 	var area_id = $(this).val();
		updateVenuesByArea(area_id);
	});
	
	 $("select#BusinessCategory").change(function(){
	 	var subcategory_id = $(this).val();
		$('.row-subcategory').hide();
		$('#row-subcategory-'+subcategory_id).show();
	});

	
	/** Get nearby areas to an area (when creating a group) **/
	
	 $("#GroupArea").change(function(){
	 	var area_id = $(this).val();
		updateNearbyAreasByAreaId(area_id);	
	});
	
	
	/** Get possible areas when switching groups **/
	
	 $(".group-select select").change(function(){
	 	var val = $(this).val();
		displayGroupDropdown(val);
	});
	
	/** Generic handler for turning a link into an ajax link**/
	
	$("a.ajax").click(function(){
		var url = $(this).attr('href');
		var id = $(this).attr('id');	
		var self = this;

		$.ajax({
			type: "GET",
			url: url,
			error: function (response){
				if(response.status == 403){
					window.location = '/account/login';
				}
			},
			success: function(message, status){
    			response = eval("("+message+")");
				switch(id){
					case 'clip-event-link': 
							ajaxHandlers.clipEvent(response, $(self));
							break;
					case 'unclip-event-link': 
							break;
					case 'follow-link':
					case 'unfollow-link':
							ajaxHandlers.follow(response, $(self));
							break;
					case 'feedback-like':
					case 'feedback-flag':
							ajaxHandlers.feedback(response, $(self));
							break;
					default:break;
					
				}
  			}
		});
		return false;
	});
 });
 
 var ajaxHandlers = {
 	
	
	clipEvent: function (response, self){
		if(response.success){
			self.parent().html('<p class="icon success-icon">This event has been saved to your <a href = "/account/calendar">calendar</a>.');
		}
	},
	
	follow: function(response, self){
		var handle = $(self).attr('handle');
		if(response.success){
			el = $(".follow-message");
			if($(".follow a").is(':visible')){
				el.html("<p class=\"icon success-icon\">You are now following "+handle+"</p>");	
				$(".unfollow").show();
				$(".follow").hide();
			} else {
				el.html("<p class=\"icon success-icon\">You are no longer following "+handle+"</p>");	
				$(".follow").show();
				$(".unfollow").hide();
			}
		}
	},
	feedback: function (response, self){
		if(response.success){
			id = self.attr('id');
			if(id == 'feedback-like'){
				$('#feedback-flag').parent().html("").removeClass("flag");
			}
			if(id == 'feedback-flag'){
				if($("#like-count").length < 1){
					$('#feedback-like').parent().html("Marked as inappropriate");	
				} else {
					$('#feedback-like').remove();
					$("#like-count br").remove();
					
				}
			}		
			self = self.parent();
			if (id == 'feedback-like') {
				self.html("Saved to <a href = \"/account/favourites\">favourites</a>.");
			} else {
				self.html("Thank you. Your feedback has been saved.");
			}
		}
	}
	
	
 };
 

 var tooltips = {
	'tag': 'A "tag" is like a keyword or category label. They\'re just single words or phrases you add to describe your items. Tags help you find items which have something in common.',
	'group-area': 'YourLocal London is all about content local to areas. When you add something to a group, select which area in the group is most suitable.',
	'question': 'Marking your post as a question will help us to organise and promote questions, to try and get the best possible answers for you.',
 	'business-about' : 'A few paragraphs describing your business',
 	'business-testimonial' : 'Add testimonials from happy customers!',
 	'business-offer' : 'Add details of promotions, discounts and special offers.<br /><br />You can set a start and end date, and we\'ll only promote your offer in that time',
 	'business-gallery' : 'Upload images to create a photo gallery.<br /><br />You can upload images of almost any size, and there\'s no limit on how many photos you can add',  
 	'business-times' : 'Add details of your opening hours. We\'ll display your hours on your page, along with a quick guide to when you are next open',
 	'location' : 'You can tag things you post to the site with a location (which is as easy as clicking on a map). This allows us to build up a map of what is going on in your community',
 	'feed': 'You can follow users on YourLocal London, (similar to Twitter or Facebook). In your My Stuff section, you\'ll get a personal feed of everything posted by people you\'ve followed - which could be friends, neighbours, or just interesting people you find on the site. Updates from any groups you join will be automatically included in your feed too'
 }

var displayGroupDropdown = function (val){
	if (isNaN(parseInt(val))) {
			$(".area-select select").attr('id', postType);
			$(".group-area-select").html('');
			$(".group-area-select").parent().hide();
			$(".area-select").parent().show();
			changeMapArea($('#'+postType).val());
		}
	else {
		var areas = group_areas[val];
		var newSelect = [];
		$(".area-select select").children().each(function(index, child){
			if ($.inArray(parseInt($(child).val(), 10), areas) > -1) {
				newSelect.push($(child).clone());
			}
		});
		$(".area-select select").attr('id', postType+'-Area');
		html = '<select id="'+postType+'" name="data[Post][Area]"></select>';
		$(".group-area-select").html(html);
		var select = $(".group-area-select select");
		$(newSelect).each(function(index, option){
			select.append(option);
		});
		$(".group-area-select").parent().show();
		$(".area-select").parent().hide();
		
		 changeMapArea($('#'+postType).val());
		 $("#"+postType).change(handleAreaChange); 
	}
}

function handleAreaChange(){
	var id = $(this).val();
	changeMapArea(id);
}

function changeMapArea(id){
	if($(".event-venue-select select").length > 0){
		updateVenuesByArea($("#"+postType).val());
	}
	if(typeof(gMapHelper) == 'undefined'){
		return;
	}

	$('#PostLongitude').val("0");
	$('#PostLatitude').val("0");
	$(".toggle-map").attr({center: gMapHelper.areas[id]})
	if(gMapHelper.visible){
		var center = gMapHelper.areas[id].split(",");
		gMapHelper.showClickMap(center[0], center[1]);
	}
}



function updateVenuesByArea(area_id){
	$(".event-venue-select").html('<div class="loading">Loading venues...</div>');
	$.ajax({
		type: "GET",
		url: getCurrentSite()+'/events/getvenues/'+area_id,
		error: function (response){
		},
		success: function(message, status){
			$(".event-venue-select").html(message);
		}
	});
	return false;
}

function updateNearbyAreasByAreaId(area_id){
	$('#additionalAreasRow .loading').show();
	$('#additionalAreasRow .selection').hide();
	$.ajax({
		type: "GET",
		url: getCurrentSite()+'/areas/nearby/'+area_id + '/' + 50,
		error: function (response){
		},
		success: function(message, status){
			
			$('#additionalAreasRow .loading').hide();
			$('#additionalAreasRow .selection').show();
			
			var response = eval("("+message+")");
			var html = '';
			var cellCount = 0;
			for(var key in response){
				if(cellCount == 0){
					html += '<tr>';
				}
				html += '<td class="area-checkbox" distance = "'+response[key].distance+'">'+response[key].name+'</td><td class="checkbox area-checkbox" distance = "'+response[key].distance+'"><input type="checkbox" name="data[Group][AdditionalArea][]" value="'+key+'" /></td>';
				if(cellCount == 1){
					html += '</tr>';
					cellCount = -1;
				}	
				cellCount++;
			}
			
			if (cellCount == 1) {
				html += '<td></td>';
			}
			html = '<table class="checkboxes">' +  html + '</tr></table><br /><br />';
			$("#groupAdditionalAreas").html(html);
			
			sliderVal = $("#groupDistanceSlider").slider('value');
			showGroupCheckboxesByDistance(sliderVal);
			
		}
	});
	return false;
}

function showGroupCheckboxesByDistance(distance){
	$(".area-checkbox").each(function(i, el){
		var areaDistance = parseFloat($(el).attr('distance'));
		if(areaDistance > distance){
			$(el).hide();
		} else {
			$(el).show();
		}
	});
}



var showProfileMore = function(){
	$('.remainder').show();
	$('.show-more').hide();
	return false;
}
var showProfileLess = function(){
	$('.remainder').hide();
	$('.show-more').show();
	return false;
}

var toggleOpeningHours = function(el){
	$('#opening-hours').toggle();
	if($('#opening-hours').is(':visible')){
		el.innerHTML = '(Hide opening hours)';
	} else {
		el.innerHTML = '(Show full opening hours)';
	}
}
var showHoursLess = function(){
	$('.remainder').hide();
	$('.show-more').show();
	return false;
}

function getCurrentSite(){
	host = jQuery.url.attr("host");
	protocol = jQuery.url.attr("protocol");
	return protocol + '://' + host;
}


function togglePitch(element){
	if ($('#elevatorPitch').is(':visible')) {
		$('#elevatorPitch').hide();
		$('#hiddenPitch').show();
		var key = $('#elevatorPitch').attr('pitch');
		$.cookie('yll-pitch-'+key, '1', {
			expires: 365
		});
	}	else {
		var key = $('#elevatorPitch').attr('pitch');
		$.cookie('yll-pitch-'+key, null);
		$('#elevatorPitch').show();
		$('#hiddenPitch').hide();
	}
}
