//Глобальные переменные
var ua			= navigator.userAgent;
var IsOpera		= /opera [56789]|opera\/[56789]/i.test(ua);
var IsIE		= !IsOpera && /msie [56789]/i.test(ua);		// preventing opera to be identified as ie
var IsMozilla	= !IsOpera && /mozilla\/[56789]/i.test(ua);	// preventing opera to be identified as mz

var cursorInTagList = false;
var listIsShown = false;
var selectedTag = false;
var initialWord = false;
var inputId = false;
var cursorPos = 0;
var snc_userlist = false;
var prevSelection = false;

//Функции
function handleTagInput(iId, tagList, ev) {
	ev	= ev || window.event;
	if (ev.keyCode != 13) {
        showE("avatars_list");
        showE("catid");
        inputId = iId;
        var elem = getE(inputId);

        initialWord = "";

        var tags = elem.value;
        var commaIndex = tags.lastIndexOf(",");
        initialWord = tags;
        if (commaIndex != -1) {
            initialWord = trim(tags.substring(commaIndex + 1));
        }

        cursorPos = getCaretPos(elem);
        if (cursorPos < elem.value.length + initialWord.length) {
            var startPart = elem.value.substring(0, cursorPos);
            var endPart = elem.value.substring(cursorPos, elem.value.length);
            var startCommaPos = startPart.lastIndexOf(",");
            var endCommaPos = endPart.indexOf(",");
            startPart = startPart.substring(startCommaPos+1, startPart.length);
            endPart = endPart.substring(0, endCommaPos);
            initialWord = trim(startPart.concat(endPart));
        }
        if (initialWord.length > 1) {
            xajax_searchTags(initialWord, inputId, tagList);
        }
    }
}

function showTagList(inputId, tagList, tagListHeight) {
    var elem = getE(inputId);
    var elemTL = getE(tagList);
    var tagListTopOffset = parseInt(absPosition(elem).y) + getIntDimension(elem.style.height);
    //var tagListWidth = getIntDimension(elem.style.width) - 5;

    elemTL.style.left = absPosition(elem).x + "px";
    elemTL.style.top = tagListTopOffset + "px";
    elemTL.style.width =  "300px";
    elemTL.style.height = parseInt(tagListHeight) + "px";
    elemTL.style.display = "block";

    if (!selectedTag) {
        selectedTag = "tl0";
    }
    highlightTagListCell(selectedTag);

    hideE("avatars_list");
    hideE("catid");
    
    listIsShown = true;
}

function highlightTagListCell(cellName) {
    var elem = getE(cellName);
    selectedTag = cellName;
    elem.style.backgroundColor = "#999999";
}

function unhighlightTagListCell(cellName) {
    var elem = getE(cellName);
    elem.style.backgroundColor = "#FFFFFF";
}

function addTag(cellName) {
    var elemCell = getE(cellName);
    var elemInput = getE(inputId);

    var startPart = elemInput.value.substring(0, cursorPos);
    var endPart = elemInput.value.substring(cursorPos, elemInput.value.length);
    var startCommaPos = startPart.lastIndexOf(",");
    var endCommaPos = endPart.indexOf(",");
    if (startCommaPos == -1) {
        startCommaPos = 0;
    }
    if (endCommaPos == -1) {
        endCommaPos = elemInput.value.length;
    }

    var startWordPart = startPart.substring(startCommaPos, startPart.length);
    var endWordPart = endPart.substring(0, endCommaPos);

    startPart = startPart.substring(0, startCommaPos);
    endPart = endPart.substring(endCommaPos, endPart.length);

    var explStr = trim(startWordPart.concat(endWordPart));

    explStr = explStr.replace(initialWord, elemCell.innerHTML);

    elemInput.value = startPart + explStr + endPart;

    var checkStr = trim(elemInput.value);
    if (checkStr.substring(checkStr.length - 1, checkStr.length) != ",") {
        elemInput.value = elemInput.value + ", ";
    }

    hideTagList();
}

function hideTagList() {
    if (isShownE('tag_list')) {
        hideE('tag_list');
        showE("avatars_list");
        showE("catid");
        inputElem = getE('new_post_tags');
        if (inputElem != undefined) {
            inputElem.focus();
        }
        selectedTag = false;
        listIsShown = false;
    }
}

function handleUsernamePopup(aclId) {
    vbmenu_register('userlist' + aclId, true);
    snc_userlist = new vB_AJAX_NameSuggest('snc_userlist', 'userlist' + aclId + '_txt', 'userlist' + aclId);
}

