// - ///////////////////////////////////////////////////////////////////////
// - BE BASE MODULE
// - ///////////////////////////////////////////////////////////////////////
//fields
beBaseModule.prototype._transport;
beBaseModule.prototype._channelId = 'site';

function beBaseModule() {}

beBaseModule.prototype.initialize = function(transport){
	this._transport = transport;
	
	//configure selected tab
	var location = window.location.pathname;
	
	if($('headerProviders') != null){
	    if(location.indexOf('/providers/') != -1){
	        $('headerProviders').addClassName('selected');
	    }else if(location.indexOf('/courses') != -1){
	        $('headerCourses').addClassName('selected');	    
	    }else if(location.indexOf('/topics/') != -1 || location.indexOf('/articles/') != -1){
	        $('headerTopics').addClassName('selected');	    	    
	    }else if(location.indexOf('/assessment/') != -1){
	        $('headerAssessment').addClassName('selected');	    	    
	    }else {
	        $('headerHome').addClassName('selected');
	    }
	}
	
	//check if we have the provider search on the homepage
	if($('dirSearch') != null){
	    this.homeConfigure();
	}
};

beBaseModule.prototype.homeConfigure = function(){
    $('dirSearch').observe('click', this.homeProviderSearchSubmit.bind(this));
    $('dirZip').observe('keypress', this.homeProviderSearchKeyPress.bind(this));
    $('dirZip').observe('focus', function(){$('dirZip').value = '';});
};

beBaseModule.prototype.homeProviderSearchKeyPress = function(event){
    switch(event.keyCode){
        case Event.KEY_RETURN: {
            this.homeProviderSearchSubmit(null);
            break;
        }
        default:{
            break;
        }
    }
};

beBaseModule.prototype.homeProviderSearchSubmit = function(event){    
    //take the value entered which is assumed to be a zip, do some light
    //validation to ensure proper zip format and then redirect to a page by zip
    var zip = $('dirZip').value;
    var group = $('dirGroup').value;
    
    if(zip.length < 5 || zip.length > 5){
        alert('Zip code should be 5 numbers in length');
    }else if(isNaN(zip)){
        alert('Zip code should only include numbers');
    }else{
        if(group != ''){
            window.location = '/providers/us/' + group + '/zip/' + zip + '/';
        }else{
            window.location = '/providers/us/zip/' + zip + '/';
        }
    }    
};

// - ///////////////////////////////////////////////////////////////////////
// - ABOUT MODULE
// - ///////////////////////////////////////////////////////////////////////
//fields
beAboutModule.prototype._transport;
beAboutModule.prototype._channelId = 'site.shared';

function beAboutModule() {}

beAboutModule.prototype.initialize = function(transport){
	this._transport = transport;
	var me = this;
	var location = window.location.toString();	

    if($('railAbout') != null){
	    if(location.indexOf('/management/') != -1){
	        $('liManagement').addClassName('active');
	    }else if(location.indexOf('/contact/') != -1){
	        $('liContact').addClassName('active');
	    }else if(location.indexOf('/testimonials/') != -1){
	        $('liTestimonials').addClassName('active');
	    }else{
	        $('liAbout').addClassName('active');
	    }
	}
		
	//configure contact form
	if($('contactForm') != null){$('contactSubmit').observe('click', this.contactFormSubmit.bind(this));}
};

beAboutModule.prototype.contactFormSubmit = function(event){
    event.stop();
    var errorList = '';
    
    if($('contactName').value == ''){errorList += '<li>Enter your name</li>';}
    if($('contactEmail').value == ''){errorList += '<li>Enter your email address</li>';}
    if($('contactPhone').value == ''){errorList += '<li>Enter a phone number to call</li>';}
    if($('contactBestTimeToCall').value == ''){errorList += '<li>Enter the best time to call</li>';}
    if($('contactComments').value == ''){errorList += '<li>Enter your comments and questions</li>';}
    
    if(errorList != ''){
        $('contactError').update('<ul>' + errorList + '</ul>');
        $('contactError').show();
    }else{
        $('contactError').hide();
        
        var request = {
            name : $('contactName').value,
            email : $('contactEmail').value,
            phone : $('contactPhone').value,
            time : $('contactBestTimeToCall').value,
            comments : $('contactComments').value,
            path : window.location.toString()
        };
        
        this._transport.transmitRequest(this._channelId, 'setcontact', request, this.contactFormSubmitCompleted.bind(this));
    }
};

beAboutModule.prototype.contactFormSubmitCompleted = function(res){
    if(res.result == 'ok'){
        $('contactForm').hide();
        $('contactSuccess').show();
        
        //track analytics goal
        pageTracker._trackPageview('/about/contact-completed');            
    }else{
        $('contactError').update(res.message);
        $('contactError').show();        
    }
};

// - ///////////////////////////////////////////////////////////////////////
// - SINUP MODULE
// - ///////////////////////////////////////////////////////////////////////
//fields
beSignupModule.prototype._transport;
beSignupModule.prototype._channelId = 'site.signup';

function beSignupModule() {}

