
var newsblock = {
	
	vars : {
		anchorListener : '',
		anchorOld : '',
		template : 'list',
		lang : 'rus',
		datatype : 'news',
		currentDate : new Date(), // текущая дата в контексте наличия новостей в месяце
		realCurrentDate : new Date(),
		timedata : {},
		timedataPieces : {},
		monthsI : ['нулябрь','январь','февраль','март','апрель','май','июнь','июль','август','сентябрь','октябрь','ноябрь','декабрь'],
		monthsR : ['нулября','января','февраля','марта','апреля','мая','июня','июля','августа','сентября','октября','ноября','декабря'],
		monthsE	: ['zeruary','January','February','March','April','May','June','July','August','September','October','November','December']
	},
	
	select : {
		show : function(selectid) {
			newsblock.select.hide();
			
			if(selectid != 'newsblock_first_select') {
				var_prefix = 'start';
			} else {
				var_prefix = 'stop';
			}
			
			if(newsblock.vars.timedataPieces['startYear'] == undefined) {
				newsblock.timedata.defaultValues();
			}
			
			
			$year = newsblock.vars.timedataPieces[var_prefix + 'Year'];
			if(newsblock.timedata.checkYear($year - 1)) {
				$('#' + selectid).find('table').find('td:first').find('img').attr('src','/img/popup_pic_left_act.gif');
			} else {
				$('#' + selectid).find('table').find('td:first').find('img').attr('src','/img/popup_pic_left.gif');
			}
			if(newsblock.timedata.checkYear($year + 1)) {
				$('#' + selectid).find('table').find('td:last').find('img').attr('src','/img/popup_pic_right_act.gif');
			} else {
				$('#' + selectid).find('table').find('td:last').find('img').attr('src','/img/popup_pic_right.gif');
			}
			
			
			shift00 = 37;
			shift01 = 18.7;
			
			if($.browser.msie) {
				shift01 = 19;
			}
			if($.browser.opera) {
				shift01 = 18;
			}
			if($.browser.safari) {
				shift01 = 18;
			}
			
			$scroll_top = -1 * ((newsblock.vars.timedataPieces[var_prefix + 'Month'] - 1) * shift01 + shift00); // 21 - 40
			$('#' + selectid).css('top',$scroll_top);
			
			newsblock.select.redraw.months(selectid, var_prefix, $year);
			
			
			$('#' + selectid).show();
		},
		hide : function() {
			$('.popup_block').hide();
		},
		redraw : {
			months: function(selectid, var_prefix, year) {
				
				$('#' + selectid).find('.month_a').find('a').each(function() {
					$(this).addClass('noact');
					if($(this).hasClass("act")) {
						$(this).removeClass('act');
						$(this).html($(this).children('span').html());
					}
				});
				
				
				$item = $('#' + selectid).find('.month_a').find('a:eq('+ (newsblock.vars.timedataPieces[var_prefix + 'Month'] - 1) +')');
				$item.addClass('act');
				$item.html('<span>' + $item.html() + '</span>');
				
				for(var i=0; i <= (newsblock.vars.timedata[year].length-1); i++) {
					indel = newsblock.vars.timedata[year][i];
					$('#' + selectid).find('.month_a').find('a:eq('+ (indel-1) +')').removeClass('noact');
				}
			}
		}
	},
	
	timedata : {
		defaultValues : function() {
			// start date = current_date
			newsblock.vars.timedataPieces['startYear']	= newsblock.vars.realCurrentDate.getFullYear();
			newsblock.vars.timedataPieces['startMonth']	= newsblock.vars.realCurrentDate.getMonth() + 1;
			// stop date = (current date - 1) month or date with news
			stop_date = newsblock.vars.currentDate;
			if((stop_date.getFullYear() == newsblock.vars.realCurrentDate.getFullYear()) && (stop_date.getMonth() == newsblock.vars.realCurrentDate.getMonth())) {
				stop_date.setMonth(stop_date.getMonth() - 1);		
			}
			newsblock.vars.timedataPieces['stopYear']	= stop_date.getFullYear();
			newsblock.vars.timedataPieces['stopMonth']	= stop_date.getMonth() + 1;
		},
		setCurrentDate : function(timestamp) {
			newsblock.vars.currentDate = new Date(timestamp * 1000);
			newsblock.vars.currentDate.toGMTString();
		},
		validate : function(value) {
			if(value != undefined) {
				return value;
			}
			return "";
		},
		
		setData : function(value) {
			newsblock.vars.timedata = value;
		},
		
		setMonth : function(parent_el_id, val) {
			
			
			if(!$('#' + parent_el_id).find('.month_a').find('a:eq(' + (val-1) + ')').hasClass('noact')) {
				
				if(parent_el_id != 'newsblock_first_select') {
					var_prefix = 'start';
				} else {
					var_prefix = 'stop';
				}
				
				newsblock.vars.timedataPieces[var_prefix + 'Month'] = val;
				
				$link_html = "";
				if(newsblock.vars.lang == 'rus') {
					if(var_prefix == 'start') {
						$link_html += newsblock.vars.monthsI[val];
					} else {
						$link_html += newsblock.vars.monthsR[val];
					}
				} else {
					$link_html += newsblock.vars.monthsE[val];
				}
				$link_html += " " + newsblock.vars.timedataPieces[var_prefix + 'Year'];
				$('#' + parent_el_id + "_link").html($link_html);
				
				newsblock.select.hide();	
			}
		},
		
		checkYear : function(year) {
			
			if(newsblock.vars.timedata[year] != undefined) {
				return true;
			} else {
				return false;
			}
		},
		
		switchYear : function(selectid, shift_direction) {
			
			if(selectid != 'newsblock_first_select') {
				var_prefix = 'start';
			} else {
				var_prefix = 'stop';
			}
			
			
			$year = newsblock.vars.timedataPieces[var_prefix + 'Year'] + shift_direction;
			if(newsblock.timedata.checkYear($year)) {
				newsblock.vars.timedataPieces[var_prefix + 'Year'] = $year;
				if(newsblock.timedata.checkYear($year - 1)) {
					$('#' + selectid).find('table').find('td:first').find('img').attr('src','/img/popup_pic_left_act.gif');
				} else {
					$('#' + selectid).find('table').find('td:first').find('img').attr('src','/img/popup_pic_left.gif');
				}
				if(newsblock.timedata.checkYear($year + 1)) {
					$('#' + selectid).find('table').find('td:last').find('img').attr('src','/img/popup_pic_right_act.gif');
				} else {
					$('#' + selectid).find('table').find('td:last').find('img').attr('src','/img/popup_pic_right.gif');
				}
				
				$('#' + selectid).find('table').find('td:eq(1)').html($year);
				
				
				
				newsblock.select.redraw.months(selectid, var_prefix, $year);
			}
		}
	},
	binds : {
		anchorBind : function() {
			newsblock.vars.anchorListener = setInterval(function() {
				var aO = newsblock.vars.anchorOld;
				var aN = new String(window.location);
				aN = aN.match(/#(.*)$/);
				if(aN && aN[1] != undefined) {
					aN = aN[1];
					if(aO != aN && aN != '') {
						newsblock.vars.anchorOld = aN;
						newsblock.sendPostRequest();
						
						var anchorDataSource = aN.split('&');
						var anchorData = {};
						for(i=0; i< anchorDataSource.length; i++) {
							anchorElement = anchorDataSource[i].split('=');
							anchorData[anchorElement[0]] = anchorElement[1];
						}
						delete anchorDataSource;
						
						// перерисовка селектов
						if(anchorData['startYear'] != undefined) {
							newsblock.vars.timedataPieces['startYear'] = parseInt(anchorData['startYear'], 10);
							newsblock.vars.timedataPieces['startMonth'] = parseInt(anchorData['stratMonth'], 10);
							newsblock.vars.timedataPieces['stopYear'] = parseInt(anchorData['stopYear'], 10);
							newsblock.vars.timedataPieces['stopMonth'] = parseInt(anchorData['stopMonth'], 10);
							
							newsblock.select.redraw.months('newsblock_first_select', 'start', anchorData['stopYear']);
							newsblock.timedata.setMonth('newsblock_first_select', anchorData['stopMonth']);
							newsblock.timedata.switchYear('newsblock_first_select', 0);
							
							newsblock.select.redraw.months('newsblock_second_select', 'start', anchorData['startYear']);
							newsblock.timedata.setMonth('newsblock_second_select', anchorData['stratMonth']);
							newsblock.timedata.switchYear('newsblock_second_select', 0);
						}
						// кейворды
						if(anchorData['keywords'] != undefined) {
							$('#newsblock_keywords').val(decodeURIComponent(anchorData['keywords']));
						}
						// тема
						if(anchorData['topic'] != undefined) {
							$('#newsblock_topic_poup').find('[js_value="' + anchorData['topic'] + '"]').click();
						}
					}
				}
			}, 300)
		},
		
		click : function(e) {
			var el			= e ? e.target : event.srcElement;
			var el_parents	= $(el).parents();
			var to_hide		= true;
			
			$(el_parents).each(function() {
				if($(this).attr("class") == "popup_block") {
					to_hide = false;
				}
			});
			
			if($(el).attr("class") == "popup_block") {
				to_hide = false;
			}
			
			
			if($(el).attr('id').match(/darkpopup/i)) {
				to_hide = false;
			}
			
			if(to_hide) {
				$('.popup_block').hide();
			}
		},
		
		press : function() {
			var el_focused = $(document.activeElement);
			if(el_focused[0].tagName == 'INPUT' && el_focused.attr("id") == "newsblock_keywords") {
				newsblock.submit("keywords");
				return;
			}
		}
	},
	
	topic_change : function() {
		$('#newsblock_topic_poup').show();
	},
	
	topic : function(element) {
		element = $(element);
		$('#newsblock_topic_name').text(element.text());
		$('#newsblock_topic').val(element.attr("js_value"));
		$('#newsblock_topic_poup').hide();
	},
	
	
	sample : function() {
		$('#newsblock_keywords').val($('#newsblock_search_sample').html());
	},
	
	lang : function(value) {
		newsblock.vars.lang = value;
	},
	datatype : function(value) {
		newsblock.vars.datatype = value;
	},
	template : function(value) {
		newsblock.vars.template = value;
	},
	
	
	get_rv : function(variable) { 
  		var query = new String(window.location); 
  		query = query.split('#');
  		if(query.length == 1) {
  			return false;
  		}
  		query = query[1];
  		
  		var vars = query.split("&"); 
  		for (var i=0;i<vars.length;i++) { 
    		var pair = vars[i].split("="); 
    		if (pair[0] == variable) { 
      			return pair[1]; 
    		} 
  		}
  		return false;
	},
		
	
	submit : function(type) {
		
		var $request_string = '';
		
		
		newsblock.select.hide();
		
		switch(type) {
			case "dates" :
				if(newsblock.vars.timedataPieces['startYear'] == undefined) {
					newsblock.timedata.defaultValues();
				}
				$request_string =	"startYear=" + newsblock.timedata.validate(newsblock.vars.timedataPieces['startYear'])
									+ "&stopYear=" + newsblock.timedata.validate(newsblock.vars.timedataPieces['stopYear'])
									+ "&stratMonth=" + newsblock.timedata.validate(newsblock.vars.timedataPieces['startMonth'])
									+ "&stopMonth=" + newsblock.timedata.validate(newsblock.vars.timedataPieces['stopMonth'])
			break;
			case "keywords" :
				if(newsblock.get_rv('interval')) {
					$request_string = "interval=" + $('#newsblock_first_interval').val()
				}
				if(newsblock.get_rv('startYear')) {
					$request_string =	"startYear=" + newsblock.timedata.validate(newsblock.vars.timedataPieces['startYear'])
									+ "&stopYear=" + newsblock.timedata.validate(newsblock.vars.timedataPieces['stopYear'])
									+ "&stratMonth=" + newsblock.timedata.validate(newsblock.vars.timedataPieces['startMonth'])
									+ "&stopMonth=" + newsblock.timedata.validate(newsblock.vars.timedataPieces['stopMonth'])
				}
				
				
				if(newsblock.vars.datatype == "news") {
					searchStat.GoCustom($('#newsblock_keywords').val(), "block_news_search");
				}
			break;
			case "interval" :
				$request_string = "interval=" + $('#newsblock_first_interval').val()
				break;
			default:
				break;
		}
		
		
		$request_string += "&keywords=" + $('#newsblock_keywords').val()
		$request_string += "&lang="	+ newsblock.vars.lang;
		$request_string += "&datatype="	+ newsblock.vars.datatype;
		$request_string += "&template="	+ newsblock.vars.template;
		
		if($('#newsblock_topic')) {
			if($('#newsblock_topic').val() != undefined) {
				$request_string += "&topic=" + $('#newsblock_topic').val();
			}
		}
		
		window.location = '#' + $request_string;
	},
	
	sendPostRequest : function() {
		$request_string = newsblock.vars.anchorOld;
		
		$.ajax({
			type:		"post",
			url:		"/system/php/scripts/newsget.php",
			data:		$request_string,
			dataType:	"html",
			beforeSend: function () {
				$('#g-news-block-result').html('<div class="block"><center><br><br><br><img src="/img/news-loader.gif" border="0"></center></div>');
				
				if($('#divNewsItem')) {
					$('#divNewsItem').remove();
				}
				$('#divNewsItemHeader').remove()
				
				if($('#divNewsList')) {
					$('#divNewsList').show();
				}
			},
			success: function(html){
				$('#g-news-block-result').html(html);
			}
		});
	}
}

$(document).ready(function() {
	newsblock.binds.anchorBind();
})

$(document).click(function(e) {
	newsblock.binds.click(e);
});

$(document).keydown(function(event){
	var keycode = event.keyCode;
	if(keycode == 13) {
		newsblock.binds.press();
	}
});












// namespace
gNB = {
	block:		function (lang, something, dataType) {
					self0 = new this.o(lang, cacheNM, dataType);
					self0.createo();
					return self0;
				}
}

// constructor
gNB.o = function (lang, cacheNM, dataType) {
	this.inst				= this,
	this.date_start			= false;
	this.date_stop			= false;	
	this.language			= lang;
	this.date				= new Date();
	this.year				= this.date.getFullYear();
	this.monthhavenews		= cacheNM;
	this.dataType 			= dataType ? dataType : 'news';
	if(lang == 'rus') {
		language = 'russian';
	} else {
		language = 'english';
	}
	this.toolbox			= toolbox.createinstance(language);
}

// prototype
gNB.o.prototype = {
	ID_COMMON:			"g-news-block",
	ID_YEAR:			"g-news-block-year",
	ID_YEAR_PREV:		"g-news-block-year-prev",
	ID_YEAR_NEXT:		"g-news-block-year-next",
	ID_MONTH:			"g-news-block-month-",
	ID_NOTIFICATION:	"g-news-block-notification",
	ID_BUTTON_CANCEL:	"g-news-block-cancel",
	ID_BUTTON_OK:		"g-news-block-ok",
	ID_NEWS_CONTEINER:	"g-news-block-result",
	X_MONTHS_HAVE_NEWS:	{eng: "/cache/eng/js/news/monthshavenews.js",
						 rus: "/cache/eng/js/news/monthshavenews.js"
						},
	X_NEWS_GET:			"/system/php/scripts/newsget.php",
	TEXT_DATE_MESSAGES:	{"eng" : {"start":"Select start date ↑","stop":"Select stop date ↑","ok":"Press OK button →","wait":"Please wait..."}, 
						 'rus' : {start: 'Выберите дату начала ↑', stop: 'Выберите дату конца ↑', ok: 'Нажмите кнопку OK →', wait: 'Пожалуйста, подождите'}},
	TEXT_ERRORS:		{"eng" : {"nodates":"Select start and stop dates ↑"}, 
						 rus: {nodates: 'Выберите даты начала и конца ↑'}},
	
	createo:			function () {
							for (var i=0; i < 10; ++i) {
								if (this.monthhavenews[this.year] != undefined) break;
								--this.year;
							}
	
							this.year_print();
							this.bind_buttons();
							$('#' + this.ID_NOTIFICATION).html(this.TEXT_DATE_MESSAGES[this.language]['start']);
							
							$('#' + this.ID_YEAR_PREV).attr('src', this.monthhavenews[this.year - 1] == undefined ? '/img/070_.gif' : '/img/070.gif');
							$('#' + this.ID_YEAR_NEXT).attr('src', this.monthhavenews[this.year + 1] == undefined ? '/img/071_.gif' : '/img/071.gif');
						},
	bind_buttons:		function () {
							self0 = this;
							$('#' + this.ID_YEAR_PREV).click(function(){
																self0.year_navigate(-1);
															});
							$('#' + this.ID_YEAR_NEXT).click(function(){
																self0.year_navigate(1);
															});
							$('#' + this.ID_BUTTON_CANCEL).click(function(){
																self0.button_cancel();
															});
							$('#' + this.ID_BUTTON_OK).click(function(){
																self0.button_ok();
															});
						},
	year_print:			function () {
							self0 = this;
							self0.months_reset();
							$('#' + this.ID_YEAR).html(this.year);
						
							if(self0.monthhavenews[this.year] != null) {
								arr = self0.monthhavenews[this.year];
								for(var i=0; i<arr.length; i++) {
									num = arr[i];
									el = $('#' + self0.ID_MONTH + num);
									el.html('<a style="cursor:pointer;" num="' + num + '">' + el.html() + '</a>').children('a').click(function() {
																																self0.date_select($(this).attr('num'));
																															});
								}
							}
						},
	year_navigate:		function (shift) {
							if (this.monthhavenews[this.year + shift] == undefined) {
								return;
							}
							this.year += shift;
							this.year_print();
							
							$('#' + this.ID_YEAR_PREV).attr('src', this.monthhavenews[this.year - 1] == undefined ? '/img/070_.gif' : '/img/070.gif');
							$('#' + this.ID_YEAR_NEXT).attr('src', this.monthhavenews[this.year + 1] == undefined ? '/img/071_.gif' : '/img/071.gif');
						},
	months_reset:		function() {
							link = $('[id^="' + this.ID_MONTH + '"]').find('a');
							link.each(function () {
								link = $(this);
								link.replaceWith(link.html());
							});
						},
	date_select:		function(month) {
							if(this.date_start == false) {
								$('#' + this.ID_NOTIFICATION).html(this.TEXT_DATE_MESSAGES[this.language]['stop']);
								this.date_start = this.year + '' + month;
							} else {
								this.date_stop = this.year + '' + month;
								$('#' + this.ID_NOTIFICATION).html(this.TEXT_DATE_MESSAGES[this.language]['ok']);
							}
						},
	button_cancel:		function() {
							$('#' + this.ID_NOTIFICATION).html(this.TEXT_DATE_MESSAGES[this.language]['start']);
							this.date_start = false;
							this.date_stop	= false;
						},
	button_ok:			function (){
							if(!this.date_start || !this.date_stop) {
								$('#' + this.ID_NOTIFICATION).html(this.TEXT_ERRORS[this.language]['nodates']);
							} else {
								self0 = this;
								$.ajax({
								type:		"post",
								url:		this.X_NEWS_GET,
								data:		"start=" + this.date_start + "&stop=" + this.date_stop + "&lang=" + self0.language + '&type=' + self0.dataType,
								dataType:	"html",
								beforeSend: function () {
									$('#' + self0.ID_NOTIFICATION).html(self0.TEXT_DATE_MESSAGES[self0.language]['wait']);
								},
								success: function(html){
									
									$('#divNewsItem').hide();
									$('#divNewsList').show();
									
									$('#' + self0.ID_NEWS_CONTEINER).html(html);
									
									self0.button_cancel();
									
									self0.toolbox.setPrintIanctive();
									self0.toolbox.setPDFInactive();
								}
							});
							}
						}
	
}
