var taskList;
var tasks;
var statusOK;
var totalTasks;
var servicesOK;

$(document).ready(function() {
	taskList = [];
	tasks = [];
	
	$('#manual').css('display', 'block');
	$('#automatic').css('display', 'none');
	
	tmp = '<table cellspacing="0" cellpadding="0"><tr>';
	allservices = {'0' : {"text" : "Русскоязычные", "data" : "russian"}, '1' : {"text" : "Англоязычные", "data" : "english"}, '2' : {"text" : "Все", "data" : "all"}};
	for(i in allservices)
	{
		currentservice = allservices[i];
		tmp += '<td><div class="variants" onclick="javascript: loadSCollection($(this), \''+currentservice.data+'\');" style="margin: 5px 0px 0px 5px; cursor: pointer;"><table cellspacing="0" cellpadding="0"><tr><td valign="middle">'+currentservice.text+'</td><td width="20" align="right"><img src="images/apply.gif" class="variants-image" /></td></tr></table></div></td>';
	}
	$('#services').before(tmp);
	tmp += '</tr></table>';

	$.blockUI.defaults.pageMessageCSS.width = '600px';
	$.blockUI.defaults.pageMessageCSS.height = '250px';
	$.blockUI.defaults.pageMessageCSS.margin = '-125px 0px 0px -300px';
	
	$('#url').dblclick(function() {
		check = ['title', 'feed', 'tags'];
		inputs = $('input[@type="text"]');
		if (!trim(inputs[0].value))
			inputs.each(function() {this.value=''});
		else
		{
			for(i=0; i<check.length; i++)
				$('#'+check[i]).val('Идет запрос...');
			flash($(inputs[0]), '#66FF66', 400);
			if (!trim(inputs[2].value))
				inputs[2].value = inputs[0].value;
			$.getJSON("getblogdata.php",
			{url: inputs[0].value},
			function(data) {
				for(i=0; i<check.length; i++)
				{
					tmp = $('#'+check[i]);
					tmp.val(data[check[i]]);
					flash(tmp, '#66FF66', 400);
				}
			}
			);
		}
	});
	
	$('#customServicesButton').click(function() {
		TcustomServicesWindow = $('#customServicesWindow').html();
		$.blockUI(TcustomServicesWindow); 
	});
	$('#customTasksButton').click(function() {
		TcustomServicesWindow = $('#customTasksWindow').html();
		$.blockUI(TcustomServicesWindow); 
	});
	$('#pingButton').click(function() {ping()});
});

function loadSCollection(jqElm, cName)
{
	 flash(jqElm, '#66FF66', 200);
	 $.post('base.php', {type: cName}, function(data) {flash($('#services'), '#66FF66', 500); $('#services').val(data)});
}

function show(id)
{
	$('div[@class="blockUI blockMsg"] #'+id).animate({height: 'toggle', opacity: 'toggle'}, "slow");
}

function FileUpload(mode)
{
	$('div[@class="blockUI blockMsg"] #buttonUpload')
	.ajaxStart(function(){
		$(this).attr('disabled', true);
		$(this).val('Загрузка...');
		$(this).next().attr('disabled', true);
	})
	.ajaxComplete(function(){
		$(this).attr('disabled', false);
		$(this).val('Загрузить');
		$(this).next().attr('disabled', false);
	});
	$.ajaxFileUpload({
		url:'fileupload.php',
		secureuri:false,
		fileElementId: 'File',
		dataType: 'json',
		success: function (data, status)
		{
			if(typeof(data.error) != 'undefined')
			{
				if(data.error != '')
					alert(data.error);
				else
					eval(mode+'Callback(data.data);');
			}
		},
		error: function (data, status, e) {	alert('Файл не был загружен!'); }
	});
	return false;
}

function servicesCallback(data)
{
	$('#services').val(data);
	$.unblockUI();
}

function tasksCallback(data)
{
	taskList = [];
	for(i in data)
	{
		tmp = data[i];
		taskList.push([tmp[0], tmp[1], tmp[2], tmp[3], tmp[4]]);
	}
	$('#manual').css('display', 'none');
	$('#automatic').css('display', 'block');
	$('#automatic').html('<font class="label">Добавлено заданий: '+taskList.length+'</font><br /><input type="button" value="Посмотреть список" class="button" onclick="javascript: viewTaskList();" /><input type="button" value="Удалить список" class="button" onclick="javascript: $(\'#manual\').css(\'display\', \'block\'); $(\'#automatic\').css(\'display\', \'none\'); taskList = [];" />');
	$.unblockUI();
}

