// Scripts
(function($){$.fn.hoverIntent=function(f,g){var cfg={sensitivity:7,interval:100,timeout:0};cfg=$.extend(cfg,g?{over:f,out:g}:f);var cX,cY,pX,pY;var track=function(ev){cX=ev.pageX;cY=ev.pageY;};var compare=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);if((Math.abs(pX-cX)+Math.abs(pY-cY))<cfg.sensitivity){$(ob).unbind("mousemove",track);ob.hoverIntent_s=1;return cfg.over.apply(ob,[ev]);}else{pX=cX;pY=cY;ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}};var delay=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);ob.hoverIntent_s=0;return cfg.out.apply(ob,[ev]);};var handleHover=function(e){var p=(e.type=="mouseover"?e.fromElement:e.toElement)||e.relatedTarget;while(p&&p!=this){try{p=p.parentNode;}catch(e){p=this;}}if(p==this){return false;}var ev=jQuery.extend({},e);var ob=this;if(ob.hoverIntent_t){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);}if(e.type=="mouseover"){pX=ev.pageX;pY=ev.pageY;$(ob).bind("mousemove",track);if(ob.hoverIntent_s!=1){ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}}else{$(ob).unbind("mousemove",track);if(ob.hoverIntent_s==1){ob.hoverIntent_t=setTimeout(function(){delay(ev,ob);},cfg.timeout);}}};return this.mouseover(handleHover).mouseout(handleHover);};})(jQuery);

