﻿/* --- MyTextBox --- */

function MyTextBox_init(id,additionalInfoID,textboxID,css) {
    var mtb = document.getElementById(id);
    if (mtb)
        mtb.setAttribute("info",additionalInfoID);
    var mtb_textbox = document.getElementById(textboxID);
    if (mtb_textbox)
        mtb_textbox.className = css;
}

function MyTextBox_checkLength(source,maxLength) {
    if (source.value.length > maxLength)
        source.value = source.value.substr(0,maxLength);
}

function MyTextBox_Validate(source,arguments) { 
    arguments.IsValid = true; 
    var message = ''; 
    var validator = source; /*document.getElementById(source.id);*/ 
    var controlToValidate = document.getElementById(validator.getAttribute('MyTextBox_TextBox')); 
    var validationMessage = validator.getAttribute('MyTextBox_ValidationMessage'); 
    var watermarkText = validator.getAttribute('MyTextBox_WatermarkText'); 
    var lastFailedDomain = validator.getAttribute('MyTextBox_LastFailedDomain'); 
    var standardMessage = null; 
    var value = controlToValidate.value; 
    if (value == watermarkText) 
        value = '';
    var mandatory = (validator.getAttribute('MyTextBox_Mandatory') == 'true'); 
    if (arguments.IsValid && mandatory) { 
        arguments.IsValid = !(new RegExp('^(\ )*$')).test(value); 
        if (!arguments.IsValid) 
            standardMessage = MYCONTROLS_RESOURCES['errRequired']; 
    } 
    var regex = validator.getAttribute('MyTextBox_RegEx'); 
    if (arguments.IsValid && (value != '') && regex) { 
        arguments.IsValid = (new RegExp(regex)).test(value); 
        if (!arguments.IsValid) 
            standardMessage = MYCONTROLS_RESOURCES['valFieldUpdate']; 
        else { 
            var emailParts = null;
            if ((lastFailedDomain != '') && (lastFailedDomain != null) && 
                                            ((emailParts = value.split('@')).length > 0) && 
                                            (lastFailedDomain.toLowerCase() == emailParts[1].toLowerCase())) { 
                //standardMessage = MYCONTROLS_RESOURCES['valFieldUpdate']; 
                arguments.IsValid = true;
            } 
        } 
    } 
    var mustBeEqualTo = validator.getAttribute('MyTextBox_MustBeEqualTo'); 
    if (arguments.IsValid && mustBeEqualTo) { 
        var controlToValidate2 = document.getElementById(mustBeEqualTo); 
        arguments.IsValid = (!controlToValidate2) || (controlToValidate2.value == value); 
        if (!arguments.IsValid) 
            validationMessage = 'No coincide'; 
    } 
    if (!arguments.IsValid) { 
        message = htmlEncode((validationMessage !== null) && (validationMessage.length > 0) ? validationMessage : standardMessage);
        source.errormessage = message;
        var callout = $find(validator.getAttribute('MyTextBox_Callout'));
        if (callout && callout._errorMessageCell)
            callout._errorMessageCell.innerHTML = validator.errormessage;
    } 
    if (arguments.IsValid) { 
        var onClientValidationOk = validator.getAttribute('MyTextBox_OnClientValidationOk'); 
        if (onClientValidationOk) 
            eval(onClientValidationOk + '(controlToValidate)'); 
        controlToValidate.style.backgroundColor = '';
    }
    else {
        if (controlToValidate.className.indexOf('boxtexterror') < 0) 
            controlToValidate.className += ' boxtexterror';
        MyTextBox_setErrorStyle(controlToValidate,1);
    }
}

function MyTextBox_setErrorStyle(control,iteration)
{
    var activeElement = document.activeElement;
    if (activeElement == control)
        iteration = (iteration == 1 ? 5 : 6);
    
    control.style.backgroundColor = (iteration % 2 == 1 ? '#FFDFDF' : '');
    
    if (iteration < 6)
        setTimeout(function() {MyTextBox_setErrorStyle(control,iteration+1)}, 250);
}

