/**
 * NNPages functionality
 */

/**
 * Initialize NNPages obj when jQuery raises 'document ready'
 */
$(function()
{
	NNPages.Initialize();
});


/**
* NNPages static object declaration.
* Contains logic for site
*/
NNPages = function() { };

// vars
NNPages._isEnabled = true;
NNPages._isInitialized = false;
NNPages._newslentaFullLoaded = false;

// constants
NNPages._weatherCityHash =
{
	26850 : 'Ì³íñê',
	33008 : 'Áðýñò',
	26666 : 'Â³öåáñê',
	33041 : 'Ãîìåëü',
	26825 : 'Ãðîäíà',
	26863 : 'Ìàã³ë¸¢'
};



/**
*  Initialize
*/
NNPages.Initialize = function()
{
	// bind global event handlers
	$(window).bind("resize", NNPages.OnWindowResize);
	$("body").click(function(event) { NNPages.OnCommonClick(event); });

	// bind local event handlers to elements
	/*$("#popularArticlesTab").click(function(event)
		{
			$("#popularArticlesTab").addClass('active');
			$("#popularDiscussionsTab").removeClass('active');

			$("#popularArticlesList").css("display", "");
			$("#popularDiscussionsList").css("display", "none");
		});
	$("#popularDiscussionsTab").click(function(event)
		{
			$("#popularDiscussionsTab").addClass('active');
			$("#popularArticlesTab").removeClass('active');

			$("#popularDiscussionsList").css("display", "");
			$("#popularArticlesList").css("display", "none");
		});

	NNPages.InitNewsLenta();
	NNPages.AttachCalendarHandlers();*/

	//$('#mainmenu').droppy();

	NNPages._isInitialized = true;

	NNPages.ReadDefaultWeatherForecast();
};


/* Global handlers ---------------------------------------------------------------------*/

/**
* Handler for body.click
*/
NNPages.OnCommonClick = function(event)
{
	var clickedLink = $(event.target).closest("a");
	if (clickedLink.length > 0)
	{
		NNPages.ProcessCommonLinkClick(clickedLink.get(0));
	}
};

/**
* Handler for window.resize
*/
NNPages.OnWindowResize = function()
{
};


/**
*  Attach calendar handlers
*/
NNPages.AttachCalendarHandlers = function()
{
	$("#calendarPrevMonth").click(function(event)
		{
			NNPages.SendCalendarRequestToServer(
				{ command: 'calendarChangeMonth',
				  c2: 'calmonprev'
				}
			);
			return false;
		});
	$("#calendarNextMonth").click(function(event)
		{
			NNPages.SendCalendarRequestToServer(
				{ command: 'calendarChangeMonth',
				  c2: 'calmonnext'
				}
			);
			return false;
		});
};

/* Common functionality  ---------------------------------------------------------------------*/

/**
* Process common click on links
*/
NNPages.ProcessCommonLinkClick = function(target)
{
	var href = $(target).attr("href");
	var hashText, hashCommand, hashCommandArg;

	// extract hash command
	if (href.indexOf('#') > -1)
	{
		hashText = href.substr(href.indexOf('#') + 1);

		if (hashText)
		{
			if (hashText.indexOf('-') > -1)
			{
				hashCommand = hashText.substr(0, hashText.indexOf('-'));
				hashCommandArg = hashText.substr(hashText.indexOf('-') + 1);
			}
			else
			{
				hashCommand = hashText;
			}
		}
	}

	// process hash command
	if (hashCommand)
	{
		switch (hashCommand)
		{
			case 'weather':
				NNPages.UpdateWeatherForecast(hashCommandArg);
				break;

		}
	}
};


/* News lenta  ---------------------------------------------------------------------*/

/**
*  Init news lenta
*/
NNPages.InitNewsLenta = function()
{
	NNPages.AttachNewsLentaHandlers();
	NNPages.AdjustNewsLentaButtons();
};

/**
*  Attach news lenta handlers
*/
NNPages.AttachNewsLentaHandlers = function()
{
	$("#newsLentaButUp").click(function(event) { return NNPages.ProcessNewsLentaUp(event); });
	$("#newsLentaButDown").click(function(event) { return NNPages.ProcessNewsLentaDown(event); });
};

