﻿/*

    LeadContactForm expects two arguments:
        uniqueClassName: LeadContactForm is designed to work with multiple forms on one page 
            if so desired. Therefore, it requires each form be passed a unique identifier that 
            conforms to the naming rules for a css class. The constructor will throw an error if 
            the identifier matches the classname of any other element on the page.
    
    
        input: an object with the following properties, all of which are optional:

            input = {

                email: string,
                coname: string,
                master_listing_id: string,
                mkt_listing_email: string,
                mkt_listing_coname: string,
                append: string

            }
    
    Public methods:
        getForm() - returns the contact form as a string
        init() - must be called after the form has been injected in the DOM. This works this way 
            because the form is created as a string. If you want to call the init function 
            before injection, it could be reworked using jQuery -  create the elements from
            the string, and use the $() method to search through the string and add event 
            handlers.
    
    Dependencies:
        - My own core.js, v1.1.3. Now that I'm using jQuery here too I'll probably write a jQuery wrapper for the core.js interface.
        - The jQuery library for one function, blurElement(). If you don't wanna use jQuery, you need to write an event triggering function.
        - Most of the behavior involves changing css classes rather than directly manipulating element properties. The relevent styles are
          defined in css/leadContactForm.css. If there are conflicts with other elements, classes can be changed by changing the uppercase
          class "constants."
        - mktsEmail() contains calls to external functions. These are defined in emailer.js and in script tags on market.aspx
        
    Future development:
        Everything in this object relates to the contact form on the markets.aspx page. It is 
        encapsulated as fully as possible given the current framework. However, it would be 
        preferable to implement this in a way that further separates presentation and allows 
        greater reuse. Specifically, the form should be created using templates. Validation 
        should be separated and used consistently across the site. The form string should be 
        turned into HTMLElements before being passed to the contact form widget. The HTML email
        that is produced should also be templated, and sent separately from this object.
          
    Author: Rick Quantz 12/2010
    
*/