function MyTextBox_getText(id) { 
    var info = document.getElementById(id).getAttribute("info");
    var validator = document.getElementById(info); 
    var watermarkText = validator.getAttribute('MyTextBox_WatermarkText'); 
    var controlToValidate = document.getElementById(validator.getAttribute('MyTextBox_TextBox')); 
    var value = controlToValidate.value; 
    if (value == watermarkText) 
        value = '';
    return value; 
} 

function MyTextBox_setText(id,text) { 
    var info = document.getElementById(id).getAttribute("info"); 
    var validator = document.getElementById(info); 
    var fieldCssClass = validator.getAttribute('MyTextBox_FieldCssClass');
    var waterMarkCssClass = validator.getAttribute('MyTextBox_WaterMarkCssClass');
    var watermarkText = validator.getAttribute('MyTextBox_WatermarkText');
    var controlToValidate = document.getElementById(validator.getAttribute('MyTextBox_TextBox')); 
    if (watermarkText != "")
    {
        var wrapper = AjaxControlToolkit.TextBoxWrapper.get_Wrapper(controlToValidate);
        wrapper.set_Value(text);
    }
    else
    {
        controlToValidate.value = ((text == '') ? watermarkText : text); 
        controlToValidate.className = ((controlToValidate.value == watermarkText) ? waterMarkCssClass : fieldCssClass);
    }
} 

function MyTextBox_setStyle(myTextBox,name,value) { 
    myTextBox.style[name] = value; 
}

function MyTextBox_Capitalize(source,type) { 
    if (type == 1) 
        source.value = source.value.toUpperCase(); 
    else if (type == 2) 
        source.value = source.value.toLowerCase(); 
    else if (type == 3) { 
        var separators = [' ', '.', ',', ';', ':']; 
        for (var i=0; i<separators.length; i++) { 
            var words = source.value.split(separators[i]); 
            for (var j=0; j<words.length; j++) 
                if (words[j].length > 0) { words[j] = words[j].charAt(0).toUpperCase() + words[j].substr(1); } 
            source.value = words.join(separators[i]); 
        } 
    } 
}


/* --- MyCheckBox --- */

function MyCheckBox_Validate(source,arguments) { 
    arguments.IsValid = true; 
    var message = ''; 
    var validator = source; /*document.getElementById(source.id);*/ 
    var controlToValidate = document.getElementById(validator.getAttribute('MyCheckBox_CheckBox')); 
    var validationMessage = validator.getAttribute('MyTextBox_ValidationMessage'); 
    var standardMessage = null; 
    var mandatory = (validator.getAttribute('MyCheckBox_Mandatory') == 'true'); 
    if (arguments.IsValid && mandatory) { 
        arguments.IsValid = (controlToValidate.checked); 
        if (!arguments.IsValid) 
            standardMessage = MYCONTROLS_RESOURCES['errRequired']; 
    } 
    if (!arguments.IsValid) { 
        message = htmlEncode((validationMessage !== null) && (validationMessage.length > 0) ? validationMessage : standardMessage); 
    } 
    if (arguments.IsValid) { 
        var onClientValidationOk = validator.getAttribute('MyCheckBox_OnClientValidationOk'); 
        if (onClientValidationOk) 
            eval(onClientValidationOk + '(controlToValidate)'); 
    } 
}


/* --- MyDropDownList --- */

function MyDropDownList_Validate(source,arguments) { 
    arguments.IsValid = true; 
    var message = ''; 
    var validator = source; /*document.getElementById(source.id); */ 
    var controlToValidate = document.getElementById(validator.getAttribute('MyDropDownList_DropDownList')); 
    var validationMessage = validator.getAttribute('MyDropDownList_ValidationMessage'); 
    var standardMessage = null; 
    var mandatory = (validator.getAttribute('MyDropDownList_Mandatory') == 'true'); 
    if (arguments.IsValid && mandatory) { 
        arguments.IsValid = !(new RegExp('^(\ )*$')).test(controlToValidate.value); 
        if (!arguments.IsValid) 
            standardMessage = MYCONTROLS_RESOURCES['errRequired']; 
    } 
    if (!arguments.IsValid) { 
        message = htmlEncode((validationMessage !== null) && (validationMessage.length > 0) ? validationMessage : standardMessage); 
    } 
}


/* --- MyGenre --- */

