function NWCommon()
{
	this.allowHidePreview = true;
}

NWCommon.prototype.setCookie = function(name,value,days)
{	
	if (days)
	{
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}	

NWCommon.prototype.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;
}

NWCommon.prototype.markRead = function(linkElement, boolRemember)
{
	if (boolRemember)
	{
		objNWCommon.setCookie(linkElement.id,1,90);
	}
	$(linkElement).addClass("readLink");
}

NWCommon.prototype.markReadLinks = function()
{
	var links = document.getElementsByTagName('a');
	for(var i = 0; i < links.length; i++)
	{
		if (objNWCommon.readCookie(links[i].id) == 1)
		{
			$(links[i]).addClass ("readLink");
		} 
	}
}

NWCommon.prototype.embed = function(strEmbed, parent)
{
	if (parent != undefined && $('#'+parent))
	{
		parent.innerHTML = strEmbed;
	}
	else
	{
		document.writeln(strEmbed);
	}
}

NWCommon.prototype.popout = function(strEmbed, strTitle, width, height)
{
		//pageTracker._trackEvent('Media', 'Popout', strTitle);
		popout = window.open('', 'nw_enclosure_popout', 'width='+width+',height='+height+',status=0,toolbar=0,location=0,menubar=0,resizable=1');
		popdoc = popout.document;
		popdoc.write('<html><head><title>'+strTitle+'</title></head><body style="margin: 0; padding: 10px 3px 3px 3px;">'+strEmbed+'</body></html>');
}

NWCommon.prototype.toggleEmailForm = function(strId)
{
	//pageTracker._trackEvent('Ajax', 'Toggle Email Form', strId);
	var form = $('#email_form_'+strId);
	if (form.style.display!='block')
	{
		form.style.display='block'
		$('#email_address_'+strId).focus();
	}
	else
	{
		form.style.display='none'
	}
}

NWCommon.prototype.toggleEmbed = function(strId)
{
	//pageTracker._trackEvent('Ajax', 'Toggle Embed Form', strId);
	var embedContainer = $('#embed_'+strId);
	if (embedContainer.style.display!='block')
	{
		embedContainer.style.display='block'
		$('#embed_code_'+strId).focus();
		$('#embed_code_'+strId).select();
	}
	else
	{
		embedContainer.style.display='none'
	}
}

NWCommon.prototype.showPreference = function()
{
	//pageTracker._trackEvent('Ajax', 'Show Preferences Dialog');
	$("#overlay").css('height', document.getElementsByTagName('body')[0].offsetHeight + 'px');
	$("#overlay").css('display','block');
	$('#preferenceDialog').css('display',"block");
}

NWCommon.prototype.hidePreference = function()
{
	$('#preferenceDialog').css('display',"none");
	$("#overlay").css('display','none');
}

NWCommon.prototype.setPreferences = function()
{
	previewOption = $('#titleClickPreview');
	pageOption = $('#titleClickPreviewPage');
	if (previewOption.checked)
	{
		//pageTracker._trackEvent('Ajax', 'Set Preview Preference', 'true');
		this.setCookie('titleClick','preview');
		this.titleClick = 'preview';
	}
	if (pageOption.checked)
	{
		//pageTracker._trackEvent('Ajax', 'Set Preview Preference', 'false');
		this.setCookie('titleClick','page');
		this.titleClick = 'page';
	}
}

NWCommon.prototype.loadPreferences = function()
{
	previewOption = $('#titleClickPreview');
	pageOption = $('#titleClickPreviewPage');
	this.titleClick = this.readCookie('titleClick');
	if (this.titleClick == 'preview')
	{
		previewOption.checked = true;
	}
	else if (this.titleClick == 'page')
	{
		pageOption.checked = true;
	}
	else
	{
		previewOption.checked = true;
		this.setCookie('titleClick','preview');
		this.titleClick = 'preview';
	}
}

NWCommon.prototype.showSearch = function()
{
	//pageTracker._trackEvent('Ajax', 'Show Search Dialog');
	$("#overlay").style.height = document.getElementsByTagName('body')[0].offsetHeight + 'px';
	$("#overlay").style.display='block';
	$('#searchDialog').style.display="block";
}

NWCommon.prototype.hideSearch = function()
{
	$('#searchDialog').style.display="none";
	$("#overlay").style.display='none';
}