function selectACL(listId, id) {
    listElem = getE(listId);
    listElem.style.backgroundColor="#999999";
    if ((prevSelection) && (prevSelection != listId)) {
        getE(prevSelection).style.backgroundColor="#FFFFFF";
    }
    prevSelection = listId;
    listtypeElem = getE('listtype');
    xajax_fillACLField(listtypeElem.value, id);
}


//Вспомогательные функции

function ltrim( source ){
    var index = 0;
    while( source.charAt(index) == " " ) index++;
    return source.substr(index);
}

function rtrim( source ){
    var index = source.length - 1;
    while( source.charAt(index) == " " ) index--;
    return source.substring(0, index + 1);
}

function trim( source ){
    return ltrim(rtrim(source));
}

function absPosition(obj) {
      var x = y = 0;
      while(obj) {
            x += obj.offsetLeft;
            y += obj.offsetTop;
            obj = obj.offsetParent;
      }
      return {x:x, y:y};
}

function getIntDimension(dimension) {
    return parseInt(dimension.substring(0, dimension.length - 2));
}

function preventFormSubmitIE(){
    if (window.event.keyCode == 13) {
        return false;
    }
}

function preventFormSubmit(e){
    if (e.keyCode == 13) {
        return false;
    }
}

function getCaretPos(el) {
    var rng, ii=-1;
    if(typeof el.selectionStart=="number") {
        ii=el.selectionStart;
    } else if (document.selection && el.createTextRange){
        rng=document.selection.createRange();
        rng.collapse(true);
        rng.moveStart("character", -el.value.length);
        ii=rng.text.length;
    }
    return ii;
}


//Базовые функции

function getE(id) {
    return document.getElementById(id);
}

function showE(id) {
    elem = getE(id);
    if (elem != undefined) {
        elem.style.display = "block";
    }
}

function isShownE(id) {
    elem = getE(id);
    if (elem == undefined) {
        return false;
    } else {
        if (elem.style.display == "block") {
            return true;
        } else {
            return false;
        }
    }
}

function hideE(id) {
    elem = getE(id);
    if (elem != undefined) {
        elem.style.display = "none";
    }
}

function showInlineE(id) {
    elem = getE(id);
    if (elem != undefined) {
        elem.style.display = "inline";
    }
}

function mouseCoords(ev){
	if(ev.pageX || ev.pageY){
		return {x:ev.pageX, y:ev.pageY};
	}
	return {
		x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
		y:ev.clientY + document.body.scrollTop  - document.body.clientTop
	};
}


//События
//document.onmousemove = mouseMove;
//document.onmousedown = mouseDown;
//document.onkeyup = keyUp;

function mouseMove(ev){
	ev	= ev || window.event;
	var mousePos = mouseCoords(ev);
	mouseX = mousePos.x;
	mouseY = mousePos.y;

	var tagListElem = getE('tag_list');

    if ((tagListElem != undefined) && (tagListElem.style.display == "block")) {
        var left = getIntDimension(tagListElem.style.left);
        var top = getIntDimension(tagListElem.style.top);
        var right = getIntDimension(tagListElem.style.left) + getIntDimension(tagListElem.style.width);
        var bottom = getIntDimension(tagListElem.style.top) + getIntDimension(tagListElem.style.height);

        if (cursorInTagList &&
            ((mouseX < left) ||
            (mouseX > right) ||
            (mouseY < top) ||
            (mouseY > bottom)))
        {
            hideTagList();
            cursorInTagList = false;
        } else if ((mouseX > left) &&
            (mouseX < right) &&
            (mouseY > top) &&
            (mouseY < bottom))
        {
            cursorInTagList = true;
        }
    }

	return true;
}

function mouseDown(ev){
    if (!cursorInTagList) {
	   hideTagList();
    }

	return true;
}

function keyUp(ev){
	ev	= ev || window.event;
	
    if (listIsShown) {
        switch (ev.keyCode) {
            case 40:
                if (!selectedTag) {
                    selectedTag = "tl0";
                } else {
                    unhighlightTagListCell(selectedTag);
                    var tagNo = selectedTag.substring(2, selectedTag.length);
                    tagNo++;
                    selectedTag = "tl" + tagNo;
                }
                highlightTagListCell(selectedTag);
                break;
            case 38:
                if (!selectedTag) {
                    selectedTag = "tl0";
                } else {
                    unhighlightTagListCell(selectedTag);
                    var tagNo = selectedTag.substring(2, selectedTag.length);
                    tagNo--;
                    selectedTag = "tl" + tagNo;
                }
                highlightTagListCell(selectedTag);
                break;
            case 13:
                addTag(selectedTag);
                break;
        }
    }
}
