var ctrlId_Tags = "tags";
var ctrlId_ShowLink = "showLink";
var ctrlId_HideLink = "hideLink";
var ctrlId_Suggestions = "suggestions";
var ctrlId_AllTags = "allTags";
var obj_TagsDict = "tagsDict";
var obj_arr = "a";
var selectedBackgroundColor="#0a246a";
var selectedFontColor="#ffffff";
var unselectedBackgroundColor="#ffffff";
var unselectedFontColor="#000000";

function SwitchOnloadMode()
{
    var d = document.all.ButtonAddDiv.lastChild.value.split(",");
    if(d.length > 1)
    {
        OnSelectScopeClick(d[1]);
        SwitchAddNewTagsList(d[0]);
    }
    document.all.ButtonAddDiv.lastChild.value= SwitchAddNewTagsListMode + "," + OnSelectScopeClickMode; 
}
function My_GetElementByID(eltag, elid)
{
	var els = document.all.tags(eltag);
	elid = "_" + elid;
	for(var i = 0; i < els.length; i++)
	{
		var index = els[i].id.lastIndexOf(elid);
		if((index > 0) && ((elid.length + index) == els[i].id.length))
			return els[i];
	}
	return null;
}

var OnSelectScopeClickMode = 0;
function OnSelectScopeClick(mode)
{
    OnSelectScopeClickMode = mode;
    document.all.ButtonAddDiv.lastChild.value= SwitchAddNewTagsListMode + "," + OnSelectScopeClickMode; 
    if(mode == "0")
    {
        tdUrl.style.display = "none";
        var web = My_GetElementByID("input", "RemoteSiteUrlTextBoxR1");
        web.value = "[site collection]";
    }
    else
    {
        tdUrl.style.display = "";
    }
}
var SwitchAddNewTagsListMode = 1;
function SwitchAddNewTagsList(mode)
{
    SwitchAddNewTagsListMode = mode;
    document.all.ButtonAddDiv.lastChild.value= SwitchAddNewTagsListMode + "," + OnSelectScopeClickMode; 
    if(mode == "0")
    {
        trAddPropertyToolbar.style.display = "none";
        AllListsRow.style.display = "none";
        trCreateListToolbar.style.display = "";
        NewListData.style.display = "";
    }
    else
    {
        trAddPropertyToolbar.style.display = "";
        AllListsRow.style.display = "";
        trCreateListToolbar.style.display = "none";
        NewListData.style.display = "none";
   }
}

function AddNewTagsList()
{
    document.all.ButtonAddDiv.firstChild.click();
}

function DeleteSelectedList(conftext, web, list)
{
    if(window.confirm(conftext) == true)
    {
        document.all.ButtonDeleteDiv.lastChild.value= "del" + "|" + web + "|" + list; 
        document.all.ButtonDeleteDiv.firstChild.click();
    }
}
function suggest(e, pWPQ)
{
    var input = document.getElementById(pWPQ);
    var div = document.getElementById(ctrlId_Suggestions + pWPQ);
    var tagsDict = eval(obj_TagsDict + pWPQ);
    if (isEntered(e, div, pWPQ))  return;
    if (isTabed(e, div, pWPQ)) return;
    if (moveUp(e, div, pWPQ))  return;
    if (moveDown(e, div, pWPQ))  return;
    var userValue = GetLastWord(input);
    var firstChar = userValue.charAt(0);
    var allowNew = input.getAttribute("allownew");
    if( tagsDict[firstChar] )
    {
        var arrFound = new Array();
        if((FindSuggestions(arrFound,firstChar,userValue, pWPQ) == false) && (allowNew == "FALSE"))
        {
            input.value = input.getAttribute("prevvalue");
            userValue = GetLastWord(input);
            firstChar = userValue.charAt(0);
            FindSuggestions(arrFound,firstChar,userValue, pWPQ);
        }
        if( arrFound.length > 0 )
        {
            buildDiv(div,arrFound,input,pWPQ);
        }
        else
        {
            //hide div
            hideDiv(pWPQ);
        }
    }
    else
    {
        if(allowNew == "FALSE")
        {
            if(firstChar != "")
            {
                if(input.value.length > 1)
                    input.value = input.getAttribute("prevvalue");
                else
                    input.value = "";
            }
        }
        hideDiv(pWPQ);
    }
    
    var div = document.getElementById(ctrlId_AllTags + pWPQ);
    if(div.style.display != 'none')
        BulidDivTagsArray(pWPQ);
    input.setAttribute("prevvalue", input.value);
}


function isEntered(e, div, pWPQ)
{
   if(e == null) e = window.event;
   if( e.keyCode == 13 )
    {
        var selected = getSelectedTagDiv(div);
        if( selected )
        {
            insertSuggestion(selected, pWPQ);

            e.cancelBubble = true;
            e.returnValue = false;
        }
        return true;
   }
   
   return false;
}

