/**
 * @author Rym<rym.the.great@gmail.com>
 */

var _enable_marque = 0; //Признак показа бегущей строки
var _show_news = 0; // Признак показа новостей на главной
var _show_analitic = 0; //заглушка для блока аналитики

var global_div;		// вспомогательная переменная для корректного формирования новостных блоков на главной
var global_sub_div; // вспомогательная переменная для корректного формирования новостных блоков на главной

var global_local = true;
if (document.location.host.indexOf('forexaw.com') == -1)
{
	global_local = false;
}

$(document).ready(function(){
	if (!global_local)
	{
		// Только локально
		return;
	}
	
	var p;
	$('.bl_sub').each(function(){
		$(this).hide();
		var pattern=/foot_(\d+)_tx/;
		var id=this.id.match(pattern);
		if(id != null)
		{
			$("#open_" + id[1]).click(function()
			{
				var pattern=/open_(\d+)/;
				var id=this.id.match(pattern);
				if($("#foot_" + id[1] + "_tx").css('display') == "none")
				{
					$("#foot_" + id[1] + "_tx").show();
					$("#sub_" + id[1] + "_tx").show();
				}else{
					$("#foot_" + id[1] + "_tx").hide();
					$("#sub_" + id[1] + "_tx").hide();
				}
			});
		}
	});
	
	$('#open_an span').toggle(function(){
		$('#foot_an_tx').show();
		$('#sub_an_tx').show()}
		, function(){
		$('#foot_an_tx').hide();
		$('#sub_an_tx').hide()}
	);

	$('.bl_partner_link').each(function(){
		var pattern=/plink_(\d+)_text/;
		var id=this.id.match(pattern);
		if(id != null)
		{
			$(this).click(function()
			{
				var pattern=/plink_(\d+)_text/;
				var id=this.id.match(pattern);
				if($("#plink_" + id[1] + "_content").css('display') == "none")
				{
					$("#plink_" + id[1] + "_content").show();
				}else{
					$("#plink_" + id[1] + "_content").hide();
				}
			});
		}
	});
	
	initParty();
});


function initParty()
{
	if(_enable_marque != 0)
	{
		$jScroller.add("#marq_data","#marq","left",4, true);
	}
	
	beginParty2();
}



var can_add = true; // семафор для посылки запросов на сервер

/**
 * Получение данных для бегущей строки и новостных блоков на главной
 * @return
 */
function beginParty2()
{
	_show_analitic = 0;
	if(_enable_marque)
	{
		$("#marq").html("");
		if(_enable_marque == 2)
		{
			$jScroller.stop();
			_enable_marque =1;
		}
		
	}
	if(_show_news)
	{
		$('.bl_text').each(function(){
			var pattern=/NB_(\d+)/;
			var id=this.id.match(pattern);
			if(id != null){
				getData(id[1]);
			}
		});
	}else{
		if(_enable_marque)
		{
			$.getJSON(url + "rym/getNews.php?act=marq&callback=?", assignData);
		}
	}
	setTimeout("beginParty2()", 5*60*1000);
}


/**
 * 
 * Посылка запроса на сервер, для получения данных для бегущей строки и новостных блоков на главной
 * @param id ID категории для которой нужны данные
 * @return
 */
function getData(id)
{
	if(can_add)
	{
		can_add= false;
		if(_show_news != 0)
		{
			/*
			var div=$("<div></div>");
			div.css('background', 'url("/rym/ajax-loader.gif") no-repeat');
			div.css('background-position', 'center center');
			div.css('text-align','center');
			div.css('color','blue');
			div.css('font-weight', 'bold');
			div.css('text-transform', 'uppercase');
			div.css('padding', '10px 0px 10px 0px');
			div.attr('id', 'load_' + id);
			div.append("&nbsp;");
			$("#sub_" + id + "_tx").before(div); */
			$("#load_" + id).css('background-image', 'url("/rym/ajax-loader.gif")');
		}
		$.getJSON(url + "rym/getNews.php?act=exact&callback=?&news=" + id, assignData2);
	}else{
		setTimeout("getData(" + id + ")", 1000);
	}
}

/**
 * Получение ответа от сервера
 * @param data данные с сервера
 * @return
 */
