/***************************************************************************/
var ColorSlider = function(bar){
  var barSize = bar.getSize();
  barSize.x -=2;
  barSize.y -=2; //take border in consideration
  var barPosition = bar.getPosition();
  var rest = bar.getElement(".rest");
  bar.colors = bar.getElements(".color");
  bar.colors.each(function(color){
    var handle = color.getElement(".handle");
    var percent = color.getElement(".percent");
  
    if (handle){
      // convert percent to px (fix an IE bug)
      handle.setStyle("left", color.offsetWidth + "px");
      
      var colorSize = color.getSize();
      var restSize;
      var colorPosition = color.getPosition();
      var colorPercent =  color.getStyle("width").toInt();
  
      new Drag(handle, {
        handle: handle.getElement('.easierToCatch'),
        limit: {y: [0,0]},
        onDrag: function(handle){
          var formerWidth = color.offsetWidth;
          
          //compute new color width
          var newWidth = handle.getStyle("left").toInt();
          //is it more than 100% ?
          var widthUsed = 0;
          bar.colors.each(function(c){widthUsed += c.offsetWidth;})
          widthUsed = widthUsed - formerWidth + newWidth;
          if (widthUsed <= barSize.x && newWidth > 0){
            //set as color width and into label
            color.setStyle("width", newWidth+"px");
            percent.innerHTML= (newWidth / barSize.x * 100).toInt();
              
            // adjust rest simultaneously
            rest.setStyle("width", Math.max(0, barSize.x - widthUsed - 2) + "px")
          } else {
            var displayedPercent = 100;
            if(newWidth <= 0){
              displayedPercent = 0;
            }else{
              var formerPercent = percent.innerHTML.toInt();
              bar.colors.each(function(c){displayedPercent -= c.getElement(".percent").innerHTML.toInt()})
              displayedPercent = displayedPercent +formerPercent;
            }
            percent.innerHTML = displayedPercent;            
            handle.setStyle("left", "");
          }
        },
        onComplete: function(taskbar){
          handle.setStyle("left", "")
          // take current url, change the color percent with the new one
          var url_parameters = window.location.search;
          bar.colors.each(function(c){
            var color = c.getStyle("backgroundColor").replace("#", "");
            var percent = c.getElement(".percent").innerHTML.toInt();
            if(percent>0){
              url_parameters = url_parameters.replace(new RegExp(color + "_\\d+"), color + "_" + percent);
            }else{
              url_parameters = url_parameters.replace(new RegExp("colors_percents%5B%5D="+color + "_\\d+"), "");
            }
          })
          loading();
          window.location = window.location.pathname + url_parameters
        }
      });
    }    
  })
}

/***************************************************************************/
var RefineLinks = function(elt){
  elt.getElements("a").each(function(link){
    link.addEvent("click", loading);
  })
}
/***************************************************************************/
function loading(){
  $("loading").setStyles({"left": "50%", "display": "block"});
}

/***************************************************************************/
var lightbox = $("lightbox");
var container = lightbox.getElement(".container")
var img = container.getElement("img");
var similar = container.getElement("a");
var effect = new Fx.Morph(container);

img.addEvent("load", function(){
  var w = Math.min(img.width, window.getSize().x)
  var h = Math.min(img.height, window.getSize().y)
  if(w != img.width || h != img.height){
    if (window.getSize().x/window.getSize().y > img.width/img.height){
      h = window.getSize().y - 100
      w = h * img.width/img.height
    }else{
      w = window.getSize().x - 100
      h = w * img.height/img.width
    }
  }
  container.setStyles({
    "width": 0,
    "height": 0,
    "visibility": "visible"
  })
  effect.start({
    "marginTop": "-"+(h/2+5)+"px",
    "marginLeft": "-"+(w/2+5)+"px",
    "width": w,
    "height": h
  })
})

lightbox.show = function(url, similarUrl){
  img.setAttribute("src", url);
  similar.setAttribute("href", similarUrl);
  lightbox.setStyle("display", "block");
}

lightbox.getElement(".overlay").addEvent("click", function(){
  lightbox.setStyle("display", "none");
  img.setAttribute("src", "")  
  container.setStyles({
    "marginTop": "-5px",
    "marginLeft": "-5px",
    "width": "",
    "height": "",
    "visibility": "hidden"
  })
})

var Result = function(result){
  // first link is the image link
  var links = result.getElements("a")
  links[0].addEvent("click", function(e){
    e.stop();
    $("lightbox").show(links[0].href, links[1].href);
  })
}
/***************************************************************************/
// Bless elemeent with specific class with a behavior
function blessIfPossible(elt, behaviors){
  $A(elt.className.split(' ')).each(function(key){
    if (behaviors[key]){
      behaviors[key](elt); // bless elt with behavior
    }
  })
}

// association CSS class / corresponding behavior
behaviors = {
 "colorSlider": ColorSlider,
 "colorPalette": RefineLinks,
 "luminosity": RefineLinks,
 "saturation": RefineLinks,
 "imageResult": Result
}

function blessStructure(root, behaviors){
  blessIfPossible(root, behaviors);
  root.getElements("*").each(function(node){
    blessIfPossible(node, behaviors);
  })
}

blessStructure($(document.body), behaviors);

if ($(document.body).hasClass("ie6")){
  $$("#content .results .imageResult").each(function(box){
    box.addEvent("mouseenter", function(){box.addClass("hover")})
    box.addEvent("mouseleave", function(){box.removeClass("hover")})    
  })
}