


CanvasImage = function(dragDiv,options){

    this.container = dragDiv;
    this.image = dragDiv.select('img')[0];
    this.removeHandler = function(){};
    this.sendToBackHandler = function(){};
    this.options = options;
    this.canvas = null;
    this.relation = this.image.getWidth()/this.image.getHeight();
    this.fx = {};
}

CanvasImage.createFromImage = function(image,options){
    var div = new Element('div',{'class':'instanceWrapEditable'});
    var width = image.getWidth();
    if(width > 300)
            width = width*0.5;
    
    
    var image = new Element('img',{
        'id': 'newinst_'+image.id.split('_')[1],
        'src': image.src,
        'width': width
    });
    div.appendChild(image);
    return new CanvasImage(div,options);
}
CanvasImage.prototype.getWidth = function(){
    return this.image.getWidth();
}

CanvasImage.prototype.setRemoveHandler = function(callbackFunction){
    this.removeHandler = callbackFunction;
}
CanvasImage.prototype.setSendToBackHandler = function(callbackFunction){
    this.sendToBackHandler = callbackFunction;
}
CanvasImage.prototype.removeButtons = function(){
    this.container.select('.imageButton').each(function(button){
        button.remove();
    });
}

CanvasImage.prototype.addButtons = function(){
   var removeImageButton = new Element('div',{'class': 'removeImageButton imageButton'});
   removeImageButton.observe('click',function(){
       this.removeHandler(this.container);
   }.bind(this));
   this.container.appendChild(removeImageButton);

   var sendToBackImageButton = new Element('div',{'class': 'sendToBackImageButton imageButton'});
   sendToBackImageButton.observe('click',function(){
       this.sendToBackHandler(this.container);
   }.bind(this));
   this.container.appendChild(sendToBackImageButton);

   /*
   var flipImageButton = new Element('div',{'class': 'flipImageButton imageButton'});
   flipImageButton.observe('click',function(){
      
      if(!this.fx.flip.active){
        this.fx.flip.active = true;
      }else{
        this.fx.flip.active = false;
      }
      this.redraw();
   }.bind(this));
   this.container.appendChild(flipImageButton);
   this.fx.flip = new FlipFx(this.image);
   */
  
   if(this.options.features.scaling){
       var scaleImageButton = new Element('div',{'class': 'scaleImageButton imageButton'});
       var scaleImageIcon = new Element('div',{'class': 'scaleImageIcon imageButton'});

       new Draggable(scaleImageButton,{
          ghosting: false,
          change: this.scaleImage.bind(this),
          onEnd: this.endScale.bind(this)
       });

       scaleImageButton.style.left = this.image.getWidth()-16+"px";
       this.container.appendChild(scaleImageIcon);
       this.container.appendChild(scaleImageButton);
   }
}

CanvasImage.prototype.scaleImage = function(draggable){
    var scaleButton = draggable.element;
    var w  = scaleButton.offsetLeft>10 ? scaleButton.offsetLeft : 10;
    this.image.width = w;
    if(this.canvas){
        this.getCanvas().width = w;
        this.getCanvas().height = w*this.relation;
        this.redraw();
    }
    
}
CanvasImage.prototype.endScale = function(draggable){
    var scaleButton = draggable.element;
    scaleButton.setStyle({
        'left':'',
        'top':'',
        'bottom': '0px',
        'right': '0px'
    });
    scaleButton.style.left = this.image.getWidth()-16+"px";
}
CanvasImage.prototype.redraw = function(){
    var ctx = this.getCanvas().getContext('2d');
    ctx.clearRect(0, 0, this.image.getWidth(), this.image.getHeight());
    ctx.drawImage(this.image,0, 0, this.image.getWidth(), this.image.getHeight());

    if(this.fx.flip.active){
        this.fx.flip.apply(this.getCanvas());
    }
}

CanvasImage.prototype.getCanvas = function(){
    if(!this.canvas){
        var h = this.image.getHeight();
        var w = this.image.getWidth();
        this.canvas = document.createElement('canvas');
        //this.canvas.style.height = h+'px';
        //this.canvas.style.width = w+'px';
        this.canvas.height = h;
        this.canvas.width = w;
        this.image.insert({after: this.canvas});
    }
    return this.canvas;
}