function MyGenre_setGenre(id,male) { 
    var info = $get($get(id).getAttribute('AdditionalInfo')); 
    var maleControl = document.getElementById(info.getAttribute('MyGenre_MaleRadioButton')); 
    var femaleControl = document.getElementById(info.getAttribute('MyGenre_FemaleRadioButton')); 
    maleControl.checked = (male === true); 
    femaleControl.checked = (male === false); 
} 

function MyGenre_Validate(source,arguments) { 
    arguments.IsValid = true; 
    var message = ''; 
    var validator = source; /*document.getElementById(source.id);*/ 
    var controlToValidateMale = document.getElementById(validator.getAttribute('MyGenre_MaleRadioButton')); 
    var controlToValidateFemale = document.getElementById(validator.getAttribute('MyGenre_FemaleRadioButton')); 
    var validationMessage = validator.getAttribute('MyGenre_ValidationMessage'); 
    var standardMessage = null; 
    var mandatory = (validator.getAttribute('MyGenre_Mandatory') == 'true'); 
    arguments.IsValid = (!mandatory) || (controlToValidateMale.checked || controlToValidateFemale.checked); 
    if (!arguments.IsValid) { 
        standardMessage = MYCONTROLS_RESOURCES['errRequired']; 
        message = htmlEncode((validationMessage !== null) && (validationMessage.length > 0) ? validationMessage : standardMessage); 
        controlToValidateMale.parentNode.className = 'male genderRequired'; 
        controlToValidateFemale.parentNode.className = 'female genderRequired'; 
        setTimeout('MyGenre_setNormalStyle("'+controlToValidateMale.id+'","'+controlToValidateFemale.id+'");',500); 
    } 
    if (arguments.IsValid) { 
        var onClientValidationOk = validator.getAttribute('MyGenre_OnClientValidationOk'); 
        if (onClientValidationOk) 
            eval(onClientValidationOk + '(controlToValidate)'); 
    } 
}

function MyGenre_setNormalStyle(male,female) { 
    var controlToValidateMale = document.getElementById(male); 
    var controlToValidateFemale = document.getElementById(female); 
    controlToValidateMale.parentNode.className = 'male'; 
    controlToValidateFemale.parentNode.className = 'female'; 
}


/* --- MyDate --- */

var MyDate__State = { NumControls : 0 };

function MyDate_onKeyDown(evt,txtBox1,txtBox2,txtBox3)
{
    var txtBoxes = [document.getElementById(txtBox1),document.getElementById(txtBox2),document.getElementById(txtBox3)];
    
    var keyCode = (evt.keyCode || evt.charCode);
    var source = (evt.srcElement || evt.target);
    
    var sourceIndex = -1;
    for (var i=0; i<txtBoxes.length; i++)
    {
        if (source.id == txtBoxes[i].id) {
            sourceIndex = i;
            break;
        }
    }
    
    var selectedRange = getInputCaretPosition(source);
    var hasSelectedText = (selectedRange != null) && (selectedRange.start != selectedRange.end);
    
    var pos = getInputSelectionStart(source);
    
    var isNumber = ((keyCode >= 48) &&  (keyCode <= 57)) || ((keyCode >= 96) &&  (keyCode <= 107));
    if ((keyCode == 8) || (keyCode == 9) || (keyCode == 37) || (keyCode == 39) || (keyCode == 46) || isNumber)
    {
        if (!hasSelectedText)
        {
            if ((keyCode == 37) || (keyCode == 8))
            {
                if ((pos == 0) && (sourceIndex > 0))
                {
                    var txtBox = txtBoxes[sourceIndex-1];
                    txtBox.focus();
                    if ((keyCode == 8) && (txtBox.value.length > 0))
                        txtBox.value = txtBox.value.substring(0,txtBox.value.length-1);
                    if ((keyCode == 8) || ((keyCode == 37) && (txtBox.value.length == 0)))
                        setInputSelectionRange(txtBox, txtBox.value.length, txtBox.value.length);
                    else
                        setInputSelectionRange(txtBox, txtBox.value.length-1, txtBox.value.length-1);
                    return false;
                }
            }
            else if (keyCode == 39)
            {
                if (((pos == source.value.length) || (pos == source.maxLength-1)) && 
                    (sourceIndex >= 0) && (sourceIndex < 2))
                {
                    var txtBox = txtBoxes[sourceIndex+1];
                    txtBox.focus();
                    setInputSelectionRange(txtBox, 0, 0);
                    return false;
                }
            }
            else if (isNumber)
            {
                if ((pos == source.maxLength) && (sourceIndex >= 0) && (sourceIndex < 2))
                {
                    var txtBox = txtBoxes[sourceIndex+1];
                    txtBox.focus();
                    setInputSelectionRange(txtBox, 0, txtBox.value.length);
                    return true;
                }
                else if ((pos == source.value.length) && (source.value.length == source.maxLength-1) &&
                         (sourceIndex >= 0) && (sourceIndex < 2))
                {
                    var number = ((keyCode >= 96) ? (keyCode - 96) : (keyCode - 48));
                    source.value = source.value + number.toString();
                    var txtBox = txtBoxes[sourceIndex+1];
                    txtBox.focus();
                    setInputSelectionRange(txtBox, 0, txtBox.value.length);
                    return false;
                }
            }
        }
    }
    else
        return false;
        
    return true;
}

