/******************************************************
    * Prototype plug-in
    * Mediameg rotator v.0.9 beta
    * Developed by mediameg (http://www.mediameg.com)
******************************************************/
/**
 * 
 *  Appel
 *    document.observe("dom:loaded", function(){
                    oMySlides = new rot_slid({                        
                        slides 	: [{src:'img/slider_0.jpg', target:'_blank', url:'www.google.ca'},{src:'img/slider_0.jpg', target:'_blank', url:'wrc.com'},{src:'img/slider_0.jpg', target:'_blank', url:'mediameg.com'}],
                        img_id : 'slider_1_img',
                        effect : 'appear',
                        div_to_insert : "test",
                        //align_center : true,
                        //infinit : false,
                        //autoplay : true,
                        //navigation : true,
                        //opacity_info : {show:false, size:50, opacity:0.6,color:'black'},
                        images_icon : {normal:"img/btn-nav.png", select:"img/btn-nav-selected.png"},
                        //show_arrows : true,
                        arrow_images : {left:'img/arrows_left.png', right:'img/arrows_right.png'},
                        width : 946,
                        height: 295,
                        return_auto : true
                    });
                })
 *
 *Les effets sont :
 *  slideleft : tasse l'image vers la gauche
    slideright : tasse l'image vers la droite
    slideup : tasse l'image vers l'haut
    slidedown : tasse l'image vers l'haut
    appear : Effet comme dans le flash
    blinddown : haut vers le bas
    grow : bas vers l'haut
    sans  effets: Le carrousel change l'image tout simplement
 *
 * Autoplay : true/false joue de façon automatique le carrousel
 * infinit : true/false fait le carrousel joue de façon infinie
 * navigation : true/false montre les boutons où l'animation est rendu
 * slides : array with object that has src, target and url
 * 
 */
