/***********************
* Adobe Edge Animate Composition Actions
*
* Edit this file with caution, being careful to preserve 
* function signatures and comments starting with 'Edge' to maintain the 
* ability to interact with these actions from within Adobe Edge Animate
*
***********************/
(function($, Edge, compId){
var Composition = Edge.Composition, Symbol = Edge.Symbol; // aliases for commonly used Edge classes

   //Edge symbol: 'stage'
   (function(symbolName) {
      
      
      Symbol.bindElementAction(compId, symbolName, "document", "compositionReady", function(sym, e) {
                  sym.$("timeTxt").css("pointer-events","none");
                  sym.$("matchTxt").css("line-height","125%");
                  
                  
                  var btn1;
                  var btn2;
                  var ko;
                  var cap1;
                  var cap2;
                  var swivelstate="tracker";       
                  
         for (var m=0; m<3; m++){
         sym.$("tabBtn" + m).bind('click', changeState);
         }
         
         sym.$("tabBtn2").css({'color':'rgba(255,255,255,1.0)','box-shadow':'none','background-color':'rgb(9,9,82)'});
         sym.$("tabBtn1").css({'color':'rgba(255,255,255,1.0)','box-shadow':'3px 3px 4px rgba(100,100,100,0.5)','background-color':'rgba(64,133,181,0.5)'});
         
         function changeState (){
         		var selected_id = $(this).attr("id");
         			if (swivelstate=="tracker"){
         				sym.play("swivel");
         				sym.$("timeTxt").hide();
         				sym.$("tabBtn0").attr("src","images/team.png");
         				sym.$("tabBtn1").css({'color':'rgba(255,255,255,1.0)','box-shadow':'none','background-color':'rgb(9,9,82)'});
         				sym.$("tabBtn2").css({'color':'rgba(255,255,255,1.0)','box-shadow':'3px 3px 4px rgba(100,100,100,0.5)','background-color':'rgba(64,133,181,0.5)'});
         				swivelstate="lineups";
         			}else if (swivelstate=="lineups"){
         				sym.playReverse();
         				sym.$("timeTxt").show();
         				sym.$("tabBtn0").attr("src","images/clock.png");
         				sym.$("tabBtn2").css({'color':'rgba(255,255,255,1.0)','box-shadow':'none','background-color':'rgb(9,9,82)'});
         				sym.$("tabBtn1").css({'color':'rgba(255,255,255,1.0)','box-shadow':'3px 3px 4px rgba(100,100,100,0.5)','background-color':'rgba(64,133,181,0.5)'});
         				swivelstate="tracker";
         			}
         			e.preventDefault()
         }
                  var sources;
                  $.ajax({	
                  	type: "GET",
                  	url: "GN30765.xml",
                  	dataType: "xml",
                  	success: function(xml) {
                  		btn1 = $(xml).find('btn1').text();
                  		sym.$("tabBtn1").html(btn1);
                  		btn2 = $(xml).find('btn2').text();
                  		sym.$("tabBtn2").html(btn2);
                  		ko = $(xml).find('ko').text();
                  		sym.getSymbol("timer").getSymbol("timeline").$("koTxt").html(ko);
                  		cap1 = $(xml).find('cap1').text();
                  		sym.getSymbol("teams").$("cap1Txt").html(cap1);
                  		sym.getSymbol("teams").$("cap2Txt").html(cap1);
                  		cap2 = $(xml).find('cap2').text();	
                  		sym.getSymbol("timer").getSymbol("penalties").$("pensTxt").html(cap2);	
                  		sources = $(xml).find('sources').text();
                  		sym.$("sourcesTxt").html(sources);
                  		}
                  });
         
                  	function getDDMMYY(thisDateStr) {
                              var dateTxt = thisDateStr.substring(thisDateStr.indexOf('(') + 1, thisDateStr.indexOf(')'));
                              var thisDate = new Date(parseInt(dateTxt, 10));
                              var mm = thisDate.getMonth() + 1;
                              var dd = thisDate.getDate();
                              mm = ((mm < 10) ? '0' : "") + mm;
                              dd = ((dd < 10) ? '0' : "") + dd;
                              return dd + "/" + mm + "/" + (thisDate.getFullYear()).toString();
                          }
         
                  var crest1 = sym.$("crest1");
                  var crest2 = sym.$("crest2");
         			var dataURL = ('http:'==document.location.protocol?"http://www2.graphicnews.com/":"https://www.graphicnews.org/")+ "infostradasports/api.php";
         
         function getInfo() {           
         	var infoData;
         	$.ajax({ type: "GET", url: dataURL,
         		data: "gn=30765&yr=2013&match="+matchID+"&q=info",
         		contentType: "text/plain", dataType: "jsonp", jsonp: "callback",
         		async: true,
         		crossDomain: true,
         		success: function (data) {
         			infoData = data;
         			var matchteam1=infoData[0].c_HomeTeam;
         			var matchteam2=infoData[0].c_AwayTeam;
         			var score1;
         			var score2;
         			if (infoData[0].n_MatchStatusCode<8){
         				score1="0";
         				score2="0";
         			}else{
         				score1=infoData[0].n_HomeGoals;
         				score2=infoData[0].n_AwayGoals;
         			}
         			var matchRef;
         			if (infoData[0].c_Referee==null){
         				matchRef="";
         			}else{
         				matchRef="Referee: " + infoData[0].c_Referee;
         			}
         			var spectators;
         			if (infoData[0].n_Spectators==null){
         				spectators="";
         			}else{
         				spectators="Attendance: " + infoData[0].n_Spectators;
         			}
         			var matchscore = score1 + "-" + score2;
         			var imgH = "crests/"+ infoData[0].n_HomeTeamID + ".png";
         			var imgA = "crests/"+ infoData[0].n_AwayTeamID + ".png";
         			var matchStatus = infoData[0].n_MatchStatusCode;
         			var tacticsH =  infoData[0].c_HomeTactics;
         			var tacticsA =  infoData[0].c_AwayTactics;
         			var matchDate = getDDMMYY(infoData[0].d_Date);
         			var matchInfo = infoData[0].c_Stadium + ", " + infoData[0].c_City + "<br />" + matchDate + "<br />" + matchRef + "<br />" + spectators ;
         			sym.$("crest1").attr("src",imgH);				
         			sym.$("crest2").attr("src",imgA);				
         			sym.$("team1Txt").text(matchteam1);
         			sym.$("team2Txt").text(matchteam2);
         			sym.$("scoreTxt").text(matchscore);
         			sym.$("matchTxt").html(matchInfo);
                  //matchStatus 8 (in progress), 128 (finished)                
         			if (matchStatus>=8){
         				getMatch();
         			}
         			//PENALTY SHOOTOUT ONLY
         			if (infoData[0].n_PeriodSort>=10){
         			//if (lastPeriod==10){
         				if (infoData[0].n_HomeGoalsShootout>=0||infoData[0].n_AwayGoalsShootout>=0){
         					sym.getSymbol("timer").$("penalties").unbind("click");
         					sym.getSymbol("timer").$("penalties").show();
         					sym.getSymbol("timer").$("penalties").css({'cursor':'pointer'});
         					penShow="show";
         					sym.getSymbol("timer").$("penalties").click(showPenalties);
         				}
         			}
         			if (infoData[0].n_PeriodSort>5){
         				sym.getSymbol("timer").$("timeline").css({'cursor':'ns-resize'});
         				sym.$("timer").on("touchstart",touchStartY);
         				sym.$("timer").on("touchmove", moveMe); //bind touch function
         				sym.$("timer").on("mousedown", mouseMoveMe); //bind mouse function
                  }
         			//END PENALTIES 							
         		}
         	});
         }
         getInfo();
         intervalId = setInterval(getInfo,60000);
         
         
         
                  var matchData;
                  var diff1;
                  var diff2;
                  var vAlign;
                  var posY;
                  var lastAction;
                  var lastPeriod;
                  var lastTime;
                  var offset = 300000;
         			var homePenHeight;
                  var awayPenHeight;
                  var penHeight;
         			var penShow;
         
         var actionsHomeArr=[];
         var actionsAwayArr=[];
         function getMatch() { 
         	$.ajax({ type: "GET", url: dataURL,
         		data: "gn=30765&yr=2013&match="+matchID,
         		contentType: "text/plain", dataType: "jsonp", jsonp: "callback",
         		async: true,
         		crossDomain: true,
         		success: function (data) {
         			matchData = data;
         			actionsHomeArr.length=0;
         			actionsAwayArr.length=0;
         			//play from last action
         			lastAction = matchData[0].n_ActionTime;
         			lastPeriod = matchData[0].n_PeriodSort;
         			var offset = 360000;
         			var lastTimetxt;
         			var myTimer = sym.getSymbol("timer");
         
                  //display latest time
                  var minutes = sym.$("timeTxt");
         			sym.getSymbol("timer").getSymbol("penalties").getSymbol("pensDiv").$("homePens").empty();
                  sym.getSymbol("timer").getSymbol("penalties").getSymbol("pensDiv").$("awayPens").empty();
                  sym.getSymbol("timer").getSymbol("timeline").$("home").empty();
         			sym.getSymbol("timer").getSymbol("timeline").$("away").empty();
                  //create display for each action	
                  var actionTxt;
                  var penTxt;
                  var HorA;
                  var actionSet;
                  var actionType;
                  var action;
                  var actionTime;
         			var actionMs;
                  var actionPeriod;
                  var player;
                  var sub;			
                  for (var i = 0; i <= matchData.length; i++) {
         		      if (matchData[i].n_ActionTime>lastAction){
         					lastAction=matchData[i].n_ActionTime;
         				}
         				if (matchData[i].n_PeriodSort>lastPeriod){
         					lastPeriod=matchData[i].n_PeriodSort;
         				}
         
                  	actionSet = matchData[i].n_ActionSet;
         				if (actionSet==1||actionSet==2||actionSet==3||actionSet==5){
         					actionType = matchData[i].n_ActionCode;
         					actionTime = matchData[i].c_ActionMinute;
         					actionMs = matchData[i].n_ActionTime;
         					actionPeriod = matchData[i].n_PeriodSort;
         					player = matchData[i].c_PersonShort;
         					sub = matchData[i].c_SubPersonShort;
         					var obj=	{number:i, time:actionMs};					
         					if (matchData[i].n_HomeOrAway==1){
         						actionTxt = "<div id='action" + i + "' class='actionhome'><div class='whitebg'><div class='tablecell' style='width:75%'><span id='person" + i + "'></span><span id='subperson" + i + "'><span></div><div class='tablecell' id='actionMins" + i + "'></div></div><div id='type" + i + "'></div></div>";
         						penTxt = "<div class='penalty'><table width='100%' style='border:none; border-collapse:collapse'><tr><td id='person" + i + "' width='90%' style='text-align:right'></td><td width='10%' id='type" + i + "'></td></tr></table></div>";
         						HorA = "home";
         						actionsHomeArr.push(obj);
         					}else if (matchData[i].n_HomeOrAway==-1){
         						actionsAwayArr.push(obj);
         						HorA = "away";
         						actionTxt = "<div id='action" + i + "' class='actionaway'><div id='type" + i + "'></div><div class='whitebg'><div class='tablecell' id='actionMins" + i + "'></div><div class='tablecell' style='width:75%'><span id='person" + i + "'></span><span id='subperson" + i + "'><span></div></div></div>";
         						penTxt = "<div class='penalty'><table width='100%' style='border:none; border-collapse:collapse'><tr><td width='10%' id='type" + i + "'></td><td id='person" + i + "' width='90%' style='text-align:left'></td></tr></table></div>";
         					}
         					//then append each action (latest at top)
         						if(matchData[i].n_PeriodSort<10){
         							sym.getSymbol("timer").getSymbol("timeline").$(HorA).append(actionTxt);
         						}else{
         							sym.getSymbol("timer").getSymbol("penalties").getSymbol("pensDiv").$(HorA+"Pens").prepend(penTxt);
         						}
         						$('#person' + i).text(matchData[i].c_PersonShort);
                           $('#actionMins' + i).text(matchData[i].c_ActionMinute);     
         						if (matchData[i].n_ActionSet==5){
         							$('#subperson' + i).text(" (" + matchData[i].c_SubPersonShort + ")");
         						}else{
         							$('#subperson' + i).text("");
         						} 
         					//create icons for each action
         					switch (actionSet){
         						case 1:
         						action= "goal";
         						break;
         						case 2:
         						if (actionType==12){
         							action="pen";
         						}else{
         							action="miss";
         						}
         						break;
         						case 3:
         						if (actionType==2048){
         							action="yellow";
         						}else{
         							action="red";
         						}
         						break;
         						case 5:
         						action="sub";
         						break;
         					}
         						var imgHTML="<img src='images/"+action +".png' height='25px' width='25px'>";
         						$('#type' + i).html(imgHTML);
         
         					$('.whitebg').css({'width':'84%','background-color':'rgba(255,255,255,0.6)','pointer-events':'none','vertical-align':'top', 'float':'left','border-radius':'5px', 'padding':'1px 3px', 'display':'inline-table'});		
                        $('.actionaway .whitebg').css({'float':'right'});		
                        $('.actionhome, .actionaway').css({'width':'100%','font-size':'12px','font-family':'pragmatica-web, sans-serif','text-align':'left'});
         					$('.tablecell').css({'display':'table-cell'});
                  		$('#action' + i).css({'cursor':'pointer','border-radius':'7px', 'height':'22px', 'overflow':'hidden', 'padding':'0'});
                  		$('#action' + i).on('mouseover touchstart',function(){ $(this).css({'z-index':'1000', 'background-color':'rgba(255,255,255,0.8)','box-shadow':'2px 2px 2px rgba(100,100,100,0.5)', 'overflow':'visible','height':'auto' });  });
         					$('#action' + i).on('mouseout touchend',function(){ $(this).css({'z-index':'100', 'background-color':'rgba(255,255,255,0)','box-shadow':'none', 'overflow':'hidden','height':'23px'}); });
         					$('#type' + i).css({'display':'inline'});
         					$('.actionhome #actionMins'+i).css({'text-align':'right'});
         					$('.actionaway #actionMins'+i).css({'text-align':'left'});
                        $('.penalty').css({"background-color":"rgb(255,255,255)","height":"25px","box-shadow":"1px 3px 3px rgba(100,100,100,0.5)","font-size":"12px","font-family":"pragmatica-web, sans-serif", "text-align":"left"});
         							//move actions that are too close together
         							//TRY LOOPING THROUGH actionsHomeArr, COMPARE i==actionsHomeArr[x].number AND TIME WITH actionsHomeArr[x-1].time
         
         							if (i+1 < matchData.length){
         								diff1 = matchData[i+1].n_ActionTime-matchData[i].n_ActionTime;
         								//if (diff1<120000){
         								if (diff1<150000){
         									posoffset=12;
         									//posoffset=18;				
         								}else{
         									posoffset=3;
         								}
         							}
         							else{
         								posoffset=3;
         							}
         							if ((matchData[i].n_ActionTime>=7200000)&&(lastPeriod<9)){
         								posY="-12px";
         							}else if ((matchData[i].n_ActionTime>=5400000)&&(lastPeriod<5)){
         								posY="-134px";
         							}else{
         							//90minute match
         								posY = 515-Math.round(405/90 * (matchData[i].n_ActionTime/60000)) + posoffset + "px";
         							}
         						$('#action' + i).css({'position':'absolute', 'top':posY});
         				}  //close if
         //TIMING
                  	if (lastAction>7200000){					//if after 120 mins but before penalties
         					lastTime=7200000+offset;
         				}else if ((lastAction>6300000)&&(lastPeriod<7)){					//if after 105 mins but before second period
         					lastTime=6300000+offset;
         				}else if ((lastAction>5400000)&&(lastPeriod==11)){					//if after 90 mins match has finished
         					lastTime=5400000+offset;
         				}else if ((lastAction>5400000)&&(lastPeriod<5)){					//if after 90 mins but before extra time
         					lastTime=5400000+offset;
         				}else if((lastAction>2700000)&&(lastPeriod<4)){ 		// if match is in 1st half but > 45 mins
         					lastTime=2700000+offset;
         				}else{
         					lastTime=lastAction+offset;
         				}
         
         				//display latest time
         				if (lastPeriod==11){
         					lastTimetxt=Math.round((lastTime-offset)/60000);
         				}else if (lastPeriod<9){ //before penalty shootout
         					if(lastAction > 0){	
         						if (sym.isPlaying ("timer")){
         							lastTimetxt=Math.round(sym.getSymbol("timer").getPosition()/60000)-5;
         						}else{
         							lastTimetxt=Math.round(lastAction/60000);
         						}
         					}
         				}else{
         					lastTimetxt="120";
         				}
         				minutes.text(lastTimetxt);
         				myTimer.play(lastTime);
         
         			} //close for 
         			homePenHeight=sym.getSymbol("timer").getSymbol("penalties").getSymbol("pensDiv").$("homePens").height();
         			awayPenHeight=sym.getSymbol("timer").getSymbol("penalties").getSymbol("pensDiv").$("awayPens").height();
         			penHeight = (homePenHeight>awayPenHeight)?homePenHeight:awayPenHeight;
         		} //close success                                                    	           
         	}); //close ajax
         }
         
         			function showPenalties(){
         							if(penShow=="show"){
         								penShow="hide";
         								sym.getSymbol("timer").getSymbol("penalties").$("pensDiv").hide();
         								sym.getSymbol("timer").$("timeline").css({'top':0}); //move timeline down
         							}else{
         								penShow="show";
         								sym.getSymbol("timer").getSymbol("penalties").$("pensDiv").show();
         								sym.getSymbol("timer").$("timeline").css({'top':penHeight}); //move timeline down
         							}
         			}
         
                  function getTeams() {           
                   var teamData;
                  $.ajax({ type: "GET", url: dataURL,
                                  data: "gn=30765&yr=2013&q=teams&match="+matchID,
                                 contentType: "text/plain", dataType: "jsonp", jsonp: "callback",
                                  async: true,
                                  crossDomain: true,
                                  success: function (data) {
                                      teamData = data;
         
                                 for (var i = 0; i < teamData.length; i++) {		
                  		if (teamData[i].n_HomeOrAway==1){
                  		var teamlist = "hometeam";
                  		}else if (teamData[i].n_HomeOrAway==-1){
                  		var teamlist = "awayteam";
                  		}
                  //		if (teamData[i].n_ActionSet!==6){			
                  			if (teamData[i].n_ActionSet==4){
                  			var lineupTxt = "<table width='100%' style='font-size:13px;font-family:pragmatica-web, sans-serif; border-collapse:collapse' id='lineup" + i + "'><tr><td width='10%' style='text-align:right;' id='teamShirt" + i + "'></td><td width='75%' style='padding-left:5px' id='teamPerson" + i + "'></td><td width='15%' style='font-style:oblique; font-size:11px; text-align:right' id='teamNat" + i + "'></td></tr></table>";
                  			} else if (teamData[i].n_ActionSet==5){
                  			var lineupTxt = "<table width='100%' style='font-size:13px;font-family:pragmatica-web, sans-serif; border-collapse:collapse' id='substitute" + i + "'><tr><td width='10%' style='text-align:right; font-style:oblique' id='teamShirt" + i + "'></td><td width='75%' style='font-style:oblique; padding-left:5px' id='teamPerson" + i + "'></td><td width='15%' style='font-style:oblique; font-size:11px; text-align:right' id='teamNat" + i + "'></td></tr></table>";
                  			} else if (teamData[i].n_ActionSet==8){
                  			var coach = "<b>" + teamData[i].c_Person + "</b> <span style='text-align:right; font-style:oblique; font-size:12px'>" + teamData[i].c_PersonNatioShort + "</span>";
                  			}
                  			sym.getSymbol("teams").$(teamlist).append(lineupTxt);                
                  			sym.getSymbol("teams").$(teamlist + "Txt").html(coach);
                  		var actionMins;	                
                  		if (teamData[i].c_ActionMinute==null){
                  		actionMins="";
                  		}else{
                  		actionMins=" ("+ teamData[i].c_ActionMinute + ")";
                  		}			
         
                                $('#teamShirt' + i).text(teamData[i].n_ShirtNr);
                                $('#teamPerson' + i).html(teamData[i].c_Person + actionMins);
                                $('#teamNat' + i).text(teamData[i].c_PersonNatioShort);
                                $('#subPerson' + i).text(teamData[i].c_SubPersonShort);
                                $('#actionMins' + i).text(teamData[i].c_ActionMinute); 
                  		var posn = teamData[i].n_Position;			
                  				}
                  //			}  
                                  }
                              });
                  }
                  getTeams();
                  intervalId = setInterval(getTeams,1800000);
         
         //SCROLL TIMELINE
         	var rail = sym.$("timer");
         	var railHeight = rail.height();
         	var railY = rail.offset().top;
         	var railBottomY = railY + railHeight;
         	var startY=0;
         	var moveTimer=0
         var startTimer=railY;
         var timerShow = sym.getSymbol("matchtracker").getSymbol("timer").$("timeline");
         var timerHeight = timerShow.height();
         var moveTimerStrip = timerHeight-railHeight;
         	rail.bind("touchstart touchmove", moveMe); //bind touch function
         	rail.bind("mousedown", mouseMoveMe); //bind mouse function
         function touchStartY(e){ //handle touch event
         	startY = e.touches[0].pageY;
         }
         //
         function moveMe(e) {
         		e.preventDefault(); //prevents it firing a mouse click when touched
         		var orig = e.originalEvent;
         		var pos = 0;
         		pos = orig.touches[0].pageY;
         var moveDistance=startY-pos;
         moveTimer=startTimer-moveDistance;   
         	if(pos>=railY&&pos<=railBottomY){
         		if(moveTimer<=0){
                  sym.getSymbol("timer").$("timeline").css({'top':moveTimer});
                 }
         	}
         
         };
         //
         function mouseMoveMe(e){ //handle mousedown event
         startY = e.pageY;
         sym.getComposition().getStage().getSymbolElement().mousemove(handleMouseMove); //bind mousemove functions to stage in case cursor goes oustide the thumb
         sym.getComposition().getStage().getSymbolElement().mouseup(handleMouseUp); //bind mouseup functions to stage 
         }	
         
         function handleMouseMove(jqEvent){
         	var pos = 0;
         		pos = jqEvent.pageY;
         	var moveDistance=startY-pos;
         	moveTimer=startTimer-moveDistance;
         			if(pos>=railY&&pos<=railBottomY){
         			if(moveTimer<=0){
                  	sym.getSymbol("timer").$("timeline").css({'top':moveTimer});
                  }
         		}
         }
         
         
         function handleMouseUp(jqEvent){ // handle mouseup event
         sym.getComposition().getStage().getSymbolElement().unbind("mousemove");
         sym.getComposition().getStage().getSymbolElement().unbind("mouseup");
         startTimer=moveTimer;
         }
         
         function handleTouchUp(jqEvent){ // handle touchup event
         sym.getComposition().getStage().getSymbolElement().unbind("touchmove");
         sym.getComposition().getStage().getSymbolElement().unbind("touchend");
         }
         

      });
      //Edge binding end

   })("stage");
   //Edge symbol end:'stage'

   //=========================================================

//=========================================================
   //Edge symbol: 'timer'
   (function(symbolName) {

      Symbol.bindTriggerAction(compId, symbolName, "Default Timeline", 3000000, function(sym, e) {
         sym.stop();
         // insert code here

      });
      //Edge binding end

      Symbol.bindTriggerAction(compId, symbolName, "Default Timeline", 5700500, function(sym, e) {
         sym.stop();

      });
      //Edge binding end

      Symbol.bindTriggerAction(compId, symbolName, "Default Timeline", 6600000, function(sym, e) {
         sym.stop();

      });
      //Edge binding end

      Symbol.bindTriggerAction(compId, symbolName, "Default Timeline", 7500000, function(sym, e) {
         sym.stop();

      });
      //Edge binding end

   })("Timer");
   //Edge symbol end:'Timer'

//=========================================================
   //Edge symbol: 'timeline'
   (function(symbolName) {

   })("Timeline");
   //Edge symbol end:'Timeline'

   //=========================================================

//=========================================================
   //Edge symbol: 'Teams'
   (function(symbolName) {

   })("Teams");
   //Edge symbol end:'Teams'

   //=========================================================
   
   //Edge symbol: 'Penalties'
   (function(symbolName) {   
   
   })("Penalties");
   //Edge symbol end:'Penalties'

   //=========================================================
   
   //Edge symbol: 'pensDiv'
   (function(symbolName) {   
   
   })("PensDiv");
   //Edge symbol end:'PensDiv'

})(jQuery, AdobeEdge, "GraphicNews30765");