
var mitem = {};
mitem.id = 0;
mitem.tagsTimer = 0;
mitem.onlyRegisteredTags = false;
mitem.maxTagsPerItem = 0;
mitem.saveTags = false;
mitem.sizeTags = false;
mitem.liveTags = '';
mitem.lastTagTerm = "";
mitem.lastTagMatches = [];
mitem.menus = {};
mitem.toolWidth = 0;
mitem.toolHeight = 0;
mitem.menuHeadWidth = 0;
mitem.menuHeadHeight = 0;

function mitemInitializeForm (textMode)
	{
	if (!core.isMobile && (!textMode || textMode == 0))
		{
		CKEDITOR.replace('mitem-text', {customConfig : baseURL+'/'+pubDir['lib']+'/js/wysiwyg.js'});
		}
	mitemUpdateRemainingTags();
	mitemInitializeTags();
	}

function mitemInitializeTags ()
	{
	$('[name=tags]').autocomplete
		({
		minLength: 1,
		source: function (t, r)
			{
			var term = t.term.split(/,\s*/).pop();
			var tagMatches = [];
			var fetch = true;
			if (term.length >= 1 && !(mitem.lastTagMatches.length == 0 && mitem.lastTagTerm != '' && term.substr(0, mitem.lastTagTerm.length) == mitem.lastTagTerm))
				{
				$.ajax
					({
					async: false,
					type: 'POST',
					url: 'ajax.php?do=tags-registered_tags',
					data: {'term': term, 'usedList': t.term},
					success: function (xml)
						{
						$(xml).find('tag').each
							(
							function ()
								{
								tagMatches[tagMatches.length] = $(this).text();
								}
							);
						},
					dataType: 'xml'
					});
				}
			mitem.lastTagTerm = term;
			mitem.lastTagMatches = tagMatches;
			r(tagMatches);
			},
		focus: function ()
			{
			return false;
			},
		select: function (event, ui)
			{
			var terms = this.value.split(/,\s*/);
			terms.pop();
			terms.push(ui.item.value);
			terms.push("");
			this.value = terms.join(", ");
			return false;
			}
		})
	.focus
		(
		function ()
			{
			if (mitem.onlyRegisteredTags || mitem.maxTagsPerItem > 0)
				{
				showFieldTip($(this), $('#mitem-tags-tip'));
				}
			}
		)
	.bind
		(
		'keyup blur',
		function (e)
			{
			// filter unregistered tags
			if (mitem.onlyRegisteredTags && (e.type == 'blur' || e.which == 188 || e.which == 13))
				{
				if (mitem.tagsTimer > 0)
					{
					clearTimeout(mitem.tagsTimer);
					}
				mitem.tagsTimer = setTimeout
					(
					function ()
						{
						tagsFilterUnregistered($('[name=tags]'), function () {mitemUpdateRemainingTags();});
						},
					333
					);
				}
			// only allow X tags
			if (mitem.maxTagsPerItem > 0)
				{
				mitemUpdateRemainingTags();
				}
			if (e.which == 13)
				{
				setTimeout(function(){mitemUpdateTags();}, 334);
				}
			}
		);
	}

function mitemUpdateTags ()
	{
	$.post
		(
		'ajax.php?do=mitem-update_tags',
		{'id': mitem.id, 'tags': $('[name=tags]').val(), 'size': mitem.sizeTags},
		function (xml)
			{
			var newTagString = "";
			var newLiveString = "";
			$(xml).find('tags').children('tag').each
				(
				function ()
					{
					var t = $(this);
					var tag = t.text();
					newTagString += tag + ", ";
					newLiveString += "<a href='search.php?q="+tag+"' style='font-size:"+t.attr('size')+"%;'>"+tag+"</a> ";
					}
				);
			if (mitem.liveTags != '')
				{
				$(mitem.liveTags).html(newLiveString.replace(/ $/, ''));
				}
			$('[name=tags]').val(newTagString.replace(/, $/, ""));
			showStatus({'head': $(xml).find('resultHead').text(), 'body': $(xml).find('resultBody').text()});
			},
		'xml'
		);
	/*
	var Request = getXMLHttpRequestObject();
	Request.open("POST", baseURL + '/ajaxdata.php?type=item_tags&id=' + itemID, true);
	Request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	var FormObject = document.getElementById('ItemTagsForm');
	var PostQuery = MakeQueryString(FormObject);
	Request.send(PostQuery);
	Request.onreadystatechange = function()
		{
		if (Request.readyState == 4) 
			{
			var itemTags = document.forms['item_tags_form']['tags'].value;
			document.forms['item_tags_form']['tags'].value = resText;
			setTimeout( function()
				{
				document.forms['item_tags_form']['tags'].value = itemTags;
				document.forms['item_tags_form']['tags'].blur();
				}
			,(resSec * 1000));
			}
		}
	*/
	}

