$(function(){
  if (!sWIDGET_EDIT_MODE){
    document.getElementById('sSearchField').focus();
  }

  $('.btns input').each(function(){
    $(this).removeAttr('disabled');
  })
//	alert(document.getElementById('sSearchSelect'));
})	
$(function(){
    $("#rec").hide();
    setTimeout(function(){$("#rec").show(); setInterval(function(){$("#rec").toggle();},1000)},2000);			
});

/*
 *	Блок избранное на главной
 */
var sFavShowEdit = function(obj){
	$(obj).children('.edit').css({visibility : 'visible'});
}

var sFavHideEdit = function(obj){
	$(obj).children('.edit').css({visibility : 'hidden'});
}

var sFavEdit = function(obj, id, widgetId){
	var 
		box = $('#sFavWidget'+widgetId),
		pos = box.sAbsPosition(), 
		offset = (box.width() - 274) / 2,
		form = $('#sFavEditFrom' + widgetId),
		name = $('input[name="xx_name"]', form),
		url = $('input[name="xx_url"]', form),
		list = $('#sFavItemList' + widgetId);

	$('#sFavEditErr' + widgetId).text('');

	if (obj){
		var	
			itm = $(obj).parent();
			lnk = $('a', itm);

		$('input[name="xx_delete"]', form).css({
			display : ''
		});

		name.attr('value',lnk.text());
		url.attr('value',lnk.attr('href'));

		$('input[name="xx_save"]', form).click(function(){
			if (sFavValidate(widgetId, name.attr('value'), url.attr('value')) === false){
				return false;
			}

			lnk.text(name.attr('value'));
			lnk.attr('href', url.attr('value'));
			sFavUpdateState (widgetId, list);
			$(this).unbind('click');
			form.css({
				display : 'none'
			});
		});
		
		$('input[name="xx_delete"]', form).one('click', function(){
			if (!confirm('Вы действительно хотите удалить эту ссылку?')){
				return;
			}
			itm.remove();
			sFavUpdateState (widgetId, list);			
			form.css({
				display : 'none'
			});			
		});			
	}else{
		name.attr('value','');
		url.attr('value','http://');
		
		$('input[name="xx_delete"]', form).css({
			display : 'none'
		});
		
		$('input[name="xx_save"]', form).click(function(){
			if (sFavValidate(widgetId, name.attr('value'), url.attr('value')) === false){
				return false;
			}																													 
			list.append('<li><a href="' + url.attr('value') + '">' + name.attr('value') + '</a></li>');
			sFavUpdateState (widgetId, list);
			$(this).unbind('click');
			form.css({
				display : 'none'
			});
		});			
	}
	pos = box.sAbsPosition(), 
	offset = (offset > 0) ? offset : 0;
	form.css({
		top : pos.top + 'px',
		left : (pos.left + offset) + 'px',
		display : ''
	});
}

var sFavValidate = function(widgetId, name, url){
	if (!name){
		$('#sFavEditErr' + widgetId).text('Вы не указали название');
		return false;
	}

	if (name.length > 30){
		$('#sFavEditErr' + widgetId).text('Длина названия не должна превышать 30 символов');
		return false;
	}

	if (!url){
		$('#sFavEditErr' + widgetId).text('Вы не указали адрес');
		return false;
	}

	if (url.length > 200){
		$('#sFavEditErr' + widgetId).text('Длина адреса не должна превышать 200 символов');
		return false;
	}
	
	return true;
}

var sFavUpdateState = function(widgetId, list){
	var	ws = {Update : {}}, i = 0;
	ws.Update[widgetId] = {config : {data : []}};

	$('li', list).each(function (a) { 
		var lnk = $('a', $(this));

		ws.Update[widgetId].config.data[i] = {
			id : i,
			name : lnk.text(),
			url : lnk.attr('href')
		};
		i++;
	});

	if (window.sWidgetState){
		window.sWidgetState.Update[widgetId] = ws.Update[widgetId];
		return;
	}

	$('#sWidget' + widgetId).animate({opacity: 0.3}, "fast");

	$.ajax({
		type : "POST", 
		url : sHTTP, 
		dataType : "html",
		data : {
			cmd:'SaveWidgets',
			singleWidgetMod :1, 
			widgetState:JSON.encode(ws)
		},
		widgetId:widgetId,
		success : function(a){
			$('#sWidget' + this.widgetId).replaceWith(a);
		}
	});
}

var sFavHideEditForm = function(obj){
	$(obj).parent().css({display : 'none'});
}


