// JavaScript Document

// global vars
var path = window.location.href;
var host = window.location.hostname;

$(document).ready(function(){
    initExtLogin();
	resetContentHeight();
	resetSubnavWidths();

	initSearchEffects();
	initFancyLogin();	
	
	alignGridPages();
	alignCommentTextareaWidths();
	alignFeaturedBoxes();
	alignFeaturedSoloBox();
	alignRelatedArticles();
	alignCategoryHeadlineStories();
	alignArchiveStories();
	alignVideoNav();
	
    initPrint();
    
	window.onload = function(){
		// Realign after content images have loaded:
		setTimeout(200,'resetContentHeight()');
	};
});

function initExtLogin() {
    $('.LoginFacebookButton').live('click', function(e) {
        e.preventDefault();
        var pattern = /facebook/;
        var url = "http://"+host+"/validate/facebook?ajax=true";
        $.post(url, function(response) {
            if(response.match(pattern)) {
                window.open(response, 'Facebook Login', 'width=500,height=550,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=yes');
            } else {
                window.location.reload();
            }
        });
    });
    $('.LoginTwitterButton').live('click', function(e) {
        e.preventDefault();
        var pattern = /oauth/;
        var url = "http://"+host+"/validate/twitter";
        $.post(url, function(response) {
            if(response.match(pattern)) {
                window.open(response, 'Twitter Login', 'width=500,height=550,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=yes');
            } else {
                window.location.reload();
            }
        });
    });
}

$('.LikeButton').live('click', function(e) {
    e.preventDefault();
    var url = $(this).attr('href');
    var count = $('.Likes');
    $.getJSON(url, function(data) {
        if(data.score == 1) {
            text = 'person likes this article';
            count.text(data.score+" "+text);
        } 
        else if(data.score > 1) {
            text = 'people like this article';
            count.text(data.score+" "+text);
        }
        else {
            count.text('');
        }
        if(data.error) {
            alert(data.error);
        }
    });
});

$('.DislikeButton').live('click', function(e) {
    e.preventDefault();
    var url = $(this).attr('href');
    var count = $('.Likes');
    $.getJSON(url, function(data) {
        if(data.score == 1) {
            text = 'person likes this article';
            count.text(data.score+" "+text);
        } 
        else if(data.score > 1) {
            text = 'people like this article';
            count.text(data.score+" "+text);
        }
        else {
            count.text('');
        }
        if(data.error) {
            alert(data.error);
        }
    });
});

/* Close Fancybox (Close icon) */
$('.close_icon').live('click',function(){
	parent.$.fancybox.close();
});

$("#user_submission_submission").live('keydown', function(ev){
	var limit = 300;
	var count = $(this).val().split(' ').length;
	$("#word_count").removeClass('limit').find("span").html(limit - count);

	if($(this).val() == '') {
		$("#word_count").removeClass('limit').find("span").html(limit);
	}	

	if(limit - count < 0) {
		$("#word_count").addClass('limit').find("span").html('0');
	}

	if(limit - count < 0 && !is_approved_keycode(ev.keyCode)) {
		ev.preventDefault();
		var words = $("#user_submission_submission").val().split(' ');
		var newVal = '';
		for(var i = 0; i < limit; i++) {
			newVal += words[i] + ' ';
		}
		$("#user_submission_submission").val(newVal);
	}
});

function is_approved_keycode(keyCode) {
	if(keyCode == 8 ||
	   keyCode == 91 ||
	   keyCode == 37 ||
	   keyCode == 38 ||
	   keyCode == 39 ||
	   keyCode == 40
	) {
		return true;
	}else {
		return false;
	}
}

function resetSubnavWidths(){
	//$('#NNavigationList li > ul').each(function(index){});
	
	//var p = $("p:first");
	//$("p:last").text( "outerWidth:" + p.outerWidth()+ " , outerWidth(true):" + p.outerWidth(true) );
}
function resetContentHeight(){
	idealHeight   = $('#NContent').outerHeight();
	sidebarHeight = $('#NContentSidebar').outerHeight();
	contentHeight = $('#NContentMain').outerHeight();
	if ( sidebarHeight > contentHeight ) {
		$('#NContentMain').height($('#NContent').height());
	}
}

