//client side code for the contact autofiller.
var g_contacts = null;
var g_pickedContacts = null;
var g_selectedIndex = 0;
var g_currentNames = new Array();
var g_currentIds = new Array();
var g_oldString = new String();
var g_cursorPosition = 0;
var g_cursorIndex = 0;
var MAX_CONTACTS;

function PopulateContacts(max)
{
    MAX_CONTACTS = max;
    var contactDiv = document.getElementById('dContacts');
    if (!contactDiv)
        return;
    
    g_contacts = new Array();
    var contactData = contactDiv.innerHTML.split(',');
    for (var i = 0; i < contactData.length; i+=4)
    {
        var endPoints = new Array;
        var numEndPoints = parseInt(contactData[i+3]);
        for (var j = 0; j < numEndPoints; ++j)
        {
            endPoints.push(contactData[i+4+j]);
        }
        g_contacts.push(new Contact(contactData[i], contactData[i+1], contactData[i+2], contactData[i+3], endPoints));
        i += numEndPoints;
    }
    g_pickedContacts = g_contacts;
    
    var tbContactIds = document.getElementById('tbContactIds');
    if (!tbContactIds)
        return;
    if (!tbContactIds.value)
        return;
        
    var tbContacts = document.getElementById('tbContacts');   
    var ids = tbContactIds.value.split(',');
    for (var i = 0; i < ids.length; ++i)
    {
        g_currentIds[i] = trim(ids[i]);
        var contact = findContactById(g_currentIds[i]);
        if (contact) tbContacts.value += contact.getName() + ', ';
        if ($.jwlib.validatePhone(g_currentIds[i]))
            tbContacts.value += g_currentIds[i] + ', ';
    }
    g_oldString = tbContacts.value;
    g_currentNames = g_oldString.split(',');
}

function findContactById(id)
{
    for (var i = 0; i < g_contacts.length; ++i)
    {
        if (id == g_contacts[i].contactId)
            return g_contacts[i];
    }
    return null;
}

