
function clearDefaultDestinationMessage()
{
    var content = $('smsdestination').value;
    if (content == '04xx xxx xxx nickname')
    {
        $('smsdestination').value = '';
    }
}

function clearDefaultMessage()
{
    var content = $('smscontent').value;
    var lineOneLength = 'Only 15c/SMS!'.length;
    var lineTwoLength = '5 FREE SMS each month with any Australia On Line dial up or ADSL account.'.length;
    if (content.length > lineOneLength + lineTwoLength
            && content.substring(0, lineOneLength) == 'Only 15c/SMS!'
            && content.substring(content.length - lineTwoLength) == '5 FREE SMS each month with any Australia On Line dial up or ADSL account.')
    {
        $('smscontent').value = '';
    }
}

function clearDefaultSchedulingSendAt()
{
    var content = $('send_at').value;
    if (content == 'd/m/y h:mm am')
    {
        $('send_at').value = '';
    }
}

function clearHistory()
{
    deleteCookie('sms-destination-history');
    deleteCookie('sms-username-history');
    deleteCookie('sms-dialog-recipient-hide');
}

function closeSMSDialog()
{
    setHideSMSDialogCookieIfRequired();

    Element.setStyle('sms', { opacity: '1.0' });
    Element.setStyle('sms', { filter: 'alpha(opacity=100)' });
    Element.setStyle('sms_dialog_recipient_name', { visibility: 'hidden' });

    $('smscontent').focus();

    return false;
}

function copyHistoryToSmsDestination()
{
    var destinationElements = new Array();
    var destination = $('smsdestinationhistory').value;
    destination = unescape(destination);
    $('smsdestination').value = destination;
}

function countAndRestrictMessageSize()
{
    restrictMessageSize();
    countMessageSize();
}

function countMessageSize()
{
    var content = $('smscontent').value;
    Element.setStyle('sms_response', { color: 'black' });
    $('sms_response').innerHTML = 'Message size is ' + content.length + ' / 160.';
}

function disableScheduling()
{
    $('send_at').value = 'd/m/y h:mm am';
    $('send_how_often').selectedIndex = 0;

    $('send_at').disabled = true;
    $('send_at_timezone').disabled = true;
    $('send_how_often').disabled = true;
}

function enableScheduling()
{
    $('send_at').disabled = false;
    $('send_at_timezone').disabled = false;
    $('send_how_often').disabled = false;
}

// Keep this method consistent with:
//  /website/sms/smscommon.php: getCanonicalSchedule($schedule)
function getCanonicalSchedule(schedule)
{
    var now = new Date();
    var todayDayMonthYear = now.getDate() + "/" + (now.getMonth() + 1) + "/" + now.getFullYear();
    var tomorrow = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1);
    var tomorrowDayMonthYear = tomorrow.getDate() + "/" + (tomorrow.getMonth() + 1) + "/" + tomorrow.getFullYear();

    // Collapse multiple spaces to one space.
    schedule = schedule.replace(/\s+/, ' ');

    // Convert [AM] to [am].
    schedule = schedule.replace(/(\s|\d)AM\b/i, '$1am');
    schedule = schedule.replace(/(\s|\d)PM\b/i, '$1pm');

    // Convert [1:23pm] to [1:23 pm].
    schedule = schedule.replace(/(\d)\s*([ap]m)\b/, '$1 $2');

    // Convert [1 pm] to [1:00 pm].
    schedule = schedule.replace(/([:0-9]\d\d?)\s*([ap]m)\b/, '$1' + ':00 $2');

    // Convert [midnight] to [12:00 am].
    schedule = schedule.replace(/\bmidnight\b/, '12:00 am');

    // Convert [noon] to [12:00 pm].
    schedule = schedule.replace(/\bnoon\b/, '12:00 pm');

    // Convert [2010-2-1] to [1/2/2010].
    schedule = schedule.replace(/\b(\d\d\d\d)[-.\/](\d\d?)[-.\/](\d\d?)\b/, '$3/$2/$1');

    // Convert [1/2/10] to [1/2/2010].
    var yearPrefix = new String(now.getFullYear()).substring(0, 2);
    schedule = schedule.replace(/\b(\d\d?)[-.\/](\d\d?)[-.\/](\d\d)\b/, '$1/$2/' + yearPrefix + '$3');

    // Convert [1-2-2010] to [1/2/2010].
    schedule = schedule.replace(/\b(\d\d?)[-.\/](\d\d?)[-.\/](\d\d\d\d)\b/, '$1/$2/$3');

    // Convert [today] to [1/2/2010].
    schedule = schedule.replace(/\btoday\b/i, todayDayMonthYear);

    // Convert [tonight] to [1/2/2010].
    schedule = schedule.replace(/\btonight\b/i, todayDayMonthYear);

    // Convert [tomorrow] to [2/2/2010].
    schedule = schedule.replace(/\btomorrow\b/i, tomorrowDayMonthYear);

    // Convert [1:23 pm 1/2/2010] to [1/2/2010 1:23 pm].
    schedule = schedule.replace(/\b(\d\d?:\d\d\s*[ap]m)\s+(\d\d?\/\d\d?\/\d\d\d\d)\b/, '$2 $1');

    return schedule;
}