function LeadContactForm(uniqueClassName, input) {

    /* Private */
    
    var self = this;

    var SHOW_CLASS = 'showForm'
      , SHOW_TEASER_CLASS = 'show_teaser'
      , SHOW_MESSAGE_CLASS = 'show_message'
      , SHOW_INFO_CLASS = 'show_info'
      , SEND_BUTTON_CLASS = 'send_button'
      , DEFAULT_VAL_CLASS = 'default_value'
      , REQUIRED_CLASS = 'required'
      , EMAIL_CLASS = 'validate_email'
      , BLACK_CLASS = 'black';
    
    var email  = input.email  || ''
      , coname = input.coname || ''
      , search_id = input.search_id || ''
      , master_listing_id = input.master_listing_id || ''
      , mkt_listing_email = input.mkt_listing_email || ''
      , mkt_listing_coname = input.mkt_listing_coname || ''
      , append = input.append || '';
    
    var theForm, contactForm, nexters, step, stepFunctions, eMessage = '', emailSent = false;

    function isUnique(uniqueClassName) {
        var els = core.getElements('.' + uniqueClassName);
        return !(els.length > 0);
    }

    function changeStateClasses() {
        core.css.removeClass(contactForm, stepClassNames[step - 1]);
        core.css.addClass(contactForm, stepClassNames[step]);
    }

    function initShowButton() {
        var show = core.getElements('.' + uniqueClassName + ' .show');
        core.each(show, function(button) {
            button.onclick = showForm;
        });
    }

    function initCancelButton() {
        var cancel = core.getElements('.' + uniqueClassName + ' .cancel');
        core.each(cancel, function(button) {
            button.onclick = cancelForm;
        });
    }

    function initNextEvents() {
        var msg = core.getElements('.' + uniqueClassName + ' .' + SHOW_MESSAGE_CLASS + 'er');
        var inf = core.getElements('.' + uniqueClassName + ' .' + SHOW_INFO_CLASS + 'er');
        var sen = core.getElements('.' + uniqueClassName + ' .' + SEND_BUTTON_CLASS);

        core.each(msg, function(el) {
            el.onfocus = showMessage;
        });
        core.each(inf, function(el) {
            el.onclick = showInfo;
        });
        core.each(sen, function(el) {
            el.onclick = sendForm;
        });        
    }

    function showForm() {
        if (!core.css.hasClass(contactForm, SHOW_CLASS)) {
            core.css.addClass(contactForm, SHOW_CLASS);
            recordContactClick();
        }
        else {
            cancelForm();            
        }
    }

    function cancelForm() {
        if (core.css.hasClass(contactForm, SHOW_INFO_CLASS) && !emailSent) {
            sendForm(false);
        }
        core.css.removeClass(contactForm, SHOW_MESSAGE_CLASS);
        core.css.removeClass(contactForm, SHOW_INFO_CLASS);
        core.css.addClass(contactForm, SHOW_TEASER_CLASS);
        
        // This must be the last class change to prevent display:none bugs in ie
        core.css.removeClass(contactForm, SHOW_CLASS);

        emptyValue('.' + uniqueClassName + ' .input_panel input[type!="hidden"], .' + uniqueClassName + ' .input_panel textarea');
        unselect('.' + uniqueClassName + ' .input_panel select');
        blurElement('.' + uniqueClassName + ' input, .' + uniqueClassName + ' textarea');
        emailSent = false;
    }

    function showMessage() {
        blurElement('.' + uniqueClassName + ' input, .' + uniqueClassName + ' textarea');
        
        core.css.addClass(contactForm, SHOW_MESSAGE_CLASS);
        core.css.removeClass(contactForm, SHOW_TEASER_CLASS);

        return false;
    }

    function showInfo() {
        if (!validate()) { return false }

        eMessage = (function() {
            var eMessage = '';

            if (document.getElementById(ctlAppened + "email").value.trim() != "");
            { eMessage += '<br />' + document.getElementById(ctlAppened + "email").value; }
            eMessage += "</p><p>Message:<br />" + document.getElementById(ctlAppened + "message").value + "</p>";

            return eMessage;
        })();
        
        core.css.addClass(contactForm, SHOW_INFO_CLASS);
        core.css.removeClass(contactForm, SHOW_MESSAGE_CLASS);
        
        return false;
    }

    function sendForm(displayThankyou) {

        displayThankyou = displayThankyou === false ? false : true;

        eMessage = (function() {
            var eMessage = "";

            eMessage += "<p>" + document.getElementById(ctlAppened + "header").value + "</p><p>";
            eMessage += 'From:';

            eMessage += '<br />' + document.getElementById(ctlAppened + "salut").value + ". ";
            if (document.getElementById(ctlAppened + "emailFName").value != "")
            { eMessage += document.getElementById(ctlAppened + "emailFName").value + " "; }
            if (document.getElementById(ctlAppened + "emailLName").value != "")
            { eMessage += document.getElementById(ctlAppened + "emailLName").value; }
            if (document.getElementById(ctlAppened + "emailCompany").value != "")
            { eMessage += "<br />" + document.getElementById(ctlAppened + "emailCompany").value; }
            if (document.getElementById(ctlAppened + "emailPhone").value.trim() != "")
            { eMessage += "<br />(" + document.getElementById(ctlAppened + "emailArcode").value + ") " + document.getElementById(ctlAppened + "emailPhone").value; }

            return eMessage;

        })() + eMessage;
        mktsEmail(eMessage, displayThankyou);
        
        cancelForm(); // To reset css classes
        return false;
    }

    function addInternalLabels() {
        var inputs = core.getElements('.' + DEFAULT_VAL_CLASS);

        core.each(inputs, function(input) {

            var defaultValue = input.value;

            input.onfocus = function() {
                if (this.value === defaultValue) {
                    this.value = '';
                    core.css.addClass(this, BLACK_CLASS);
                }
            }

            input.onblur = function() {
                if (this.value === '') {
                    this.value = defaultValue;
                    core.css.removeClass(this, BLACK_CLASS);
                }
            }
        });
    }

    function validate() {
        var required = core.getElements('.' + uniqueClassName + ' .' + REQUIRED_CLASS);
        var email = core.getElements('.' + uniqueClassName + ' .' + EMAIL_CLASS);
        var ret = true;

        core.each(required, function(input) {
            if (!input.value || !core.css.hasClass(input, BLACK_CLASS)) {
                ret = false;
                alert('One or more required fields (*) are empty');
            }
        });

        core.each(email, function(input) {
            e = input.value;
            ret = /.+\@.+\..+/.test(e);
            if (ret === false) {
                alert('Please use a valid email address');
            }
        });
        
        return ret;
    }

    function mktsEmail(eMessage, displayThankyou) {
        var emailProperties = formatLead();

        displayThankyou = displayThankyou === false ? false : true;
        
        
        
        checkWait(function() { sendEmailM(eMessage); });
        checkWait(function() { saveLead(emailProperties); });

        if (displayThankyou) {
            checkWait(function() { document.getElementById("thankyou").style.display = "block"; waiting = false; });
        }
        
        emailSent = true;
    }
    // This is basically a hack. It needs to be refactored
    function formatLead() {
        var emailProperties = "";
        
        emailProperties += "&master_listing_id=" + document.getElementById(ctlAppened + "masterListingId").value;
        emailProperties += "&salut=" + document.getElementById(ctlAppened + "salut").value;
        emailProperties += "&fName=" + document.getElementById(ctlAppened + "emailFName").value;
        emailProperties += "&lName=" + document.getElementById(ctlAppened + "emailLName").value;
        emailProperties += "&coName=" + document.getElementById(ctlAppened + "emailCompany").value;
        emailProperties += "&email=" + document.getElementById(ctlAppened + "email").value;
        emailProperties += "&arcode=" + document.getElementById(ctlAppened + "emailArcode").value;
        emailProperties += "&phone=" + document.getElementById(ctlAppened + "emailPhone").value;
        emailProperties += "&message=" + escape(document.getElementById(ctlAppened + "message").value);

        return emailProperties;
    }

    function recordContactClick()
    {
        xmlhttp.open("POST", "http://" + location.host + "/IWPWebService.asmx/trackContactOpen", true);
        xmlhttp.setRequestHeader ("Content-Type", "application/x-www-form-urlencoded");
        xmlhttp.send("master_listing_id="+master_listing_id + "&search_id=" + search_id);
    }
 

    /*
        These functions uses the jQuery library. The $() function accepts any CSS selector
        the .blur() method triggers the default blur event and any blur handlers.
        For more info, see the jQuery api at api.jquery.com
    */
    function blurElement(selectorStr) {
        $(selectorStr).blur();
    }
    function emptyValue(selectorStr) {
        $(selectorStr).attr('value', '');
    }
    function unselect(selectorStr) {
        $(selectorStr).each(function() {
            this.selectedIndex = 0;
        });
    }

    
    /* Public */

    this.getForm = function() {
        return theForm;
    }

    this.init = function() {
        contactForm = core.getElements('.' + uniqueClassName)[0];

        addInternalLabels();
        initShowButton();
        initCancelButton();
        initNextEvents();
    }

    /* Constructor logic */
    
    theForm = (function() {
        var stringout = '';

        stringout += '<div class="app_detail_block ' + SHOW_TEASER_CLASS + ' ' + uniqueClassName + '" id=\"leadDisplay\">';
        stringout += '    <div class="contact_button show">';
        stringout += '		  <span class="SH">Contact this market</span>';
        stringout += '    </div>';
        stringout += '    <div class="contact_form" id="' + ctlAppened + 'emailer">';
        stringout += '        <div class="teaser"' + (email.trim() ? '' : 'style="display: none"') + '>';
        stringout += '            <input type="text" value="Enter your message here" class="' + SHOW_MESSAGE_CLASS + 'er" />';
        stringout += '        </div>';

        stringout += '        <div class="input_panel">';

        stringout += '            <div class="contact_info">';

        stringout += '                <p><span>Your message has been sent.</span> Please complete the following information to make it easier for this market to contact you.</p>';
        stringout += '                <div class="name name_labels">';
        stringout += '                    <label for="salut">Salut</label>';
        stringout += '                    <label for="fname">First</label>';
        stringout += '                    <label for="lname">Last</label>';
        stringout += '                </div>';
        stringout += '                <div class="input_group name name_inputs">';
        stringout += '                    <label>Name</label>';
        stringout += '                    <select id="' + ctlAppened + 'salut" class="salut" name="salut" >';
        stringout += '                        <option value="" selected="selected"></option>';
        stringout += '                        <option value="Mr">Mr</option>';
        stringout += '                        <option value="Ms">Ms</option>';
        stringout += '                        <option value="Mrs">Mrs</option>';
        stringout += '                    </select>';
        stringout += '                    <input id="' + ctlAppened + 'emailFName" type="text" maxlength="15" class="fname" name="fname" /><input id="' + ctlAppened + 'emailLName" type="text" maxlength="15" class="lname" name="lname" />';
        stringout += '                </div>';
        stringout += '                <div class="input_group company">';
        stringout += '                    <label for="coname">Company</label>';
        stringout += '                    <input id="' + ctlAppened + 'emailCompany" type="text" maxlength="40" name="coname" />';
        stringout += '                </div>';
        stringout += '                <div class="input_group phone">';
        stringout += '                    <label for="arcode" >Phone</label>';
        stringout += '                    <span class="area_code">(<input id="' + ctlAppened + 'emailArcode" type="text" maxlength="3" name="arcode" />)</span>';
        stringout += '                    <input id="' + ctlAppened + 'emailPhone" type="text" maxlength="8" name="phone" />';
        stringout += '                </div>';
        stringout += '                <a class="' + SEND_BUTTON_CLASS + ' next" src="images/btn_sendnow_sm.gif" alt="Send now">next</a>';        
        
        //stringout += '                <div class="buttons">';
        //stringout += '                    <a class="cancel" src="images/btn_cancel_sm.gif" alt="Cancel">close</a>';
        //stringout += '                </div>';
        
        stringout += '            </div>';

        stringout += '            <div class="message">';
        stringout += '                <textarea id="' + ctlAppened + 'message" class="' + DEFAULT_VAL_CLASS + ' ' + REQUIRED_CLASS + '" onkeyup="checkLength(this.id, 400)" onmouseup="checkLength(this.id, 400)" >Your message*</textarea>';
        stringout += '                <input id="' + ctlAppened + 'email" class="' + DEFAULT_VAL_CLASS + ' ' + REQUIRED_CLASS + ' ' + EMAIL_CLASS + '" type="text" maxlength="100" value="Your email address*" />';
        stringout += '                <a class="' + SHOW_INFO_CLASS + 'er next" src="images/btn_sendnow_sm.gif" alt="Send now">next</a>';

        //stringout += '                <div class="buttons">';
        //stringout += '                    <a class="cancel" src="images/btn_cancel_sm.gif" alt="Cancel">close</a>';
        //stringout += '                </div>';
        
        stringout += '            </div>';

        stringout += '            <input id="' + ctlAppened + 'masterListingId" type="hidden" value="' + master_listing_id + '" />';
        stringout += '            <input id="' + ctlAppened + 'toEmail" type="hidden" value="' + mkt_listing_email + '" />';
        stringout += '            <input id="' + ctlAppened + 'subject" type="hidden" value="InsuranceWebPortal: lead from ' + mkt_listing_coname + '" />';
        stringout += '            <input id="' + ctlAppened + 'header" type="hidden" value="The following inquiry was entered through InsuranceWebPortal.com" />';

        stringout += '        </div>';

        // If you want to add anything after the buttons, now's the time.
        stringout += append;

        stringout += '    </div>';
        stringout += '</div>';

        stringout += '<div id="thankyou">';
        stringout += '    <div>';
        stringout += '        <p>Your message has been sent.</p>';
        stringout += '        <input id="ok" type="button" value="Ok" onclick="hideTY()" />';
        stringout += '    </div>';
        stringout += '</div>';

        return stringout;

    })();
    
    if (!isUnique(uniqueClassName)) {
        throw new Error('That contact form class name is not unique');
    }

    window.onunload = function() {
        if (core.css.hasClass(contactForm, SHOW_INFO_CLASS) && !emailSent) {
            sendForm();
        }
    }

}
