// sendToPhone.js
//
// Depends on pedro.js and friends.

var sendToPhone = {};

function constructSendToPhonePane() {
    sendToPhone.phone = "";
    sendToPhone.entityId = "";
    sendToPhone.entityName = "";

    sendToPhone.closePopup = function() {
        byId('sendpane').style.display = 'none';
    }

    // Make the popup show startpane, successpane, or errorpane
    sendToPhone.setPaneContent = function(paneId) {
        byId('startpane').setStyle('display','none');
        byId('errorpane').setStyle('display','none');
        byId('successpane').setStyle('display','none');
        byId('sendpane').setStyle('display','block');
        byId(paneId).setStyle('display','block');

        if (paneId == 'startpane') {
            // clear messages and agree checkbox, but preserve phone number
            byId('agree').checked = false;
            byId('sendStatus').innerHTML = '';
            sendToPhone.areaBox.focus();
            sendToPhone.areaBox.selectionStart=0;
            sendToPhone.areaBox.selectionEnd=0;
        }

        if (paneId == 'successpane') {
            byId('confirmation').innerHTML =
                sendToPhone.entityName + ' information was sent to ('
                + sendToPhone.phone.substring(0, 3) + ') '
                + sendToPhone.phone.substring(3, 6) + '-'
                + sendToPhone.phone.substring(6, 10);
        }
    }

    // Makes the popup visible with the form
    //    anchorId - id of element at which to place the upperleft of the popup
    //    eid - entity id of the entity whose info is to be "sent to phone"
    //    ename - name of the entity to be sent
    sendToPhone.showPopup = function(anchorId, eid, ename) {
        var pane = byId('sendpane');
        var popupLocation = byId(anchorId).getCoordinates();
        var eleWidth = byId(anchorId).getCoordinates().width;
        pane.setStyle('left', popupLocation.left - 70 + 'px');
        pane.setStyle('top', popupLocation.bottom + 'px');
        pane.setStyle('display','block');
        sendToPhone.setPaneContent('startpane');
        sendToPhone.entityId = eid;
        sendToPhone.entityName = ename;
        byId(sendToPhone.sendButton).setStyle('visibility','visible');
    }

    sendToPhone.sendButton = img({
        "src" : guideConfig.imagePath + "sendtophone/send.gif",
        "alt" : "Send to Phone"
    });

    sendToPhone.sendButton.onclick = function() {
        sendToPhone.sendButton.style.visibility='hidden';

        sendToPhone.phone = byId('area').value + byId('prefix').value
            + byId('suffix').value;

        if (!byId('agree').checked) {
            alert('You must agree to the terms and conditions');
            sendToPhone.sendButton.style.visibility='visible';

        } else if (! /\d{10}/.test(sendToPhone.phone)) {
            alert('The phone number must contain 10 digits');
            sendToPhone.sendButton.style.visibility='visible';

        } else {
            byId('sendStatus').innerHTML = 'Sending...';
            sendToPhoneService.send(
                '1' + sendToPhone.phone, sendToPhone.entityId, {
                callback: sendToPhone.handleServerResponse,
                timeout: 180000,
                errorHandler: sendToPhone.handleRemotingError
            });
        }
    }

    sendToPhone.sponsorImage = img({
        "src" : guideConfig.imagePath + "sendtophone/hyundai_logo.gif",
        "alt" : "Hyundai"
    });

    sendToPhone.sponsorImageSuccess = img({
        "src" : guideConfig.imagePath + "sendtophone/hyundai_logo.gif",
        "alt" : "Hyundai"
    });

    sendToPhone.sponsorImageError = img({
        "src" : guideConfig.imagePath + "sendtophone/hyundai_logo.gif",
        "alt" : "Hyundai"
    });

    sendToPhone.handleServerResponse = function(message) {
        sendToPhone.setPaneContent(message.indexOf('OK') == 0 ?
            'successpane' : 'errorpane');
    }

    sendToPhone.handleRemotingError = function(message) {
        sendToPhone.setPaneContent('errorpane');
        alert(message);
    }

    sendToPhone.supportedCarriers = function() {
        return p(
            "Supported carriers include Alltel, Boost, Dobson Cellular Systems, "
            + "Cellular One, AT&T, "
            + "Nextel, Sprint, T-Mobile\xAE, and Verizon.  No pre-paid phones are "
            + "supported."
        );
    }

    sendToPhone.optOut = function() {
        return div(
            "To opt out at anytime, send the word ", strong("STOP"),
            " to 50909 from your mobile phone. ",
            "To get a help message, send the word ", strong("HELP"),
            " to 50909 from your mobile phone."
        );
    }

    sendToPhone.areaBox = input(
        {"type" : "text", "id" : "area", "size" : "3", "maxlength" : "3"}
    );

    sendToPhone.prefixBox = input(
        {"type" : "text", "id" : "prefix", "size" : "3", "maxlength" : "3"}
    );

    sendToPhone.suffixBox = input(
        {"type" : "text", "id" : "suffix", "size" : "4", "maxlength" : "4"}
    );

    sendToPhone.areaBox.onkeyup = function() {
        if (sendToPhone.areaBox.value.length == 3) {
            sendToPhone.prefixBox.focus();
        }
    }

    sendToPhone.prefixBox.onkeyup = function() {
        if (sendToPhone.prefixBox.value.length == 3) {
            sendToPhone.suffixBox.focus();
        }
    }

    sendToPhone.startPane = div(
        {"id" : "startpane"},
        div("Send this listing as a ", strong("text message"), " to your cell phone."),
        p(
            {"style" : "text-align:center", "align" : "center"},
            "To: ",
            sendToPhone.areaBox,
            " - ",
            sendToPhone.prefixBox,
            " - ",
            sendToPhone.suffixBox
        ),
        p(
            input({"type" : "checkbox", "id" : "agree"}),
            " ",
            span({"id" : "agreeText"}, "I agree to the terms and conditions")
        ),
        p(
            {"style": "text-align:center", "align" : "center"},
            sendToPhone.sendButton
        ),

        span({"id" : "sendStatus"}),
        p(strong("Terms and Conditions")),
        p(strong("SMS and other charges may apply depending on your carrier and phone plan.")),
        sendToPhone.supportedCarriers()
    );

    sendToPhone.successPane = div(
        {"id" : "successpane"},
        div(strong("Your message was successfully sent!")),
        p( {"id" : "confirmation"}, ""),
        sendToPhone.optOut()
    );

    sendToPhone.errorPane = div(
        {"id" : "errorpane"},
        div(strong("Your message was not sent!")),
        p(strong("Please make sure you type your mobile phone number correctly, and your wireless carrier is supported.")),
        sendToPhone.supportedCarriers(),
        sendToPhone.optOut()
    );

    sendToPhone.closeButton = span({"class" : "pseudoButton"}, "X");

    sendToPhone.closeButton.onclick = sendToPhone.closePopup;

    // Main pane: contains close box and one of the three possible content divs
    return div(
        {"id" : "sendpane", "class" : "popupBlock"},
        div(
            {"style" : "text-align:right", "align" : "right"},
            sendToPhone.closeButton
        ),
        sendToPhone.startPane,
        sendToPhone.successPane,
        sendToPhone.errorPane
    );
}

pedro.event.addToOnLoad(
    function() {d.body.appendChild(constructSendToPhonePane());}
);