function initSearchEffects(){
	$('#PrimarySearchLink').click(function(e){
		e.preventDefault();
		$(this).fadeOut(250,function(){
			$( $(this).attr('href') ).fadeIn(250,function(){
				$(this).parent().find('input:first').focus();
			});
		});
	});
}

function initFancyLogin(){
	$('a[href^="/ajax_login"],a[href^="/app_dev.php/ajax_login"]').fancybox({
		'overlayColor'		: '#fff',
		'showCloseButton'   : false,
		'overlayOpacity'	: 0.9
	});
}

function alignCommentTextareaWidths(){
	$('.CommentComposeWidget').each(function(i){
		newwidth = $(this).find('.CommentComposeFormContainer').outerWidth() - $(this).find('.CommentComposeAuthorAvatar').outerWidth();
		oldpadding = $(this).find('.CommentComposeField').outerWidth() - $(this).find('.CommentComposeField').width();
		$(this).find('.CommentComposeContainer').width(newwidth);
		$(this).find('.CommentComposeField').width(newwidth-oldpadding);
		
	});
}

function alignGridPages(){
	newheight = 0;
	$('.gridpage > div > div').each(function(i){
		if( $(this).height() > newheight ) {
			newheight = $(this).height();
		}
	});
	
	$('.gridpage > div > div').each(function(i){
		$(this).height( newheight );
	});
}

function alignFeaturedBoxes(){
	if($("body").hasClass('mobile')) {
		return false;
	}
	var PrimaryBrief          = $('.FeaturedPanel .PanelLarge:first');
	var firstBrief            = $('.FeaturedPanel .PanelMedium:first');
	var lastBrief             = $('.FeaturedPanel .StoryBrief.PanelMedium:last');
	if ( !PrimaryBrief.length || !firstBrief.length || !lastBrief.length ) return;
	
	var PrimaryBriefDesc      = PrimaryBrief.find('.Description');
	var PrimaryBriefShift     = PrimaryBrief.find('.ShiftWrapper');
	var PrimaryBriefContext   = PrimaryBrief.find('.ContextBar');
	var firstBriefPos         = firstBrief.position();
	var lastBriefPos          = lastBrief.position();
	var lastBriefContextPos   = lastBrief.find('.ContextBar').position();
	var newHeight             = lastBriefPos.top + lastBrief.outerHeight() - firstBriefPos.top;
	var descriptionHeight     = newHeight - PrimaryBriefShift.height() - PrimaryBriefDesc.outerHeight() + PrimaryBriefDesc.height() - PrimaryBriefContext.outerHeight() ;
	var descriptionLineHeight = PrimaryBriefDesc.length > 0 ? PrimaryBriefDesc.css('line-height').replace(/[^0-9]/g, '') : '';
	var lines                 = Math.floor( descriptionHeight / descriptionLineHeight );
	var linesEpx              = descriptionHeight % descriptionLineHeight;

	// Set the Panel container height
	PrimaryBrief.css( 'overflow', 'hidden' );
	PrimaryBrief.height( newHeight );
	
	// Set the Description container height
	PrimaryBriefDesc.height( descriptionHeight - 5 );
	
	// If we don't have enough room to show a full line, hide it
	PrimaryBriefDesc.find('div').css( 'overflow', 'hidden' );
	PrimaryBriefDesc.find('div').height( lines * descriptionLineHeight );
}

function alignFeaturedSoloBox(){
	var PrimaryBrief          = $('.FeaturedPanel .PanelSolo');
	if ( !PrimaryBrief.length ) return;
	
	var PrimaryBriefWindow    = $('.FeaturedStoryWindow');
	var PrimaryBriefHeader    = $('.FeaturedStoryWindow .HeaderInfo');
	var PrimaryBriefDesc      = PrimaryBrief.find('.Description');
	
	var headerHeight          = PrimaryBriefHeader.outerHeight();
	var descriptionHeight     = PrimaryBriefDesc.height( PrimaryBriefWindow.height() - headerHeight + PrimaryBriefDesc.height() - PrimaryBriefDesc.outerHeight() ).height();
	var descriptionTHeight    = PrimaryBriefDesc.outerHeight();
	var descriptionLineHeight = PrimaryBriefDesc.css('line-height').replace(/[^0-9]/g, '');
	var lines                 = Math.floor( descriptionTHeight / descriptionLineHeight );
	var linesEpx              = descriptionHeight % descriptionLineHeight;
	
	// If we don't have enough room to show a full line, hide it
	PrimaryBriefDesc.find('div').css( 'overflow', 'hidden' );
	PrimaryBriefDesc.find('div').height( lines * descriptionLineHeight );
}