function MyDate_setErrorStyle(txtBox1,txtBox2,txtBox3)
{
    var txtBoxes = [document.getElementById(txtBox1),document.getElementById(txtBox2),document.getElementById(txtBox3)];
    
    for (var i=0; i<txtBoxes.length; i++) {
        if ((txtBoxes[i] != null) && (txtBoxes[i].className.indexOf('boxtexterror') == -1))
            txtBoxes[i].className = txtBoxes[i].className + ' boxtexterror';
    }
}

function MyDate_setReadOnly(id,readOnly)
{
    var container = document.getElementById(id);
    if (container)
    {
        var inputs = container.getElementsByTagName("input");
        for (var i=0; i<inputs.length; i++)
        {
            var input = inputs[i];
            if (input.getAttribute("_mydate") == "1")
                input.readOnly = readOnly;
        }
    }
}

function MyDate_clearDate(id)
{
    var container = document.getElementById(id);
    if (container)
    {
        var inputs = container.getElementsByTagName("input");
        for (var i=0; i<inputs.length; i++)
        {
            var input = inputs[i];
            if (input.getAttribute("_mydate") == "1")
                input.value = "";
        }
    }
}

function MyDate_setDate(id,year,month,day)
{
    var container = document.getElementById(id);
    if (container)
    {
        var inputs = container.getElementsByTagName("input");
        for (var i=0; i<inputs.length; i++)
        {
            var input = inputs[i];
            if (input.getAttribute("_mydate") == "1")
            {
                var value = (input.className == "year" ? year : (input.className == "month" ? month : day));
                value = (value === null ? "" : value.toString());
                var maxLength = parseInt(input.maxLength,10);
                if (isNaN(maxLength))
                    input.value = value;
                else
                {
                    if (value.length > 0)
                        while (value.length < maxLength)
                            value = "0" + value;
                    input.value = value;
                }
            }
        }
    }
}

function MyDate_getDate(id,showError)
{
    showError = (showError || false);
    
    var container = document.getElementById(id);
    if (container)
    {
        var inputs = container.getElementsByTagName("input");
        if (inputs.length > 2)
        {
            var isOk = true;
            var values = [null,null,null];

            for (var i=0; i<=2; i++)
            {
                var input = inputs[i];
                var position = (input.className == "year" ? 0 : (input.className == "month" ? 1 : 2));
                values[position] = (input.value === "" ? null : parseInt(input.value,10));
                if ((values[position] !== null) && isNaN(values[position]))
                {
                    isOk = false;
                    break;
                }
            }
            
            if (isOk)
            {
                if ( (values[0] === null && (values[1] !== null || values[2] !== null)) ||
                     (values[1] === null && values[2] !== null) )
                    isOk = false;
                else if ( ((values[0] !== null) && (values[0] < 0 || values[0] > 9999)) ||
                          ((values[1] !== null) && (values[1] < 1 || values[1] > 12)) ||
                          ((values[2] !== null) && (values[2] < 1 || values[2] > 31)) )
                    isOk = false;
                else if (values[2] !== null)
                {
                    try {
                        var date = new Date(values[0],values[1]-1,values[2]);
                        isOk = ((date.getFullYear() == values[0]) &&
                                (date.getMonth() == values[1]-1) &&
                                (date.getDate() == values[2]));
                    }
                    catch(e)
                    {
                        isOk = false;
                    }
                }
            }
            
            if (isOk)
                return values;
            else
            {
                if (showError)
                {
                    alert("Error");
                    try { inputs[0].focus(); } catch (e) {}
                }
                return -1;
            }
        }
    }
    
    return null;
}

