/**
 * @updates Ilya Kil <do-it@list.ru>
 * @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;
	}
	
	$('.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();
				}
			});
		}

		pattern = /map_(\d+)_tx/;
		id = this.id.match(pattern);
		if(id != null)
		{
			$("#map_" + id[1]).click(function()
			{
				var pattern = /map_(\d+)/;
				var id = this.id.match(pattern);
				if($("#map_" + id[1] + "_tx").css('display') == "none")
				{
					$("#map_" + id[1] + "_tx").show();
				}
				else
				{
					$("#map_" + 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);
		$("#marq").html("");
	}
	
	beginParty2();
}


var commandList = [];

var can_add = true; // семафор для посылки запросов на сервер

/**
 * Получение данных для бегущей строки и новостных блоков на главной
 * @return
 */
function beginParty2()
{
	_show_analitic = 0;
	if(_enable_marque)
	{
		_enable_marque = 1;
	}

	if(_show_news)
	{
		$('.bl_text').each(function(){
			var pattern=/NB_(\d+)/;
			var id=this.id.match(pattern);
			if(id != null)
			{
				var cmd = 'getData(' + id[1] + ')';
				commandList.push(cmd);
			}
		});

		execList();
	}
	else if(_enable_marque)
	{
		$.getJSON(url + "rym/getNews.php?act=marq&callback=?", assignData);
	}
	
	setTimeout("beginParty2()", 5*60*1000);
}


function execList()
{
	if (commandList.length < 1)
	{
		return;
	}

	var cmd = commandList.shift();

	eval(cmd);

	/* setTimeout("execList()", 500); */
}

/**
 * 
 * Посылка запроса на сервер, для получения данных для бегущей строки и новостных блоков на главной
 * @param id ID категории для которой нужны данные
 * @return
 */
function getData(id)
{
	if(can_add)
	{
		can_add = false;
		if(_show_news != 0)
		{
			$("#load_" + id).css('background-image', 'url("/rym/ajax-loader.gif")');
		}

		$.getJSON(url + "rym/getNews.php?act=exact&callback=?&news=" + id, assignData2);
	}
	else
	{
		commandList.unshift('getData(' + id + ')');
		setTimeout("execList()", 1000);
	}
}

/**
 * Получение ответа от сервера
 * @param data данные с сервера
 * @return
 */
function assignData2(data)
{
	//var result = $.parseJSON(data);
	var result = data;
	buildNews2(result);
	buildMarque2(result);
	can_add = true;
	execList();
}


/**
 * Формирование новостного блока на главной
 * @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" width="16" height="16" '
						+ '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" width="16" height="16" '
								+ '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 + this.url);
					link.attr("target","_blank");
					if (this.vip == '1')
					{
						link.addClass('vip');
					}
					
					link.append($("<span class='pre_sub'></span>").html(this.title));
					link.append($("<span class='sub nb_sub_" + global_id + "'></span>").html(this.sub));
					res.append(link);

					res.append('<span class="news_cat_diff"> | </span>');
					link = $("<a class='news_cat'></a>").html(this.cat_title || 'test');
					link.attr("href", url + this.cat_url);
					res.append(link);

					global_div.append(res);
				});
				global_sub_div.append(global_div);
			});
		}
		else
		{
			global_sub_div.html(
				$("<h1>" + "\u0417\u0430 \u043f\u043e\u0441\u043b\u0435\u0434\u043d\u0435\u0435 \u0432\u0440\u0435\u043c\u044f \u0432 \u0434\u0430\u043d\u043d\u043e\u043c \u0440\u0430\u0437\u0434\u0435\u043b\u0435 \u043d\u043e\u0432\u043e\u0441\u0442\u0435\u0439 \u043d\u0435 \u0431\u044b\u043b\u043e" + "</h1>")
			);
		}
		
		global_sub_div.show();
	}
	
	$("#load_" + result.cat_id).remove();
	assignToggler();
	adjustCounters();
}


function adjustCounters()
{
	return;
	/*
	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 + this.url + "' "
							+ (this.vip == '1' ? 'class="vip"' : '') + ">"
							+ this.title + "</a></span>&nbsp;|&nbsp;";
						global_s_num --;
					}
				});
			});
			
			if(_enable_marque == 1)
			{
				$jScroller.stop();
				$("#marq").html("");
				$("#marq").css('left', $("#marq_data").width());
			}
			
			$("#marq").append(global_marquee);
			if(_enable_marque == 1)
			{
				_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 + this.url + "' "
							+ (this.vip == '1' ? 'class="vip"' : '') + ">"
							+ this.title + "</a></span>&nbsp;|&nbsp;";
					});
				});
			}
		});

		$jScroller.stop();
		$("#marq").html(global_marquee);
		$("#marq").css('left', $("#marq_data").width());
		$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;
		}
	}
}

//
// Video-Player functions
//
function initVideo()
{
	$('.forexaw_hide').hide();
	$('.video_ch').click(set_ch).mouseover(doVideoOver).mouseout(doVideoOut);
	$($('.video_ch').get(0)).click();

	/* fix for forexclub */
}

function doVideoOver()
{
	$(this).toggleClass('video_over', true);
}

function doVideoOut()
{
	$(this).toggleClass('video_over', false);
}

function set_ch()
{
	var cur_id = $(this).attr('cur_id');

	if ( $('#data_' + cur_id).length == 0
		|| (cur_id != '17' && $('#ch_content #data_' + cur_id).length == 1) )
	{
		return;
	}

	var elm;
	var content;
	elm = $('#ch_content div');
	if ( elm.attr('encoded') )
	{
		content = elm[0].innerHTML;
		content = content.replace(/>/g, '&gt;');
		content = content.replace(/</g, '&lt;');
		elm.html(content);
	}

	elm.appendTo('#data_list');
	$('#ch_content').empty();

	elm = $('#data_' + cur_id);
	if ( elm.attr('encoded') )
	{
		content = elm[0].innerHTML;
		content = content.replace(/&amp;/g, '&');
		content = content.replace(/&gt;/g, '>');
		content = content.replace(/&lt;/g, '<');
		elm.html(content);
	}

	elm.appendTo('#ch_content');

	$('.video_ch').toggleClass('video_play', false);
	$(this).toggleClass('video_play', true);

	if (global_local && window.adjustCounters)
	{
		adjustCounters();
	}

	if (cur_id == 17)
	{
		if (window.brightcove)
		{
			brightcove.createExperiences();
		}

		var tmpWidth = $('#myExperience').css('width');
		if (tmpWidth == '99%')
		{
			tmpWidth = '100%';
		}
		else
		{
			tmpWidth = '99%';
		}

		$('#myExperience').css('width', tmpWidth);
	}
}
