var c_flag = false;
var m_names = {};
m_names["1"]="января";
m_names["2"]="февраля";
m_names["3"]="марта";
m_names["4"]="апреля";
m_names["5"]="мая";
m_names["6"]="июня";
m_names["7"]="июля";
m_names["8"]="августа";
m_names["9"]="сентября";
m_names["10"]="октября";
m_names["11"]="ноября";
m_names["12"]="декабря";

var li_class='';
var project_id = 0;
var user_id = 0;

var support_menu_$;

$(document).ready(function()
{
	$('#header ul a').each(function(){
		if ($(this).html() == 'техподдержка')
		{
			support_menu_$ = $(this);
			
			$('#index').append('<iframe style="display:none;position:absolute;width:0;height:0" src="'+this.href+'"></iframe>');
		}
	});	
	
	askServer(true);
	
	//alert(support_menu_$.attr('href').split('?')[1]);

	// переодически дергаем сервер, чтобы не ушла авторизация
	setInterval(askServer, 240000);
	//http://portal.webrover.ru/ligth.php?class=a
	
	$("#project-list .title u,#planning-list .title u").live("click",function()
	{
		$("#project-list .elem,#planning-list .elem").not($(this)).addClass("collapsed");
		if ($(this).parent().parent().parent().attr("rel")!="y")
		{
			$(this).parent().parent().parent().removeClass("collapsed");
			$("#project-list .elem,#planning-list .elem").attr("rel","n");
			$(this).parent().parent().parent().attr("rel","y");
		}
		else
		{
			$("#project-list .elem,#planning-list .elem").attr("rel","n");
		}
		//$(this).parent().parent().parent().toggleClass("collapsed");
	});
	
	// кнопка закрытия окна
	$(".windows .close-button").live("click",function()
	{
		$("#window-1").animate({opacity: 'toggle'},250,function()
		{
			$("#window-1 .content").html("");
		});
	});

	// инфа о задаче , в т.ч. получаемая через ссылку в логе
	$("#project-list ul li a,#left-menu li a.task").live("click",function()
	{
		var flmsg = ($(this).attr("class").indexOf('message-not-read')>0); // надо отметить факт прочтения
		if (flmsg) $(this).removeClass("message-not-read");
		// сообщения переписки
		
		$("#window-1").css("margin-top","-150px");
		$("#window-1").addClass("window-content-not-load");
		$("#window-1").animate({opacity: 'toggle'},250);
		$("#window-1 .content").load($(this).attr("href"),function()
		{
			// прочли переписку
			if (flmsg)
			{
				var id_ = $("#info-task-id").get(0).value;
				$.post('/api/task.php',{operation: 'setmsgreaded',id: id_,user: 0});
			}
			
			//$("#window-1").css("margin-top",-$("#window-1").height()/2+'px');
			var dy = -$("#window-1").height()/2;
			$("#window-1").css("margin-top", dy+"px");
			$("#window-1").removeClass("window-content-not-load");
			
			// проставляем трудоемкость задачи, если есть			
			if ($("#hour-for-complit").length>0)
			{
				var timehit = $("#window-1 input[name='PROPERTY_TaskSize']").get(0).value;
				//alert(timehit);
				var h_ =(timehit/60);
				h_ = h_ - (h_%1);
				var m_ = timehit-h_*60;
				$("#hour-for-complit").get(0).options[h_].selected=true;
				$("#minutes-for-complit").get(0).options[m_/15].selected=true;
			}
			wevent1();			
		});

		return false;
	});	
	
	// создание новой задачи
	$("#project-list .title .plus").live("click",function()
	{
		$("#window-1").css("margin-top","-150px");
		$("#window-1").addClass("window-content-not-load");
		$("#window-1").animate({opacity: 'toggle'},250);
		project_id = $(this).parent().children("u").attr("class");			
		$("#window-1 .content").load('/taskajax.php?group_id='+$(this).parent().children("u").attr("class"),function()
		{			
			$("#window-1").removeClass("window-content-not-load");
			wevent2();			
		});
	});
	
	// создание новой задачи на странице "задачи" и "проекты"
	$("#project-list .s-title .plus").live("click",function()
	{
		var usID = $(this).parent().children("input").attr("value");		
		var grID = $(this).parent().children("u").attr("class");
		
		$("#window-1").addClass("window-content-not-load");
		$("#window-1").animate({opacity: 'toggle'},250);
		project_id = grID;
		user_id = usID;
		$("#window-1 .content").load('/taskajax.php?group_id='+grID+'&assigned='+usID,function()
		{
			$("#window-1").removeClass("window-content-not-load");
			wevent2();			
		});
	});
	
});