function tbContacts_keyup(e, object)
{
    var autofill = document.getElementById('autofill');
    if (!autofill)
        return true;

    if (g_oldString == object.value)
        return;
    
    e = e || windows.event;
    
    //the current cursor position is the first difference in the string.
    var len = Math.min(g_oldString.length, object.value.length);
    g_cursorPosition = len - 1;
    g_cursorIndex = 0;
    for (var i = 0; i < len; ++i)
    {
        var iPlus1 = i+1;
        if (g_oldString.substring(i,iPlus1) != object.value.substring(i,iPlus1))
        {
            g_cursorPosition = i - 1;
            break;//the difference if before a comma, so break.
        }
        if (object.value.substring(i,iPlus1) == ',')
            ++g_cursorIndex;//If there's a comma we're in a new contact index.
    }
    g_oldString = object.value;
    
    
    //if something wiped out a bunch of contacts (like holding down backspace)
    //we need to rebuild the arrays.
    var newNames = object.value.split(',');
    if (newNames.length != g_currentNames.length)
    {
        //Create a new ID array, and init to -1.
        var newIds = Array(newNames.length);
        for (var i = 0; i < newIds.length; ++i)
            newIds[i] = -1;
        
        //See if any of the current names, match any of the new names.
        for (var i = 0; i < g_currentNames.length; ++i)
        {
            var foundIndex = -1;
            for (var j = 0; j < newNames.length; ++j)
            {
                //if they match this contact must have moved positions in the array.
                if (trim(g_currentNames[i]) == trim(newNames[j]))
                {
                    foundIndex = j;
                    break;
                }
            }
            //so move the current ID to the new ID position.
            if (foundIndex >= 0)
                newIds[foundIndex] = g_currentIds[i];
        }
        g_currentIds = newIds;
    }
    g_currentNames = newNames;
    
    //were editing so clear out the current cursor index.
    g_currentIds[g_cursorIndex] = -1;
    
    var currentString = trim(g_currentNames[g_cursorIndex].toLowerCase());
    if (!currentString)
    {
        //if the length of the current string is 0
        //the user just started a new contact.
        //scrub the picked contacts and start over.
        g_pickedContacts = g_contacts;
        g_selectedIndex = 0;
        autofill.style.display = 'none';
        return;
    }
 
    //if we're to this point we're going to display some contacts (maybe)
    autofill.style.display = 'block';        
    
    //replaced regex chars with escaped equivelent.
    currentString = currentString.replace('.', '\\.');
    currentString = currentString.replace('-', '\\-');
    currentString = currentString.replace('^', '\\^');
    currentString = currentString.replace('$', '\\$');
    currentString = currentString.replace('?', '\\?');
    currentString = currentString.replace('*', '\\*');
    currentString = currentString.replace('+', '\\+');
    currentString = currentString.replace('|', '\\|');
    currentString = currentString.replace('(', '');
    currentString = currentString.replace(')', '');
    currentString = currentString.replace('\\', '');

    //create a regular expression from the current string the user is editing.
    var regex = new RegExp('^' + currentString, "i");
    var regexStrict = new RegExp('^' + currentString + '$', "i");
    
    var regexPhone = new RegExp('^' + StripPhoneFormatting(currentString), "i");
    var regexPhoneStrict = new RegExp('^' + StripPhoneFormatting(currentString) + '$', "i");

    //loop through the current picked contacts.
    //if the contact matches, add it's index to the
    //keep array.
    var keepIndicies = new Array();
    var match = false;//this is used after the autofiller is built
    for (var i = 0; i < g_pickedContacts.length; ++i)
    {
        //check to see if this contact is already
        //one of the Id's we're adding. if it is, skip it.
        var keep = true;
        for (var j = 0; j < g_currentIds.length; ++j)
        {
            if (g_pickedContacts[i].contactId == g_currentIds[j])
            {
                keep = false;
                break;
            }
        }
        if (!keep)
            continue;
            
        //first do the strict test.
        if (regexStrict.test(g_pickedContacts[i].firstName + ((g_pickedContacts[i].firstName && g_pickedContacts[i].lastName)?' ':'') + g_pickedContacts[i].lastName))
        {
            keepIndicies.push(i);
            match = true;
            continue;
        }//then do partial test.
        else if (regex.test(g_pickedContacts[i].firstName) ||
            regex.test(g_pickedContacts[i].lastName) ||
            regex.test(g_pickedContacts[i].firstName + ((g_pickedContacts[i].firstName && g_pickedContacts[i].lastName)?' ':'') + g_pickedContacts[i].lastName))
        {
            keepIndicies.push(i);
            continue;
        }
        
        //if we don't have a match yet check the endpoints.
        if (g_pickedContacts[i].endPoints)
        {
            for (var j = 0; j < g_pickedContacts[i].endPoints.length; ++j)
            {
                //strict test
                if (regexStrict.test(g_pickedContacts[i].endPoints[j]) || 
                    regexPhoneStrict.test(g_pickedContacts[i].endPoints[j]))
                {
                    keepIndicies.push(i);
                    match = true;
                    break;
                }//partial test.
                else if (regex.test(g_pickedContacts[i].endPoints[j]) || 
                    regexPhone.test(g_pickedContacts[i].endPoints[j]))
                {
                    keepIndicies.push(i);
                    break;
                }
            }
        }
        
    }
    
    
    //build the new picked contacts array from the 
    //keep indicies.
    var temp = g_pickedContacts;
    g_pickedContacts = new Array();
    
    for (var i = 0; i < keepIndicies.length; ++i)
    {
        g_pickedContacts.push(temp[keepIndicies[i]]);
    }
    
    //clear out the autofiller.
    autofill.innerHTML = '';
    
    /*Removing match case that was causing some contacts not to show up.
    if (match && g_pickedContacts.length == 1)
    {
        g_currentIds[g_cursorIndex] = g_pickedContacts[0].contactId;
        g_pickedContacts = new Array();
    }
    */
    
    //if there aren't any picked contacts, hide the autofiller
    //and return.
    if (!g_pickedContacts || g_pickedContacts.length < 1)
    {
        autofill.style.display = 'none';
        g_selectedIndex = 0;
        return;
    }
    
    //we have our picked contacts, now we build the autofiller.
    for (var i = 0; i < g_pickedContacts.length && i < MAX_CONTACTS; ++i)
    {
        var contactDiv = document.createElement('div');
        var contactAnchor = document.createElement('a');
        contactAnchor.href = 'javascript:;';
        contactAnchor.innerHTML = trim(g_pickedContacts[i].firstName + ' ' + g_pickedContacts[i].lastName);
        if (g_pickedContacts[i].endPoints && g_pickedContacts[i].endPoints.length > 0)
        {
            var endPointStrings = '';
            for (var j = 0; j < g_pickedContacts[i].endPoints.length; ++j)
            {
                var endpoint = trim(g_pickedContacts[i].endPoints[j]);
                
                //truncate to a length of 40 so it fits.
                if (endpoint.length > 40)
                    endpoint = endpoint.substring(0, 40) + '...';
                    
                endPointStrings += endpoint;
                if (endPointStrings && j < g_pickedContacts[i].endPoints.length - 1 && trim(g_pickedContacts[i].endPoints[j+1]))
                    endPointStrings += ', ';
            }
            if (endPointStrings)
                contactAnchor.innerHTML += ' (' + endPointStrings + ')';
        }
        contactAnchor.onclick = contactOnclick;
        if (g_selectedIndex == i) {contactAnchor.style.background='#fff';contactAnchor.style.color='#5252ee';contactAnchor.style.fontWeight='bold';}
        var contactInfoSpan = document.createElement('span');
        contactInfoSpan.style.display = 'none';
        contactInfoSpan.innerHTML = 'cid+' + g_pickedContacts[i].contactId + '+cid';
        contactAnchor.appendChild(contactInfoSpan);
        contactDiv.appendChild(contactAnchor);
        autofill.appendChild(contactDiv); 
    }
}