function getSmsDestinationName(numberAndOptionalName)
{
    var numberAndName = getPhoneNumberAndName(numberAndOptionalName);
    return numberAndName[1];
}

function getSmsDestinationNumber(numberAndOptionalName)
{
    var numberAndName = getPhoneNumberAndName(numberAndOptionalName);
    return numberAndName[0];
}

function isEqualToNameOrNumber(candidate, numberAndName, alreadyDeterminedNumber)
{
    if (numberAndName == candidate)
    {
        return true;
    }
    else
    {
        var name = getSmsDestinationName(numberAndName);
        if (name != null)
        {
            if (name.toLowerCase() == candidate.toLowerCase())
            {
                return true;
            }
            else
            {
                var selectedName = getSmsDestinationName(candidate);
                if (selectedName != null && name.toLowerCase() == selectedName.toLowerCase())
                {
                    return true;
                }
            }
        }
        var number = alreadyDeterminedNumber;
        if (number == null)
        {
            number = getSmsDestinationNumber(numberAndName);
        }
        if (number != null)
        {
            if (number.toLowerCase() == candidate.toLowerCase())
            {
                return true;
            }
            else
            {
                var selectedNumber = getSmsDestinationNumber(candidate);
                if (selectedNumber != null && number.toLowerCase() == selectedNumber.toLowerCase())
                {
                    return true;
                }
            }
        }
    }
    return false;
}

function refreshHistory()
{
    var historyDescription = getCookieSetByPhp('sms-destination-history');
    if (historyDescription != null)
    {
        var history = historyDescription.split('|');

        var selectedValue = $('smsdestination').value;
        var selectedIndex = 0;
        $('smsdestinationhistory').options.length = 0;
        $('smsdestinationhistory').options[0] = new Option('- or choose a number -', '');
        for (var i=0; i < history.length; i++)
        {
            var number = getSmsDestinationNumber(history[i]);
            var description = history[i];
            $('smsdestinationhistory').options[i + 1] = new Option(description, number);

            if (selectedIndex == 0 && selectedValue != null && selectedValue != '04xx xxx xxx nickname')
            {
                if (isEqualToNameOrNumber(selectedValue, history[i], number))
                {
                    selectedIndex = i + 1;
                }
            }
        }
        $('smsdestinationhistory').selectedIndex = selectedIndex;
        $('smsdestinationhistory').disabled = false;
    }
}

function restrictMessageSize()
{
    var maximumSize = 160;
    var content = $('smscontent').value;
    if (content.length > maximumSize)
    {
        content = content.substring(0, maximumSize);
        $('smscontent').value = content;
    }
}

function addNameToNumber()
{
    var ajaxCall = new Ajax.Request('/sms/add-name-to-number.php', {method: 'post', parameters: Form.serialize('sms_dialog_recipient_name_form'), onSuccess: hideSMSDialogRecipientName });

    return false;
}

