// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
/*Hash.prototype.toQueryString = function() {
	var s = [];
	var k = this.keys();
	var a = $A(arguments[0] || []);
	if(arguments[1]) a.push(arguments[1]);
	for(var i=0;i<k.length;i++) {
		var p,v = this.get(k[i]);
		if(a.length == 0) p = k[i];
		else p = a[0]+"["+a.slice(1).concat([k[i]]).join("][")+"]";
		if(typeof(v) == "object") {
			if(Object.isArray(v)) {
				s.push(encodeURIComponent(p)+"="+encodeURIComponent(v.first()));
			} else {
				s.push($H(v).toQueryString(a,k[i]));
			}
		} else if(typeof(v) != 'function') {
			s.push(encodeURIComponent(p)+"="+encodeURIComponent(v));
		}
	}
	return s.join("&");
}
*/

Effect.ScrollTo = Class.create(Effect.Base, {
      initialize: function(element) {
              var options = Object.extend({
                      x: 0,
                      y: 0
              }, arguments[0] || { });
              this.start(options);
      },
      setup: function() {
              scroll_offs = document.viewport.getScrollOffsets()
              this.originalLeft = parseFloat(scroll_offs.left || '0');
              this.originalTop = parseFloat(scroll_offs.top || '0');
              this.options.x = this.options.x - this.originalLeft;
              this.options.y = this.options.y - this.originalTop;
      },
      update: function(position) {
              window.scrollTo(
                      (this.options.x * position + this.originalLeft).round(),
                      (this.options.y * position + this.originalTop).round()
              )
      }
});

function closeTextContainer(which) {
  new Effect.ScrollTo({ duration: 0.5, x: 0, y: 0 });

  var textContainer = $('textContainer')
  if(textContainer && textContainer.visible() && !textContainer.innerHTML.blank()) {
    textContainer.reloadURL = which && which.src
    Effect.Fade(textContainer,{
      afterFinish: function(eff) {
        $('back').hide();
//         if(eff.element.reloadURL) document.location = eff.element.reloadURL
      }
    });
  return false;
  } else return true;
}

