/***********************
* 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) {
         //var matchID = "1533406"; This is set in the html page as a global variable
         
                  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";       
         			//sym.setVariable("swivelstate", "tracker");
         
         for (var m=0; m<3; m++){
         sym.$("tabBtn" + m).bind('click', changeState);
         }
         
         function changeState (){
         		var selected_id = $(this).attr("id");
         //		if (selected_id=="Stage_tabBtn0") {
         			if (swivelstate=="tracker"){
         				sym.play("swivel");
         				sym.$("timeTxt").hide();
         				sym.$("tabBtn0").attr("src","images/team.png");
         				sym.$("tabBtn1").css("color","rgba(0,0,0,1.0)");
         				sym.$("tabBtn2").css("color","rgba(255,255,255,1.0)");
         				swivelstate="lineups";
         			}else if (swivelstate=="lineups"){
         				sym.playReverse();
         				sym.$("timeTxt").show();
         				sym.$("tabBtn0").attr("src","images/clock.png");
         				sym.$("tabBtn2").css("color","rgba(0,0,0,1.0)");
         				sym.$("tabBtn1").css("color","rgba(255,255,255,1.0)");
         				swivelstate="tracker";
         			}
         /*			}
         		if (selected_id=="Stage_tabBtn1") {
         				sym.play("swivel");
         				sym.$("timeTxt").hide();
         				sym.$("tabBtn0").attr("src","images/team.png");
         				sym.$("tabBtn1").css("color","rgba(0,0,0,1.0)");
         				sym.$("tabBtn2").css("color","rgba(255,255,255,1.0)");
         				swivelstate="tracker";
         		}
         		if (state_id=="Stage_tabBtn2") {
         				//sym.playReverse("back");
         				sym.$("timeTxt").show();
         				sym.$("tabBtn0").attr("src","images/clock.png");
         				sym.$("tabBtn2").css("color","rgba(0,0,0,1.0)");
         				sym.$("tabBtn1").css("color","rgba(255,255,255,1.0)");
         				swivelstate="lineups";
         		}
         */
         			e.preventDefault()
         }
                  var sources;
                  $.ajax({	
                  	type: "GET",
                  	url: "GN29768.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=29768&yr=2012&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=infoData[0].n_HomeGoals + "-" + infoData[0].n_AwayGoals;
                  			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();
                  			intervalId = setInterval(getMatch,60000);
                  			} 							
                                  }
                              });
                  }
                  getInfo();
                  intervalId = setInterval(getInfo,60000);
         
         
         
                  var matchData;
                  var diff1;
                  var diff2;
                  var vAlign;
                  var posY;
                  var lastAction;
                  var lastTime;
                  var offset = 300000;
         			var homePenHeight;
                  var awayPenHeight;
                  var penHeight;
         			var penShow;
         
                  function getMatch() { 
         
                   $.ajax({ type: "GET", url: dataURL,
                                  data: "gn=29768&yr=2012&match="+matchID,
                                  contentType: "text/plain", dataType: "jsonp", jsonp: "callback",
                                  async: true,
                                  crossDomain: true,
                                  success: function (data) {
                                  matchData = data;
         
                  //play from last action
                        lastAction = matchData[matchData.length-1].n_ActionTime;
                  		var lastPeriod = matchData[matchData.length-1].n_PeriodSort;
                  		var offset = 300000;
                  		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<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;
                  		}
                  		var myTimer = sym.getSymbol("timer");
                  		myTimer.play(lastTime);
                  		//if penalty shootout
                  		if (lastPeriod>5){
                  		sym.getSymbol("timer").$("timeline").css({'cursor':'ns-resize'});
                  		}
         					if (lastPeriod==10){
         					sym.getSymbol("timer").$("penalties").unbind("click");
         					sym.getSymbol("timer").$("penalties").show();
         					sym.getSymbol("timer").$("penalties").css({'cursor':'pointer'});
         					sym.$("timer").bind("touchstart touchmove", moveMe); //bind touch function
         					sym.$("timer").bind("mousedown", mouseMoveMe); //bind mouse function
         					penShow="show";
         					sym.getSymbol("timer").$("penalties").click(showPenalties);
         					}
         
                  //display latest time
                  		var minutes = sym.$("timeTxt");
                  		if (lastPeriod<9){ //before penalty shootout
         						if(lastAction > 0){		    
         							if (sym.isPlaying ("timer")){
         								minutes.text(Math.round(sym.getSymbol("timer").getPosition()/60000)-5);
         							}else{
         								minutes.text(Math.round(lastAction/60000));
         							}
         						}
         					}else{
         						minutes.text("120");
         					}
         					sym.getSymbol("timer").getSymbol("penalties").getSymbol("pensDiv").$("homePens").empty();
                  		sym.getSymbol("timer").getSymbol("penalties").getSymbol("pensDiv").$("awayPens").empty();
                  //create display for each action		
                          for (var i = 0; i <= matchData.length; i++) {		
                  //first clear the div so that it doesn't just stack appended data on top of one another
                  		if (i==0){
                  		sym.getSymbol("timer").getSymbol("timeline").$("home").empty();
                  		sym.getSymbol("timer").getSymbol("timeline").$("away").empty();
                  		}         
                  		var actionTxt;
                  		var penTxt;
                  		var HorA;
                  		var actionSet = matchData[i].n_ActionSet;
                  		var actionType = matchData[i].n_ActionCode;
                  		var action;
         					if (actionSet==1||actionSet==2||actionSet==3||actionSet==5){
         							if (matchData[i].n_HomeOrAway==1){
                                 actionTxt = "<div><table width='100%' style='font-size:12px;font-family:pragmatica-web, sans-serif' id='action" + i + "'><tr><td width='85%' style='text-align:right'><span id='person" + i + "'></span> <span id='subperson" + i + "'><span></td><td width='5%' style='text-align:right' id='actionMins" + i + "'></td><td width='10%' id='type" + i + "'></td></tr></table></div>";
         								penTxt = "<div class='penalty'><table width='100%' style='font-size:12px;font-family:pragmatica-web, sans-serif; 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";
         							}else if (matchData[i].n_HomeOrAway==-1){
         								HorA = "away";
         								actionTxt = "<div><table width='100%' style='font-size:12px;font-family:pragmatica-web, sans-serif; text-align:left' id='action" + i + "'><tr><td width='10%' id='type" + i + "'></td><td width='5%' style='text-align:left' id='actionMins" + i + "'></td><td width='85%' style='text-align:left'><span id='person" + i + "'></span> <span id='subperson" + i + "'><span></td></tr></table></div>";
         								penTxt = "<div class='penalty'><table width='100%' style='font-size:12px;font-family:pragmatica-web, sans-serif; text-align:left; 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);
         							}
         							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;
         							$('#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='35px' width='35px'>";
                                $('#type' + i).html(imgHTML);		
                   		var actionTime = matchData[i].c_ActionMinute;
                  		var actionPeriod = matchData[i].n_PeriodSort;
                              $('.penalty').css({"background-color":"rgb(255,255,255)","height":"35px","box-shadow":"1px 3px 3px rgba(100,100,100,0.5)"});                                           
                  //move actions that are too close together
                  		if (i+1 < matchData.length){
                  			diff1 = matchData[i+1].n_ActionTime-matchData[i].n_ActionTime;
                  				if (diff1<120000){
                  				posoffset=9;				
                  				}else{
                  				posoffset=0;
                  				}
                  			}
                  			else{
                  			posoffset=0;
                  			}
         
                  		if ((matchData[i].n_ActionTime>=7200000)&&(lastPeriod<9)){
                  		posY="-5px";
                  		}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, "pointer-events":"none"});
                  		} //close if		                			
                                      } //close for 
                                  } //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=29768&yr=2012&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;
         
         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;
         		if(pos>=railY&&pos<=railBottomY){
         				sym.getSymbol("timer").$("timeline").css({'top':165-pos});
         	}		
         };
         
         function mouseMoveMe(){ //handle mousedown event
         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;
         if(pos>=railY&&pos<=railBottomY){
         		sym.getSymbol("timer").$("timeline").css({'top':165-pos});
         		}
         }
         
         function handleMouseUp(jqEvent){ // handle mouseup event
         sym.getComposition().getStage().getSymbolElement().unbind("mousemove");
         sym.getComposition().getStage().getSymbolElement().unbind("mouseup");
         }
         
         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, "GraphicNews29768");