function wevent1()
{
	// форма информации о задачи
	$("#task-accept").click(function() // принять задачу
	{
		formsbm1("HEEA_NotStarted_InProgressEvent",50);
	});
	$("#task-finished").click(function() // завершить задачу
	{
		formsbm1("HEEA_InProgress_CompleteEvent",100);
	});	
	$(".file-send-wrapper input").change(function()
	{
		supportFile($(this),false);
	});
	// возможность редактирования исполнителя
	$(".impl-list .edit-impl").click(function()
	{
		$(this).parent().find("a").hide();
		$(this).parent().find("select").show();
	});
	$(".userlist").change(function()
	{
		$(this).parent().find(".save-impl").show();
	});
	// сохраняем отредактированного исполнителя
	$(".impl-list .save-impl").click(function()
	{
		var ahref = '';
		ahref = '/taskajax.php?action=edit&iamauthor&task_id='+$("#info-task-id").get(0).value+
				'&group_id='+$("#task-group-id").get(0).value;
		$("#window-1 .content").hide();
		$("#window-1").addClass("window-content-not-load");
		
		$.post('/api/task.php',{operation: 'editex',
								task: $("#info-task-id").get(0).value,
								userid: $(this).parent().attr("rel"),
								usernew: $(this).parent().find("select").get(0).value},
		function()
		{
			// сброс кэша для данного проекта
			$.post('/api/task.php',{id: $("#task-group-id").get(0).value,user:GetTA(),operation: 'clearcashe',project: '0'});
			
			$.get(window.location.href,{isajax: 'y'},function(data)
			{
				// запоминаем какой пункт списка был раскрытым
				li_class=$("#project-list .elem[rel='y'] .title u").attr("class");
				$("#index").html(data);					
				wbr_init();
				// раскрываем его
				$("#project-list .elem .title u."+li_class).parent().parent().parent().removeClass("collapsed");
				$("#project-list .elem .title u."+li_class).parent().parent().parent().attr('rel','y');

				
				// подгружаем обратно задачу в окно
				$("#window-1 .content").hide();
				$("#window-1").animate({opacity: 'toggle'},1);
				$("#window-1").addClass("window-content-not-load");
				$("#window-1 .content").load(ahref,function()
				{					
					var dy = -$("#window-1").height()/2;
					$("#window-1").css("margin-top", dy+"px");
					$("#window-1").removeClass("window-content-not-load");
					$("#window-1 .content").show();
					wevent1();			
				});
			});
		});
	});
	
	$("textarea").click(function()
	{
		if ($(this).get(0).value=="Введите текст сообщения") 
		{
			$(this).attr("value","");
			$(this).removeClass("no-active");
		}
	});
	$("textarea").blur(function()
	{
		if ($(this).get(0).value=="")
		{
			$(this).attr("value","Введите текст сообщения");
			$(this).removeClass("no-active");
		}
	});
	// сабмит сообщения
	$("#wbr-chat-send").click(function()
	{
		$("#window-1 .content").hide();
		$("#window-1").addClass("window-content-not-load");
		
		// убираем надпись Введите текст сообщения
		if ($("#window-1 textarea").get(0).value=='Введите текст сообщения')
			$("#window-1 textarea").attr("value","");
			
		var val_ = $("#window-1 textarea").get(0).value;
		val_ = str_replace(">","&gt;",val_);
		val_ = str_replace("<","&lt;",val_);
		val_ = str_replace("\n","<br/>",val_);
		
		$("#window-1 textarea").attr("value",val_);

		$("form[name='iblock_add']").ajaxSubmit(function(data)
		{
			// сброс кэша для данного проекта
			$.post('/api/task.php',{id: $("#task-group-id").get(0).value,user:GetTA(),operation: 'clearcashe',project: '2'});
			
			var pth = $("form[name='bx_users_filter_simple_form']").attr("action");
			
			$("#window-1 .content").load(pth,function()
			{				
				var dy = -$("#window-1").height()/2;
				$("#window-1").css("margin-top", dy+"px");
				$("#window-1").removeClass("window-content-not-load");
				$("#window-1 .content").show();
				wevent1();
			});	
			// открываем задачу
			if ($(".select-time-elem input[type='button']").length==0)
			{				
				formsbm1("NotAccepted",0);				
			}
				// сшибаем флаг завершенности у последнего исполнителя
				var id_ = $("#info-task-id").get(0).value;
				$.post('/api/task.php',{operation: 'canselfinish',task: id_});
		});
	});
}


	// добавить новый список выбора исполнителя
	$(".add-new-implement").live("click",function()
	{
		var html_ = $("#window-1 .form-elem:first").html()+'<span class="remove-implement"></span>';//<span class="save-implement"></span>';
		$("#window-1 .form-elem:last").after("<p class='form-elem'>"+html_+"</p>");
		//wevent2_add_new_userlist();
		var dy = -$("#window-1").height()/2;
		$("#window-1").css("margin-top", dy+"px");
		
		$(".task-create-data-showed:last").datePicker({
			createButton:false,
			clickInput:true,
			startDate: '01-01-2000'
		});
		$(".task-create-data-showed:last").addClass("no-active");
		$(".task-create-data-showed:last").blur(function()
		{
			if ($(this).get(0).value=="")
			{
				$(this).attr("value","Срок готовности");
				$(this).addClass("no-active");
			}
		});
	});
	// удалить список выбора пользователя
	$(".remove-implement").live("click",function()
	{
		$(this).parent().remove();
		var dy = -$("#window-1").height()/2;
		$("#window-1").css("margin-top", dy+"px");
	});

