<commit_before>//Объявление общедоступных переменных
let ContactsArray = [];
let Contact;
let createNewContact = true;
let SearchArray = [];
//Блок событий при отображении списка контактов
document.getElementById('add-contact-button').addEventListener('click', AddNewContact, false);
let inputSearch = document.getElementById('inputsearch');
inputSearch.oninput = function () {

    SearchArray.length = 0;

    let matchValue = /^[a-zA-Z\s]*$/;
    if (!inputSearch.value.match(matchValue) || inputSearch.value.length > 22)
    {
        inputSearch.value = inputSearch.value.substr(0, inputSearch.value.length - 1);
    }

    for (let i = 0; i < ContactsArray.length; i++)
    {
        if (ContactsArray[i].name.toLowerCase().indexOf(inputSearch.value.toLowerCase()) ==  0 )
        {
            SearchArray.push(ContactsArray[i]);
        }
    }
    ReloadContactList(SearchArray);
}
document.getElementById('contact-list').onclick = function (event){
    let target = event.target || event.srcElement
    if (target.id != 'contact-list') {
        if (target.id != '')EditContact(target.id);
    }
    }
document.getElementById('add-contact').onclick = function (event){
    let target = event.target || event.srcElement

    if (target.className == 'button-plus-phone'){
        AddNumber();
    }
    if (target.className == 'button-minus-phone'){
        RemoveNumber(target);
    }
    if (target.className == 'button-plus-email'){
        AddMail();
    }
    if (target.className == 'button-minus-email'){
        RemoveMail(target);
    }
}
//Подтягивание базы контактов при первом запуске/релоаде
    if (localStorage.getItem('Contacts'))
    {
        ContactsArray = JSON.parse(localStorage.getItem('Contacts'));
        ReloadContactList(ContactsArray);
    }
//Логика добаления и редактирования контакта
function AddNewContact() {
    createNewContact = true;
    let newContact = {
        id: 0,
        name: '',
        number: [''],
        email: ['']
    }

    OpenContactWindow(newContact);
}
function RemoveContact() {
    ContactsArray.splice(Contact.id, 1);
    localStorage.setItem('Contacts', JSON.stringify(ContactsArray));
    CloseContactWindow();
    ReloadContactList(ContactsArray);
}
function EditContact(id) {
    for (let i = 0; i < ContactsArray.length; i++){
        if (ContactsArray[i].id == id){
            Contact = ContactsArray[i];
            createNewContact = false;
            OpenContactWindow(Contact);
            break;
        }
    }
}
function SaveContact() {

    let inputName = document.getElementById('name');
    let numberId0 = document.getElementById('number0');
    let emailId0 = document.getElementById('email0');

    SaveInputValue();

        if(inputName.value != '' && numberId0.value != '' && emailId0.value != '')
        {

            for (let i = 0; i < Contact.number.length; i++){
                if (Contact.number[i] == '')
                {
                    Contact.number.splice(i, 1);
                    i--;
                }
            }
            for (let i = 0; i < Contact.email.length; i++){
                if (Contact.email[i] == '')
                {
                    Contact.email.splice(i, 1);
                    i--;
                }
            }
    if (createNewContact) {
        ContactsArray.push(Contact);
    }

    ReloadContactList(ContactsArray)
    localStorage.setItem('Contacts', JSON.stringify(ContactsArray));

    CloseContactWindow();
        }
        else {
    if (numberId0.value == ''){
        numberId0.setAttribute('placeholder', 'Enter phone number');
    }
    if (emailId0.value == '') {
        emailId0.setAttribute('placeholder', 'Enter e-mail address')
    }
    if (inputName.value == ''){
        inputName.setAttribute('placeholder', 'Enter contact name')
    }
}
}
function SaveInputValue() {
    let inputName = document.getElementById('name');
    Contact.name = inputName.value;
    for(let z = 0; z < Contact.number.length; z++){
        let numberId = document.getElementById('number'+z);
        if (numberId != null)Contact.number[z] = numberId.value;
    }
    for(let y = 0; y < Contact.email.length; y++){
        let emailId = document.getElementById('email'+y);
        if (emailId != null)Contact.email[y] = emailId.value;
    }
}
//Логика переключения между списком контактов и формой добавления/редактирования контакта
function OpenContactWindow(contact) {

    Contact = contact;
    document.getElementById('contact-list').style.display = 'none';
    document.getElementById('header').style.display = 'none';
    document.getElementById('add-contact').style.display = 'flex';
    AddContactDrow();

    document.getElementById('save-contact').addEventListener('click', SaveContact, false);
    document.getElementById('reset-change').addEventListener('click', CloseContactWindow, false);
    if (!createNewContact) document.getElementById('removecontact').addEventListener('click', RemoveContact, false);

}
function CloseContactWindow() {
    document.getElementById('contact-list').style.display = 'flex';
    document.getElementById('header').style.display = 'flex';
    document.getElementById('add-contact').style.display = 'none';
    ContactsArray = JSON.parse(localStorage.getItem('Contacts'));

    ResetAddContactWindow();
    ReloadContactList(ContactsArray);
}
function ResetAddContactWindow() {
    SaveInputValue();
    let inputClean = document.getElementsByTagName('input');
    for (let i = 0; i < inputClean.length; i++){
        inputClean[i].value = '';
    }

    let addContact = document.getElementById('add-contact');
    while (addContact.firstChild){
        addContact.removeChild(addContact.firstChild);
    }
}
function ReloadContactList(currentArray) {
    let contactList = document.getElementById('contact-list');
    while (contactList.firstChild){
        contactList.removeChild(contactList.firstChild);
    }
    currentArray.sort(function (x, y) {
        if (x.name > y.name)
            return 1;
        if (x.name < y.name)
            return -1;
        return 0;
    });

    if (currentArray != ContactsArray) {
        for (let i = 0; i < currentArray.length; i++) {
            ContactListDraw(currentArray[i]);
        }
    } else {
        for (let i = 0; i < ContactsArray.length; i++) {
            ContactsArray[i].id = i;
            ContactListDraw(currentArray[i]);
        }
    }
}
//Отрисовка формы добавления и редактирования контакта
function AddContactDrow() {

    let contactForm = document.getElementById('add-contact');

    let headerDiv = document.createElement('div');
    headerDiv.setAttribute('class', 'text');
    contactForm.appendChild(headerDiv);
    let headerH = document.createElement('h2');
    if (createNewContact) {
        headerH.innerText = 'Add Contact';
    }else {
        headerH.innerText = 'Edit Contact';
        let removeContact = document.createElement('div');
        removeContact.setAttribute('id', 'removecontact');
        removeContact.innerText = 'Remove Contact';
        contactForm.appendChild(removeContact);
    }
    headerDiv.appendChild(headerH);

    for (element in Contact) {
        if (element == 'name') {
            let nameDiv = document.createElement('div');
            nameDiv.setAttribute('class', 'search');
            contactForm.appendChild(nameDiv);

            let nameSpan = document.createElement('span');
            nameSpan.innerText = 'Name';
            nameDiv.appendChild(nameSpan);
            let nameInput = document.createElement('input');
            nameInput.setAttribute('type', 'text');
            nameInput.setAttribute('id', 'name');
            nameDiv.appendChild(nameInput);
            nameInput.value = Contact.name;
            nameInput.oninput = function ()
            {
                let matchValue = /^[a-zA-Z\s]*$/;
                if (!nameInput.value.match(matchValue) || nameInput.value.length > 22)
                {
                    nameInput.value = nameInput.value.substr(0, nameInput.value.length - 1);
                }
            }
        }
        if (element == 'number') {
            for (let l = 0; l < Contact.number.length; l++) {
                let phoneDiv = document.createElement('div');
                phoneDiv.setAttribute('class', 'search plus-minus-fields');
                phoneDiv.setAttribute('id', 'phone-number-div');
                contactForm.appendChild(phoneDiv);

                let minusDiv = document.createElement('div');
                minusDiv.setAttribute('class', 'button-minus-phone');
                minusDiv.innerText = '-';
                minusDiv.setAttribute('id', l);
                phoneDiv.appendChild(minusDiv);

                let phoneDivEmpty = document.createElement('div');
                phoneDiv.appendChild(phoneDivEmpty);

                let phoneSpan = document.createElement('span');
                phoneSpan.innerText = 'Phone Number';
                phoneDivEmpty.appendChild(phoneSpan);
                let phoneInput = document.createElement('input');
                phoneInput.setAttribute('type', 'text');
                phoneInput.setAttribute('id', 'number'+l);
                phoneDivEmpty.appendChild(phoneInput);
                phoneInput.oninput = function ()
                {
                    if (isNaN(phoneInput.value+1) || phoneInput.value.length > 10)
                    {
                        phoneInput.value = phoneInput.value.substr(0, phoneInput.value.length - 1);
                    }
                }

                let plusDiv = document.createElement('div');
                plusDiv.setAttribute('class', 'button-plus-phone');
                plusDiv.innerText = '+';
                phoneDiv.appendChild(plusDiv);

                phoneInput.value = Contact.number[l];
            }
        }
        if (element == 'email') {
            for (let h = 0; h < Contact.email.length; h++) {
                let emailDiv = document.createElement('div');
                emailDiv.setAttribute('class', 'search plus-minus-fields');
                emailDiv.setAttribute('id', 'email-div');
                contactForm.appendChild(emailDiv);

                let minusDiv = document.createElement('div');
                minusDiv.setAttribute('class', 'button-minus-email');
                minusDiv.innerText = '-';
                minusDiv.setAttribute('id', h);
                emailDiv.appendChild(minusDiv);

                let emailDivEmpty = document.createElement('div');
                emailDiv.appendChild(emailDivEmpty);

                let emailSpan = document.createElement('span');
                emailSpan.innerText = 'E-mail Address';

                emailDivEmpty.appendChild(emailSpan);
                let emailInput = document.createElement('input');
                emailInput.setAttribute('type', 'text');
                emailInput.setAttribute('id', 'email'+h);
                emailDivEmpty.appendChild(emailInput);
                emailInput.oninput = function ()
                {
                    let matchValue = /^[a-z0-9@._]*$/;
                    if (!emailInput.value.match(matchValue) || emailInput.value.length > 25)
                    {
                        emailInput.value = emailInput.value.substr(0, emailInput.value.length - 1);
                    }
                }

                let plusDiv = document.createElement('div');
                plusDiv.setAttribute('class', 'button-plus-email');
                plusDiv.innerText = '+';
                emailDiv.appendChild(plusDiv);

                emailInput.value = Contact.email[h];
            }
        }
    }

    let buttonDiv = document.createElement('div');
    buttonDiv.setAttribute('class', 'search buttons');
    contactForm.appendChild(buttonDiv);

    let buttonOkDiv = document.createElement('div');
    buttonOkDiv.setAttribute('id', 'save-contact');
    buttonOkDiv.innerText = 'Ok';
    buttonDiv.appendChild(buttonOkDiv);

    let buttonCancelDiv = document.createElement('div');
    buttonCancelDiv.setAttribute('id', 'reset-change');
    buttonCancelDiv.innerText = 'Cancel';
    buttonDiv.appendChild(buttonCancelDiv);
}
function RemoveNumber(element) {
    if (element.id != 0){
        let removeElementParent = element.parentElement;
        let removeElement = removeElementParent.parentElement;
        removeElement.removeChild(removeElementParent);
        Contact.number.splice(element.id, 1);
        ResetAddContactWindow();
        OpenContactWindow(Contact);
    }
}
function AddNumber() {
    Contact.number[Contact.number.length] = '';
    ResetAddContactWindow();
    OpenContactWindow(Contact);
}
function RemoveMail(element) {
    if (element.id != 0) {
        let removeElementParent = element.parentElement;
        let removeElement = removeElementParent.parentElement;
        removeElement.removeChild(removeElementParent);
        Contact.email.splice(element.id, 1);
    }
}
function AddMail() {
    Contact.email[Contact.email.length] = '';
    ResetAddContactWindow();
    OpenContactWindow(Contact);
}
//Отрисовка списка контактов
function ContactListDraw(contact) {

    let contactList = document.getElementById('contact-list');

    let listDiv = document.createElement("div");
    listDiv.setAttribute('class', 'list');
    contactList.appendChild(listDiv);

    let logoDiv = document.createElement("div");
    logoDiv.setAttribute('class', 'logo');
    logoDiv.setAttribute('id', contact.id);
    listDiv.appendChild(logoDiv);
    let logoSpan = document.createElement('span');
    logoSpan.setAttribute('class', 'logospan');
    logoSpan.setAttribute('id', contact.id);
    logoDiv.appendChild(logoSpan);
    logoSpan.innerText ='Z';

    let contactdataDiv = document.createElement("div");
    contactdataDiv.setAttribute('class', 'contactdata');
    listDiv.appendChild(contactdataDiv);

for (element in contact){
    if (element == 'name') CreateName(contactdataDiv, contact);
    if (element == 'number')
    {
       // for (let j = 0; j < contact.number.length; j++) {
            CreateNumber(contactdataDiv, contact.number[0]);
      //  }
    }
    if (element == 'email')
    {
      //  for (let k = 0; k < contact.email.length; k++) {
            CreateEmail(contactdataDiv, contact.email[0]);
    //    }
    }
}

}
function CreateName(Div, contact) {
    let nameDiv = document.createElement("div");
    nameDiv.setAttribute('class', 'name');
    Div.appendChild(nameDiv);
    nameDiv.innerText = contact.name;
}
function CreateNumber(Div, contact) {
    let phoneDiv = document.createElement("div");
    phoneDiv.setAttribute('class', 'phone');
    Div.appendChild(phoneDiv);
    phoneDiv.innerText = contact;
}
function CreateEmail(Div,contact) {
    let emailDiv = document.createElement("div");
    emailDiv.setAttribute('class', 'email');
    Div.appendChild(emailDiv);
    emailDiv.innerText = contact;
}<commit_msg>Contact<commit_after>//Объявление общедоступных переменных
let ContactsArray = [];
let Contact;
let createNewContact = true;
let SearchArray = [];
//Блок событий при отображении списка контактов
document.getElementById('add-contact-button').addEventListener('click', AddNewContact, false);
let inputSearch = document.getElementById('inputsearch');
inputSearch.oninput = function () {

    SearchArray.length = 0;

    let matchValue = /^[a-zA-Z\s]*$/;
    if (!inputSearch.value.match(matchValue) || inputSearch.value.length > 22)
    {
        inputSearch.value = inputSearch.value.substr(0, inputSearch.value.length - 1);
    }

    for (let i = 0; i < ContactsArray.length; i++)
    {
        if (ContactsArray[i].name.toLowerCase().indexOf(inputSearch.value.toLowerCase()) ==  0 )
        {
            SearchArray.push(ContactsArray[i]);
        }
    }
    ReloadContactList(SearchArray);
}
document.getElementById('contact-list').onclick = function (event){
    let target = event.target || event.srcElement
    if (target.id != 'contact-list') {
        if (target.id != '')EditContact(target.id);
    }
    }
