﻿//everything with _ in front whether it's a variable or function, they're meant to be private
//so please don't use it outside of the class
var Prearrival = new Class({
    Implements: [Options, Events],
    options:
    {
        sections: [],       //ex: 'guest', 'welcome', 'dining', 'spa', 'activities', 'checkOut'
        reqFields: [],
        url: 'prearrival_submit.aspx',
        form: null,
        imagePath: '',
        disableScreenBG: '#f0f0f0',
        advancedBooking: null,  //will take an object {name: inputField, day: number of days required to book online}
        _currSection: '',   //ex: 'guest'
        _isBusy: false      //check to see if the form is being processed
    },
    initialize: function(options)
    {
        //init the options passing in when an object of this class is created
        this.setOptions(options);
        
        //init currSection to be the first one in sections
        this.options._currSection = this.options.sections[0];
        
        //re-set form into an ojb
        this.options.form = $(this.options.form);
        
        //attach event on to the form
        this.options.form.addEvent('submit', function(e){
            this._toggleSection(this.options.sections[this.options.sections.length - 1]);
        
            new Event(e).stop();
            //this._validate(this.options.form);
            this._processForm();
        }.bind(this));
        
        //init sections events
        this._initSections();
        
        //init disable screen so we can use it later
        this._initDisableScreen();
    },
    
    //init each section with mouseover, out, and click
    _initSections: function()
    {
    
        this.options.sections.each(function(item)
        {
            var img = $(item + 'Img');
            //add pointer cursor to the section image
            img.setStyle('cursor', 'pointer');
            
            //init mouse over, out and click for each item
            img.addEvents({
                click: function()
                {
                    if(!this.options._isBusy)
                    {
                        if($('disableScreen'))
                            this._enableScreen();
                            
                        this._toggleSection(item);
                    }
                    
                }.bind(this),
                //mouseenter is an overwritten mouseover function
                mouseenter: function()
                {
                    this._toggleImg(item, true);
                }.bind(this),
                //mouseleave is an overwritten mouseout function
                mouseleave: function()
                {
                    this._toggleImg(item, false);
                }.bind(this)
            });
            
            
        }.bind(this));
        
    },
    
    //changes the image according to mouse over or out on a section image
    _toggleImg: function(ele, isRoll)
    {
        if(this.options._currSection == ele)
            return;
            
        if(isRoll)
            $(ele + 'Img').setProperty('src', this.options.imagePath+ele+'_roll.gif');
        else
            $(ele + 'Img').setProperty('src', this.options.imagePath+ele+'.gif');
    },
    
    //switches between section
    _toggleSection: function(ele)
    {
        var currSection = this.options._currSection;
        
        if($(currSection))
        {
            $(currSection).setStyle('display', 'none');
            $(currSection + 'Img').setProperty('src', this.options.imagePath + currSection + '.gif');
        }
        
        $(ele + 'Img').setProperty('src', this.options.imagePath + ele + '_roll.gif');
        
        //problem here: google chrome and safari won't retrieve the width and height
        //unless it's inline-table
        $(ele).setStyle('display', 'block');
        this.options._currSection = ele;
    },
    
    //create a generic disable screen and hide it until we need it
    //it'll cover over a region based on w, h, x, y
    _initDisableScreen: function()
    {
        var div = new Element('div', {
            id: 'disableScreen',
            styles:
            {
                position: 'absolute',
                left: 0,
                top: 0,
                zIndex: 999,
                backgroundColor: this.options.disableScreenBG,
                opacity: 0,
                color: '#ff4040'
                
            }
        }).inject($(document.body));
        
        var table = new Element('table', {
            width: '100%',
            height: '100%'
        }).inject(div);
        var tbody = new Element('tbody').inject(table);
        var tr = new Element('tr').inject(tbody);
        var td = new Element('td', {styles:{color: '#ff4040'}}).inject(tr);
        var divText = new Element('div', {
            id: 'disableText', 
            styles:{padding: 20}
        }).inject(td);
    },
    
    //takes away the the disable screen
    _enableScreen: function()
    {
        $('disableScreen').setStyle('opacity', 0);
        $('disableText').set('text', '');
    },

    //disable the screen of the passed in element
    //based on that element w, h, x, y
    _disableScreen: function(id)
    {
        var container = $(id);
        
        $('disableScreen').setStyles({
            opacity: 0.9,
            //weird on my machine need -1 only VPC doesn't
            left: Browser.Engine.gecko ? container.getPosition().x : container.getPosition().x, //FF is not position correctly and need to be 1px left, not sure why - Kevin
            top: container.getPosition().y,
            width: container.getWidth(),
            height: container.getHeight(),
            lineHeight: "100%"
        });
        
    },
    
    //this is a re-written version of Jim's validate fucntion, basically it will do the same thing
    //but instead of return true or false, it will return a string or empty string
    //for displaying purpose
    _validate: function(form)
    {
        this._disableScreen(this.options.sections[this.options.sections.length - 1]);
    
        //not worth it to build out using element
        var html = '<strong>Please fill in the following required fields:</strong> <ul>';
        var msg = '';
        
        this.options.reqFields.each(function(item){
            var temp = '';
            
            switch(item.type)
            {
                case 'string': 
                    temp = stringCheck(form, item.name, true, item.length, item.display); break;
                case 'email':
                    temp = checkEmail(form, item.name, true, item.length, item.display); break;
                case 'phone':
                    temp = checkPhone(form, item.name, true, item.length, item.display); break;
                case 'checkbox':
                    if(!$(item.name).checked) 
                        temp = "Please put a check for " + item.display; break;
            }
            msg += temp != '' ? '<li style="color:#ff4040">' + temp + '</li>' : '';
        });
        
        if(this.options.advancedBooking)
        {
            var now = new Date();
            var today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
            today.setDate(today.getDate() + this.options.advancedBooking.day)
            var arrivalDate = new Date($(this.options.advancedBooking.name).value);
            
            if(today > arrivalDate)
                msg += '<li style="color:#ff4040">A 24-hour advance notice is required for online processing. Please contact the concierge at 831-667-2331 ext. 225 to make arrangements so that we may expedite all preparations.</li>';
            
        }
        
        html += msg + '</ul>';
        
        if(msg == '')
            return true;
        else
        {
            $('disableText').set('html', html);
            return false;
        }
    },
    
    _processForm: function()
    {
        if(!this._validate(this.options.form))
            return false;
        
        var processHtml = '<div style="text-align:center">Processing your submission...<br/><img src="images/loader.gif"></div>' ;
        $('disableText').set('html', processHtml);
        
        
        
        //the request is starting to put a busy marker here
        this.options._isBusy = true;
        
        var request = new Request.JSON({
            url: this.options.url,
            onComplete: function(response)
            {
                //if there is no error then print out the thank you text
                if(response && response.error == '')
                {
                    $('disableText').set('html', $('thankyou').get('html'));
                }
                //else if the error is there then print it out
                else if(response && response.error != '')
                {
                    this._printError('disableText', response.error);
                }
                //if response is not there that means the submit url is incorrect
                else
                {
                    this._printError('disableText', 'There was an error with your request.  Please try again, if the problem persists please contact the administrator.');
                }
                this.options._isBusy = false;
            }.bind(this),
            onFailure: function(error)
            {
                //report or bury the error
                this._printError('disableText', 'There was an error with your request.  Please try again, if the problem persists please contact the administrator.');
                this.options._isBusy = false;
            }.bind(this)
        });
        
        //there is a problem with this form, since we don't want it to be runat="server" but the form tag is
        //in the master page, so I have no control over it.  Therefore, I have to get the data manually
        //and post it using ajax form.
        
        
        (function(){
            request.post(this.options.form);
        }).delay(1000, this);
        
    },
    
    _printError: function(id, msg)
    {
        $(id).set('html', '<div style="text-align:center">' + msg + '</div>');
    }
    

});


