var top50 = {
	
	init: function(){
		
		// Custom parser to handle commas when sorting
		$.tablesorter.addParser({ 
		 	id: 'commas', 
		  	is: function(s) { 
		    	return false; 
		       	}, 
		  	format: function(s) { 
		 		return s.replace(',','').replace(',',''); 
			}, 
		 	type: 'numeric' 
		});
		
		$('#category_table').tablesorter({ 
            headers: { 
                2: { 
                    sorter:'commas' 
                },
				3: { 
                    sorter:'commas' 
                },
				4: { 
                    sorter:'commas' 
                },
				5: { 
                    sorter:false 
                }
            },
			sortList:[[0,0],[4,1]],
			widgets: ['zebra']
        });
		
		top50.currentPage();
		top50.showChildren();
		top50.collapseTable();
		top50.dropDown();
		
		tooltip.tip('td.fans a, td.followers a');
		
		if($('.search-results').length <= 0){
			top50.goldStar();
			//top50.under50();
		}
	},
	
	currentPage: function(){
		var loc = window.location.href;
		loc = loc.split('/');

		if(loc[3] != ''){
			$('#category-selector select').val(loc[3]);
		}else{
			
		}

	},
	
	showChildren: function(){
		$('a.parent').toggle(function(event){
			event.preventDefault();
			var message = $(this).children();
			var id = $(this).attr('href');
			var parentItem = $(this).parent().parent();
			var parentClass = $(this).parent().parent().attr('class');
			$.getJSON('php/config.php?get_children=true&parent='+id, function(data){
				var childTable = '';
				$.each(data, function(i){
					childTable += '<tr class="child-row parent-'+id+' '+parentClass+'">';
					childTable += '<td class="rank">';
					childTable += data[i].rank;
					childTable += '</td>';
					childTable += '<td class="name">';
					childTable += data[i].name;
					childTable += '</td>';
					childTable += '<td class="fans">';
					if(data[i].fans == 0 || data[i].facebookLink == '-'){
						childTable += '0';
					}else{
						childTable += '<a href="'+data[i].facebookLink+'" target="_blank" title="'+data[i].fbUpdate+'" class="child-data">';
						childTable += data[i].fans;
						childTable += '</a>';
					}
					childTable += '</td>';
					childTable += '<td class="followers">';
					if(data[i].followers == 0 || data[i].twitterLink == '-'){
						childTable += '0';
					}else{
						childTable += '<a href="http://www.twitter.com/'+data[i].twitterLink+'" target="_blank" title="'+data[i].twUpdate+'" class="child-data">';
						childTable += data[i].followers;
						childTable += '</a>';
					}	
					childTable += '</td>';
					childTable += '<td class="score">';
					childTable += data[i].total;
					childTable += '</td>';
					childTable += '</tr>';
				});
				parentItem.after(childTable);
				message.text('(Hide)');
				tooltip.tip('.child-data');
			});
		}, function(event){
			event.preventDefault();
			var message = $(this).children();
			var id = $(this).attr('href');
			var parentItem = $(this).parent().parent();
			parentItem.nextAll('tr.parent-'+id).remove();
			message.text('(Show All)');
		});
	},
	
	collapseTable: function(){
		$('th, a.qp_next, a.qp_prev').click(function(event){
			$('tr.child-row').remove();
		});
	},
	
	under50: function(){
		var lastRow = $('td.rank:last').html();
		var oops = '<p class="oops">Oops - we are not quite at 50 yet for this category, help us out by <a href="contact-and-suggestions.php">suggesting</a> more people and companies to list.</p>';
		if(lastRow < 50){
			$('#table_sub').html(oops);
		}
	},
	
	goldStar: function(){
		$('td.rank:first').css('background', 'url(images/gold-star.jpg) no-repeat 50% 42%');
	},
	
	dropDown: function(){
		$('#category-selector select').change(function() {
			var cat = $('#category-selector select').val();			
			//Live Site
			window.location.href = 'http://overdrive50.com/'+cat;
		});
	}
	
};

