var TCALS = Class.create({
    currentPageIndex:0,
    pageLabel: null,
    gSoundVolume: 75,
    urlServer: null,
    quizId: null,
    previewMode: false,
    participantId: -1,
    servercmdpage: 'srvcmd.php',
    pathSoundIntro: null,
    playedIntroSound: false,
    timerTitle: '',
    mediaLoadingTimer: null,
    
    //msgs
    msgMustIntroSound: null,
    msgQuizNotExist: null,
    msgQuizInactive: null,
    msgKeyNotExist: null,
    msgKeyUsed: null,
    msgGeneralError: null,
    msgUnonload: null,
    msgRepeatNumEtudiant: null,
    msgModuleError: null,
    msgAddressModuleError: null,
    msgAnswerQuestion: null,

    
    initialize: function(){
        this.pages = new Array();
    },
    
    connect: function(){
        if((this.urlServer.substr(0,7) != 'http://') || (this.urlServer.length == 0) || (this.urlServer.replace('http://','').length == 0)){
            $('msgErreur').update(this.msgAddressModuleError);
            return;
        }
    
        var url = this.urlServer + '/' + this.servercmdpage + '?cmd=checkstatus';
        var params = {
           qidentifier: this.quizId
        };
        
        new Ajax.Request(url, {
           method: 'post',
           parameters: params,
           asynchronous: true,
           onSuccess: tcals_onConnectSuccess,
           encoding: 'ISO-8859-1'
        });
    },
    
    connectSuccess: function(transport){
        var response = transport.responseJSON;
        
        var serverMsg = response.msg;
        
        switch(serverMsg){
            case 0:
                $('msgErreur').update(this.msgQuizNotExist);
                break;
            case 1:
                //exist and active
                break;
            case 2:
                $('msgErreur').update(this.msgQuizInactive);
                break;
        }
    },
    
    auth: function(){
        //checker si sound intro played
        if(!this.playedIntroSound){
            alert(this.msgMustIntroSound);
            return;
        }
    
        //checker si numero correct
        if($F('txtNumEtudiant') != $F('txtRepeatNumEtudiant')){
            $('msgErreur').update(this.msgRepeatNumEtudiant);
            return;
        }
        //wrap en json les txt
        var params = {
            qidentifier: this.quizId,
            firstName: escape($F('txtPrenom')),
            lastName: escape($F('txtNom')),
            school: escape($F('txtEtablissement')),
            other: escape($F('txtAutre')),
            englishLevel: escape($F('lstNiveau')),
            homeLang: escape($F('lstLangue')),
            sex: escape($F('lstSexe')),
            key: escape($F('txtNumEtudiant'))
        };
        
        //ship le json a tcals
        var url = this.urlServer + '/' + this.servercmdpage + '?cmd=auth';
                
        new Ajax.Request(url, {
            method: 'post',
            parameters: params,
            onSuccess: tcals_onAuthSuccess,
            asynchronous: false
        });
    },
    
    authSuccess: function(transport){
        var response = transport.responseJSON;
       
        var serverMsg = response.msg;
        switch(serverMsg){
            case 0:
                $('pagewrapperauth').hide();
                $('pagewrapperquiz').show();
                this.participantId = response.participantId;
                $('username').update(response.username);
                
                window.onbeforeunload = tcals_onunload;
                
                if(response.questionNb == -1)
                    this.pageGoto(0);
                else
                    this.resume(response.questionNb);
                break;
            case 1:
                $('msgErreur').update(this.msgKeyNotExist);
                break;
            case 2:
                $('msgErreur').update(this.msgKeyUsed);
                break;
            case 3:
                $('msgErreur').update(this.msgGeneralError);
                break;
        }
    },
    
    newPage: function(){
        this.pages[this.pages.length] = new Page();
        
        return this.pages[this.pages.length - 1];
    },
    
    pageNext: function(isFromButton){

        if(isFromButton){

            var theCurrentPage = this.pages[this.currentPageIndex];

            if (theCurrentPage.question){
               if (theCurrentPage.question.isAnswered()){
                  if(this.currentPageIndex < (this.pages.length - 1))
                       this.pageGoto(this.currentPageIndex + 1);
               }else{
                   alert(this.msgAnswerQuestion)
               }
            }
            else{
                if(this.currentPageIndex < (this.pages.length - 1))
                    this.pageGoto(this.currentPageIndex + 1);
            }
        }
        else{
            if(this.currentPageIndex < (this.pages.length - 1))
                this.pageGoto(this.currentPageIndex + 1);
        }

    },
    pageBack: function(){
        if(this.currentPageIndex > 0)
            this.pageGoto(this.currentPageIndex - 1);
    },
    pageGoto: function(pageIndex){
        if(pageIndex > -1 && pageIndex < this.pages.length){
            this.savePage();

            this.displayPage(this.pages[pageIndex]);
            this.currentPageIndex = pageIndex;
        }
    },
    resume: function(questionNb){
        var questionAt = 0;
        var thePage;

        for(i = 0;i < this.pages.length;i++){

              thePage = this.pages[i];

              if (thePage.question){
                 if (questionAt == questionNb){
                    this.pageGoto(i);
                    return;
                 }
                 else{
                     questionAt = questionAt + 1;
                 }
              }
        }
    },
    
    savePage: function(){
      var currentPage = this.pages[this.currentPageIndex];

      if (currentPage.question){
            var answer = currentPage.question.save();
            
            if (!this.previewMode){
                var url = this.urlServer + '/' + this.servercmdpage + '?cmd=save';
                var params = {
                    participantId: this.participantId,
                    questionNb: currentPage.question.questionNb,
                    value: answer
                }
                        
                new Ajax.Request(url, {
                    method: 'post',
                    parameters: params,
                    asynchronous: false,
                    encoding: 'ISO-8859-1'
                });
            }
      }
    },
    
    displayPage: function(page){
        this.resetLayout();

        if (page.title)
           $('pageTitle').update(page.title);
        else
            $('pageTitle').update('&nbsp;');
        
        //statement
        if(page.statement){
            $('statement').show();
            $('statement').update(page.statement);
        }

        //guideline
        if(page.textGuideline){
            $('textGuidelinequiz').show();
            $('textGuidelinequiz').update(page.textGuideline);
        }


        //image
        if(page.imagePath){
            imageOnPage = document.createElement('img');
            imageOnPage.src = page.imagePath;
            //A VOIR AVEC REJ QU'EST-CE QUI ARRIVE AVEC CA...MEME CHOSE POUR VIDEOS
            //imageOnPage.style.width = '25px';
            //imageOnPage.style.height = '100px';

            $('imageContainer').update(imageOnPage);
            $('imageContainer').show();
        }

        //video
        if(page.videoPath){
            videoHeight16 = page.videoHeight + 16;

            htmlVideo = "<OBJECT classid='clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B' width=\"320\" height=\"" + videoHeight16 + "\" codebase='http://www.apple.com/qtactivex/qtplugin.cab'>";
            htmlVideo = htmlVideo + "<param name='src' value=\"" + page.videoPath + "\">";
            htmlVideo = htmlVideo + "<param name='autoplay' value=\"true\">";
            htmlVideo = htmlVideo + "<param name='controller' value=\"true\">";
            htmlVideo = htmlVideo + "<param name='loop' value=\"false\">";
            htmlVideo = htmlVideo + "<EMBED src=\"" + page.videoPath + "\" width=\"320\" height=\"" + videoHeight16 + "\" autoplay=\"true\" controller=\"true\" loop=\"false\" pluginspage='http://www.apple.com/quicktime/download/'>";
            htmlVideo = htmlVideo + "</EMBED>";
            htmlVideo = htmlVideo + "</OBJECT>";

            $('videoContainer').update(htmlVideo);
            $('videoContainer').show();
        }

        //sound
        if(page.soundPath){
            htmlSound = "";
            htmlSound = "<OBJECT classid='clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B' name=\"theSouns\" id=\"theSound\" width=\"0\" height=\"0\" codebase='http://www.apple.com/qtactivex/qtplugin.cab'>";
            htmlSound = htmlSound + "<param name='src' value=\"" + page.soundPath + "\">";
            htmlSound = htmlSound + "<param name='autoplay' value=\"true\">";
            htmlSound = htmlSound + "<param name='controller' value=\"false\">";
            htmlSound = htmlSound + "<param name='loop' value=\"false\">";
            htmlSound = htmlSound + "<param name='volume' value=\"" + gTCALS.gSoundVolume + "\">";
            htmlSound = htmlSound + "<EMBED src=\"" + page.soundPath + "\" name=\"theSound\" enablejavascript=\"true\" width=\"1\" height=\"1\" autoplay=\"true\" controller=\"true\" loop=\"false\" volume=\"" + gTCALS.gSoundVolume + "\" pluginspage='http://www.apple.com/quicktime/download/'>";
            htmlSound = htmlSound + "</EMBED>";
            htmlSound = htmlSound + "</OBJECT>";
            
            //SI PAS DE SHOW, LE SON JOUE PAS...
            $('soundOnly').update(htmlSound);
            $('soundOnly').show();

            //htmlSound = "<br /><br /><img src=\"images/btn_back_disabled.jpg\" onClick=\"javascript:volumeControl(0,document.theSound);\">&nbsp;&nbsp;&nbsp;<img src=\"images/btn_next_disabled.jpg\" onClick=\"javascript:volumeControl(1,document.theSound);\">";
            //$('soundContainer').update(htmlSound);
            //$('soundContainer').show();

            htmlSound = "<img src=\"images/icn_sonvolume.jpg\" />&nbsp;<img src=\"images/vol_plus_norm.jpg\" onClick=\"javascript:volumeControl(1,document.theSound);\" onmouseover=\"this.src='images/vol_plus_roll.jpg'\" onmouseout=\"this.src='images/vol_plus_norm.jpg'\" /><img src=\"images/vol_moins_norm.jpg\" onClick=\"javascript:volumeControl(0,document.theSound);\" onmouseover=\"this.src='images/vol_moins_roll.jpg'\" onmouseout=\"this.src='images/vol_moins_norm.jpg'\"/>";
            $('soundControls').update(htmlSound);
        }

        if(page.question)
            page.question.display();

        this.updateNavBar(page);

        if (page.lastPage){
           $('navbar').update('');
           this.submit();
        }

        //timer
        if(!this.timer){
            this.timer = getNewNQTimer();
            this.timer.width = 116;
            this.timer.height = 9;
            this.timer.sliderImage = 'images/timerslider.jpg';
            this.timer.bkgColor = 'white';
            this.timer.onFinish = TCALSTimerFinish;
            this.timer.show($('timerContainer'));
        }

        if(page.timerEnabled){

            var bgTimer = "url(./images/timerwrapper.jpg) no-repeat top left";
            $('timerContainer').style.background = bgTimer;

            $('timerTitle').update(this.timerTitle);

            this.timer.stopCompletely = false;
            this.timer.delay = page.timerDelay;
            this.timer.sliderImage = 'images/timerslider.jpg';
            this.timer.mainElement.style.background = 'url(' + this.timer.sliderImage + ') no-repeat top left';
            this.timer.stop();
            //**** update 27/02/10 pour permettre au timer d'attendre la fin du load du media 
            if(page.soundPath){
                this.mediaLoadingTimer = new PeriodicalExecuter(
                    function(){
                        var mediaDuration = -1;
                        try{
                            mediaDuration = document.theSound.GetDuration();
                        }catch(e){}
                        
                        if(mediaDuration > -1){
                            gTCALS.mediaLoadingTimer.stop();
                            gTCALS.timer.start();
                            
                        }
                    },
                    .5
                );
                //this.timer.start();
            }else{
                this.timer.start();
            }
            //****
        }
        else{
            if (this.timer){
              this.timer.stopCompletely = true;
              this.timer.mainElement.style.background = "url(./images/spacer.gif) no-repeat top left";
            }
        }

        resizeDiv(2);
    },
    
    init: function(){
        $('pagewrapperauth').show();
        $('pagewrapperquiz').hide();

        if(this.previewMode){
            this.begin();
        }else{
            this.connect();
        }
    },
    
    begin: function(){
        $('pagewrapperauth').hide();
        $('pagewrapperquiz').show();

        this.pageGoto(0);
    },
    
    updateNavBar: function(page){
        //back toujours hide TCALS
        $('btnBackEnabled').hide();
        $('btnBackDisabled').hide();

        /*CODE SI BESOIN BACK
        if(page.pageBackEnabled){
            $('btnBackEnabled').show();
            $('btnBackDisabled').hide();
        }else{
            $('btnBackEnabled').hide();
            $('btnBackDisabled').show();
        }*/

        
        $('pageLabel').update(this.pageLabel);

        //index
        pageIndex = this.pages.indexOf(page);
        $('navBarPageIndex').update(pageIndex + 1);
        $('navBarPageCount').update(this.pages.length);
        
        //next
        if(page.pageNextEnabled){
            $('btnNextEnabled').show();
            $('btnNextDisabled').hide();
        }else{
            $('btnNextEnabled').hide();
            $('btnNextDisabled').show();
        }
    },
    
    resetLayout: function(){
        var bgTimerInit = "url(./images/spacer.gif) no-repeat top left";
        $('timerContainer').style.background = bgTimerInit;

        $('statement').hide();
        $('textGuidelinequiz').hide();

        $('question').update('');
        $('timerTitle').update('');

        //STOP (REMOVE) MEDIAS AND HIDE CONTAINER
        $('sonAcc').update('');
        $('sonAcc').hide();

        $('imageContainer').update('');
        $('imageContainer').hide();

        $('videoContainer').update('');
        $('videoContainer').hide();

        $('soundOnly').update('');
        $('soundOnly').hide();

        $('soundControls').update('');

        resizeDiv(1);

    },

    submit: function(){
        window.onbeforeunload = null;
        
        if (!this.previewMode){
            var url = this.urlServer + '/' + this.servercmdpage + '?cmd=submit';
            var params = {
                participantId: this.participantId
            }
                        
            new Ajax.Request(url, {
                method: 'post',
                parameters: params,
                asynchronous: false,
                encoding: 'ISO-8859-1'
            });
        }
    },
    
    timerFinish: function(){
       this.pageNext(false);
    },
    
    onunload: function(){
        return this.msgUnonload;
    }
});