function contactOnclick()
{
    var tbContacts = document.getElementById('tbContacts');
    
    var name = '';
    var possibleNames = this.innerHTML.split(/[)(,]/);
    for (var i = 0; i < possibleNames.length; ++i)
    {
        if (trim(possibleNames[i]))
        {
            name = trim(possibleNames[i]);
            break;
        }
    }
    var contactIdString = this.innerHTML.substring(this.innerHTML.indexOf('cid+') + 4, this.innerHTML.indexOf('+cid'));
    g_currentIds[g_cursorIndex] = parseInt(contactIdString);

    var startOfString = tbContacts.value.lastIndexOf(',', g_cursorPosition) + 1;
    if (startOfString < 0)
        startOfString = 0;
    var endOfString = tbContacts.value.indexOf(',', g_cursorPosition);
    if (endOfString < 0)
        endOfString = tbContacts.value.length;
        
    tbContacts.value = tbContacts.value.substring(0, startOfString) + ((startOfString)?' ':'') + name + tbContacts.value.substr(endOfString) + ((endOfString == tbContacts.value.length)?', ':'');
    g_oldString = tbContacts.value;
    g_currentNames = g_oldString.split(',');
    g_pickedContacts = g_contacts;

    var autofill = document.getElementById('autofill');
    if (autofill)
    {
        autofill.style.display='none';
        autofill.innerHTML = '';
    }

    tbContacts.focus();
}

function HideAutoFill()
{
    var autofill = document.getElementById('autofill');
    if (autofill)
    {
        autofill.style.display='none';
    }
}

function tbContacts_blur(e, object)
{
    return true;
}

function tbContacts_focus()
{
    var autofill = document.getElementById('autofill');
    if (!autofill || !autofill.childNodes || autofill.childNodes.length < 1)
        return true;
    document.getElementById('autofill').style.display='block';
    return true;
}

function tbContacts_keydown(e, object)
{
    var k = GetKeyCode(e);
    e = e || window.event;
    
    var autofill = document.getElementById('autofill');
    if (!autofill)
        return true;
        
    //don't allow up or down arrows in the text box.
    if (k == 38)
    {
        var contactAnchor;
        if (autofill.childNodes.length > 0)
        {
            contactAnchor = autofill.childNodes[g_selectedIndex].childNodes[0];
            contactAnchor.style.background='';contactAnchor.style.color='';contactAnchor.style.fontWeight='';
        }
        //decrement selected index.
        if (g_selectedIndex <= 0)
            g_selectedIndex = ((autofill.childNodes.length)?autofill.childNodes.length - 1:0);
        else
            --g_selectedIndex;
        if (autofill.childNodes.length > 0)
        {
            contactAnchor = autofill.childNodes[g_selectedIndex].childNodes[0];
            contactAnchor.style.background='#fff';contactAnchor.style.color='#5252ee';contactAnchor.style.fontWeight='bold';
        }
        return false;
    }
    else if (k == 40)
    {
        var contactAnchor;
        if (autofill.childNodes.length > 0)
        {
            contactAnchor = autofill.childNodes[g_selectedIndex].childNodes[0];
            contactAnchor.style.background='';contactAnchor.style.color='';contactAnchor.style.fontWeight='';
        }
        //increment selected index.
        if (g_selectedIndex >= autofill.childNodes.length - 1)
            g_selectedIndex = 0;
        else
            ++g_selectedIndex;
        if (autofill.childNodes.length > 0)
        {
            contactAnchor = autofill.childNodes[g_selectedIndex].childNodes[0];
            contactAnchor.style.background='#fff';contactAnchor.style.color='#5252ee';contactAnchor.style.fontWeight='bold';
        }
        return false;
    }
    else if (k == 8 || k == 46)
    {
        //reset picked keys if backspace or delete
        g_pickedContacts = g_contacts;
        g_selectedIndex = 0;
    }
    else if (k == 188)//comma
    {
        if (autofill.childNodes && autofill.childNodes[0] && autofill.childNodes[0].childNodes[0])
        {
            autofill.childNodes[0].childNodes[0].onclick();
            return false;
        }
        g_pickedContacts = g_contacts;
        g_selectedIndex = 0;
    }
    else if (k == 13 || k == 9)
    {
        // Note that we allow tab to autofill, then move to the next field
        if (k == 13)
        {
            //special handling of enter in firefox.
            setTimeout('document.getElementById(\''+object.id+'\').focus()',1);
        }
        if (autofill.childNodes.length > g_selectedIndex)
            autofill.childNodes[g_selectedIndex].childNodes[0].onclick();
        g_pickedContacts = g_contacts;
        g_selectedIndex = 0;
        if (k == 13)
        {
            return false;
        }
        else
        {
            return true;
        }
    }
    else if (k == 220 || k == 191 || k == 61 || k == 219 || k == 221)
        return false;
    return true;
}

function copyContactIds()
{
    var tbContactIds = document.getElementById('tbContactIds');
    if (!tbContactIds)
        return;
    tbContactIds.value = '';
    for (var i = 0; i < g_currentIds.length; ++i)
    {
        if (g_currentIds[i] == -1)
            tbContactIds.value += g_currentNames[i];
        else
            tbContactIds.value += g_currentIds[i];
        if (i != g_currentIds.length - 1)
            tbContactIds.value += ',';
    }
}