$(".task-create-data-showed").live("click",function()
{
	if ($(this).get(0).value=="Срок готовности")
	{
		$(this).attr("value","");
		$(this).removeClass("no-active");
	}
});

function wevent2()
{
	// добавляем функционал набития исполнителей \\	
	// меняем в выпадающем списке 
	$("#window-1 .userlist:first").change(function()
	{
		_active = $($(this).get(0).options[$(this).get(0).selectedIndex]);
	
		var this_ = _active.html()+" <"+_active.attr("class")+"> ["+$(this).get(0).value+"]";
		//alert(this_);
		$("input[name='PROPERTY_TaskAssignedTo']").attr("value",this_);
	});
	// добавить новый список выбора исполнителя
	//wevent2_add_new_userlist();
	
	/*\\ добавляем функционал набития исполнителей */
	
	$(".task-create-data-showed").datePicker({
		createButton:false,
		clickInput:true,
		startDate: '01-01-2000'
	});
	
	$("input[type='text'],textarea").click(function()
	{
		//$(this).attr("value","");
		//$(this).removeClass("no-active");
		if ($(this).attr("name")=="NAME")
		{
			if ($(this).get(0).value=="Новая задача") 
			{
				$(this).attr("value","");
				$(this).removeClass("no-active");
			}
		}
		if ($(this).attr("name")=="DETAIL_TEXT")
		{
			if ($(this).get(0).value=="Введите текст сообщения") 
			{
				$(this).attr("value","");
				$(this).removeClass("no-active");
			}
		}
	});
	$("input[type='text'],textarea").blur(function()
	{
		if ($(this).get(0).value=="")
		{
			$(this).addClass("no-active");
			if ($(this).attr("name")=="NAME")
			{
				$(this).attr("value","Новая задача");
			}			
			if ($(this).attr("name")=="DETAIL_TEXT")
			{
				$(this).attr("value","Введите текст сообщения");
			}
		}
	});
	
	$(".file-send-wrapper input").change(function()
	{
		supportFile($(this),true);
	});	
	
	
	$("#task-create-submit").click(function()
	{		
		$("#task-create-data").attr("value",$(".task-create-data-showed").get(0).value);
		
		flag_=false;
		for (i=0;i<$(".task-create-data-showed").length;i++)
		{
			if (($(".task-create-data-showed").get(i).value=='') || ($(".task-create-data-showed").get(i).value=='Срок готовности'))
			{
				flag_=true;
				$(".task-create-data-showed:eq("+i+")").css("borderColor","#ff0000");
			}
		}
		if (flag_) return false;

		$("#window-1 .content").hide();
		$("#window-1").addClass("window-content-not-load");
		// убираем надпись Введите текст сообщения
		if ($("#window-1 textarea").get(0).value=='Введите текст сообщения')
			$("#window-1 textarea").attr("value","");
			
		var val_ = $("#window-1 textarea").get(0).value;
		val_ = str_replace(">","&gt;",val_);
		val_ = str_replace("<","&lt;",val_);
		val_ = str_replace("\n","<br/>",val_);
		$("#window-1 textarea").attr("value",val_);
			
		var user_ = $("input[name='PROPERTY_TaskAssignedTo']").get(0).value;
				var i_ = user_.indexOf('[');
				user_ = user_.substr(i_+1,user_.length-i_-2);
				
		var title_ = $("#window-1 .title").get(0).value;
		var body_ = $("#window-1 textarea").get(0).value;
			
		// набиваем в массив ид исполнителей и сроки
		var arr=[];
		var arrd=[];
		var obj_;
		var id_ = 0;
		for (i=0;i<$("#window-1 .form-elem").length;i++)
		{
			obj_ = $("#window-1 .form-elem:eq("+i+") select").get(0);
			id_ = obj_.selectedIndex;
			arr[i] = obj_.options[id_].value;
			arrd[i] = $("#window-1 .task-create-data-showed").get(i).value;
		}

		$("form[name='bx_users_filter_simple_form']").ajaxSubmit(function(data)
		{
			if (data.indexOf("task-error-id",0)>0)
			{
				$("#window-1").removeClass("window-content-not-load");
				$("#window-1 .content").show();
				$("#window-1 .content").html(data);
				wevent2();
			}
			else
			{
				j_ = jQuery(data).find('input[name="PROPERTY[NAME][0]"]');
				//alert(j_.get(0).value);
				sendmail(user_,title_,body_);
				// сброс кэша для данного проекта и пользователя
				ussID = $("select.userlist").get(0).value;	

				$.post('/api/task.php',{id: project_id,user:ussID, operation: 'clearcashe',project: '0'});

				// сохранение списков исполнителей в БД
				saveimplementations(arr,arrd,j_.get(0).value,0);
				$.get(window.location.href,{isajax: 'y'},function(data)
				{
					// запоминаем какой пункт списка был раскрытым
					li_class=$("#project-list .elem[rel='y'] .title u").attr("class");												
					$("#index").html(data);
					wbr_init();
					// раскрываем его
					$("#project-list .elem .title u."+li_class).parent().parent().parent().removeClass("collapsed");
					$("#project-list .elem .title u."+li_class).parent().parent().parent().attr('rel','y');

					//$("#window-1").animate({opacity: 'toggle'},250);
				});
				
				// привязка задачи к типовой работе планирования
				objSel = $("#planning-link-select").get(0);
				$.post('/api/task.php',{operation: 'setlinkforplanning',
										task: j_.get(0).value,
										workname: $(objSel.options[objSel.selectedIndex]).html(),
										work: objSel.value});
			}
		});
	});
}