function MyDate_isValid(id)
{
    return MyDate_isValidValue(MyDate_getDate(id,false));
}

function MyDate_isValidValue(value)
{
    return (value !== -1);
}

function MyDate_validate(id)
{
    return MyDate_isValidValue(MyDate_getDate(id,true));
}

function MyDate_create(labelText)
{
    var numControl = MyDate__State.NumControls++;
    
    var container = document.createElement("div");
    container.id = "Mydate_ClientControl" + numControl;
    container.className = "wrapper-value";
    
    var label = document.createElement("label");
    if (labelText != null && labelText != "")
        label.innerHTML = labelText;
    container.appendChild(label);
    
    var dateContainer = document.createElement("div");
    dateContainer.className = "date";
    container.appendChild(dateContainer);
    
    var positions = MyDate_getFieldsPosition();
    
    var js = "return MyDate_onKeyDown(event"
    for (var i=0; i<positions.length; i++)
        js += ",'" + container.id + "_" + positions[i] + "'";
    js += ");"
    
    for (var i=0; i<positions.length; i++)
    {
        var field = document.createElement("input");
        field.setAttribute("type", "text");
        field.id = container.id + "_" + positions[i];
        field.className = positions[i];
        field.setAttribute("_mydate", "1");
        field.maxLength = (positions[i] == "year" ? 4 : 2);
        field.style.width = parseInt(15 * field.maxLength / 2,10) + "px";
        $addHandler(field, "keydown", new Function("event", js));
        dateContainer.appendChild(field);
        
        if (i < 2)
        {
            var separator = document.createElement("span");
            separator.innerHTML = htmlEncode(Sys.CultureInfo.CurrentCulture.dateTimeFormat.DateSeparator);
            dateContainer.appendChild(separator);
        }
    }
    
    return { id : container.id, element : container };
}

function MyDate_getFieldsPosition()
{
    var format = Sys.CultureInfo.CurrentCulture.dateTimeFormat.ShortDatePattern.toLowerCase();
    
    var dayPos = format.indexOf("d");
    var monthPos = format.indexOf("m");
    var yearPos = format.indexOf("y");

    var info = [null,null,null];
    
    info[(dayPos > monthPos ? 1 : 0) + (dayPos > yearPos ? 1 : 0)] = "day";
    info[(monthPos > dayPos ? 1 : 0) + (monthPos > yearPos ? 1 : 0)] = "month";
    info[(yearPos > dayPos ? 1 : 0) + (yearPos > monthPos ? 1 : 0)] = "year";
    
    return info;
}


/* --- ImportContacts --- */

var ImportContacts_Value_Separator = String.fromCharCode(6);

function ImportContacts_selectGroup(id,idGroup) {
    var info = ImportContacts_Info[id];
    $get(info.hdnIDGroup).value = idGroup;
    fireClickEvent($get(info.btnSelectGroup));
}

function ImportContacts_removeContact(id,email) {
    var info = ImportContacts_Info[id];
    $get(info.hdnEmail).value = email;
    $get(info.hdnScrollTop).value = $get(info.panel).scrollTop;
    //fireClickEvent($get(info.btnRemoveContact));
}

function ImportContacts_setTextBoxFocus(id) {
    var info = ImportContacts_Info[id];
    var panel = $get(info.panel);
    panel.scrollTop = panel.offsetHeight;
    try { document.getElementById(info.txtContact).scrollIntoView(); document.getElementById(info.txtContact).focus(); } catch(e) {};
}

