function header_bounce()
{
	$('#header_actions li:eq(0) a').children().effect("bounce", { distance:25, times: 4 }, 300);
}

function header_pulsate($elem)
{
	$elem.effect("pulsate", { distance:25, times: 2 }, 300);
}
	
$(function()
{
	var global_id = null;
	
	$.ajaxSetup(
	{
		complete	: function(){ overlay.hide(); },
		beforeSend	: function()
		{
			if(		this.url.indexOf('/oohembed/?url=') 	== -1
				&&	this.url.indexOf('active_users=') 		== -1
				&&	this.url.indexOf('_autocompleter=') 	== -1
				&&	this.url.indexOf('hide_loader')	 		== -1
				&&	this.url.indexOf('empty_f')	 			== -1
			){ overlay.show(); }
		}
	});
	
	$('.delete').live('click', function(){ return confirm(__globals.ERRORS.listing_delete) ? true : false; });
	
	// Croppables
	var $croppables = $('.croppable');
	if($croppables.length)
	{
		var $frame = $('<iframe id="upload_frame" name="upload_frame" src="about:blank" style="width: 0px; height: 0px; border: 0px solid #000;"></iframe>').appendTo($('body'));
		
		$croppables.find('img.crop-img').hide();
		$('.upload', $croppables[0]).click(function()
		{
			var $this = $(this);
			if($this.parents('.input:eq(0)').find('.file_field input').val().length <= 0){ return false; }
			
			$this.val('Uploading ...').addClass('uploading').parents('form:eq(0)').attr('target', $frame.attr('name'))
			
			// needs timeout to work after submit
			setTimeout(function(){ $this.attr('disabled','disabled').parents('.croppable').find('input[type=file]').attr('disabled','disabled'); }, 10);
		});
		$('input[type=file]', $croppables[0]).change(function(){ $('input[name^=upload_croppable]:hidden', $croppables[0]).fadeIn(); });
		
		$croppables.find('input[name^=upload_delete]').unbind('click')
			.click(function(){ $croppables.find('.jcrop-holder, .preview').slideToggle(); });
		
		window.croppable = function(field_name, image)
		{
			var $container = $('#id_'+field_name).parents('.croppable');
			
			// needs timeout to work everytime
			setTimeout(function()
			{
				$container
					.find('input[type=file]').removeAttr('disabled').val('').end()
					.find('input[name^=upload_croppable]').fadeOut().val('Upload').removeAttr('disabled').end()
					.find('input[name^=upload_delete]').parent().show()
					.parents('form:eq(0)').removeAttr('target');
			}, 10);
			
			$img = $container.find('img:eq(0)').hide().attr('src', __rootPath + 'public/files/'+image);
			
			if('Jcrop' in $img[0])
			{
				delete $img[0].Jcrop; // delete must be on new line!!!
				$container.find('.jcrop-holder').remove();
			}
			
			$img.show().unbind('load').load(function()
			{
				var $img = $(this).css('width', '');
				var maxWidth 	= parseInt($img.css('maxWidth') || $img.css('max-width'));
				var maxHeight 	= parseInt($img.css('maxHeight') || $img.css('max-height'));
				
				$img.css('maxWidth', '').css('maxHeight', '');
				var naturalWidth = $img[0].naturalWidth || $img[0].width;
				var naturalHeight = $img[0].naturalHeight || $img[0].height;
				$img.css('maxWidth', maxWidth).css('maxHeight', maxHeight);
				
				var iw = $img.width();
				var ih = $img.height();
				var iwk = iw / naturalWidth;
				var ihk = ih / naturalHeight;
				
				var $preview = $container.find('.preview').show().find('img').attr('src', __rootPath + 'public/files/'+image);
				var $preview_cnt = $preview.parent().click(function(){ return false; });
				var cw = $preview_cnt.width();
				var ch = $preview_cnt.height();
				
				var coords = { x: 0, y: 0, x2: 0, y2: 0 };
				var $coord_x = $img.nextAll('.coord-x');
				var $coord_y = $img.nextAll('.coord-y');
				var $coord_x2 = $img.nextAll('.coord-x2');
				var $coord_y2 = $img.nextAll('.coord-y2');
				
				if($coord_x.val() == ''){ coords.x = iw/2-cw/2; $coord_x.val(Math.floor(coords.x/iwk)) }else{ coords.x = $coord_x.val()*iwk; }
				if($coord_y.val() == ''){ coords.y = ih/2-ch/2; $coord_y.val(Math.floor(coords.y/ihk)) }else{ coords.y = $coord_y.val()*ihk; }
				if($coord_x2.val() == ''){ coords.x2 = iw/2+cw/2; $coord_x2.val(Math.floor(coords.x2/iwk)) }else{ coords.x2 = $coord_x2.val()*iwk; }
				if($coord_y2.val() == ''){ coords.y2 = ih/2+ch/2; $coord_y2.val(Math.floor(coords.y2/ihk)) }else{ coords.y2 = $coord_y2.val()*ihk; }
				
				
				$img.Jcrop(
				{
					setSelect: [ coords.x, coords.y, coords.x2, coords.y2 ],
					onSelect: function(coords){ $coord_x.val(coords.x); $coord_y.val(coords.y); $coord_x2.val(coords.x2); $coord_y2.val(coords.y2); },
					onChange: function(coords)
					{
						cwk = coords.w*iwk;
						chk = coords.h*ihk;
						
						$preview.css(
						{
							width: Math.round( cw*(iw/(cwk)) ) + 'px',
							height: Math.round( ch*(ih/(chk)) ) + 'px',
							marginLeft: '-' + Math.round(coords.x*iwk*(cw/cwk)) + 'px',
							marginTop: '-' + Math.round(coords.y*ihk*(ch/chk)) + 'px'
						});
					},
					boxWidth: maxWidth, 
					boxHeight: maxHeight,
					aspectRatio: ($img.is('.keep-ratio') ? cw/ch : 0)
				});
				
				$container.find('.crop-loader').hide();
			});
			
			if($('.avatar').length)
			{
				$('.avatar li.active').removeClass('active').find('input[type=radio]').attr('checked', '');
			}
		}
	}
	
	// Custom
	$('#tabs').tabs();
	
	$('#id_school').autocomplete(
	{ 
	    queryName: 'school_autocompleter', //aditional parameters
	    minChars: 3, 
	    maxHeight: 300,
	    width: 450,
	    deferRequestBy: 0, //miliseconds
	    
	    onSelect: function(value, data)
	    {
	    	$('#id_school_id').val(data).data('school_title', value).data('school_id', data); 
	    	$('.input:has(#id_school)').removeClass('invalid');
	    },
	    onStart: function(query)
	    {
	    	this.isStarted = query;
	    	$('.input:has(#id_school)').addClass('loading');
	    },
	    onEnd: function(query)
	    {
	    	if(this.isStarted == query){ $('.input:has(#id_school)').removeClass('loading'); }
	    }
	});
	
	$('#id_school')
	//	.change(function(e){ if($('#id_school_id').data('school_title') != this.value){ $('#id_school_id').val(''); } })
		.blur(function()
		{
			if($('#id_school_id').data('school_title') == this.value)
			{
				$('.input:has(#id_school)').removeClass('invalid');
				$('#id_school_id').val($('#id_school_id').data('school_id'));
			}
			else
			{
				$('.input:has(#id_school)').addClass('invalid');
				$('#id_school_id').val('');
			}
		}
	);
	
	$('#id_done_action, #id_like_action').live('click', function()
	{
		var url = $(this).attr('href') + '?hide_loader';
		var id = $(this).attr('id');
		var elem = $(this);
		if(elem.data('doing') == 1){ return false; }
		
		elem.data('doing', 1);
		
//		overlay.show();
		$.get( url, {},	function(result)
		{
			elem.data('doing', 0);
			$('.action_updated').hide();
			if(result)
			{ 
				$('.comment_button_and_alert').show(); $('#' + id + '_alert').fadeIn(); 
				$('#id_like_action').fadeOut();
				if(id == 'id_done_action')
				{
					$('#id_times_done').text(parseInt($('#id_times_done').text())+1).parent().fadeIn();
					$('#all_times_done').text(parseInt($('#all_times_done').text())+1);
					
					var $header_update_all = $('#id_header_all_done');
					if($header_update_all.length>0)
					{
						var header_all_done = parseInt($header_update_all.html()) + 1;
						$header_update_all.html(header_all_done);
						if (header_all_done == 2){ $('#id_header_all_done_multiple').html('s'); }
						header_pulsate($header_update_all);
					}
					
					/*
					if(result.alert_id)
					{
						$('#action_alert_message').html(result.message);
						$('#action_alert').dialog('option', 'buttons', {'Ok' : function(){ $(this).dialog('close'); } });
						$('#action_alert').dialog('open');
					}
					*/
				}
				else if(id == 'id_like_action')
				{
					var a_href = url.replace(/like/, 'view');
					var a_title = $('#id_action_title').attr('title');
					var image = $('#id_action_image').html().replace(/height:(\s*)(\d+)px/, 'height: 26px').replace(/width:(\s*)(\d+)px/, 'width: 26px');
					
					if($('#header_actions').children('li').length == 6){ $('#header_actions').children('li:last').fadeOut().remove(); }
					$('<li>'
					+	'<a href="' + a_href +'" title="' + a_title +'">' + image +	'</a>'
					+'</li>').prependTo($('#header_actions')).hide().fadeIn();
					
					var $update_all = $('.sidebar_start_tracking #tracking_total');
					if($update_all.length>0)
					{
						var all_done = parseInt($update_all.html())>0 ? parseInt($update_all.html()) + 1 : 1;
						$update_all.html(all_done);
						if (all_done == 2){ $('.sidebar_start_tracking #tracking_multiple').html('s'); }
					}
					
					var $header_update_all = $('#id_header_all_track');
					if($header_update_all.length>0)
					{
						var header_all_done = parseInt($header_update_all.html()) + 1;
						$header_update_all.html(header_all_done);
						if (header_all_done == 2){ $('#id_header_all_track_multiple').html('s'); }
						header_pulsate($header_update_all);
					}
					
					header_bounce();
				}
			}
		}, 'json');
		
		return false;
	});
	
	$('#ajax_done_comment, #ajax_class_done_comment').live('click', function()
	{
		var url = $(this).attr('href') + '?hide_loader';
		var elem = $(this);
		if(elem.data('doing') == 1){ return false; }
		
		elem.data('doing', 1);
		
//		overlay.show();
		$.get( url, {},	function(result)
		{
			elem.data('doing', 0);
			$('.action_updated').hide();
			if(result)
			{ 
				$('#id_like_action').fadeOut();

				$('#id_times_done').text(parseInt($('#id_times_done').text())+1).parent().fadeIn();
				$('#all_times_done').text(parseInt($('#all_times_done').text())+1);
				
				var $header_update_all = $('#id_header_all_done');
				if($header_update_all.length>0)
				{
					var header_all_done = parseInt($header_update_all.html()) + 1;
					$header_update_all.html(header_all_done);
					if (header_all_done == 2){ $('#id_header_all_done_multiple').html('s'); }
					header_pulsate($header_update_all);
				}
					
				/*
				if(result.alert_id)
				{
					$('#action_alert_message').html(result.message);
					$('#action_alert').dialog('option', 'buttons', 
					{'Ok' : function()
						{ 
							$(this).dialog('close'); 
							$('#id_done_action_alert').hide();
							$('#post_comment').dialog('open');
						} 
					});
					$('#action_alert').dialog('open');
				}
				else
				{
					$('#id_done_action_alert').hide();
					$('#post_comment').dialog('open');
				}
				*/
				$('#id_done_action_alert').hide();
				$('#post_comment').dialog('open');
			}
		}, 'json');
		
		return false;
	});

	$('.movie_dialog').dialog(
	{
		autoOpen		: false,
		bgiframe		: false,
		width			: 550,
		// height			: 500,
		modal			: true,
		closeOnEscape	: true,
		draggable		: false,
		resizable		: false,
		buttons:		{	
			'Close' 	: function(){ $(this).dialog('close'); }
		}
	});
		
	$('#what_are_actions_toggle').click(function(){

		$('#what_are_actions').dialog('open');
		
		return false;
	});

	$('#play_video_toggle').click(function(){

		$('#play_video').dialog('open');
		
		return false;
	});
	
	$('#id_class_done_action, #id_class_like_action').live('click', function()
	{
		var url = $(this).attr('href') + '?hide_loader';
		var id = $(this).attr('id');
		var elem = $(this);
		if(elem.data('doing') == 1){ return false; }
		
		elem.data('doing', 1);
		
//		overlay.show();
		$.get(url, {}, function(result)
		{
			elem.data('doing', 0);
			$('.action_updated').hide();
			if(result)
			{ 
				$('.comment_button_and_alert').show(); $('#' + id + '_alert').fadeIn(); 
				$('#id_class_like_action').fadeOut();
				if(id == 'id_class_done_action')
				{
					$('#id_times_done').text(parseInt($('#id_times_done').text())+1).parent().fadeIn();
					$('#all_times_done').text(parseInt($('#all_times_done').text())+1);
					
					var $header_update_all = $('#id_header_all_done');
					if($header_update_all.length>0)
					{
						var header_all_done = parseInt($header_update_all.html()) + 1;
						$header_update_all.html(header_all_done);
						if (header_all_done == 2){ $('#id_header_all_done_multiple').html('s'); }
						header_pulsate($header_update_all);
					}
					/*
					if(result.alert_id)
					{
						$('#action_alert_message').html(result.message);
						$('#action_alert').dialog('open');
					}
					*/
				}
				else if(id == 'id_class_like_action')
				{
					var a_href = url.replace(/like/, 'view');
					var a_title = $('#id_action_title').attr('title');
					var image = $('#id_action_image').html().replace(/height:(\s*)(\d+)px/, 'height: 26px').replace(/width:(\s*)(\d+)px/, 'width: 26px');
					
					if($('#header_actions').children('li').length == 6){ $('#header_actions').children('li:last').fadeOut().remove(); }
					$('<li>'
					+	'<a href="' + a_href +'" title="' + a_title +'">' + image +	'</a>'
					+'</li>').prependTo($('#header_actions')).hide().fadeIn();
					
					var $update_all = $('.sidebar_start_tracking #tracking_total');
					if($update_all.length>0)
					{
						var all_done = parseInt($update_all.html())>0 ? parseInt($update_all.html()) + 1 : 1;
						$update_all.html(all_done);
						if (all_done == 2){ $('.sidebar_start_tracking #tracking_multiple').html('s'); }
					}
					
					var $header_update_all = $('#id_header_all_track');
					if($header_update_all.length>0)
					{
						var header_all_done = parseInt($header_update_all.html()) + 1;
						$header_update_all.html(header_all_done);
						if (header_all_done == 2){ $('#id_header_all_track_multiple').html('s'); }
						header_pulsate($header_update_all);
					}
					
					header_bounce();
				}
			}
		}, 'json');
		
		return false;
	});
	
	$('.action_updated .cancel').click(function(){
		$(this).parents('.action_updated').fadeOut();
		$('button.dialog_toggle').attr('id', '');
	});
	
	
	var linkified_links = function()
	{
		var $this = $(this);
		$.get('/home/link_clicked/?url='+escape($this.attr('href')).replace(new RegExp('\/', 'g'), '%2F'));
		$this.attr('target', '_blank');
	}
	$('#cnt .linkify').each(function()
	{
		var $c = $(this);
		var links_cache = [];
		var links = $c.text().match(/((?:http:\/\/|www.)[^\s^)]+)/g)
		
		if(links)
		{
			for(i=0, len=links.length; i<len; i++)
			{
				var l = links[i];
				if($.inArray(l, links_cache) > -1){ continue; }
				links_cache[links_cache.length] = l
				
				var html = '<a href="http://'+l.replace(new RegExp('^http://'), '')+'" class="linkified">'+l+'</a>';
				var replace = new RegExp(l.replace(/\?/g, '\\?').replace(/&/g, '&amp;'), 'g');
				$c[0].innerHTML = $c[0].innerHTML.replace(replace, html);
			}
		}
		$c.find('.linkified').click(linkified_links);
	});
	
	if(($oohembed = $('.oohembed')).length > 0)
	{
		$oohembed.each(function()
		{
			var links_cache = [];
			var $ooh = $(this);
			var links = $ooh.text().match(/((?:http:\/\/|www.)[^\s^)]+)/g);
			
			if(links)
			{
				for(i=0, len=links.length; i<len; i++)
				{
					var l = links[i];
					if($.inArray(l, links_cache) > -1){ continue; }
					links_cache[links_cache.length] = l;
					
					var html = '<a href="http://'+l.replace(new RegExp('^http://'), '')+'" class="linkified">'+l+'</a>';
					var replace = new RegExp(l.replace(/\?/g, '\\?').replace(/&/g, '&amp;'), 'g');
					$ooh[0].innerHTML = $ooh[0].innerHTML.replace(replace, html);
					
					$.getJSON('/oohembed/?url='+l.replace(/&/g, '%26'), function(json)
					{
						if(json.error){ return; }
						
						var _html = '<div class="oohembedreplaced">'
						+	(json.responce.html || '')
						+	(json.responce.url ? '<img src="'+json.responce.url+'" />' : '')
						+	'</div>';
						
						var anchor = '<a href="http://'+json.url.replace(new RegExp('^http://'), '')+'" class="linkified">'+json.url+'</a>';
						var _replace = new RegExp(anchor.replace(/\?/g, '\\?').replace(/&/g, '&amp;'), 'gi');
						$ooh[0].innerHTML = $ooh[0].innerHTML.replace(_replace, _html);
					});
				}
				
				$ooh.find('.linkified').click(linkified_links);
			}
		});
	}
	
	$('#cant_find_school, #cant_find_new_school').click(function()
	{
		$('#id_school_id, #id_new_school_id').val('');
		$('#school_in_uk, #new_school').slideUp().find('input').each(function(){$(this).not('.button').val('');});
		//$('#id_school, #id_new_school').val('').parents('.input').slideUp();
		$('#find_school').slideDown();

		return false;
	});