$(document).ready(function(){
	
	$("select#home-team-select").change(function(event){
		event.preventDefault();
		var league = this.attributes.rel.value ? this.attributes.rel.value : this.options[this.selectedIndex].getAttribute('data-league');
		var abbr = this.options[this.selectedIndex].getAttribute('data-abbr');
		var name = this.options[this.selectedIndex].text;
		$('#home-team-name').text(name);
		var img = 'img/'+league+'/40px/'+abbr+'.png';
		$('#home-team-logo').attr('src',img);
		$('#reset-matchup,#load-matchup').fadeIn();
	});
	$("select#away-team-select").change(function(event){
		event.preventDefault();
		var league = this.attributes.rel.value ? this.attributes.rel.value : this.options[this.selectedIndex].getAttribute('data-league');
		var abbr = this.options[this.selectedIndex].getAttribute('data-abbr');
		var name = this.options[this.selectedIndex].text;
		$('#away-team-name').text(name);
		var img = 'img/'+league+'/40px/'+abbr+'.png';
		$('#away-team-logo').attr('src',img);
		$('#reset-matchup,#load-matchup').fadeIn();
	});
	$('#load-matchup').click(function(event){
		event.preventDefault();
		var home = document.getElementById("home-team-select").options[document.getElementById("home-team-select").selectedIndex].value;
		var away = document.getElementById("away-team-select").options[document.getElementById("away-team-select").selectedIndex].value;
		window.location = 'matchup/'+home+'/'+away;
	});
	$('#matchup-header').hoverIntent(function(event){
		$('<div id="mu-popup">Click on a team name to change the matchup, then click the \'update\' button when it appears.</div>').appendTo('#matchup-header').fadeIn();
	},function(){
		$('#matchup-header #mu-popup').fadeOut(function(){
			$(this).remove();
		});
	});

	$('table.week-cal td, table.week-cal thead th.week, table.week-cal thead th.week-first, table.week-cal thead th.week-last').hover(function(){
		var t = $(this);
		$('table.week-cal tr td:nth-child('+t.attr('rel')+'), table.week-cal tr th:nth-child('+t.attr('rel')+')').addClass('expanded');
	},function(){
		var t = $(this);
		$('table.week-cal tr td:nth-child('+t.attr('rel')+'), table.week-cal tr th:nth-child('+t.attr('rel')+')').removeClass('expanded');
	});

	$('#day_pager li.larrow a, #day_pager li.rarrow a').live('click',function(event){

		event.preventDefault();

		var t = $(this);

		$('#day_pager').animate({opacity:0},200,function(){
			$.get(t.attr('href'),function(data){
				$('#day_pager').html(data).animate({opacity:1},200);
			});
		});

	});

	$('a#showCompTable').click(function(event){
		event.preventDefault();
		var t = $(this);
		if(t.hasClass('hide')){
			t.removeClass('hide').text('Show League Table');
			$('#tableHolder').hide(); //html('');
			$('a#showCompTable').unbind('click').click(function(event){
				event.preventDefault();
				var t = $(this);
				if(t.hasClass('hide')){
					$('#tableHolder').hide();
					t.removeClass('hide').text('Show League Table');
				} else {
					$('#tableHolder').show();
					t.addClass('hide').text('Hide League Table');
				}
			});
		} else {
			t.text('Loading...');
			$.get('ng-includes/league-table/'+this.hash.substring(1)+'.php',{'comp_id':t.attr('rel'),'ajax':true,'istable':true},function(data){
				$('#tableHolder').html(data);
				t.addClass('hide').text('Hide League Table');
			});
		}
	});
	
	$('a#showMore').live('click',function(event){
		event.preventDefault();
		var t = $(this);
		var tpp = t.parent().parent();
		t.text('Loading...');
		$.get(t.attr('href')+'/next/'+t.data('prev_date'),function(data){
			tpp.after(data);
			tpp.remove();
		});
	});
	
	$('a#showPrev').live('click',function(event){
		event.preventDefault();
		// var cp = event.clientX;
		var t = $(this);
		var tpp = t.parent().parent();
		// var op = tpp.offset();
		// var oh = $('table.day-list').height();
		t.text('Loading...');
		$.get(t.attr('href')+'/previous/'+t.data('date')+'/'+t.data('id'),function(data){
			tpp.before(data);
			// var p = tpp.offset();
			// var h = $('table.day-list').height();
			// console.log(oh,h,cp,op.top,p.top);
			// $('html, body').animate({scrollTop:parseInt((p.top-op.top)+(cp-op.top))}, 0);
			tpp.remove();
		});
	});
	
	$('a.ajax-teams').click(function(event){
		event.preventDefault();
		var t = $(this);
		$('ul.league-list li a.active').removeClass('active');
		$('div.teams .col2').html('<h3 style="background:url(\'ng-resources/images/loading.gif\') no-repeat 12px center;padding-left:50px;">Loading...</h3>');
		$.get(t.attr('href')+'/ajax/',function(data){
			$('ul.league-list li a[data-abbr="'+t.data('abbr')+'"]').addClass('active');
			$('div.teams .col2').html(data);
			$('ul.league-list').removeClass('hidden');
			$('title').text($('div.teams .col2 h3').text()+' » Teams » nextga.me');
		});
	});

	$('h3 a.hide').click(function(event){
		event.preventDefault();
		var t = $(this);
		if($(t.attr('href')).hasClass('hidden')) {
			$(t.attr('href')).show(0,function(){
				$(this).removeClass('hidden');
				t.text('Hide').parent().removeClass('hidden');
				setCookie('ng_hide_'+t.attr('href').substring(1),false,1000);
			});
		} else {
			$(t.attr('href')).hide(0,function(){
				$(this).addClass('hidden');
				t.text('Show').parent().addClass('hidden');
				setCookie('ng_hide_'+t.attr('href').substring(1),true,1000);
			});
		}
	});
	
	$('input#create_myteam').live('click',function(event){

		event.preventDefault();

		$('#ajax_message').show().html('<div class="loading">Adding Team...</div>');

		var c = $('#myteams-list').data('count');

		$.post('ng-includes/actions/create-myteam.php',{ team_id: $('#myteams_teamid').val(), ng_nonce: $('#ng_nonce').val() },function(data){
			$('#ajax_message').html(data).delay(3000).slideUp('slow',function(){
				$('#ajax_message').html('');
			});
			if(c%3!=0) {
				$('#myteams-list tbody tr').last().append('<td'+(c%2==1?' class="alt"':'')+'><span id="team-'+$('#myteams_teamid option:selected').val()+'"><a style="background-image:url(img/'+$('#myteams_teamid option:selected').data('league')+'/40px/'+$('#myteams_teamid option:selected').data('abbr')+'.png);" href="team/'+($('#myteams_teamid option:selected').data('slug')!=''?$('#myteams_teamid option:selected').data('slug'):$('#myteams_teamid option:selected').val())+'">'+$('#myteams_teamid option:selected').text()+' <abbr>('+$('#myteams_teamid option:selected').data('abbr').toUpperCase()+')</abbr></a><a href="my-teams/#del" data-teamid="'+$('#myteams_teamid option:selected').val()+'" data-state="new" class="del">Unfollow</a></span></td>');
			} else {
				$('#myteams-list tbody').append('<tr><td'+(c%2==1?' class="alt"':'')+'><span id="team-'+$('#myteams_teamid option:selected').val()+'"><a style="background-image:url(img/'+$('#myteams_teamid option:selected').data('league')+'/40px/'+$('#myteams_teamid option:selected').data('abbr')+'.png);" href="team/'+($('#myteams_teamid option:selected').data('slug')!=''?$('#myteams_teamid option:selected').data('slug'):$('#myteams_teamid option:selected').val())+'">'+$('#myteams_teamid option:selected').text()+' <abbr>('+$('#myteams_teamid option:selected').data('abbr').toUpperCase()+')</abbr></a><a href="my-teams/#del" data-teamid="'+$('#myteams_teamid option:selected').val()+'" data-state="new" class="del">Unfollow</a></span></td></tr>');
			}
			$('#myteams-list').data('count',c+1);
			$('#myteams_teamid').val('');
		},'html');

	});

	$('table.team-list a.follow').live('click',function(event){

		event.preventDefault();

		$('#ajax_message').show().html('<div class="loading">Adding Team...</div>');

		var t = $(this);
		var teamid = t.data('teamid');

		$.post('ng-includes/actions/create-myteam.php',{ team_id: teamid, ng_nonce: $('#ng_nonce').val() },function(data){
			$('#ajax_message').html(data).delay(3000).slideUp('slow',function(){
				$('#ajax_message').html('');
			});
			t.text('Remove').removeClass('follow').addClass('del');
			t.after('<img src="ng-resources/images/tick.png" class="followtick"/>');
		},'html');

	});

	$('h1.team a.follow').live('click',function(event){

		event.preventDefault();

		$('#ajax_message').show().html('<div class="loading">Adding Team...</div>');

		var t = $(this);
		var teamid = t.data('teamid');

		$.post('ng-includes/actions/create-myteam.php',{ team_id: teamid, ng_nonce: $('#ng_nonce').val() },function(data){
			$('#ajax_message').html(data).delay(3000).slideUp('slow',function(){
				$('#ajax_message').html('');
			});
			t.text('Remove').removeClass('follow').addClass('del');
		},'html');

	});

	$('table.team-list a.del').live('click',function(event){

		event.preventDefault();

		$('#ajax_message').show().html('<div class="loading">Removing Team...</div>');

		var t = $(this);

		var myteamsid = t.data('myteamsid');
		var teamid = t.data('teamid');
		var stateid = t.data('state');

		if(myteamsid!=0 && !teamid) { // On the my teams page

			$.post('ng-includes/actions/delete-myteam.php',{ myteams_id: myteamsid, ng_nonce: $('#ng_nonce').val() },function(data){
				$('#ajax_message').html(data).delay(3000).slideUp('slow',function(){
					$('#ajax_message').html('');
				});
				$('#myteams-'+myteamsid).fadeOut(1000,function(){
					$(this).remove();
				});
			},'html');

		} else if(teamid!=0 && stateid=='new') { // Newly added On the my teams page

			$.post('ng-includes/actions/delete-myteam.php',{ team_id: teamid, ng_nonce: $('#ng_nonce').val() },function(data){
				$('#ajax_message').html(data).delay(3000).slideUp('slow',function(){
					$('#ajax_message').html('');
				});
				$('#team-'+teamid).fadeOut(1000,function(){
					$(this).remove();
				});
			},'html');

		} else if(myteamsid!=0 && teamid!=0) { // Already following - On the Team List

			$.post('ng-includes/actions/delete-myteam.php',{ myteams_id: myteamsid, ng_nonce: $('#ng_nonce').val() },function(data){
				$('#ajax_message').html(data).delay(3000).slideUp('slow',function(){
					$('#ajax_message').html('');
				});
				t.text('Add').removeClass('del').addClass('follow').data('myteamsid','');
				t.siblings('img.followtick').remove();
			},'html');

		} else if(myteamsid==0 && teamid!=0) { // Not Already following - On the Team List

			$.post('ng-includes/actions/delete-myteam.php',{ team_id: teamid, ng_nonce: $('#ng_nonce').val() },function(data){
				$('#ajax_message').html(data).delay(3000).slideUp('slow',function(){
					$('#ajax_message').html('');
				});
				t.text('Add').removeClass('del').addClass('follow');
				t.siblings('img.followtick').remove();
			},'html');

		}

	});

	$('h1.team a.del').live('click',function(event){

		event.preventDefault();

		$('#ajax_message').show().html('<div class="loading">Removing Team...</div>');

		var t = $(this);

		var myteamsid = t.data('myteamsid');
		var teamid = t.data('teamid');

		if(myteamsid!=0 && teamid!=0) { // Already following - On the Team List

			$.post('ng-includes/actions/delete-myteam.php',{ myteams_id: myteamsid, ng_nonce: $('#ng_nonce').val() },function(data){
				$('#ajax_message').html(data).delay(3000).slideUp('slow',function(){
					$('#ajax_message').html('');
				});
				t.text('Add').removeClass('del').addClass('follow').data('myteamsid','');
			},'html');

		} else if(myteamsid==0 && teamid!=0) { // Not Already following - On the Team List

			$.post('ng-includes/actions/delete-myteam.php',{ team_id: teamid, ng_nonce: $('#ng_nonce').val() },function(data){
				$('#ajax_message').html(data).delay(3000).slideUp('slow',function(){
					$('#ajax_message').html('');
				});
				t.text('Add').removeClass('del').addClass('follow');
			},'html');

		}

	});

	/* Signin */
	$('#signin').click(function(event){
		event.preventDefault();
		$('#login-form').css('display','inline');
		$('#register-form').css('display','none');
		$('#login-holder').css('display','none');
		$('#register-holder').css('display','inline');
		$('#login-register').show();
		$('#login-overlay').show();
		$('#login-username').focus();
	});

	$('#signup,#signup-link').click(function(event){
		event.preventDefault();
		$('#login-form').css('display','none');
		$('#register-form').css('display','inline');
		$('#login-holder').css('display','inline');
		$('#register-holder').css('display','none');
		$('#login-register').show();
		$('#login-overlay').show();
		$('#register-username').focus();
	});

	$('#signup-switch').click(function(event){
		event.preventDefault();
		$('#login-form').css('display','none');
		$('#register-form').css('display','inline');
		$('#login-holder').css('display','inline');
		$('#register-holder').css('display','none');
		$('#register-username').focus();
	});

	$('#signin-switch').click(function(event){
		event.preventDefault();
		$('#login-form').css('display','inline');
		$('#register-form').css('display','none');
		$('#login-holder').css('display','none');
		$('#register-holder').css('display','inline');
		$('#login-username').focus();
	});

	$('#login-overlay,#login-close,#feedback-close').click(function(event){
		event.preventDefault();
		$('#login-register').hide();
		$('#login-overlay').hide();
		$('#feedback').hide();
		$('#login-form').css('display','inline');
		$('#register-form').css('display','none');
		$('#login-holder').css('display','none');
		$('#register-holder').css('display','inline');
	});

	$('#just-myteams').click(function(event){
		event.preventDefault();
		if($('table.week-cal').hasClass('just-myteams')) {
			$('table.week-cal td a[class!="myteam"], table.week-cal td a[class!="myteam"]+hr').show();
			$('table.week-cal').removeClass('just-myteams');
			$(this).text('Just show My Teams');
		} else {
			$('table.week-cal td a[class!="myteam"], table.week-cal td a[class!="myteam"]+hr').hide();
			$('table.week-cal').addClass('just-myteams');
			$(this).text('Show all games');
		}
	});

	$('#setlocation').click(function(event){
		event.preventDefault();
		
		if (typeof google === 'object') {

			var g = $('#settings_geolocation').val().split(',');
			if(g!=''){
				var the_center = new google.maps.LatLng(g[0],g[1]);
				var the_zoom = 14;
			} else {
				var the_center = new google.maps.LatLng(32.3992926,155.4269028); // Sydney (-33.8696517,151.2081528)
				var the_zoom = 1;
			}
			var marker;
			var map;

			function location_initialize() {
				var mapOptions = {
					zoom: the_zoom,
					mapTypeId: google.maps.MapTypeId.ROADMAP,
					center: the_center
				};
				map = new google.maps.Map(document.getElementById("get_location_map"),mapOptions);

				marker = new google.maps.Marker({
					map:map,
					draggable:true,
					animation: google.maps.Animation.DROP,
					position: the_center
				});
				// google.maps.event.addListener(marker, 'click', toggleBounce);
				google.maps.event.addListener(marker, 'dragend', markerReport);
			}

			function markerReport() {
				var x = Math.round(marker.position.lat()*10000000)/10000000;
				var y = Math.round(marker.position.lng()*10000000)/10000000;
				$('#settings_geolocation').val(x+','+y);
				$('#settings_geolocation_text').text(x+','+y);

				geocoder = new google.maps.Geocoder();
				var latlng = new google.maps.LatLng(x,y);
				geocoder.geocode({'latLng':latlng }, function(results, status) {
					if (status == google.maps.GeocoderStatus.OK) {
						if (results[1]) {
							$('#settings_location').val(results[1].formatted_address);
							$('#settings_location_text').text(results[1].formatted_address);
						}
					}
				});

			}

			$('#get_location_map_wrapper').slideDown('fast',function(){
				location_initialize();
			});
		}

	});

	$('#password-link').click(function(event){
		event.preventDefault();
		$('#password-change').hide();
		$('#password-fields').show();
	});

	/* This isn't finished */
	$('#showonmap').click(function(event){
		event.preventDefault();

		$.get('ng-includes/team-league-map.php',{ 'ajax_comp': $(this).data('comp') },function(data){
			$('#showonmap-holder').css('display','none').html(data);

			if (typeof google === 'object') {

				var infowindow = new google.maps.InfoWindow();
				var bounds = new google.maps.LatLngBounds();

				function location_initialize() {

					var the_center = new google.maps.LatLng(32.3992926,155.4269028); // Sydney (-33.8696517,151.2081528)
					var the_zoom = 1;
					var map;

					var mapOptions = {
						zoom: the_zoom,
						mapTypeId: google.maps.MapTypeId.ROADMAP,
						center: the_center
					};
					map = new google.maps.Map(document.getElementById("map_canvas"),mapOptions);
					setMarkers(map, teams);
					document.getElementById("map_canvas").appendChild(document.getElementById("message"));

				}

				var matchinfowindow = new Array();
				var marker = new Array();

				function setMarkers(map, locations) {
					var shadow = new google.maps.MarkerImage("ng-resources/images/location_marker.png", new google.maps.Size(40, 40), new google.maps.Point(0,0), new google.maps.Point(20,40));
					var shape = { coord: [1, 1, 1, 20, 20, 20, 20 , 1], type: "poly" };
					for (var i = 0; i < locations.length; i++) {
						var venue = locations[i];
						var myLatLng = new google.maps.LatLng(venue[1], venue[2]);
						bounds.extend(myLatLng);
						var image = new google.maps.MarkerImage(venue[3], new google.maps.Size(20, 20), new google.maps.Point(0,0), new google.maps.Point(10, 35));
						marker[venue[7]] = new google.maps.Marker({
							position: myLatLng,
							map: map,
							shadow: shadow,
							icon: image,
							shape: shape,
							title: venue[0],
							zIndex: venue[7],
							home: venue[4],
							away: venue[5],
							time: venue[6]
						});
						google.maps.event.addListener(marker[venue[7]], "click", function() {
							var contentString = "<div id=\"pointer\"></div><table style=\"text-align:center;font-size:20px;text-shadow:1px 1px 0 #FFF;\"><tr><td style=\"vertical-align:middle;\"><img src=\'"+this.home+"\' style=\"vertical-align:middle;\"/> <em style=\"margin:0 10px;color:#999;\">Vs</em> <img src=\'"+this.away+"\' style=\"vertical-align:middle;\"/></td></tr><tr><td style=\"color:#666;\">"+this.time+" @ <strong>"+this.title+"</strong></td></tr></table>";
							displayPoint(this,contentString);
						});
					}

					map.fitBounds(bounds);
				}

				function displayPoint(venue,contentString){
					document.getElementById("message").style.display = "none";
					document.getElementById("message").innerHTML = contentString;
					document.getElementById("message").style.display = "block";
					map.panTo(venue.position);
				}
			
				$('#showonmap-holder').slideDown('fast',function(){
					location_initialize();
				});
			}
		});

	});

	/* Feedback */
	$('#show_feedback').click(function(event){
		event.preventDefault();
		$('#feedback').show();
		$('#login-overlay').show();
		$('#feedback_text').focus();
	});
	/* $('#feedback_text').focus(function(event){
		if($(this).val()=='Please report any bugs, glitches, errors or suggestions. Thanks for testing!'){
			$(this).val('');
		}
	}); */
	/* $('#feedback_text').blur(function(event){
		if($(this).val()==''){
			$(this).val('Please report any bugs, glitches, errors or suggestions. Thanks for testing!');
		}
	}); */
	$('#feedback_submit').click(function(event){
		event.preventDefault();
		// if($('#feedback_text').val()!='' && $('#feedback_text').val()!='Please report any bugs, glitches, errors or suggestions. Thanks for testing!'){
		if($('#feedback_text').val()!=''){
			$.post('ng-includes/send-feedback.php', {url:$('#current_url').val() ,user:$('#current_user').val() ,text:$('#feedback_text').val() }, function(data){
				$('#feedback').html(data);
			});
		}
	});

	if(typeof team_array === 'object') {
		setGlobalTags(team_array);
		$('#tags').tagSuggest();
	}
	
	$('#inpage-tabs a').click(function(event){
		event.preventDefault();
		$('#inpage-tabs a.active').removeClass('active');
		$('#inpage-content div').addClass('hidden');
		$(this).addClass('active');
		$($(this).attr('href')).removeClass('hidden');
		$.sparkline_display_visible();
	});

});

