var photos = [], alt, gphoto;
var modifier = 20;
var Rules = {
  // LINKS
  'a.confirm:click': function(element,event) {
    Event.stop(event);
    element = Event.findElement(event,'a');
    if (confirm(element.className.split('confirm ')[1].split(' ')[0].replace(/\_/ig,' ')))
      window.location = element.href + '?confirm=true';
  },
  'a.load:click': function(element,event) {
    Event.stop(event);
    element = Event.findElement(event,'a');
    var options = element.className.split('load ')[1].split(' ');
    Controller.Element = $(options[1]);
    new Ajax.Request(element.href,{onComplete: options[0] == 'update' ? Controller.Ajax.Update : options[0] == 'destroy' ? Controller.Ajax.Destroy : options[0] == 'destroy' ? Controller.Ajax.UpdateAttribute : Controller.Ajax.Alert});
  },
  'a.load_photo:loaded': function(element) {
    photos.push(element.className.split('load_photo ')[1].split(' ')[0]);
  },
  'a.load_photo:click': function(element,event) {
    Event.stop(event);
    element = Event.findElement(event,'a');
    alt = element.getElementsByTagName('img')[0].alt;
    Controller.Photo.Load(element.className.split('load_photo ')[1].split(' ')[0]);
  },
  '.swap:click': function(element,event) {
    Event.stop(event);
/*    element = Event.findElement(event,'a');*/
    var replace = $(element.className.split("swap ")[1].split(" ")[0]);
    while (element.id == "")
      element = element.parentNode;
    element.style.display = "none";
    replace.style.display = "";
  },
  'a.toggle:click': function(element,event) {
    Event.stop(event);
    element = Event.findElement(event,'a');
    if (arrow = Element.getChildByClass(element,'arrow'))
      arrow.src = Element.visible(element.className.split(" ")[1]) ? arrow.src.replace('down','right') : arrow.src.replace('right','down');
    var options = element.className.split('toggle ')[1].split(' ');
    new Effect.toggle($(options[0]),options[1] || 'blind',{duration:1,queue:'end'});
  },
  'h1:loaded': function(element) {
    Controller.sIFR(element,"red")
  },
  // FORM ELEMENTS
  'input.multiple:change': function(element) {
    var input = element.cloneNode(false);
    var file = element.parentNode.appendChild(document.createElement('div'));
    file.innerHTML = '<img alt="Attachment" align="top" src="/images/icons/attachment.gif" /> ' + element.value.replace(/\\/ig,'/').substring(element.value.replace(/\\/ig,'/').lastIndexOf('/')+1) + ' <a class="remove ' + element.id + ',' + element.id + '_holder tiny">(remove)</a>';
    file.id = element.id + '_holder'
    input.id = element.id + '_new';
    input.value = '';
    element.parentNode.appendChild(input,element);
    element.style.position = 'absolute';
    element.style.left = '-2000px';
    EventSelectors.assign(Rules);
  },
  'input.select_all:click': function(element) {
    $A(element.form.getElementsByTagName('input')).each(function(input) {
      if (input.type == 'checkbox') {
        input.checked = element.checked;
/*        if (Element.getParentByTagName(input,'TR'))
          Element.getParentByTagName(input,'TR').className = input.checked ? Element.getParentByTagName(input,'TR').className + ' selected' : Element.getParentByTagName(input,'TR').className.replace(/(selected)/ig,'');*/
      }
    });
  },
  'select.load:change': function(element) {
    if (element.value != "" && element.value != "none" && element.value != "other") {
      var options = element.className.split("load ")[1].split(" ");
      new Ajax.Updater(options[1], options[0] + "/" + element.value,{evalScripts:true});
    }
  },
  'textarea.editor:loaded': function(element) {
    if (typeof(document.designMode) == "string") {
      new Editor(element);
    }
  },
  // TABLES
  'tr.row1:click, tr.row2:click': function(element,event) {
    if (element.tagName == 'A' || element.tagName == 'INPUT' || element.tagName == 'SELECT' || element.tagName == 'BUTTON' || element.tagName == 'TEXTAREA')
      return false
    element = Event.findElement(event,'TR'); 
    $A(Event.findElement(event,'TR').getElementsByTagName('input')).each(function(input) {
      if (input.disabled == false) {
        if (input.type.toLowerCase() == 'checkbox')
          input.checked = !input.checked;
        else if (input.type.toLowerCase() == 'radio')
          input.checked = true;
      }
    });
  },
  // Controls
  '#slider:loaded': function(element) {
    new Control.Slider('slider_handle','slider',{axis:'horizontal', range: $R(25,128), onSlide: function(value) {
      document.getElementsByClassName('dashboard_item',$('dashboard')).each(function(item) {
        item.style.width = (value.toFixed() < 50 ? 50 : value.toFixed()) + 'px';
        item.style.height = (value.toFixed() < 50 ? 60 : (value + 10).toFixed()) + 'px';
        item.getElementsByTagName('img')[0].style.width = value.toFixed() + "px";
      })
    }});
  }
}

