function htmlspecialchars(str,typ) {
    if(typeof str=="undefined") str="";
    if(typeof typ!="number") typ=2;
    typ=Math.max(0,Math.min(3,parseInt(typ)));
    var from=new Array(/&/g,/</g,/>/g);
    var to=new Array("&amp;","&lt;","&gt;");
    if(typ==1 || typ==3) {from.push(/'/g); to.push("&#039;");}
    if(typ==2 || typ==3) {from.push(/"/g); to.push("&quot;");}
    for(var i in from) str=str.replace(from[i],to[i]);
    return str;
}

var Clipr={};
Clipr.editActive = false;

Clipr.unlinkImages = function(){
    $('imagelist').select('img').each(function(img){
        img.parentNode.writeAttribute('onclick','Clipr.toggleImageSelection('+img.id.split('_')[1]+');return false;');
    });
    $('imagelist').select('.imageCheck').each(function(div){
        div.show();
    });
}
/**
 * enables advanced options
 */
Clipr.toggleEditMode = function(){
    
    if(Clipr.editActive){
        
        Clipr.editActive = false;
        if($('imagelist')){
            $('imagelist').select('img').each(function(img){
                img.parentNode.writeAttribute('onclick','');
            });

            $('imagelist').select('.imageCheck').each(function(div){
                div.hide();
            });
        }
    }else{
        Clipr.editActive = true;
        if($('imagelist')){
            Clipr.unlinkImages();
            
        }
        
    }
}

/**
 * selects images in the imagelist which are not selected and visa versa
 * checkboxes are checked/unchecked
 */
Clipr.toggleImageSelection = function(imgUid){
    // toggle just one image
    try{
        if(imgUid){
            var cb = $('cb'+imgUid);
            var image = $('img_'+imgUid);
            if(cb.checked){
                cb.checked = false;
                image.removeClassName('highlighted');
            }else{
                cb.checked = true;
                image.addClassName('highlighted');
            }
        }else{  // or toggle all images
            
            $('imagelist').select('img').each(function(img){
                Clipr.toggleImageSelection(img.id.split('_')[1]);
            });

        }
    }catch(e){
        console.log(e);
    }
}
/**
 * adds margin and reflection to images in the list
 */
Clipr.tidyList = function(listname,showShaddow){
    
    var h = $('header');
	if(!listname)
        listname = 'imagelist';
    if($(listname)){
    
        //$(listname).select('img').each(function(img){
        $(listname).select('.imageDiv').each(function(div){
        	
           var img = div.select('img')[0];
           //h.innerHTML = img.parentNode.parentNode.innerHTML;
			   //var margin = (img.parentNode.parentNode.getHeight()-img.getHeight())/2;
			   var margin = (div.getHeight()-img.getHeight())/2;
	           margin -= 5;
	           img.setStyle({marginTop: margin+'px'});
	           if(showShaddow)
	                Reflection.add(img,{ height: margin, opacity: 2/3 });
		   
        });
    }
    
}




function EventManager(){
  
  var tagsAdded = 0;
  var projsAdded = 0;

  var username;
  var imageId;
  var projectId;
  var baseUrl;

  var tooltips = new Array();
  
  this.init = function(baseUrl){
    if($('addTagButton'))
       $('addTagButton').observe('click', this.addTag.bindAsEventListener(this));
    if($('saveTagButton'))
       $('saveTagButton').observe('click',this.saveTag.bindAsEventListener(this));
    if($('addProjectButton'))
       $('addProjectButton').observe('click',this.addProject.bindAsEventListener(this));
    if($('saveProjectButton'))
       $('saveProjectButton').observe('click',this.saveProject.bindAsEventListener(this));
   
    
	this.baseUrl = baseUrl;
    var path = path = xajax.config.requestURI.split('/');
    for(var i=0;i<path.length-1;i++){
      if(path[i] == 'users'){
        this.username = path[i+1];
      }else if(path[i] == 'image'){
        this.imageId = path[i+2];
      }else if(path[i] == 'collection'){
        this.projectId = path[i+2];
      }
    }
    
    this.assignTooltips();
    
  }
  
  

  this.getSelectedImageIds = function(){
    var imageIds = [];
    $('imagelist').select('input[type=checkbox]').each(function(cb){
    if(cb.checked)
      imageIds.push(cb.value);
    });
    imageIds = imageIds.join(',');

    if(!imageIds)
        growler.growl('You have to select some images first!');

    return imageIds;
  }
  this.addTooltip = function(elementId,html){
      tooltips[elementId] = new Tooltip(elementId);
      tooltips[elementId].setInnerHTML(html);
  }
  this.setTooltipHTML = function(elementId,html){
      
      tooltips[elementId].setHTML(html);
  }
  this.assignTooltips = function(){
      $$('.tooltip').each(function(elem){
         var targetId = elem.id.sub('Tooltip','');
         tooltips[targetId] = new Tooltip(targetId,elem.id);
      });
  }
  this.bindButton = function(elementId,method){
      if($(elementId)){
       $(elementId).observe('click', method.bindAsEventListener(this));
      }
  }
  this.saveTag = function(){
    var tags = '';
    for(var i=0;i<tagsAdded;i++){
      tags += $('newtag'+i).value+',';
      $('saveTagButton').style.display = 'inline';
    }
	
	new Ajax.Updater('taglist', this.baseUrl+'users/'+this.username+'/image/addtags/'+this.imageId+'/', {
		method: 'post',
		parameters: { 'tags': tags }
	});
    tagsAdded=0;
    $('saveTagButton').hide();
  }
  this.deleteTag = function(tagId){
	new Ajax.Updater('taglist', this.baseUrl+'users/'+this.username+'/image/deletetags/'+this.imageId+'/', {
		method: 'post',
		parameters: { 'tag': tagId }
	});
    tagsAdded = 0;
    $('saveTagButton').hide();
  }
  this.addTag = function(event){
    if(event.isLeftClick() || event.keyCode == Event.KEY_RETURN){
        $('taglist').insert({top: '<li><input type=\'text\' name=\'newtag'+tagsAdded+'\' id=\'newtag'+tagsAdded+'\' class=\'tagbox\' /></li>'});
        $('newtag'+tagsAdded).focus();
        $('newtag'+tagsAdded).observe('keydown',this.addTag.bindAsEventListener(this));
        tagsAdded++;
        $('saveTagButton').style.display = 'inline';
    }
    return false;
  }
  this.addProject = function(event){
    if(event.isLeftClick() || event.keyCode == Event.KEY_RETURN){
        $('projmenu').insert({top: '<li><input type=\'text\' name=\'newproj'+projsAdded+'\' id=\'newproj'+projsAdded+'\' class=\'tagbox\' /></li>'});
        $('newproj'+projsAdded).focus();
        $('newproj'+projsAdded).observe('keydown',this.addProject.bindAsEventListener(this));
        projsAdded++;
        $('saveProjectButton').style.display = 'inline';
    }
    return false;
  }
  this.saveProject = function(){
    var projs = '';
    for(var i=0;i<projsAdded;i++){
      projs += $('newproj'+i).value+',';
    }
    xajax_addProjects(this.username,projs);
    projsAdded=0;
    $('saveProjectButton').hide();
  }
  this.deleteProject = function(){
    if(confirm('Do you really want to delete this collection?')){
        xajax_deleteProject(this.username,this.projectId);
        projsAdded = 0;
    }
  }
  this.buyImage = function(){
    $('buy').innerHTML = '<div class="spinner"></div>';
    xajax_buy(this.imageId);
  }
  this.boughtImage = function(){
    
  }
  this.displayInput = function(sender){
    if(!sender.editing){
      var id = sender.id;
      sender.className = "";
      sender.editing = true;
      sender.innerHTML = '<input type="text" name="tb_'+id+'" id="tb_'+id+'" value="'+sender.innerHTML+'" /><a href="'+document.location.href+'#" onclick="xajax_save'+id+'(\''+this.username+'\',\''+this.imageId+'\',$(\'tb_'+id+'\').value);return false;" >[save]</a>';
    }
  }
  this.displayProjectInput = function(sender){
    if(!sender.editing){
      var id = sender.id;
      sender.className = "";
      sender.editing = true;
      sender.innerHTML = '<input type="text" name="tb_'+id+'" id="tb_'+id+'" value="'+sender.innerHTML+'" /><a href="'+document.location.href+'#" onclick="xajax_save'+id+'(\''+this.username+'\',\''+this.projectId+'\',$(\'tb_'+id+'\').value);return false;" >[save]</a>';
    }
  }
  this.displayTextarea = function(sender){
    if(!sender.editing){
      var id = sender.id;
      var height = $(id).getHeight()+'px';
      var html = sender.innerHTML.toString();
      html = html.replace(/<br>/g,'\n');
      html = html.replace(/<h2>/g,'==');
      html = html.replace(/<\/h2>/g,'==');
      sender.className = "";
      sender.editing = true;
      sender.innerHTML = '<textarea type="text" name="tb_'+id+'" id="tb_'+id+'">'+html+'</textarea><a href="'+document.location.href+'#" onclick="xajax_save'+id+'(\''+this.username+'\',\''+this.imageId+'\',$(\'tb_'+id+'\').value);return false;" >[save]</a>';
      $('tb_'+id).style.height = height;
      $('tb_'+id).focus();
    }
  }

  this.addImagesToProject = function(){
    var dd = $('ddProjects');
    var imageIds = this.getSelectedImageIds();
    if(dd.options.length){
        if(imageIds.length){
            var projId = dd.options[dd.selectedIndex].value;
            xajax_addImagesToProject(this.username,projId,imageIds);
        }
    }else{
        growler.growl('You have to create a collection first!');
    }
  }

  this.removeImagesFromProject = function(){
    var imageIds = this.getSelectedImageIds();
    if(imageIds.length){
        xajax_removeImagesFromProject(this.username,this.projectId,imageIds);
    }
    
  }

  this.deleteImages = function(){
      var imageIds = this.getSelectedImageIds();
      if(imageIds){

        if(confirm('Do you really want to delete the selected images? All users which have bought one of these images will lose them!')){
            xajax_deleteImages(this.username,imageIds);
        }
      }
  }
  this.saveProfileImage = function(){
    xajax_saveProfileImage(this.username,this.imageId); 
  }
  this.showSendAsPresent = function(){
      $('sendAsPresent').innerHTML = 'Enter username or emailadress: <input type="text" name="sendTo" id="sendTo" /><input type="button" name="bSendTo" value="send" onclick="ev.sendAsPresent();"/><div id="sendToChoices"></div><div id="sendToMessage"></div>';
      //new Ajax.Autocompleter("sendTo", "sendToChoices", "/users/"+this.username+"/customers", {});
      //new Ajax.Updater("sendToChoices","/users/"+this.username+"/customers")
      new Ajax.Request("users/"+this.username+"/customers", {
          method: 'get',
          onSuccess: function(transport) {
            $('sendToChoices').innerHTML = transport.responseText;
            $('sendToChoices').select('li').each(function(li){
                li.innerHTML = '<a href="#" onclick="return false;">'+li.innerHTML+'</a>';
                li.observe('click',function(){
                    $('sendTo').value = this.childNodes[0].innerHTML;
                });
            });
          }
      });

      $('sendTo').focus();
  }
  this.sendAsPresent = function(){
      $('sendToMessage').innerHTML = '<div class="spinner"></div>';
      xajax_sendAsPresent(this.username,this.imageId,$('sendTo').value);
  }
  
  
}