document.getElementById('add-contact').onclick = function (event){
    let target = event.target || event.srcElement

    if (target.className == 'button-plus-phone'){
        AddNumber();
    }
    if (target.className == 'button-minus-phone'){
        RemoveNumber(target);
    }
    if (target.className == 'button-plus-email'){
        AddMail();
    }
    if (target.className == 'button-minus-email'){
        RemoveMail(target);
    }
}
//Подтягивание базы контактов при первом запуске/релоаде
    if (localStorage.getItem('Contacts'))
    {
        ContactsArray = JSON.parse(localStorage.getItem('Contacts'));
        ReloadContactList(ContactsArray);
    }
//Логика добаления и редактирования контакта
function AddNewContact() {
    createNewContact = true;
    let newContact = {
        id: 0,
        name: '',
        number: [''],
        email: ['']
    }

    OpenContactWindow(newContact);
}
function RemoveContact() {
    ContactsArray.splice(Contact.id, 1);
    localStorage.setItem('Contacts', JSON.stringify(ContactsArray));
    CloseContactWindow();
    ReloadContactList(ContactsArray);
}
function EditContact(id) {
    for (let i = 0; i < ContactsArray.length; i++){
        if (ContactsArray[i].id == id){
            Contact = ContactsArray[i];
            createNewContact = false;
            OpenContactWindow(Contact);
            break;
        }
    }
}
function SaveContact() {

    let inputName = document.getElementById('name');
    let numberId0 = document.getElementById('number0');
    let emailId0 = document.getElementById('email0');

    SaveInputValue();

        if(inputName.value != '' && numberId0.value != '' && emailId0.value != '')
        {

            for (let i = 0; i < Contact.number.length; i++){
                if (Contact.number[i] == '')
                {
                    Contact.number.splice(i, 1);
                    i--;
                }
            }
            for (let i = 0; i < Contact.email.length; i++){
                if (Contact.email[i] == '')
                {
                    Contact.email.splice(i, 1);
                    i--;
                }
            }
    if (createNewContact) {
        ContactsArray.push(Contact);
    }

    ReloadContactList(ContactsArray)
    localStorage.setItem('Contacts', JSON.stringify(ContactsArray));

    CloseContactWindow();
        }
        else {
    if (numberId0.value == ''){
        numberId0.setAttribute('placeholder', 'Enter phone number');
    }
    if (emailId0.value == '') {
        emailId0.setAttribute('placeholder', 'Enter e-mail address')
    }
    if (inputName.value == ''){
        inputName.setAttribute('placeholder', 'Enter contact name')
    }
}
}
function SaveInputValue() {
    let inputName = document.getElementById('name');
    Contact.name = inputName.value;
    for(let z = 0; z < Contact.number.length; z++){
        let numberId = document.getElementById('number'+z);
        if (numberId != null)Contact.number[z] = numberId.value;
    }
    for(let y = 0; y < Contact.email.length; y++){
        let emailId = document.getElementById('email'+y);
        if (emailId != null)Contact.email[y] = emailId.value;
    }
}
//Логика переключения между списком контактов и формой добавления/редактирования контакта
function OpenContactWindow(contact) {

    Contact = contact;
    document.getElementById('contact-list').style.display = 'none';
    document.getElementById('header').style.display = 'none';
    document.getElementById('add-contact').style.display = 'flex';
    AddContactDrow();

    document.getElementById('save-contact').addEventListener('click', SaveContact, false);
    document.getElementById('reset-change').addEventListener('click', CloseContactWindow, false);
    if (!createNewContact) document.getElementById('removecontact').addEventListener('click', RemoveContact, false);

}
function CloseContactWindow() {
    document.getElementById('contact-list').style.display = 'flex';
    document.getElementById('header').style.display = 'flex';
    document.getElementById('add-contact').style.display = 'none';
    ContactsArray = JSON.parse(localStorage.getItem('Contacts'));

    ResetAddContactWindow();
    ReloadContactList(ContactsArray);
}
function ResetAddContactWindow() {
    SaveInputValue();
    let inputClean = document.getElementsByTagName('input');
    for (let i = 0; i < inputClean.length; i++){
        inputClean[i].value = '';
    }

    let addContact = document.getElementById('add-contact');
    while (addContact.firstChild){
        addContact.removeChild(addContact.firstChild);
    }
}
function ReloadContactList(currentArray) {
    let contactList = document.getElementById('contact-list');
    while (contactList.firstChild){
        contactList.removeChild(contactList.firstChild);
    }
	if (currentArray != null){
    currentArray.sort(function (x, y) {
        if (x.name > y.name)
            return 1;
        if (x.name < y.name)
            return -1;
        return 0;
    });
	}
    if (currentArray != ContactsArray) {
        for (let i = 0; i < currentArray.length; i++) {
            ContactListDraw(currentArray[i]);
        }
    } else {
        for (let i = 0; i < ContactsArray.length; i++) {
            ContactsArray[i].id = i;
            ContactListDraw(currentArray[i]);
        }
    }
}
//Отрисовка формы добавления и редактирования контакта
function AddContactDrow() {

    let contactForm = document.getElementById('add-contact');

    let headerDiv = document.createElement('div');
    headerDiv.setAttribute('class', 'text');
    contactForm.appendChild(headerDiv);
    let headerH = document.createElement('h2');
    if (createNewContact) {
        headerH.innerText = 'Add Contact';
    }else {
        headerH.innerText = 'Edit Contact';
        let removeContact = document.createElement('div');
        removeContact.setAttribute('id', 'removecontact');
        removeContact.innerText = 'Remove Contact';
        contactForm.appendChild(removeContact);
    }
    headerDiv.appendChild(headerH);

    for (element in Contact) {
        if (element == 'name') {
            let nameDiv = document.createElement('div');
            nameDiv.setAttribute('class', 'search');
            contactForm.appendChild(nameDiv);

            let nameSpan = document.createElement('span');
            nameSpan.innerText = 'Name';
            nameDiv.appendChild(nameSpan);
            let nameInput = document.createElement('input');
            nameInput.setAttribute('type', 'text');
            nameInput.setAttribute('id', 'name');
            nameDiv.appendChild(nameInput);
            nameInput.value = Contact.name;
            nameInput.oninput = function ()
            {
                let matchValue = /^[a-zA-Z\s]*$/;
                if (!nameInput.value.match(matchValue) || nameInput.value.length > 22)
                {
                    nameInput.value = nameInput.value.substr(0, nameInput.value.length - 1);
                }
            }
        }
        if (element == 'number') {
            for (let l = 0; l < Contact.number.length; l++) {
                let phoneDiv = document.createElement('div');
                phoneDiv.setAttribute('class', 'search plus-minus-fields');
                phoneDiv.setAttribute('id', 'phone-number-div');
                contactForm.appendChild(phoneDiv);

                let minusDiv = document.createElement('div');
                minusDiv.setAttribute('class', 'button-minus-phone');
                minusDiv.innerText = '-';
                minusDiv.setAttribute('id', l);
                phoneDiv.appendChild(minusDiv);

                let phoneDivEmpty = document.createElement('div');
                phoneDiv.appendChild(phoneDivEmpty);

                let phoneSpan = document.createElement('span');
                phoneSpan.innerText = 'Phone Number';
                phoneDivEmpty.appendChild(phoneSpan);
                let phoneInput = document.createElement('input');
                phoneInput.setAttribute('type', 'text');
                phoneInput.setAttribute('id', 'number'+l);
                phoneDivEmpty.appendChild(phoneInput);
                phoneInput.oninput = function ()
                {
                    if (isNaN(phoneInput.value+1) || phoneInput.value.length > 10)
                    {
                        phoneInput.value = phoneInput.value.substr(0, phoneInput.value.length - 1);
                    }
                }

                let plusDiv = document.createElement('div');
                plusDiv.setAttribute('class', 'button-plus-phone');
                plusDiv.innerText = '+';
                phoneDiv.appendChild(plusDiv);

                phoneInput.value = Contact.number[l];
            }
        }
        if (element == 'email') {
            for (let h = 0; h < Contact.email.length; h++) {
                let emailDiv = document.createElement('div');
                emailDiv.setAttribute('class', 'search plus-minus-fields');
                emailDiv.setAttribute('id', 'email-div');
                contactForm.appendChild(emailDiv);

                let minusDiv = document.createElement('div');
                minusDiv.setAttribute('class', 'button-minus-email');
                minusDiv.innerText = '-';
                minusDiv.setAttribute('id', h);
                emailDiv.appendChild(minusDiv);

                let emailDivEmpty = document.createElement('div');
                emailDiv.appendChild(emailDivEmpty);

                let emailSpan = document.createElement('span');
                emailSpan.innerText = 'E-mail Address';

                emailDivEmpty.appendChild(emailSpan);
                let emailInput = document.createElement('input');
                emailInput.setAttribute('type', 'text');
                emailInput.setAttribute('id', 'email'+h);
                emailDivEmpty.appendChild(emailInput);
                emailInput.oninput = function ()
                {
                    let matchValue = /^[a-z0-9@._]*$/;
                    if (!emailInput.value.match(matchValue) || emailInput.value.length > 25)
                    {
                        emailInput.value = emailInput.value.substr(0, emailInput.value.length - 1);
                    }
                }

                let plusDiv = document.createElement('div');
                plusDiv.setAttribute('class', 'button-plus-email');
                plusDiv.innerText = '+';
                emailDiv.appendChild(plusDiv);

                emailInput.value = Contact.email[h];
            }
        }
    }

    let buttonDiv = document.createElement('div');
    buttonDiv.setAttribute('class', 'search buttons');
    contactForm.appendChild(buttonDiv);

    let buttonOkDiv = document.createElement('div');
    buttonOkDiv.setAttribute('id', 'save-contact');
    buttonOkDiv.innerText = 'Ok';
    buttonDiv.appendChild(buttonOkDiv);

    let buttonCancelDiv = document.createElement('div');
    buttonCancelDiv.setAttribute('id', 'reset-change');
    buttonCancelDiv.innerText = 'Cancel';
    buttonDiv.appendChild(buttonCancelDiv);
}
function RemoveNumber(element) {
    if (element.id != 0){
        let removeElementParent = element.parentElement;
        let removeElement = removeElementParent.parentElement;
        removeElement.removeChild(removeElementParent);
        Contact.number.splice(element.id, 1);
        ResetAddContactWindow();
        OpenContactWindow(Contact);
    }
}
function AddNumber() {
    Contact.number[Contact.number.length] = '';
    ResetAddContactWindow();
    OpenContactWindow(Contact);
}
function RemoveMail(element) {
    if (element.id != 0) {
        let removeElementParent = element.parentElement;
        let removeElement = removeElementParent.parentElement;
        removeElement.removeChild(removeElementParent);
        Contact.email.splice(element.id, 1);
    }
}
function AddMail() {
    Contact.email[Contact.email.length] = '';
    ResetAddContactWindow();
    OpenContactWindow(Contact);
}
//Отрисовка списка контактов
function ContactListDraw(contact) {

    let contactList = document.getElementById('contact-list');

    let listDiv = document.createElement("div");
    listDiv.setAttribute('class', 'list');
    contactList.appendChild(listDiv);

    let logoDiv = document.createElement("div");
    logoDiv.setAttribute('class', 'logo');
    logoDiv.setAttribute('id', contact.id);
    listDiv.appendChild(logoDiv);
    let logoSpan = document.createElement('span');
    logoSpan.setAttribute('class', 'logospan');
    logoSpan.setAttribute('id', contact.id);
    logoDiv.appendChild(logoSpan);
    logoSpan.innerText ='Z';

    let contactdataDiv = document.createElement("div");
    contactdataDiv.setAttribute('class', 'contactdata');
    listDiv.appendChild(contactdataDiv);

for (element in contact){
    if (element == 'name') CreateName(contactdataDiv, contact);
    if (element == 'number')
    {
       // for (let j = 0; j < contact.number.length; j++) {
            CreateNumber(contactdataDiv, contact.number[0]);
      //  }
    }
    if (element == 'email')
    {
      //  for (let k = 0; k < contact.email.length; k++) {
            CreateEmail(contactdataDiv, contact.email[0]);
    //    }
    }
}

}
function CreateName(Div, contact) {
    let nameDiv = document.createElement("div");
    nameDiv.setAttribute('class', 'name');
    Div.appendChild(nameDiv);
    nameDiv.innerText = contact.name;
}
function CreateNumber(Div, contact) {
    let phoneDiv = document.createElement("div");
    phoneDiv.setAttribute('class', 'phone');
    Div.appendChild(phoneDiv);
    phoneDiv.innerText = contact;
}
function CreateEmail(Div,contact) {
    let emailDiv = document.createElement("div");
    emailDiv.setAttribute('class', 'email');
    Div.appendChild(emailDiv);
    emailDiv.innerText = contact;
}<|endoftext|>


