//require jtimer
(function($){
	
	$.fn.extend({ 
		realtime: function(options) { 
 
            var defaults = {
					ctrl_match:				"http://www.site.com/controller",			//link controller partite
					ctrl_league:			"http://www.site.com/controller2",			//link controller classifica
					updatetime:				5,			//seconds
					postdata:				"team=&league=",
					shield_src:				"res/img/#dynamic.jpg",
					shield_href:			"/it/#league/Match-report.page?idmatch=#dynamic", //"/it/#league/Squadre/#dynamic/Squadra.page",
					matchreport_href:		"/it/#league/Match-report.page?idmatch=#dynamic",
					matchreport_src:		"res/img/matchreport.jpg",
					league_names:			["A", "B"],
					calendar_obj:			"table",
					league_obj:				"table",
					enable_autochangetab:	false,
					enable_getleague:		false,
					enable_update_calendar:	false
            }; 
         
            var options = $.extend(defaults, options);
	
            return this.each(function(){
				
                obj = $(this);
				
				var actual_match = 0;
				var updatetime = options.updatetime+"s";
				
				function startRealTime(){
					$.ajax({
						type: "POST",
						url: options.ctrl_match,
						data: options.postdata,
						dataType: "json",
						error: function(){
							obj.parent().hide();
							return false;
						},
						success: function(data){
							if(data.length!=0){
								processData(data);
								if(options.enable_getleague){
									getLeague();
								}
							}else{
								obj.parent().hide();
							}
						}
					});
				}
				
				function getLeague(){
					$.each(options.league_names, function(k, item){
						$.ajax({
							type: "POST",
							url: options.ctrl_league,
							data: "league="+item,
							dataType: "json",
							error: function(){
								return false;
							},
							success: function(data){
								if(data.length!=0){
									processLeagueData(data, k);
								}
							}
						});
					});
				}

				function processData(data){
					writeData(data);
					for(i=0;i<options.league_names.length;i++){
						if(options.league_names[i]!="" && options.enable_update_calendar){
							processCalendarData(data, i);
						}
					}
				}
				
				function processCalendarData(data, position){
					var objcal = $(options.calendar_obj+":eq("+(position)+")");
					objcal.find("tr[id^='match']").each(function(j){
						_self = $(this);
						$.each(data, function(j, item){
							if( _self.find("th:nth-child(1)").text().toUpperCase()==item.squadra1.toUpperCase() ){
								
								if( _self.find("td:nth-child(2)").text()==item.res1.toString() && _self.find("td:nth-child(4)").text()==item.res2.toString() ){
									_self.removeClass("updated");
								}else{
									_self.addClass("updated");
								}
								_self.find("td:nth-child(2)").html(item.res1.toString());
								_self.find("td:nth-child(4)").html(item.res2.toString());
							}
						});
					});
				}
				
				function processLeagueData(data, position){
					var objleague = $(options.league_obj+":eq("+(position)+")");
					var alternate_class = objleague.find("tbody tr:nth-child(2)").attr("class");
					var tpl_table = objleague.find("tbody tr:nth-child(1)").clone();
					var tbody = objleague.find("tbody");
					tbody.empty();
					$.each(data, function(j, team){
						tpl_table.find("td:nth-child(1)").html(team.squadra);
						tpl_table.find("td:nth-child(2)").html(team.punti.toString());
						tpl_table.find("td:nth-child(3)").html(team.giocate.toString());
						tpl_table.find("td:nth-child(4)").html(team.vinte.toString());
						tpl_table.find("td:nth-child(5)").html(team.nulle.toString());
						tpl_table.find("td:nth-child(6)").html(team.perse.toString());
						tbody.append("<tr>"+tpl_table.html()+"</tr>");
					});
					objleague.find("tbody tr:odd").addClass(alternate_class);
				}
				
				function writeData(data){
					obj.parent().show();
					if(actual_match>=data.length){
						actual_match=0;
						//nuova chiamata
						startRealTime();
						return false;
					}
					
					if(options.enable_autochangetab){
						var tabnumber = 0;
						$.each(options.league_names, function(s, league){
							if(data[actual_match].league.indexOf(league.replace("_","-"))!=-1){
								tabnumber=s;
							}
						});
						obj.parent().parent().find("[id$='_title_"+tabnumber+"']").click();
						$(options.league_obj).parent().parent().find("[id$='_title_"+tabnumber+"']").click();
					}
					
					//<a href=\"" + getRealUrl(options.shield_href, data[actual_match].idMatch, data[actual_match].leagueSquadra1) + "\"></a>
					//<a href=\"" + getRealUrl(options.shield_href, data[actual_match].idMatch, data[actual_match].leagueSquadra2) + "\"></a>
					
					obj.find("#shieldA").html("<img src=\"" + getRealUrl(options.shield_src, data[actual_match].squadra1, data[actual_match].leagueSquadra1) + "\" alt=\""+data[actual_match].squadra1+"\" height=\"52\" width=\"66\" />");
					obj.find("#shieldB").html("<img src=\"" + getRealUrl(options.shield_src, data[actual_match].squadra2, data[actual_match].leagueSquadra2) + "\" alt=\""+data[actual_match].squadra2+"\" height=\"52\" width=\"66\" />");
					obj.find("#resultA").html(data[actual_match].res1.toString());
					obj.find("#resultB").html(data[actual_match].res2.toString());
					obj.find("#teamA").html(data[actual_match].squadra1);
					obj.find("#teamB").html(data[actual_match].squadra2);
					obj.find("#mr_link").html("<a href=\"" + getRealUrl(options.matchreport_href, data[actual_match].idMatch, data[actual_match].league) + "\"><img src=\"" + options.matchreport_src + "\" alt=\"Match report\" /></a>");
					
					obj.oneTime(updatetime, function(){
						actual_match++;
						writeData(data);
					});
				}
				
				function getRealUrl(link, value, league){
					var link = link.replace("#dynamic", value);
					var link = link.replace("#league", league.replace(" ", "-"));
					return link;
				}
				
				//real exec
                startRealTime();
			}); 
        } 
    }); 
})(jQuery);