beSignupModule.prototype.initialize = function(transport){
	this._transport = transport;
	var location = window.location.toString();
	
	if(location.indexOf('/signup/signup-') != -1 && location.indexOf('http://www.centralreach.com') != -1){
	    window.location = location.replace('http://','https://');
	}
	
	//configure the tabs if available
	if($('tabs') != null){
	    if(location.indexOf('features-clients') != -1){
	        $('tabClients').addClassName('active');
	    }else if(location.indexOf('features-providers') != -1){
	        $('tabProviders').addClassName('active');
	    }else{
	        $('tabOverview').addClassName('active');
	    }
	}
	
	//configure help tips
	var me = this;
	$$('.tip').each(function(tip){
	    tip.observe('mouseover', me.showTip.bind(me));
	    tip.observe('mouseout', me.hideTip.bind(me));
	});
	
	//configure if signup form available
	if($('signupform') != null){    
	    if(location.indexOf('signup-clients') != -1){
	        $('signupTypeId').value = 20;
	        $('signupformheaderclient').show();
	        $('signupClient').show();
	    }else{
	        $('signupTypeId').value = 572;
	        $('signupformheaderprovider').show();
	        $('signupformtrialinfo').show();
	        $('signupProvider').show();
	        
	        var date = new Date();
	        date.setDate(date.getDate() + 30);
	        $('signupTrialDate').update(date.toDateString());
	    }
	    
	    $('signupCreate').observe('click', this.createAccount.bind(this));
	    $('recaptcha_response_field').observe('keyup', this.createAccountEnter.bind(this));
	}
};

beSignupModule.prototype.showTip = function(event){
    var e = event.element();
    var x = e.viewportOffset().left-280;
    var y = e.viewportOffset().top-50;
    var t = $('toolTip');
    
    t.setStyle({'position':'absolute','left':x + 'px','top':y + 'px'});
    t.update(event.element().readAttribute('content'));
    t.show();
};

beSignupModule.prototype.hideTip = function(event){
    $('toolTip').update();
    $('toolTip').hide();
};

beSignupModule.prototype.createAccountEnter = function(event){
   switch(event.keyCode){
        case Event.KEY_RETURN: {
            this.createAccount(event);
            break;
        }
        default:{
            break;
        }
    }    
};

beSignupModule.prototype.createAccount = function(event){
    event.stop();
    var errorMsg = '';
    var typeId = $('signupTypeId').value;
    
    $('signupError').hide();
    $('signupform').select('input').each(function(input){input.setStyle({'border':'solid 1px #bbb'});});
    
    if(typeId == 20){
        if($('signupClientFirstName').value == ''){this.markInputError('signupClientFirstName');errorMsg += '- enter the clients first name\n';}
        if($('signupClientLastName').value == ''){this.markInputError('signupClientLastName');errorMsg += '- enter the clients last name\n';}  
        if($('signupGuardianFirstName').value == ''){this.markInputError('signupGuardianFirstName');errorMsg += '- enter the guardians first name\n';}
        if($('signupGuardianLastName').value == ''){this.markInputError('signupClientLastName');errorMsg += '- enter the guardians last name\n';}             
    }else{
        if($('signupFirstName').value == ''){this.markInputError('signupFirstName');errorMsg += '- enter your first name\n';}
        if($('signupLastName').value == ''){this.markInputError('signupLastName');errorMsg += '- enter your last name\n';}
    }
    
    if($('signupEmail').value == ''){this.markInputError('signupEmail');errorMsg += '- enter your email\n';}    
    if($('signupUsername').value == ''){this.markInputError('signupUsername');errorMsg += '- enter a username\n';}
    if($('signupPassword').value == ''){this.markInputError('signupPassword');errorMsg += '- enter a password\n';}    
    if($('signupPasswordConfirm').value == ''){this.markInputError('signupPasswordConfirm');errorMsg += '- confirm your password\n';}
    if($('recaptcha_response_field').value == ''){this.markInputError('recaptcha_response_field');errorMsg += '- enter the words seen in the image\n';}
    if($('signupPassword').value != $('signupPasswordConfirm').value){this.markInputError('signupPassword'); this.markInputError('signupPasswordConfirm');errorMsg += '- your passwords don\'t match\n';}    
    
    if(this.isValidEmail($('signupEmail').value) == false && errorMsg.length == 0){this.markInputError('signupEmail');errorMsg += '- your email appears to be invalid\n';}
    if($('signupPassword').value.length < 6 && errorMsg.length == 0){this.markInputError('signupPassword');errorMsg += '- password must be at least 6 characters in length\n';}
    
    if(errorMsg.length > 0){
        alert('Please complete the following:\n\n' + errorMsg);
    }else{
        $('signupCreateBttn').hide();
        $('signupCreatingBttn').show();
    
        var request = {
            typeId:typeId,
            firstName:$('signupFirstName').value,
            lastName:$('signupLastName').value,
            clientFirstName:$('signupClientFirstName').value,
            clientLastName:$('signupClientLastName').value,
            guardianFirstName:$('signupGuardianFirstName').value,
            guardianLastName:$('signupGuardianLastName').value,                        
            email:$('signupEmail').value,
            username:$('signupUsername').value,
            password:$('signupPassword').value,
            recaptcha_challenge_field : $('recaptcha_challenge_field').value,
            recaptcha_response_field : $('recaptcha_response_field').value
        };
        
        this._transport.transmitRequest('site.signup', 'createaccount', request, this.createAccountCompleted.bind(this));
    }
};