<commit_before>(function() {
  'use strict';
  angular.module('runAndFun').controller('ActivityController', ActivityController);

  ActivityController.$inject = [ 'ActivityService', '$filter' ];

  function ActivityController(ActivityService, $filter) {
    var vm = this;

    // public methods
    vm.list = list;
    vm.remove = remove;

    // public fields
    vm.activities = {
      totalElements : 0
    };
    vm.predicate = 'date';
    vm.reverse = true;

    vm.size = 10;
    vm.filterType = 'Running';

    vm.totalActivities = 0;
    vm.totalDistance = 0;
    vm.totalDuration = 0;
    vm.totalTimePerKm = 0;
    vm.totalTimePer5Km = 0;
    vm.totalTimePer10Km = 0;

    vm.years = [];

    // init
    years();
    list();

    function list() {
      console.debug('ActivityController.list');
      var minDate = $filter('date')(vm.filterMinDate, 'yyyy-MM-dd');
      var maxDate = $filter('date')(vm.filterMaxDate, 'yyyy-MM-dd');
      if (vm.filterYear.key !== '') {
        minDate = vm.filterYear.year + '-01-01';
        maxDate = vm.filterYear.year + '-12-31';
      }
      ActivityService.list(vm.size, vm.filterType, minDate, maxDate, vm.filterMinDistance, vm.filterMaxDistance, vm.filterFulltext).then(
          function(data) {
            vm.activities = data;
            ActivityService.recalculateTotals(vm);
          });
    }

    function remove(activity) {
      console.debug('ActivityController.remove');
      var index = vm.activities.content.indexOf(activity);
      vm.activities.content.splice(index, 1);
      ActivityService.recalculateTotals(vm);
    }

    function years() {
      var filterAll = {
        'key' : '',
        'year' : 'All years'
      };
      vm.years.push(filterAll);
      var startYear = 2010;
      var endYear = 2020;
      for (var i = startYear; i <= endYear; i++) {
        vm.years.push({'key' : i, 'year' : i });
      }
      vm.filterYear = filterAll;
    }
  }
})();
<commit_msg>removed unused comparison<commit_after>(function() {
  'use strict';
  angular.module('runAndFun').controller('ActivityController', ActivityController);

  ActivityController.$inject = [ 'ActivityService', '$filter' ];

  function ActivityController(ActivityService, $filter) {
    var vm = this;

    // public methods
    vm.list = list;
    vm.remove = remove;

    // public fields
    vm.activities = {
      totalElements : 0
    };
    vm.predicate = 'date';
    vm.reverse = true;

    vm.size = 10;
    vm.filterType = 'Running';

    vm.totalActivities = 0;
    vm.totalDistance = 0;
    vm.totalDuration = 0;
    vm.totalTimePerKm = 0;
    vm.totalTimePer5Km = 0;
    vm.totalTimePer10Km = 0;

    vm.years = [];

    // init
    years();
    list();

    function list() {
      console.debug('ActivityController.list');
      var minDate = $filter('date')(vm.filterMinDate, 'yyyy-MM-dd');
      var maxDate = $filter('date')(vm.filterMaxDate, 'yyyy-MM-dd');
      if (vm.filterYear.key) {
        minDate = vm.filterYear.year + '-01-01';
        maxDate = vm.filterYear.year + '-12-31';
      }
      ActivityService.list(vm.size, vm.filterType, minDate, maxDate, vm.filterMinDistance, vm.filterMaxDistance, vm.filterFulltext).then(
          function(data) {
            vm.activities = data;
            ActivityService.recalculateTotals(vm);
          });
    }

    function remove(activity) {
      console.debug('ActivityController.remove');
      var index = vm.activities.content.indexOf(activity);
      vm.activities.content.splice(index, 1);
      ActivityService.recalculateTotals(vm);
    }

    function years() {
      var filterAll = {
        'key' : '',
        'year' : 'All years'
      };
      vm.years.push(filterAll);
      var startYear = 2010;
      var endYear = 2020;
      for (var i = startYear; i <= endYear; i++) {
        vm.years.push({'key' : i, 'year' : i });
      }
      vm.filterYear = filterAll;
    }
  }
})();
<|endoftext|>


<commit_before>var patientId = 0;
var therapyId = 0;

