function remove_sub(id)
{
	$.post("/ajax/common/unsubscribe_my_area", {"id": id},
		function(data){
			$("#item_unsub_"+id).remove();
			
			
			// Check for last element from a list
			if ($("#ul_unsub_f > li").length == 1)
			{
				$("#li_unsub_f").show();
			}
			if ($("#ul_unsub_e > li").length == 1)
			{
				$("#li_unsub_e").show();
			}
			if ($("#ul_unsub_v > li").length == 1)
			{
				$("#li_unsub_v").show();
			}
			
			
		}, "json");
		return false;
	
}

function remove_account(id)
{
	$.post("/ajax/common/remove_account", {"id": id});
	$("#item_unsub_"+id).remove();
	return false;	
}



var current_carousel = 0;
var total_carousel = 0;


function newsletter_decision()
{
	if ($("#reg_newsletter").attr('checked'))
	{
		// Show them
		$(".newsletter_additional").show();
	}
	else
	{
		// Hide them
		$(".newsletter_additional").hide();
	}
}

function show_box_account(what)
{
	if (what == "register")
	{
		$('.frm_login').hide();
		$('.frm_register').show();
		$('.frm_forgot').hide();
	}
	else
	{
		$('.frm_login').hide();
		$('.frm_register').hide();
		$('.frm_forgot').show();
	}
}

function reset_login_forms()
{
	$('.frm_login').show();
	$('.frm_register').hide();
	$('.frm_forgot').hide();
}

function check_forgot(msg1)
{
	$("#forgot_loader").show();
	$("#forgot_account").hide();
	$.post("/ajax/common/check_forgot", { "email": $("#forgot_email").val() },
		function(data){
			$("#forgot_error").html('');
			if (data.error)
			{
				$("#forgot_error").html(data.error);
			}
			if (data.success)
			{
				alert(msg1);
				location.reload(true);
			}
			$("#forgot_loader").hide();
			$("#forgot_account").show();
		}, "json");
	return false;
}

function check_login()
{
	$("#login_loader").show();
	$("#login_account").hide();
	$.post("/ajax/common/do_login", { "email": $("#login_email").val(), "password": $("#login_pass").val() },
		function(data){
			$("#login_error").html('');
			if (data.error)
			{
				$("#login_error").html(data.error);
			}
			if (data.success)
			{
				location.reload(true);				
			}
			$("#login_loader").hide();
			$("#login_account").show();
		}, "json");
	return false;
}

function check_register()
{
	// Clear success/error boxes
	$("#register_success").text("");
	$("#register_loader").show();
	$("#register_account").hide();
	var newsletter = 0;
	if ($("#reg_newsletter").attr('checked'))
	{
		newsletter = 1;
	}
	$.post("/ajax/common/register_account", { "newsletter": newsletter, "home_location" : $("#reg_home_location").val(), "username": $("#reg_user").val(), "email": $("#reg_email").val(), "password1": $("#reg_pass_1").val(), "password2": $("#reg_pass_2").val() },
		function(data){
			$("#register_error").html("");
			if (data.error)
			{
				$("#register_error").html(data.error);
			}
			if (data.success)
			{
				alert(data.success);
				location.reload(true);				
			}
			$("#register_loader").hide();
			$("#register_account").show();
		}, "json");
	return false;
}