function sendmail(user_,title_,body_)
{
				// отправляем запрос на отсылку уведомления на почту
				$.post('/api/index.php',{operation: 'sendmail',user: user_,
							title: title_, body: body_},function(data){});
}
function saveimplementations(arr,arrd,taskid,i)
{
	//alert(arr.length);
	//alert("!");	
	//for (i=0;i<arr.length;i++)
	//{
	if (i<arr.length)
	{
		$.post('/api/task.php',{operation: 'addimplemantation',task: taskid,user: arr[i],datato: arrd[i]},function(data){
				saveimplementations(arr,arrd,taskid,i+1);
		});
	}
	//}
}

function formsbm1(taskcomplete,taskcompleteV)
{
	$("#window-1 .content").hide();
	$("#window-1").addClass("window-content-not-load");
		
		//$("input[name='PROPERTY_TaskComplete']").attr("value",50);
		var frm = $("form[name='bx_users_filter_simple_form']");
		var pth = frm.attr("action");
		var nam = frm.children("input[name='NAME']").get(0).value;
		var asg = frm.children("input[name='PROPERTY_TaskAssignedTo']").get(0).value;
		var pr = frm.children("input[name='PROPERTY_TaskPriority']").get(0).value;
		var sid = $("#sessid").get(0).value;
		// записываем в задачу сколько !!!минут!!! она будет идти или идет
		var timehit  = 0;
		if ($("#hour-for-complit").length>0)
			var timehit  = $("#hour-for-complit").get(0).value*60+1*$("#minutes-for-complit").get(0).value;			

		$.post(pth,
		{
				PROPERTY_TaskComplete: taskcompleteV,
				bizproc_event: taskcomplete,
				NAME: nam,
				PROPERTY_TaskAssignedTo: asg,
				PROPERTY_TaskPriority: pr,
				apply: "Сохранить",
				//PROPERTY_TaskSize: timehit,				
				sessid: sid
				//PROPERTY_TaskAlert
		},
		function()
		{
			// перемещение задачи по цепочке исполнителей после завершения			
			if (taskcompleteV==100)
			{			
				$.post('/api/task.php',{operation: 'movetask',task: $("#info-task-id").get(0).value});
			}
			// сброс кэша для данного проекта
			$.post('/api/task.php',{id: $("#task-group-id").get(0).value,user:GetTA(),operation: 'clearcashe',project: '2'});
			
			$.get(window.location.href,{isajax: 'y'},function(data)
			{
				// запоминаем какой пункт списка был раскрытым
				li_class=$("#project-list .elem[rel='y'] .title u").attr("class");
				$("#index").html(data);					
				wbr_init();
				// раскрываем его
				$("#project-list .elem .title u."+li_class).parent().parent().parent().removeClass("collapsed");
				$("#project-list .elem .title u."+li_class).parent().parent().parent().attr('rel','y');

				//$("#window-1").animate({opacity: 'toggle'},250);
			});
		});
}