function mitemUpdateRemainingTags ()
	{
	var tmpTags = $('[name=tags]').val().split(",");
	var tagCount = 0;
	for (var i = 0; i < tmpTags.length; i++)
		{
		tmpTags[i] = jQuery.trim(tmpTags[i]);
		if (tmpTags[i] != '')
			{
			tagCount++;
			}
		}
	var remaining = (mitem.maxTagsPerItem - tagCount);
	if (remaining >= 0)
		{
		$('.mitem-tags_remaining').show();
		$('.mitem-tags_too_many').hide();
		}
	else
		{
		$('.mitem-tags_remaining').hide();
		$('.mitem-tags_too_many').show();
		}
	$('#tags-remaining').html(remaining);
	}


function mitemAddAnotherImage (ImgText)
	{
	var curImageCount = document.getElementById('multImageCount').value;
	curImageCount++;
	var newField = '';
	newField += "<div class='mitem-row'>";
	newField += "<div class='mitem-row_left'>" + ImgText + " " + curImageCount + "</div><!-- end mitem-row_left -->";
	newField += "<div class='mitem-row_right'><input type=\"file\" class='mitem-input_file' name=\"image" + curImageCount + "\"/></div><!-- end mitem-row_right -->";
	newField += "</div><!-- end mitem-row -->";
	$('#multImageArea').append(newField);
	document.getElementById('multImageCount').value = curImageCount;
	}


function mitemAddAnotherAttachment (AttText)
	{
	var CurAddAttCount = document.getElementById('multAttachmentCount').value;
	CurAddAttCount++;
	var newField = '';
	newField += "<div class='mitem-row'>";
	newField += "<div class='mitem-row_left'>" + AttText + " " + CurAddAttCount + "</div><!-- end mitem-row_left -->";
	newField += "<div class='mitem-row_right'><input type='file' class='mitem-input_file' name='attachment" + CurAddAttCount + "'/></div><!-- end mitem-row_right -->";
	newField += "</div><!-- end mitem-row -->";
	$('#multAttachmentArea').append(newField);
	document.getElementById('multAttachmentCount').value = CurAddAttCount;
	}

function mitemToggleTextMode (mode)
	{
	var useWYSIWYG = false;
	if (mode == 1)
		{
		useWYSIWYG = false;
		}
	else if (mode == 2)
		{
		useWYSIWYG = false;
		}
	else
		{
		useWYSIWYG = true;
		}
	if (CKEDITOR.instances['mitem-text'])
		{
		//CKEDITOR.remove(CKEDITOR.instances['mitem-text']);
		CKEDITOR.instances['mitem-text'].destroy();
		}
	if (useWYSIWYG)
		{
		CKEDITOR.replace('mitem-text', {customConfig : baseURL+'/'+pubDir['lib']+'/js/wysiwyg.js'});
		}
	}

function mitemUpdateVersionField (sectionID)
	{
	var projectID = document.forms['submitform']['issue_project'].value;
	loadURLIntoID('ajaxdata.php?type=version_field&section=' + sectionID + '&project=' + projectID, 'ProjectVersionField');
	}