function destinationIsUnnamed(numberAndOptionalName)
{
    var unnamed = true;
    var name = getSmsDestinationName(numberAndOptionalName);
//alert('bravo[' + name + ']');
    if (name != null && name != '')
    {
        unnamed = false;
    }
    else
    {
        // Is this number in the history? If so, is it named in the history?
        //
        // (Selecting a dropdown entry will populate only its number, not
        //  it's name into the destination field; retyping a historic
        //  number.)

        var historyDescription = getCookieSetByPhp('sms-destination-history');
        if (historyDescription != null)
        {
            var candidateNumber = getSmsDestinationNumber(numberAndOptionalName);
            var history = historyDescription.split('|');
            for (var i=0; i < history.length; i++)
            {
                var number = getSmsDestinationNumber(history[i]);
                if (number != null)
                {
                    if (number.toLowerCase() == candidateNumber.toLowerCase())
                    {
                        var historicalName = getSmsDestinationName(history[i]);
                        if (historicalName != null && historicalName != '')
                        {
                            unnamed = false;
                        }
                    }
                }
            }
        }
    }
    return unnamed;
}

function hideSMSDialogRecipientName()
{
    setHideSMSDialogCookieIfRequired();

    Element.setStyle('sms', { opacity: '1.0' });
    Element.setStyle('sms', { filter: 'alpha(opacity=100)' });
    Element.setStyle('sms_dialog_recipient_name', { visibility: 'hidden' });

    refreshHistory();
    $('smscontent').select();
}