/**
*  Process news lenta up click
*/
NNPages.ProcessNewsLentaUp = function()
{
	/*
	NNPages.SendNewsLentaRequestToServer(
		{ command: 'newslenta',
		  startIndex: $("#newsLentaButUp").attr('startIndex'),
		  pageSize: $("#newsLentaButUp").attr('pageSize')
		}
	);
	*/

	$("#newsLentaListContainer")
		.height($("#newsLentaListContainer").height());
		//.css('position', 'relative')
		//.css('overflow', 'hidden');

	if ($("#newsLentaList").position().top < 0)
	{
		//$("#newsLentaList")
		//	.css('position', 'relative');
			//.css('border', '1px solid green');

		$("#newsLentaList").animate({'top': NNPages.FindPositionNewsLentaUp()}, function() { NNPages.AdjustNewsLentaButtons(); });
	}

	return false;
};

/**
*  Process news lenta down click
*/
NNPages.ProcessNewsLentaDown = function()
{
	/*
	NNPages.SendNewsLentaRequestToServer(
		{ command: 'newslenta',
		  startIndex: $("#newsLentaButDown").attr('startIndex'),
		  pageSize: $("#newsLentaButDown").attr('pageSize')
		}
	);
	*/

	$("#newsLentaListContainer")
		.height($("#newsLentaListContainer").height());
		//.css('position', 'relative')
		//.css('overflow', 'hidden');
	//$("#newsLentaList")
	//	.css('position', 'relative');

	if (!NNPages._newslentaFullLoaded)
	{
		NNPages.LoadNewsLenta();
		return;
	}

	var top = NNPages.FindPositionNewsLentaDown();
	if (top < 0)
		$("#newsLentaList").animate({'top': top}, function() { NNPages.AdjustNewsLentaButtons(); });


	return false;
};

/**
*  Find element/position for lenta up
*/
NNPages.FindPositionNewsLentaUp = function()
{
	var newTopPos = 0;

	var listTop = $("#newsLentaList").position().top;

	$("#newsLentaList li").each(function(index)
	{
		var liTop = $(this).position().top;
		var liHeight = $(this).outerHeight();

		//if ((listTop + liTop + liHeight) <= 0)
		if ((listTop + liTop) < 0)
			//newTopPos = listTop + liTop;
			newTopPos = -liTop;
		else
			return false;
	});

	return newTopPos;
};

/**
*  Find element/position for lenta down
*/
NNPages.FindPositionNewsLentaDown = function()
{
	var newTopPos = 0;

	var listTop = $("#newsLentaList").position().top;

	$("#newsLentaList li").each(function(index)
	{
		var liTop = $(this).position().top;
		var liHeight = $(this).outerHeight();

		if ((listTop + liTop) > 0)
		{
			newTopPos = -liTop;
			return false;
		}
	});

	return newTopPos;
};

/**
*  Adjust news lenta buttons
*/
NNPages.AdjustNewsLentaButtons = function()
{
	if ($("#newsLentaList").position().top >= 0)
	{
		// disable 'up' button
		$("#newsLentaButUp").attr('class', 'b-arrowbuttons_up_disabled g-diblockie');
	}
	else
	{
		$("#newsLentaButUp").attr('class', 'b-arrowbuttons_up g-diblockie');
	}
};

/**
 *  Load newslenta from server
 */
NNPages.LoadNewsLenta = function()
{
	var currentSize = $("#newsLentaList li").size();
	var pageSize = 200;

	NNPages.SendNewsLentaRequestToServer(
		{ command: 'newslenta',
		  startIndex: currentSize,
		  pageSize: pageSize
		}
	);
};

/**
*  Send news lenta request to server
*/
NNPages.SendNewsLentaRequestToServer = function(reqPassport)
{
	NNPages.ShowProgressControl($("#newsLenta"));

	$.ajax({
		type: 'GET',
		url: 'gate.php',
		success: NNPages.ProcessNewsLentaServerResponse,
		data: reqPassport,
		error: NNPages.AjaxErr
	});
};

/**
*  Receive server response
*/
NNPages.ProcessNewsLentaServerResponse = function(responseText, status)
{
	NNPages.HideProgressControl();

	if (!NNPages._newslentaFullLoaded)
	{
		NNPages._newslentaFullLoaded = true;

		$("#newsLentaList").append(responseText);

		NNPages.ProcessNewsLentaDown();
	}
};


/* Weather functionality  ---------------------------------------------------------------------*/

/**
* Refresh weather forecast
*/
NNPages.ReadDefaultWeatherForecast = function()
{
	// determine city
	var cityCode = $.cookie('weatherCity');

	// if the city is unknown assign it Minsk
	if (!NNPages._weatherCityHash[cityCode])
	{
		cityCode = 26850;
	}
	//alert('ReadDefaultWeatherForecast: ' + NNPages._weatherCityHash[cityCode]);

	NNPages.UpdateWeatherForecast( cityCode );
};

