var ControlledAccess = new Class({
    Implements: [Options, Events],
    options: {
        startJobtype:'store',
        cookieName:'benefit',
        rejectedId:'rejected',
        jobtypeClass:'radio',
        hiddenJobtypeClass:'styled',
        responseId:'replace',
        questionId:'question',
        questionMsgId:'question-msg',
        jobtypeId:'jobtype',
        submitJobtypeId:'sub_jobtype',
        answerClass:'answer',
        contextTitleId:'leftheader_img',
        storeQuestionsArray:false,
        fieldQuestionsArray:false,
        officeQuestionsArray:false,
        templatePath: '/index?action=showView&tpl={jobtype}-userform.json',
        titleImagePath:false,
        bodyImagePath:false,
        altTitleImagePath:false,
        onShowContent:function() {
            var jtype = Cookie.read('current_jobtype');
            if(this.response) {
                var reps = {jobtype: jtype};
                var url = this.templatepath.substitute(reps); 
                this.response.load(url);
            }
            return false;
        },
        onFailedQuestion:false
    },
    initialize: function(options) {
        try {
            // (this) inside event functions.
            ref = this;
            this.setOptions(options);

            // Question
            this.currentQuestion = 0;
            this.currentJobType  = this.options.startJobtype;
            this.cookieName      = this.options.cookieName;
            this.lastAnswer      = false;
            
            // Yes/No
            this.question        = $(this.options.questionId);
            // Question Text
            this.question_msg    = $(this.options.questionMsgId);
            // Message when answer does not compute.
            this.rejected        = $(this.options.rejectedId);
            // Form that holds the radio tob to switch jobs.
            this.jobtype         = $(this.options.jobtypeId);
            // Div for the secret content to be loaded into.
            this.response        = $(this.options.responseId);
            // Button to submit the job switch.
            this.sub_jobtype     = $(this.options.submitJobtypeId); 
            // The job switch radio class
            this.jobtypes        = $$('.' + this.options.jobtypeClass);
            // These are Mikes' radio images.
            this.answers         = $$('.' + this.options.answerClass);
            // These are the actual (hidden) radios.
            this.jobtypesradio   = $$('.' + this.options.hiddenJobtypeClass);
            this.contexttitle    = $(this.options.contextTitleId); 

            // template path for final ajax request.
            this.templatepath = this.options.templatePath;

            // Urls for generating image text.
            this.title_imgtext = this.options.titleImagePath;
            this.body_imgtext = this.options.bodyImagePath;
            this.resulttitle_text = this.options.altTitleImagePath;

            // Our question arrays.
            this.stockQuestions  = this.options.storeQuestionsArray;
            this.fieldQuestions  = this.options.fieldQuestionsArray;
            this.officeQuestions = this.options.officeQuestionsArray;

            this.question.setStyle('display','none');

            // Add event to yes/no
            this.answers.each(function(el) { 
                var myanswer =  el.get('rel');
                el.setStyle('cursor', 'pointer'); 
                el.addEvent('click', ref.answerQuestion.bindWithEvent(ref, myanswer));
            });

            // Add event to radio images to change job type..
            this.jobtypes.each(function(el) {
                el.addEvent('click', ref.setJobtype.bindWithEvent(ref));
            });

            // Check the cookie to see if we have already started
            // We will need to update header images and image checkboxes/radios.
            cookie = Cookie.read(this.cookieName);
            if(cookie && cookie[0] && cookie[1] && cookie[2]) {
                cookie = cookie.split(',');
                currentQuestion = cookie[0];
                currentJobType = cookie[1];    
                lastAnswer  = cookie[2];
                if($chk(currentJobType) && $chk(lastAnswer) && $chk(currentQuestion)) { 
                    this.currentJobType = currentJobType;
                    this.currentQuestion = currentQuestion;
                    this.lastAnswer = lastAnswer;
                    Cookie.write('current_jobtype', currentJobType);

                    // We need to set Mikes radio image and the sibling radio as checked.
                    this.jobtypesradio.each(function(el) {
                        if(el.get('value') == currentJobType) {
                            el.set('checked',true);
                            el.getPrevious('span').setStyle("background-position", "0pt -50px");
                        }
                    });        

                    // Now update the header image.
                    if(this.contexttitle) {
                        var reps = {insert_text: currentJobType + "%20Registration"};
                        var header_text = this.title_imgtext.substitute(reps);
                        this.contexttitle.set("src", header_text);                 
                    }

                    this.answerQuestion(this, lastAnswer); 
                }
            }

            // Alter the cursor, set event for next job button..
            this.sub_jobtype.setStyle('cursor', 'pointer'); 
            this.sub_jobtype.addEvent('click', this.nextQuestion.bindWithEvent(this));

            return false;
        } catch(e) {
            return false;
        }
    },
    answerQuestion:function(ref, resp) {
        try {
            this.question.setStyle('display','block');
            this.question_msg.setStyle('display','block');
            $('btop').setStyle('display','block');
            $('bbottom').setStyle('display','block');
            this.currentQuestion = this.checkCurrentQValue(this.currentQuestion);
            var questions = this.getQuestions();
            var current = questions[this.currentQuestion];
            this.currentJobType = Cookie.read('current_jobtype');
            var save = new Array(this.currentQuestion, this.currentJobType, resp);
            Cookie.write(this.cookieName, save);         

            // false = failed (get 'reject' property)
            // true - passed.
            // Integer - get the next question using the int as index.
            if(current[resp] === false) {
                this.question.setStyle('display','none');
                this.question_msg.setStyle('display','none');
                var reps = {insert_text: current.reject};
                var reject_text = this.body_imgtext.substitute(reps);
                // Use the imgText generator for pretty text..           
                this.rejected.set('html', "<img src='" + this.resulttitle_text + "' /><br/><img align='absmiddle' src='" + reject_text + "' />");
                this.rejected.setStyle('display','block');
                // Reset.
                this.currentQuestion = 0;
            } else if(current[resp] === true) {
                // Allow the designer to (safely) use  their callback.
                return this.fireEvent('onShowContent', [this]);
            } else {
                // Was an integer - Get the next question.
                this.currentQuestion = current[resp];
                return this.nextQuestion(this);                 
            }
        } catch(e) {
            return false;
        }    
    },
    nextQuestion:function(ref) {
        try {
            this.currentQuestion = this.checkCurrentQValue(this.currentQuestion);
            this.questions = this.getQuestions();
            var reps = {insert_text: this.questions[this.currentQuestion].title};
            var question_text = this.body_imgtext.substitute(reps);
            this.question_msg.set("html", "<img align='absmiddle' src='" + question_text + "' />");                 
            this.rejected.setStyle('display','none');
            this.question.setStyle('display','block');
            this.question_msg.setStyle('display','block');
            $('btop').setStyle('display','block');
            $('bbottom').setStyle('display','block');
        } catch(e) {
            return false;
        }
    },
    setJobtype:function(ref) {
        // User has chosen a new job type - Reset everything and save the cookie.
        try {
            var newjobtype=ref.target.getNext().get('value');
            
            if(newjobtype == false || newjobtype == null) {
            	alert('No job type !!');
            }            
            
            if(newjobtype) {
                var save = new Array(0, newjobtype, false);
                Cookie.write(this.cookieName, save);                                
                Cookie.write('current_jobtype', newjobtype);
                // Switch the context header image.
                if(this.contexttitle) {
                    var reps = {insert_text: newjobtype + "%20Registration"};
                    var header_text = this.title_imgtext.substitute(reps);
                    this.contexttitle.set("src", header_text);                 
                }
                // Reset Question.
                this.currentQuestion = 0;
                // Call first question.
                return this.nextQuestion(this); 
            }
        } catch(e) {
            return false;
        } 
    },
    getQuestions:function() {
        try {
            var ref = this;
            var questions = false;
            this.jobtypesradio.each(function(el) {
                if(el.get('checked')) {
                    ref.currentJobType = el.get('value');
                }
            });

            // Get the questions set
            if(ref.currentJobType == 'store')
                questions = this.stockQuestions; 
            if(ref.currentJobType == 'field')
                questions = this.fieldQuestions;
            if(ref.currentJobType == 'office')
                questions = this.officeQuestions;                 

            return questions;  

        } catch(e) {
            return false;
        }                             

    },
    checkCurrentQValue:function(v) {
        if(!$chk(v) || v < 0) return 0;             
        return v;
    }
});