function alignRelatedArticles(){
	var content = $('.Story .ArticleCopy');
	var related = $('.RelatedArticles');
	if( related && content ){
		if( target = content.find('.Copy > p') ){
			target.each(function(i){
				if(i==0){
					related.insertBefore($(this));
				}
			});
		}
	}
}

function alignCategoryHeadlineStories(){
	$(".StoryIndex").each(function(){
		var maxHeight = 0;
		
		$(this).find(".StoryBrief").each(function(){
			$(this).find(".Description").each(function(){
				var description = $(this);
				description.after("<div></div>");
				description.next().css('display', 'none').html(description.html());
				var descriptionArray = description.html().split(' ');
				var newHtml = '';
				for(var i = 0; i < 16; i++) {
					if(descriptionArray[i]) {
						newHtml += descriptionArray[i] + ' ';
					}
				}
				description.html(newHtml);
			});
			if($(this).height() > maxHeight) {
				maxHeight = $(this).height();
			}
		});
		
		$(this).find(".StoryBrief").height(maxHeight + 18);
		
		var panelWindow = $(this).find('.PanelWindow');
		$(this).find(".StoryBrief").has(".Description").each(function(){
			var whiteSpace = $(this).height() - panelWindow.height();
			whiteSpace -= 18;
			var description = $(this).find(".Description");
			var lineHeight = parseInt(description.css('line-height').replace('px', ''));
			if(whiteSpace >= lineHeight) {
				var newDescriptionHeight = description.height() + whiteSpace;
				var fullDescriptionArray = description.next().html().split(' ');
				description.html('');
				var newHtml = '';
				var i = 0;
				while(i < fullDescriptionArray.length && description.prop('scrollHeight') <= newDescriptionHeight) {
					newHtml += fullDescriptionArray[i] + ' ';
					description.html(newHtml);
					i++;
				}
				for(var x = i; x < i + 1; x++) {
					if(fullDescriptionArray[x]) {
						newHtml += fullDescriptionArray[x] + ' ';
						description.html(newHtml);
					}
				}
			}
			if(description.html() != '' && description.html().replace(/\s/g,'') != '') {
				var link = $(this).find("h3.Title").find("a").clone();
				link.html('...');
				description.append(link);
			}
			
			panelWindow.height( maxHeight + 5 );
		});
		
	});
}
	
function alignArchiveStories(){
	if($("#CategoryArchiveStories").length > 0) {
		$(".CategoryArchive").each(function(){
			var height = $(this).find(".Social").prop('scrollHeight') - $(this).find("h2.Title").height();
			var lineHeight = parseInt($(this).find(".Description").css('line-height').replace('px', ''));
			height = Math.floor(height/lineHeight);
			height++;
			height = height * lineHeight;
			height -= 25;
			$(this).find(".Description").height(height);

			var description = $(this).find(".Description");
			var readMore = description.find("a.read-more");
			description.find("a.read-more").remove();
			var html = description.html();
			var htmlArray = html.split(' ');
			description.html('');
			description.height(0);
			var newHtml = '';
			var i = 0;
			while(i < htmlArray.length && description.prop('scrollHeight') <= height) {
				if(htmlArray[i]) {
					newHtml += htmlArray[i] + ' ';
					description.html(newHtml);
				}
				i++;
			}
			for(var x = i; x < i + 18; x++) {
				if(htmlArray[x]) {
					newHtml += htmlArray[x] + ' ';
					description.html(newHtml);
				}
			}
			description.height(description.prop('scrollHeight'));
			description.append(readMore)
		});
	}
}

function alignVideoNav(){
	var videosNav = $("#NContentSidebar .SidebarWidget .video-nav");
	if( videosNav ){
		var parentWidth = videosNav.parent().width();
		videosNav.css('padding-left', (parentWidth - videosNav.width()) / 2);
	}
}

function initPrint() {
    $('#print').live('click', function(e) {
        e.preventDefault();    
        window.open(''+self.location+'print', 'Article Print', 'width=700, height=1000');
    });
}