beSignupModule.prototype.createAccountCompleted = function(objResponse){        
    var err = '';
    $('signupCreatingBttn').hide();
    $('signupCreateBttn').show();

    if(objResponse.captcha == false){    
        this.markInputError('recaptcha_response_field');
        err = 'The two words don\'t match the image shown';
    }else if(objResponse.missingField != null && objResponse.missingField == true){
        err = 'Please ensure all fields are filled in';        
    }else if(objResponse.emailTaken != null && objResponse.emailTaken == true){
        this.markInputError('signupEmail');
        err = 'The email address is already associated with an active account\n\nUse a different email address or use the "Forgot login" option on the login page';
    }else if(objResponse.usernameTaken != null && objResponse.usernameTaken == true){
        this.markInputError('signupUsername');
        err = 'Your desired username is already taken.\n\nPlease choose a different username and try again';
    }
    
    if(err.length == 0){
        $('signupform').hide();
        $('signupsuccess').show();
        
        if($('signupTypeId').value == 20){
            pageTracker._trackPageview('/signup/signup-clients');     
        }else{
            pageTracker._trackPageview('/signup/signup-providers');     
        }
    }else{
        alert(err);
        $('signupError').update(err);
        $('signupError').show();
        Recaptcha.reload();
    }
};

beSignupModule.prototype.markInputError = function(inputId){
    $(inputId).setStyle({'border':'solid 2px red'});
};

beSignupModule.prototype.isValidEmail = function(email){
	var good="@_-.+:/ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
	var upper=email.toUpperCase()
	var valid=true;	
	for(x=0; x>email.length; x++){c=upper.charAt(x);for(y=0; y<good.length; y++){if(c==good.charAt(y)){break;}}if(y==good.length){valid=false;break;}}	
	if (!valid || email.length < 7 || email.indexOf("@") == "-1" || email.indexOf(".") == "-1" || email.indexOf("@") != email.lastIndexOf("@")) {
	    return false;
	}else{
	    return true;
	}
};

// - ///////////////////////////////////////////////////////////////////////
// - ASSESSMENT MODULE
// - ///////////////////////////////////////////////////////////////////////
//fields
beAssessmentModule.prototype._transport;
beAssessmentModule.prototype._channelId = 'site.shared';

function beAssessmentModule() {}

beAssessmentModule.prototype.initialize = function(transport){
	this._transport = transport;
	
    //configure contact form
	if($('contactAssessmentForm') != null){$('contactSubmit').observe('click', this.contactFormSubmit.bind(this));}
};

beAssessmentModule.prototype.contactFormSubmit = function(event){
    event.stop();
    var errorList = '';
    var concerns = new Array();
    var services = new Array();
    
    $('concerns').select('input').each(function(input){if(input.checked){concerns.push(input.value);}});
    $('services').select('input').each(function(input){if(input.checked){services.push(input.value);}});
    
    if($('contactAge').value == ''){errorList += '<li>Select the individuals age</li>';}
    if(concerns.length == 0){errorList += '<li>Select at least one concern</li>';}
    if(services.length == 0){errorList += '<li>Select at least one service</li>';}
    if($('contactName').value == ''){errorList += '<li>Enter your name</li>';}
    if($('contactEmail').value == ''){errorList += '<li>Enter your email address</li>';}
    if($('contactPhone').value == ''){errorList += '<li>Enter a phone number to call</li>';}
    if($('contactComments').value == ''){errorList += '<li>Enter your comments and questions</li>';}
    
    if(errorList != ''){
        $('contactError').update('<ul>' + errorList + '</ul>');
        $('contactError').show();
    }else{
        $('contactError').hide();
        
        var request = {
            name : $('contactName').value,
            email : $('contactEmail').value,
            phone : $('contactPhone').value,
            comments : $('contactComments').value,
            age : $('contactAge').value,
            concerns : concerns.join(','),
            concernsOther : $('contactConcernOther').value,
            services : services.join(','),
            servicesOther : $('contactServicesOther').value,
            insurance : $('contactInsurance').value
        };
        
        this._transport.transmitRequest(this._channelId, 'setassessmentcontact', request, this.contactFormSubmitCompleted.bind(this));
    }
};

beAssessmentModule.prototype.contactFormSubmitCompleted = function(res){
    if(res.result == 'ok'){         
        $('contactAssessmentForm').hide();
        $('contactSuccess').show();
        window.scrollTo(0,0);
                    
        //track analytics goal
        pageTracker._trackPageview('/assessment/contact-completed');            
    }else{
        $('contactError').update(res.message);
        $('contactError').show();        
    }
};