function supportFile(obj,fl)
{
	var fname = String(obj.get(0).value);
	var name0 = obj.parent().parent().find('.left-part').html(); // левая часть, из которой состоит имя поля
	var name1 = obj.parent().parent().find('.right-part').html(); // пр. часть, из которой состоит имя поля

	if (fname=="") return false;
	
	var i = fname.lastIndexOf("\\");
	if (i>0)
	{
		fname = fname.substr(i+1);
	}
	obj.parent().find("span").html(fname);
	obj.parent().find("span").css("text-decoration","none");
	
	//var len = $(".file-send-wrapper").length;
	var len = obj.parent().parent().find(".file-send-wrapper").length;
	
	//if ((obj.attr("name")!="PROPERTY_TaskFiles[n"+(len-1)+"]") && (len>1)) return false;
	if ((obj.attr("name")!=name0+(len-1)+name1) && (len>1)) return false;
		
	// add fileload	
	if (fl)
	{
		obj.parent().parent().append("<div class='file-send-wrapper'><input type='file' class='ifile' size='0' name='"+name0+len+name1+"' /><span class='file-send-click'>" + 
		$("#attach-more").html()+"</span></div>");
	}
	else
	{
		obj.parent().parent().append("<div class='file-send-wrapper'><input type='file' class='ifile' size='0' name='"+name0+len+name1+"' /><input type='hidden' value='' name='PROPERTY[259]["+len+"]'/><span class='file-send-click'>" + 
		$("#attach-more").html()+"</span></div>");
	}	
		obj.parent().parent().find(".file-send-wrapper").css("overflow","hidden");
		var obj = obj.parent().parent().find(".file-send-wrapper input");
		obj.css("opacity","0");
		obj.css("font-size","20px");
		obj.css("left","-208px");
		$(".file-send-click").css("display","block");
		$(".file-send-wrapper input").change(function()
		{
			supportFile($(this));
		});
}

