var photos = [], alt, gphoto;
var modifier = 20;
var Rules = {
  '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]);
    Controller.Top = Event.pointerY(event);
    new Ajax.Request(element.href,{onComplete: options[0] == 'update' ? Controller.Ajax.Update : options[0] == 'destroy' ? Controller.Ajax.Destroy : options[0] == 'cover' ? Controller.Ajax.Cover : options[0] == 'destroy' ? Controller.Ajax.UpdateAttribute : Controller.Ajax.Alert});
  },
  '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,'');*/
      }
    });
  },
  '#cover_opacity:click, #cover_close:click': function() {
    Controller.Cover.Hide();
  }
}

var Controller = {
  Ajax: {
    Alert: function(response) {
      alert(response.responseText);
    },
    Cover: function(response) {
      Controller.Cover.Show(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);
        }});
      } else
        alert(response.responseText);
    },
    Update: function(response) {
      Controller.Element.innerHTML = response.responseText;
      new Effect.Highlight(Controller.Element,{queue:'front'});
      reapply();
    }
  },
  Cover: {
    Hide: function() {
      $('cover').style.display = "none";
    },
    Show: function(text) {
      var container = $('cover_container');
      if (text)
        container.innerHTML = text;
      var opacity = $('cover_opacity');
      var cover = $('cover');
      var close = $('cover_close');
      var dimensions = Element.getDimensions(document.body);
      var cdimensions = Element.getDimensions(container);
      if (Controller.Top && (Controller.Top - cdimensions.height - 30) > 0) {
        container.style.top = (Controller.Top - cdimensions.height - 30) + 'px';
        close.style.top = (Controller.Top - cdimensions.height - 23) + 'px';
      } else {
        container.style.top = "10px";
        close.style.top = "3px";
      }
      if (Element.getDimensions(cover).height < dimensions.height)
        cover.style.height = dimensions.height + 'px';
      cover.style.display = "";
      container.style.display = "";
    }
  },
  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;
  },
  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));
      }
    }
  }
}

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});
      EventSelectors.assign(Rules);
    } selse
      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);}
// })