/*
 * $Id:$
 *
 * This is a javascript file used in the process of sharing stuff.
 */

//
// Validate a notification form, which is used to share
// both braggits and companies.
//
function validateNotify(form) {
    var completeRows = 0;
    var incompleteRows = 0;
    var invalidEmails = 0;
    for(var i = 0; i < 5; i++) {
        var fname = $F(form["fnames[" + i + "]"]);
        var lname = $F(form["lnames[" + i + "]"]);
        var email = $F(form["emails[" + i + "]"]);
        if(fname && lname && email) {
            completeRows++;
        } else if(fname || lname || email) {
            incompleteRows++;
        }
        if(email && !email.match(/^[^@]+@[^.]+[.].*$/)) {
            invalidEmails++;
        }
    }
    if(completeRows == 0) {
        $('notifyFormError').innerHTML = "You must fill in at least one complete row";
        return false;
    } else if(incompleteRows > 0) {
        $('notifyFormError').innerHTML = "Sorry, there are incomplete rows found";
        return false;
    } else if(invalidEmails > 0) {
        $('notifyFormError').innerHTML = "An invalid e-mail was found. Please double check and send again.";
        return false;
    } else {
        return true;
    }
}

//
// Select all items in our sharing box
//
function toggleAllContacts(link) {
    if(link.innerHTML.match(/^Select/)) {
        $$('#sharing-box li input').each(function(i) {
                                             i.checked = true;
                                         });
        link.innerHTML = 'Unselect All Contactz';
    } else {
        $$('#sharing-box li input').each(function(i) {
                                             i.checked = false;
                                         });
        link.innerHTML = 'Select All Contactz';
    }
    return false;
}


function addContactBox(event) {
    var inputs = {};
    function row(label, key) {
        var input = $E('input', {name: key});
        inputs[key] = input;
        return $E('div', {className: 'row'},
                  $E('label', {}, $E('span', {className: 'required'}, "*"), label + ":"),
                  input);
    }
    function buttons() {
        var row = $E('div', {className: 'row', id: 'button-row'});
        $A(arguments).each(function(entry){
                               row.appendChild($E('input', {className: 'button', type: 'button',
                                                            id: entry[0].replace(/ /g,"_") + "_Button",
                                                            value: entry[0],
                                                            onclick: function() { entry[1](); }}));
                           });
        return row;
    }
    function checkHasValue(key, label) {
        if(inputs[key].value.trim() == '') {
            alert("You must provide a value for " + label);
            return false;
        } else {
            return true;
        }
    }
    function checkIsEmail(key, label) {
        if(!isEmailAddress(inputs[key].value)) {
            alert(label + " must be a valid e-mail address");
            return false;
        } else {
            return true;
        }
    }
    function addToUi(firstName, lastName, email, id) {
        if($('no-contacts-message')) {
            $('contact-list').removeChild($('no-contacts-message'));
        }
        $('contact-list').insertBefore($E('li', {},
                                          $E('input', {type: 'checkbox',
                                                       name: 'contact_ids[]',
                                                       id: 'cb' + id,
                                                       value: id,
                                                       checked: 'checked'}),
                                          $E('label', {htmlFor: 'cb' + id},
                                             $E('abbr', {title: 'E-mail: ' + email},
                                                lastName + ", " + firstName))),
                                       $('contact-list').firstChild);
    }
    var dialog = $E('div', {className: 'overlay'},
                    $E('h2', {}, "Add New Contact"),
                    $E('form', {},
                       row("First Name", "first_name"),
                       row("Last Name", "last_name"),
                       row("E-mail", "email"),
                       buttons(["Add Contact", function() {
                         if(checkHasValue('first_name', "First Name") &&
                            checkHasValue('last_name', "Last Name") &&
                            checkHasValue('email', "E-mail") &&
                            checkIsEmail('email', "E-mail")) {
                              $('button-row').appendChild($E('img', {src:  APP_URL + '/shared/images/loading/mozilla_blu.gif' }));
                              $('Add_Contact_Button').disabled = true;
                              new Ajax.Request(APP_URL + "/bizcontactz/add",  {
                                method: 'GET',
                                parameters: {
                                  first_name: inputs['first_name'].value.trim(),
                                  last_name: inputs['last_name'].value.trim(),
                                  email: inputs['email'].value.trim()
                                },
                                onSuccess: function(t) {
                                  $('body').removeChild(dialog);
                                  var data =   t.responseText.evalJSON();
                                  if(data.contact_id) {
                                    addToUi(inputs['first_name'].value.trim(),
                                            inputs['last_name'].value.trim(),
                                            inputs['email'].value.trim(),
                                            data.contact_id);
                                  } else {
                                    alert("Unable to add contact: " + inputs['email'].value + ' ' + data.cause.toLowerCase());
                                  }
                                },
                                onFailure: function(t) {
                                  alert(t.status + ": " + t.responseText);
                                }
                              });
                         }
                       }],
                               ["Cancel", function() { $('body').removeChild(dialog) }])));
    $('body').appendChild(dialog);
    var m = {x: Event.pointerX(event), y: Event.pointerY(event)};
    var d = {w: $(dialog).getWidth(), h: $(dialog).getHeight()};
    dialog.style.left = (m.x  - d.w < 0  ? m.x : m.x - d.w) + "px";
    dialog.style.top = (m.y - d.h < 0 ? m.y : m.y - d.h) + "px";
    return false;
}


function confirmOneNameSelected(form) {
    var nodes = $$('#sharing-box li input').findAll(function(input) {
                                                        return input.checked;
                                                    });

    if(nodes.length == 0) {
        alert("You must select at least one contact to send to");
        return false;
    } else {
        return confirm("Are you sure you want to send a message to " +
                       nodes.length + " contact" + (nodes.length == 1 ? "" : "s") + "?");
    }
}