$(function(){
	$('.replace').live('blur',function(){
		var default_value;
		if($(this).attr('rel')){
			default_value = $(this).attr('rel');
		} else {
			default_value = $(this).attr('defaultValue');
		}
		
		if( ! $(this).val())$(this).val(default_value);
	});
	$('.replace').live('focus', function(){
		var default_value;
		if($(this).attr('rel')){
			default_value = $(this).attr('rel');
		} else {
			default_value = $(this).attr('defaultValue');
		}
		
		if($(this).val() == default_value){
			$(this).val('');
		}
	});

	$("#change_location_link a").click(function(){
		if($(".change_location_container").is(":visible")){
			$('#change_location_link').removeClass("selected");
			$(".change_location_container").hide();
		} else {
			$(this).parent().addClass("selected");
			$(".change_location_container").show();
		}
		return false;
	});
	
	$("#change_language").click(function(){
		if($(".change_language_container").is(":visible")){
			$('#language_link').removeClass("selected");
			$(".change_language_container").hide();
		} else {
			$(this).parent().addClass("selected");
			$(".change_language_container").show();
		}
		return false;
	});
	
	$("#profile_link a").click(function(){
		if($(".change_profile_container").is(":visible")){
			$('#change_profile_link').removeClass("selected");
			$(".change_profile_container").hide();
		} else {
			$(this).parent().addClass("selected");
			$(".change_profile_container").show();
		}
		return false;
	});
	$(".event_instance_link").click(function(){
		if($(".event_instances_container").is(":visible")){
			$('.event_instance_link').parent().removeClass("selected");
			$(".event_instances_container").hide();
		} else {
			$(this).parent().addClass("selected");
			$(".event_instances_container").show();
		}
		return false;
	});
	$(document).mouseup(function(e) {
		if($(e.target).parents('.change_location_container').length == 0) {
			$('#change_location_link').removeClass("selected");
			$(".change_location_container").hide();
		}
		if($(e.target).parents('.change_profile_container').length == 0) {
			$('#profile_link').removeClass("selected");
			$(".change_profile_container").hide();
		}
		if($(e.target).parents('.change_labguage_container').length == 0) {
			$('#language_link').removeClass("selected");
			$(".change_language_container").hide();
		}
		if($(e.target).parents('.event_instances_container').length == 0) {
			$('.event_instance_link').parent().removeClass("selected");
			$(".event_instances_container").hide();
		}
	});
	
	$('.rsvp_holder').hover(function(){
		$('.rsvp_container', $(this)).show();
	}, function(){
		$('.rsvp_container', $(this)).hide();
	});
	$('.calendar_holder').hover(function(){
		$('.calendar_container', $(this)).show();
	}, function(){
		$('.calendar_container', $(this)).hide();
	});
	
	$('.tab_buttons a').click(function(){
		var tab = $(this).attr('rel');
		if( ! $('#' + tab).is(':visible')){
			$('.tab_content', $(this).parents('.tabs_holder')).hide();
			$('#' + tab).show();
			$('a.selected', $(this).parent()).removeClass('selected');
			$(this).addClass('selected');
		}
		return false;
	});
	
	$('.filter_comments label, .virtual_event label, .my_settings label').each(function(i){
		var id = $(this).attr('for');
		var a = $('<a>').attr("href","#").attr("rel", id);
		
		$('#'+id).wrap('<span class="input_wrapper"></span>');
		if($("#"+id).attr("checked")){
			a.addClass("checked");
			$(this).addClass("checked");
		} else {
			a.addClass("unchecked");
		}
		
		$('#'+id).after(a);
	});
	$('.filter_comments input, .virtual_event input, .my_settings input').change(function(){
		var id = $(this).attr('name');
		changeInput(id);
	});
	
	$('.filter_comments a, .virtual_event a, .my_settings a').click(function(){
		var id = $(this).attr('rel');
		$("#"+id).click();
		changeInput(id);
		return false;
	});
	/*
if ($.browser.msie && $.browser.version == 6.0) {
		$('.filter_comments label, .virtual_event label, .my_settings label').click(function(){
			var id=$(this).attr('for');
			$("#"+id).click();
			changeInput(id);
			return false;
		});
	}
*/
	
	$('.close_notification').live('click', function(){
		$(this).parents('.notification').slideUp('fast', function(){
			$(this).remove();
		});
		return false;
	});
	
	// Show map dialog
	$('#show-map-box').dialog
	({ 
		autoOpen: false,
		modal: true,
		width: 650,
		height: 400
	});
	$('#show_map-box-link').click(function(){
		$('#show-map-box').dialog('open');
		call_set_center_venue_map();
		return false;
	});
	
	
	
	// events javasctipt
	
	//rsvp functionality
	
	$('.rsvp_container ul li a').live('click', function(){
		var rel = $(this).attr('rel');
		rel = rel.split(',');
		var id = rel[0]
		var action = rel[1];
		var id_event = rel[2];
		var $element = $(this);
		$.ajax({
			type: 'POST',
			url: "/ajax/event/rsvp",
			dataType: "json",
			data: "action="+action+"&id_event="+id,
			success: function(data){
				if(data.error){
					$('.rsvp_error', $element.parents('.rsvp_holder')).remove();
					$element.parents('.rsvp_holder').append('<p class="rsvp_error">'+data.error+'</p>');
				} else {
					$('.rsvp', $element.parents('.rsvp_holder')).html(data.msg);
					var $parent = $element.parents('.rsvp_container');
					if($('.undo', $parent).is(':visible')){
						$('li', $parent).show();
						$('.undo', $parent).hide();
					} else {
						$('li', $parent).hide();
						$('.undo', $parent).show();
					}
					// Also do subscribe
					if (data.result == 0)
					{
						//un_subscribe('event', id_event, 'unsub');
					}
					else
					{
						un_subscribe('event', id_event, 'sub');
					}
				}
			},
			error: function(){}
		});
		return false;
	});
	$('.share_on_twitter, .share_on_facebook').attr('target', '_blank');
	$('.add_event_button').wrap('<span class="add_wrapper"></span>');
});

function changeInput(id){
		if($('#'+id).attr('checked')){
			$("a[rel^='"+id+"']").addClass("checked").removeClass("unchecked");
			$("label[for^='"+id+"']").addClass("checked");
		} else {
			$("a[rel^='"+id+"']").removeClass("checked").addClass("unchecked");
			$("label[for^='"+id+"']").removeClass("checked");
		}
}

var marker_primary;
var map_primary;
var geocoder_primary;