ImportContacts_OnPersonSelected = function(source,eventArgs) {
    var id = ImportContacts_Info[source.get_id()];
    var info = ImportContacts_Info[id];
    var txtContact = $get(info.txtContact);
    var hdnContact = $get(info.hdnContact);
    var values = eventArgs.get_value().split(ImportContacts_Value_Separator);
    var idPerson = values[0];
    var email = values[1];
    var name = values[2];
    $get(info.hdnIDPerson).value = idPerson;
    hdnContact.value = txtContact.value;
    txtContact.value = '';
    ImportContacts_addContact(id,idPerson,name,email);
    txtContact.focus();
    //setTimeout(new Function('fireClickEvent(document.getElementById("' + info.btnAddContact + '"));'), 10);
};

function ImportContacts_onBlur(id) {
    var info = ImportContacts_Info[id];
    var txtContact = $get(info.txtContact);
    var hdnContact = $get(info.hdnContact);
    var hdnIDPerson = $get(info.hdnIDPerson);
    if ((txtContact.value != '') && (txtContact.value != info.watermark))
    {
        var email = txtContact.value;
        hdnIDPerson.value = '';
        hdnContact.value = txtContact.value;
        txtContact.value = '';
        ImportContacts_addContact(id,null,email,email);
        txtContact.focus();
        //setTimeout(new Function('fireClickEvent(document.getElementById("' + info.btnAddContact + '"));'), 10);
    }
}

function ImportContacts_txtContactOnKeyPress(event,id) {
    var info = ImportContacts_Info[id];
    var hdnIDPerson = $get(info.hdnIDPerson);
    var evt = new Sys.UI.DomEvent(event);
    var charCode = evt.charCode;
    var txtContact = $get(info.txtContact);
    var hdnContact = $get(info.hdnContact);
    if ((charCode == Sys.UI.Key.enter) || 
        ((charCode == Sys.UI.Key.space) && (txtContact.value.indexOf('@') > 0))) {
        if ((txtContact.value != '') && (txtContact.value != info.watermark)) {
            hdnIDPerson.value = '';
            hdnContact.value = txtContact.value;
            var email = txtContact.value;
            txtContact.value = '';
            ImportContacts_addContact(id,null,email,email);
            evt.stopPropagation();
            evt.preventDefault();
            txtContact.focus();
            //setTimeout(new Function('fireClickEvent(document.getElementById("' + info.btnAddContact + '"));'), 10);
        }
        return false;
    }
    else if (hdnIDPerson.value != '') {
        txtContact.value = '';
        hdnContact.value = '';
        hdnIDPerson.value = '';
    }
    return true;
}

function ImportContacts_addContact(id,idPerson,name,email)
{
    var info = ImportContacts_Info[id];

    var txtContact = $get(info.txtContact);

    if ((info.emailMode) && ((email == '') && (!((new RegExp(info.emailRegEx)).test(email)))))
    {
        txtContact.blur();
        setTimeout(function() {alert(info.emailErrorMessage)},0);
        return;
    }
    else if ((!info.emailMode) && (idPerson == null))
    {
        txtContact.blur();
        //setTimeout(function() {alert(info.personErrorMessage)},0);
        return;
    }
    
    for (var i=0; i<info.selectedContacts.length; i++)
    {
        var selectedContact = info.selectedContacts[i];
        if (((info.emailMode) && (selectedContact.email == email)) ||
            ((idPerson != null) && (selectedContact.idPerson == idPerson)))
        {
            if ((selectedContact.name == selectedContact.email) && (name != selectedContact.name))
                ImportContacts_removeContact2(id,selectedContact.container);
            else
                return;
        }
    }
    

    info.counter = (info.counter || 0);
    info.counter++;
    
    var itemsContainer = $get(info.itemsContainer);
    
    var itemContainer = document.createElement("li");
    itemContainer.id = id + "__newItem" + info.counter;
    itemsContainer.insertBefore(itemContainer, $get(info.insertContactContainer));
    
    itemContainer.appendChild(document.createTextNode(name));
    
    var link = document.createElement("a");
    link.innerHTML = "x";
    link.className = "remove-contact";
    link.href = "#";
    link.info = [id, itemContainer.id];
    link.onclick = function() { ImportContacts_removeContact2(this.info[0], this.info[1]); return false; };
    itemContainer.appendChild(link);
    
    info.selectedContacts.push( { idPerson  : idPerson, 
                                  name      : name, 
                                  email     : email,
                                  container : itemContainer.id } );

    ImportContacts_updateHiddenState(id);
}

