/***********************
* 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) {
//TOUCH OR CLICK
var clickEventType = ('ontouchstart' in document.documentElement ? "touchstart" : "click");
//DATE STUFF
var todayDate;
var nextDate;
function getToday(){
todayDate = new Date();
nextDate = new Date(todayDate.getDate()+1);
}
getToday();

var headline;
var standfirst;
var calDate;
var noDate;
var mainPic = sym.$("otdImg0");
var globe = sym.$("globe");
var year;
var string;
var month;
var months;
var day;
var string2;
var days;
var mm;
var dd;
var yyyy;
var picturetxt;
var picture;
var thumbRow=0;
var thumbRowMax=3;
var numOfDays;
function newDay(){ //creates selcted date
					year = todayDate.getFullYear();
					month = todayDate.getMonth();
					day = todayDate.getDate();
					mm = (month+1<10)?"0"+(month+1): (month+1)+ "";
					dd = (day<10)?"0" + day: day + "";
					yyyy=year;
}
newDay();

function closestNum (num, arr) {
	var curr = arr[0];
	var diff = Math.abs(num - curr);
	for (var i = 0; i < arr.length; i++) {
		if (num<=arr[i]){
			var newdiff = Math.abs (num - arr[i]);
			if (newdiff < diff) {
				diff = newdiff;
				curr = arr[i];
			}
		}
	}
	return curr;
}

function mainXml(){ //get main captions
$.ajax({	
	type: "GET",
	url: "GN31300.xml",
	dataType: "xml",
	success: function(xml) {
		string = $(xml).find('monthnames').text();
		months = string.split(",");
		picturetxt = $(xml).find('picture').text();
		headline = $(xml).find('headline').text();
		sym.$("headlineTxt").html(headline);
		standfirst = $(xml).find('standfirst').text();
		sym.$("standfirstTxt").html(standfirst + " " +months[month] +" "+ (todayDate.getFullYear()));
		sym.getSymbol("calendar").$("calDateTxt").html(months[month] +" "+ (todayDate.getFullYear()));
		noDate = $(xml).find('noDate').text();
		sym.$("noDateTxt").html(noDate);
		}
});
}
mainXml();

var picNo=0;
var eventPix = [];
var eventDates=[];
var dayPics;
var totalPics;
sym.$('arrowright').fadeIn(0);
sym.$('arrowleft').fadeIn(0);

function getDay(){ //change the day xml, pictures
$.ajax({	
	type: "GET",
	url: yyyy+"/"+mm+"/GN31300_"+mm+".xml",
	dataType: "xml",
	success: function (xml){
		sym.$("textBox").empty();
		sym.$("textBox").css({'top':597,'height':'auto'});
		eventPix.length=0;
		var txtHeight;
		var thumbRowPic;
		var thumbCount=[];
			$(xml).find("day").each(function(){
				var $eventdate = $(this);
				eventPix.push($eventdate);
			if(parseInt(dd,10)<=eventDates[eventDates.length-1]){ //If dd is less than the last day in the current xml
				var todaydd=closestNum(parseInt(dd,10),eventDates); //make todaydd the closest day to today
				dd=(todaydd<10)?"0"+todaydd:todaydd+"";
				day=todaydd;
				if ($eventdate.attr("date")==dd+"-"+mm){
					if (picNo>0){
						var t="_"+picNo;
						var order=picNo;
						var globeSrc=yyyy+"/"+mm +"/globe"+ mm + "_" + dd + "_"+picNo+".png";
					}else{
						var t="";
						var order=0;
						var globeSrc=yyyy+"/"+mm +"/globe"+ mm + "_" + dd +".png";
					}
					var $events = $eventdate.find('event');
					$events.each(function(){					
						var $event = $(this);
						thumbCount.push($event);
						if($event.attr("order")==order){
							var cap = $event.find('caption').text();
							var picCap=$event.find('picture').text();
							var html = "<div style='float:left; font-family:pragmatica-web,sans-serif; font-size:16px; padding-left:10px; padding-right:10px; padding-top:5px; padding-bottom:8px'>"+cap+" <span style='font-size:12px'> "+picCap+"</span></div>";
							sym.$("textBox").append(html);
							sym.$("eventTxtCount").html((order+1)+"/");
							txtHeight=sym.$("textBox").height();
							//sym.$("textBox").stop().animate ({top:597-txtHeight+20}, 500);
							sym.$("textBox").stop().animate ({top:532, height:85}, 500);
						globe.attr("src", yyyy+"/"+mm +"/globe"+ mm + "_" + dd + t+".png");
						mainPic.fadeOut(0);
						mainPic.attr("src", yyyy+"/"+mm +"/"+ mm + "_" + dd +t+".jpg");
						mainPic.fadeIn(800);

						}					
					});
					$('#mm'+(parseInt(mm,10)-1)+'dd'+parseInt(dd,10)).addClass('dayNow');
					$('.thumb'+mm+dd).addClass('thumbselect');														
					$(".thumbselect").css({'border':'solid 0.2em rgb(255,0,0)', 'opacity':'1.0'});
					$(".dayNow").css({'color':'rgb(255,255,255)','background-color':'rgb(255,0,0)'});
					thumbRowPic=eventPix.indexOf($eventdate);
					thumbRow=Math.floor(thumbRowPic/3);
					todayDate.setDate(parseInt(dd,10)); //NEW
				}					
			}else{
				//Otherwise change month
				if (todayDate.getMonth()==11){
					todayDate.setFullYear(todayDate.getFullYear());
				}
				todayDate.setMonth(todayDate.getMonth()+1);
				todayDate.setDate(1);
				newDay();
				getCalendar();
			}
			//end
			});
			dayPics=thumbCount.length;
			sym.$("eventTxtCount").append(thumbCount.length);
////MOVED
			thumbRowMax=Math.ceil((eventPix.length)/3)+1; //added one to show an extra line of thumbs
			if (thumbRow<thumbRowMax-3||thumbRowMax<3){
			sym.getSymbol('thumbBtnsMc').$('thumbBox').stop().animate({'top':thumbRow*-101+'px'},400);
			}else{
			sym.getSymbol('thumbBtnsMc').$('thumbBox').stop().animate({'top':(thumbRowMax-3)*-101+'px'},400);
			}
			var testDate= new Date();
			if(testDate>=todayDate){
				sym.$("arrowleft").fadeOut(0);
			}else{
				sym.$("arrowleft").fadeIn(0);
			}			
//////END			
			sym.$("arrowleft").unbind(clickEventType);
			sym.$("arrowright").unbind(clickEventType);

			if (thumbCount.length>1){
				//sym.$('eventTxtCount').fadeIn(0);
				//var t="_"+picNo;
				if(picNo==0){
										//sym.$("arrowleft").unbind("touchstart click");
										//sym.$("arrowleft").on("touchstart click", picChange);
										sym.$("arrowleft").on(clickEventType, picChange);
				}else if(picNo>0){

										//sym.$("arrowleft").unbind("touchstart click");
										//sym.$("arrowleft").on("touchstart click", eventChange);
										sym.$("arrowleft").on(clickEventType, eventChange);
				}
				if(picNo+1<thumbCount.length){

										//sym.$("arrowright").unbind("touchstart click");
										//sym.$("arrowright").on("touchstart click", eventChange);
										sym.$("arrowright").on(clickEventType, eventChange);
				}else if(picNo+1==thumbCount.length){
										//sym.$("arrowright").unbind("click touchstart");
										//sym.$("arrowright").on("click touchstart", picChange);
										sym.$("arrowright").on(clickEventType, picChange);
				}
			}else{
				////var t="";
				//sym.$("arrowleft").unbind("touchstart click");
				//sym.$("arrowleft").on("touchstart click", picChange);
				//sym.$("arrowright").unbind("touchstart click");
				//sym.$("arrowright").on("touchstart click", picChange);

				sym.$("arrowleft").on(clickEventType, picChange);
				sym.$("arrowright").on(clickEventType, picChange);
			}

	},
error: function(){
								//Otherwise show previous month

				todayDate.setMonth(todayDate.getMonth()-1);
				todayDate.setDate(1);
				getCalendar();
				newDay();
	}

});
}

function getMonth(){ //change the month
	sym.getSymbol('thumbBtnsMc').$("thumbBox").empty();
	eventDates.length=0;
	$.ajax({	
		type: "GET",
		url: yyyy+"/"+mm+"/GN31300_"+mm+".xml",
		dataType: "xml",
		success: function (xml){
			todayDate.setYear(todayDate.getFullYear());
			$(xml).find("day").each(function(){
				var $eventdate = $(this);
				//create events for month on calendar and matching thumbnails
				var ddselect = $eventdate.attr("date").substr(0,2);
				var mmselect = $eventdate.attr("date").substr(3,2);
								var yselect = yyyy;

				eventDates.push(parseInt(ddselect,10));
				$('#mm'+(parseInt(mmselect,10)-1)+'dd'+parseInt(ddselect,10)).addClass('select');
				//$('#mm'+(parseInt(mmselect,10)-1)+'dd'+parseInt(ddselect,10)).on("touchstart click", calDate($eventdate.attr("date"),todayDate.getFullYear(),0));
				$('#mm'+(parseInt(mmselect,10)-1)+'dd'+parseInt(ddselect,10)).on(clickEventType, calDate($eventdate.attr("date"),todayDate.getFullYear(),0));
					var $events = $eventdate.find('event');
					var thumbCount=[];
					$events.each(function(){
						var $event = $(this);
						thumbCount.push($event);
						var thumbNo=(thumbCount.indexOf($event)>0)?"_"+thumbCount.indexOf($event):"";
						var thumbTable="<div style='background-image:url("+yselect+"/"+mmselect+"/"+mmselect+ "_" +ddselect+thumbNo +".jpg)' id='th"+mmselect+ddselect+thumbNo+"' class='thumbBtns thumb"+mmselect+ddselect+"'>";
						sym.getSymbol('thumbBtnsMc').$("thumbBox").append(thumbTable);
						$('#th'+mmselect+ddselect+thumbNo).on("touchstart click",calDate($eventdate.attr("date"),todayDate.getFullYear(),thumbCount.indexOf($event)));
					});
				$(".select").css({'background-color':'rgb(200,230,255)','cursor':'pointer'});
				$(".thumbBtns").css({'float':'left','border':'solid 0.2em rgb(255,255,255)','cursor':'pointer', 'opacity':'0.6','background-position':'center','background-size':'148px 95px','width':'95px','height':'95px'});
			});
			getDay();
		}
	});
}

var calDate = function(dateselect,yrC,thumbno){ //sets new date, number of events per date
	return function (e) {
					//change class of selcted event date to highlight with border/bg-color
					$('.thumbBtns').removeClass('thumbselect');
					$('.monthNow').removeClass('dayNow');
					$(".monthNow").css({'color':'rgb(0,0,0)','background-color':'rgb(255,255,255)'});
					$('.thumbBtns').css({'border':'solid 0.2em rgb(255,255,255)', 'opacity':'0.6'});
					$('.select').css({'color':'rgb(0,0,0)','background-color':'rgb(200,230,255)'});
					var dayC = parseInt(dateselect.substr(0,2),10);
					var monthC = parseInt(dateselect.substr(3,2),10)-1;					
					todayDate = new Date(yrC,monthC,dayC);
					picNo=thumbno;
					newDay();
					getDay();
					e.preventDefault();
	};
};

// TOGGLE NO DATE BUTTON
	var showPlus = 0;
	sym.$('noDateBtn').click(function() {
	e.stopPropagation();
	e.preventDefault();
	if (showPlus == 0) {
			sym.getSymbol("noDateBtn").$("plus").fadeOut(60);
			thumbRow=thumbRowMax-3;
			sym.getSymbol('thumbBtnsMc').$('thumbBox').stop().animate({'top':thumbRow*-101+'px'},600);
			showPlus = 1;

		}else{
			sym.getSymbol("noDateBtn").$("plus").fadeIn(60);
			thumbRow=0;
			sym.getSymbol('thumbBtnsMc').$('thumbBox').stop().animate({'top':thumbRow*-101+'px'},600);
			showPlus = 0;
		}
	});

	var thumbsCount = 0;


// HEADER DAY BTNS
sym.$("arrowleft").css({'cursor':'pointer'});
sym.$("arrowright").css({'cursor':'pointer'});

function eventChange(){
e.preventDefault();
e.stopPropagation();
var selected=$(this).attr("id");
if (selected=="Stage_eventBtnTopNext"||selected=="Stage_arrowright"){
 picNo=picNo+1;
}else if(selected=="Stage_eventBtnTopBack"||selected=="Stage_arrowleft"){
 picNo=picNo-1;
}
getDay();
}

function picChange(){
	e.preventDefault();
	e.stopPropagation();
	var selected=$(this).attr("id");
	var loadFunction;
	picNo=0;
	$('.thumbBtns').removeClass('thumbselect');
	$('.monthNow').removeClass('dayNow');
	$(".monthNow").css({'color':'rgb(0,0,0)','background-color':'rgb(255,255,255)'});
	$('.thumbBtns').css({'border':'solid 0.2em rgb(255,255,255)', 'opacity':'0.6'});
	$('.select').css({'color':'rgb(0,0,0)','background-color':'rgb(200,230,255)'});
	for (var i=0;i<eventDates.length; i++){
		if(eventDates[i]==day){
			if (selected=="Stage_arrowright"){
				if(i==eventDates.length-1){
					if (eventDates[i]==numOfDays){
						todayDate.setDate(todayDate.getDate()+1);
					}else{
						todayDate.setMonth(todayDate.getMonth()+1);
						todayDate.setDate(1);
					}
					loadFunction=getCalendar();
				}else{
					console.log(eventDates[i+1]);
					todayDate.setDate(eventDates[i+1]);
					loadFunction=getDay();
				}
			}else if(selected=="Stage_arrowleft"){
				if(i==0){
					todayDate.setMonth(todayDate.getMonth()-1);
					todayDate.setDate(1);
					loadFunction=getCalendar();				
				}else{
					todayDate.setDate(eventDates[i-1]);
					loadFunction=getDay();	
				}
			}
		}
	}

	newDay();
	loadFunction;
}

// CALENDAR THUMBNAIL NAVIGATION BTNS
thumbNav = []; //the array that will hold references to the buttons.
	for (var h = 0; h < 2; h++){
		var thumbBtnSymbols = sym.getSymbol("thumbNav" +h); // Create an instance element of a symbol as a child of the given parent element
		thumbBtnSymbols.setVariable("thumbId", h); //set the value of a Symbol variable
		thumbNav.push(thumbBtnSymbols); //push it into the array
		}
	$.each(thumbNav, function( count, thumbInTheArray ){ //a 'for each' loop through the newly populated array
		var thumbBtnElement = thumbInTheArray.getSymbolElement(); //create a jQuery reference to the DIV element inside the symbol
		//thumbBtnElement.on ("touchstart click", {thumbId:count}, thumbBtnClick);
		thumbBtnElement.on (clickEventType, {thumbId:count}, thumbBtnClick);
		thumbBtnElement.on ("mouseover", {thumbId:count}, thumbShow);
		thumbBtnElement.on ("mouseout", {thumbId:count}, thumbHide);
		})
	function thumbBtnClick (e){
		var thumb_id = (e.data.thumbId); //get the id of the clicked item
		if (thumb_id==0){
			if (thumbRow>0){
				thumbRow--;
			}
		}else{
			if(thumbRow<(thumbRowMax-3)){
				thumbRow++;
			}else{
			thumbRow=thumbRowMax-3;
			}
		}
		sym.getSymbol('thumbBtnsMc').$('thumbBox').stop().animate({'top':thumbRow*-101+'px'},400);
	}
	function thumbShow (e){
         	var thumb_id = (e.data.thumbId); //get the id of the over button
         	sym.getSymbol("thumbNav" + thumb_id).$("btnOut").fadeOut(0);
	}
	function thumbHide (e){
         	var thumb_id = (e.data.thumbId); //get the id of the out button
         	sym.getSymbol("thumbNav" + thumb_id).$("btnOut").fadeIn(0);
	}

//CREATE CALENDAR
function getCalendar(){
	$.ajax({	
	type: "GET",
	url: "GN31300.xml",
	dataType: "xml",
	success: function(xml) {
		string = $(xml).find('monthnames').text();
		months = string.split(",");
		string2 = $(xml).find('daynames').text();
		days = string2.split(",");

		sym.getSymbol("calendar").$("calTxt").empty();	
		var yrC = todayDate.getFullYear();
		var monthC = todayDate.getMonth();
		var leap;
		if (monthC==1){
			leap=((parseInt(yrC)%4 == 0)&&(parseInt(yrC)%100 != 0)||(parseInt(yrC)%400 == 0))?"true":"false";
			var febDays=(leap=="true")?29:28;
		}
		var daysPerMonth = ["31",febDays,"31","30","31","30","31","31","30","31","30","31"];
		var nextMonthC = monthC+1; //Used to match up the current month with the correct start date.
		var prevMonthC = monthC-1;
		// days in previous month and next one , and day of week.
		var firstOfMonth = new Date(yrC,monthC,1);
		var weekdays= firstOfMonth.getDay();
		var weekdays2 = weekdays;
		numOfDays = daysPerMonth[monthC];

		var calContent="";
		var calendarBody="";

		var counter=1;
// leave blank for days of previous month
		while (weekdays>0){
			calContent += "<td class='monthPre'></td>";
			weekdays--;
		}
		while (counter <= numOfDays){
			if (weekdays2 > 6){ // start new line.
				weekdays2 = 0;
				calContent += "</tr><tr height='48px'>";
			}		
			calContent +="<td id='mm"+monthC+"dd"+counter+"' class='monthNow'>"+counter+"</td>";    			
			weekdays2++;
			counter++;
		}
		// building the calendar html body.
		calendarBody +="<table class='calendar' width='100%'><tr class='daysOfWeek'><td>"+days[0]+"</td><td>"+days[1]+"</td><td>"+days[2]+"</td><td>"+days[3]+"</td><td>"+days[4]+"</td><td>"+days[5]+"</td><td>"+days[6]+"</td></tr>";
		calendarBody += "<tr height='48px'>";
		calendarBody += calContent;
		calendarBody += "</tr></table>";
		sym.getSymbol("calendar").$("calTxt").append(calendarBody);
		$(".calendar").css({'font-family':'Times New Roman,Times,serif', 'font-size':'30px','width':'100%','border-collapse':'collapse'});
		$(".monthNow").css({'color':'rgb(0,0,0)','background-color':'rgb(255,255,255)','text-align':'center','border':'0.1em solid rgb(255,255,255)'});
		$(".daysOfWeek td").css({'font-family':'pragmatica-web,arial,sans-serif','width':'14%','color':'rgb(100,100,100)','text-align':'center'});
		sym.getSymbol("calendar").$("calDateTxt").text(months[monthC] +" "+ (yrC));
		var testDate = new Date();
		if(testDate>=todayDate){
			sym.getSymbol("calendar").$("monthBtn0").fadeOut(0);
		}else{
			sym.getSymbol("calendar").$("monthBtn0").fadeIn(0);
		}
		getMonth();

	}
});

}
getCalendar();
// CALENDAR MONTH BTNS
var calArray = ["monthBtn0","monthBtn1"];
for (var i=0; i<2; i++){
		sym.getSymbol("calendar").$("monthBtn"+i).on(clickEventType,changeMonth);
		sym.getSymbol("calendar").$("monthBtn"+i).on("mouseover",calOver);
		sym.getSymbol("calendar").$("monthBtn"+i).on("mouseout",calOut);
		sym.getSymbol("calendar").$("monthBtn"+i).css({"cursor":"pointer"});
		}
function changeMonth() {
			var selected_id = $(this).attr("id");
			if(selected_id == "Stage_calendar_monthBtn0"){
				todayDate.setMonth(todayDate.getMonth()-1);
				todayDate.setDate(1);
			}else if(selected_id == "Stage_calendar_monthBtn1"){
				if (todayDate.getDate()==numOfDays){
						todayDate.setDate(todayDate.getDate()+1);
					}else{
						todayDate.setMonth(todayDate.getMonth()+1);
						todayDate.setDate(1);
					}
			}
			newDay();
			getCalendar();
}
function calOver() {
			var selected_id = $(this).attr("id");
			$("#"+selected_id+"_btnOut").fadeOut(0);
}
function calOut() {
			var selected_id = $(this).attr("id");
			$("#"+selected_id+"_btnOut").fadeIn(0);
}

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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