/***********************
* Adobe Edge 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
*
***********************/
(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;
         sym.setVariable("swivelstate", "tracker");
         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);		
         		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");
         
         function getInfo() {           
          var infoData;
         $.ajax({ type: "GET", url: "//www2.graphicnews.com/infostradasports/api.php",
                         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;
            
         function getMatch() { 
          
          $.ajax({ type: "GET", url: "//www2.graphicnews.com/infostradasports/api.php",
         // $.ajax({ type: "GET", url: "//www.graphicnews.com/cgi/first.cgi",
                         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>5400000){					//if after 90 mins
         		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);
         
         //display latest time
         		var minutes = sym.$("timeTxt");
         		if(lastAction > 0){		    
         		    if (sym.isPlaying ("timer")){
         		    minutes.text(Math.round(sym.getSymbol("timer").getPosition()/60000)-5);
         		    }else{
         		    minutes.text(Math.round(lastAction/60000));
         		    }
         		}
         //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 HorA;
         		var actionSet = matchData[i].n_ActionSet;
         		var actionType = matchData[i].n_ActionCode;
         		var action;
       		if (actionSet==1||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>";
         		HorA = "home";
         		}else if (matchData[i].n_HomeOrAway==-1){
         		HorA = "away";
         		actionTxt = "<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>";
         		}
         //then append each action (latest at top)
                       sym.getSymbol("timer").getSymbol("timeline").$(HorA).append(actionTxt);                
                       $('#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
         //		var actionMins= escapeRegExp(matchData[i].c_ActionMinute);

         		switch (actionSet){
         		case 1:
         		action= "goal";
         		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;
         		
         //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>=5400000){
         		posY="-5px";
         		}else{
         		posY = 385-Math.round(405/90 * (matchData[i].n_ActionTime/60000)) + posoffset + "px";
         		}
         		$('#action' + i).css({"position":"absolute", "top":posY});
         		} //closes if		                			
                             } //closes for                   		                                   
                         } //closes success                                                    	           
                     }); //closes ajax
         }
         
         
         function getTeams() {           
          var teamData;
         $.ajax({ type: "GET", url: "//www2.graphicnews.com/infostradasports/api.php",
                         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);
         
         

      });
      //Edge binding end

            Symbol.bindElementAction(compId, symbolName, "${_tabBtn2}", "click", function(sym, e) {
         var swivel = sym.getVariable("swivelstate");
         if (swivel=="lineups"){
         sym.playReverse();
         sym.$("timeTxt").show();
         sym.$("tabBtn2").css("color","rgba(0,0,0,1.0)");
         sym.$("tabBtn1").css("color","rgba(255,255,255,1.0)");
         //sym.$("tabBtn1").css("box-shadow","2px 3px 2px rgba(75,75,100,0)");
         sym.$("icon").attr("src","images/clock.png");
         }

      });
         //Edge binding end



            Symbol.bindElementAction(compId, symbolName, "${_tabBtn1}", "click", function(sym, e) {
         var swivel = sym.getVariable("swivelstate");
         if (swivel=="tracker"){
         sym.play("swivel");
         sym.$("timeTxt").hide();
         sym.$("tabBtn1").css("color","rgba(0,0,0,1.0)");
         sym.$("tabBtn2").css("color","rgba(255,255,255,1.0)");
         //sym.$("tabBtn2").css("box-shadow","2px 3px 2px rgba(75,75,100,0)");
         sym.$("icon").attr("src","images/team.png");
         }

      });
         //Edge binding end



      Symbol.bindTriggerAction(compId, symbolName, "Default Timeline", 500, function(sym, e) {
         //set the value of a Symbol variable
         sym.setVariable("swivelstate", "lineups");
         sym.stop();

      });
      //Edge binding end

      Symbol.bindTriggerAction(compId, symbolName, "Default Timeline", 0, function(sym, e) {
         sym.setVariable("swivelstate", "tracker");

      });
      //Edge binding end

      Symbol.bindElementAction(compId, symbolName, "${_icon}", "click", function(sym, e) {
         var swivel = sym.getVariable("swivelstate");
         if (swivel=="tracker"){
         sym.play("swivel");
         sym.$("timeTxt").hide();
         sym.$("tabBtn1").css("color","rgba(0,0,0,1.0)");
         sym.$("tabBtn2").css("color","rgba(255,255,255,1.0)");
         sym.$("icon").attr("src","images/team.png");
         }else if (swivel=="lineups"){
         sym.playReverse();
         sym.$("timeTxt").show();
         sym.$("tabBtn2").css("color","rgba(0,0,0,1.0)");
         sym.$("tabBtn1").css("color","rgba(255,255,255,1.0)");
         sym.$("icon").attr("src","images/clock.png");
         }
         

      });
      //Edge binding end

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

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

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

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

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

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

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

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

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

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

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

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

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

//=========================================================
   //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

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

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

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

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

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

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

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

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

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

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