/***********************
* 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) {
//EDIT THESE VARIABLES
	var sportID=217; //EDIT sport ID number for each graphic
	var sportarr=[10072,10071,10070,12319]; //EDIT Include ID numbers for all the events to be covered e.g. Downhill, Super-G, Giant Slalom, Slalom
	var numberEvents=4;//EDIT to show how many events are to be shown. Men and Women count as two separate events
//END EDIT

	var headline;
	var headlinetxt = sym.getSymbol("styleHead").$("headlineTxt").css("pointer-events","none");
	var stand;
	var standtxt = sym.getSymbol("styleHead").$("standTxt").css("pointer-events","none");
	var source;
	var sourcetxt = sym.getSymbol("styleBase").$("sourceTxt").css("pointer-events","none");
	var resultsHeadtxt = sym.getSymbol("resultsMc").$("resultsHeadTxt").css("pointer-events","none");

	//create array of text elements
	var txt=[];
	// .css("backgroundColor","#686868");
	txt[0] = sym.$("txt0").css("pointer-events","none");
	txt[1] = sym.$("txt1").css("pointer-events","none");
	txt[2] = sym.$("txt2").css("pointer-events","none");
	txt[3] = sym.$("txt3").css("pointer-events","none");
	txt[4] = sym.$("txt4").css("pointer-events","none");
	txt[5] = sym.$("txt5").css("pointer-events","none");
	txt[6] = sym.$("txt6").css("pointer-events","none");
	txt[7] = sym.$("txt7").css("pointer-events","none");
	txt[8] = sym.$("txt8").css("pointer-events","none");
	txt[9] = sym.$("txt9").css("pointer-events","none");
	txt[10] = sym.getSymbol("axelMc").$("txt10").css("pointer-events","none");
	txt[11] = sym.$("txt11").css("pointer-events","none");
	txt[12] = sym.$("txt12").css("pointer-events","none");
	txt[13] = sym.$("txt13").css("pointer-events","none");
	txt[14] = sym.$("txt14").css("pointer-events","none");
	txt[15] = sym.$("txt15").css("pointer-events","none");
	txt[16] = sym.$("txt16").css("pointer-events","none");
	txt[17] = sym.$("txt17").css("pointer-events","none");
	txt[18] = sym.$("txt18").css("pointer-events","none");
	txt[19] = sym.$("txt19").css("pointer-events","none");
	txt[20] = sym.getSymbol("axelMc").$("txt20").css("pointer-events","none");
	txt[21] = sym.getSymbol("axelMc").$("txt21").css("pointer-events","none");
	txt[22] = sym.$("txt22").css("pointer-events","none");
	txt[23] = sym.$("txt23").css("pointer-events","none");
	txt[24] = sym.$("txt24").css("pointer-events","none");
	txt[25] = sym.$("txt25").css("pointer-events","none");
	txt[26] = sym.$("txt26").css("pointer-events","none");
	txt[27] = sym.$("txt27").css("pointer-events","none");
	txt[28] = sym.$("txt28").css("pointer-events","none");
	txt[29] = sym.$("txt29").css("pointer-events","none");
	txt[30] = sym.$("txt30").css("pointer-events","none");


	var txtArr=[];	
	var countryCaps=[];
	var resultArr=[];
	var sportCaps=[];
	var months=[];

	//AJAX retrieves data from xml source specified in url, maps xml variable to DOM object variable
	$.ajax({	
		type: "GET",
		url: "GN31321.xml",
		dataType: "xml",
		success: function(xml) {
			headline = $(xml).find('headline').text();
			headlinetxt.html(headline);
			stand = $(xml).find('stand').text();
			standtxt.html(stand);
			source = $(xml).find('source').text();
			sourcetxt.html(source);
	//ADD THIS			
			var sportString= $(xml).find('sportevents').text();
			sportCaps=sportString.split(";");
			var monthstring = $(xml).find('months').text();
			months=monthstring.split(";");
			for (var n=0; n<18; n++){
			resultArr[n]= $(xml).find('result'+n).text();
			}
			resultsHeadtxt.html(resultArr[1]);
			for (var c=0; c<95; c++){
			countryCaps[c]= $(xml).find('country'+c).text();
			}
	//END ADD THIS
			for (var i=0; i<22; i++){
			txtArr[i]=$(xml).find('txt'+i).text();
			txt[i].html(txtArr[i]);
			}
			sym.getSymbol("resultsMc").$("resultsPanel").animate({height:6 + sym.getSymbol("resultsMc").$("table").height() + 0}, 0);
			sym.$("resultsMc").animate({top:505 - sym.getSymbol("resultsMc").$("table").height() + 47}, 0);
			sym.$("txt16").animate({left:772 - sym.$("txt16").width() +3}, 0);
		}
	}); // END XML

	//DATE FUNCTIONS ----------------------
var d=new Date();
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();
        }
function getDDmonthYY(thisDateStr) {
	var dateTxt = thisDateStr.substring(thisDateStr.indexOf('(') + 1, thisDateStr.indexOf(')'));
	var thisDate = new Date(parseInt(dateTxt, 10));
	var mm = thisDate.getMonth();
	var dd = thisDate.getDate();
	return months[mm] + " " + dd +", "+ (thisDate.getFullYear()).toString();
}
var oneday = 1000*60*60*24;
var startDate = new Date("February 6, 2014"); //first medals awarded Sat Feb 8 2014 13:55:00 GMT+0000 (GMT)
var olyDate = new Date();
var endDate = new Date("February 23, 2014");
var endTime = endDate.getTime();
var startTime = startDate.getTime();
var olyTime = olyDate.getTime();

	// MEDAL BUTTON
	//sym.getSymbol('resultsMc').$('medalBtn').fadeOut(0);

	var medal = 0;
	var tablePos=sym.getSymbol('resultsMc').$('table').position();
	var tableLeft=tablePos.left;
	var tableWidth=sym.getSymbol('resultsMc').$('table').width();
//ADD THIS
	if (olyTime>startTime){
		var eventHeight=78;
	}else{
		var eventHeight=25;	
	}
//END	
	if (numberEvents>=6){
		var tableHeight=485; //maximum height of table
	}else{
		var tableHeight=numberEvents*eventHeight;
	}
	sym.getSymbol("resultsMc").$("rectangle").css ({'opacity':'0.0'});
	sym.getSymbol("resultsMc").$("medalBtn").on('touchstart click', function(e){
	e.stopPropagation(); e.preventDefault();
	if (medal == 0) {
		sym.getSymbol("resultsMc").$('table').css({'height':tableHeight+'px','max-height':'485px','overflow-y':'auto'});
		$('.silver,.bronze').css({'display':'table'});
		sym.getSymbol("resultsMc").$("resultsPanel").animate({height:6+tableHeight}, 500);
		sym.$("resultsMc").stop().animate ({top:505-(tableHeight)+48}, 500);
		sym.getSymbol("resultsMc").$("rectangle").stop().animate ({opacity:1.0}, 500);
		sym.getSymbol("resultsMc").getSymbol("medalBtn").$("medalArrow").stop().animate ({rotate:180}, 300, 'easeOutCubic');
		medal = 1;
	}else{
		sym.getSymbol("resultsMc").$('table').css({'height':'48px','overflow':'hidden'});
		sym.getSymbol("resultsMc").$("resultsPanel").animate({height:6 + sym.getSymbol("resultsMc").$("table").height() + 0}, 500);
		sym.$("resultsMc").stop().animate ({top:505}, 500);
		sym.getSymbol("resultsMc").$("rectangle").stop().animate ({opacity:0.0}, 500);
		sym.getSymbol("resultsMc").getSymbol("medalBtn").$("medalArrow").stop().animate ({rotate:0}, 300, 'easeOutCubic');
		medal = 0;
	}

	});
	sym.getSymbol("resultsMc").$("medalBtn").mouseover(function(){
		sym.getSymbol("resultsMc").getSymbol("medalBtn").$("btnOver").fadeOut(200);
	});
	sym.getSymbol("resultsMc").$("medalBtn").mouseout(function(){
		sym.getSymbol("resultsMc").getSymbol("medalBtn").$("btnOver").fadeIn(200);
	});


	// ROTATE 
	(function($){
 var _e = document.createElement("canvas").width
 $.fn.cssrotate = function(d) {  
    return this.css({
  '-moz-transform':'rotate('+d+'deg)',
  '-webkit-transform':'rotate('+d+'deg)',
  '-o-transform':'rotate('+d+'deg)',
  '-ms-transform':'rotate('+d+'deg)'
 }).prop("rotate", _e ? d : null)
 }; 
 var $_fx_step_default = $.fx.step._default;
 $.fx.step._default = function (fx) {
 if(fx.prop != "rotate")return $_fx_step_default(fx);
 if(typeof fx.elem.rotate == "undefined")fx.start = fx.elem.rotate = 0;
 $(fx.elem).cssrotate(fx.now)
 }; 
})(jQuery);


// LIVE MEDAL TABLE DATA FUNCTIONS
	var countries=[74,20,155,24,213,157,151,214,116,103,147,260,78,16,148,159,119,219,26,31,12,168,89,80,17,152,8,222,161,144,163,2,83,211,171,38,28,226,227,87,19,29,6,248,18,160,229,124,9,90,167,7,231,156,23,22,173,3679,172,274,1,158,94,153,236,174,130,150,10,164,146,175,165,239,107,14,30,178,106,145,154,149,132,33,13,5,15,162,241,72,73,197,242,11,3]
	var dataURL = ('http:'==document.location.protocol?"http://www2.graphicnews.com/":"https://www.graphicnews.org/")+ "infostradasports/api.php";
function getEvents(sportID){
	$.ajax({ type: "GET", url: dataURL,
		data: "type=olympics&yr=2014&gn=31160&q=events"+sportID,
		contentType: "text/plain", dataType: "jsonp", jsonp: "callback",
		async: true,
      crossDomain: true,
      success: function (data) {
				eventData=data;
				if (olyTime>=startTime){
					resultsHeadtxt.html(resultArr[0]);
					for (var i = 0; i < eventData.length; i++) {
						for (var n=0;n<sportarr.length; n++){			
							if (eventData[i].n_EventID==sportarr[n]){
								if (eventData[i].b_Finished==true){
								var phaseData=eventData[i].n_EventPhaseID;
								var eventTxt = "<div class='eventtab' id='event" +sportID + "_"+ i + "'>";
								eventTxt += "<div><span class='eventtitle' id='eventtitle"+sportID + "_"+ i + "'></span>"
								eventTxt += "<span class='date' id='date"+sportID + "_"+ i + "'></span></div>";
								eventTxt += "<div class='table'>";
								eventTxt += "<div class='medalwinners' id='results"+phaseData+"'></div><div class='gender' id='gender" + sportID + "_"+ i + "'></div></div></div>";
								sym.getSymbol("resultsMc").$("table").append(eventTxt);
								getPhase(phaseData);
							}else{
								var eventTxt = "<div class='eventtab' id='event" +sportID + "_"+ i + "'>";
								eventTxt += "<div><span class='eventtitle' id='eventtitle"+sportID + "_"+ i + "'></span>"
								eventTxt += "<span class='date' id='date"+sportID + "_"+ i + "'></span></div>";
								eventTxt += "<div class='gender' id='gender" + sportID + "_"+ i + "'></div></div>";
								sym.getSymbol("resultsMc").$("table").append(eventTxt);			
							}
							var eventID=eventData[i].n_EventID;
							var eventName;
							for(var c=0;c<sportarr.length;c++){
								if (eventID==sportarr[c]){
									eventName=sportCaps[c];
								}
							}
							$('#date' + sportID + '_' + i).text(getDDmonthYY(eventData[i].d_DateEndLocal));
							if (eventData[i].b_Finished==true){
									var imgGender='<img src="images/gender'+(eventData[i].n_GenderID)+'.png">';
									$('.date').css({'float':'right'});
									$('.gender').css({'opacity':'0.4','width':'8%'});
							}else{
									var imgGender='<img src="images/gender'+(eventData[i].n_GenderID)+'.png" height="18px">';
									$('.date').css({'float':'right', 'padding-right':'14%'});
									$('.gender').css({'width':'3.5%','padding':'0 3.5% 0 0'});
							}
							$('#gender' + sportID + '_' + i).html(imgGender);
							$('#eventtitle' + sportID + '_'  + i).text(eventName);
							$(".eventtab").css({'display':'table','width':'99%', 'font-size':'13px','font-family':'pragmatica-web, sans-serif', 'border-top':'1px solid rgb(255,255,255)','background-color':'rgba(255,255,255,0.4)', 'margin':'0 0 2px 0','padding':'0 0 0 1%', 'box-shadow':'0px 1px 0px rgba(150,150,150,0.5)'});	
							$('.eventtitle').css({'float':'left','font-weight':700});
							$('.table').css({'display':'table','clear':'both', 'width':'100%','height':'44px','overflow':'hidden'});
							$(".medalwinners").css({'display':'table-cell','float':'left','width':'100%'});
							$('.date').css({'float':'right'});
							$('.gender').css({'display':'table-cell'});
							}
						}
					}
				}else{
					resultsHeadtxt.html(resultArr[1]);
					if(numberEvents<3){
						sym.getSymbol('resultsMc').$('medalBtn').fadeOut(0);
						sym.getSymbol('resultsMc').$('table').css({'width': tableWidth+53+'px','left': tableLeft-52+'px'});
					}
					for (var i=0;i<numberEvents;i++){
						var eventTxt = "<div class='eventtab' id='event" +sportID + "_"+ i + "'>";
						eventTxt += "<div id='table'>";
						eventTxt += "<div id='medalwinners'>";
						eventTxt += "<div id='medalwinner'>";
						eventTxt += "<div class='medal' id='medal" + sportID + "_"+ i + "'><img src='images/gold2.png' height='16px'></div>";
						eventTxt += "<div class='flag' id='flag" + sportID + "_"+ i + "'></div>";
						eventTxt += "<div class='name' id ='name" + sportID + "_"+ i + "'></div>";
						eventTxt += "<div class='nation' id='nation" + sportID + "_"+ i + "'></div>";
						eventTxt += "<div class='gender' id='gender" + sportID + "_"+ i + "'></div>";
						eventTxt += "</div>";
						eventTxt += "</div></div>";
						sym.getSymbol("resultsMc").$("table").append(eventTxt);	
						var imgGender='<img src="images/gender'+(resultArr[i+2+(numberEvents*2)])+'.png" height="16px">';
						var imgFlag='<img src="flags/'+(resultArr[i+2+(numberEvents*3)])+'.png" height="14px">';
						$('#gender' + sportID + '_' + i).html(imgGender);
						$("#name" + sportID + "_"+ i).html(resultArr[i+2]);
						$("#nation" + sportID + "_"+ i).html(resultArr[i+2+numberEvents]);
						$("#flag" + sportID + "_"+ i).html(imgFlag);
						$(".eventtab").css({'display':'table','width':'99%', 'font-size':'13px','font-family':'pragmatica-web, sans-serif', 'border-top':'1px solid rgb(255,255,255)','background-color':'rgba(255,255,255,0.4)', 'margin':'0 0 2px 0','padding':'0 0 0 1%', 'box-shadow':'0px 1px 0px rgba(150,150,150,0.5)'});	
						$('.table').css({'display':'table','clear':'both', 'width':'100%','height':'44px','overflow':'hidden'});
						$(".medalwinners").css({'display':'table-cell','float':'left','width':'100%'});
						$('.date').css({'float':'right'});
						$('.gender').css({'display':'table-cell','padding':'0 3.5% 0 0'});
						$('.flag').css({'display':'table-cell','width':'10%','padding-left':'15px','padding-top':'3px'});
						$('.name').css({'display':'table-cell','width':'65%'});
						$('.nation').css({'display':'table-cell','font-style':'oblique','width':'20%'});
						$('.medal').css({'display':'table-cell','width':'3%'});
					}
				}
		}
});
}
getEvents(sportID);

function getPhase(phase){
$.ajax({ type: "GET", url: dataURL,
		data: "type=olympics&yr=2014&gn=31160&q=result"+phase,
		contentType: "text/plain", dataType: "jsonp", jsonp: "callback",
		async: true,
      crossDomain: true,
      success: function (data) {
				phaseData=data;
				var medalNo=0;
				var medal=[' ','gold','silver','bronze'];
				for (var i = 0; i < phaseData.length; i++) {
					if (phaseData[i].b_MedalGold==true){
						medalNo=1;					
					}
					if(phaseData[i].b_MedalSilver==true){
						medalNo=2;
					}
					if (phaseData[i].b_MedalBronze==true){
						medalNo=3;
					}
					if (phaseData[i].b_MedalGold==true||phaseData[i].b_MedalSilver==true||phaseData[i].b_MedalBronze==true){
					var resultTxt = "<div class='medalwinner "+medal[medalNo]+"' id='"+medal[medalNo]+phase+"_"+i+"'>";
					resultTxt +="<div class='resultrank' id='resultrank"+phase+"_"+i+"'></div><div class='resultflag' id='resultflag" + phase + "_"+ i + "'></div>";
					resultTxt +="<div class='resultname' id='resultname" + phase + "_"+ i + "'></div>";
					resultTxt +="<div class='resultnation' id ='resultnation" + phase + "_"+ i + "'></div>";
					resultTxt +="<div class='medal' id='medalimg" + phase + "_"+ i + "'></div></div>";
					}else{
					var resultTxt = "";
					}
					$('#results'+phase).append(resultTxt);
					var medalHTML='<img src="images/'+medal[medalNo]+'2.png">';
					var imgHTML='<img src="flags/'+(phaseData[i].n_NOCID)+'.png" height="14px" width="24px">';
					$('#resultrank' + phase + '_'  + i).text(phaseData[i].c_Rank);
					$('#resultname' + phase + '_'  + i).text(phaseData[i].c_Participant);
               $('#resultnation' + phase + '_'  + i).text(phaseData[i].c_NOCShort);
               $('#resultflag' + phase + '_' + i).html(imgHTML);
               $('#medalimg' + phase + '_' + i).html(medalHTML);
					$(".medalwinner").css({'display':'table','width':'100%', 'padding':'0 0 0 3px', 'height':'18px','border-top':'1px solid rgb(114,206,255)'});
					$(".medal img").css({'height':'18px'});
               $(".resultflag").css({'display':'table-cell','width':'10%','padding-top':'3px'});
					$(".resultnation").css({'display':'table-cell','font-style':'oblique','width':'20%'});
					$(".resultname").css({'display':'table-cell','width':'65%'});
					$(".resultrank").css({'display':'table-cell','width':'5%'});
					$(".medal").css({'display':'table-cell','width':'3%'});
					$(".silver,.bronze").css({'display':'none'});
				}
		}
});
}

	sym.$("playBtn").on('touchstart click', function(e){
		e.stopPropagation(); e.preventDefault();
		sym.$("playBtn").fadeOut(200);
		sym.$("playBtn").delay(4000).fadeIn(200);
		sym.getSymbol("axelMc").play(501);
	});

         	});//Edge binding end	
		
		// VIDEO BTN 1 =========================================================
         	
			
         	
         		
         	
			
			
         	// VIDEO BTN 2 =========================================================
         	
         	
         	
         		
         	
         	


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

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

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

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

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

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

   //=========================================================
   
   //Edge symbol: 'axelMc'
   (function(symbolName) {   
   
      Symbol.bindTriggerAction(compId, symbolName, "Default Timeline", 10500, function(sym, e) {
         
         sym.play(1);

      });
      //Edge binding end

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

      });
      //Edge binding end

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

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