$('#signin-page').ready(function(){

	$('#signin-page #login-form input').focus(function(){
		$('#rf').css('opacity',0.25);
		$('#lf').css('opacity',1);
	});

	$('#signin-page #register-form input').focus(function(){
		$('#lf').css('opacity',0.25);
		$('#rf').css('opacity',1);
	});

	if(typeof(the_focus) != 'undefined') {
		if(the_focus == 'signup') {
			$('#signin-page #register-form input#register-username').focus();
		} else {
			$('#signin-page #login-form input#login-username').focus();
		}
	}

});

// if (typeof google === 'object') {
// 
// 	var g = $('#settings_geolocation').val().split(',');
// 	if(g!=''){
// 		var the_center = new google.maps.LatLng(g[0],g[1]);
// 	} else {
// 		var the_center = new google.maps.LatLng(32.3992926,155.4269028); // Sydney (-33.8696517,151.2081528)
// 	}
// 	var marker;
// 	var map;
// 
// 	function location_initialize() {
// 		var mapOptions = {
// 			zoom: 1,
// 			mapTypeId: google.maps.MapTypeId.ROADMAP,
// 			center: the_center
// 		};
// 		map = new google.maps.Map(document.getElementById("get_location_map"),mapOptions);
// 
// 		marker = new google.maps.Marker({
// 			map:map,
// 			draggable:true,
// 			animation: google.maps.Animation.DROP,
// 			position: the_center
// 		});
// 		// google.maps.event.addListener(marker, 'click', toggleBounce);
// 		google.maps.event.addListener(marker, 'dragend', markerReport);
// 	}
// 
// 	function markerReport() {
// 		var x = Math.round(marker.position.wa*10000000)/10000000
// 		var y = Math.round(marker.position.ya*10000000)/10000000
// 		$('#settings_geolocation').val(x+','+y);
// 
// 		geocoder = new google.maps.Geocoder();
// 		var latlng = new google.maps.LatLng(x,y);
// 		geocoder.geocode({'latLng':latlng }, function(results, status) {
// 			if (status == google.maps.GeocoderStatus.OK) {
// 				if (results[1]) {
// 					$('#settings_location').val(results[1].formatted_address);
// 				}
// 			}
// 		});
// 
// 	}
// 
// 	$('#get_location_map').ready(function(){
// 		location_initialize();
// 	});
// }