$(document).ready(function () {

	/*********************
	 FIRST STAGE NAVIGATION
	 **********************/

	$('.select-patient').click(function () {
		// get id and name
		patientId = $(this).attr('data-id');
		$('.patient-selected').html($(this).attr('data-name'));

		// open next page
		$('#page-one').slideUp(500);
		$('#page-two').slideDown(500);
	});

	$('#go-back-to-select-patient').click(function () {
		// open prev page
		$('#page-one').slideDown(500);
		$('#page-two').slideUp(500);
	});

	$('.select-therapy').click(function () {
		// get id and name
		therapyId = $(this).attr('data-id');
		$('.therapy-selected').html($(this).attr('data-name') + ' ');

		// reload tooltips
		$("body").tooltip({selector: '[data-toggle=tooltip]'});

		// set specified cameras
		var rawCameras = ($(this).attr('data-cameras').split(":"))[1].split(",");
		var cameras = [];
		for (var c in rawCameras) {
			if (rawCameras[c] != "") cameras.push(rawCameras[c]);
		}
		if (cameras.length > 0) {
			selectedCameras = cameras;
		}

		// open next page
		$('#page-two').slideUp(500);
		$('#page-three').slideDown(500);
	});

	$('#go-back-to-select-therapy').click(function () {
		// open prev page
		$('#page-two').slideDown(500);
		$('#page-three').slideUp(500);
	});

	/***********************
	 FIRST STAGE DATA TABLES
	 ***********************/

	setUpDataTable('#patients-table', 0, [[1, 1], [1, 1], [1, 1], [1, 1], [1, 1], [0, 0]]);
	setUpDataTable('#therapies-table', 0, [[1, 1], [1, 1], [1, 1], [1, 1], [0, 0]]);

	// "show more" links
	$('.more-camera-types').click(function (e) {
		e.preventDefault();
		$('#' + $(this).attr('data-target')).slideDown();
		$(this).closest('span').hide();
	});

	/********************
	 SECOND STAGE CALENDAR
	 *********************/

	// initial set up
	var calendar = $('.calendar');

	// when the "show bookings" button is clicked...
	$('#view-available-bookings').click(function () {
		// hide buttons
		$(this).slideUp(300);
		$('#go-back-to-select-therapy').hide();

		// add button for saving the bookings
		$('#page-three-sub-div').find('div.col-sm-4').eq(2).html('<button class="btn btn-primary" id="saveAppointments" disabled>Select Time Slot(s) Below...</button>');

		// variables for modal
		var startTimeObject;
		var endTimeObject;

		// modal inputs
		var startTimeInput = $('input[name=start-time]');
		var endTimeInput = $('input[name=end-time]');

		// function to be ran when a slot is selected
		var onSelectFunction = function (start, end, allday) {
			// assign outer items
			startTimeObject = start;
			endTimeObject = end;

			// get options to pre-fill modal
			var startHours = (start.getHours() < 10 ? '0' : '') + start.getHours();
			var startMins = (start.getMinutes() < 10 ? '0' : '') + start.getMinutes();
			var endHours = (end.getHours() < 10 ? '0' : '') + end.getHours();
			var endMins = (end.getMinutes() < 10 ? '0' : '') + end.getMinutes();

			if (start.getDate() < (new Date()).getDate()) {
				toastr.error("You cannot make a booking in the past");
				calendar.fullCalendar('unselect');
				return;
			}

			// pre-fill modal
			startTimeInput.val(startHours + ':' + startMins);
			endTimeInput.val(endHours + ':' + endMins);
			prepareTimeSelector();

			// open Modal
			var timeModal = $('.time-modal');
			timeModal.removeClass('hide').modal('show');
			setTimeout(function () {
				timeModal.find('select').eq(0).focus().select();
			}, 200);
		};

		// show calendar
		calendar = setupCalendar($('.calendar'), onSelectFunction, {
			linkEvents: false,
			selectable: true
		});

		// start building JSON to send
		var datesSelectedJSON;
		datesSelectedJSON = "{\"patientId\":" + patientId + "," + "\"therapyId\":" + therapyId + "," + "\"bookingSections\":[";

		// click ok to keep appointment;
		$('.btn-save').click(function () {
			// get start/end time
			var startTime = startTimeInput.val();
			var endTime = endTimeInput.val();

			// check valid times were entered
			if (!startTime.match(/[0-9]{2}:[0-9]{2}/) || !endTime.match(/[0-9]{2}:[0-9]{2}/)) {
				toastr.error("Please select valid start and end times.");
				return;
			}

			// check start < end
			if (new Date('2000-01-01 ' + startTime) >= new Date('2000-01-01 ' + endTime)) {
				toastr.error("Please ensure the start time is before the end time.");
				return;
			}

			// enable button
			$('#saveAppointments').removeAttr('disabled').html("Save Booking");

			// add to json
			var fullStartTime = startTimeObject.getFullYear() + '-'
				+ (startTimeObject.getMonth() < 10 ? '0' : '') + (startTimeObject.getMonth() + 1) + '-'
				+ (startTimeObject.getDate() < 10 ? '0' : '') + startTimeObject.getDate() + 'T'
				+ startTime + ":00";
			var fullEndTime = endTimeObject.getFullYear() + '-'
				+ (endTimeObject.getMonth() < 10 ? '0' : '') + (endTimeObject.getMonth() + 1) + '-'
				+ (endTimeObject.getDate() < 10 ? '0' : '') + endTimeObject.getDate() + 'T'
				+ endTime + ":00";
			datesSelectedJSON += "{\"startTime\":\"" + fullStartTime + "\",";
			datesSelectedJSON += "\"endTime\":\"" + fullEndTime + "\"},";

			// add to calendar
			calendar.fullCalendar('renderEvent',
				{
					title: $('.therapy-selected').text() + ":\n" + $('.patient-selected').eq(0).text(),
					start: fullStartTime,
					end: fullEndTime,
					msg: "Start time: " + startTime + "" +
					"
End time: " + endTime + "",
					allDay: false
				},
				true
			);
			calendar.fullCalendar('unselect');

			// close modal
			$('.time-modal').modal('hide');
		});

		// Function to send the user to the next page.
		$('#saveAppointments').click(function () {
			// finish the JSON
			datesSelectedJSON = datesSelectedJSON.substring(0, datesSelectedJSON.length - 1);
			datesSelectedJSON += "]}";

			// send!
			$('#jsonToSend').val(datesSelectedJSON);
			$('form.submission-form').submit();
		});
	});

});
<commit_msg>Fixed calendars on new booking page<commit_after>var patientId = 0;
var therapyId = 0;

$(document).ready(function () {

	/*********************
	 FIRST STAGE NAVIGATION
	 **********************/

	$('.select-patient').click(function () {
		// get id and name
		patientId = $(this).attr('data-id');
		$('.patient-selected').html($(this).attr('data-name'));

		// open next page
		$('#page-one').slideUp(500);
		$('#page-two').slideDown(500);
	});

	$('#go-back-to-select-patient').click(function () {
		// open prev page
		$('#page-one').slideDown(500);
		$('#page-two').slideUp(500);
	});

	$('.select-therapy').click(function () {
		// get id and name
		therapyId = $(this).attr('data-id');
		$('.therapy-selected').html($(this).attr('data-name') + ' ');

		// reload tooltips
		$("body").tooltip({selector: '[data-toggle=tooltip]'});

		// set specified cameras
		var rawCameras = ($(this).attr('data-cameras').split(":"))[1].split(",");
		var cameras = [];
		for (var c in rawCameras) {
			if (rawCameras[c] != "") cameras.push(rawCameras[c]);
		}
		if (cameras.length > 0) {
			selectedCameras = cameras;
		}

		// open next page
		$('#page-two').slideUp(500);
		$('#page-three').slideDown(500);
	});

	$('#go-back-to-select-therapy').click(function () {
		// open prev page
		$('#page-two').slideDown(500);
		$('#page-three').slideUp(500);
	});

	/***********************
	 FIRST STAGE DATA TABLES
	 ***********************/

	setUpDataTable('#patients-table', [[1, 1], [1, 1], [1, 1], [1, 1], [1, 1], [0, 0]], {
		order: [0, 'asc']
	});
	setUpDataTable('#therapies-table', [[1, 1], [1, 1], [1, 1], [1, 1], [0, 0]], {
		order: [0, 'asc']
	});

	// "show more" links
	$('.more-camera-types').click(function (e) {
		e.preventDefault();
		$('#' + $(this).attr('data-target')).slideDown();
		$(this).closest('span').hide();
	});

	/********************
	 SECOND STAGE CALENDAR
	 *********************/

	// initial set up
	var calendar = $('.calendar');

	// when the "show bookings" button is clicked...
	$('#view-available-bookings').click(function () {
		// hide buttons
		$(this).slideUp(300);
		$('#go-back-to-select-therapy').hide();

		// add button for saving the bookings
		$('#page-three-sub-div').find('div.col-sm-4').eq(2).html('<button class="btn btn-primary" id="saveAppointments" disabled>Select Time Slot(s) Below...</button>');

		// variables for modal
		var startTimeObject;
		var endTimeObject;

		// modal inputs
		var startTimeInput = $('input[name=start-time]');
		var endTimeInput = $('input[name=end-time]');

		// function to be ran when a slot is selected
		var onSelectFunction = function (start, end, allday) {
			// assign outer items
			startTimeObject = start;
			endTimeObject = end;

			// get options to pre-fill modal
			var startHours = (start.getHours() < 10 ? '0' : '') + start.getHours();
			var startMins = (start.getMinutes() < 10 ? '0' : '') + start.getMinutes();
			var endHours = (end.getHours() < 10 ? '0' : '') + end.getHours();
			var endMins = (end.getMinutes() < 10 ? '0' : '') + end.getMinutes();

			if (start.getDate() < (new Date()).getDate()) {
				toastr.error("You cannot make a booking in the past");
				calendar.fullCalendar('unselect');
				return;
			}

			// pre-fill modal
			startTimeInput.val(startHours + ':' + startMins);
			endTimeInput.val(endHours + ':' + endMins);
			prepareTimeSelector();

			// open Modal
			var timeModal = $('.time-modal');
			timeModal.removeClass('hide').modal('show');
			setTimeout(function () {
				timeModal.find('select').eq(0).focus().select();
			}, 200);
		};

		// show calendar
		calendar = setupCalendar($('.calendar'), onSelectFunction, {
			linkEvents: false,
			selectable: true
		});

		// start building JSON to send
		var datesSelectedJSON;
		datesSelectedJSON = "{\"patientId\":" + patientId + "," + "\"therapyId\":" + therapyId + "," + "\"bookingSections\":[";

		// click ok to keep appointment;
		$('.btn-save').click(function () {
			// get start/end time
			var startTime = startTimeInput.val();
			var endTime = endTimeInput.val();

			// check valid times were entered
			if (!startTime.match(/[0-9]{2}:[0-9]{2}/) || !endTime.match(/[0-9]{2}:[0-9]{2}/)) {
				toastr.error("Please select valid start and end times.");
				return;
			}

			// check start < end
			if (new Date('2000-01-01 ' + startTime) >= new Date('2000-01-01 ' + endTime)) {
				toastr.error("Please ensure the start time is before the end time.");
				return;
			}

			// enable button
			$('#saveAppointments').removeAttr('disabled').html("Save Booking");

			// add to json
			var fullStartTime = startTimeObject.getFullYear() + '-'
				+ (startTimeObject.getMonth() < 10 ? '0' : '') + (startTimeObject.getMonth() + 1) + '-'
				+ (startTimeObject.getDate() < 10 ? '0' : '') + startTimeObject.getDate() + 'T'
				+ startTime + ":00";
			var fullEndTime = endTimeObject.getFullYear() + '-'
				+ (endTimeObject.getMonth() < 10 ? '0' : '') + (endTimeObject.getMonth() + 1) + '-'
				+ (endTimeObject.getDate() < 10 ? '0' : '') + endTimeObject.getDate() + 'T'
				+ endTime + ":00";
			datesSelectedJSON += "{\"startTime\":\"" + fullStartTime + "\",";
			datesSelectedJSON += "\"endTime\":\"" + fullEndTime + "\"},";

			// add to calendar
			calendar.fullCalendar('renderEvent',
				{
					title: $('.therapy-selected').text() + ":\n" + $('.patient-selected').eq(0).text(),
					start: fullStartTime,
					end: fullEndTime,
					msg: "Start time: " + startTime + "" +
					"
End time: " + endTime + "",
					allDay: false
				},
				true
			);
			calendar.fullCalendar('unselect');

			// close modal
			$('.time-modal').modal('hide');
		});

		// Function to send the user to the next page.
		$('#saveAppointments').click(function () {
			// finish the JSON
			datesSelectedJSON = datesSelectedJSON.substring(0, datesSelectedJSON.length - 1);
			datesSelectedJSON += "]}";

			// send!
			$('#jsonToSend').val(datesSelectedJSON);
			$('form.submission-form').submit();
		});
	});

});
<|endoftext|>