/**
* Update weather city forecast
*/
NNPages.UpdateWeatherForecast = function(cityCode)
{
	// if the city is unknown assign it Minsk
	if (!NNPages._weatherCityHash[cityCode])
	{
		cityCode = 26850;
	}

	// change city label
	var cityLabel = NNPages._weatherCityHash[cityCode];
	$("#weatherCity").html(cityLabel);

	// store city in cookie
	NNPages.SetCookieValue('weatherCity', cityCode, 1000);

	$("#weatherText").html('loading...');

	// make request to server for city weather forecast
	$.ajax({
		type: 'GET',
		url: 'weather.php',
		success: NNPages.UpdateWeatherForecastServerResponse,
		data: { cityCode: cityCode },
		error: NNPages.AjaxErr
	});
};

/**
*  Receive server response
*/
NNPages.UpdateWeatherForecastServerResponse = function(responseText, status)
{
	$("#weatherText").html(responseText);
};



/**
* Set cookie value
*
*/
NNPages.SetCookieValue = function(cookieName, cookieValue, expireDays)
{
	var options = { path: '/', expires: expireDays };

	$.cookie(cookieName, cookieValue, options);

	/* examples

	var COOKIE_NAME = 'test_cookie';
	var ADDITIONAL_COOKIE_NAME = 'additional';
	var options = { path: '/', expires: 10 };

	// set cookie by number of days
	$.cookie(COOKIE_NAME, 'test', options);

	// set cookie by date
	var date = new Date();
	date.setTime(date.getTime() + (3 * 24 * 60 * 60 * 1000));
	$.cookie(COOKIE_NAME, 'test', { path: '/', expires: date });

	// get cookie
	alert($.cookie(COOKIE_NAME));

	// delete cookie
	$.cookie(COOKIE_NAME, null, options);

	// set a second cookie
	$.cookie(ADDITIONAL_COOKIE_NAME, 'aou?;foo=bar', { expires: 10 });

	// get second cookie
	alert($.cookie(ADDITIONAL_COOKIE_NAME));

	// delete second cookie
	$.cookie(ADDITIONAL_COOKIE_NAME, null);
	*/
};


/**
*  Send calendar request to server
*/
NNPages.SendCalendarRequestToServer = function(reqPassport)
{
	NNPages.ShowProgressControl($("#calendar"), -52);

	$.ajax({
		type: 'GET',
		url: 'gate.php',
		success: NNPages.ProcessCalendarServerResponse,
		data: reqPassport,
		error: NNPages.AjaxErr
	});
};

/**
*  Receive calendar server response
*/
NNPages.ProcessCalendarServerResponse = function(responseText, status)
{
	NNPages.HideProgressControl();

	$("#calendar").html(responseText);
	NNPages.AttachCalendarHandlers();
};

/**
*  Ajax err handler
*/
NNPages.AjaxErr = function()
{
	NNPages.HideProgressControl();
};

/* Progress control  ---------------------------------------------------------------------*/

NNPages.ShowProgressControl = function(el, correctionX, correctionY)
{
	correctionX = correctionX || 0;
	correctionY = correctionY || 0;

	var elOffset = el.offset();
	var progCtrl = $(".progresscontrol");

	var left = elOffset.left + el.outerWidth()/2 - progCtrl.width()/2 + correctionX;
	var top  = elOffset.top + el.outerHeight()/2 - progCtrl.height()/2 + correctionY;

	progCtrl
		.css("display", "block")
		.css("left", left)
		.css("top", top);
};

NNPages.HideProgressControl = function()
{
	$(".progresscontrol").css("display", "none");
};


/* Article font size  ---------------------------------------------------------------------*/

/*
$(document).ready(function(){
	var cfs = $.cookie('def_font_size');
	$('body,td,th').css('font-size', cfs+'px');
});
*/

NNPages.ChangeArticleFontSize = function( action )
{
	// define current and new font size
	var articleFontSize = 3; // def value
    var article = $('.b-news_big-i');
	var articleClass = article.attr('class');
	if (articleClass.indexOf(' f') >= 0)
	{
		articleFontSize = articleClass.substr(articleClass.indexOf(' f')+2) * 1;
        article.removeClass('f' + articleFontSize);
		if (articleFontSize < 0 || articleFontSize > 10)
			articleFontSize = 3;
	}

	if (action == 'reduce' && articleFontSize > 1)
		articleFontSize--;

	if (action == 'enlarge' && articleFontSize < 10)
		articleFontSize++;

	// store in cookie
	NNPages.SetCookieValue('articleFontSize', articleFontSize, 1000);

	// apply to article
	article.addClass('f'+articleFontSize);
};
