_cfscriptLocation = "/ajax/functions/functions.cfm";

var emailFriend = {};

function isEmail(s) {
	if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(s)){ return true; }
	return false;
}

function constructEmailFriendPane() {
    emailFriend.entityId = "";
    emailFriend.entityName = "";
    emailFriend.title = "";
    emailFriend.linkurl = "";
	emailFriend.anchorId = '';
	emailFriend.mailtype = '';
	emailFriend.emailToLines = 2;

    emailFriend.closePopup = function() {
        byId('emailfriendpane').style.display = 'none';
		emailFriend.anchorId = '';
    }

    // Make the popup show startpane, successpane, or errorpane
    emailFriend.setPaneContent = function(paneId) {
        byId('emailfriend-startpane').style.display = 'none';
        byId('emailfriend-successpane').style.display = 'none';
        byId('emailfriendpane').style.display = 'block';
        byId(paneId).style.display = 'block';

        if (paneId == 'emailfriend-startpane') {
            byId('emailsendStatus').innerHTML = '';
        }

        if (paneId == 'emailfriend-successpane') {
        }
    }

    // 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
    emailFriend.showPopup = function(anchorId, eid, ename, title, linkurl, mailtype) {
		if( emailFriend.anchorId == anchorId ) {
			emailFriend.closePopup();
		}
		else {
			var pane = byId('emailfriendpane');
			var popupLocation = getAbsoPos(byId(anchorId));
			var eleWidth = getWidth(byId(anchorId));
			byId('emailtitle').innerHTML = title;
			//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 - 415 + 'px';
			pane.style.display = 'block';
			emailFriend.setPaneContent('emailfriend-startpane');
			emailFriend.entityId = eid;
			emailFriend.entityName = ename;
			emailFriend.sendButton.style.visibility='visible';
			emailFriend.title = title;
			emailFriend.linkurl = linkurl;
			emailFriend.anchorId = anchorId;
			emailFriend.mailtype = mailtype;
		}
    }

    emailFriend.sendButton = img({
        "src" : "/images/emailfriend/send_email.gif",
        "alt" : "Send via Email"
    });

    emailFriend.startPane = div(
        {"id" : "emailfriend-startpane"},
        div({ "style" : "margin-top: 10px;padding: 5px;font-size: 14px;" }, "This form will send details on ", strong(span({"id" : "emailtitle"}, "this")), " to (one or more) email addresses."),
		p({ "id" : "emailaddresses"}, "Send To Email Addresses",br(),
			input({"type" : "text", "id" : "email1", "size" : "30", "maxlength" : "50"}),
			br(),
			input({"type" : "text", "id" : "email2", "size" : "30", "maxlength" : "50", "style": "margin-top:2px;"}),
			a({"href" : "javascript:emailFriend.addAddressLine();", "style" : "padding-left: 5px;"}, "+1")
		 ),
		p( "Your Name", br(),
			input({"type" : "text", "id" : "emailfromname", "size" : "30", "maxlength" : "50"})
		),
		p( "Your Email Address", br(),
			input({"type" : "text", "id" : "emailfromaddress", "size" : "30", "maxlength" : "50"})
		),
		p( "Your Note (optional)", br(),
			textarea({"rows" : "3", "cols" : "40", "id" : "emailnote" })
		),
        p(
            emailFriend.sendButton
        ),
		span({"id" : "emailsendStatus"})
    );
	
	emailFriend.addAddressLine = function() {
		emailFriend.emailToLines = emailFriend.emailToLines + 1;
		var newline = input({"type" : "text", "id" : "email"+emailFriend.emailToLines, "size" : "30", "maxlength" : "50", "style": "margin-top:2px;"});
		byId('emailaddresses').appendChild(newline);
		
	}
    emailFriend.sendButton.onclick = function() {
		var valid_emails = 0;
		var toaddresses = '';
		for( var i=1; i <=emailFriend.emailToLines; i++ ) {
			var toaddress = byId('email'+i).value;
			if( toaddress != '' && !isEmail(toaddress) ) {
				alert('Your friend\'s email address is not formatted properly');
				byId('email'+i).focus();
				return;
			}
			else if ( toaddress != '' ) { 
				valid_emails = valid_emails + 1; 
				if( valid_emails > 1 ) {
					toaddresses = toaddresses + ',' + toaddress;
				}
				else {
					toaddresses = toaddresses + toaddress;		
				}
			}
		}
		if( valid_emails == 0 ) {
			alert('Please enter one or more email addresses.');
			byId('email1').focus();
			return;
		}
		if( byId('emailfromname').value == '' ) {
			alert('Please enter your NAME');
			byId('emailfromname').focus();
			return;
		}
		if( ! isEmail(byId('emailfromaddress').value) ) {
			alert('Please enter a valid FROM email address');
			byId('emailfromaddress').focus();
			return;
		}
        emailFriend.sendButton.style.visibility='hidden';
        byId('emailsendStatus').innerHTML = 'Sending...';

		DWREngine._execute(_cfscriptLocation, null, 'emailFriends', 
				byId('emailfromname').value, 
				byId('emailfromaddress').value, 
				toaddresses,
				byId('emailnote').value, 
				emailFriend.title,
				emailFriend.linkurl,
				emailFriend.mailtype,
				emailFriend.handleServerResponse);	 
    }

    emailFriend.handleServerResponse = function(message) {
        emailFriend.setPaneContent(message.indexOf('OK') == 0 ?
            'emailfriend-successpane' : 'emailfriend-errorpane');
		
		// omniture tracking
		if( emailFriend.linkurl.indexOf('dealpage.cfm') != -1) {
			s.pageName = 'Deals: Email Friend: ' + emailFriend.title;
		}
		else {
			s.pageName = s.channel + ": Email Friend: " + emailFriend.title;
		}
		void(s.t());
    }

    emailFriend.successPane = div(
        {"id" : "emailfriend-successpane" },
        div({"style" : "font-size: 16px;margin: 25px;"}, strong("Your message has been sent!") ),
		p(a({"style" : "text-align: center;margin: auto;", "class" : "closelink", "href" : "javascript:emailFriend.closePopup();"},"CLOSE THIS WINDOW")),
        p( {"id" : "confirmation"}, "")
    );

    emailFriend.closeButton = span({"class" : "pseudoButton"}, "");

    emailFriend.closeButton.onclick = emailFriend.closePopup;

	    // Main pane: contains close box and one of the three possible content divs
    return div(
        {"id" : "emailfriendpane", "class" : "popupBlock"},
        div(
            {"style" : "text-align:right;", "align" : "right"},
            emailFriend.closeButton
        ),
        emailFriend.startPane,
        emailFriend.successPane/*,
        emailFriend.errorPane*/
    );

}

pedro.event.addToOnLoad(
    function() {d.body.appendChild(constructEmailFriendPane());}
);