function ImportContacts_removeContact2(id,itemContainerID)
{
    var info = ImportContacts_Info[id];
    
    for (var i=0; i<info.selectedContacts.length; i++)
    {
        var selectedContact = info.selectedContacts[i];
        if (selectedContact.container == itemContainerID)
        {
            var itemContainer = $get(itemContainerID);
            $clearHandlers(itemContainer);
            itemContainer.parentNode.removeChild(itemContainer);
            Array.removeAt(info.selectedContacts,i);
            ImportContacts_updateHiddenState(id);
            break;
        }
    }
    return false;
}

function ImportContacts_removeAll(id)
{
    var info = ImportContacts_Info[id];
    info.selectedContacts = new Array();
    
    var itemsContainer = $get(info.itemsContainer);
    var items = itemsContainer.getElementsByTagName("li");
    while (items.length > 0)
    {
        var item = items[0];
        if (item.id == info.insertContactContainer)
            break;
        else
        {
            $clearHandlers(item);
            item.parentNode.removeChild(item);
        }
    }
    ImportContacts_updateHiddenState(id);
}

function ImportContacts_updateHiddenState(id)
{
    var info = ImportContacts_Info[id];
    var hidden = new Array();
    hidden[hidden.length] = "<xml>";
    for (var i=0; i<info.selectedContacts.length; i++)
    {
        var selectedContact = info.selectedContacts[i];
        hidden[hidden.length] = "<contact>" + 
                                    "<idPerson>" + xmlEncode(selectedContact.idPerson) + "</idPerson>" +
                                    "<name>" + xmlEncode(selectedContact.name) + "</name>" +
                                    "<email>" + xmlEncode(selectedContact.email) + "</email>" +
                                "</contact>";
    }
    hidden[hidden.length] = "</xml>";
    $get(info.hdnState).value = hidden.join("");
}


/* --- Change Parents --- */

var ChangeRelationships_Value_Separator = String.fromCharCode(6);

function ChangeRelationships_openPopup(id,onClose) {
    onClose = (onClose || null);
    var info = CHANGE_RELATIONSHIPS[id];
    info.onClose = onClose;
    $find(info.mpuChangeParents).show();
}

function ChangeRelationships_closePopup(id)
{
    var info = CHANGE_RELATIONSHIPS[id];
    $find(info.mpuChangeParents).hide();
    if (typeof(info.onClose) == "function")
        info.onClose();
}
ChangeRelationships_onPersonSelected = function(source,eventArgs) {
    var id = CHANGE_RELATIONSHIPS[source.get_id()];
    var info = CHANGE_RELATIONSHIPS[id];
    var values = eventArgs.get_value().split(ChangeRelationships_Value_Separator);
    var idPerson = values[0];
    var name = values[1];
    document.getElementById(info.hdnParent1).value = idPerson;
    document.getElementById(info.Parent1).value = name;
    document.getElementById(info.Parent2).options.length = 0;
    setTimeout(new Function(info.btnRefreshParent2Click), 10);
};
function ChangeRelationships_Parent1OnKeyPress(event,id) {
    var info = CHANGE_RELATIONSHIPS[id];
    var hdnParent1 = document.getElementById(info.hdnParent1);
    var evt = new Sys.UI.DomEvent(event);
    var charCode = evt.charCode;
    if ((charCode != Sys.UI.Key.enter) && (hdnParent1.value != '')) {
        hdnParent1.value = '';
        document.getElementById(info.Parent1).value = '';
        document.getElementById(info.Parent2).options.length = 0;
    }
    return true;
}
function ChangeRelationships_Parent1OnKeyDown(event,id) {
    var info = CHANGE_RELATIONSHIPS[id];
    var hdnParent1 = document.getElementById(info.hdnParent1);
    var charCode = (event.keyCode || event.charCode);
    if (((charCode == 8) || (charCode == 46)) && (hdnParent1.value != '')) {
        hdnParent1.value = '';
        document.getElementById(info.Parent1).value = '';
        document.getElementById(info.Parent2).options.length = 0;
    }
    return true;
}