function isTabed(e, div, pWPQ)
{
    if(e == null) e = window.event;
    if( e.keyCode == 9 )
    {
        var selected = getSelectedTagDiv(div);
        if( selected )
        {
            insertSuggestion(selected, pWPQ);
            
            e.cancelBubble = true;
            e.returnValue = false;
        }
        return true;
   }
   
   return false;
}

function showSuggestionSelected(el, pWPQ)
{
    var div = document.getElementById(ctrlId_Suggestions + pWPQ);
    var selected = getSelectedTagDiv(div);
    if(el == selected)
        return;
    if( selected )
    {
        selected.style.backgroundColor=unselectedBackgroundColor;
        selected.setAttribute("selected", "0");
        selected.style.color=unselectedFontColor;
        el.style.backgroundColor=selectedBackgroundColor;
        el.setAttribute("selected", "1");
        el.style.color=selectedFontColor;
    }
}

function moveUp(e, div)
{
    if(e == null) e = window.event;
    if( e.keyCode == 38 )
    {
        var selected = getSelectedTagDiv(div);
        if( selected )
        {
            //if i am not first
            if( selected.previousSibling )
            {
                selected.style.backgroundColor=unselectedBackgroundColor;
                selected.style.color=unselectedFontColor;
                selected.setAttribute("selected", "0");
                selected.previousSibling.style.backgroundColor=selectedBackgroundColor;
                selected.previousSibling.style.color=selectedFontColor;
                selected.previousSibling.setAttribute("selected", "1");
            }
        }

        return true;
    }
    
    return false;
}


function moveDown(e, div)
{
    if(e == null) e = window.event;
    if( e.keyCode == 40 )
    {
        var selected = getSelectedTagDiv(div);
        if( selected )
        {
            //if i am not last
            if( selected.nextSibling )
            {
                selected.style.backgroundColor=unselectedBackgroundColor;
                selected.style.color=unselectedFontColor;
                selected.setAttribute("selected", "0");
                selected.nextSibling.style.backgroundColor=selectedBackgroundColor;
                selected.nextSibling.style.color=selectedFontColor;
                selected.nextSibling.setAttribute("selected", "1");
            }
        }

        return true;
    }
    
    return false;
}

function GetLastWord(input)
{
    //the current word type (after ",")
    var str = input.value.toLowerCase();
    var lastWordLocation = str.lastIndexOf(",") + 1;
    str = str.slice(lastWordLocation, str.length);

    var userValue = str;
    
    userValue = userValue.trim();
    return userValue;
}

function FindSuggestions(arrFound,firstChar,userValue, pWPQ)
{
    var input = document.getElementById(pWPQ);
    var tags = input.value.trim().split(',');
    //we have some arrays, put correct values in arrFound 
    var tagsDict = eval(obj_TagsDict + pWPQ);    
    for(var i = 0; i < tagsDict[firstChar].length; i++)
    {
        var add = true;
        var found = false;
        // See if the tag already is in the text box
        for (var iii = 0; iii < tags.length; iii++) 
        {
            if (tags[iii].trim().toLowerCase() == tagsDict[firstChar][i].toLowerCase()) 
            {
                found = true;
                break;
            }
        }
        
        for(var ii = 1; ii < userValue.length; ii++)
        {
            if((ii >  tagsDict[firstChar][i].length) || (tagsDict[firstChar][i].charAt(ii).toLowerCase() != userValue.charAt(ii) ))
            {
                add = false;
                break;
            }
        }
        if( add )
            arrFound[arrFound.length] = tagsDict[firstChar][i];
     }
    return (arrFound.length > 0);
}

function buildDiv(div,arrFound,input, pWPQ)
{
    hideDiv(pWPQ);
    var sHTML = "";
    var Size=10;
    if (arrFound.length<10)
    {
        Size = arrFound.length;
    }
    for(var i=0;i<Size;i++)
    {
         sHTML +="<div onmouseover=\"showSuggestionSelected(this, '"+pWPQ+"')\" selected=\"1\" onclick=\"insertSuggestion(this, '"+pWPQ+"')\" style='cursor:pointer;";
         sHTML += i == 0 ? "background-color:" + selectedBackgroundColor + ";color:" + selectedFontColor + ";'>" : "'>";
         sHTML += "&nbsp;&nbsp;" + arrFound[i] + "&nbsp;&nbsp;</div>";

    }

    div.innerHTML = sHTML;
    div.style.display='';
    input.style.position = "absolute";
    var tmp = input.offsetLeft + "px";
    div.style.left = tmp;
    if(div.offsetWidth < 250)
        div.style.width = "250px"; 
    if(div.scrollHeight > 100)
        div.style.height = "100px";
    else
        div.style.height = div.scrollHeight; 
         
    if(div.offsetHeight < 40)
        div.style.height = "40px"; 
    div.style.overflowY = "auto";
    tmp = (input.offsetTop - div.offsetHeight - 7) + "px";
    div.style.top = tmp;
    input.style.position = "";
}

function hideDiv(pWPQ)
{
    var div = document.getElementById(ctrlId_Suggestions + pWPQ);
    if( div )
    {
        div.style.display = 'none';
        div.style.height = "1px"; 
        div.style.height = "1px"; 
    }
}

