var root = '/';

if (top.location != location && typeof is_sidebar == 'undefined')
    top.location.href = document.location.href ;

$(document).ready(function(){
	/*
		GENERAL FUNCTIONS
	*/	
	shorten = function(string, max)
	{
		if(string.length > max)
			return string.substr(0, max)+'...';
		else
			return string;
	}
	
	// load the register page
	$('.osx').click(function()
	{
		$('#osx-modal-data').load(root + 'a/users/register', function() {
			$('#UserRegisterForm').bind('submit', function(event) { onRegisterSubmit(event, $(this).serialize()); });
		});
		
	});
	
	// submit register page
	onRegisterSubmit = function(event, form_data)
	{
		event.preventDefault();
		
		$.post(root + 'a/users/register',
			form_data,
			function(data) {
				$('#osx-modal-data').html(data);
				$('#UserRegisterForm').bind('submit', function(event) { onRegisterSubmit(event, $(this).serialize()); });
			});
	}
	
	$('.sidebar_close').click(function()
	{
		$('#sidebar_container').remove();
	});
	
	/*
		RESULTS FUNCTIONS
	*/
	// loads and displays the given array of slugs
	loadResults = function(slugs)
	{
		$.post(root + 'a/links/getData',
		  { 'data[Link][Slugs]' : slugs },
		  function (data) {
			$('#resultsBox').html('');
			var output;
			output = '<div class="results_top">'+data.clicks+' Clicks this week</div>';
			output += '<div class="results_thead"><div class="results_head results1 text-left">Clicks</div><div class="results_head results2 text-left">Links</div><div class="results_head results3 text-center">Analytics</div><div class="results_head results4 text-center">Date</div><div class="results_head results5 text-center">Options</div><div class="clear"></div></div><div id="resultsRows">';
			
			if(data['links'] == null)
				output += '<div class="results_none">No shortened links at this time.</div>';
			
			for(var key in data['links'])
			{
				link = data['links'][key];
				output += '<div class="results_trow" id="result_'+link['slug']+'"><div class="results_row results1"><div class="clicks"><span class="local">'+link['clicks_local']+'</span><br /><span class="global">'+link.clicks_global+'</span></div></div><div class="results_row results2"><img src="'+root+'favicon/'+link['slug']+'" alt="" /><div class="link_info"><div class="valign"><input type="hidden" name="full_title" value="'+link.full_title+'" /><a class="main_link" href="'+root+link['slug']+'" name="link_title">'+link.title+'</a><br /><a class="long_link" href="'+link.full_url+'">'+link.display_url+'</a></div></div></div><div class="results_row results3"><div class="valign"><a href="'+root+link['slug']+'+"><div class="blue button">Analyze+</div></a></div></div><div class="results_row results4 results_row_line_height text-center bold">'+link.created+'</div><div class="results_row results5 results_row_line_height text-center results_options"><a class="clickable big bold" name="edit_link_title">Open Options</a></div><div class="clear"></div></div>';

			}
			output += '</div>'
			$('#resultsBox').append(output);
			$('.results_trow').hide().slideDown('slow');
			$("a[name='edit_link_title']").bind('click', editTitle);
			
		  },
		  'json');
	}
	
	// remove the given slug
	removeResult = function(slug)
	{
		$("#result_" + slug).remove();
	}
	
	// prepends the given slugs
	addResults = function(slugs)
	{
		$.post(root + 'a/links/getData',
		  { 'data[Link][Slugs]' : slugs },
		  function (data) {
			// remove notice about not having any links yet
			$('#resultsRows').children('.results_none').remove();

			var output = '';
			
			for(var key in data['links'])
			{
				link = data['links'][key];
				output += '<div class="results_trow" id="result_'+link['slug']+'"><div class="results_row results1"><div class="clicks"><span class="local">'+link['clicks_local']+'</span><br /><span class="global">'+link.clicks_global+'</span></div></div><div class="results_row results2"><img src="'+root+'favicon/'+link['slug']+'" alt="" /><div class="valign"><input type="hidden" name="full_title" value="'+link.full_title+'" /><a class="main_link" href="'+root+link['slug']+'" name="link_title">'+link.title+'</a><br /><a class="long_link" href="'+link.full_url+'">'+link.display_url+'</a></div></div><div class="results_row results3"><div class="valign"><a href="'+root+link['slug']+'+"><div class="blue button">Analyze+</div></a></div></div><div class="results_row results4 results_row_line_height text-center bold">'+link.created+'</div><div class="results_row results5 results_row_line_height text-center results_options"><a class="clickable big bold" name="edit_link_title">Open Options</a></div><div class="clear"></div></div>';
				$('#resultsRows').prepend(output);
				$('.results_trow:first').hide().slideDown('slow');
				$("a[name='edit_link_title']").bind('click', editTitle);
			}


			
		  },
		  'json');
	}
	
	/*
		SHORTEN & CUSTOMIZING FUNCTIONS
	*/
	
	// click shorten event
	$('#shorten_links_btn').click(function()
	{
		checkLinks();
	});
	
	// click "Click to Copy"
	copyLink = function(event)
	{
		$(this).parent().children('.url').children('input').select();
	}
	
	// show the editing box... to customize the url
	showEdit = function(button)
	{
		// convert this area to the customize box
		$(button).parent().children('.copy').children('.url').children("input[name='url']").removeAttr('readonly');
		
		$(button).parent().children('.copy').children('.url').children("input[name='url']").css('margin-left', '0px');
		$(button).parent().children('.copy').children('.url').children("input[name='url']").width(90);
		$(button).parent().children('.copy').children('.url').children("input[name='url']").val($(button).parent().children('.copy').children('.url').children("input[name='slug']").val());
		$(button).parent().children('.copy').children('.url').children("input[name='tadly']").show();
		$(button).parent().children('.copy').children('.url').children("input[name='url']").focus();
		
		$(button).parent().children('.copy').children('.inner').removeClass('clickable').removeClass('white').addClass('orange').html('Edit Link');
		$(button).parent().children('.copy').removeClass('copy').addClass('edit');
		$(button).removeClass('blue').addClass('orange');
		$(button).html('Save Edit');
		$(button).parent().children(':input').removeAttr('disabled');

	}
	
	showCopy = function(data, button, old_slug)
	{
		if(data['success'] == 1)
		{
			// change hidden old_slug to new slug
			$(button).parent().children('.edit').children('.url').children("input[name='slug']").val(data['Link']['slug']);
			
			$(button).parent().children('.edit').children('.url').children("input[name='tadly']").hide();
			$(button).parent().children('.edit').children('.url').children("input[name='url']").css('margin-left', '10px');
			$(button).parent().children('.edit').children('.url').children("input[name='url']").width(180);
			
			var new_url = 'http://tad.ly/' + $(button).parent().children('.edit').children('.url').children("input[name='url']").val();
			$(button).parent().children('.edit').children('.url').children("input[name='url']").val(new_url);
			
			// convert this area to the copy box
			$(button).parent().children('.edit').children('.url').children("input[name='url']").attr('readonly', true);
			$(button).parent().children('.edit').children('.inner').removeClass('orange').addClass('clickable').addClass('white').html('Click to Copy');
			$(button).parent().children('.edit').removeClass('edit').addClass('copy');
			$(button).removeClass('orange').addClass('blue');
			$(button).html('Customize');

			// remove old result below
			removeResult(old_slug);
			addResults(new Array(data['Link']['slug']));
			
			// change stats link
			if($('#sidebar_container').length == 0)
			{
				$(button).parent().parent().children("div[name='customize_links']").children('.left').children("a[name='real_time']").html(shorten('http://tad.ly/' + data['Link']['slug'] + '+', 25)).removeAttr('href').attr('href', 'http://tad.ly/' + data['Link']['slug'] + '+');
			}else{
				$(button).parent().children("div[name='customize_links']").children('.left').children("a[name='real_time']").html(shorten('http://tad.ly/' + data['Link']['slug'] + '+', 25)).removeAttr('href').attr('href', 'http://tad.ly/' + data['Link']['slug'] + '+');
			}
			
			
		}else{
			// show the error in the input box
			// then revert it to the old slug
			$(button).parent().children('.edit').children('.url').children("input[name='tadly']").hide();
			$(button).parent().children('.edit').children('.url').children("input[name='url']").css('margin-left', '10px');
			$(button).parent().children('.edit').children('.url').children("input[name='url']").width(180);
			$(button).parent().children('.edit').children('.url').children("input[name='url']").attr('readonly', true);
			$(button).parent().children('.edit').children('.url').children("input[name='url']").hide().val(data['error']).fadeIn('slow').delay(2000).fadeOut('slow', 
				function() {  
					$(this).val(old_slug).show();
					$(button).parent().children('.edit').children('.url').children("input[name='url']").removeAttr('readonly');
					$(button).parent().children('.edit').children('.url').children("input[name='url']").css('margin-left', '0px');
					$(button).parent().children('.edit').children('.url').children("input[name='url']").width(90);
					$(button).parent().children('.edit').children('.url').children("input[name='tadly']").show();
				});

		}
	}
	
	// clicking either save edit or customize
	saveCustomize = function()
	{
		if($(this).html() == 'Customize')
		{
			showEdit($(this));
		}else{
			// attempt to save customization
			var new_slug = $(this).parent().children('.edit').children('.url').children("input[name='url']").val();
			var old_slug = $(this).parent().children('.edit').children('.url').children("input[name='slug']").val();
			
			if(new_slug == old_slug)
			{
				// convert this area to the copy box
				$(this).parent().children('.edit').children('.url').children("input[name='url']").attr('readonly', true);
				$(this).parent().children('.edit').children('.inner').removeClass('orange').addClass('clickable').addClass('white').html('Click to Copy');
				
				$(this).parent().children('.edit').children('.url').children("input[name='tadly']").hide();
				$(this).parent().children('.edit').children('.url').children("input[name='url']").css('margin-left', '10px');
				$(this).parent().children('.edit').children('.url').children("input[name='url']").width(180);
				
				var new_url = 'http://tad.ly/' + $(this).parent().children('.edit').children('.url').children("input[name='url']").val();
				$(this).parent().children('.edit').children('.url').children("input[name='url']").val(new_url);
				
				$(this).parent().children('.edit').removeClass('edit').addClass('copy');
				$(this).removeClass('orange').addClass('blue');
				$(this).html('Customize');
				return;
			}
			
			var button = $(this);
			
			$.post(root + 'a/links/customize',
			  { 'data[Link][new_slug]' : new_slug, 'data[Link][old_slug]' : old_slug },
			  function (data) {
				showCopy(data, button, old_slug);
			  }, 'json');
		}
	}
	
	// attempt to shorten given link(s)
	checkLinks = function()
	{
		$('#shorten_links_working').show();
		// our basic regex eval to prevent uneccesarry ajax calls
		var lines = $('#shorten_links').val().split('\n');
		var repack = '';
		var i = 0;
		for(var line in lines)
		{
			if(lines[line].substr(0, 13) != 'http://tad.ly') {
				// post to shortener
				$.post(root + 'a/links/shorten',
				  { 'data[Link][url]' : lines[line], 'data[Link][line]' : line },
				  function (data) {
					
					// this will show the customize option
					if(data['success'] == 1)
					{
						i++;
						// show the link
						lines[data['line']] = 'http://tad.ly/' + data['Link']['slug'];
						$('#shorten_links').val(lines.join('\n'));
						

						if($('#sidebar_container').length == 0)
						{
							// show customization options
							if($('#new_link_welcome .homepage_new_link_container').length == 0)
								$('#new_link_welcome').html('');
								
							if($('#new_link_welcome .homepage_new_link_container').length == 3)
								$('#new_link_welcome .homepage_new_link_container:last').remove();
								
							var output = '<div class="homepage_new_link_container"><div class="bar"><div class="copy left"><div class="left url"><input name="slug" type="hidden" value="'+data['Link']['slug']+'" /><input name="tadly" type="text" value="http://tad.ly/" class="left hide" style="width:83px;" readonly="readonly" /><input name="url" value="http://tad.ly/'+data['Link']['slug']+'" readonly="true" /></div><div class="right inner clickable white">Click to Copy</div></div><div class="blue button_small left">Customize</div></div><div name="customize_links" class="pad-side white"><div class="left">Get real-time stats: <a class="white" name="real_time" href="http://tad.ly/'+data['Link']['slug']+'+">'+shorten('http://tad.ly/'+data['Link']['slug']+'+', 25)+'</a></div><div class="right">Long link: <a class="white" href="'+data['Link']['url']+'">'+shorten(data['Link']['url'], 25)+'</a></div></div></div><div class="clear"></div><br />';
							$('#new_link_welcome').prepend(output);

							
							// fade it...
							$('#new_link_welcome .homepage_new_link_container:first').hide().fadeIn('slow');
							
							// bind events
							$('.homepage_new_link_container .bar .button_small:first').bind('click', saveCustomize);
							$('.homepage_new_link_container .copy .clickable:first').bind('click', copyLink);
							
							// add it to our links list below
							addResults(new Array(data['Link']['slug']));

						}else{
							var output = '<div class="sidebar_new_link_container"><div class="bar"><div class="copy left"><div class="left url"><input name="slug" type="hidden" value="'+data['Link']['slug']+'" /><input name="tadly" type="text" value="http://tad.ly/" class="left hide" style="width:83px;" readonly="readonly" /><input name="url" value="http://tad.ly/'+data['Link']['slug']+'" readonly="true" /></div><div class="right inner clickable white">Click to Copy</div></div><div class="sidebar_space"></div><div class="right blue button_small">Customize</div><div name="customize_links" class="left sidebar_links"><div class="left">Stats: <a name="real_time" href="http://tad.ly/'+data['Link']['slug']+'+">'+shorten('http://tad.ly/'+data['Link']['slug']+'+', 25)+'</a></div></div></div><div class="clear"></div><br /></div>';
							
							
							$('#sidebar_new_link').prepend(output);

							
							// fade it...
							$('#sidebar_new_link .sidebar_new_link_container:first').hide().fadeIn('slow');
							
							// bind events
							$('.sidebar_new_link_container .bar .button_small:first').bind('click', saveCustomize);
							$('.sidebar_new_link_container .copy .clickable:first').bind('click', copyLink);
							
						}
						
						if(i == lines.length)
								$('#shorten_links_working').hide();
					}else{
						i++;
						if(i == lines.length)
							$('#shorten_links_working').hide();
					}
				  },
				  'json');
			}else{
				i++;
				if(i == lines.length)
					$('#shorten_links_working').hide();
			}

		}
	}
	
	/* OPTIONS STUFF */
	editTitle = function()
	{
		var node = $(this).parent().parent().children('.results_row').children('.link_info').children('.valign');
		var curTitle = node.children('input[name="full_title"]').val();
		var curID = $(this).parent().parent().attr('id');
		
		if(node.css('display') == 'none')
		{
			// we were showing the edit options
			// but now we remove them
			node.parent().children('div[name="edit_title_option"]').remove();
			node.show();
		}else{
			// we are not showing the edit options
			// create them
			node.hide();
			node.parent().append('<div class="valign" name="edit_title_option"><input class="edit_title_option" type="text" value="'+curTitle+'" /><br /><div class="edit_title_option_result"><a class="clickable">Save Title</a> <span class="red bold" name="edit_title_option_error" class="pad-side"></span></div></div>');
			$('.edit_title_option_result a').bind('click', saveTitle);
		}
	};
	
	saveTitle = function()
	{
		var curID = $(this).parent().parent().parent().parent().parent().attr('id');
		var newTitle = $(this).parent().parent().children('.edit_title_option').val();
		var node = $(this).parent().parent().parent().parent().parent().children('.results_row').children('.link_info').children('.valign');
		$.post(root + 'a/links/editTitle',
			  { 'data[Link][new_title]' : newTitle, 'data[Link][id]' : curID },
			  function(data) { saveTitleCallback(data, node); }, 'json');
	}
	
	saveTitleCallback = function(data, node)
	{
		// return to normal with new title
				// or show error
				if(data.success == 0)
				{
					node.parent().children('div[name="edit_title_option"]').children('.edit_title_option_result').children('span[name="edit_title_option_error"]').show().html(data.error).delay(2000).fadeOut();
					node.parent().children('div[name="edit_title_option"]').children('input').val(node.children('input[name="full_title"]').val());
				}else{
					node.children('input[name="full_title"]').val(data.new_title);
					node.children('a.main_link').html(data.new_title);
					node.parent().children('div[name="edit_title_option"]').remove();
					node.show();
				}
	}
	
	/* CHARTS STUFF */

	
	// tabs on info page - categories
	$('#info_tabs li').hover(function()
	{
		$('#info_tabs li').removeClass('on');
		$(this).addClass('on').removeClass('off');
	},
	function()
	{
		$('#info_tabs li').removeClass('on');
		$('#info_tabs .current').addClass('on').removeClass('off');
	});
	
	$('#info_tabs li').click(function()
	{
		$('#info_tabs li').removeClass('current');
		$(this).addClass('current');
		
		
		// change content
		$('#charts_content').children('div').hide();
		var tab = $(this).attr('rel');
		$('#' + $(this).attr('rel') + '_content').show();
		
		switch($(this).attr('rel'))
		{
			case 'referrers':
				$('#referrers_content').children('div').hide();
				$('#referrers_' + $(this).attr('rel')).show();
				reloadReferrers($('#info_tabs_dates .current').attr('rel'));
				break;
			case 'locations':
				$('#locations_tables').children('table').hide();
				$('#locations_table_' + $('#info_tabs_dates .current').attr('rel')).show();
				break;
		}
	});
	
	// tabs on info page - dates
	$('#info_tabs_dates .button_small').hover(function()
	{
		$('#info_tabs_dates .button_small').removeClass('orange');
		$(this).addClass('orange').removeClass('blue');
	},
	function()
	{
		$('#info_tabs_dates .button_small').removeClass('orange');
		$('#info_tabs_dates .current').addClass('orange').removeClass('blue');
	});
	
	$('#info_tabs_dates .button_small').click(function()
	{
		$('#info_tabs_dates .button_small').removeClass('current');
		$(this).addClass('current');
		
		if($('#link_stats').length != 0)
		{
			switch($('#info_tabs .current').attr('rel'))
			{
				case 'clicks':
					tmp = findSWF('clicks_chart');
					x = tmp.load( JSON.stringify(eval('data_clicks_' + $(this).attr('rel')) ));
					break;
				case 'referrers':
					$('#referrers_content').children('div').hide();
					$('#referrers_' + $(this).attr('rel')).show();
					reloadReferrers($(this).attr('rel'));
					break;
				case 'locations':
					$('#locations_tables').children('table').hide();
					$('#locations_table_' + $(this).attr('rel')).show();
					tmp = findSWF('locations_chart');
					x = tmp.load( JSON.stringify(eval('data_locations_' + $(this).attr('rel')) ));
					break;
			}
		}else{
			tmp = findSWF('clicks_chart');
			x = tmp.load( JSON.stringify(eval('data_clicks_' + $(this).attr('rel')) ));
					
			$('#locations_tables').children('table').hide();
			$('#locations_table_' + $(this).attr('rel')).show();
			tmp = findSWF('locations_chart');
			x = tmp.load( JSON.stringify(eval('data_locations_' + $(this).attr('rel')) ));
			
			$('#referrers_tables').children('table').hide();
			$('#referrers_table_' + $(this).attr('rel')).show();
			tmp = findSWF('referrers_chart');
			x = tmp.load( JSON.stringify(eval('data_referrers_' + $(this).attr('rel')) ));
		}
	});
	
	reloadCharts = function()
	{
		if($('#link_stats').length != 0)
		{
			if($('#info_tabs .current').attr('rel') == 'clicks')
			{
				tmp = findSWF('clicks_chart');
				tmp.load( JSON.stringify(eval('data_clicks_' + $('#info_tabs_dates .current').attr('rel'))));
			}else if($('#info_tabs .current').attr('rel') == 'locations'){
				tmp = findSWF('locations_chart');
				tmp.load( JSON.stringify(eval('data_locations_' + $('#info_tabs_dates .current').attr('rel'))));
			}
		}
	}
	
	reloadReferrers = function(period)
	{
		// already loaded
		if($('#referrers_' + period + ' table').length == 1)
			return;
			
		$.post(root + 'a/links/getReferrers',
		{ 'data[Referrer][period]' : period, 'data[Referrer][slug]' :  $('#current_slug').html()},
			function(data)
			{
				$('#referrers_' + period).html('');
				var output = '<table class="table referrers_table"><thead><tr><th>Referrer</th><th>Clicks</th></tr></thead>';

				if(data.length == 0) {
					output += '<tbody><tr><td colspan="2">No data.</td></tr></tbody>';
				}else{
					for(var key in data)
					{
						output += '<tbody><tr><td>'+data[key]['domain']+' <span class="clickable orange toggle_referrer" rel="pages_'+key+period+'">+</span></td><td>'+data[key]['total']+'</td></tr></tbody>';
						output += '<tbody class="hide" id="pages_'+key+period+'">';
							
						for(var key2 in data[key]['pages'])
						{
							if(data[key]['domain'] == 'Direct')
								data[key]['pages'][key2]['page'] = 'Direct includes instant messages or emails. Any hits not from a website.';
								
							output += '<tr><td class="sub_page">'+data[key]['pages'][key2]['page']+'</td><td>'+data[key]['pages'][key2]['total']+'</td></tr>';
						}
						output += '</tbody>';
					}
				}
				
				output += '</table>';
				
				$('#referrers_' + period).hide().append(output).show();
				$('.toggle_referrer').unbind();
				$('.toggle_referrer').bind('click', function() {
					$('#' + $(this).attr('rel')).toggle();
				});

			}
		, 'json');
		
	
	}

});


