/*Our main js library*/
var tjLib = {
	removeEmptyArticle:function(){
		//Remove any article that has a headline of 'Headline' or 'Web head for editor' 
		$('article > h1').each(function(){
			if($.trim($(this).text().toLowerCase()) === 'web head for editor' || 
				$.trim($(this).text().toLowerCase()) === 'headline' ||
				$.trim($(this).text().toLowerCase()) === ''){
				$(this).parent().remove();	
			}
		});
	},
	//Cookie management routines
	cookie_manager: {
        createCookie: function (name, value, days) {
            var expires;
			if (days) {
				var date = new Date();
				date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
				expires = "; expires=" + date.toGMTString();
			}
			else expires = "";
			document.cookie = name + "=" + value + expires + "; path=/";
        },
		readCookie: function (name) {
            var nameEQ = name + "=";
			var ca = document.cookie.split(';');
			for (var i = 0; i < ca.length; i++) {
				var c = ca[i];
				while (c.charAt(0) == ' ') c = c.substring(1, c.length);
				if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
			}
			return null;
        },
		eraseCookie: function (name) {
             this.createCookie(name, "", -1);
        },
		areCookiesEnabled:function(){
			var r = false;
			this.createCookie("cookiesEnabled", "Hello", 1);
			if (this.readCookie("cookiesEnabled") != null) {
				r = true;
				this.eraseCookie("cookiesEnabled");
			}
			return r;	
			}
	},
	//Hyperlinks the masthead h1 to point at the appropriate publication
	hyperlinkMasthead: function(){
		var url = '/csp/cms/sites/TJOnline/Main/index.csp';
		var path = window.location.pathname;
		
		var pattern = /\/TimesTranscript\//i;
		if(pattern.test(path)){
			url = '/csp/cms/sites/TJOnline/TimesTranscript/index.csp';
		}
		
		pattern = /\/TheDailyGleaner\//i
		if(pattern.test(path)){
			url = '/csp/cms/sites/TJOnline/TheDailyGleaner/index.csp';
		}
		
		pattern = /\/Etoile\//i
		if(pattern.test(path)){
			url = '/csp/cms/sites/TJOnline/Etoile/index.csp';
		}
		
		pattern = /\/Madawaska\//i
		if(pattern.test(path)){
			url = '/csp/cms/sites/TJOnline/Madawaska/index.csp';
		}
		
		$('#masthead > hgroup > h1').click(
			function(){
			window.location = url;		
		});
		
		var h2Url;
		//Link the section name to the section front
		if($('body.section-front').length > 0){
			h2Url = path.replace(/(.*)\/.*?\.csp$/, '$1/index.csp');
		}
		else{
			h2Url = path.replace(/\/[^\/]*?\/([^\/]*?)\/[^\/]*?\/[^\/]*?\.csp/, '/csp/cms/sites/TJOnline/$1/index.csp');			
		}
		$('#masthead > hgroup > h2').click(
			function(){
				window.location = h2Url;
				});										   
	},
	//Scripts for the sign-in page
	signin: {
        init: function () {
            
			$('#noticeBox').hide();
                
                if(!tjLib.cookie_manager.areCookiesEnabled()){
                	$('#noticeBox').text('Please enable cookies to login.');
                    $('#noticeBox').show();
                }
                
                $('#btnSubscribe').click(function(){window.location = 'https://www.telegraphjournal.com/iservices/circulation/addrfind.html'});
                
                $('#btnSubscibeFrench').click(function(){window.location = 'https://www.telegraphjournal.com/iservices/circulation/addrfind.html?siteid=French'});

                if(pastedU){
                	$('#DTILogin').val(pastedU);
					if($('#chkSave').length > 0) 
						$('#chkSave')[0].checked = true;
                }
                
                if(pastedP){
                	$('#DTIPassword').val(pastedP);
                }
            
            	$('#btnSubmit').click(
                	function(){
                    	if($('#DTILogin').val() != '' && 
                        	$('#DTIPassword').val() != '' &&
							$('#chkSave').length > 0 &&
							$('#chkSave')[0].checked)
                            {
                            	//AJAX call to page where we set our credentials cookie
                            	$.ajax({
                                	url: '/csp/cms/sites/TJOnline/Main/setCookie.csp?u=' + $('#DTILogin').val() + '&p=' + $('#DTIPassword').val(),
                                	async: false,
                                    timeoutNumber: 1000,
                                    error: $.noop,
                                    success: $.noop
                                });
                            }
							else if($('#chkSave').length > 0 &&
							!$('#chkSave')[0].checked){
								//If the save credentials check box is unchecked, delete any credential cookies
								tjLib.cookie_manager.eraseCookie('u');
								tjLib.cookie_manager.eraseCookie('p');
							}
                    }

                )
        }
	},
	//Script for main section front layout
    section_front: {
		CONST_WIDTH : 620,
        CONST_HEIGHT : 400,
        CONST_DELAY : 9000,
		PLAY : 'Play',
		NEXT : 'Next',
		PREVIOUS : 'Previous',
        init: function () {
            
			//Disable same page link
			this.checkSameLink();
            this.massageMarkup();            
            this.carouselInit();
			this.tickerSetup();
			tjLib.hyperlinkMasthead();
        },
		
		massageMarkup:function(){
			/*Prevents FOUC*/
			$('#main-story').css('left', '0');
			
			//Remove any article that has a headline of 'Headline' or 'Web head for editor' 
			tjLib.removeEmptyArticle();
			
			/*Any story that precedes a header shouldn't have a bottom border*/
            $('section.features article + h1').prev().css('border-width', '0').css('margin-bottom', '0'); /*Top stories that begin with a thumbnail shouldn't have spacing applied to the thumbnail*/
            $('.top-stories article > a:first-child > img').css('margin-top', '0');
            $('.top-stories article:first-child > a:first-child > img').css('margin-top', '5px'); /*If no label before first article in top stories, use a hairline*/
            $('.top-stories').each(

            function () {
                if ($(this).children()[0] && $(this).children()[0].nodeName.toLowerCase() != 'h1') {
                    $(this).css('border-top', '1px solid #000');
                }
            }); /*If latest updates is empty, remove h1*/
            if ($('.features > h1 + h1').length > 0) {
                $('.features > h1 + h1').prev().remove();
            }
			
			//Remove border from last top story
			$('#features-with-top-stories .top-stories > article:last').css('border-width', '0');
			
			//Remove videos and galleries if empty
			if($('#galleryAndVideos article').length === 0){
				$('#galleryAndVideos').remove();
			}
			
			//Remove photo rail if empty
			if($('#photoRail').length > 0 && $('#photoRail article').length === 0){
				$('#photoRail').remove();
			}
			
			//Remove poll if empty
			if($('#poll > form').length === 0){
				$('#poll').remove();
			}

			//For top stories with narrow thumbnail
            $('.top-stories article.alternate').each(function () {
                if ($(this).find($('a > img')).length > 0) {
                    $(this).find('h1').after($(this).find($('a > img').parent()));
                    $(this).find('h1').css('margin-bottom', '15px');
                    $(this).find('p').css('width', '150px').css('float', 'right').css('margin-top', '0');
                    $(this).find('time').css('clear', 'both').css('margin-top','10px');
					$(this).find('p').append('<br />').append($(this).find('time'));
					$(this).find('p').append($(this).find('div#attachments'));
                    $(this).find($('a > img').css('margin-right', '9px'));
                }
            });
			
			
			
			//Colour non Latest Update articles black
			if($('div #features-with-top-stories > section.features > h1:first').text().toLowerCase() === 'latest updates'){
				var latestFlag = 0;
				$('div #features-with-top-stories > section.features > *').each(
					function(){
						if(this.nodeName.toLowerCase() === 'h1'){
							latestFlag += 1;
						}
						
						if(this.nodeName.toLowerCase() === 'article' && latestFlag > 1){
							$(this).find('a').css('color','#000').css('text-transform','none');	
						}
				});
			}

            //Ensures images in single columns are 140px max
            $('.features img, .latest-updates img, #galleryAndVideos img').each(

            function () {
                if (this.width > 140) {
                    $(this).css('width', '140px');
                }
            });
			
			//Remove comment icon if there aren't any comments
			$('.features article, .top-stories article, #businessNews article').each(function(){
				var count = $(this).find('.commentCount').text();
				if(count.indexOf('0') == 0 || count.indexOf(' Comments') == 0)
				{
					$(this).find('.commentCount').remove();
					$(this).find('.commentIcon').remove();
				}
				
				//Singularize single comment
				if(count.indexOf('1 Comments') == 0)
				{
					$(this).find('.commentCount').text("1 comment");
				}
				
				//Remove icon rules if there is less than two icons
				if($(this).find('*:last')[0].nodeName == 'SPAN' &&
					$(this).find('*:last').attr('class') == "iconRule")
				{
					$(this).find('*:last').hide();	
				}
			});
		},
		
		tickerSetup: function(){
			//Set up ticker fade
            if ($('.breaking-news > article').length > 1) {
                $('.breaking-news > article').fadeOut(0);
                $($('.breaking-news > article')[0]).fadeIn(0);
                setInterval(function(){
					var c;
					$('.breaking-news > article').each(
				
					function (index) {
						if ($(this).is(':visible')) {
							c = index;
							$(this).fadeOut(0);
						}
					});
					if (c === ($('.breaking-news > article').length - 1)) {
						c = -1;
					}
					//Don't pass c++ as slice
					$($('.breaking-news > article')[c + 1]).fadeIn(2000);}, 7000);
            }
			if($('.breaking-news > article').length == 0) {
				$('.breaking-news + hr').remove();
				$('.breaking-news').remove();
			}
		},
		
		checkSameLink : function(){
			//Disable nav links that point to the page we're on
			var path = window.location.pathname;
			var fullPath = window.location;
			
			$('nav a[href$="' + path + '"]').each(function(index){
				$(this).addClass('disabled'); 
				$(this).click(function(){return false;} ); 
			});
			
			$('nav a[href$="' + fullPath + '"]').each(function(index){
				$(this).css('color', 'black').css('cursor', 'crosshair');
				$(this).click(function(){return false;} ); 
			}); 
		},
		
        carouselInit: function () {
			var $this = this;
			if ($("#main-story > article").length > 1) {
                //We have multiple lead articles, build the nav strip
                var strip = '<div class="carouselControls"><a href="#" class="carouselPause">Pause</a> <span class="controlWrapper">| <a href="#" class="carouselNext">' + $this.NEXT +'</a> | <a href="#" class="carouselPrevious">' + $this.PREVIOUS + '</a></span><ul class="ui-tabs-nav">';

                $("#main-story > article > img").each(function (index) {
                    var src = $(this).attr('src');
                    strip += '<li class="ui-tabs-nav-item" id="nav-fragment-' + (index + 1) + '"><a href="#fragment-' + (index + 1) + '">' + (parseInt(index) + 1) + '</a></li>';
                });
                strip += '</ul></div>';

                //Add the id and class markers to the articles
                $("#main-story > article").each(

                function (index) {
                    $(this).attr("id", "fragment-" + (index + 1));
                    if (index > 0) {
                        $(this).addClass(".ui-tabs-hide");
                    }
                });

                //Append nav strip into main story section
                $('#main-story').append(strip);
                //Specify options for our carousel tabs
                $("#main-story").tabs({
                    fx: {
                        opacity: "toggle"
                    }
                }).tabs("rotate", $this.CONST_DELAY, false);

                //Pause tab rotation while the user hovers over a thumbnail
                $("ul.ui-tabs-nav li").hover(

                function () {
                    if ($(this).hasClass("ui-tabs-selected")) {
                        $("#featured").tabs("rotate", 0, false);
                    }
                }, function () {
                    if ($(this).hasClass("ui-tabs-selected")) {
                        $("#featured").tabs("rotate", $this.CONST_DELAY, false);
                    }
                });

                $('.carouselPause').click(

                function () {
                    if ($('.carouselPause').html() === 'Pause') {
                        $("#main-story").tabs("rotate", 0, false);
                        $('.carouselPause').html($this.PLAY);
                        $('.controlWrapper').hide();
                    } else {
                        tjLib.section_front.carouselBegin();
                        $('.carouselPause').html('Pause');
                        $('.controlWrapper').show();
                    }
                    return false;
                });

                $('.ui-tabs-nav-item a').click(

                function () {
                    $("#main-story").tabs("rotate", 0, false);
                    $('.carouselPause').html($this.PLAY);
                    $('.controlWrapper').hide();
                });

                $('.carouselPrevious').click(

                function () {
                    var selected = $("#main-story").tabs('option', 'selected');
                    (selected === 0) ? selected = $("#main-story").tabs("length") - 1 : selected--;
                    $("#main-story").tabs("select", selected);
                    $("#main-story").tabs("rotate", $this.CONST_DELAY, false);
                    return false;
                });

                $('.carouselNext').click(

                function () {
                    tjLib.section_front.carouselBegin();
					return false;
                });
            }

        },

        carouselBegin: function () {
            var selected = $("#main-story").tabs('option', 'selected');
            (selected === $("#main-story").tabs("length") - 1) ? selected = 0 : selected++;
            $("#main-story").tabs("select", selected);
            $("#main-story").tabs("rotate", this.CONST_DELAY, false);
            return false;
        },

        carouselResizeImage: function (img) {
            var orientation = "";
            var width = img.naturalWidth || img.width;
            var height = img.naturalHeight || img.height;

            //Crude trap for when images don't load in IE < 9, refactor when possible
            if (width < 40) {
                width = 620;
                height = 400;
                img.width = 620;
                img.height = 400;
            }

            //Even after I change the height of an image, IE will continue to use
            //the old value when I calculate where I need to place the image
            var globalWidth;
            var globalHeight;

            (width > height) ? orientation = "landscape" : orientation = "portrait";

            //We scale to 620px wide, scaling height appropriately
            if (orientation === "landscape") {
                var ratio = width / this.CONST_WIDTH;
                var newWidth = this.CONST_WIDTH;
                var newHeight = height / ratio;
                //We need to ensure the new height is less than 400
                if (newHeight > this.CONST_HEIGHT) {
                    var ratio2 = newHeight / this.CONST_HEIGHT;
                    newWidth = newWidth / ratio2;
                    newHeight = this.CONST_HEIGHT;
                }
                img.height = newHeight
                img.width = newWidth;
                globalWidth = newWidth;
                globalHeight = newHeight;
            }

            //We scale to 400px wide, scaling width appropriately
            if (orientation === "portrait") {
                var ratio = height / this.CONST_HEIGHT;
                var newHeight = this.CONST_HEIGHT;
                var newWidth = width / ratio;

                //We need to ensure the new width is less than 620px;
                if (newWidth > this.CONST_WIDTH) {
                    var ratio2 = newWidth / this.CONST_WIDTH;
                    newHeight = newHeight / ratio2;
                    newWidth = this.CONST_WIDTH;
                }
                img.width = newWidth;
                img.height = newHeight;
                globalWidth = newWidth;
                globalHeight = newHeight;
            }

            //Reset the hiding trick in the CSS
            $(img).css('position', 'relative');
            $(img).css('left', 0);

            /*Centre vertically*/
            if (img.height < this.CONST_HEIGHT) {
                var margin = this.CONST_HEIGHT - globalHeight;
                $(img).css('top', margin / 2 + 'px');
            }
        },
		//Script for photo rail at bottom of page
		photoRailInit: function(){
				//If we have more than 6 gallery thumbs, build gallery nav controls
			var imageCount = $('#galleryImages > .galleryItem > figure > a > img').length;
			var imageMark = 0;
			var IMAGE_COUNT = 6;
			var IMAGE_SHIFT = 145;
			
			if (imageCount > IMAGE_COUNT) {
				//we're at the start, hide right nav control
				$('#galleryNavLeft').hide();
	
				$('#galleryNavLeft').click(
				function () {
					//Update image mark
                imageMark += 1;
                //Slide images
                $('#galleryImages').animate({ left: '+=' + + IMAGE_SHIFT }, 500);

                //Check to see if we should disable left nav control and enable right nav control
                if (imageMark == 0) {
                    $('#galleryNavLeft').hide();
                }

                //Check to see if we should enable right nav control
                if (imageMark + imageMark != IMAGE_COUNT) {
                    $('#galleryNavRight').show();
                }
					
					
					
            });

            $('#galleryNavRight').click(
            function () {
                //Update image mark
					imageMark -= 1;
					//Slide images
					$('#galleryImages').animate({ left: '-=' + IMAGE_SHIFT }, 500);
					//Check to see if we should disable right nav control
					if ((imageCount + imageMark) == IMAGE_COUNT) {
						$('#galleryNavRight').hide();
					}
	
					//Check to see if we should enable left nav control
					if (imageMark < 0) {
						$('#galleryNavLeft').show();
					}
            });
        }
        else {
            //hide gallery nav controls
            $('#galleryNavLeft').hide();
            $('#galleryNavRight').hide();
        }	
		},
		
		//Ensure all heads and images in single columns are sized properly
		shrinkToFit:function(){
			//Ensure all feature heads are 130px or less wide
			$('.features > h1').each(function(){
				var words = $(this).text().split(" ");
				var FONTSIZE = 18;
				var MAXWIDTH = 130;
				var div = document.createElement('div');
				$('body').append(div);
				for(i in words){

			  var div = document.createElement('div');
			  document.body.appendChild(div);
				  $(div).css({
				   position: 'absolute',
				   left: '-1000em',
				   top: '-9000em'
				  });                 

				$(div).html(words[i]);
	
				var styles = ['font-size','font-style', 'font-weight', 'font-family','line-height', 'text-transform', 'letter-spacing'];
	
				  var $this = $(this)

				  $(styles).each(function() {
				   var s = this.toString();
				   $(div).css(s, $this.css(s));
				  });

				while($(div).outerWidth() > MAXWIDTH){
					FONTSIZE--;
					$(div).css('font-size', FONTSIZE + 'px');
					$(this).css('font-size', FONTSIZE + 'px');
				} 
				
				$(div).remove();
             }       
		});			
			
			
            $('.features img, .latest-updates img, #galleryAndVideos img, #galleryImages img').each(

            function () {
                if (this.width > 140 || this.width === 0) {
                    $(this).css('width', '140px');
                }
				$(this).show();
            });
			},
		
		//Build the tabbed video interface
		videoInit: function(){
			//If there are no videos, remove widget
			if($('#videos div').length === 0){
				$('#featured-videos').remove();
			}
		},
		//Ensure left column has less than the maximum number of stories
		trimLeftColumn:function(maxCount){
			var total = $('#features-with-top-stories > .features:first > *').length;
			
			if(total > maxCount){
				var diff = total - maxCount;
				for(var i = 0; i < diff; i++){
					if($('#features-with-top-stories > .features:first > *:last')){
						$('#features-with-top-stories > .features:first > *:last').remove();
					}
				}
				//Ensure the last item isn't a header
				if($('#features-with-top-stories > .features:first > *:last') && 
					 $('#features-with-top-stories > .features:first > *:last')[0].nodeName.toLowerCase() === 'h1'){
					$('#features-with-top-stories > .features:first > *:last').remove();
				}
			}
		},
		
		//Massages markup for Etoile and Madawaska
		frenchInit:function(){
			var $this = this;
			
				//French categories need to be massaged
				$('#more li a').each(
					function(){
						$(this).text($(this).text().replace(/FR-actualit/i, 'Actualit'));
						$(this).text($(this).text().replace(/FR-culture/i, 'Culture'));
						$(this).text($(this).text().replace(/FR-economie/i, '\u00C9conomie'));
						$(this).text($(this).text().replace(/FR-opinion/i, 'Opinion'));
						$(this).text($(this).text().replace(/FR-sports/i, 'Sports'));
						}									 
					);
				
				//Remove empty popular videos
				if($('.popular-videos article').length === 0){
					$('.popular-videos').remove();
				}
				
				//Remove prefix H's from article text
				$('article > p, .info > p').each(
					function(){
							$(this).html($(this).html().replace(/^\s*H /, ""));
						});
				
				//Fix carousel
				$this.PLAY = 'Visionner';
				$this.NEXT = 'Suivant';
				$this.PREVIOUS = 'Pr\u00E9c\u00E9dent';
				
				$('.carouselNext').text($this.NEXT);
				$('.carouselPrevious').text($this.PREVIOUS);
				
				//Fix french dates
				$('article .mainLastMod em, article time').each(
				function(){
                var stamp = $(this).text();
                var hourPattern = new RegExp('(\\d\\d?) hour', 'i');
                var minutePattern = new RegExp('(\\d\\d?) minute', 'i');
                var newStamp = 'Publi\u00E9 il y a ';
                hourPattern.test(stamp) || minutePattern.test(stamp)
                if (hourPattern.test(stamp) || minutePattern.test(stamp)) {
                    if (hourPattern.test(stamp)) {
                        var hourNo = stamp.match(hourPattern)[1];
                        (hourNo === 1) ? newStamp += '1 heure' : newStamp += hourNo + ' heures';
                    }

                    if (minutePattern.test(stamp)) {
                        var minuteNo = stamp.match(minutePattern)[1];
                        (minuteNo === 1) ? newStamp += '1 minute' : newStamp += minuteNo + ' minutes';
                    }
                }
                else {

                    var datePattern = new RegExp('Updated: ([\\s\\S]*)$');
                    if (datePattern.test(stamp)) {
                        var datestamp = stamp.match(datePattern)[1];

                        var d = new Date(datestamp);
                        if (d) {
                            newStamp = 'Publi\u00E9 le ' + d.toFrench();
                        }
                    }
                }
                $(this).html(newStamp);
           
				});
		},
		
		//Window Init should be fired at window.load to ensure images and text are loaded and dimensioned
        windowInit: function () {
			this.shrinkToFit();
			
			var ref_this = this;

			
			$('#main-story img').each(
				function(){
				ref_this.carouselResizeImage(this);
			}				  
								  );
			
        }
    },
	//Scripts for alternate section front layout (currently just used for business
	section_front2:{
		CONST_WIDTH : 620,
        CONST_HEIGHT : 400,
        CONST_DELAY : 9000,
		init: function(){

			 //Disable same page link
			tjLib.section_front.checkSameLink();
            tjLib.section_front.massageMarkup();            
            this.carouselInit();
			tjLib.section_front.tickerSetup();
		},
			
		carouselInit: function(){
			if ($("#main-story > article").length > 1) {
            //We have multiple lead articles, build the nav strip
            var strip = '<div class="carouselControls"><a href="#" class="carouselPlay">Play</a> <a href="#" class="carouselStop">Stop</a><ul class="ui-tabs-nav">';
			
            $("#main-story > article > img").each(function (index) {
                var src = $(this).attr('src');
                strip += '<li class="ui-tabs-nav-item" id="nav-fragment-' + (index + 1) + '"><a href="#fragment-' + (index + 1) + '">' + (parseInt(index) + 1) + '</a></li>';
            });
            strip += '</ul></div>';
						
            //Add the id and class markers to the articles
            $("#main-story > article").each(
                function (index) {
                    $(this).attr("id", "fragment-" + (index + 1));
                    if (index > 0) {
                        $(this).addClass(".ui-tabs-hide");
                    }
                }
            );

            //Append nav strip into main story section
            $('#main-story').append(strip);
            //Specify options for our carousel tabs
            $("#main-story").tabs({ fx: { opacity: "toggle"} }).tabs("rotate", this.CONST_DELAY, false);

            //Pause tab rotation while the user hovers over a thumbnail
            $("ul.ui-tabs-nav li").hover(
            function () {
                if ($(this).hasClass("ui-tabs-selected")) {
                    $("#featured").tabs("rotate", 0, false);
                }
            },
            function () {
                if ($(this).hasClass("ui-tabs-selected")) {
                    $("#featured").tabs("rotate", this.CONST_DELAY, false);
                }
            }
            );
			
			$('.carouselStop').click(
				function(){				
					 $("#main-story").tabs("rotate", 0, false);
					return false; 
				}						 
			);

			
			$('.ui-tabs-nav-item a').click(
				function(){
					$("#main-story").tabs("rotate", 0, false);
				}
				);
			
			
			$('.carouselPlay').click(
				function(){									 
					tjLib.section_front.carouselBegin();
					return false;
				}
			);
        }
		},
		carouselBegin: function () {
            tjLib.section_front.carouselBegin();
        },

        carouselResizeImage: function (img) {
           tjLib.section_front.carouselResizeImage(img);
		   if(img.width < this.CONST_WIDTH){
				$(img).css('position','relative').css('left', (this.CONST_WIDTH - img.width)/2);   
		   }
        },
		windowInit:function(){
			
			tjLib.section_front.shrinkToFit();
			
			var ref_this = this;
			
			//Resize all images
			$('#main-story img').each(
				function(){
				ref_this.carouselResizeImage(this);
			});
			
			//To ensure we don't have the page shifting vertically, fix the height of the text area for the lead area
			$('#main-story article').css('height', '550px').css('overflow', 'hidden');
		}
	},
	//Scripts for category page
    category: {
        init: function () {
			tjLib.removeEmptyArticle();
			
            //Check thumbnails, if less than 141px, float next to abstract
            $('article').each(function () {
                var i = $(this).find('img');
                var w = i.naturalWidth || i.width;
                if (w < 141) {
                    $(this).find('h1').after(i);
                }
            });
        }
    },
	//Script for search page
	searchPage: {
		init: function(){
			tjLib.removeEmptyArticle();
		}
	},
	//Script for full story layout
    story: {
        init: function (isFrench) {
			tjLib.removeEmptyArticle();
			tjLib.hyperlinkMasthead();
            //massage our markup into a format consumable by AD Gallery to create gallery
            $(".ad-thumb-list > li").each(function (index) {
                var largeSrc = $(this).find('img.galleryFull').attr('src');
                var thumbSrc = $(this).find('img.galleryThumb').attr('src');
                var caption = $(this).find('span').html();
                caption = caption.replace(/"/g, '&quot;');
                caption = caption.replace(/<em>\s*<\/em>/g, '');
                caption = caption.replace(/\n/g, '');
                caption = caption.replace(/<span>\s*<\/span>/g, '');
                caption = $.trim(caption);

                $(this).html('<a href="' + largeSrc + '">' + '<img src="' + thumbSrc + '" alt="' + caption + '" /></a>');
            });
			
			
			//Add flag as inappropriate link to comments
			$('.comment').each(
            function(i){
                $(this).attr('id','Comment'+i);
                $(this).append('<p class="flag clearfix"><a href="#">Flag as inappropriate</a></p>');
            }
        );
       
	   //Create querystring containing info on inappropriate comment
       $('.comment a').live('click', function() {
            var title = $('#mainContainer > h1').text().trim();
            var url = document.URL;
            var container = $(this).parent().parent();
            var comment, flagger, flaggerId, commentDate, commenter;
            var queryString = '?title='+title;
            
            if(container[0].nodeName.toLowerCase() === 'div'){
                comment = container.find('p + p').text().replace('Flag as inappropriate', '');
                commenter = container.find('.commentHeader strong').text();
                var id = container.attr('id');
                url += '%23' + id;
                flagger = '#(firstName)# ' + '#(lastName)#';
                flaggerId = '#(WebUserId)#';
                commentDate = container.find('.commentHeader  em').text();
            }
            queryString += '&comment=' + comment;
            queryString += '&flagger=' + flagger;
            queryString += '&flaggerId=' + flaggerId;
            queryString += '&title=' + title;
            queryString += '&commentDate=' + commentDate;
            queryString += '&commenter=' + commenter;
            queryString += '&url=' + url;
            queryString += '&section=#(gSection.name)#';
            
            //Send email flagging inappropriate comment
            $.ajax({
                url: '#(gPublication.getPublicationPath())#' + '/assets/scripts/email/submit.csp' + queryString,
                async: true,
                error: function(){alert('Your message could not be sent at this time, please try again later.')},
                success: function(){alert('Your message has been sent.')}
            });
            return false;
       });
	   			
			//Remove the H that precedes Etoile's articles
			if($('.byline + p').length > 0){
				$('.byline + p').html($('.byline + p').html().replace(/^H /, ""));
			}
			
			if($('.byline + p + p').length > 0){
				$('.byline + p + p').html($('.byline + p + p').html().replace(/^H /, ""));
			}
			
			if($('.headshotContainer + p').length > 0){
				$('.headshotContainer + p').html($('.headshotContainer + p').html().replace(/^H /, ""));
			}			
			
			if($('.headshotContainer + p + p').length > 0){
				$('.headshotContainer + p + p').html($('.headshotContainer + p + p').html().replace(/^H /, ""));
			}

            //Remove the photo credit if empty
            if ($('.photo-credit').length > 0 && $.trim($('.photo-credit').text()) === "") {
                $('.photo-credit').remove();
            }

            //Remove the headshot container if empty
            if ($('.headshotContainer p').length > 0 && $.trim($('.headshotContainer p').text()) === "") {
                $('.headshotContainer p').remove();
            }

            if ($('.headshotContainer img').length < 1) {
                $('.headshotContainer').remove();
            }

            //Add an 'odd' class to odd factbox items
            $('.factboxcontent p').filter(':odd').addClass('odd');

            //Build tabs if we have an article, photo gallery, video, and/or comments
            var content = {
                galleryExists: $('.ad-gallery').length > 0,
                articleExists: $('.byline + p').length > 0 || $('.byline + div.headshotContainer').length > 0,
                videoExists: $('#main-video').length > 0
            };

            //If article doesn't exist, re-format and move headline to make it a label
            if (!content.articleExists) {
                $('#main-section').prepend($('figure#main-photo'));
                $('#main-section').prepend($('#mainContainer > h1').attr('id', 'mainLabel'));

                //Remove subcategory label if h1 label already exists
                $('h2.label').remove();

            }

            //If any are true, build tabs
            var extraContent = false;
            var count = 0;

            //If two or more constituent pieces of a page exist, create tabs
            for (var i in content) {
                if (content[i] === true) {
                    count++;
                    if (count === 2) {
                        extraContent = true;
                        break;
                    }
                }
            }

            if (extraContent) {
                var tabArray, contentArray;
                tabArray = [];
                contentArray = [];
				
				//If an articles exists, take body text and main photo
                if (content.articleExists) {
                    tabArray.push('Article');
                    contentArray.push('<figure id="main-photo">' + $('#main-photo').html() + '</figure>' + $('#mainContainer').html());
                    $('#mainContainer').remove();
					$('#main-photo').remove();
                }

                if (content.galleryExists) {
                    tabArray.push(isFrench ? 'Galerie photos' : 'Photo Gallery');
                    contentArray.push('<div class="ad-gallery">' + $('.ad-gallery').html() + '</div>');
                    $('.ad-gallery').remove();
                }

                if (content.videoExists) {
                    tabArray.push(isFrench ? 'Vidéo' : 'Video');
                    contentArray.push($('#main-video').html());
                    $('#main-video').remove();
                }

                var tabMarkup = '<ul>';
                var videoIndex = 0;
                for (var i = 1; i < tabArray.length + 1; i++) {
                    tabMarkup += '<li><a href="#tabs-' + i + '">' + tabArray[i - 1] + '</a></li>';
                    if (tabArray[i - 1] === 'Video') {
                        videoIndex = i;
                    }
                }
                tabMarkup += '</ul>';


                var contentMarkup = '';
                for (var i = 1; i < contentArray.length + 1; i++) {
                    contentMarkup += '<div id="tabs-' + i + '">' + contentArray[i - 1] + '</div>';
                }

                //For some reason, in IE the html() function won't work
                document.getElementById('main-section').innerHTML = tabMarkup + contentMarkup;
				
                $('#main-section').tabs();
				
				//remove border from lsat li for IE7's sake
				$('#page #main-section .ui-widget-header li').last().css('border-width', '0');
				
				//adjust background of tab header if last link is clicked
				$('.ui-tabs-nav li a').click(function(){
					if(this === $('.ui-tabs-nav li:last-child a').get(0))
					{
						$('.ui-widget-header').css('background', '#999');
					}
					else{
						$('.ui-widget-header').css('background', '#DCDDD6');
					}
				});
				
				//Ensure we flip back to the article tab if the user clicks on the comments link
				$('.comment-link a').click(function(){
					if($('#page #main-section .ui-widget-header li a').length > 0){
						//First tab is always the article
						$($('#page #main-section .ui-widget-header li a')[0]).trigger('click');
					}
												   });

                //Lazy load video....because IE won't load it with tabs any other way
                if (videoIndex > 0) {
                    $('a[href="#tabs-' + videoIndex + '"]').one('click', function () {
                        var lazyMarkup = $('#tabs-' + videoIndex).html().replace('<!--', '').replace('-->', '').replace(/videoPlaceHolder/g, videoId);
                        $('#tabs-' + videoIndex).html(lazyMarkup);
                    });
                }

            } else {
                //If no article, move the gallery under the h1
                if ($('.ad-gallery').length > 0) {
                    $('#articleText').prepend($('.ad-gallery'));

                }
            }
			
			//Set up AD Galleries
            var galleries = $('.ad-gallery').adGallery({
                loader_image: 'loader.gif',
                width: 580,
                // Width of the image, set to false and it will read the CSS width
                height: 504,
				thumb_opacity: 0.5,
                slideshow: {
                    enable: true,
                    autostart: true,
                    start_label: 'Play',
                    countdown_prefix: '<span style="display:none">',
                    // Wrap around the countdown
                    countdown_sufix: '</span>'
                },
                callbacks: {
                    //Fiddle with the design to effect designer's spec
                    init: function () {
                        $('.ad-nav').prependTo($('.ad-gallery'));
                        $('.ad-controls').prependTo($('.ad-gallery'));
                        $('.ad-slideshow-start').css('font-style', 'normal').css('text-decoration', 'underline');
                        $('.ad-slideshow-start').click(function () {
                            $('.ad-slideshow-start').css('text-decoration', 'underline');
                            $('.ad-slideshow-stop').css('text-decoration', 'none');
                        });

                        $('.ad-slideshow-stop').click(function () {
                            $('.ad-slideshow-stop').css('text-decoration', 'underline');
                            $('.ad-slideshow-start').css('text-decoration', 'none');
                        });

                        $('.ad-controls').after($('.ad-info'));
						$('.ad-slideshow-start').after('<span style="margin-left:5px;position:relative;top:-2px;font-size:12px;">|</span>');
						
						$('#page .ad-gallery .ad-back').html('<span class="nav-chevron">&laquo;</span>');
						$('#page .ad-gallery .ad-forward').html('<span class="nav-chevron">&raquo;</span>');

                    },
                    // This gets fired right after the new_image is fully visible
                    afterImageVisible: function () {
                        //Setup the caption of the first imag to appear on hover
                        if ($('.ad-image-description').length > 0) {
                            var desc = $('.ad-image-description');
                            var img_container = $('.ad-image');
                            img_container.unbind('mouseenter');
                            img_container.unbind('mouseleave');

                            img_container.bind('mouseenter', function () {
                                desc.css('display', 'block');
                                desc.css('bottom', '-' + desc[0].offsetHeight + 'px');
                                desc.animate({
                                    bottom: 0
                                }, 400 * 2);
                            });

                            img_container.bind('mouseleave', function () {
                                desc.stop();
                                desc.css('bottom', '-' + desc[0].offsetHeight + 'px');
                            });
                        };
                    }
                }
            });

            //Bylines come across with spaces in the class names, with illegal class names to boot
            //Need to code a solution so that they're styled properly
            $('.byline > p:first-child').removeClass().addClass('Byline1');
            $('.byline > p:first-child + p').removeClass().addClass('Byline2');
            $('.byline > p:first-child + p + p').css('display', 'none');


            //Check for a poll. If one exists, create a chart
            if ($('section#userPoll').length > 0) {


                if (numAnswers == 2) {
                    var total = parseInt(answer1) + parseInt(answer2);
                    var selector;
                    $('#tabs-1').length > 0 ? selector = '#tabs-1' : selector = '#main';

                    $(selector).append('<img class="pollResults" src="http://chart.googleapis.com/chart?cht=p3&chd=t:' + answer1 + ',' + answer2 + '&chs=400x200&chl=' + opt1 + '|' + opt2 + '&chf=bg,s,E9E4DC" title="- ' + opt1Label + ' (' + answer1 + ' votes) | - ' + opt2Label + ' (' + answer2 + ' votes)"/>' + '<br/>1) ' + opt1Label + ' (' + answer1 + ' votes)<br/>2) ' + opt2Label + ' (' + answer2 + ' votes)');
                } else if (numAnswers == 3) {
                    var total = parseInt(answer1) + parseInt(answer2) + parseInt(answer3);
                    var selector;
                    $('#tabs-1').length > 0 ? selector = '#tabs-1' : selector = '#main';

                    $(selector).append('<img class="pollResults" src="http://chart.googleapis.com/chart?cht=p3&chd=t:' + answer1 + ',' + answer2 + ',' + answer3 + '&chs=400x200&chl=' + opt1 + '|' + opt2 + '|' + opt3 + '&chf=bg,s,E9E4DC" title="- ' + opt1Label + ' (' + answer1 + ' votes) | - ' + opt2Label + ' (' + answer2 + ' votes) | - ' + opt3Label + ' (' + answer3 + ' votes)"/>' + '<br/>1) ' + opt1Label + ' (' + answer1 + ' votes)<br/>2) ' + opt2Label + ' (' + answer2 + ' votes)<br/>3) ' + opt3Label + ' (' + answer3 + ' votes)');
                } else if (numAnswers == 4) {
                    var total = parseInt(answer1) + parseInt(answer2) + parseInt(answer3) + parseInt(answer4);
                    var selector;
                    $('#tabs-1').length > 0 ? selector = '#tabs-1' : selector = '#main';

                    $(selector).append('<img class="pollResults" src="http://chart.googleapis.com/chart?cht=p3&chd=t:' + answer1 + ',' + answer2 + ',' + answer3 + ',' + answer4 + '&chs=400x200&chl=' + opt1 + '|' + opt2 + '|' + opt3 + '|' + opt4 + '&chf=bg,s,E9E4DC" title="- ' + opt1Label + ' (' + answer1 + ' votes) | - ' + opt2Label + ' (' + answer2 + ' votes) | - ' + opt3Label + ' (' + answer3 + ' votes) | - ' + opt4Label + ' (' + answer4 + ' votes)"/>' + '<br/>1) ' + opt1Label + ' (' + answer1 + ' votes)<br/>2) ' + opt2Label + ' (' + answer2 + ' votes)<br/>3) ' + opt3Label + ' (' + answer3 + ' votes)<br/>4) ' + opt4Label + ' (' + answer4 + ' votes)');
                }
            }
			
			//Show comments form on demand
			$('#comments').click(
				function(){
					$('#DefaultComments').css('display', 'block');
					$('#comments').hide();
					return false;
					}									
				);
			
			
			//Copy the comment count to the link tray
			var commentCount = $('#commentCount span').text();
			var commentText = " Comment";
			if(commentCount != "1"){
				commentText += "s";
			}
			$('.comment-link a').text(commentCount + " " + commentText);
			
			//Remove border from last comment
			$('.comment').last().css('border-width', '0');
			
			 //Remove the figure entirely if no image exists
            if ($('figure#main-photo img').length === 0) {
                $('figure#main-photo').remove();
            }
        },
		//French manipulations
		frenchInit:function(){
			//Translate tabs
			$('.ui-tabs-nav li a').each(
				function(){
					if($(this).text() === 'Photo Gallery'){
						$(this).text('Galerie photo');
					}
					
					if($(this).text() === 'Video'){
						$(this).text('Vidéo');
					}
					
					if($(this).text() === 'Comments'){
						$(this).text('Commentaires');
					}					
				});
			
			//Copy the comment count to the link tray
			var commentCount = $('#commentCount span').text();
			var commentText = " Commentaire";
			if(commentCount != "1"){
				commentText += "s";
			}
			$('.comment-link a').text(commentCount + " " + commentText);
			
			//Translate flagging text
			$('.flag a').text("Signaler un abus");
			
			$('.comment .commentHeader em').each(function(){
														  
				//Translate timestamp for comments
				var timestamp = $(this).text();
				var datePattern = new RegExp('^([\\s\\S]*? \\d\\d\\d\\d) ([\\s\\S]*)$', 'i');

				var extractedDate;
				var extractedTime;
				var newTimestamp;
				
				if(datePattern.test(timestamp)){
					extractedDate = timestamp.match(datePattern)[1];
					extractedTime = timestamp.match(datePattern)[2];
					
					//Translate date				
					var d = new Date(extractedDate);
					if (d) {
						newTimestamp = 'le ' + d.toFrench();
					}					
					
					//Translate time
					var timePattern = new RegExp('^(\\d\\d?):(\\d\\d)[\\s\\S]*?(\\w\\w)$', 'i')
					if(timePattern.test(extractedTime)){
						var hour = parseInt(extractedTime.match(timePattern)[1]);
						hour = extractedTime.match(timePattern)[3] === 'PM' ? hour + 12 : hour;
						var minute = extractedTime.match(timePattern)[2];
						newTimestamp += ' ' + hour + 'h' + minute;
					}
					
					$(this).text(newTimestamp);
				}				
				
			});
		},

        windowInit: function () {
			
            if ($('figure#main-photo img')[0]) {
                var imgWidth = $('figure#main-photo img')[0].naturalWidth || $('figure#main-photo img')[0].width;
                //If image is 3 columns, move it into the article area
                if (imgWidth != 0 && imgWidth <= 580) {
                    $('figure#main-photo img').css('left', '0');
					//Reduce size of main figure wrapper
                    $('figure#main-photo').css('width', imgWidth +'px').css('border', '0');
					//Reduce size of tabs to match
					$('#page #main-section .ui-tabs-nav').css('width', imgWidth + 'px');
                    $('#mainContainer').prepend($('figure#main-photo'));
                    $('#mainContainer').prepend($('h1#mainLabel'));
                }
				
				//If image has old portrait dimension width is 460px, reduce to 430px per newest spec
				if(imgWidth == 460){
					$('figure#main-photo').css('width', '430px');
					$('#page #main-section .ui-tabs-nav').css('width', '430px');
					var imgHeight = $('figure#main-photo img')[0].naturalHeight || $('figure#main-photo img')[0].height;
					
					$('figure#main-photo img').width(430);
					$('figure#main-photo img').height(430/460 * imgHeight);
				}
				
            }
			
			//The tabs have been re-sized by this point, make visible
			$('#page #main-section .ui-tabs-nav').css('left', '0');

			//Resize gallery thumbs to 60px high	
			$('.ad-thumb-list img').each(

				function (index) {
				   var imgHeight = this.naturalHeight || this.height;
					var imgWidth = this.naturalWidth || this.width;
					if(imgHeight > 0){
						var ratio = 60/imgHeight;
						var newWidth = imgWidth * ratio;
						this.width = newWidth;
						this.height = 60;
					}
    		});
			$('.ad-thumb-list').css('left','0');
			
        }
    }
}

//Fades ticker stories in and out
function tickerSwap() {
    var c;
    $('.breaking-news > article').each(

    function (index) {
        if ($(this).is(':visible')) {
            c = index;
            $(this).fadeOut(100);
        }
    });
    if (c === ($('.breaking-news > article').length - 1)) {
        c = -1;
    }
    //Don't pass c++ as slice
    $($('.breaking-news > article')[c + 1]).fadeIn(600);
}

//Creates French date
Date.prototype.toFrench = function () {
	var months = ["janvier", "f\u00E9vrier", "mars", "avril", "mai", "juin", "juillet", "ao\u00FBt", "septembre", "octobre", "novembre", "d\u00E9cembre"];
	var date = this.getDate();
	if (date === 1) {
		date += "<sup>er</sup>";
	}
	var output = date + " " + months[this.getMonth()] + " " + this.getFullYear();
	return output;
}