function CanvasFx(){}

FlipFx = function(image){
    this.image = image;
    this.active = false;
}
FlipFx.prototype.apply = function(canvas){
    var ctx = canvas.getContext('2d');
    ctx.translate(canvas.getWidth(),0);
    ctx.scale(-1,1);
    ctx.drawImage(this.image,0,0,this.image.getWidth(),this.image.getHeight());
}






/**
 * CliprHeader 
 * Author: Stephan Petzl
 */
CliprHeader = function(containerId,username){
    this.username = username;
    this.container = $(containerId);
    this.activeImage = null;
    //indicates if the item was dragged - is set to true while dragging - set to false after drag
    this.dontBringToFront = false;
    this.imageCount = 0;
    this.options = {
        features : {
            scaling: false
        },
        maxImages: 5
    };
    this.images = [];

    this.init = function(options){

        if(options)
            this.options = options;
        this.imageCount = this.container.select('.instanceWrapEditable').size();
        this.container.observe('click',function(){
            this.setActiveImage(null);
        }.bind(this));
        
        this.container.select('.instanceWrapEditable').each(function(div){
            var self = this;

            div.observe('click',function(event){
                //console.log('click');
                event.stop();
                // just flip to top if it was clicked without dragging
                if(!self.dontBringToFront){
                    this.style.zIndex = parseInt(this.style.zIndex)+1000;
                    self.fixZIndexes();
                }
                self.dontBringToFront = false;
                self.pleaseSave();
                self.setActiveImage(this);
            });

            new Draggable(div,{
                ghosting: false,
                onStart: function(){
                    self.dontBringToFront = true;
                }
            });
            div.style.cursor = 'all-scroll';
            // add buttons only if there is not already a button in the div
            var ci = new CanvasImage(div, this.options);
            ci.setRemoveHandler(function(div){
                this.imageCount--;
                div.remove();
            }.bind(this));

            ci.setSendToBackHandler(function(div){
                var backDiv = this.getByZIndex(div.style.zIndex-1);
                if(backDiv){
                    backDiv.style.zIndex = parseInt(backDiv.style.zIndex)+1;
                    div.style.zIndex = parseInt(div.style.zIndex)-1;
                    this.dontBringToFront = true;
                }
            }.bind(this));
            ci.removeButtons();
            ci.addButtons();
            this.images.push(ci);
            

       }.bind(this));

       document.observe('keypress',this.keyDown.bind(this));
       this.fixZIndexes();

    }
    // retrieves the div with the specified zIndex
    this.getByZIndex = function(zIndex){
        var found = null;
        this.container.select('.instanceWrapEditable').each(function(div){
            if(zIndex == div.style.zIndex)
                found = div;
        });
        return found;
    }
    
    this.activateDropableHeader = function(){
        if($('dropableHeader'))
            Droppables.add('dropableHeader',{
                onDrop: function(dragElem,dropElem,event){
                    cliprHeader.addImage(dragElem,event.clientX-cliprHeader.container.cumulativeOffset()[0],event.clientY-cliprHeader.container.cumulativeOffset()[1]);
                }.bind(this),
                hoverclass: 'hclass'
            });
    }
    this.deactivateDropableHeader = function(){
        Droppables.remove('dropableHeader');
    }
    this.setActiveImage = function(image){
        if(this.activeImage){
            this.activeImage.removeClassName('activeImage');
        }
        if(image) {
            image.addClassName('activeImage');
        }
        this.activeImage = image;
    }
    this.keyDown = function(event){

        if(this.activeImage){
            switch(event.keyCode){
                case Event.KEY_UP:
                    this.activeImage.setStyle({'top': parseInt(this.activeImage.getStyle('top'))-1+'px'});
                    Event.stop(event);
                    break;
                case Event.KEY_DOWN:
                    this.activeImage.setStyle({'top': parseInt(this.activeImage.getStyle('top'))+1+'px'});
                    Event.stop(event);
                    break;
                case Event.KEY_LEFT:
                    this.activeImage.setStyle({'left': parseInt(this.activeImage.getStyle('left'))-1+'px'});
                    Event.stop(event);
                    break;
                case Event.KEY_RIGHT:
                    this.activeImage.setStyle({'left': parseInt(this.activeImage.getStyle('left'))+1+'px'});
                    Event.stop(event);
                    break;
            }

        }

    }
    
    
    this.pleaseSave = function(){
        if(!$('saveNote')){
            growler.growl('<div id="saveNote">There are unsaved changes, click <a href="'+document.location.href+'#" onclick="cliprHeader.save();return false;">here</a> to save them!</div>',{location: 'br',sticky: true});
        }
    }
    this.showMessage = function(message){
        if(!$('headerMessage')){
            var headerMessage = new Element('div',{
                'id': 'headerMessage'
            });
            $('headercontainer').insert({after: headerMessage});
            $('headerMessage').style.display = "none";
            $('headerMessage').innerHTML = message+'<br/>'+$('headerMessage').innerHTML;
        }
        $('headerMessage').show();
    }

    this.save = function(){
        var objArr = [];
        this.setActiveImage(null);
        this.container.select('img').each(function(img){

            var x = img.parentNode.offsetLeft;
            //var center = this.container.getWidth()/2;
            objArr.push({
              '_image': img.id,
              'x': x-1,
              'y': img.parentNode.offsetTop-1,
              'z': img.parentNode.style.zIndex,
              'width': img.getWidth(),
              'height': img.getHeight()
            });
        });

        xajax_saveImageHeader(this.username,objArr);
        this.saved();
    }
    this.saved = function(){
        $('Growler').innerHTML = '';
    }
    this.addImage = function(image,x,y){

        if(this.options.maxImages > this.imageCount){
            var ci = CanvasImage.createFromImage(image,options)
            var div = ci.container;
            //console.log(ci.image);
            x = x-ci.image.getWidth();
            div.setStyle({
                top: y+'px',
                left: x+'px',
                zIndex: 1000
            });
            $('headerimageContainer').appendChild(div);
            this.init();
            this.pleaseSave();
        }else{
            growler.growl('You are only allowed to add '+this.options.maxImages+' images to your imageheader. Buy an <a href="clipr/help/imageheader" target="_blank">upgrade item</a>. Currently you have '+this.imageCount+' images in your header.',{life:10});
        }
    }

    this.toggleHeaderArea = function(){
        var h = $('header');
        var b = $('pulldown');
        if(h.style.display == ''){
            h.blindUp();
            b.className = 'pulldown_down';

            xajax_setUserParam(this.username,'dropdown','');
        }else{
            h.blindDown();
            b.className = 'pulldown_up';

            xajax_setUserParam(this.username,'dropdown','1');
        }
    }


    this.fixZIndexes = function(){
        // 1.: order by z-index
        var divs = this.container.select('.instanceWrapEditable').sort(function(e1,e2){
            return e1.style.zIndex - e2.style.zIndex;
        });
        // 2.: fix the sparse array (remove empty elements in z-index array
        var divs2 = [];
        var addToIndex = 1;
        divs.each(function(div){
           var id = div.id.split('_')[1];
           var z = parseInt(div.style.zIndex);

           if(!z || z=='' || z==0)
               z=1;

           if(typeof divs2[z]=='undefined'){
               divs2[z] = div;
           }else{
               divs2[z+addToIndex] = div;
               addToIndex++;
           }

        });

        // 3.: assign the indexes to the zIndex property of the images
        divs2.each(function(e,index){

            e.style.zIndex = index+1;
        });

    }
    this.makeDragable = function(){

        $$('img').each(function(img){

            var imgName = img.id.split('_');
            // initialise just the images- no imageinstances here
            if(imgName.length < 2 || imgName[0]!='img')
                return;
            new Draggable(img,{ ghosting: true,
                                revert: true,
                                scroll: window,
                                onStart:function(e){
                                    Element.extend(e);
                                    // disable the image link
                                    var img = e.element;
                                    img.parentNode.writeAttribute('onclick','if(this.dragging){this.dragging=false;return false;}');
                                    img.parentNode.style.overflow = '';
                                    img.parentNode.dragging = true;
                                    img.absolutize();

                                    cliprHeader.activateDropableHeader();
                                },
                                onEnd:function(e){
                                    cliprHeader.deactivateDropableHeader();
                                }
            });

        });
    }

}