//	if($('#id_find_school').val() && !$('#id_school_id').val()){ $('#cant_find_school').click(); }
	
	overlay = new(function()
	{
		var $overlay = $('<div></div>').hide().appendTo('body').css(
		{
			position: 'fixed', top: 0, left: 0, width: $(document).width()+'px', height: $(document).height()+'px',
			background: '#000 url('+__rootPath+'public/styles/images/loader.gif) center '+((screen.height/2)-150)+'px no-repeat',
			zIndex: 10000,
			opacity: 0.5 
		}).click(function(){ $(this).hide(); });
		
		return {
			show: function(){ $overlay.fadeIn(); },
			hide: function(){ $overlay.fadeOut(); }
		}
	});
	
	$('#show_more_feeds').click(function()
	{
		var elem = $(this);
		if(elem.data('show_more_feeds') == 1){ return false; }
		
		elem.data('show_more_feeds', 1);
		var page = parseInt(elem.attr('href').substr(1));
		
		$.get(location.href, {feed_page: page}, function(data)
		{
			var $data = $(data);
			var feeds = $data.find('.timeline #comments li');
			
			$('.timeline #comments.not-featured ul').append(feeds);
			elem.attr('href', '#'+(++page)).data('show_more_feeds', 0);
			
			if(!$data.find('#show_more_feeds').length){ elem.hide(); }
			
			for(f=0, flen = feeds.length; f < flen; f++)
			{
				(function()
				{
					var $f = $(feeds[f]);
					var links = $f.text().match(/((?:http:\/\/|www.)[^\s^)]+)/g);
										
					if(links)
					{
						var links_cache = [];
						for(i=0, len=links.length; i<len; i++)
						{
							var l = links[i];
							if($.inArray(l, links_cache) > -1){ continue; }
							links_cache[links_cache.length] = l;
							
							var html = '<a href="'+l+'">'+l+'</a>';
							var replace = new RegExp(l.replace(/\?/g, '\\?').replace(/&/g, '&amp;'), 'g');
							$f[0].innerHTML = $f[0].innerHTML.replace(replace, html);
							
							$.getJSON('/oohembed/?url='+l.replace(/&/g, '%26'), function(json)
							{
								var _html = '<div class="info">'
								+	(json.responce.html || '')
								+	(json.responce.url ? '<img src="'+json.responce.url+'" />' : '')
								+	'</div>';
								
								var anchor = '<a href="'+json.url+'">'+json.url+'</a>';
								var _replace = new RegExp(anchor.replace(/\?/g, '\\?').replace(/&/g, '&amp;'), 'g');
								$f[0].innerHTML = $f[0].innerHTML.replace(_replace, _html);
							});
						}
					}
				})();
			}
			
			setTimeout(function()
			{
				FB.Facebook.init('{Application_Config::$FACEBOOK_API_KEY}', "/xd_receiver.htm");
				FB.XFBML.Host.autoParseDomTree = true;
			}, 500);
		});
		
		return false;
	});
	
	if($('.datepicker').length > 0)
	{
		$(".datepicker").datepicker();
	}
	
	$('ul.featured_resources li')