function getSelectedTagDiv(parentDiv)
{
    var temp = false;
    if( parentDiv.style.display == '' )//if div is visible
    {
        for(var i=0;i<parentDiv.childNodes.length;i++)//for each tag in it
        {
            if(parentDiv.childNodes[i].getAttribute("selected")  == "1")
            {
                return parentDiv.childNodes[i];
            }
        }
    }
    return null;
}

String.prototype.trim = function() 
{
    text = this.replace(/^\s+/, '');
    text = text.replace(/&nbsp;/g,'');
    return text.replace(/\s+$/, '');
}

function showLinkClick(pWPQ)
{
    BulidDivTagsArray(pWPQ);
    ShowByID(ctrlId_AllTags + pWPQ);
    ShowByID(ctrlId_HideLink + pWPQ);
    HideByID(ctrlId_ShowLink + pWPQ); 
}

function BulidDivTagsArray(pWPQ)
{
    var div = document.getElementById(ctrlId_AllTags + pWPQ);
    var input = document.getElementById(pWPQ);
    var tags = input.value.trim().split(',');

    var a = eval(obj_arr + pWPQ);
    var sHTML = "";
    sHTML = "<div style='text-align: justify;'>";
    for(var i=0;i<a.length;i++)
    {
        if(a[i].length == 0)
            continue;
        var found = false;
        // See if the tag already is in the text box
        for (var iii = 0; iii < tags.length; iii++) 
        {
            if (tags[iii].trim().toLowerCase() == a[i].toLowerCase()) 
            {
                found = true;
                break;
            }
        }
        if(found == false)
        {
           sHTML += "<a href='#' onclick=\"SelectTag(this,'"+pWPQ+"'); return false;\" >"+a[i]+"</a>";
           if( i < a.length-1 )
               sHTML += "&nbsp; ; &nbsp;";
        }
    }
    sHTML += "</div>";
    div.innerHTML = sHTML;
}

// Responds to a click on a tag by adding that click to the input box. 
function SelectTag(TagClicked, pWPQ)
{
    //   var input = document.getElementById(ctrlId_Tags + pWPQ);
    var input = document.getElementById(pWPQ);

    if (!input) return;

    var curVal = input.value.trim();

    if (curVal == "")
    {
        input.value = TagClicked.innerHTML +",";
    } 
    else 
    {
        var txt = TagClicked.innerHTML;
        AddTagToInput(input,txt);
    }
    BulidDivTagsArray(pWPQ);
}

function hideLinkClick(pWPQ)
{
    HideByID(ctrlId_AllTags + pWPQ);
    HideByID(ctrlId_HideLink + pWPQ);
    ShowByID(ctrlId_ShowLink + pWPQ); 
}

function HideByID(ID)
{
    var div = document.getElementById(ID);
    div.style.display = 'none';
}
function ShowByID(ID)
{
    var div = document.getElementById(ID);
    div.style.display = '';
}

function insertSuggestion(ell, pWPQ)
{
   // var input = document.getElementById(ctrlId_Tags + pWPQ);
     var input = document.getElementById(pWPQ);
    if (!input) return;
    hideDiv(pWPQ);
    AddTagToInput(input, ell.innerHTML, true);
    BulidDivTagsArray(pWPQ);
}

function AddTagToInput(input,txt, isFromsugg)
{
   // Remove excess whitespace
    var tags = input.value.trim().split(',');
    txt = txt.trim();
    var found = false;
    // See if the tag already is in the text box
    for (var i=0; i < tags.length; i++) 
    {
        tags[i] = tags[i].trim();
        if (tags[i] == txt) 
            found = true;
    }
    // If not, add it.
    if (!found) 
    {
        var newSrt = "";
        var leng = isFromsugg == true ? tags.length - 1 : tags.length;
        for (var i=0; i < leng; i++) 
        {
            if(tags[i].length == 0)
                continue;
            newSrt += tags[i] + ",";
        }
        input.value =newSrt+ txt + ",";
    }
    
    if(input.value.charAt(input.value.length - 1) != ',')
        input.value += ",";
        
}


function _AC_SimpleStore(pWPQ)
{
    var arr = eval(obj_arr+pWPQ);
    var tagsDict = eval(obj_TagsDict + pWPQ);
   
    //run for each tag in array (arr)
    for(var i=0;i<arr.length;++i)
    {
        if(arr[i])
        {
            //check first letter -> f
            var f=arr[i].charAt(0).toLowerCase();
            //look in this.wordsArr for a value in key: f
            var g=tagsDict[f];
            
            if(!g)//if no value found - assign this.wordsArr an empty array.
            {
                g=(tagsDict[f]=[])
            }
            //if last added value in the array == current tag skip adding the word
            else 
            {
                if(g[g.length-1].value==arr[i])
                {
                    continue
                }
            }
            
            //add to array each tag
            g.push(arr[i]);
        }
    }
}