NWCommon.prototype.loadPreview = function(link, url, originUrl)
{
	var context = this;
	var link = $(link);
	var previewBox = $('#previewBox');
	var previewContent = $('#previewContent');
	var content = $('#content');
	var scrollEl = scrollableElement('html', 'body');
	var win = $(window);
	
	$('.postSelected').removeClass('postSelected');
	link.parents(".post").first().addClass('postSelected');
	var column = link.parents(".box").first().attr('id');
	
	previewContent.scrollTop(0);
	previewBox.hide();
	
	previewContent.empty().append('<div id="loading"><img src="'+IMG_URL+'/loading.gif" /></div>');
	
	if ($('.box').not('#'+column).not('.infoBox').not('#previewBox').size())
	{
		$('.box').not('#'+column).not('.infoBox').not('#previewBox').fadeOut(250, function()
		{	
			if (link.offset().top + win.height() - link.parents('.post').first().height() < content.offset().top + content.height())
			{
				$(scrollEl).animate({scrollTop: link.offset().top - 30}, 350, function()
				{
					context.showPreviewBox();
				})
			}
			else if (content.height() > win.height() )//&& win.scrollTop() +win.height() >= content.offset().top + content.innerHeight())
			{
				$(scrollEl).animate({scrollTop: content.offset().top + content.height() - win.height() + 10}, 350, function()
				{
					context.showPreviewBox();
				})
			}
			else
			{
				context.showPreviewBox();
			}
		});
	}
	else
	{
		$('#'+column+'.box.box1').removeClass('box1').addClass('box3', 250)
			
		if (link.offset().top + win.height() - link.parents('.post').first().height() < content.offset().top + content.height())
		{
			$(scrollEl).animate({scrollTop: link.offset().top - 30}, 350, function()
			{
				context.showPreviewBox();
			})
		}
		else if (content.height() > win.height() )//&& win.scrollTop() +win.height() >= content.offset().top + content.innerHeight())
		{
			$(scrollEl).animate({scrollTop: content.offset().top + content.height() - win.height() + 10}, 350, function()
			{
				context.showPreviewBox();
			})
		}
		else
		{
			context.showPreviewBox();
		}
	}
	$.ajax({ url: url + '/preview',
			 context: document.body,
			 success: function(data, textStatus, XMLHttpRequest){objNWCommon.displayPreview(XMLHttpRequest);}
	  	   });
}

NWCommon.prototype.showPreviewBox = function()
{
	var loading = $('#loading');
	$('#previewBox').show();
	this.adjustPreviewSize();
	loading.css('margin-top', $('#previewContent').height()/2 - loading.height()/2 - 10);
	this.adjustPreviewPos();
}

NWCommon.prototype.hidePreviewBox = function()
{
	if (this.allowHidePreview)
	{
		$('.popup').css('display','none');
		$('#previewBox').fadeOut(250, function()
		{
			//$('.postSelected').removeClass('postSelected');
			$('.box').not('.infoBox').not('#previewBox').fadeIn(250);
		});	
	}
}

NWCommon.prototype.displayPreview = function(objRequest)
{
  //pageTracker._trackEvent('Ajax', 'Post Preview', xajax.config.requestURI);
	var previewContent = $('#previewContent');
	previewContent.empty().append(objRequest.responseText);
	previewContent.focus();
	previewContent.scrollTop(0);
   gapi.plusone.go();
}

NWCommon.prototype.adjustPreviewSize = function()
{
	var previewBox = $('#previewBox');
	var win = $(window);
	var content = $('#content');
	if (content.height() < win.height())
	{
		var previewHeight = content.height() - 57;
	}
	else
	{
		var previewHeight = win.height() - $('#previewHeader').height() - 55;
	}
	previewBox.css('position', 'fixed');
	$('#previewContent').css('height', previewHeight);
	previewBox.css('top', -5);
}

NWCommon.prototype.adjustPreviewPos = function()
{
	var previewBox = $('#previewBox');
	var content = $('#content');
	var win = $(window);
	if (win.scrollTop() < content.offset().top)
	{
		previewBox.css('position', 'absolute');
		previewBox.css('top', content.offset().top - 10);
	}
	else if (win.scrollTop() > content.offset().top + content.innerHeight() - win.height())
	{
		previewBox.css('position', 'absolute');
		previewBox.css('top', content.offset().top + content.innerHeight() - previewBox.innerHeight() - 40);
	}
	else
	{
		this.adjustPreviewSize();
	}
}