var rot_slid = new Class.create();
rot_slid.prototype = {
    initialize : function (parameter){
        //Default time to change is 5sec
        this.time_change    = parameter.time_change     ? parameter.time_change : 5000;
        this.current        = 0;
        this.img_id         = parameter.img_id;
        this.slides         = parameter.slides          != undefined ? parameter.slides : new Array();
        this.effect         = parameter.effect          ? parameter.effect : 0;
        this.align_center   = parameter.align_center    ? parameter.align_center : true;
        this.window_div     = "";
        this.div_img        = "";
        this.pixels_to_slid = 0;
        this.reverse        = false;
        this.infinit        = parameter.infinit         != undefined ? parameter.infinit : false;
        this.div_to_insert  = parameter.div_to_insert;
        this.opacity_info   = parameter.opacity_info    ? parameter.opacity_info : {show:false};
        this.autoplay       = parameter.autoplay        != undefined ? parameter.autoplay : true;
        this.div_left       = "";
        this.div_right      = "";
        this.navigation     = parameter.navigation      != undefined ? parameter.navigation : true;
        this.images_icon    = parameter.images_icon;
        this.width          = parameter.width;
        this.height         = parameter.height;        
        this.show_arrows    = parameter.show_arrows     != undefined ? parameter.show_arrows : false;
        this.arrows_image   = parameter.arrow_images    != undefined ? parameter.arrow_images : false;
        this.nb_clone_image = parameter.nb_clone_image  != undefined ? parameter.nb_clone_image : 2;
        this.return_auto    = parameter.return_auto     != undefined ? parameter.return_auto : false;
        this.do_back        = false;
        this.random         = parameter.random          != undefined ? parameter.random : false;
        this.new_div        = ''; // div that will contaim images
        this.minus_width    = parameter.minus_width     != undefined ? parameter.minus_width : 0;
        this.add_div_mask   = parameter.add_div_mask    != undefined ? parameter.add_div_mask : false;
        
        if ( this.slides ) {
                
                if ( !this.slides.length) {
                        console.log('No slides?');
                        return;
                }
                
                this.numOfImages = this.slides.length;
                if(parameter.effect == "slideright" ||  parameter.effect == "slidedown"){
                    this.slides.reverse();
                    this.reverse  = true;
                }
        }
        this.start_rot();
        
    },
    start_rot: function(){        
        //check we are random load different image        
        if(this.random){
            this.current = this._randomFromTo(0, this.numOfImages - 1);  
            //add new element on start of array
            this.slides.unshift(this.slides[this.current]);
            //remove element from its original position
            this.slides.splice(this.current+1,1);
        }
        

        this.add_new_div_rot_slid();
        // now let's correct height width
        this.get_width_window_div();

        this.set_up_div_effects();
        if(this.navigation){
            // if is set we will show little guides
            this._createNavigation();
        }
        if( this.show_arrows){
            // we show div with arrows
             this._create_arrows();
        }

        this.id_time_out = 0;
        this._change_icon();
        this.play_next_image();
    },
    _create_arrows: function(){

       var new_div_left =   new Element('div', {id:'arrow_left_'+this.img_id, 'class':'arrow_'+this.img_id});
       var new_div_right =  new Element('div', {id:'arrow_right_'+this.img_id, 'class':'arrow_'+this.img_id});
       var content_left =   this.arrows_image.left != ""   ?'<img src="'+this.arrows_image.left+'" alt="" />': '<';
       var content_right =  this.arrows_image.right != ""  ?'<img src="'+this.arrows_image.right+'" alt="" />' : '>';

        // we insert images into new div
        new_div_left.insert(content_left).observe('click', this.previousimage.bind(this));
        new_div_right.insert(content_right).observe('click', this.nextimage.bind(this));

          $(this.div_to_insert).insert(new_div_left);
          $(this.div_to_insert).insert(new_div_right);

    },
    play_next_image: function(){
         if(this.autoplay){
            this.id_time_out = setTimeout(this.nextimage.bind(this), this.time_change);
        }
    },
    play_previous_image: function(){
         if(this.autoplay){
            this.id_time_out = setTimeout(this.previousimage.bind(this), this.time_change);
        }
    },
    add_new_div_rot_slid: function(){
        this.window_div  = "window_"+this.img_id;
        this.div_img = "div_"+this.img_id;
        this.div_left = "div_left_"+this.img_id;
        this.div_right = "div_right_"+this.img_id;
        
        this.div_mask = "";
        if(this.add_div_mask){
            this.div_mask = new Element('div', {className: 'mask_rotator_'+this.img_id,id:'mask_rotator_'+this.img_id});
        }
        
        

        this.new_div = new Element('div', {className: 'rot_ctn',id:this.div_img, style: "position: absolute;"});        
        

        // means we have to clone last image and insert first to be able to display correct
        // if we have opacity is to show an aspect of infiniti
        if(this.infinit && (this.reverse || this.opacity_info.show)){

            //we clone first image to create a new effect
            if(this.effect != "slideup" && this.effect != "slideright" || ((this.effect == "slideup" || this.effect == "slideright") && this.opacity_info.show)){                
                
                for(i = this.nb_clone_image; i > 1; i-- ){
                    if(this.slides[this.slides.length-i] && this.slides[this.slides.length-i].src){
                        this._insert_ctn_image_structure(this.slides.length-i)
                    }
                }
                
            }                        
            
            this._insert_ctn_image_structure(this.slides.length-1)

        }



        // we insert images into new div
        for(var i = 0; i <  this.slides.length; i++){
            this._insert_ctn_image_structure(i);
        }

        if(this.infinit &&  !this.reverse && this.effect != "appear" && this.effect != "blinddown" && this.effect != "grow"){
            
            this._insert_ctn_image_structure(0); 

            if(this.opacity_info.show){
                // if we are in mode to show preview of next we clone second image also                
                 for(i = 1; i < this.nb_clone_image+1; i++ ){  
                    if(this.slides[i] && this.slides[i].src){                        
                        this._insert_ctn_image_structure(i);                        
                    }                    
                 } 
            }
        }

        //we clone last to give impression of infinit
        if(this.infinit &&  this.reverse){
                this._insert_ctn_image_structure(0);              
               
               if(this.opacity_info.show){
                 for(i = 1; i <= this.nb_clone_image; i++ ){  
                     if(this.slides[i].src){
                        this._insert_ctn_image_structure(i);                        
                     }
                 }                   
               }
               
        }                
        

        var window_div = new Element('div', {className: 'rot_window', id:this.window_div, style: "overflow: hidden; position: relative;"+( this.align_center ? " margin: 0 auto;" : "")});
        if(this.opacity_info.show && this.effect != 0){
            window_div.insert(new Element ('div',{id:this.div_left, style:"background-color:"+this.opacity_info.color+"; "+(this.opacity_info.opacity == 0 ?"display: none;" : "display: inline-block;" )+(Prototype.Browser.IE ? "filter: alpha(opacity = "+(this.opacity_info.opacity*100)+")" : "opacity:"+this.opacity_info.opacity)+";  overflow: hidden;  position: absolute;  width: "+this.opacity_info.size+"px;   z-index: 999999;"}));
        }

        window_div.insert(this.new_div);
        
        if(this.opacity_info.show && this.effect != 0){
            window_div.insert(new Element ('div',{id:this.div_right, style:"background-color:"+this.opacity_info.color+"; "+(this.opacity_info.opacity == 0 ?"display: none;" : "display: inline-block;" )+(Prototype.Browser.IE ? "filter: alpha(opacity = "+(this.opacity_info.opacity*100)+");" : "opacity:"+this.opacity_info.opacity)+";   overflow: hidden;  position: absolute;  width: "+this.opacity_info.size+"px;   z-index: 999999;"}));
        }
        
                

        $(this.div_to_insert).insert(window_div);
        //add mask div
        $(this.div_to_insert).insert(this.div_mask);

    },
    _insert_ctn_image_structure: function (id){
        this.new_div.insert(new Element('a',{className: 'rot_img', target:  this.slides[id].target, href: this.slides[id].url}).insert(new Element ('img',{src: this.slides[id].src, style:"display:inline-block;",id:this.img_id+'img_'+id})));                                            
    },    
    set_up_div_effects: function(){

        var calculate_initial_setup = -parseInt(this.pixels_to_slid*(this.infinit ? (this.opacity_info.show ? this.nb_clone_image : 0) : 0))+parseInt(this.opacity_info.show ? this.opacity_info.size : 0);

        switch(this.effect){
                case "slideleft":
                    $( this.div_img).setStyle({top: 0, left:    calculate_initial_setup+"px"});
                    break;
                case "slideright":
                    $( this.div_img).setStyle({top: 0, right:   calculate_initial_setup+"px"});
                    break;
                 case "slideup":
                     $( this.div_img).setStyle({top:            calculate_initial_setup+"px"});
                    break;
                 case "slidedown":
                     $( this.div_img).setStyle({bottom:         calculate_initial_setup+"px"});
                    break;                
        }
    }
    ,
    get_width_window_div: function(){
        // we get dimmentions of image to set height and width of div
        var height_div = this.height;
        var width_div = this.width ;
        this.pixels_to_slid = width_div;        
        $(this.window_div).setStyle({width:(width_div-this.minus_width)+"px", height: height_div+"px"});

        // if we have this effects we will change width of div
        if(this.effect == "slideleft" || this.effect == "slideright"){
            // if we have infinit we add one more img to end of div, since we will duplicate first image
            //if we have infinit and we display preview we add 3 mores img sizes to end
            $(this.div_img).setStyle({width: this.pixels_to_slid*this.return_nb_img_div()+"px"});
            if(this.opacity_info.show){
                $(this.div_left).setStyle({height: height_div+"px"});
                $(this.div_right).setStyle({height: height_div+"px", left: width_div+this.opacity_info.size+"px"});
                $(this.window_div).setStyle({width:(width_div-this.minus_width)+(this.opacity_info.size*2)+"px"});
            }
        }
        else if(this.effect == "slideup" || this.effect == "slidedown" ){
             this.pixels_to_slid = height_div;
            $(this.div_img).setStyle({height: this.pixels_to_slid*this.return_nb_img_div()+"px"});
            if(this.opacity_info.show){
                $(this.div_left).setStyle({width: width_div+"px", height: this.opacity_info.size+"px"});
                $(this.div_right).setStyle({width: width_div+"px", height: this.opacity_info.size+"px", top: height_div+this.opacity_info.size+"px"});
                $(this.window_div).setStyle({height:(height_div-this.minus_width)+(this.opacity_info.size*2)+"px"});
            }
        }
        else{
            this.pixels_to_slid = height_div;
        }
    },
    return_nb_img_div: function(){
        return $$('#'+this.div_img+" > img").length + $$('#'+this.div_img+" > a > img").length;
    },   
    nextimage : function (){
  
        // first we stop counter
        this._clear_counter();
        
        if(this.do_back || this.return_auto && this._check_arrive_final()){            
            // if we are here means we have select return_auto
            // so slider we will up to last slid and will commeback to first slid
            this.do_back = true;
            
            if(this._check_arrive_start()){
                this.do_back = false;
            }
            
            if(this.do_back){
                this.previousimage();
                return;
            }
            
        }                
        
        //we pass counter to next image
        this.control_current('next');
        // change icon
        this._change_icon();        
        // change slid
        this._change_slide('next');      
        // play next if auto play
        this.play_next_image();                
        
    },
    previousimage : function(){

        // first we stop counter
        this._clear_counter();
        //we pass counter to previous image
        this.control_current('previous');
        // change icon
        this._change_icon();
        // change slid
        this._change_slide('previous');
        // play next if auto play
        this.play_next_image();

    },
    control_current: function(action){

        if(!this.random){
            if(action == 'next'){
                // if we have infinit option
                if(this.infinit && this.current >= this.numOfImages){
                    this.current = 0;
                }

                this.current++;

                // if not infinit normal trateament            
                if(!this.infinit && this.current >= this.numOfImages){
                    this.current = 0;
                }
            
            }
            else if(action == 'previous'){
                if(this.infinit && this.current < 0){
                    this.current = this.numOfImages - 1;
                }

                this.current--;

                if(!this.infinit && this.current < 0){
                    this.current = this.numOfImages - 1;
                }


            }
            else{
                return;
            }  
        }
        else{// means we are loading on random
                        
            var new_current = this.current;            
            while(this.current == new_current){                
                this.current = this._randomFromTo(0, this.numOfImages - 1);                
            }
        }
                       
    },    
    calculate_travel_slid: function (infinit_slid){
        return ((parseInt(this.opacity_info.show ? this.pixels_to_slid*(this.infinit ? parseInt(infinit_slid) : 0) : 0)+parseInt(this.pixels_to_slid*this.current)-parseInt(this.opacity_info.show ? this.opacity_info.size : 0)))*-1;
    },
    _randomFromTo: function (from, to){
       return Math.floor(Math.random() * (to - from + 1) + from);
    },
    _check_arrive_final: function(){
        return this.current >= this.numOfImages - 1;
    },
    _check_arrive_start: function(){        
        return this.current <= 0;
    },
    _change_slide: function(action){
                
          switch(this.effect){
                case "slideleft":
                    new Effect.Morph(this.div_img,{style:'left: '   +this.calculate_travel_slid(this.nb_clone_image)+"px", afterFinish: this._check_after_change.bind(this, action)});
                    break;
                case "slideright":
                    new Effect.Morph(this.div_img,{style:'right: '  +this.calculate_travel_slid(this.nb_clone_image)+"px", afterFinish: this._check_after_change.bind(this, action)});
                    break;
                case "slideup":
                    new Effect.Morph(this.div_img,{style:'top: '    +this.calculate_travel_slid(this.nb_clone_image)+"px", afterFinish: this._check_after_change.bind(this, action)});
                    break;
                case "slidedown":
                    new Effect.Morph(this.div_img,{style:'bottom: ' +this.calculate_travel_slid(this.nb_clone_image)+"px", afterFinish: this._check_after_change.bind(this, action)});
                    break;
                case "appear":
                    this._hide_all_images();
//                    console.log(this.current);
//                    console.log(this.img_id+'img_'+(this.current));
                    if($(this.img_id+'img_'+(this.current))){
                        new Effect.Appear(this.img_id+'img_'+(this.current));
                    }                    
                    break;
                case "blinddown":
                    this._hide_all_images();
                    new Effect.BlindDown(this.img_id+'img_'+(this.current));
                    break;
                 case "grow":
                    this._hide_all_images();
                    new Effect.Grow(this.img_id+'img_'+(this.current));
                    break;                
                default : // no animation
                    $(this.div_img).setStyle({top: -this.pixels_to_slid*this.current});

        }
  
    },
    _hide_all_images: function(){        
        $$("#"+this.div_img+" img").each(
            function(elem){
                 //Effect.Fade(elem.id);
                elem.hide();
            }
        );
    },
    _change_slide_no_effects: function(){
                switch(this.effect){
                        case "slideleft":
                            $(this.div_img).setStyle({left: this.calculate_travel_slid(this.nb_clone_image)+"px"});
                            break;
                        case "slideright":
                            $(this.div_img).setStyle({right: this.calculate_travel_slid(this.nb_clone_image-1)+"px"});
                            break;
                        case "slideup":
                            $(this.div_img).setStyle({top: this.calculate_travel_slid(this.nb_clone_image)+"px"});
                            break;
                        case "slidedown":
                            $(this.div_img).setStyle({bottom: this.calculate_travel_slid(this.nb_clone_image-1)+"px"});
                            break;
                        default : // no animation
                            $(this.div_img).setStyle({top: -this.pixels_to_slid*this.current});

                    }
    },
    _check_after_change: function(action){

            //if we are next and we arrived at end of image we change to start
            if(action == 'next' && this.infinit&& this.current == this.numOfImages){                
                this.set_up_div_effects();                
            }
            // if we are backing and we arrived on last image to show, we has to show as last image
            if(action == 'previous' && this.infinit && this.current < 0){                
                var tmp_current = this.current;
                this.current = this.numOfImages - (this.reverse ? 0 : 1);
                this._change_slide_no_effects();
                this.current = tmp_current;
            }
    },
    _createNavigation: function(){
         var new_div = new Element('ul', {id:'navigation_'+this.img_id, 'class':'nav_'+this.img_id});
         
          // we insert images into new div
        var li = new Element('li',{id:'nav_'+this.img_id+'_first', style:'cursor:pointer;list-style-type: none;', className: ''});
        new_div.insert(li);
        for(var i = 0; i <  this.slides.length; i++){
          var a = new Element('li',{id:'nav_'+this.img_id+'_'+i, style:'cursor:pointer;list-style-type: none;', className: 'nav_btn'}).update((i+1));
          a.observe('click', this._check_click.bind(this, i));
          new_div.insert(a);
        }
        li = new Element('li',{id:'nav_'+this.img_id+'_last', style:'cursor:pointer;list-style-type: none;', className: ''});
        new_div.insert(li);
        $(this.div_to_insert).insert(new_div);

    },
    _check_click: function(img_change){
        this.current = img_change - 1;
        this.nextimage();
    },
    _change_icon: function (){
        var counter = 0;
        var CopyObj = this;
        var length_navigation = $$('#navigation_'+this.img_id+" > li.nav_btn");

        
        $$('#navigation_'+this.img_id+" > li.nav_btn").each(function(img_icon){
                        
            if(counter == CopyObj.current || (CopyObj.current == CopyObj.numOfImages && counter == 0) || (CopyObj.current < 0 && counter == length_navigation.length-1) ){
                img_icon.addClassName('nav_btn_selected');
            }
            else{
               img_icon.removeClassName('nav_btn_selected');
            }

            counter++;
        });
    },
    _clear_counter: function(){
       // first we stop counter
        if(this.id_time_out != 0){
            clearTimeout(this.id_time_out);
        }        
    }
}// end class rot_slid