function getNewTCALS(){
    if (top.ccdmd == null) top.ccdmd = {};
    top.ccdmd.tcals = new TCALS();
    return top.ccdmd.tcals;
}

var labelLetters = new Array("a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z");

function getLetterLabel(i){
    var label = '';
    
    if(i < 27){
        label = labelLetters[i - 1];
    }else if((i % 26) == 0) {
        label = labelLetters[Math.floor(i  / 26) - 2] + labelLetters(26);
    }else{
        label = labelLetters[Math.floor(i  / 26) - 1] + labelLetters(i % 26);
    }
    
    return label;
}

function TCALSTimerFinish(){
    top.ccdmd.tcals.timerFinish();
}
function tcals_onConnectSuccess(transport){
    top.ccdmd.tcals.connectSuccess(transport);
}
function tcals_onAuthSuccess(transport){
    top.ccdmd.tcals.authSuccess(transport);
}
function tcals_auth(){
    top.ccdmd.tcals.auth();
}

function volumeControl(upOrDown,containerid){

         //PARAM VOLUME = 0-100, mais pour changer avec JS le volume, les values sont 0-255. Faire conversion avant...

         gTCALS.gSoundVolume = Math.round((gTCALS.gSoundVolume / 100) * 255);

         if (gTCALS.gSoundVolume > 255)
            gTCALS.gSoundVolume = 255;
         else if (gTCALS.gSoundVolume < 25)
            //NEVER MUTED
            gTCALS.gSoundVolume = 25;

         if (upOrDown == 1){
            if ((gTCALS.gSoundVolume + 35) <= 255)
               gTCALS.gSoundVolume = gTCALS.gSoundVolume + 35;
            else
               gTCALS.gSoundVolume = 255;
         }
         else{
            if ((gTCALS.gSoundVolume - 35) >= 35)
               gTCALS.gSoundVolume = gTCALS.gSoundVolume - 35;
            else
               //NEVER MUTED 
               gTCALS.gSoundVolume = 25;
         }

         containerid.SetVolume(gTCALS.gSoundVolume);

         gTCALS.gSoundVolume = Math.round((gTCALS.gSoundVolume / 255) * 100);
}