var sMailClass = function(){ 
return {
		current : -1,
		currentData : false,
		isOpen : false,
		isMouseOver : false,
		closing : false,

		init : function(widgetId){
			this.widgetId = widgetId;
			this.widget = $('#sWidget' + widgetId);
			this.content = $('#sMailContent' + widgetId);
			this.list = $('#sMailList' + widgetId);
			this.settings = $('#sMailSettings' + widgetId);
			this.loading = $('#sMailLoading' + widgetId);
			this.host = $('#sMailHost' + widgetId);
		},
		
		/*
		* открывает соответсвующий почтовый ящик
		*/	
		show : function(num, check){
			if (this.current == num){
				this.hide();
				return;
			}
			
			if ( !this.isOpen ){
				this.isOpen = true;
				this.content.show(200);
			}
			
			this.current = num;
			$('.box', this.content).hide();
			$('.selected', this.widget).attr('class','');
			$('#sMailLink' + this.widgetId + '_' + num).attr('class','selected');

			if (check){
				this.settings.hide();			
				this.list.empty();
				this.loading.show();
				$.ajax({
					type : "POST", 
					url : sHTTP, 
					dataType : "json",
					data : {cmd : 'list',	box : num, hm : 402, id : this.widgetId, ajax : 1},
					parent : this,
					num : num,						
					success : function(a){
						if (this.num != this.parent.current){
							return;
						}

						this.parent.loading.hide();
						this.parent.currentData = a.data;
						if (a.data.err){
							this.parent.showSettingsForm('',a.data.err,a.data.login);
						}else{
							this.parent.list.empty();
							this.parent.list.attr('class','box');
							var html = '';
							if (a.data.count > 0){
								for (var i = 0, len = a.data.count; i < len; i++){
									html+= [
										'<div class="from">', a.data.list[i].from, '</div>',
										'<div class="date">', (a.data.list[i].date) ? sDateTime(a.data.list[i].date) : '', '</div>',
										'<div class="subject"><a href=',a.data.list[i].url,' target="_blank">', a.data.list[i].subject, '</a></div>'
									].join('');
								}
							}else{
								html = '<div class="empty">Список пуст</div>';
							}

							html += '<div class="edit"><input type="button" onclick="sMailBox' + this.parent.widgetId + '.showSettings();" value="Изменить настройки"/></div>';
							this.parent.list.append(html);
							this.parent.list.show();
						}
					}
				});		
			}else{
				this.loading.hide();
				this.showSettingsForm();
			}
		},
		/*
		* отображет форму настроек для текущего почтовика
		*/	
		showSettings : function(){
			this.list.hide();		
			this.showSettingsForm('','',this.currentData.login);
		},
		/*
		* отображет форму настроек и подставляет в нее нужные значения
		*/	
		showSettingsForm : function(comments, errors, login){
	
			if (this.current == 0){
//				alert(sIsLogged);
			}else if(this.current == 1){
				this.host.text('@tut.by');
			}else if(this.current == 2){
				this.host.html('@&nbsp;<select><option value="mail.ru">mail.ru</option>' + 
											 '<option value="inbox.ru">inbox.ru</option>'+
											 '<option value="bk.ru">bk.ru</option>'+
											 '<option value="list.ru">list.ru</option></select>');
				$('select', this.host).attr('value', this.currentData.host);
			}else if(this.current == 3){
				this.host.text('@gmail.com');
			}else if(this.current == 4){
				this.host.text('@yandex.ru');
			}

			if (comments){
				$('.comments', this.settings).text(comments);
				$('.comments', this.settings).show();
			}else{
				$('.comments', this.settings).hide();
			}
			
			if (errors){
				$('.errors', this.settings).text(errors);
				$('.text', this.settings).hide();
				$('.errors', this.settings).show();
			}else{
				$('.errors', this.settings).hide();
				$('.text', this.settings).show();
			}
						
			if (login){
				$('input[name="login"]', this.settings).attr('value', login);
				$('input[name="pass"]', this.settings).attr('value', '******');
				$('input[name="pass"]', this.settings).one('focus', function(){
					this.value = '';
				});
			}else{
				$('input[name="login"]', this.settings).attr('value', '');
				$('input[name="pass"]', this.settings).attr('value', '');
			}
			
			if (!errors && login){
				$('input[name="cancel"]', this.settings).show();
			}else{
				$('input[name="cancel"]', this.settings).hide();
			}
			
			this.settings.show();		
		},
		/*
		* прячет выпадающую часть
		*/	
		hide : function(){
			var parent = this;
			this.current = -1;
			$('.selected', this.widget).attr('class','');

			this.content.hide(200, function(){
				parent.isOpen = false;
			});
		},
/*		
		out : function(){
			this.isMouseOver = false;	
			this.closing = setTimeout('sMailBox' + this.widgetId + '.hide()', 5000);
		},
	
		over : function(){
			this.isMouseOver = true;
			if (this.closing){
				clearTimeout(this.closing);
			}
		},
*/
		/*
		* сохраняет авторизационные данные
		*/	
		saveBox : function(){
			var 
				login = $('input[name="login"]', this.settings).attr('value'),
				pass = $('input[name="pass"]', this.settings).attr('value'),
				host;
			
			if (!login){
				$('.errors', this.settings).text('Вы не указали логин');
				$('.errors', this.settings).show();
				$('.text', this.settings).hide();
				return false;				
			}
			
			if (!pass || pass == '******'){
				$('.errors', this.settings).text('Вы не указали пароль');
				$('.errors', this.settings).show();
				$('.text', this.settings).hide();
				return false;				
			}
			
			this.settings.hide();			
			this.loading.show();			
			
			if (this.current == 2){
				host = $('select', this.host).attr('value');
			}

			$.ajax({
				type : "POST", 
				url : sHTTP, 
				dataType : "html",
				data : {
					cmd : 'SaveData',	box : this.current, hm : 402, id : this.widgetId,
					login : login,
					pass : pass,
					host : host
				},
				parent : this,
				success : function(a){
					this.parent.widget.replaceWith(a);
				}
			});
		},
		
		cancelBox : function(){
			this.settings.hide();
			this.list.show();
		},
		
		dropBox : function(){
			$.ajax({
				type : "POST", 
				url : sHTTP, 
				dataType : "html",
				data : {
					cmd : 'DropData',	box : this.current, hm : 402, id : this.widgetId
				},
				parent : this,
				success : function(a){
					this.parent.widget.replaceWith(a);
				}
			});
		}
	};
};