function initialize_map(point1, point2, address, city, title) {
	// Change title
	$("#show-map-box").dialog("option", "title", title);
	// We don't have lat/long but we have an address
	if (point1 == "")
	{
		var myOptions = {
				address: address
		};
		geocoder_primary = new google.maps.Geocoder;
		geocoder_primary.geocode(myOptions,
				function(results, status) {
					if (status == google.maps.GeocoderStatus.OK)
					{
						set_map_center(results[0].geometry.location.lat(), results[0].geometry.location.lng());
					}
					else
					{
						alert('Lookup failed : '+status);
					}
				}
		);	
	}
	else
	{
		set_map_center(point1, point2);
	}
}

function set_map_center(point1, point2)
{
	// We have a lat/long pair :D
	var latlng = new google.maps.LatLng(point1, point2);
    var myOptions = {
		zoom: 14,
		center: latlng,
		mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    // Init map
    map_primary = new google.maps.Map(document.getElementById("mmaapp_holder"), myOptions);
    // Create the pin point marker
    marker_primary = new google.maps.Marker({
    	position: latlng, 
    	map: map_primary
  	});
    marker_primary.setMap(map_primary);
}



// Sorin below ... TODO : update when Mircea finishes with the other templates

var form_options_general = {
	dataType: 'json',
	success: function(data){
		$(".error-formelement").html("");
		if(data.error)
		{
			for (error in data.error)
			{
				$("#error_"+error).show();
				$("#error_"+error).html(data.error[error]);
			}
		}
		else
		{
			//display message on success
			if (data.redirect_to)
			{
				window.location = data.redirect_to;
			}
		}
	},
	error: function(data){
		alert('An error has occured while executing the script!');
	}
};







var cache = {}; // Used on jQuery UI autocomplete
$(document).ready(function(){
	
	// Make locations clickable + save location
	$('.geo_tags').click(function(){
		$('#location_name').val($(this).attr('title'));
		save_location();
		return false;
	});
	
	// Autocomplete for change location
	$("#location_name").autocomplete({
		source: function(request, response) {
			if (cache.term == request.term && cache.content) {
				response(cache.content);
			}
			if (new RegExp(cache.term).test(request.term) && cache.content && cache.content.length < 13) {
				var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
				response($.grep(cache.content, function(value) {
					return matcher.test(value.value)
				}));
			}
			$.ajax({
				url: "/ajax/geo/get_cities?get_countries=1",
				dataType: "json",
				data: request,
				success: function(data) {
					//cache.term = request.term;
					//cache.content = data;
					response(data);
				}
			});
		},
		minLength: 2,
		select: function(event, ui) {
			save_location();
		}
	});
	
	// Login if needed
	$('#login-box').dialog
	({ 
		autoOpen: false,
		modal: true,
		width: 710,
		height: 400
	});
	
	$('.show_login-box').click(function(){
		$('#login-box').dialog('open');
		return false;
	});	
	
	$('#video .gallery_item a img, #video_gallery .gallery_item a img').hover(function(){
		current_image_displayed = 0;
		s3_url_thumb = $(this).attr('src');
		s3_url_thumb = s3_url_thumb.replace('thumb_3.jpg', '');
		current_image_hovered = $(this);
		interval = setInterval('get_new_image()', 600);
		get_new_image();
	}, function(){
		clearInterval(interval);
		current_image_hovered.attr('src', s3_url_thumb+'thumb_3.jpg');
	});
});
var interval;
var current_image_displayed;
var current_image_hovered;
var s3_url_thumb;
function get_new_image()
{
	if(current_image_displayed == 5)current_image_displayed = 0;
	img = new Image();
	img.src = s3_url_thumb+'thumb_'+current_image_displayed+'.jpg';
	current_image_hovered.attr('src', img.src);
	current_image_displayed++;
}

function save_location()
{
	$('#save_location_form').ajaxSubmit(form_options_general);
	return false;
}

// Like / unlike handler
function like_unlike(what, id)
{
	$("#error_like_it").text("");
	$("#like_unlike_link").addClass('ajax_loader_like_it');
	$.post("/ajax/like_unlike/voting", { "what": what, "id": id },
		function(data){
			if (data.error)
			{
				$("#error_like_it").text(data.error);
			}
			if (data.text)
			{
				$("#like_it_text").text(data.text);
			}
			if (data.action_done)
			{
				if (data.action_done == "1")
				{
					// Vote up
					$("#like_unlike_link").removeClass('unlike_it');
					$("#like_unlike_link").addClass('like_it');
				}
				else if (data.action_done == "-1")
				{
					// Vote down
					$("#like_unlike_link").removeClass('like_it');
					$("#like_unlike_link").addClass('unlike_it');
				}
			}
			$("#like_unlike_link").removeClass('ajax_loader_like_it');
		}, "json");
}

function fixRSVP(){
	$('.carousel_container .item').each(function(i){
		$('a:first', $(this)).wrap('<span class="fix_rsvp"></span>');
	});
}

function set_cookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function get_cookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}


function delete_cookie ( cookie_name )
{
  var cookie_date = new Date ( );  // current date & time
  cookie_date.setTime ( cookie_date.getTime() - 1 );
  document.cookie = cookie_name += "=; expires=" + cookie_date.toGMTString();
}