function tcals_playIntro(){
         //SON PAGE PRINCIPALE

        htmlSound = "";
        htmlSound = "<OBJECT classid='clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B' id=\"theSoundAcc\" width=\"0\" height=\"0\" codebase='http://www.apple.com/qtactivex/qtplugin.cab'>";
        htmlSound = htmlSound + "<param name='src' value=\"" + gTCALS.pathSoundIntro + "\">";
        htmlSound = htmlSound + "<param name='autoplay' value=\"true\">";
        htmlSound = htmlSound + "<param name='controller' value=\"false\">";
        htmlSound = htmlSound + "<param name='loop' value=\"false\">";
        htmlSound = htmlSound + "<param name='volume' value=\"" + gTCALS.gSoundVolume + "\">";
        htmlSound = htmlSound + "<EMBED src=\"" + gTCALS.pathSoundIntro + "\" name=\"theSoundAcc\" enablejavascript=\"true\" width=\"1\" height=\"1\" autoplay=\"true\" controller=\"false\" loop=\"false\" volume=\"" + gTCALS.gSoundVolume + "\" pluginspage='http://www.apple.com/quicktime/download/'>";
        htmlSound = htmlSound + "</EMBED>";
        htmlSound = htmlSound + "</OBJECT>";

        $('sonAcc').update(htmlSound);
        $('sonAcc').show();

        gTCALS.playedIntroSound = true;
}

function resizeDiv(param){
         
    if (param == 1){
        document.getElementById('pagewrapperquiz').style.height = '100%';
        document.getElementById('aroundquiz').style.height = '100%';
        document.getElementById('aroundImgTCALSquiz').style.height = '100%';
    }
    else{
        //Workaround...till better solution
        var adjustHeightDiv = document.getElementById('contentquiz').offsetHeight;

        document.getElementById('pagewrapperquiz').style.height = adjustHeightDiv + 'px';
        document.getElementById('aroundquiz').style.height = adjustHeightDiv + 'px';
        document.getElementById('aroundImgTCALSquiz').style.height = adjustHeightDiv + 'px';
    }

}

function tcals_createElement(nodeName, name){
    var node;
    
    try {
        node = document.createElement("<"+nodeName+" name="+name+">");
    } catch (e) {
        node = document.createElement(nodeName);
        node.name = name;
    }
    
    return node;
}

function over_btn(inOrOut){
    if (inOrOut == 0)
       $('btnContinuer').src = 'images/btn_go_roll.jpg';
    else
       $('btnContinuer').src = 'images/btn_go_norm.jpg';
}

function tcals_onunload(){
    return top.ccdmd.tcals.onunload();
}