Entry = {
  over: function(which) {
    which = $(which);
    if(which.hasClassName('over')) return;
    var m = which.className.match(/entry_\d+/);
    if(!m) return;
    $$('.'+m[0]).each(function(el) {
      el.addClassName('over');
      if(el.hasClassName('pictContainer')) Entry.morphOver(Element.up(el));
//      new Effect.Opacity(el,{ from: 1.0, to: 0.5 , duration : 0.3 });
    });
  },
  out: function(which) {
    which = $(which);
    if(!which.hasClassName('over')) return;
    var m = which.className.match(/entry_\d+/);
    if(!m) return;
    $$('.'+m[0]).each(function(el) {
//      new Effect.Opacity(el,{ from: 0.5, to: 1.0 , duration : 0.3 });
			if(el.hasClassName('pictContainer')) Entry.morphOut(Element.up(el));
      el.removeClassName('over');
    });
  },
  click: function(which) {
    var li = $(which);

    if(li.nodeName != 'LI') {
       li = li.up('li');
      if(!li) return;
    }
    $$('.pictContainer .'+li.id+' a').invoke('onclick');

    li.addClassName('active');
    li.siblings().each(function(li){
      li.removeClassName('active');
    });
  },
  change: function(opts) { //id,level,root_id,content) {
    for(var i=2;i>opts["level"];i--) {
      if($('level_'+i+"_container").visible()) new Effect.Fade('level_'+i+"_container",{duration: 0.3});
    }
    var homeimages = $('entryImageContainer');
    if(opts["level"] == 0) {
      if(!homeimages.visible()) {
        new Effect.Appear(homeimages);
      }
      this.text();
    } else {
      if(homeimages.visible()) {
        new Effect.Fade(homeimages);
      }
      var element = $('level_'+opts["level"]+"_container");
      if(element) {
        if(element.visible()) {
          element.newContent = opts["content"] ? opts["content"] : "";
          if(opts.edit) {
            element.hide();
            element.down('ul').update(element.newContent);
            element.show();
            this.sortable(opts);
          } else {
            new Effect.Fade(element,{
              duration: 0.3,
              afterFinish: function(eff) {
                eff.element.down('ul').innerHTML = eff.element.newContent;
                new Effect.Appear(eff.element);
              }
            });
          }
        } else {
          element.down('ul').update(opts["content"]);
          if(opts.edit) {
            element.show();
            this.sortable(opts);
          } else {
            new Effect.Appear(element);
          }
        }
      }
    }


    var images = $('pageImageContainer').immediateDescendants();
    for(var i=0;i<images.length;i++) {
      var image = images[i];
      if(image.id == "entry_"+opts["root_id"]+"_image") {
        if(!image.visible())
          new Effect.Appear(image);
      } else if(image.visible()) {
          new Effect.Fade(image);
      }
    }
  },
  sortable: function(opts) {
    var year = opts['year']
		/*
    for(var s in Sortable.sortables) {
      Sortable.destroy(s);
      Element.removeClassName(s,'sorting');
    }
		*/
    var element = $('level_'+opts["level"]);
    if(opts["add_button"] && !opts["add_button"].blank()) {
      $('level_'+opts["level"]+"_container").select("input").invoke('remove');
      element.insert({after: opts["add_button"]});
    }

    element.addClassName('sorting');
    Sortable.create(element,{
        format: /^(.*)$/,
        //handle: 'handle',
        onUpdate: function(cont) {
        	var p = Sortable.serialize(cont);
          new Ajax.Request("/entries/", {
            method: "post",
            parameters: encodeURI(p)
          });
        }
    });
  },
  text: function(content,instant) {
    var tc = $('textContainerContent');
    if(instant) {
      tc.update(content);
      tc.show();
      return;
    }
    if(content.blank() && tc.innerHTML.blank()) return;
    if(!tc.innerHTML.blank()) {
      new Effect.Opacity(tc,{
          from: 1, to: 0,
          duration: 0.3,
          afterFinish: function(eff) {
						eff.element.scrollTop = 0;
          eff.element.update(content);
					eff.element.show();
          new Effect.Opacity(eff.element, {
//            duration: 0.3,
            from:0, to:1
            });
          }
      });
    } else {
			tc.setOpacity(0);
      tc.update(content);
			tc.scrollTop = 0;

//			tc.show();
      new Effect.Opacity(tc, {
//        duration: 0.4,
        from:0, to:1
      });

    }
  },
  reset: function() {
  	if(! $('pageCont').visible()) {
  					pageswitch();
  	} else if($("entryImageContainer").visible()) {
  					pagerevert();
		} else {
			new Effect.Appear("entryImageContainer");
			var f = $('pageImageContainer').select('div').select(function(i){
				return i.visible();
			});
			f.push($('level_1_container'));
			f.push($('level_2_container'));
			f.push($('textContainerContent'));
			Effect.multiple(f, Effect.Fade,{
				afterFinish: function(eff) {$('textContainerContent').update();}
			});
		}
  },

  morphSomethingToDo: false,
  morphStartLoop: function() {
  	this.morphElements = $$('td.pictContainer');
  	if(this.morphElements.size = 0) return;
  	this.morphElements.each(function(me){
  		me.state = 0.0;
			me.image = me.down(".mediaObject");
			me.image.setStyle({top: "0px",left: "0px"});
  		me.setStyle({zIndex: 1000});
  	});
  	window.setInterval(Entry.morphLoop,50);
  },
  morphLoop: function() {
  	var stillSomethingToDo = false;
  	var me, newZindex;
  	if(!Entry.morphSomethingToDo) return;
		for(var i=0;i<Entry.morphElements.length;i++) {
  		me = Entry.morphElements[i];
  		if((me.state == 0 && !me.over) || (me.state == 1 && me.over)) continue;
  		me.state = me.state + 0.1 * (me.over ? 1 : -1);
  		if(me.state < 0) me.state = 0;
  		if(me.state > 1) me.state = 1;
  		factor =   Effect.Transitions.sinoidal(me.state);
  		me.image.style.top = -(8*factor).round()+"px";
  		me.image.style.left = -(12*factor).round()+"px";
  		me.image.style.width = (120+24*factor).round()+"px";
  		me.image.style.height = (80+16*factor).round()+"px";
		//	newZindex = 1000+(me.state*10).round();
  	//	if(newZindex != me.image.style.zIndex) me.image.style.zIndex = newZindex;
  		stillSomethingToDo = true;
  	}
  	Entry.morphSomethingToDo = stillSomethingToDo;
  },
  morphOver: function(e) {
  	if(typeof(e.state) == "undefined") {
  		/*
  		if(!e.startbutton) e.startbutton = e.down('.videoStart');
  		if(e.startbutton)	new Effect.Appear(e.startbutton,{
  				duration: 0.3,
  				afterFinish: function(eff) {

  				}
  		});
  		*/
  		return;
  	}
  	for(var i=0;i<this.morphElements.length;i++) {
  		var me = this.morphElements[i];
  		if(e == me) {
  			me.over = true;
  			if(me.state == 0) this.morphSomethingToDo = true;
  		} else {
  			me.over = false;
  			if(me.state > 0) this.morphSomethingToDo = true;
  		}
  	}
  },
  morphOut: function(e) {
  	if(typeof(e.state) == "undefined") {
  		//if(!e.startbutton) new Effect.Fade(e.startbutton,0.3);
  		return;
  	}
		for(var i=0;i<this.morphElements.length;i++) {
  		var me = this.morphElements[i];
  		me.over = false;
  		if(me.state > 0) this.morphSomethingToDo = true;
  	}
  }
}

function pageswitch() {
	new Effect.Parallel([
		new Effect.Fade('pageStart'),
		new Effect.SlideDown('pageCont')
	],{
	});
}
function pagerevert() {
	marquee("my_restart");
	new Effect.Parallel([
		new Effect.Appear('pageStart'),
		new Effect.SlideUp('pageCont')
	],{
	});
}

function marquee(f) {
	($("marquee_flash")[f] ? $("marquee_flash") : document.marquee_flash)[f]()
}