var search = {
	
	init: function(){
		search.clearSearchBox();
		search.submitSearch();
	},
	
	clearSearchBox: function(){
		$('#search-box input').one('click', function(event){
			$(this).val('');
		});
	},
	
	submitSearch: function(){
		$('#search-button input').one('click', function(event){
			if($('#search-box input').val() == ''){
				event.preventDefault();
			}
		});
	}
	
};

var form = {
	
	init: function(){
		
		form.validate('#contact-form', '#submit', function(){
			var formData = $('#contact-form').serializeArray();
			var loc = $('#page-loc').val();
			$.post('php/config.php?contact-form=true', formData, function(d){
				
				if(loc == 'sug'){
					var message = '<p class="thanks">Thanks for helping to build the Overdrive Social Top 50. Please check back soon, as new listings and features are being added all the time!</p>';
				}else if(loc == 'con'){
					var message = '<p class="thanks">Thanks for getting in touch. Please check back soon, as new listings and features are being added all the time!</p>';
				}
				
				$('#contact-form').html(message);
			});
		});
		
	},
	
	validate: function(formId, submitId, callback){

		$(formId+' '+submitId).click(function(event){

			var totalRequired = $(formId+' .required').length;
			var errorCount = 0;
			var warning = 'error';

			$(formId+' .required').each(function(i){

				if($(this).hasClass('email')){

					if($(this).val() != $(this).val().match(/.+@.+\..+/)){

						$(this).addClass(warning);
						$(this).siblings('label').addClass(warning);

						errorCount++;

					}else{

						$(this).removeClass(warning);
						$(this).siblings('label').removeClass(warning);


					}

				}else if($(this).val() == ''){

					$(this).addClass(warning);
					$(this).siblings('label').addClass(warning);

					errorCount++;

				}else{

					$(this).removeClass(warning);
					$(this).siblings('label').removeClass(warning);

				}

				if($(this).is(':checkbox') && !$(this).is(':checked')){
					errorCount++;
					$(this).siblings('label').addClass(warning);
				}else if($(this).is(':checkbox') && $(this).is(':checked')){
					$(this).siblings('label').removeClass(warning);
				}


			});

			var errorMessage = 'Missing <span>'+errorCount+' / '+totalRequired+'</span> required fields.';

			if(errorCount > 0){
				event.preventDefault();
				if(errorCount > 1){
					$('p.error').html(errorMessage);
				}else{
					$('p.error').html(errorMessage);
				}
			}else{
				if($.isFunction(callback)){
					event.preventDefault();
					callback();
				}
				$('p.error').html('* <span>- Required</span>;');
			}

		});

	}
	
};

var tooltip = {
	
	tip: function(elementId){
		
		$(elementId).hover(function(e){

	    // Hover over code
	
	    	var titleText = $(this).attr('title');
	
	    	$(this).data('tipText', titleText).removeAttr('title');

	    	$('<p class="tooltip"></p>')
	      		.html('<b>Updated:</b> '+titleText+' EST')
	      		.appendTo('body')
	      		.css('top', (e.pageY - 10) + 'px')
	      		.css('left', (e.pageX + 20) + 'px')
	      		.fadeIn();
	
		}, function() {
		
		// Hover out code
	
	    	$(this).attr('title', $(this).data('tipText'));
	    	$('.tooltip').remove();
	
		}).mousemove(function(e){
		
	    // Mouse move code
	
			$('.tooltip')
				.css('top', (e.pageY - 64) + 'px')
				.css('left', (e.pageX - 122) + 'px');
				
	  });
		
	}
	
};


$(document).ready(function(){

	search.init();
	
	top50.dropDown();
	
	if($('#category_table').length > 0){
		top50.init();
	}
	
	if($('#contact-form').length > 0){
		form.init()
	}
	
	
});