function assignData2(data)
{
	//var result = $.parseJSON(data);
	var result = data;
	can_add =true;
	buildNews2(result);
	buildMarque2(result);
}


/**
 * Формирование новостного блока на главной
 * @param result данные для вставки
 * @return
 */
function buildNews2(result)
{
	if(_show_news != 0)
	{
		if (_show_analitic == 0){
			$("#our_analitics").show();
			_show_analitic++;
		}
		global_sub_div=$("#NB_" + result.cat_id);
		global_sub_div.html("");
		if(result.days)
		{
			global_id = result.cat_id;
			$(result.days).each(function(){
				var res = $('<div style="margin-bottom: 20px"></div>');
				res.attr("id", global_sub_div.attr("id") + '_' + this.daynum);
				var spn = $("<span class='date_string'></span>");
				var toggle;
				if (global_local)
				{
					toggle = $("<img class='toggler2' src='/templates/forexaw/static/images/arrows/arrow2_right.png' />");
				}
				else
				{
					toggle = $("<span class='toggler2'></span>");
				}
				
				toggle.css('vertical-align','middle');
				spn.html(this.name);
				
				toggle.appendTo(spn);
				res.append(spn);
				global_div = res;
				$(this.news).each(function(){
					var res = $("<span class='detail_link'></span>");
					res.append($("<span class='block_time'></span>").html(this.time + '&nbsp;'))
					if(this.sub != '')
					{
						if (global_local)
						{
							res.append($("<img class='toggler' src='/templates/forexaw/static/images/arrows/arrow_right.png'/>"));
						}
						else
						{
							res.append($("<span class='toggler'>- </span>"));
						}
					}
					else
					{
						res.append("&nbsp;-&nbsp;");
					}
					var link = $("<a></a>");
					link.attr("href", url + 'NEWs-' + this.cat_url + '/' + this.id);
					link.attr("target","_blank");
					link.append($("<span class='pre_sub'></span>").html(/*'&nbsp;' + */this.title));
					link.append($("<span class='sub nb_sub_" + global_id + "'></span>").html(this.sub));
					res.append(link);
					global_div.append(res);
				});
				global_sub_div.append(global_div);
			});
		}else
		{
			global_sub_div.html($("<h1>За последнее время в данном разделе новостей не было</h1>"));
		}
		global_sub_div.show();
	}
	$("#load_" + result.cat_id).remove();
	assignToggler();
	adjustCounters();
}


function adjustCounters()
{
	var p = $('#center_col').height() - $('#right_col').height()- $('#counterCont').height();
	//if (p - parseInt( $('#counterCont').css('margin-top') ) > 0)
	{
		$('#counterCont').css('margin-top', p);
	}
}


/**
 * Формирование бегущей строки на главной
 * @param result данные для вставки в бегущую строку
 * @return
 */
function buildMarque2(result)
{
	if(_enable_marque != 0)
	{
		global_id = result.cat_id;
		if(result.days)
		{
			global_marquee ="";
			global_marquee += "<span class='run_st_" + result.cat_id + "'>" + result.s_title + "</span>&nbsp;";
			global_s_num = result.s_num;
			$(result.days).each(function(){
				$(this.news).each(function(){
					if(global_s_num >0)
					{
						global_marquee +="<span class='run_s_" + global_id + "'><span class='block_time'>" + this.time + "&nbsp;-&nbsp;</span>" + "<a target='_blank' href='" + url + 'NEWs-' + this.cat_url + '/' + this.id + "'>" + this.title + "</a></span>&nbsp;|&nbsp;";
						global_s_num --;
					}
				});
			});
			$("#marq").append(global_marquee);
			if(_enable_marque == 1)
			{
				//$("#marq").css('left', $("#marq_data").width());
				_enable_marque = 2;
				$jScroller.start();
			}
		}
	}
}



/**
 * Прием данных от сервера для формирования бегущей строки не на главной странице
 * @param data результат ajax запроса
 * @return
 */
function assignData(data)
{
	//var result = $.parseJSON(data);
	var result = data;
	buildMarque(result);
}


var global_marquee;  // бегущая строка
var global_s_num; // количество записей раздела в бегущей строке
var global_id;

/**
 * Построение бегущей строки из данных на страницах, отличных от главной
 * @param result данные для вставки в бегущую строку
 * @return
 */
