/*
init namespace
*/
BL.registration = {};
// default modal height
BL.registration.static_modal_height = 525;
// a boolean to determine whether user has registered
BL.registration.registered = false;

BL.registration.getModalHeight = function() {
    return BL.registration.static_modal_height;  
};

BL.registration.schoolform = function(){
    var input = J('#user-zip').val();
    var re = /^\d{5}([\-]\d{4})?$/;
    //if the zip code looks ready
    if ((re.test(input))){
        J('#find_btn').removeClass('selected'); 
        //send an show the image, send an ajax
        J('#user-zip').attr('readonly' , true);
        // J('#zip-submit').hide();
        J('#zip-loading').css('visibility', 'visible');
        var url = '/schools/schoolsbyzip_registration/' + input;
        J.get( url , function( data ){
            J('#user-zip').removeAttr('readonly');
            J('#zip-loading').css('visibility', 'hidden');
            // J('#zip-submit').show();
            J('#custom-school-fields').hide();
            J('#add-custom-school-div').show();
            J('#school-tip').show();
            J('#school-list').show().css('visibility', 'visible').html( data ); 
        });
    } else {
        J('#find_btn').addClass('selected'); //grey out the find button if there are <> 5 characters
    }
}

/*
    initialization called once, here, after page load
*/
BL.registration.init = function() {

    J('#close-confirmation').live( 'click', function( e ) {
        e.preventDefault();

        J.colorbox.close();
    });

    J("#add-custom-school").live( 'click', function( e ) {
        e.preventDefault();

        J('#add-custom-school-div').hide();
        J('#school-list').hide();
        J('#custom-school-fields').show();
        J('#school-name').focus();
    });

    J("#signup-form").live( 'submit', function( e ) {
        e.preventDefault();

        //capture the current url to redirect user to where they came from
        var registered_page = encodeURIComponent(window.location);
        J('#registered-page').val( registered_page );

        // get form elements
        var fnElem = J('#first-name');
        var lnElem = J('#last-name');
        var emailElem = J('#email');
        var passElem = J('#registration-password');

        // remove error classes if any
        fnElem.removeClass('form-error');
        lnElem.removeClass('form-error');
        emailElem.removeClass('form-error');
        passElem.removeClass('form-error');
        // blank out error message if any
        J('#name-error').text('');
        J('#email-error').text('');
        J('#password-error').text('');

        // check form values for empty
        var hasEmpty = false;
        if (J.trim(fnElem.val()) === '') {
            fnElem.addClass('form-error');
            J('#name-error').text('Please enter your first and last name.');

            hasEmpty = true;
        } 
        if (J.trim(lnElem.val()) === '') {
            lnElem.addClass('form-error');
            J('#name-error').text('Please enter your first and last name.');

            hasEmpty = true;
        }
        if (J.trim(emailElem.val()) === '') {
            emailElem.addClass('form-error');
            J('#email-error').text('Please enter your email.');

            hasEmpty = true;
        }
        if (J.trim(passElem.val()) === '') {
            passElem.addClass('form-error');
            J('#password-error').text('Please enter a password.');

            hasEmpty = true;
        }
        // return if there are empties adjust height for any errors
        if (hasEmpty) {
            return false;
        }

        //activity indicator
        J('#signup-submit').addClass('btn-disabled').attr('disabled', 'disabled');
        J('#signup-loading').show();

        // // Submit the form
        var action_url = J(this).attr('action');
        J.post(action_url, J(this).serialize(), function( data ) {
            var a_data = { "reg-version": 2 , "source" : window.location , "label" : window.isDeepLink || null };
            BL.registration.logToMixAndKISS( 'Submit Registration' , a_data );
            if (data == 1) {
                BL.registration.registered = true;
                J('#inner').text('Thanks!');
                J('.your-email').text(emailElem.val());
                J('#signup-form-wrapper').hide();

                if ( J('#downloading').val() === '' ) {
                    J('#confirmation-landing').show();
                } else {
                    J('#confirmation-download').show();
                }

                a_data = { "reg-version": 2 , "source" : window.location , "label" : window.isDeepLink || null };
                BL.registration.logToMixAndKISS( 'Complete Registration' , a_data );
            } else {
                // Display the validation errors returned
                J('#signup-loading').hide();
                J('#signup-submit').removeClass('btn-disabled').removeAttr('disabled');


                var json_result =  jQuery.parseJSON(data);
                if (json_result.first_name) {
                    J('#first-name').addClass('form-error');
                    J('#name-error').text('Please enter your first and last name.');
                } 
                if (json_result.last_name) {
                    J('#last-name').addClass('form-error');
                    J('#name-error').text('Please enter your first and last name.');
                }
                if (json_result.email) {
                    J('#email').addClass('form-error');
                    J('#email-error').text(json_result.email);
                }
                if (json_result.password) {
                    J('#registration-password').addClass('form-error');
                    J('#password-error').text(json_result.password);
                }
            }
        });

        return false;
    });

     J('#user-zip').live( 'keyup', function( e ) {
        BL.registration.schoolform(); 
     }).live( 'keypress', function( e ) { // only keypress can we prevent form from submitting
        if (e.which === 13) {
            return false;
        }
     });

    J('#user-zip').removeAttr('readonly' );
    J('#user-zip').val('');
    J('#zip-submit').live('click' , function ( e ){
        e.preventDefault();
        BL.registration.schoolform(); 
        return false;
    });
}

