// sendToPhone.js
//
// Depends on pedro.js and friends.

/* This script and many more are available free online at
The JavaScript Source!! http://javascript.internet.com
Created by: Cyanide_7 |  */
var isNN = (navigator.appName.indexOf("Netscape")!=-1);

function autoTab(input,len, e, nextfield) {
  var keyCode = (isNN) ? e.which : e.keyCode; 
  var filter = (isNN) ? [0,8,9] : [0,8,9,16,17,18,37,38,39,40,46];
  if(input.value.length >= len && !containsElement(filter,keyCode)) {
    input.value = input.value.slice(0, len);
	byId(nextfield).focus();
  }

  function containsElement(arr, ele) {
    var found = false, index = 0;
    while(!found && index < arr.length)
    if(arr[index] == ele)
    found = true;
    else
    index++;
    return found;
  }
  return true;
}


var sendToPhone = {};

function constructSendToPhonePane() {
    sendToPhone.phone = "";
    sendToPhone.entityId = "";
    sendToPhone.entityName = "";
	sendToPhone.anchorId = '';

    sendToPhone.closePopup = function() {
        byId('sendpane').style.display = 'none';
		sendToPhone.anchorId = '';
    }

    // Make the popup show startpane, successpane, or errorpane
    sendToPhone.setPaneContent = function(paneId) {
        byId('startpane').style.display = 'none';
        byId('errorpane').style.display = 'none';
        byId('successpane').style.display = 'none';
        byId('sendpane').style.display = 'block';
        byId(paneId).style.display = 'block';

        if (paneId == 'startpane') {
            // clear messages and agree checkbox, but preserve phone number
            byId('agree').checked = false;
            byId('sendStatus').innerHTML = '';
        }

        if (paneId == 'successpane') {
            byId('phone-confirmation').innerHTML = '<strong>Mobile phone - ('
                + sendToPhone.phone.substring(0, 3) + ') '
                + sendToPhone.phone.substring(3, 6) + '-'
                + sendToPhone.phone.substring(6, 10) + '</strong>';
        }
    }

    // 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, title, message) {
		if( sendToPhone.anchorId == anchorId ) {
			sendToPhone.closePopup();
		}
		else {
			var pane = byId('sendpane');
			var popupLocation = getAbsoPos(byId(anchorId));
			var eleWidth = getWidth(byId(anchorId));
			//pane.style.left = eleWidth + popupLocation.x + 'px';
			pane.style.left =  popupLocation.x - 250 + 'px';
			//pane.style.top = popupLocation.y + 'px';
			pane.style.top = popupLocation.y - 295 + 'px';
			pane.style.display = 'block';
			sendToPhone.setPaneContent('startpane');
			sendToPhone.entityId = eid;
			sendToPhone.entityName = ename;
			sendToPhone.message = title + ' - ' + message;
			sendToPhone.sendButton.style.visibility='visible';
			byId('textmessage').innerHTML = title + ' - ' + message;
			sendToPhone.anchorId = anchorId;
		}
    }

    sendToPhone.sendButton = img({
        "src" : "/images/sendtophone/send_to_phone.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('sendbuttonline').style.display = 'none';
            byId('sendStatus').innerHTML = '<strong>Sending message...</strong>';
			
		DWREngine._execute(_cfscriptLocation, null, 'sendToPhone', 
				'1'+sendToPhone.phone, 
				sendToPhone.message, 
				sendToPhone.handleServerResponse);	 
        }
    }

    sendToPhone.handleServerResponse = function(obj) {
		eval(obj);
		byId('sendbuttonline').style.display = 'block';
		if( response.code == '1000' ) {
			sendToPhone.setPaneContent('successpane');
		}
		else {
			byId('errormessage').innerHTML = response.code + ': ' + response.description;
			sendToPhone.setPaneContent('errorpane');
		}
		
		// omniture tracking
		s.pageName = s.channel + ": Send To Phone: " + sendToPhone.title;
		void(s.t());
     }

    sendToPhone.handleRemotingError = function(message) {
        sendToPhone.setPaneContent('errorpane');
        alert(message);
    }

    sendToPhone.startPane = div(
        {"id" : "startpane"},
		div(p({"id" : "messagehead"},"Send SMS Message:"),
			  div({"id" : "textmessage"}, "")),
		p("as a text message to your cell phone"),
        p(
            {"style" : "text-align:left"},
            "Cell phone: ",
            input({"type" : "text", "id" : "area", "size" : "3", "maxlength" : "3", "onKeyUp" : "return autoTab(this, 3, event,'prefix');" }),
            " - ",
            input({"type" : "text", "id" : "prefix", "size" : "3", "maxlength" : "3", "onKeyUp" : "return autoTab(this, 3, event,'suffix');"}),
            " - ",
            input({"type" : "text", "id" : "suffix", "size" : "4", "maxlength" : "4"})
        ),
        p(
            input({"type" : "checkbox", "id" : "agree"}),
            " ",
            span({"id" : "agreeText"}, "I agree to the terms and conditions")
        ),
        p(
            {"id": "sendbuttonline", "style": "text-align:left"},
            sendToPhone.sendButton
        ),
            
        span({"id" : "sendStatus"}),
        p(strong("Terms and Conditions:"),br(),
			"SMS and other charges may apply depending on your carrier and phone plan.")
    );

    sendToPhone.successPane = div(
        {"id" : "successpane", "style" : "height:350px;"},
        div({"style" : "font-size: 14px;margin-top: 25px;"}, strong("Your message was successfully sent to:")),
        p( {"id" : "phone-confirmation"}, ""),
		p(a({"class" : "closelink", "href" : "javascript:sendToPhone.closePopup();"},"CLOSE THIS WINDOW"))
    );

    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.")),
		p({"id" : "errormessage"},"")
    );

    sendToPhone.closeButton = span({"class" : "pseudoButton"}, "");

    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
    );
}

/*document.onload = constructSendToPhonePane;*/

pedro.event.addToOnLoad(
    function() {d.body.appendChild(constructSendToPhonePane());}
);