function buildMarque(result)
{
	if(_enable_marque != 0)
	{
		global_marquee ="";
		$(result).each(function()
		{
			if(this.days)
			{
				global_marquee += "<span class='run_st_" + this.cat_id + "'>" + this.s_title + "</span>&nbsp;";
				global_id = this.cat_id;
				$(this.days).each(function(){
					$(this.news).each(function(){
						global_marquee +="<span class='run_s_" + global_id + "'><span class='block_time'>" + this.time + "&nbsp;-&nbsp;</span>" + "<a target='_blank' href='" + url + 'NEWs-' + this.cat_url + '/' + this.id + "'>" + this.title + "</a></span>&nbsp;|&nbsp;";
					});
				});
			}
		});
		$("#marq").html(global_marquee);
		if(_enable_marque == 1)
		{
			//$("#marq").css('left', $("#marq_data").width());
			_enable_marque = 2;
			$jScroller.start();
		}
	}
}



var waiting;

/**
 * Я ХЗ чья это ф-ция, но с ней все норм работает
 * @return
 */
function assignToggler()
{
	if (!global_local)
	{
		return;
	}

	var toggleHintOpen = 'Скрыть краткое содержание';
	var toggleHintClose = 'Показать краткое содержание';

	var toggle2HintOpen = 'Скрыть краткое содержание всех новостей\n в данном блоке';
	var toggle2HintClose = 'Показать краткое содержание всех новостей\n в данном блоке';

	$('.toggler').attr('title', toggleHintClose);
	$('.toggler2').attr('title', toggle2HintClose);
	
	$('.toggler').unbind('click');
	$('.toggler').bind('click', function(){
		if (waiting)
		{
			return;
		}
		
		var tmp = $(this).nextAll('a').children('.sub').get(0);
		if ( toggleImg(this, 'toggleHint') )
		{
			toggleDiv(tmp, 'open');
		}
		else	
		{
			toggleDiv(tmp, 'close');
		}
	});
	$('.toggler2').unbind('click');
	$('.toggler2').bind('click', function(){
		if (waiting)
		{
			return;
		}
			
		if ( toggleImg(this, 'toggle2Hint') )
		{
			$('.sub', $(this).parent().parent()).each(function(){
				toggleDiv(this, 'open');
			});
			$('.toggler', $(this).parent().parent()).each(function(){
				toggleImg(this, 'toggleHint', 'open');
			});
		}
		else	
		{
			$('.sub', $(this).parent().parent()).each(function(){
				toggleDiv(this, 'close');
			});
			$('.toggler', $(this).parent().parent()).each(function(){
				toggleImg(this, 'toggleHint', 'close');
			});
		}
	});


	/**
	 * elm image to toggle
	 * hint basename of variable with hint
	 * state force 'open', 'close'
	 */
	function toggleImg(elm, hint, state)
	{
		if (elm.opened == undefined)
		{
			elm.opened = false;
		}
			
		// Open
		if ( !elm.opened && (state == undefined || state == 'open') )
		{	
			if (global_local)
			{
				elm.src = elm.src.replace('_right', '_down');
			}
			
			elm.opened = true;
			if (hint && global_local)
			{
				hint += 'Open';
				$(elm).attr('title', window[hint]);
			}	
		}
		else
		// Close
		if ( elm.opened && (state == undefined || state == 'close') )
		{
			if (global_local)
			{
				elm.src = elm.src.replace('_down', '_right');
			}
			
			elm.opened = false;
			if (hint && global_local)
			{
				hint += 'Close';
				$(elm).attr('title', window[hint]);
			}	
		}

		return elm.opened;
	}

	/**
	 * elm element to toggle
	 * state force 'open', 'close'
	 */
	function toggleDiv(elm, state)
	{
		waiting = true;
		if (elm.opened == undefined)
		{
			elm.opened = false;
		}
		
		// Open
		if ( !elm.opened && (state == undefined || state == 'open') )
		{
			elm.opened = true;
			$(elm).css('display', 'block');
			waiting = false;
		}
		else
		// Close
		if ( elm.opened && (state == undefined || state == 'close') )
		{
			elm.opened = false;
			$(elm).hide();
			waiting = false;
		}
	}
}