function mitemMenu (id, e)
	{
	var menuID = 'mitem-manager-'+id;
	if (mitem.toolHeight == 0)
		{
		$('body').append("<div class='mitem-menu_head' id='mitem-tmp-menu-head'></div><ul id='mitem-tmp-menu'><li class='mitem-menu_tool'>dummy</li></ul>");
		mitem.menuHeadHeight = $('#mitem-tmp-menu-head').outerHeight(true);
		mitem.menuHeadWidth = $('#mitem-tmp-menu-head').outerWidth(true);
		mitem.toolHeight = $('#mitem-tmp-menu').find('li').outerHeight(true);
		mitem.toolWidth = $('#mitem-tmp-menu').find('li').outerWidth(true);
		$('#mitem-tmp-menu-head').remove();
		$('#mitem-tmp-menu').remove();
		}
	if (typeof(mitem.menus[id]) == 'undefined')
		{
		var menu = "<div id='"+menuID+"'><div class='mitem-menu_loading'></div></div>";
		mitem.menus[id] = menu;
		$.post
			(
			'ajax.php?do=mitem-menu',
			{'id': id},
			function (xml)
				{
				var liHeight = 0;
				menu = "";
				var liCount = 0;
				if ($(xml).find('menu').children().size() > 0)
					{
					$(xml).find('menu').children().each
						(
						function ()
							{
							var tool = $(this);
							var action = tool.find('action').text();
							var url = baseURL+"/adm.php?action="+action+"&id="+id;
							var click = "window.location.href='"+url+"';";
							var top = (liCount * mitem.toolHeight);
							var url = baseURL+"/adm.php?action="+action+"&id="+id;
							var toolLabel = tool.find('label').text();
							if (tool.find('options').children().size() > 0)
								{
								click = "";
								toolLabel = "<select onchange=\""+tool.find('toggleAction').text()+"("+id+", this); $(this).blur();\">";
								if (tool.find('defOpt').size() > 0)
									{
									toolLabel += "<option value='"+tool.find('defOpt').children('value').text()+"'>"+tool.find('defOpt').children('label').text()+"</option>";
									}
								tool.find('options').children().each
									(
									function ()
										{
										var opt = $(this);
										var optID = opt.find('id').text();
										var isSel = "";
										if (optID == tool.find('selOpt').text())
											{
											isSel = " selected='selected'";
											}
										toolLabel += "<option value='"+optID+"'"+isSel+">"+opt.find('name').text()+"</option>";
										}
									);
								toolLabel += "</select>";
								}
							menu += "<li aid='"+action+"' class='mitem-menu_tool' style='top:+"+top+"px;' onclick=\""+click+"\"";
							menu += " onmouseover=\"mitemToolOver(this);\"";
							menu += " onmouseout=\"mitemToolOut(this);\"";
							menu += ">";
							menu += "<div class='mitem-menu_tool_icon mitem-menu_tool_icon_"+action+"'></div>";
							menu += toolLabel;
							menu += "</li>";
							liCount++;
							}
						);
					}
				mWidth = mitem.toolWidth;
				mHeight = mitem.toolHeight * liCount;
				menu = "<div class='mitem-menu_head'>"+$(xml).find('head').text()+"<div class='mitem-menu_close'></div></div><ul class='mitem-menu' id='mitem-menu-"+id+"' style='width:"+mWidth+"px;height:"+mHeight+"px;'>"+menu+"</ul>";
				$('#'+menuID).html(menu);
				mitem.menus[id] = menu;
				syncTipPosition();
				},
			'xml'
			);
		}
	else
		{
		var menu = mitem.menus[id];
		}
	showToolCap(menu, e);
	}

function mitemToolOver (obj)
	{
	$(obj).stop(true, true).animate({'left': '6px'}, 100);
	}

function mitemToolOut (obj)
	{
	var hasFocus = false;
	$(obj).children('select').each
		(
		function ()
			{
			if (this == document.activeElement)
				{
				hasFocus = true;
				}
			}
		);
	var childFocus = false;
	$(obj).children().each
		(
		function ()
			{
			$(this).mouseenter
				(
				function ()
					{
					childFocus = true;
					}
				);
			}
		);
	if (!hasFocus && !childFocus)
		{
		$(obj).stop(true, true).animate({'left': '0px'}, 100);
		}
	}

function mitemSetCategory (id, field)
	{
	$.post
		(
		'ajax.php?do=mitem-set_category',
		{'id': id, 'category': field.value},
		function (xml)
			{
			showStatus({'body': $(xml).find('result').text()});
			},
		'xml'
		);
	}

function mitemSetOpenStatus (id, field)
	{
	$.post
		(
		'ajax.php?do=mitem-set_open_status',
		{'id': id, 'status': field.value},
		function (xml)
			{
			showStatus({'body': $(xml).find('result').text()});
			},
		'xml'
		);
	}

function mitemSetStickyStatus (id, field)
	{
	$.post
		(
		'ajax.php?do=mitem-set_sticky_status',
		{'id': id, 'status': field.value},
		function (xml)
			{
			showStatus({'body': $(xml).find('result').text()});
			},
		'xml'
		);
	}

function mitemSetPhotoAlbum (id, field)
	{
	$.post
		(
		'ajax.php?do=mitem-set_photo_album',
		{'id': id, 'album': field.value},
		function (xml)
			{
			showStatus({'body': $(xml).find('result').text()});
			},
		'xml'
		);
	}