NWCommon.prototype.nextPost = function()
{
	$('.popup').css('display','none');
	var nextPost = $('.postSelected').next();
	if (nextPost.hasClass('dateDivider'))
	{
		nextPost = nextPost.next();
	}
	nextPost.find('.postTitleLink').first().trigger('click');
	
}

NWCommon.prototype.previousPost = function()
{
	$('.popup').css('display','none');
	var prevPost = $('.postSelected').prev();
	if (prevPost.hasClass('dateDivider'))
	{
		prevPost = prevPost.prev();
	}
	prevPost.find('.postTitleLink').first().trigger('click');
}

NWCommon.prototype.showPopup = function(id, el, position)
{
	//pageTracker._trackEvent('Popup', 'Show Popup '+id);
	
	$('.popup').css('display','none');
	el = $(el);
	var popup = $('#'+id);
	popup.find('.tipText').text(el.text());
	popup.css('display','block');
	var o = el.offset();
	popup.css('left', o.left);
	if (position == undefined)
	{
		popup.css('top', o.top + el.height() + "px");
	}
	if (position == 'above')
	{
		popup.css('top', o.top - popup.height() + 5 + "px");
	}
	popup.css('marginLeft', -1 * (popup.width() / 2) + (el.width() / 2) + "px");
	this.popupEl = el;
}

NWCommon.prototype.enableTip = function(id, el, position)
{ 
	$(el).mouseenter(function(e){objNWCommon.showPopup(id, this, position);});
	$(el).mouseleave(function(){$('.popup').css('display','none');});
}

NWCommon.prototype.matchColumnHeights = function(strClassName)
{
	var maxHeight = 0;
	$('.'+strClassName).each(function(){
		if (!$(this).hasClass('short'))
		{
			if ($(this).height() > maxHeight)
			{
				maxHeight = $(this).height();
			}
		}
	});
	$('.'+strClassName).not('.short').css('min-height', maxHeight + 'px');	
}

NWCommon.prototype.openPostOrigin = function()
{
	var url = $('#postSourceLink').attr('href');
	if (url != undefined && url != '' && url.indexOf('http://') == 0)
	{
		window.open(url,'_blank');
		window.focus();
	}
}

var objNWCommon = new NWCommon();

$(window).resize(function() 
{
  objNWCommon.adjustPreviewSize();
  objNWCommon.adjustPreviewPos();
});

$(window).scroll(function ()
{ 
	objNWCommon.adjustPreviewPos();
});

$(document).keydown(function (e)
{ 
	var key = String.fromCharCode(e.which);
	if (key  == 'n' || key == 'N' || key == 'j' || key == 'J')
	{
		objNWCommon.nextPost();
	}
	if (key  == 'p' || key == 'P' || key == 'k' || key == 'K')
	{
		objNWCommon.previousPost();
	}
	if (key  == 'l' || key == 'L')
	{
		objNWCommon.openPostOrigin();
	}
	if (e.which == 27)
	{
		objNWCommon.hidePreviewBox();
	}
});

 
// use the first element that is "scrollable"
function scrollableElement(els) {
  for (var i = 0, argLength = arguments.length; i <argLength; i++) {
    var el = arguments[i],
        $scrollElement = $(el);
    if ($scrollElement.scrollTop()> 0) {
      return el;
    } else {
      $scrollElement.scrollTop(1);
      var isScrollable = $scrollElement.scrollTop()> 0;
      $scrollElement.scrollTop(0);
      if (isScrollable) {
        return el;
      }
    }
  }
  return [];
}

$(document).ready(function()
{
	$('.popup').mouseleave(function(){$('.popup').css('display','none');});
	objNWCommon.enableTip('LDSBlogsPopup', '#box-lds-blogs h2', 'above');
	objNWCommon.enableTip('MormonBlogsPopup', '#box-mormon-bloggers h2', 'above');
	objNWCommon.enableTip('MissionaryBlogsPopup', '#box-missionary-blogs h2', 'above');
	objNWCommon.enableTip('LDSOfficialPopup', '#box-lds-official h2', 'above');
	objNWCommon.enableTip('ConferencePopup', '#box-general-conference h2', 'above');
	objNWCommon.enableTip('datePopup', '.dateDivider a', 'above');
	objNWCommon.enableTip('prevPopup', '#preview-prev');
	objNWCommon.enableTip('nextPopup', '#preview-next');
	objNWCommon.enableTip('closePopup', '#preview-close');
        gapi.plusone.go();
});