/*
 *	Управление всплювающим блочком "в закладки в блог"
 */
var sShowFavTools = function(obj){
	var 
		lnk = $(obj),
		box = $('#sFavBox'),
		pos = lnk.sAbsPosition();

	box.css({
		display:'', 
		top : (pos.top - 7) + 'px',
		left : (pos.left + lnk.width() - 138) + 'px'
	});
}

var sHideFavTools = function(obj){
	$(obj).parent().parent().css({display:'none'});
}


/*
 *	Переключение режима списка с аносом или без на главной
 */
var sSetWidgetSettings = function(widgetId, hnd, data){
	if (sWIDGET_EDIT_MODE){
		sUpdateWidget($('#sWidget' + widgetId), widgetId, hnd, data);
	}else{
		var ws = {Update : {}};
		
		ws.Update[widgetId] = {config : data};
	
		$('#sWidget' + widgetId).animate({opacity: 0.3}, "fast");
	
		$.ajax({
			type : "POST", 
			url : sHTTP, 
			dataType : "html",
			data : {
				cmd:'SaveWidgets',
				singleWidgetMod :1, 
				widgetState:JSON.encode(ws)
			},
			widgetId:widgetId,
			success : function(a){
				$('#sWidget' + this.widgetId).replaceWith(a);
			}
		});
	}
}

var sHideNewWidgetsBlock = function(obj){
  $(obj).parent().remove();
  $.ajax({
    type:'POST',
    url: sHTTP,
    dataType : 'json',
    data : {
      cmd : 'HideNewWidgets',
      ajax : 1
    }
  })
}

var sVote = function(){
    answer_id = $('#poller input:checked').val();
    poll_id   = $('#poll_id').val();
    
    $.ajax({
		type : "POST", 
		cache: false,
		url : sHTTP, 
		dataType : "html",
		data : {
			cmd : 'DoVote',
			answerId: answer_id,
                        pollId: poll_id
                        
		},
		
		success : function(a){
			$('#poll_injection').replaceWith(a);
		}
	});
}

function sShowPollResult()
{
    poll_id   = $('#poll_id').val();
    
    $.ajax({
		type : "POST", 
		cache: false,
		url : sHTTP, 
		dataType : "html",
		data : {
			cmd : 'showPollResult',
			pollId: poll_id
                        
		},
		
		success : function(a){
			$('#poll_injection').replaceWith(a);
		}
	});
}

function checkRegion(rId)
{
    $('#region-wrapper-'+rId + ' .region-towns-list :checkbox').removeAttr('checked');
    $('.news-menu .towns-row :checkbox').removeAttr('checked');
}

function checkTown(rId)
{
    $('#region-wrapper-'+rId + ' .region-title :checkbox').removeAttr('checked');
    $('.news-menu .towns-row :checkbox').removeAttr('checked');
}

function checkActiveTown(rId)
{
    $('#region-wrapper-'+rId + ' .region-title :checkbox').removeAttr('checked');
    $('#region-wrapper-'+rId + ' .region-towns-list :checkbox').removeAttr('checked');
}