function viewTaskList()
{
	tmp = '';
	for(i=0; i<taskList.length; i++)
	{
		tmp += '<font size="+1">Задание №'+(i+1)+'</font>';
		tmp += '<hr />';
		tmp += '<strong>URL блога</strong><br>';
		tmp += taskList[i][0];
		tmp += '<br><strong>Название блога</strong><br>';
		tmp += taskList[i][1];
		tmp += '<br><strong>URL изменившейся страницы</strong><br>';
		tmp += taskList[i][2];
		tmp += '<br><strong>URL RSS, RDF или Atom</strong><br>';
		tmp += taskList[i][3];
		tmp += '<br><strong>Теги сайта</strong><br>';
		tmp += taskList[i][4];
		tmp += '<br /><br /><br />';
	}
	$('#taskListDiv').html(tmp);
	TtaskListWindow = $('#taskListWindow').html();
	$.blockUI(TtaskListWindow); 
}

function flash(elm, color, delay)
{
	elm.animate({backgroundColor: color}, 100, false, function() {$(this).animate({backgroundColor: '#FFFFFF'}, (!delay)? 3000: delay)});
}

Array.prototype.contains = function(elem) 
{
	var i;
	for (i=0; i<this.length; i++)
    	if (this[i] == elem)
			return true;
	return false;
}

function trim(string)
{
	return String(string).replace(/(^\s+)|(\s+$)/g, "");
}

function ping()
{
	checkFields = (!taskList.length)? ['url', 'title', 'changedurl', 'feed', 'services'] : ['services'];
	allOK = true;
	for(i=0; i<checkFields.length; i++)
		if (!trim($('#'+checkFields[i]).val()))
		{
			flash($('#'+checkFields[i]), '#FF6666');
			allOK = false;
		}
	if (!allOK)
	{
		alert('Незаполнено одно или несколько обязательных полей!');
		return false;
	}

	if (!taskList.length)
		taskList[0] = [$('#url').val(), $('#title').val(), $('#changedurl').val(), $('#feed').val(), $('#tags').val()];
	
	tmpServices = $('#services').val().split("\n");
	tasks = [];
	for(j=0; j<taskList.length; j++)
	{
		for(i=0; i<tmpServices.length; i++)
		{
			currservice = trim(tmpServices[i]);
			if (currservice)
			{
					tmp = [];
					tmp['service'] = currservice;
					tmp['data'] = taskList[j];
					tasks.push(tmp);
			}
		}
	}
	TpingWindow = $('#pingWindow').html();
	$.blockUI(TpingWindow);
	statusOK = 0;
	servicesOK = [];
	totalTasks = tasks.length;
	pingNext();
}

function pingNext()
{
	elm = $('div[@class="blockUI blockMsg"] #pingDiv');
	if (!tasks.length)
	{
		elm.append('Работа окончена<br /><br />');
		elm.append('<strong>Удачно</strong>: '+statusOK+'<br /><strong>Ошибок</strong>: '+(totalTasks-statusOK)+'<br />');
		elm.append('<strong>Список работающих сервисов</strong>: <br />'+servicesOK.join('<br />'));
		
		elm.animate({height: '160px'}, 400, function() {elm.after('<input type="button" value="Закрыть окно" class="button" onclick="javascript: $.unblockUI(); return false;" />');});
		
		return false;
	}
	currItem = tasks.pop();
	
	elm.append('Пинг <a href="'+currItem['data'][0]+'" target="_blank">'+currItem['data'][1]+'</a><br>');
	elm.append('Сервис '+currItem['service']+'...');
	elm[0].scrollTop += 100;
	$.ajax({
		type: "POST", 
		url: "ping.php", 
		cache: false,
		timeout: 20000,
		data:
		{
			service: currItem['service'],
			url: currItem['data'][0],
			title: currItem['data'][1],
			urlc: currItem['data'][2],
			rss: currItem['data'][3],
			tags: currItem['data'][4]
		}, 
		success: function(data) 
		{
			tmp = $(data);
			if (tmp.find('status').text()=='1')
			{
				elm.append('<font color="green">ok</font>');
				statusOK++;
				if (!servicesOK.contains(currItem['service']))
					servicesOK.push(currItem['service']);
			}
			else
				elm.append('<font color="red">ошибка</font>');
			message = trim(tmp.find('message').text());
			if (message)
				elm.append(' ('+message+')');
			elm.append('<br/ ><br/ >');
			pingNext();
		},
		timeout: function()
		{
			elm.append('истек лимит времени ожидания<br/ ><br/ >');
			pingNext();
		},
		error: function()
		{
			elm.append('ошибка отправки запроса<br/ ><br/ >');
			pingNext();
		}
	});
}