//var readyForNewMessage = function(result)
function readyForNewMessage(result)
{
    Element.toggle('smssubmit'); 
    refreshHistory();
    if (result.responseText.substr(0, 5) == 'Sent:'
            || result.responseText.substr(0, 10) == 'Scheduled:')
    {
        // If a monthly repeating SMS for the 29th, 30th or 31st was 
        // successfully scheduled, show a modal warning.
        var isASchedule = result.responseText.substr(0, 11) == 'Scheduled: ';
//alert($('send_how_often').options[$('send_how_often').selectedIndex].text);
        var isAMonthlyRepeat = $('send_how_often').options[$('send_how_often').selectedIndex].text == 'monthly';
        var isAYearlyRepeat = $('send_how_often').options[$('send_how_often').selectedIndex].text == 'yearly';
        if (isASchedule && isAMonthlyRepeat)
        {
            var schedule = getCanonicalSchedule($('send_at').value);
//alert(schedule);
            var isDay29 = schedule.match( /^29\// );
//alert(isDay29);
            var isDay30 = schedule.match( /^30\// );
//alert(isDay30);
            var isDay31 = schedule.match( /^31\// );
//alert(isDay31);
            if (isDay29)
            {
                alert("You scheduled a monthly SMS on the 29th.\n"
                        + "\n"
                        + "We won't send an SMS when it's February unless it's a leap year.");
            }
            else if (isDay30)
            {
                alert("You scheduled a monthly SMS on the 30th.\n"
                        + "\n"
                        + "We won't send an SMS when it's February.");
            }
            else if (isDay31)
            {
                alert("You scheduled a monthly SMS on the 31st.\n"
                        + "\n"
                        + "We won't send an SMS when it's February, April, June, September, or November.");
            }
        }
        else if (isASchedule && isAYearlyRepeat)
        {
            var schedule = getCanonicalSchedule($('send_at').value);
//alert(schedule);
            var isDay29 = schedule.match( /^29\/0?2\// );
//alert(isDay29);
            if (isDay29)
            {
                alert("You scheduled a yearly SMS on the 29th of February.\n"
                        + "\n"
                        + "We won't send an SMS when it's February 29 unless it's a leap year.");
            }
        }
        
        Element.setStyle('sms_response', { color: 'black' });
    }
    else
    {
        Element.setStyle('sms_response', { color: 'red' });
    }
    if (result.responseText.substr(0, 6) == 'Sent: '
            || result.responseText.substr(0, 11) == 'Scheduled: ')
    {
        var skipDialog = getCookieSetByPhp('sms-dialog-recipient-hide');
        if (skipDialog == null || !skipDialog)
        {
            var numberAndOptionalName = $('smsdestination').value;
            if (destinationIsUnnamed(numberAndOptionalName))
            {
                var destinationNumber = getSmsDestinationNumber(numberAndOptionalName);

                $('sms_dialog_recipient_name_number').value = destinationNumber;
                $('sms_dialog_recipient_name_number_label').innerText = destinationNumber;
                $('sms_dialog_recipient_name_number_label').textContent = destinationNumber;

                showSMSDialogRecipientName();
            }
        }
        resetSchedulingThenResetContent();
    }
    else if (result.responseText.toString() == 'SMS not sent: Please type in the To phone number.')
    {
        $('smsdestination').select();
    }
    else if (result.responseText == 'SMS not sent: Please type in your Australia On Line email.')
    {
        $('smsemail').select();
    }
    else if (result.responseText == 'SMS not sent: Please type in your password.')
    {
        $('smspassword').select();
    }
    else if (result.responseText == 'SMS not sent: Please type in the sms message.'
           || result.responseText == 'SMS not sent: Please make your message smaller than 160.'
           || result.responseText == 'SMS not sent: Please type in a message that is not blank.')
    {
        $('smscontent').select();
    }
    else if (result.responseText == 'SMS not sent: Please confirm your mobile phone number.')
    {
        window.location = 'http://australiaonline.net.au/sms/not-sent/confirm-your-mobile-phone-number.php';
        exit;
    }
    else if (result.responseText == 'SMS not sent: Please tell us your mobile phone number.')
    {
        window.location = 'http://australiaonline.net.au/sms/not-sent/what-is-your-mobile-phone-number.php';
        exit;
    }
}

function resetSchedulingThenResetContent()
{
    if ($('send_later').checked)
    {
        $('send_now').checked = true;
        disableScheduling();
        // Setting checked = true doesn't trigger the onclick event,
        // so call disableScheduling manually.
        // 
    }

    $('smscontent').value = '';
    $('smscontent').focus();
}

function setHideSMSDialogCookieIfRequired()
{
    var hide = $('sms_dialog_recipient_name_hide').checked;
    if (hide)
    {
        setCookie('sms-dialog-recipient-hide', hide, 365);
    }
}

function showSMSDialogRecipientName()
{
    $('sms_dialog_recipient_name_name').value = '';

    Element.setStyle('sms', { opacity: '0.4' });
    Element.setStyle('sms', { filter: 'alpha(opacity=40)' });
    Element.setStyle('sms_dialog_recipient_name', { visibility: 'visible' });

    $('sms_dialog_recipient_name_name').focus();
}

function sendSMS()
{
    // Assumptions:
    // - A successful send has an XMLHttpRequest.responseText starting
    //   with a literal 'Sent:'.
    // - A successful schedule has an XMLHttpRequest.responseText starting
    //   with a literal 'Scheduled:'.

    Element.toggle('smssubmit');
    Element.setStyle('sms_response', { color: 'black' });
    $('sms_response').innerHTML = 'Sending&hellip;';
    var ajaxCall = new Ajax.Updater('sms_response', '/sms/send.php', {method: 'post', parameters: Form.serialize('smsform'), onSuccess: readyForNewMessage });

    return false;
}
Event.observe($('smsdestination'), 'focus', clearDefaultDestinationMessage, false);
Event.observe($('smscontent'), 'focus', clearDefaultMessage, false);
Event.observe($('smscontent'), 'keyup', countAndRestrictMessageSize, false);
Event.observe($('smscontent'), 'input', countAndRestrictMessageSize, false);
Event.observe($('send_now'), 'click', disableScheduling, false);
Event.observe($('send_later'), 'click', enableScheduling, false);
Event.observe($('send_at'), 'focus', clearDefaultSchedulingSendAt, false);
Event.observe($('smsdestinationhistory'), 'change', copyHistoryToSmsDestination, false);
Event.observe($('sms_clear_history'), 'click', clearHistory, false);
Event.observe($('sms_dialog_close'), 'click', closeSMSDialog, false);
Event.observe($('sms_dialog_close_x'), 'click', closeSMSDialog, false);