//		.live("mouseover", function (){ $(this).addClass('hover');	})
//		.live("mouseout", function (){ $(this).removeClass('hover'); })
		.live("click", function()
		{
			if( $(this).parent().parent().parent().attr('id') != "Stats" )
			{
				$(this).siblings().removeClass('active').find('span.desc').slideUp().end().find('dl').slideUp();
				$(this).addClass('active');
				$(this).find('span.desc').slideDown().end().find('dl').slideDown();
			}
			
		})
	;

	$('#sidebar .sidebar_actions_list .sidebar_ajax_like').live('click', function()
	{
		var id = $(this).attr('id').substring(10);
		var $next_a = $(this).siblings('a');
		$(this).remove();
		var li = $next_a.parents('li').html();
		//$('.sidebar_actions_list.no_ajax').removeClass('no_ajax');
		
//		overlay.show();
		$.get((LOGGED_CLASS ? '/actions/group_like/' : '/actions/like/') + id + '/?hide_loader', function(data)
		{
			if(data)
			{
				$next_a.fadeOut();
				$.get('/home/empty_f/?sidebar_actions=1', function(result)
				{
					$('.sidebar_actions_list ul').html(result);
				});
				$('.sidebar_actions_list_arrow, .sidebar_my_actions_list, .sidebar_actions_no_button').show();
				$('#empty_tracker_li').remove();
				$('<li>' + li + '</li>').prependTo($('.sidebar_my_actions_list ul')).hide().fadeIn();
				if($('.sidebar_my_actions_list ul').children().length == 1)
				{
					$('.sidebar_actions_list_arrow, .sidebar_my_actions_list, .sidebar_actions_button').show();
					$('.sidebar_my_actions_list, .sidebar_actions_list').removeClass('no_ajax');
					$('.sidebar_my_actions_list .see_all').hide();
				}
				if($('.sidebar_my_actions_list ul').children().length > 5)
				{
					$('.sidebar_my_actions_list ul li:last-child').remove();
					$('.sidebar_my_actions_list .see_all').css({'display': 'block'});
				}
				var $tracking_total = $('.sidebar_start_tracking #tracking_total');
				if($tracking_total.length>0)
				{
					var all_done = parseInt($tracking_total.html())>0 ? parseInt($tracking_total.html()) + 1 : 1;
					$tracking_total.html(all_done);
					if (all_done == 2){ $('.sidebar_start_tracking #tracking_multiple').html('s'); }
				}
				$('.sidebar_start_tracking').show();
				
				var $header_update_all = $('#id_header_all_track');
				if($header_update_all.length>0)
				{
					var header_all_done = parseInt($header_update_all.html()) + 1;
					$header_update_all.html(header_all_done);
					if (header_all_done == 2){ $('#id_header_all_track_multiple').html('s'); }
					header_pulsate($header_update_all);
				}
				
				if($('#header_actions').children('li').length == 6){ $('#header_actions').children('li:last').fadeOut().remove(); }
				$('<li>'
				+	'<a href="' + $next_a.attr('href') +'" title="' + $next_a.text() +'">'
				+ 		'<img src="/public/files/actions/' + $next_a.attr('rel') + '/50x50/' + id + '.' + $next_a.attr('rev') + '" />'
				+	'</a>'
				+'</li>').prependTo($('#header_actions')).hide().fadeIn();
				
				header_bounce();
			}
		});
		
		return false;
	});
	
	$('#sidebar .sidebar_my_actions_list .sidebar_ajax_like').live('click', function(){ return true; });
	
	
	
	// *********************************
	// SEARCH AND FILTERS
	// *********************************
	var current_location_hash;
	function location_hash_change(hash)
	{
		location.hash = hash;
		current_location_hash = location.hash;
	}
	
	function do_submit(element)
	{
		var $element = $(element);
		var $parent = $element.parents('.tab-container.selected');
		// for campaign builder items listing
		if(!$parent.length){ $parent = $element.parents('.no_hash'); }
		if(!$parent.length && $element.hasClass('category_chooser_search'))
		{ 
			$parent = $('#actions_chooser').find('.no_hash');
			if($parent.length){ $parent.find('.item_search').val($element.val()); }
			
		}
		// for listings without tabs
		if(!$parent.length){ $parent = $element.parents('.box_inn'); }
		
		var href = '?';
		var post_href = '';
		var paging = '';
		var filter = '';
		var cat = '';
		if($element.is('a') && $element.hasClass('.items_manipulation'))
		{
			href = $element.attr('href');
			
			var $page = $parent.find('.paging li.selected a');
			if($page.length)
			{
				var page_match = $page.attr('href').match(/^\??(?:page(\w*)=(.*))?/);
				paging = '&page'+page_match[1]+'='+page_match[2];
			}
			
			var $filter = $parent.find('.items-filter a.selected');
			if($filter.length)
			{
				var filter_match = $filter.attr('href').match(/^\??(?:order(\w*)=(.*))?/);
				if($filter.is('.dsc')){ post_href='-'; }
				filter = '&order'+filter_match[1]+'='+filter_match[2]+post_href;
			}
			
			var cat_search = $element.parents('.no_hash').find('.item_search').val();
			if(cat_search && (escape(cat_search) == escape('Search our Actions') || escape(cat_search) == escape('Search')))
			{
				var $cat = $("#our_big_change_div input[type='radio']:checked");
				if($cat.length)
				{
					cat = '&cat_idA='+$cat.val();
				}
			}
			
		}
		else if($element.is('a'))
		{
			$element.addClass('selected').siblings('a').removeClass('asc').removeClass('dsc').removeClass('selected');
			if		($element.is('.asc'))	{ $element.removeClass('asc').addClass('dsc'); post_href = '-'; 	}
			else if	($element.is('.dsc'))	{ $element.addClass('asc').removeClass('dsc');						}
			else 							{ $element.addClass('asc'); 										}
			
			href = $element.attr('href')+post_href;
		}
		/*
		else
		{
			var $selected = $parent.find('.items-filter a.selected');
			if($selected.is('.dsc'))	{ post_href = '-'; 	}

			href = $selected.attr('href');//+post_href+'&';
		}
		*/

		var id = $parent.find('.items-cnt').addClass('loading').attr('id');
		var letter = '';
		if(id)
		{ 
			letter = id.substr(9);
			$('#categories_type'+letter+' li').removeClass('selected'); 
		}
		var ys_search = '';
		var $ys = $parent.find('.search_young_speakers');
		if($ys.attr('checked')){ ys_search = '&'+$ys.attr('name')+'=1'; }
		
		var $search = $parent.find('.item_search');
		var search = '';
		if($search.length)
		{
			if(!escape($search.val()).match(/^Search/)){ search = '&'+$search.attr('name')+'='+escape($search.val()); }
		}
		
		$element.siblings('a').removeClass('asc').removeClass('dsc');
		
		
		var m = (href+search).match(/^\??(?:order(\w*)=(.*))?(?:&.*_search(\w*)=(.*))?/);
				
		if(m && !$element.parents('#act'+letter).hasClass("no_hash") && !$element.parents('#category_chooser').hasClass("no_hash"))
		{ 
			var tab = m[1] || m[3]; 
			location_hash_change( (tab ? 'tab='+tab+'&' : '') + (m[2] ? 'order='+m[2] : '') + (m[2] && m[4] ? '&' : '') + (m[4] ? 'search='+m[4] : '') ); 
		}
		
		$.get(href+'&hide_loader'+ys_search+search+paging+filter+cat+'#'+id, itemSearchCallback);
	}
	
	// Item search
	var item_search_val = $('.item_search')
		.focus(function(){ if(this.value==item_search_val){ this.value=''; } })
		.blur(function(){ if(!this.value){ this.value=item_search_val; } })
		.keydown(function(e)
		{
			if(e.keyCode == 13) // On Enter key
			{ 
				$(this).parents('form').submit(function(){return false;});
				var $element = $(this);
				if($(this).hasClass('category_chooser_search'))
				{
					$element = $('#actions_chooser .item_search');
					$element.val($(this).val());
				}
				do_submit($element);
				if($(this).hasClass('category_chooser_search'))
				{
					$('#category_chooser').hide();
					$('#actions_chooser').show();
				}
				
				var $cat = $("#our_big_change_div input[type='radio']:checked");
				if($cat.length){ $cat.attr('checked', ''); }
			}
		})
		.val()
	;
	
	$('#id_go_search').live('click', function()
	{
		var $search = $(this).parent().find('.item_search');
		search_val = $search.val();
		$(this).parents('form').submit(function(){return false;});
		var $element = $('#actions_chooser .item_search');
		$element.val(search_val);
		do_submit($element);
		if($search.hasClass('category_chooser_search'))
		{
			$('#category_chooser').hide();
			$('#actions_chooser').show();
		}
		
		var $cat = $("#our_big_change_div input[type='radio']:checked");
		if($cat.length){ $cat.attr('checked', ''); }
		
		return false;
	});
	
	$('.search_young_speakers').live('click', function(){ do_submit($('.item_search')); });
	
	var itemSearchCallback = function(responce)
	{
		var id = this.url.substr(this.url.indexOf('#'));
		$(id).replaceWith($(responce).find(id).find('.paging a').click(itemSearchPagingClick).end());
	}
	var itemSearchPagingClick = function()
	{
		var id = $(this).parents('.items-cnt').addClass('loading').attr('id');
		var letter = id.substring(9);
		var cat = '';
		if($('#categories_type'+letter+' li.selected').length > 0)
		{
			var vars = $('.categories li.selected a').attr('href').split('/');
			cat = '&cat_id'+letter+'='+vars[3];
		}
		if(!cat.length)
		{
			var $cat = $("#our_big_change_div input[type='radio']:checked");
			if($cat.length)
			{
				cat = '&cat_idA='+$cat.val();
			}
		}
		
		var href = $(this).attr('href');
		var hash = location.hash.substr(1).replace(/page=\d+|tab=\w+/g, '').replace(/&&/g, '&').replace(/^&/, '');
		
		var m = href.match(/page(\w*)=(\d*)/), m_tab = m[1], m_page = m[2];

		if(!$(this).parents('#act'+letter).hasClass("no_hash"))
		{
			location_hash_change((m_tab ? 'tab='+m_tab+'&' : '')+'page='+m_page+(hash?'&':'')+hash);
		}
		
		$.get(href.replace('&hide_loader', '').replace(/&cat_id[A-Z]=\d+/g, '')+cat+'&hide_loader'+'#'+id, itemSearchCallback);
		
		return false;
	} 
	
	$('.items-cnt .paging a').click(itemSearchPagingClick);
	
	// Jump to Page
	$('.page-jump input').live('keypress', function(e){ if(e.keyCode == 13){ $(this).next().click(); return false; } });
	$('.page-jump a').live('click', function()
	{
		var val = $('.page-jump input').val();
		$('.items-cnt .paging a').each(function()
		{
			var str = jQuery.trim($(this).html());
			if(parseInt(str) == parseInt(val)){ $(this).click(); return false; }
		});
		return false; 
	});
	
	$('.items-filter a').click(function()
	{
		var $cat = $("#our_big_change_div input[type='radio']:checked");
		if($cat.length){ $cat.attr('checked', ''); }
		
		do_submit($(this));

		return false;
	});
	
	switchCategory = function(_this)
	{
		$(_this).parents('li').addClass('selected').siblings().removeClass('selected');
		
		var id = $('.tab-container.selected .items-cnt').addClass('loading').attr('id');
		var href = $(_this).attr('href');
		var cat_id = href.match(/cat(\w+)\/(\d+)/)[2];

		$.get(href+'?hide_loader'+'#'+id, itemSearchCallback);

		return href;
	}
	$('.categories li a').click(function()
	{
		var href = switchCategory(this);
		var m = href.match(/cat(\w+)\/(\d+)/);
		var letter = m[1];
		var cat_id = m[2];
		if(!$(this).parents('#act'+letter).hasClass("no_hash"))
		{
			location_hash_change('tab='+letter+'&cat='+cat_id);
		}
		
		if($('#special_page_flip_category_div').length && letter=='A')
		{
			$('#special_page_flip_category_div').load('/page_flip/?cat_id='+cat_id+'&hide_loader');
		}
		
		return false;
	});
	
	switchTab = function(_this)
	{
		$('.tab-titles .selected a').data('hash', location.hash.replace(/tab=\w+/, '').substr(1));
		var tab_id = $(_this).parents('li').addClass('selected').siblings().removeClass('selected').end().end().attr('href').replace('/products/','');
		$(tab_id).addClass('selected').siblings().removeClass('selected');
		$('#categories_type' + tab_id.substr(4)).show().siblings().hide();
		
		return tab_id;
	}
	
	$('.tab-titles a').data('hash', '').click(function()
	{ 
		if($(this).attr('href').indexOf('/products/') > -1 && location.href.indexOf('/products/') == -1)
		{
			$(this).attr('href',$(this).attr('href').replace(/#act/, '#tab='));
			return; 
		}
		tab_id = switchTab(this);
		var letter = tab_id.substr(4);
		if(!$(this).parents('#act'+letter).hasClass("no_hash"))
		{
			location_hash_change('tab='+ letter + $(this).data('hash'));
		}
		
		if($('#special_page_flip_category_div').length)
		{
			if(letter=='B')
			{
				$('#special_page_flip_category_div').html('<img src="/public/styles/images/suggested_banner.jpg" />');
			}
			else if(letter=='A')
			{
				var cat = current_location_hash.match(/cat=(\d+)/); if(cat){ cat = cat[1]; }
				$('#special_page_flip_category_div').load('/page_flip/?cat_id='+cat+'&hide_loader');
			}
		}
		
		return false; 
	});
	
	setInterval(function()
	{
		if(location.hash.length == 0 || current_location_hash == location.hash){ return; }
		current_location_hash = location.hash;
		
		var tab = location.hash.match(/tab=(\w+)/);
		if(tab){ tab = tab[1]; switchTab('.tab-titles a[href$=#act'+tab+']'); }
		else { tab = ''; }

		var page = location.hash.match(/page=(\d+)/);
		
		var cat = location.hash.match(/cat=(\d+)/); 			if(cat)		{ cat = cat[1]; }
		var search = location.hash.match(/search=(.+)/); 		if(search)	{ search = search[1]; }
		var order = location.hash.match(/order=([\w-]+)?/); 	if(order)	{ order = order[1]; }
		
		if(page)
		{
			page = page[1];
			$( (tab ? '#act'+tab : '') + ' .items-filter').parent().children('.items-cnt').addClass('loading');
			
			$('#categories_type'+tab+' li:has(a[href$=/'+cat+'/])').addClass('selected').siblings().removeClass('selected');
			$.get(
				(cat ? 'cat'+tab+'/'+cat+'/' : '')
				+'?page'+tab+'='+page
				+(search ? '&action_search'+tab+'='+search : '')
				+(order ? '&order'+tab+'='+order : '')
				+'&hide_loader#items_cnt'+tab
			, itemSearchCallback);
			
		}
		else if(cat)
		{ 
			switchCategory('#categories_type'+tab+' a[href$=/'+cat+'/]'); 
		}
		else if(search || order)
		{
			var $el = $((tab ? '#act'+tab : '') + ' .item_search');
			if(search)
			{
				$el.val(unescape(search));
			}
			
			if(order)
			{
				order_way = order.substr(-1) == '-' ? 1 : 0;
				order_name = order_way ? order.substr(0, order.length -1) : order; 
				
				$el = $( (tab ? '#act'+tab : '') + ' .items-filter a[href=?order'+tab+'='+order_name+']' );
				$el.addClass('selected').addClass( order_way ? 'asc' : 'dsc' )
					.siblings('a').removeClass('asc').removeClass('dsc').removeClass('selected')
				;
			}
			
			do_submit( $el );
		}
		
		if($('#special_page_flip_category_div').length)
		{
			if(tab=='B')
			{
				$('#special_page_flip_category_div').html('<img src="/public/styles/images/suggested_banner.jpg" />');
			}
			else if(tab=='A')
			{
				$('#special_page_flip_category_div').load('/page_flip/?cat_id='+cat+'&hide_loader');
			}
		}
		
	}, 100);
	
	$('#see_in_popup').dialog(
	{
		autoOpen		: false,
		bgiframe		: false,
		width			: 600,
//				height			: 600,
		modal			: true,
		closeOnEscape	: true,
		draggable		: false,
		resizable		: false,
		
		buttons:		{	
			'Close' 			: function(){ $(this).dialog('close'); }
		}
	});
	
	$('.see_in_popup').live('click' ,function()
	{
		var url = $(this).attr('href');
		$.get(url, {}, function(result)
		{
			if(result.id)
			{
				if(result.image){ $('#see_in_popup_image').html('<img src="' + result.image + '" />'); }
				$('#ui-dialog-title-see_in_popup').html('See ' + result.title);
				$('#see_in_popup_title').html(result.title);
				$('#see_in_popup_description').html(result.description);
				if(result.stats_facts){ $('#see_in_popup_stats_facts').html(result.stats_facts); }
				$('#see_in_popup').dialog('open');
				$('.media').media();
			}
		}, 'json');
		return false;
	});
	
	$('.items_ul li a').live('click' ,function()
	{
		var url = $(this).attr('href');
		var item = $(this).attr('rel');
		var items_count = $(this).attr('rev');
		var $element = $('#items_manipulation');

		if(!$(this).hasClass('see_in_popup') && !$(this).hasClass('delete_item'))
		{
			$.get(url+'&hide_loader', function(result)
			{
				if(result)
				{
//					$.get(url.replace(/\?.*/,'?refreshU=1')+'&hide_loader'+'#items_cntU', itemSearchCallback);
					do_submit($element);
					$('#' + items_count + '_header').show();
					$('#sidebar_' + item).slideDown();
					$('#' + items_count).text(parseInt($('#' + items_count).text())+1);
				}
			});
		}
		
//		else if($(this).hasClass('delete_item'))
//		{
//			$('#delete_item_confirm').dialog('option', 'buttons' 
//				,{	
//					'Yes Please' : function()
//					{ 
//						$(this).dialog('close');
//						$.get(url+'&hide_loader', function(result)
//						{
//							if(result)
//							{
//								$.get(url.replace(/\?.*/,'?refreshU=1')+'&hide_loader'+'#items_cntU', itemSearchCallback);
//								do_submit($element);
//								$('#sidebar_' + item).slideUp();
//								$('#' + items_count).text(parseInt($('#' + items_count).text())-1);
//							}
//						});
//					},
//					'No Thanks' : function(){ $(this).dialog('close'); }
//				} 
//			);
//			$('#delete_item_confirm').dialog('open');
//		}
		
		return false;
	});
	
	$('#cmpgn-list-actions .delete_item, #cmpgn-list-stuff .delete_item').live('click', function()
	{
		var url = $(this).attr('href');
		var item = $(this).attr('rel');
		var items_count = $(this).attr('rev');
		var $element = $('#items_manipulation');
		
		$('#delete_item_confirm').dialog('option', 'buttons', 
			{	
				'Yes Please' : function()
				{ 
					$(this).dialog('close');
					$.get(url+'&hide_loader', function(result)
					{
						if(result)
						{
							if($element.length && item.match(new RegExp( $element.attr('rel') ))){ do_submit($element); }
							$('#sidebar_' + item).slideUp();
							$('#' + items_count).text(parseInt($('#' + items_count).text())-1);
						}
					});
				},
				'No Thanks' : function(){ $(this).dialog('close'); }
			} 
		).dialog('open');
	
		return false;
	});
	
	$("#category_chooser #id_category_id li").live('click' ,function()
	{
		var val = $(this).find("input[type='radio']").val();
		var cat_title = $(this).find('label').text();
		$(this).find("input[type='radio']").attr('checked', 'checked');
		$('#actions_chooser').find('.items-cnt').addClass('loading');
		$('.item_search').val(__globals['TEXTS']['S']['search']);

		$.get(location.pathname+'?cat_idA='+val+'&hide_loader#items_cntA', itemSearchCallback);
		
		$('#category_chooser').hide();
		$('#actions_chooser').show();
		
		if(!$('#my_big_change_div #id_description').val())
		{
			$('#theme_aim').show();
			$('#theme_aim #cmpgn-list-aim li a').text(cat_title);
		}
		
		var params = {};
		params['theme_category_id'] = val;
		$.post(location.pathname + '?hide_loader', params);
				
		return false;
	});
	
	$('#category_chooser #see_all_categories').live('click', function()
	{
		var $cat = $("#our_big_change_div input[type='radio']:checked");
		if($cat.length){ $cat.attr('checked', ''); }
		$('#actions_chooser').find('.items-cnt').addClass('loading');
		$.get(location.pathname+'?refreshA=1&hide_loader#items_cntA', itemSearchCallback);
		$('#category_chooser').hide();
		$('#actions_chooser').show();
		return false;
	});
	
	//	Action search tags autocomplete
	
	$('.action_tags').autocomplete(
	{ 
	    queryName: 'action_tag_autocompleter', //aditional parameters
	    minChars: 3, 
	    maxHeight: 300,
	    width: 250,
	    deferRequestBy: 0, //miliseconds
	    
	    onSelect: function(value, data)
	    {
			item_search_val = value;
			var $el = $('.tab-container.selected').find('.item_search.action_tags');
			if(!$el.length){ $el = $('.actions-list').find('.item_search.action_tags');}
			if($el){ do_submit($el); }
	    }
	});
	
	// SEARCH AND FILTERS
	
	
	$('.media').media();
	
	$('#go_to_featured_tab').live('click', function(){ $('#featured_tab').click(); return false; });
	
	
	$('.overlay').click(function()
	{
		var $dialog = $('#overlay-dialog');
		if(!$dialog.length)
		{
			$dialog = $('<div id="overlay-dialog"></div>').appendTo('body').hide();
			$dialog.dialog(
			{
				width			: 465,
				height			: 431,
				modal			: true,
				draggable		: false,
				resizable		: false
			});
		}
		
		var $this = $(this);
		var href = $this.attr('href');
		
		$dialog.dialog('option', 'title', $this.text()).html('<span class="loader"></span>').dialog('open');
		$.getJSON('/oohembed/?url='+href.replace(/&/g, '%26'), function(json)
		{
			var html = (json.responce.html || '') +	(json.responce.url ? '<img src="'+json.responce.url+'" />' : '');
			
			if(!html)
			{
				html = '<iframe src="'+href+'" width="100%" height="100%"></iframe>';
			}
			else
			{
				html = '<div class="inner">'+html+'</div>';
			}
			
			$dialog.html(html)
		});
		
		return false;
	});
	
	$('.log_me_anywhere_with_this_session').click(function()
	{
		var _target		= $(this).attr('target');
		var _href		= $(this).attr('href') + '?session=' + session_id;
		if(_target){ window.open(_href, _target); }
		else { location.href = _href; }
		
		return false;
	});
	
	$('#id_under_14').click(function()
	{
		$(this).is(':checked') ? $(".birthdate").slideDown() : $(".birthdate").slideUp();
	});
	
	$('.dialog_comment_alert').dialog(
	{
		autoOpen		: false,
		bgiframe		: false,
		width			: 500,
		// height			: 500,
		modal			: true,
		closeOnEscape	: true,
		draggable		: false,
		resizable		: false,
		buttons:		{	
			'Ok'	 	: function(){ $(this).dialog('close'); }
		}
	});

	$('.dialog_action_alert').dialog(
	{
		autoOpen		: false,
		bgiframe		: false,
		width			: 500,
		// height			: 500,
		modal			: true,
		closeOnEscape	: true,
		draggable		: false,
		resizable		: false,
		buttons:		{	
			'Ok'	 	: function(){ $(this).dialog('close'); location.href=location.protocol+'//'+location.hostname+'/actions/'; }
		}
	});
	
	
	$('#flash_overlay .close, #flash_overlay .close_button').click(function(){ $('#flash_overlay').hide(); });
	$('.flash').click(function(){ $('#flash_overlay').show(); });
	
	$('#switch_class_dialog').dialog(
	{
		autoOpen		: false,
		bgiframe		: false,
		width			: 300,
		// height			: 500,
		modal			: true,
		closeOnEscape	: true,
		draggable		: false,
		resizable		: false,
		buttons:		{
			'Switch'	: function(){ $('#switch_class_dialog form').submit(); },
			'Close' 	: function(){ $(this).dialog('close'); }
		}
	});
	
	$('#switch_class').click(function()
	{
		$('#switch_class_dialog').dialog('open');
		
		return false;
	});
	
	$('#action_alert').dialog(
	{
		autoOpen		: false,
		bgiframe		: false,
		width			: 550,
		// height			: 500,
		modal			: true,
		closeOnEscape	: true,
		draggable		: false,
		resizable		: false,
		buttons			:
		{	
			'Yes Please' 			: function(){ $(this).dialog('close');/*$(this).dialog('option', 'buttons', {}); location.href = '/actions/view/' + global_id + '/?open_comment=1'; */},
			'No Thanks' 			: function(){ $(this).dialog('close'); }
		}
	});
	
	$('.single-click').click(function(){ $(this).unbind('click').click(function(){ return false; }); });
	
	$('#nav > li').hover(function(){
		$(this).addClass('hover'); 
	}, function()
	{
		$(this).removeClass('hover');
	});
	
	$('#step_what .radio-list ul li label').click(function(){

		$(this).parent().siblings().removeClass('active').end().addClass('active');

	});
	
	$('#delete_item_confirm').dialog(
	{
		autoOpen		: false,
		bgiframe		: false,
		width			: 550,
		// height			: 500,
		modal			: true,
		closeOnEscape	: true,
		draggable		: false,
		resizable		: false
	});
	
	$('.avatar.list label').click(function(){

		$(this).parent().addClass("active").siblings().removeClass("active");
		var avatar_id = $(this).find('img').attr('src').substr(28, 6);
		$('.page-wide .col.preview > a > img').attr("src", "/public/files/avatars/200x200/" + avatar_id)
	});
	
});