<commit_before>/* jshint browser: true */
(function(window, document) {"use strict";  /* Wrap code in an IIFE */

var jQuery, $; // Localize jQuery variables
//var opendesktopwigeturl = 'http://pling.local/';
var opendesktopwigeturl = 'http://pling.cc/';
//var opendesktopwigeturl = 'https://opendesktop.org/';
 let indicator = '';

function loadScript(url, callback) {
  /* Load script from url and calls callback once it's loaded */
  var scriptTag = document.createElement('script');
  scriptTag.setAttribute("type", "text/javascript");
  scriptTag.setAttribute("src", url);
  if (typeof callback !== "undefined") {
    if (scriptTag.readyState) {
      /* For old versions of IE */
      scriptTag.onreadystatechange = function () {
        if (this.readyState === 'complete' || this.readyState === 'loaded') {
          callback();
        }
      };
    } else {
      scriptTag.onload = callback;
    }
  }
  (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(scriptTag);
}

function opendesktopFilterReviews(filterBtn){
    //init
    let reContainer = $('#opendesktopwidget-reviews');
    reContainer.find('.opendesktopwidget-reviews-rows').show();

    let inactive =  reContainer.find('.opendesktopwidget-reviews-rows-inactive');
    let active = reContainer.find('.opendesktopwidget-reviews-rows-active');
    let up =  reContainer.find('.opendesktopwidget-reviews-rows-clsUpvotes');
    let down = reContainer.find('.opendesktopwidget-reviews-rows-clsDownvotes');

    if($(filterBtn).attr('id')=='opendesktopwidget-reviews-filters-all'){
          inactive.show();
          active.show();
    } else  if($(filterBtn).attr('id')=='opendesktopwidget-reviews-filters-active'){
          inactive.hide();
          active.show();
    } else  if($(filterBtn).attr('id')=='opendesktopwidget-reviews-filters-likes'){
          up.show();
          down.hide();
          inactive.hide();
    } else if($(filterBtn).attr('id')=='opendesktopwidget-reviews-filters-hates'){
          up.hide();
          down.show();
          inactive.hide();
    }
    $('html, body').animate({
           scrollTop: reContainer.offset().top-150
       }, 1);
}

function opendesktoptoggleDetail(thisrow){
                let listcontainer = $('#opendesktopwidget-main');
                let detailcontainer = $('#opendesktopwidget-main-detail-container');

                let detailpopup = '
'
                                            +'

'
                                            +'×'
                                            +'
'
                                            +'
'
                                            +'

'
                                            +'

';

                let modal = $('#opendesktopwidget-main-detail-modal');
                if(detailcontainer.length==0){
                      listcontainer.parent().append($(detailpopup));
                      detailcontainer = $('#opendesktopwidget-main-detail-container');
                      modal.show();
                }else{
                     modal.show();
                      detailcontainer.html('');
                }

                $('a[data-opendesktop-dismiss]').on('click',function(){
                      $('#opendesktopwidget-main-detail-modal').hide();
                });

                let projectid = $(thisrow).attr('data-project-id').trim();
                let container  = $('

');
                container.append(indicator);
                detailcontainer.append(container);
                let jsonp_url_projectdetail = opendesktopwigeturl+"embed/v1/project/"+projectid+"?&callback=?";
                $.getJSON(jsonp_url_projectdetail, function(data) {
                    container.html(data.html);

                    // images carousel
                    let imgs = $('#opendesktopwidget-main-detail-carousel').find('img');
                    if(imgs.length>1){

                            $('#opendesktopwidget-main-detail-carousel').slick({
                                    dots: true
                                });
                    }

                    // tabs onclick
                    let lis = container.find('#opendesktopwidget-content-tabs').find('li');
                    lis.each(function(index) {
                        $(this).on("click", function(){
                            $(this).addClass('active').siblings().removeClass('active');
                            let tabcontainerid = $(this).find('a').attr('data-wiget-target');
                            $(tabcontainerid).addClass('active').siblings().removeClass('active') ;

                        });
                    });

                    // project comments paging
                    let spans = container.find('.opendesktopwidgetcomments').find('ul.opendesktopwidgetpager').find('span');
                    spans.each(function(index) {
                        $(this).on("click", function(){
                            $(this).parent().addClass('active').siblings().removeClass('active');

                           $(indicator).insertBefore(container.find('.opendesktopwidgetcomments').find('ul.opendesktopwidgetpager'));
                            let jsonp_url_nopage = opendesktopwigeturl+"embed/v1/comments/"+projectid+"?nopage=1&page="+$(this).html()+"&callback=?";
                            $.getJSON(jsonp_url_nopage, function(data) {
                                container.find('i.fa-spinner').remove();
                                let ct = container.find('#opendesktopwidget-main-container-comments');
                                ct.html(data.html);

                            });

                        });
                    });

                    // reviews filter
                    let reviewsfilters = container.find('#opendesktopwidget-reviews').find('.opendesktop-widget-reviews-filters-btn');
                    reviewsfilters.each(function(index){
                          $(this).on("click", function(){
                                $(this).addClass('opendesktopwidget-reviews-activeRating').siblings().removeClass('opendesktopwidget-reviews-activeRating');
                                opendesktopFilterReviews(this);
                          });
                    });

                });
        }

function main() {

        /******* Load CSS *******/

        let opendesktopwidgetcss_link = $("<link>", { rel: "stylesheet", type: "text/css", href: opendesktopwigeturl+"widget/style.css" });
        let fontawsomecss_link =$("<link>", { rel: "stylesheet", type: "text/css", href:"http://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" });
        let slick_link =$("<link>", { rel: "stylesheet", type: "text/css", href:"https://cdn.jsdelivr.net/jquery.slick/1.6.0/slick.css" });
        let slick_theme_link =$("<link>", { rel: "stylesheet", type: "text/css", href:"https://cdn.jsdelivr.net/jquery.slick/1.6.0/slick-theme.css" });

        opendesktopwidgetcss_link.appendTo('head');
        fontawsomecss_link.appendTo('head');
        slick_link.appendTo('head');
        slick_theme_link.appendTo('head');

        /******* Load HTML *******/
      let this_js_script = $('#opendesktopwiget');
      let memberid = this_js_script.attr('data-memberid');
      let countperpage = this_js_script.attr('data-countperpage');
      let catids = this_js_script.attr('data-catids');
      let query = '';
      if(countperpage){
           query = 'pagelimit='+countperpage+'&';
      }
      if(catids){
           query =query+'catids='+catids+'&';
      }

       if (typeof memberid === "undefined" ) {
          alert('Please set data-memberid in your script.');
          return;
       }

       $('#opendesktopwiget').after('
'+indicator+'
');
       let jsonp_url = opendesktopwigeturl+"embed/v1/member/"+memberid+"?"+query+"callback=?";
        $.getJSON(jsonp_url, function(data) {
              $('#opendesktop-widget-container').html(data.html);
              let spans = $('.opendesktopwidgetpager').find('span');
              spans.each(function(index) {
                  $(this).on("click", function(){
                      $(this).parent().addClass('active').siblings().removeClass('active');
                      $(indicator).insertBefore($('#opendesktop-widget-container').find('ul.opendesktopwidgetpager'));
                      let jsonp_url_nopage = opendesktopwigeturl+"embed/v1/member/"+memberid+"?"+query+"nopage=1&page="+$(this).html()+"&callback=?";
                      $.getJSON(jsonp_url_nopage, function(data) {
                          $('#opendesktop-widget-container').find('i.fa-spinner').remove();
                          $('#opendesktopwidget-main-container').html(data.html);
                          let rows =$('#opendesktop-widget-container').find('.opendesktopwidgetrow');
                               rows.each(function(index) {
                                   $(this).on("click", function(){
                                        opendesktoptoggleDetail(this);
                                   });
                               });
                      });

                  });
              });

              let rows =$('#opendesktop-widget-container').find('.opendesktopwidgetrow');
              rows.each(function(index) {
                  $(this).on("click", function(){
                        opendesktoptoggleDetail(this);
                  });
              });

        });
}

/* Load jQuery */
loadScript("https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js", function() {

      loadScript("https://code.jquery.com/jquery-migrate-1.2.1.min.js", function() {

                /* Restore $ and window.jQuery to their previous values and store the
                   new jQuery in our local jQuery variables. */
                  //$ = jQuery = window.jQuery.noConflict(false);
                  $ = jQuery = window.jQuery.noConflict();

                //$.noConflict();
                //$.noConflict();
                /* Load jQuery plugin and execute the main logic of our widget once the
                   plugin is loaded is loaded */

                loadScript("https://cdn.jsdelivr.net/jquery.slick/1.6.0/slick.min.js", function() {

                  main();
                });

      });
});

}(window, document)); /* end IIFE */<commit_msg>widget update2<commit_after>/* jshint browser: true */
(function(window, document) {"use strict";  /* Wrap code in an IIFE */

var jQuery, $; // Localize jQuery variables
//var opendesktopwigeturl = 'http://pling.local/';
var opendesktopwigeturl = 'http://pling.cc/';
//var opendesktopwigeturl = 'https://opendesktop.org/';
 let indicator = '';

function loadScript(url, callback) {
  /* Load script from url and calls callback once it's loaded */
  var scriptTag = document.createElement('script');
  scriptTag.setAttribute("type", "text/javascript");
  scriptTag.setAttribute("src", url);
  if (typeof callback !== "undefined") {
    if (scriptTag.readyState) {
      /* For old versions of IE */
      scriptTag.onreadystatechange = function () {
        if (this.readyState === 'complete' || this.readyState === 'loaded') {
          callback();
        }
      };
    } else {
      scriptTag.onload = callback;
    }
  }
  (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(scriptTag);
}

function opendesktopFilterReviews(filterBtn){
    //init
    let reContainer = $('#opendesktopwidget-reviews');
    reContainer.find('.opendesktopwidget-reviews-rows').show();

    let inactive =  reContainer.find('.opendesktopwidget-reviews-rows-inactive');
    let active = reContainer.find('.opendesktopwidget-reviews-rows-active');
    let up =  reContainer.find('.opendesktopwidget-reviews-rows-clsUpvotes');
    let down = reContainer.find('.opendesktopwidget-reviews-rows-clsDownvotes');

    if($(filterBtn).attr('id')=='opendesktopwidget-reviews-filters-all'){
          inactive.show();
          active.show();
    } else  if($(filterBtn).attr('id')=='opendesktopwidget-reviews-filters-active'){
          inactive.hide();
          active.show();
    } else  if($(filterBtn).attr('id')=='opendesktopwidget-reviews-filters-likes'){
          up.show();
          down.hide();
          inactive.hide();
    } else if($(filterBtn).attr('id')=='opendesktopwidget-reviews-filters-hates'){
          up.hide();
          down.show();
          inactive.hide();
    }
    $('html, body').animate({
           scrollTop: reContainer.offset().top-150
       }, 1);
}

function opendesktoptoggleDetail(thisrow){
                let listcontainer = $('#opendesktopwidget-main');
                let detailcontainer = $('#opendesktopwidget-main-detail-container');

                let detailpopup = '
'
                                            +'

'
                                            +'×'
                                            +'
'
                                            +'
'
                                            +'

'
                                            +'

';

                let modal = $('#opendesktopwidget-main-detail-modal');
                if(detailcontainer.length==0){
                      listcontainer.parent().append($(detailpopup));
                      detailcontainer = $('#opendesktopwidget-main-detail-container');
                      modal.show();
                }else{
                     modal.show();
                      detailcontainer.html('');
                }

                $('a[data-opendesktop-dismiss]').on('click',function(){
                      $('#opendesktopwidget-main-detail-modal').hide();
                });

                let projectid = $(thisrow).attr('data-project-id').trim();
                let container  = $('

');
                container.append(indicator);
                detailcontainer.append(container);
                let jsonp_url_projectdetail = opendesktopwigeturl+"embed/v1/project/"+projectid+"?&callback=?";
                $.getJSON(jsonp_url_projectdetail, function(data) {
                    container.html(data.html);

                    // images carousel
                    let imgs = $('#opendesktopwidget-main-detail-carousel').find('img');
                    if(imgs.length>1){

                            $('#opendesktopwidget-main-detail-carousel').slick({
                                    dots: true
                                });
                    }

                    // tabs onclick
                    let lis = container.find('#opendesktopwidget-content-tabs').find('li');
                    lis.each(function(index) {
                        $(this).on("click", function(){
                            $(this).addClass('active').siblings().removeClass('active');
                            let tabcontainerid = $(this).find('a').attr('data-wiget-target');
                            $(tabcontainerid).addClass('active').siblings().removeClass('active') ;

                        });
                    });

                    // project comments paging
                    let spans = container.find('.opendesktopwidgetcomments').find('ul.opendesktopwidgetpager').find('span');
                    spans.each(function(index) {
                        $(this).on("click", function(){
                            $(this).parent().addClass('active').siblings().removeClass('active');

                           $(indicator).insertBefore(container.find('.opendesktopwidgetcomments').find('ul.opendesktopwidgetpager'));
                            let jsonp_url_nopage = opendesktopwigeturl+"embed/v1/comments/"+projectid+"?nopage=1&page="+$(this).html()+"&callback=?";
                            $.getJSON(jsonp_url_nopage, function(data) {
                                container.find('i.fa-spinner').remove();
                                let ct = container.find('#opendesktopwidget-main-container-comments');
                                ct.html(data.html);

                            });

                        });
                    });

                    // reviews filter
                    let reviewsfilters = container.find('#opendesktopwidget-reviews').find('.opendesktop-widget-reviews-filters-btn');
                    reviewsfilters.each(function(index){
                          $(this).on("click", function(){
                                $(this).addClass('opendesktopwidget-reviews-activeRating').siblings().removeClass('opendesktopwidget-reviews-activeRating');
                                opendesktopFilterReviews(this);
                          });
                    });

                });
        }

function main() {

        /******* Load CSS *******/

        let opendesktopwidgetcss_link = $("<link>", { rel: "stylesheet", type: "text/css", href: opendesktopwigeturl+"widget/style.css" });
        let fontawsomecss_link =$("<link>", { rel: "stylesheet", type: "text/css", href:"http://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" });
        let slick_link =$("<link>", { rel: "stylesheet", type: "text/css", href:"https://cdn.jsdelivr.net/jquery.slick/1.6.0/slick.css" });
        let slick_theme_link =$("<link>", { rel: "stylesheet", type: "text/css", href:"https://cdn.jsdelivr.net/jquery.slick/1.6.0/slick-theme.css" });

        opendesktopwidgetcss_link.appendTo('head');
        fontawsomecss_link.appendTo('head');
        slick_link.appendTo('head');
        slick_theme_link.appendTo('head');

        /******* Load HTML *******/
      let this_js_script = $('#opendesktopwiget');
      let memberid = this_js_script.attr('data-memberid');
      let countperpage = this_js_script.attr('data-countperpage');
      let catids = this_js_script.attr('data-catids');
      let query = '';
      if(countperpage){
           query = 'pagelimit='+countperpage+'&';
      }
      if(catids){
           query =query+'catids='+catids+'&';
      }

       if (typeof memberid === "undefined" ) {
          alert('Please set data-memberid in your script.');
          return;
       }

       $('#opendesktopwiget').after('
'+indicator+'
');
       let jsonp_url = opendesktopwigeturl+"embed/v1/member/"+memberid+"?"+query+"callback=?";
        $.getJSON(jsonp_url, function(data) {
              $('#opendesktop-widget-container').html(data.html);
              let spans = $('.opendesktopwidgetpager').find('span');
              spans.each(function(index) {
                  $(this).on("click", function(){
                      $(this).parent().addClass('active').siblings().removeClass('active');
                      $(indicator).insertBefore($('#opendesktop-widget-container').find('ul.opendesktopwidgetpager'));
                      let jsonp_url_nopage = opendesktopwigeturl+"embed/v1/member/"+memberid+"?"+query+"nopage=1&page="+$(this).html()+"&callback=?";
                      $.getJSON(jsonp_url_nopage, function(data) {
                          $('#opendesktop-widget-container').find('i.fa-spinner').remove();
                          $('#opendesktopwidget-main-container').html(data.html);
                          let rows =$('#opendesktop-widget-container').find('.opendesktopwidgetrow');
                               rows.each(function(index) {
                                   $(this).on("click", function(){
                                        opendesktoptoggleDetail(this);
                                   });
                               });
                      });

                  });
              });

              let rows =$('#opendesktop-widget-container').find('.opendesktopwidgetrow');
              rows.each(function(index) {
                  $(this).on("click", function(){
                        opendesktoptoggleDetail(this);
                  });
              });

        });
}

/* Load jQuery */
loadScript("https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js", function() {

      loadScript("https://cdnjs.cloudflare.com/ajax/libs/jquery-migrate/3.0.0/jquery-migrate.min.js", function() {

                /* Restore $ and window.jQuery to their previous values and store the
                   new jQuery in our local jQuery variables. */
                  //$ = jQuery = window.jQuery.noConflict(false);
                  $ = jQuery = window.jQuery.noConflict();

                //$.noConflict();
                //$.noConflict();
                /* Load jQuery plugin and execute the main logic of our widget once the
                   plugin is loaded is loaded */

                loadScript("https://cdn.jsdelivr.net/jquery.slick/1.6.0/slick.min.js", function() {

                  main();
                });

      });
});

}(window, document)); /* end IIFE */<|endoftext|>


<commit_before>define(function(require, exports, module) {
  exports.controller = (function() {
    var modules = {
      versioning: require('versioning').versioning,
      session: require('session').session,
      sync: require('sync').sync,
      ajax: require('ajax').ajax,
      webfinger: require('webfinger').webfinger,
      oauth: require('oauth').oauth,
      couch: require('couch').couch,
      button: require('button').button
    };
    var deadLine;
    var working=false;
    var intervalTimer;
    var options = {
      onChange: function(key, oldValue, newValue) {
        console.log('item "'+key+'" changed from "'+oldValue+'" to "'+newValue+'"');
        console.log('WARNING: Please configure an onChange function! Forcing full page refresh instead');
        window.location = '';
      },
      category: location.host.replace('.', '_')
    };
    function onError(str) {
      alert(str);
    }
    function connect(userAddress) {
      document.getElementById('remoteStorageSpinner').style.display='inline';
      if(true) {
      //if(false) {
        connectTo(userAddress);
      } else {
        navigator.id.getVerifiedEmail(function(assertion) {
          console.log(assertion);
          modules.ajax({
            //url: 'https://browserid.org/verify',
            //url: 'http://unhosted.org/browserid-verifier',
            //url: 'http://unhosted.nodejitsu.com/browserid-verifier',
            url: 'http://myfavouritesandwich.org/browserid-verifier',
            method: 'POST',
            data: 'assertion='+assertion+'&audience='+window.location,
            success: function(data) {
              console.log(data);
              connectTo(JSON.parse(data).email);
            },
            error: function(status) {
              console.log('error status '+status);
              document.getElementById('remoteStorageSpinner').style.display='none';
            }
          });
        });
      }
    }
    function connectTo(userAddress) {
      modules.webfinger.getAttributes(userAddress, {
        allowHttpWebfinger: true,
        allowSingleOriginWebfinger: false,
        allowFakefinger: true
      }, onError, function(attributes) {
        var backendAddress = modules.webfinger.resolveTemplate(attributes.template, options.category);
        if(attributes.api == 'CouchDB') {
          localStorage.setItem('_shadowBackendModuleName', 'couch');
        } else {
          console.log('API "'+attributes.api+'" not supported! please try setting api="CouchDB" in webfinger');
        }
        modules.session.set('backendAddress', backendAddress);
        modules.oauth.go(attributes.auth, options.category, userAddress);
      });
    }
    function disconnect() {
      modules.session.disconnect();
      var isConnected = modules.session.isConnected();
      var userAddress = modules.session.get('userAddress');
      modules.button.show(isConnected, userAddress);
    }
    function configure(setOptions) {
      console.log(setOptions);
      if(setOptions) {
        for(var i in setOptions) {
          options[i] = setOptions[i];
        }
      }
    }
    function needLoginBox() {
      if(options.suppressDialog) {
        return false;
      } else {
        return true;
      }
    }
    function linkButtonToSession() {
      var isConnected = modules.session.isConnected();
      var userAddress = modules.session.get('userAddress');
      if(needLoginBox()) {
        modules.button.on('connect', connect);
        modules.button.on('disconnect', disconnect);
        modules.button.show(isConnected, userAddress);
      }
    }
    function onLoad(setOptions) {
      configure(setOptions);
      if(needLoginBox()) {
        linkButtonToSession();
      }
      modules.oauth.harvestToken(function(token) {
        require('session').session.set('token', token);
        modules[localStorage.getItem('_shadowBackendModuleName')].init(
          modules.session.get('backendAddress'),
          token);
        modules.sync.start();
      });
      modules.sync.setBackend(modules[localStorage.getItem('_shadowBackendModuleName')]);
      var autoSaveMilliseconds = 5000;//FIXME: move this to some sort of config
      setInterval(function() {
        require(['controller'], function(controller) {
          controller.controller.trigger('timer');
        })
      }, autoSaveMilliseconds);
      document.getElementById('remoteStorageSpinner').style.display='none';
    }
    function trigger(event) {
      document.getElementById('remoteStorageSpinner').style.display='inline';
      console.log(event);
      if(!working) {
        var newTimestamp = modules.versioning.takeLocalSnapshot()
        if(newTimestamp) {
          console.log('changes detected');
          if(modules.session.isConnected()) {
            console.log('pushing');
            modules.sync.push(newTimestamp);
          } else {
            console.log('not connected');
          }
        }
        if(modules.session.isConnected()) {
          working = true;
          modules.sync.work(deadLine, function(incomingKey, incomingValue) {
            console.log('incoming value "'+incomingValue+'" for key "'+incomingKey+'".');
            var oldValue = localStorage.getItem(incomingKey);
            modules.versioning.incomingChange(incomingKey, incomingValue);
            options.onChange(incomingKey, oldValue, incomingValue);
          }, function() {
            working = false;
          });
        } else {
          document.getElementById('remoteStorageSpinner').style.display='none';
        }
      } else {
        console.log('still working?');
      }
    }
    return {
      configure: configure,
      onLoad: onLoad,
      trigger: trigger
    };
  })();
});
<commit_msg>start sync-sleep loop with a sync instead of with a sleep<commit_after>define(function(require, exports, module) {
  exports.controller = (function() {
    var modules = {
      versioning: require('versioning').versioning,
      session: require('session').session,
      sync: require('sync').sync,
      ajax: require('ajax').ajax,
      webfinger: require('webfinger').webfinger,
      oauth: require('oauth').oauth,
      couch: require('couch').couch,
      button: require('button').button
    };
    var deadLine;
    var working=false;
    var intervalTimer;
    var options = {
      onChange: function(key, oldValue, newValue) {
        console.log('item "'+key+'" changed from "'+oldValue+'" to "'+newValue+'"');
        console.log('WARNING: Please configure an onChange function! Forcing full page refresh instead');
        window.location = '';
      },
      category: location.host.replace('.', '_')
    };
    function onError(str) {
      alert(str);
    }
    function connect(userAddress) {
      document.getElementById('remoteStorageSpinner').style.display='inline';
      if(true) {
      //if(false) {
        connectTo(userAddress);
      } else {
        navigator.id.getVerifiedEmail(function(assertion) {
          console.log(assertion);
          modules.ajax({
            //url: 'https://browserid.org/verify',
            //url: 'http://unhosted.org/browserid-verifier',
            //url: 'http://unhosted.nodejitsu.com/browserid-verifier',
            url: 'http://myfavouritesandwich.org/browserid-verifier',
            method: 'POST',
            data: 'assertion='+assertion+'&audience='+window.location,
            success: function(data) {
              console.log(data);
              connectTo(JSON.parse(data).email);
            },
            error: function(status) {
              console.log('error status '+status);
              document.getElementById('remoteStorageSpinner').style.display='none';
            }
          });
        });
      }
    }
    function connectTo(userAddress) {
      modules.webfinger.getAttributes(userAddress, {
        allowHttpWebfinger: true,
        allowSingleOriginWebfinger: false,
        allowFakefinger: true
      }, onError, function(attributes) {
        var backendAddress = modules.webfinger.resolveTemplate(attributes.template, options.category);
        if(attributes.api == 'CouchDB') {
          localStorage.setItem('_shadowBackendModuleName', 'couch');
        } else {
          console.log('API "'+attributes.api+'" not supported! please try setting api="CouchDB" in webfinger');
        }
        modules.session.set('backendAddress', backendAddress);
        modules.oauth.go(attributes.auth, options.category, userAddress);
      });
    }
    function disconnect() {
      modules.session.disconnect();
      var isConnected = modules.session.isConnected();
      var userAddress = modules.session.get('userAddress');
      modules.button.show(isConnected, userAddress);
    }
    function configure(setOptions) {
      console.log(setOptions);
      if(setOptions) {
        for(var i in setOptions) {
          options[i] = setOptions[i];
        }
      }
    }
    function needLoginBox() {
      if(options.suppressDialog) {
        return false;
      } else {
        return true;
      }
    }
    function linkButtonToSession() {
      var isConnected = modules.session.isConnected();
      var userAddress = modules.session.get('userAddress');
      if(needLoginBox()) {
        modules.button.on('connect', connect);
        modules.button.on('disconnect', disconnect);
        modules.button.show(isConnected, userAddress);
      }
    }
    function onLoad(setOptions) {
      configure(setOptions);
      if(needLoginBox()) {
        linkButtonToSession();
      }
      modules.oauth.harvestToken(function(token) {
        require('session').session.set('token', token);
        modules[localStorage.getItem('_shadowBackendModuleName')].init(
          modules.session.get('backendAddress'),
          token);
        modules.sync.start();
      });
      modules.sync.setBackend(modules[localStorage.getItem('_shadowBackendModuleName')]);
      var autoSaveMilliseconds = 5000;//FIXME: move this to some sort of config
      trigger('timer');
      setInterval(function() {
        require(['controller'], function(controller) {
          controller.controller.trigger('timer');
        })
      }, autoSaveMilliseconds);
      document.getElementById('remoteStorageSpinner').style.display='none';
    }
    function trigger(event) {
      document.getElementById('remoteStorageSpinner').style.display='inline';
      console.log(event);
      if(!working) {
        var newTimestamp = modules.versioning.takeLocalSnapshot()
        if(newTimestamp) {
          console.log('changes detected');
          if(modules.session.isConnected()) {
            console.log('pushing');
            modules.sync.push(newTimestamp);
          } else {
            console.log('not connected');
          }
        }
        if(modules.session.isConnected()) {
          working = true;
          modules.sync.work(deadLine, function(incomingKey, incomingValue) {
            console.log('incoming value "'+incomingValue+'" for key "'+incomingKey+'".');
            var oldValue = localStorage.getItem(incomingKey);
            modules.versioning.incomingChange(incomingKey, incomingValue);
            options.onChange(incomingKey, oldValue, incomingValue);
          }, function() {
            working = false;
          });
        } else {
          document.getElementById('remoteStorageSpinner').style.display='none';
        }
      } else {
        console.log('still working?');
      }
    }
    return {
      configure: configure,
      onLoad: onLoad,
      trigger: trigger
    };
  })();
});
<|endoftext|>


<commit_before>var http = require("http");
var fs  = require("fs");
var path = require("path");

http.createServer(function(req, res){
    console.log(`${req.method} request for ${req.url}`);

    if (req.url === "/"){
        fs.readFile("./public/index.html", "UTF-8", function(err, html){
        res.writeHead(200 ,{"Content-Type":"text/html"} );
        res.end(html);

        });
     } else if (req.url.match(/.css$/)){

        var cssPath = path.join(__dirname , 'public' , req.url);
        var fileStream = fs.createReadStream(cssPath , "UTF-8");

        res.writeHead(200 , {"Content-Type":"text/css"});

        fileStream.pipe(res);

}).listen(4000); <commit_msg>Map request urls to serve image extensions ( png | jpeg)<commit_after>var http = require("http");
var fs  = require("fs");
var path = require("path");

http.createServer(function(req, res){
    console.log(`${req.method} request for ${req.url}`);

    if (req.url === "/"){
        fs.readFile("./public/index.html", "UTF-8", function(err, html){
        res.writeHead(200 ,{"Content-Type":"text/html"} );
        res.end(html);

        });
     } else if (req.url.match(/.css$/)){

        var cssPath = path.join(__dirname , 'public' , req.url);
        var fileStream = fs.createReadStream(cssPath , "UTF-8");

        res.writeHead(200 , {"Content-Type":"text/css"});

        fileStream.pipe(res);
     } else if (req.url.match(/.jpg/ || /.png/  )) {

        var imgPath = path.join(__dirname , "public", req.url);
        var imgStream =  fs.createReadStream(imgPath);

        res.writeHead(200, {"Content-Type":"image/jpeg"} || {"Content-Type":"image/png"})
        imgStream.pipe(res);

}).listen(4000); <|endoftext|>


<commit_before>/**
 *  Poppy Pagination
 *  Generate page options/results using pre-existing content
 *
 *  Copyright 2012-2015, Marc S. Brooks (http://mbrooks.info)
 *  Licensed under the MIT license:
 *  http://www.opensource.org/licenses/mit-license.php
 *
 *  Dependencies:
 *    jquery.js
 */

if (!window.jQuery || (window.jQuery && window.jQuery.fn.jquery < '1.8.3')) {
  throw new Error('Poppy-Pagination requires jQuery 1.8.3 or greater.');
}

(function($) {

  /**
   * @namespace PoppyPagination
   */
  var methods = {

    /**
     * Create new instance of Poppy-Pagination
     *
     * @memberof PoppyPagination
     * @method init
     *
     * @param {Object} config
     * @param {Function} callback
     *
     * @returns {Object} jQuery object
     */
    "init": function(config, callback) {
      var $this = $(this);

      // config defaults
      config = $.extend(true, {
        totalResults: 0,
        perPage:      10,
        startPage:    1,
        uiText: {
          LAST_PAGE: 'Last Page',
          NEXT_PAGE: 'Next Page',
          RESULTS:   '%first - %last of %total results',
          VIEWING:   'Viewing'
        }
      }, config);

      $this.data('config', config);

      return $this.PoppyPagination('_createPageResults', callback);
    },

    /**
     * Perform cleanup
     *
     * @memberof PoppyPagination
     * @method destroy
     */
    "destroy": function() {
      $(this).removeData();
    },

    /**
     * Perform cleanup
     *
     * @memberof PoppyPagination
     * @method _createPageResults
     * @private
     *
     * @param {Function} callback
     *
     * @returns {Object}
     */
    "_createPageResults": function(callback) {
      var $this = $(this);

      // If results are available, create page elements.
      var results = $this.PoppyPagination('_calcPageResults');
      if (results.total > 0) {
        var pager = $this.find('div.poppy_pagination');

        // Remove existing elements..
        if (pager[0]) {
          pager.remove();
        }

        // .. header
        var header = $('

')
          .addClass('poppy_pagination');

        var elm1 = $this.PoppyPagination('_createResultElm', results, callback),
            elm2 = $this.PoppyPagination('_createPagerElm',  results, callback);
        header.append(elm2, elm1);
        $this.prepend(header);

        // .. footer
        var footer = header.clone(true);
        footer.append(footer.children().get().reverse());
        $this.append(footer);
      }

      return $this;
    },

    /**
     * Create page result elements.
     *
     * @memberof PoppyPagination
     * @method _createResultElm
     * @private
     *
     * @param {Object} results
     * @param {Function} callback
     *
     * @returns {Object}
     */
    "_createResultElm": function(results, callback) {
      var $this = $(this),
          data  = $this.data(),
          lang  = data.config.uiText;

      // Create result total elements..
      var span = $('')
        .append(replaceTokens(lang.RESULTS, results));

      var form = $('<form></form>');

      if (results.total > 10 && results.limit > 1) {

        // .. select menu
        var label = $('')
          .append(replaceTokens(lang.VIEWING, results));

        form.append(label);

        var option = $('<option>-</option>'),
          select = $('<select></select>')
          .append(option);

        var opts = [ 10, 20, 30, 40, 50 ];

        // .. options
        $.each(opts, function() {
          if (this <= results.total) {
            option = $('<option>' + this + '</option>')
              .attr('value', this);
            select.append(option);

            // If the option is selected..
            if (this == results.limit) {
              select.selectedIndex = this;
            }
          }
        });

        // Attach menu options events.
        if ( $.isFunction(callback) ) {
          select.on('change', function() {
            results.limit = parseInt(this.value);
            callback(results);
          });
        }

        form.append(select);
      }

      // Return HTML object.
      return $('

')
        .addClass('options')
        .append(span, form);
    },

    /**
     * Create the first/last and subsequent page links.
     *
     * @memberof PoppyPagination
     * @method _createPagerElm
     * @private
     *
     * @param {Object} results
     * @param {Function} callback
     *
     * @returns {Object}
     */
    "_createPagerElm": function(results, callback) {
      var $this = $(this),
          data  = $this.data(),
          lang  = data.config.uiText;

      // Create node elements.
      var list = $('

')
        .addClass('pages');

      var crumbs = $('

')
        .addClass('crumbs');

      // Define onclick event
      function onClickEvent(event) {
        event.preventDefault();
        results.start = event.data;

        if ( $.isFunction(callback) ) {
          callback(results);
        }
      }

      // Always show 10 results, if available..
      (function() {
        var show_links = 10,
            first_link = (results.first / results.limit) - (show_links / 2),
            last_link  = (results.last  / results.limit) + (show_links / 2);

        for (var i = 1; i <= results.pages; i++) {
          if (first_link > i) continue;
          if (last_link  < i) continue;

          var link = null;

          // .. page links
          if (results.start != i) {

            // Bind mouse event
            link = $('' + i + '')
              .on('click', i, onClickEvent);
          }
          else {

            // disable crumb
            link = $('' + i + '');
          }

          crumbs.append(link);
        }
      })();

      // .. last page link
      (function() {
        if (results.total > 0) {
          var item = $('

')
            .addClass('last');

          var link = null;

          if (results.start > 1) {

            // Bind mouse event
            link = $('')
              .on('click', (results.start - 1), onClickEvent);
          }
          else {

            // Disable button
            link = $('');
          }

          link.append(replaceTokens(lang.LAST_PAGE, results));
          item.append(link);
          list.append(item);
        }
      })();

      // .. page crumbs (links)
      if (crumbs.children()) {
        list.append(crumbs);
      }

      // .. next page link
      (function() {
        if (results.total > 1) {
          var item = $('

')
            .addClass('next');

          var link = null;

          if (results.pages != results.start) {

            // Bind mouse event
            link = $('')
              .on('click', (results.start + 1), onClickEvent);
          }
          else {

            // Disable button
            link = $('');
          }

          link.append(replaceTokens(lang.NEXT_PAGE, results));
          item.append(link);
          list.append(item);
        }
      })();

      if (results.pages == 1) {
        list.addClass('disabled');
      }

      return list;
    },

    /**
     * Calculate page totals and return object of results.
     *
     * @memberof PoppyPagination
     * @method _calcPageResults
     * @private
     *
     * @returns {Object}
     */
    "_calcPageResults": function() {
      var $this = $(this),
          data  = $this.data();

      var obj = {};
      obj.total = data.config.totalResults;
      obj.limit = data.config.perPage;
      obj.start = data.config.startPage || 1;
      obj.pages = getTotalRows(obj.total, obj.limit);
      obj.first = obj.start * obj.limit + 1 - obj.limit;
      obj.last  = ((obj.first + obj.limit - 1) < obj.total) ? (obj.first + obj.limit - 1) : obj.total;
      return obj;
    }
  };

  $.fn.PoppyPagination = function(method) {
    if (methods[method]) {
      return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
    }
    else
    if (typeof method === 'object' || !method) {
      return methods.init.apply(this, arguments);
    }
    else {
      $.error('Method ' +  method + ' does not exist in jQuery.PoppyPagination');
    }
  };

  /**
  * Return the row tota;.
  *
  * @protected
  *
  * @param {String} total
  * @param {Number} limit
  *
  * @returns {Number}
  */
  function getTotalRows(total, limit) {
    var count = Math.round(total / limit);
    if ((count * limit) < total) {
      count++;
    }
    return count;
  }

  /**
  * Replace language string tokens with its object defined value.
  *
  * @protected
  *
  * @param {String} text
  * @param {Object} vals
  *
  * @returns {String}
  */
  function replaceTokens(text, vals) {
    for (var key in vals) {
      if (vals[key]) {
        var token = key,
          regex = new RegExp('%' + token, 'i');

        text = text.replace(regex, vals[key]);
      }
    }
    return text;
  }
})(jQuery);
<commit_msg>Added example code for all public methods<commit_after>/**
 *  Poppy Pagination
 *  Generate page options/results using pre-existing content.
 *
 *  Copyright 2012-2015, Marc S. Brooks (http://mbrooks.info)
 *  Licensed under the MIT license:
 *  http://www.opensource.org/licenses/mit-license.php
 *
 *  Dependencies:
 *    jquery.js
 */

if (!window.jQuery || (window.jQuery && parseInt(window.jQuery.fn.jquery.replace('.', '')) < parseInt('1.8.3'.replace('.', '')))) {
  throw new Error('Poppy-Pagination requires jQuery 1.8.3 or greater.');
}

(function($) {

  /**
   * @namespace PoppyPagination
   */
  var methods = {

    /**
     * Create new instance of Poppy-Pagination
     *
     * @memberof PoppyPagination
     * @method init
     *
     * @example
     * $('#container').PoppyPagination(config, callback);
     *
     * @param {Object} config
     * @param {Function} callback
     *
     * @returns {Object} jQuery object
     */
    "init": function(config, callback) {
      var $this = $(this);

      // Config defaults
      config = $.extend(true, {
        totalResults: 0,
        perPage:      10,
        startPage:    1,
        uiText: {
          LAST_PAGE: 'Last Page',
          NEXT_PAGE: 'Next Page',
          RESULTS:   '%first - %last of %total results',
          VIEWING:   'Viewing'
        }
      }, config);

      $this.data('config', config);

      return $this.PoppyPagination('_createPageResults', callback);
    },

    /**
     * Perform cleanup
     *
     * @memberof PoppyPagination
     * @method destroy
     *
     * @example
     * $('#container').PoppyPagination('destroy');
     */
    "destroy": function() {
      $(this).removeData();
    },

    /**
     * Perform cleanup
     *
     * @memberof PoppyPagination
     * @method _createPageResults
     * @private
     *
     * @param {Function} callback
     *
     * @returns {Object}
     */
    "_createPageResults": function(callback) {
      var $this = $(this);

      // If results are available, create page elements.
      var results = $this.PoppyPagination('_calcPageResults');
      if (results.total > 0) {
        var pager = $this.find('div.poppy_pagination');

        // Remove existing elements..
        if (pager[0]) {
          pager.remove();
        }

        // .. Header
        var header = $('

')
          .addClass('poppy_pagination');

        var elm1 = $this.PoppyPagination('_createResultElm', results, callback),
            elm2 = $this.PoppyPagination('_createPagerElm',  results, callback);
        header.append(elm2, elm1);
        $this.prepend(header);

        // .. Footer
        var footer = header.clone(true);
        footer.append(footer.children().get().reverse());
        $this.append(footer);
      }

      return $this;
    },

    /**
     * Create page result elements.
     *
     * @memberof PoppyPagination
     * @method _createResultElm
     * @private
     *
     * @param {Object} results
     * @param {Function} callback
     *
     * @returns {Object}
     */
    "_createResultElm": function(results, callback) {
      var $this = $(this),
          data  = $this.data(),
          lang  = data.config.uiText;

      // Create result total elements..
      var span = $('')
        .append(replaceTokens(lang.RESULTS, results));

      var form = $('<form></form>');

      if (results.total > 10 && results.limit > 1) {

        // .. Select menu
        var label = $('')
          .append(replaceTokens(lang.VIEWING, results));

        form.append(label);

        var option = $('<option>-</option>'),
          select = $('<select></select>')
          .append(option);

        var opts = [ 10, 20, 30, 40, 50 ];

        // .. Options
        $.each(opts, function() {
          if (this <= results.total) {
            option = $('<option>' + this + '</option>')
              .attr('value', this);
            select.append(option);

            // If the option is selected..
            if (this == results.limit) {
              select.selectedIndex = this;
            }
          }
        });

        // Attach menu options events.
        if ( $.isFunction(callback) ) {
          select.on('change', function() {
            results.limit = parseInt(this.value);
            callback(results);
          });
        }

        form.append(select);
      }

      // Return HTML object.
      return $('

')
        .addClass('options')
        .append(span, form);
    },

    /**
     * Create the first/last and subsequent page links.
     *
     * @memberof PoppyPagination
     * @method _createPagerElm
     * @private
     *
     * @param {Object} results
     * @param {Function} callback
     *
     * @returns {Object}
     */
    "_createPagerElm": function(results, callback) {
      var $this = $(this),
          data  = $this.data(),
          lang  = data.config.uiText;

      // Create node elements.
      var list = $('

')
        .addClass('pages');

      var crumbs = $('

')
        .addClass('crumbs');

      // Define onclick event
      function onClickEvent(event) {
        event.preventDefault();
        results.start = event.data;

        if ( $.isFunction(callback) ) {
          callback(results);
        }
      }

      // Always show 10 results, if available..
      (function() {
        var show_links = 10,
            first_link = (results.first / results.limit) - (show_links / 2),
            last_link  = (results.last  / results.limit) + (show_links / 2);

        for (var i = 1; i <= results.pages; i++) {
          if (first_link > i) continue;
          if (last_link  < i) continue;

          var link = null;

          // .. Page links
          if (results.start != i) {

            // Bind mouse event
            link = $('' + i + '')
              .on('click', i, onClickEvent);
          }
          else {

            // Disable crumb
            link = $('' + i + '');
          }

          crumbs.append(link);
        }
      })();

      // .. Last page link
      (function() {
        if (results.total > 0) {
          var item = $('

')
            .addClass('last');

          var link = null;

          if (results.start > 1) {

            // Bind mouse event
            link = $('')
              .on('click', (results.start - 1), onClickEvent);
          }
          else {

            // Disable button
            link = $('');
          }

          link.append(replaceTokens(lang.LAST_PAGE, results));
          item.append(link);
          list.append(item);
        }
      })();

      // .. Page crumbs (links)
      if (crumbs.children()) {
        list.append(crumbs);
      }

      // .. Next page link
      (function() {
        if (results.total > 1) {
          var item = $('

')
            .addClass('next');

          var link = null;

          if (results.pages != results.start) {

            // Bind mouse event
            link = $('')
              .on('click', (results.start + 1), onClickEvent);
          }
          else {

            // Disable button
            link = $('');
          }

          link.append(replaceTokens(lang.NEXT_PAGE, results));
          item.append(link);
          list.append(item);
        }
      })();

      if (results.pages == 1) {
        list.addClass('disabled');
      }

      return list;
    },

    /**
     * Calculate page totals and return object of results.
     *
     * @memberof PoppyPagination
     * @method _calcPageResults
     * @private
     *
     * @returns {Object}
     */
    "_calcPageResults": function() {
      var $this = $(this),
          data  = $this.data();

      var obj = {};
      obj.total = data.config.totalResults;
      obj.limit = data.config.perPage;
      obj.start = data.config.startPage || 1;
      obj.pages = getTotalRows(obj.total, obj.limit);
      obj.first = obj.start * obj.limit + 1 - obj.limit;
      obj.last  = ((obj.first + obj.limit - 1) < obj.total) ? (obj.first + obj.limit - 1) : obj.total;
      return obj;
    }
  };

  $.fn.PoppyPagination = function(method) {
    if (methods[method]) {
      return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
    }
    else
    if (typeof method === 'object' || !method) {
      return methods.init.apply(this, arguments);
    }
    else {
      $.error('Method ' +  method + ' does not exist in jQuery.PoppyPagination');
    }
  };

  /**
   * Return the row tota;.
   *
   * @protected
   *
   * @param {String} total
   * @param {Number} limit
   *
   * @returns {Number}
   */
  function getTotalRows(total, limit) {
    var count = Math.round(total / limit);
    if ((count * limit) < total) {
      count++;
    }
    return count;
  }

  /**
   * Replace language string tokens with its object defined value.
   *
   * @protected
   *
   * @param {String} text
   * @param {Object} vals
   *
   * @returns {String}
   */
  function replaceTokens(text, vals) {
    for (var key in vals) {
      if (vals[key]) {
        var token = key,
          regex = new RegExp('%' + token, 'i');

        text = text.replace(regex, vals[key]);
      }
    }
    return text;
  }
})(jQuery);
<|endoftext|>


<commit_before>var preferencesservice=require("preferences-service");
var Request=require("request").Request;
var selection=require("selection");
var self=require("self");
var simpleprefs=require("simple-prefs");
var tabs=require("tabs");
// tabs.open("http://www.languagetool.org/forum/");
var widgets=require("widget");
var _=require("l10n").get;

var EMPTYTEXTWARNING="
"+_("emptyText")+"
";
var PLEASEWAITWHILECHECKING="
"+_("pleaseWaitWhileChecking")+"
";
var MAXCONTEXTLENGTH=20;
var MAXLENGTHWEBSERVICE=50000;

var selectedText="";
var selectedTextProcessed="";

function selectionChanged(event) {
	selectedText=selection.text;
}

selection.on("select", selectionChanged);

/**
 * escape &, <, >, and " in xml
 */
function escapeXml(string) {
	// prevent double escaping of html entities
	string=string.replace(/"/g,"\"").replace(/</g,"<").replace(/>/g,">");
	return string.replace(/&/g,"&").replace(/\</g,"<").replace(/\>/g,">").replace(/\"/g,""");
}

/**
 * removes contents of