var Controller = {
  Ajax: {
    Alert: function(response) {
      alert(response.responseText);
    },
    Destroy: function(response) {
      if (parseBoolean(response.responseText)) {
        new Effect.Highlight(Controller.Element,{queue:'front',startcolor:'#FFCDCC',afterFinish: function() {
          Controller.Element.parentNode.removeChild(Controller.Element);
        }});
/*        reapply();*/
      } else
        alert(response.responseText);
    },
    Update: function(response) {
      Controller.Element.innerHTML = response.responseText;
      new Effect.Highlight(Controller.Element,{queue:'front'});
      reapply();
    }
  },
  Duplicate: {
    Above: function(element,remove) {
      var duplicate = element.cloneNode(false);
      if (typeof(duplicate.value) != 'undefined')
        duplicate.value = '';
      element.parentNode.insertBefore(duplicate,element);
      element.parentNode.insertBefore(document.createElement('br'),element);
      duplicate.focus();
      reapply();
    }
  },
  List: {
    Reorder: function(container,className) {
      var rows = document.getElementsByClassName(className,$(container));
      for(i=0;i<rows.length;i++) {
        rows[i].className = rows[i].className.replace(/(row\d)/,'row' + (i%2+1));
      }
    }
  },
  Photo: {
    Buttons: function() {
      $('photo_holder').style.overflow = 'visible';
      if (photos.length > 1) {
        if (photos.indexOf(gphoto) + 1 == photos.length)
          $('previous').style.display = '';
        else if (photos.indexOf(gphoto) == 0)
          $('next').style.display = '';
        else {
          $('previous').style.display = '';
          $('next').style.display = '';
        }
      }
      if (!Element.visible('photo_details'))
        new Effect.BlindDown('photo_details', {queue: 'end', duration: .5});
    },
    Drop: function(drag,drop) {
      if (drop = drop.getElementsByTagName('iframe')[0]) {
        drag = drag.getElementsByTagName('img')[0];
        drop = drop.contentWindow.document;
        drop.execCommand("InsertImage",false,drag.src.replace("small","medium"));
      }
    },
    Load: function(photo) {
      if (photo) {
        gphoto = photo;
        $('photo_details_detail').innerHTML = '<div class="tiny float_left">(' + (photos.indexOf(photo)+1) + ' of ' + photos.length + ')</div><div class="tiny float_right"><a onclick="Controller.Cover.Hide();">Close</a></div>' + alt;
        var image = document.createElement('img');
        var container = $('container');
        $('previous').style.display = 'none';
        $('next').style.display = 'none';
        container.innerHTML = '';
        image.src = photo;
        image.id = 'photo';
        image.style.display = 'none';
        container.appendChild(image);
        var spinner = $('spinner');
        if (!Element.visible(spinner))
          Element.toggle(spinner);
        setTimeout('Controller.Photo.Load()',1);
      } else {
        var photo = $('photo');
        if (photo.height > 0 && photo.width > 0) {
          var cover = $('cover');
          var spinner = $('spinner');
          var photo_holder = $('photo_holder');
          var ph = photo.height + modifier;
          var pw = photo.width + modifier;
          photo.style.display = 'none';
          if (Element.visible(spinner))
            spinner.style.display = 'none';
          if (!Element.visible(cover))
            cover.style.display = '';
          var dimensions = Element.getDimensions(photo_holder);
          var h = ph / dimensions.height * 100;
          var w = pw / dimensions.width * 100;
          if ((h > 98 && h < 102) && (w > 98 && w < 102))
            new Effect.Appear(photo, {queue: 'front', duration: .25, afterFinish: function() {
              Controller.Photo.Buttons();
            }});
          else {
            /*if (Element.visible('photo_details'))
              new Effect.BlindUp('photo_details', {queue: 'end', duration: .5});*/
            new Effect.Scale(photo_holder, h, {queue: 'end', scaleContent: false, scaleFromCenter: true, scaleX: false, scaleY: true});
            new Effect.Scale(photo_holder, w, {queue: 'end', scaleContent: false, scaleFromCenter: true, scaleX: true, scaleY: false});
            new Effect.Appear(photo, {queue: 'end', duration: .25, afterFinish: function() {
                Controller.Photo.Buttons();
            }});
          }
        } else
          setTimeout('Controller.Photo.Load()',1000);
      }
    }
  },
  FlashTag: function(src, width, height, vars, bgcolor) {
    var version = '7,0,14,0';
    var ie = (navigator.appName.indexOf ("Microsoft") != -1) ? 1 : 0;
    var tag = new String();
    if (ie) {
      tag += '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" ';
      tag += 'codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version='+version+'" ';
      tag += 'width="'+width+'" ';
      tag += 'height="'+height+'">';
      tag += '<param name="movie" value="'+src+'"/>';
      tag += '<param name="quality" value="best"/>';
      tag += '<param name="wmode" value="transparent"/>'
      tag += '<param name="flashvars" value="'+vars+'"/>';
      tag += '</object>';
    } else {
      tag += '<embed src="'+src+'" ';
      tag += 'quality="best" ';
      tag += 'wmode="transparent" '
      tag += 'width="'+width+'" ';
      tag += 'height="'+height+'" ';
      tag += 'type="application/x-shockwave-flash" ';
      tag += 'flashvars="'+vars+'" ';
      tag += 'pluginspage="http://www.macromedia.com/go/getflashplayer">';
      tag += '</embed>';
    }
    return tag;
  },
  sIFR: function(element,bgcolor) {
    element.innerHTML = Controller.FlashTag("/images/fonts/spring_lp.swf", element.offsetWidth, element.offsetHeight, "txt=" + element.innerHTML.replace(/\+/ig,"%2B").replace(/\&/g,"%26").replace(/\"/g, "%22") + "&w=" + element.offsetWidth + "&h=" + element.offsetHeight + "&textcolor=#ffffff", bgcolor);
  },
  Turn: {
    Off: function(element) {
      element.src = element.src.replace('_on.gif','.gif');
    },
    On: function(element) {
      element.src = element.src.replace('.gif','_on.gif');
    }
  }
}

var Handlers = {
  onCreate: function() {
    if (!Element.visible('spinner'))
      $('spinner').style.display = '';
  },
  onComplete: function() {
    if (Element.visible('spinner') && Ajax.activeRequestCount == 0) {
      new Effect.Fade('spinner',{queue:'end',duration:.5});
      reapply();
    } else
      setTimeout("Handlers.onComplete()",1000);
  }
}
Ajax.Responders.register(Handlers);


function parseBoolean(value) {
  return value.toLowerCase() == 'true'
}

function reapply() {
  EventSelectors.assign(Rules);
}




// EventSelectors 
// Copyright (c) 2005-2006 Justin Palmer (http://encytemedia.com)
// Examples and documentation (http://encytemedia.com/event-selectors)
// 
// EventSelectors allow you access to Javascript events using a CSS style syntax.
// It goes one step beyond Javascript events to also give you :loaded, which allows 
// you to wait until an item is loaded in the document before you begin to interact
// with it.
//
// Inspired by the work of Ben Nolan's Behaviour (http://bennolan.com/behaviour)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// 
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//
// This version of the software includes the Sasser fix to remove the infinite
// loop on element:loaded when there are more than one element

var EventSelectors = {
  version: '1.0_pre',
  cache: [],
  
  start: function(rules) {
    this.rules = rules || {};
    this.timer = new Array();
/*    this.startTime = new Date(); */
    this._extendRules();
    this.assign(this.rules);
  },
  
  assign: function(rules) {
    var observer = null;
	  var x = 0;
    this._unloadCache();
    rules._each(function(rule) {
      var selectors = $A(rule.key.split(','));
      selectors.each(function(selector) {        
        var pair = selector.split(':');
        var event = pair[1];
        $$(pair[0]).each(function(element) {
          if(pair[1] == '' || pair.length == 1) return rule.value(element);
          if(event.toLowerCase() == 'loaded') {
			      x++;
            this.timer[pair[0] + x] = setInterval(this._checkLoaded.bind(this, element, pair[0] + x, rule), 15);
          } else {
            observer = function(event) {
              var element = Event.element(event);
              if (element.nodeType == 3) // Safari Bug (Fixed in Webkit)
            		element = element.parentNode;
              rule.value($(element), event);
            }
            this.cache.push([element, event, observer]);
            Event.observe(element, event, observer);
          }
        }.bind(this));
      }.bind(this));
    }.bind(this));
/*    document.write('event:Selectors Execution: ' + (new Date() - this.startTime) + 'ms');*/
  },
  
  // Scoped caches would rock.
  _unloadCache: function() {
    if (!this.cache) return;
    for (var i = 0; i < this.cache.length; i++) {
      Event.stopObserving.apply(this, this.cache[i]);
      this.cache[i][0] = null;
    }
    this.cache = [];
  },
  
  _checkLoaded: function(element, timer, rule) {
    var node = $(element);
    if(element.tagName != 'undefined') {
      clearInterval(this.timer[timer]);
      rule.value(node);
    }
  },
  
  _extendRules: function() {
    Object.extend(this.rules, {
     _each: function(iterator) {
       for (key in this) {
         if(key == '_each') continue;         
         var value = this[key];
         var pair = [key, value];
         pair.key = key;
         pair.value = value;
         iterator(pair);
       }
     }  
    });
  }
}

// Remove/Comment this if you do not wish to reapply Rules automatically
// on Ajax request.
// Ajax.Responders.register({
//   onComplete: function() { EventSelectors.assign(Rules);}
// })