/* --- Person Searcher --- */

var PersonSearcher_Value_Separator = String.fromCharCode(6);

PersonSearcher_OnPersonSelected = function(source,eventArgs) {
    var id = PersonSearchers_Info[source.get_id()];
    var info = PersonSearchers_Info[id];
    var PersonName = $get(info.PersonName);
    var IDPerson = $get(info.IDPerson);
    var values = eventArgs.get_value().split(PersonSearcher_Value_Separator);
    var idPerson = values[0];
    var email = values[1];
    var name = values[2];
    IDPerson.value = idPerson;
    PersonName.value = name;
    var onClientChange = info.OnClientChange;
    if (onClientChange != '')
        eval(onClientChange + "('" + jsEncode(id) + "'," + idPerson + ",'" + jsEncode(name) + "')");
    if (info.OnPersonSelected)
        info.OnPersonSelected();
};
function PersonSearcher_clearSelectedPerson(id) {
    var info = PersonSearchers_Info[id];
    $get(info.IDPerson).value = "";
    AjaxControlToolkit.TextBoxWrapper.get_Wrapper($get(info.PersonName)).set_Value("");
}
function PersonSearcher_setContextKey(id,contextKey) {
    var autocomplete = $find(PersonSearchers_Info[id].AutoComplete);
    var oldContextKey = autocomplete.get_contextKey();
    autocomplete.set_contextKey(contextKey);
    if (oldContextKey != contextKey)
        autocomplete._cache = null;
}
function PersonSearcher_PersonNameOnKeyPress(event,id) {
    var info = PersonSearchers_Info[id];
    var IDPerson = document.getElementById(info.IDPerson);
    var PersonName = $get(info.PersonName);
    var evt = new Sys.UI.DomEvent(event);
    var charCode = evt.charCode;

    if (charCode == Sys.UI.Key.enter)
        return false;
    else
    {
        if (IDPerson.value != '')
            IDPerson.value = '';

        var onClientChange = info.OnClientChange;
        if (onClientChange != '')
            eval(onClientChange + "('" + jsEncode(id) + "',null)");
    }
    return true;
}
function PersonSearcher_Parent1OnKeyDown(event,id) {
    var info = PersonSearchers_Info[id];
    var IDPerson = document.getElementById(info.IDPerson);
    var charCode = (event.keyCode || event.charCode);
    if (((charCode == 8) || (charCode == 46)) && (IDPerson.value != '')) {
        IDPerson.value = '';
    }
    return true;
}
function PersonSearcher_setFocus(id,clearText)
{
    var info = PersonSearchers_Info[id];
    var PersonName = $get(info.PersonName);
    if (clearText)
    {
        PersonName.blur();
        PersonName.value = "";
    }
    PersonName.focus();
}
function PersonSearcher_clearText(id)
{
    var info = PersonSearchers_Info[id];
    var PersonName = $get(info.PersonName);
    PersonName.value = "";
}


/* --- Group Selector --- */

function GroupSelector_verify(elem)
{
    if (elem.checked)
    {
        var idGroup = elem.getAttribute("_idGroup");
        var exclusive = (elem.getAttribute("_exclusive") == "1");
        if (exclusive)
        {
            var checks = elem.parentNode.parentNode.getElementsByTagName("INPUT");
            for (var i=0; i<checks.length; i++)
            {
                var check = checks[i];
                var idGroup2 = check.getAttribute("_idGroup");
                if ((idGroup2 != idGroup) && (check.getAttribute("_inclusive") != "1"))
                    check.checked = false;
            }
        }
        else if (elem.getAttribute("_inclusive") != "1")
        {
            var checks = elem.parentNode.parentNode.getElementsByTagName("INPUT");
            for (var i=0; i<checks.length; i++)
            {
                var check = checks[i];
                var idGroup2 = check.getAttribute("_idGroup");
                var exclusive2 = (check.getAttribute("_exclusive") == "1");
                if (exclusive2 && (idGroup != idGroup2))
                    check.checked = false;
            }
        }
    }
}