function str_replace(search, replace, subject) {
    return subject.split(search).join(replace);
}
// извлекает ид пользователя из строки формы просмотра задачи
function GetTA()
{
	str_ = $("input[name='PROPERTY_TaskAssignedTo']").get(0).value;
	i_ = str_.indexOf("[");
	j_ = str_.indexOf("]");
	return str_.substr(i_+1,j_-i_-1);
}

function askServer(onlylog)
{
	if ($("#left-menu .attention").length>0)
	{
		$("#left-menu ul,#left-menu .attention").hide();
		$("#left-menu").css("background-image","url('/bitrix/templates/webrover/import/i/ajax-loader.gif')");
		$("#left-menu").css("background-position","center");
		$("#left-menu").css("background-repeat","no-repeat");
		$("#left-menu").height("200px");
		$.get(document.location.href,{getlog: 'Y'},function(data)
		{
			datahtml = $(data).find("#left-menu").html();
			$("#left-menu").html($(data).find("#left-menu").html());
			$("#left-menu").attr("style","");
			$("#left-menu ul,#left-menu .attention").show();
			
			if (typeof onlylog == 'undefined')
				$("#content").html($(data).find("#content").html());

			wbr_init();
			
			// обновляем токен авторизаций
			var $menu = $(data).find('#header').html();
			$('#header').html($menu);
			
			$('#header ul a').each(function(){
				if ($(this).html() == 'техподдержка')
				{
					support_menu_$ = $(this);
				}
			});	
		});
	}
	else
	{
		$.get('http://portal.webrover.ru/?getalltiskets=y',function(data)
		{
			if ($(data).find("#left-menu ul:first li.support").length>0)
			{	// поймали обращение в техподдержку
				$(".support-new-message").remove();
				$("#index").prepend("<div class='support-new-message'>"+$(data).find("#left-menu ul:first li.support").html()+"</div>");
				
				$(".support-new-message a").click(function()
				{
					$(".support-new-message").remove();
				});
			}
		});
		$.get(document.location.href,function(data)
		{
			// обновляем токен авторизаций
			var $menu = $(data).find('#header').html();
			$('#header').html($menu);
			
			$('#header ul a').each(function(){
				if ($(this).html() == 'техподдержка')
				{
					support_menu_$ = $(this);
				}
			});	
		});
	}
}


// Установить куки
function setCookie(name, value) {
      var valueEscaped = escape(value);
      var expiresDate = new Date();
      expiresDate.setTime(expiresDate.getTime() + 24 * 60 * 60 * 1000); // срок - 1 день
      var expires = expiresDate.toGMTString();
      var newCookie = name + "=" + valueEscaped + "; path=/; expires=" + expires;
      if (valueEscaped.length <= 4000) document.cookie = newCookie + ";";
}

// Получить куки
function getCookie(name) 
{
      var prefix = name + "=";
      var cookieStartIndex = document.cookie.indexOf(prefix);
      if (cookieStartIndex == -1) return null;
      var cookieEndIndex = document.cookie.indexOf(";", cookieStartIndex + prefix.length);
      if (cookieEndIndex == -1) cookieEndIndex = document.cookie.length;
      return unescape(document.cookie.substring(cookieStartIndex + prefix.length, cookieEndIndex));
}