BL.registration.attachTo = function( selector ) {
    // initialized onclick so it can get reopened in the last height set
    J( selector ).live('click', function(e) {
        e.preventDefault();

        var _selector = J(this);

        // make sure the log in form is hidden, and the sign up form is shown
        J('#signup-form-wrapper').show();

        J.colorbox( { 
            width:"600px"
            , height: BL.registration.getModalHeight()
            , inline: true
            , href: '#signup-container'
            , transition: "none"
            , opacity: .5
            , title: '<div id="inner">Sign up for your <strong><em>free</em></strong> BetterLesson.com account</div>'
            , close: "x"
            , onClosed : function() {
                if (BL.registration.registered) {
                    window.location.reload();
                }
            }
            , onComplete :  function() {
                // fixes
                J('#colorbox').css({ 'top' : '50px', 'position' : 'fixed' })
            }
            , onOpen : function (){
                // this code was pulled from getstarted modal
                // segments against the DOM selector so we know what element was clicked on a page
                //track the initial open as a click event
                var source = '';
                if (_selector.hasClass('download')) {
                    source = 'Big Green Download';
                } else if (_selector.hasClass('from-deep-link')) {
                    source = 'Get Started Deep Link';
                } else if (_selector.hasClass('from-old-landing')) {
                    source = 'Get Started Green Button (Blue landing page)';
                } else if (_selector.hasClass('from-new-landing')) {
                    source = 'Get Started Red Button (Public Search Landing)';
                } else {
                    source = 'source undetermined';
                }
                
                if ( window.pageTracker ) { pageTracker._trackEvent( 'Registration', source , window.isDeepLink || null ); }
                var a_data = { "reg-version": 2 , "source" : source , "label" : window.isDeepLink || null };
                BL.registration.logToMixAndKISS( 'Registration Click' , a_data );
            }
        } );

        // if has class download then set value that tell back end to 
        // start the download after activation
        if ( _selector.hasClass('download') ){
            //TODO this will change depending on what page it's on. 
            var controller = J('#bl_curriculum_controller').val();
            var downloadurl = '';
            if (controller == 'lessonfiles'){
                downloadurl = '/lessonfiles/download/' + J('#bl_curriculum_item_id').val() ;
            } else if (controller == 'lessons'){
                downloadurl = '/lessons/downloadAll/' + J('#bl_curriculum_item_id').val() ;
            }
            J('#downloading').val( downloadurl );

            // set congratulation screen information about the download
            J('#download-title').text(' ' + J('.heading-item-type').text() + ' ' + J('.heading-title-holder').text());
        } else {
            // reset download values
            J('#downloading').val('');
            J('#download-title').text('');
        }
    } );
};

// INIT
J(document).ready(function() {
    BL.registration.init();

    BL.registration.attachTo(".registration-modal");

    // initialize placeholder plugin for sign up container
    try {
        J('#signup-container input').placeholder();
    } catch(e){ }
    
});

/** Log to both
 */
BL.registration.logToMixAndKISS = function( str, data ) {
    BL.registration.logToMixpanel( str, data );
    BL.registration.logToKISSmetrics( str, data );
}

/** Log to mixpanel or debug.
 */
BL.registration.logToMixpanel = function( str, data ) {
    try {
        if( window.mpq ) {
            mpq.track( str, data );
        } else {
            bl_debug( null, "mpq.track( \"" + str + "\", "+JSON.stringify(data)+" );", "console" );
        }
    } catch (e) {
        ;
        //Do nothing - this error occurrs if there was trouble loading KISSmetrics or with the JSON object
        //bl_debug(e, 'KissMetricsContentView_trackAttempt');
    }
}

/** Log to kissmetrics or debug.
 */
BL.registration.logToKISSmetrics = function( str, data ) {
    try {
        if( window._kmq ) {
            _kmq.push(['record', str, data]);
        } else {
            bl_debug( null, '_kmq.push([ "record", "'+str+'", '+JSON.stringify(data)+' ])', "console" );
        }
    } catch (e) {
        ;
        //Do nothing - this error occurrs if there was trouble loading KISSmetrics or with the JSON object
        //bl_debug(e, 'KissMetricsContentView_trackAttempt');
    }
}

