// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

/* Hackery Scrolling

		The first DOM object in a containing DOM object has it's left margin set to a negative value and the value is incremented 1px every 1/100 sec (if pc has the nuts)
		until it is negatively positioned with it's margin outside of the viewable area. Then it is removed and appended to end of the DOM container it originated from.
		The next DOM object in line has its margin negated until out of viewable area and so on...
		The css float of the DOM objects in the containing block redraw when the first DOM object in line is moved so we get smooth scroll.  
		
		Passing 'true' to the constructor will insert buttons to start/stop the scroll.
		--like so: scrollz = new GalleryScroll("inner-gallery-list-0", "true"); 

*/
var GalleryScroll = Class.create();
var steadyHack=0;
function doSteadyMove() {
  steadyHack.doMove();
  setTimeout("doSteadyMove()", 40);
}
GalleryScroll.prototype = {
	pe: 0,																																			// holds our instance of the PeriodicalExecuter object - this is the meaty part of how we control the movement
	status: 1,																																	// status of if scroller is scrolling - used with buttons
	firstCall: 0,																																// initialization value to store the test to see if a DOM object needs its initial margin value set or not
	howWide: 0,																																	// initialization value to store the DOM object width that is being moved - used for deciding whe to shuffle a DOM object to the end of the line
	steady_interval: 0.08,
	interval: 0.02,																															// set time between 1px movements of the scrolling stuff. right now it moves stuff 100px/sec (if the browser/system speed allows)

	initialize: function(container, scroll_type, control_container, dev) {
		this.container = container;																								// store the DOM object that contains all of the stuff to be scrolled - used later to shuffle stuff to the back of the line
		this.mover = $(this.container).down(0);																		// read the first DOM object of the DOM object that contains the stuff to be scrolled
    this.scrollType = scroll_type;                                            // set as either "steady" or "triggered" - if "triggered" control_container needs to be passed to
    this.controlContainer = control_container;                                // stores the string that $$ uses to find the DOM object which contains a collection of elements (two of them) that control the direction of scroll onmouseover - one with a class of "scroll-arrows-left" and the other with the class of "scroll-arrows-right"
		
		var totalWidth = $(this.container).childElements().inject(0, function(acc, n){ return acc + n.getWidth()});
		var scrollingSpaceWidth = $(this.container).up().getWidth();
				
    switch(this.scrollType) {
      case 'steady': 
        // this.pe = new PeriodicalExecuter(this.doMove.bind(this), this.steady_interval);  // starts the call to doMove function and sets it to call every 1/100sec - PeriodicalExecuter is better than setInterval/setTimeout as it has flags that will not let new instances spawn on top of long running ones (this could seriously break your shit) 
       break;
      case 'triggered': 
        if (totalWidth > scrollingSpaceWidth) {
					this.addObservers();                                                      // adds mouse events to the control elements contained in the control_container DOM object
				};
       break;
      default: return null;
		};
		
		if (dev == 'true' && this.scrollType == 'steady') {this.addControlButtons()};														// if string 'true' is passed in the constructor this calls the function to add buttons to stop/start scroll. useful if you doing development and don't want the scroller running all the time but don't want to comment out the initialization
  },
  startSteady: function() {
    steadyHack = this;
    doSteadyMove();
  },
  addObservers: function(){
    var events = {
      mouseOver: this.scrollControlArrows.bindAsEventListener(this),
      mouseOut:  this.stopScroll.bind(this)
    };
    var arrows = $$(this.controlContainer);
    arrows.each(function (item, index) {
      Element.show(item.down());
      Event.observe(item, 'mouseover', events.mouseOver);
      Event.observe(item, 'mouseout', events.mouseOut);
    });
  },
  scrollControlArrows: function(event){
    var arrow = Event.element(event).up(0);
    switch(Event.element(event).className) {
      case 'scroll-arrows-left': 
			  this.pe = new PeriodicalExecuter(this.doMoveRev.bind(this), this.interval);
       break;
      case 'scroll-arrows-right': 
			  this.pe = new PeriodicalExecuter(this.doMove.bind(this), this.interval);  
       break;
      default: return null;
    };
  },
	doMove: function() {
		var pub, positioning, howFar;

		if (this.firstCall == 0) {																								// test if this DOM object is newly leading at the head of the line
			$(this.mover).setStyle({"marginLeft" :"-1px"});													// set new head of the line with initial margin value of -1px - setting it to 0 makes it look like the animation is stuttering
			this.firstCall = 1;																											// set objects firstCall so that it tests false and the objects margin is progressively reduced and the DOM object slide to the left
			this.howWide = $(this.mover).getWidth();																// grab DOM object width for later testing
		};
			
 		if(parseInt(this.mover.style.marginLeft) <= -this.howWide){								// test current negative margin against the DOM object width to determine if it needs to be set to the back of the line
 			pub = $(this.mover);																								    // set current DOM object to local variable as it now out of view and needs to be moved
 			this.mover = $(this.mover).next();																			// sets the second in line as the new DOM item we operate on 
 			this.firstCall = 0;																											// reset objects firstCall value so margin value will be set on DOM object that now heads the line	
 			this.outOfFrame = $(pub).remove();																			// remove out of view DOM object from front of floated elements
 			$(this.outOfFrame).setStyle({"marginLeft" :"0", cssFloat : 'left'});    // set style attribues on out of view DOM object - not resetting the margin will place it under the one before it due to the negative margin
 			Element.insert(this.container, this.outOfFrame);												// add out of view DOM object to end of image row
 		};
	
 		positioning = parseInt(this.mover.style.marginLeft) - 5;									// get current margin and move it one pixel to the left
 		$(this.mover).setStyle({"margin": "0 0 0 " + positioning + "px"});  			// trying to set the margin using marginLeft caused an argument error in IE7 - so we set all margin values as a workaround   // **note for possible improvement
  },
	doMoveRev: function(){
		var positioning, howFar;
    
    if(parseInt(this.mover.style.marginLeft) >= -1 || this.firstCall == 0){
			this.mover.style.marginLeft = 0;
			this.mover = $(this.container).childElements().last();
 			this.howWide = $(this.mover).getWidth();																					
 			this.outOfFrame = $(this.mover).remove();	
 			howFar = "-" + (this.howWide + 1) + "px";
 			$(this.outOfFrame).setStyle({"marginLeft" : howFar, cssFloat : 'left'});
 			Element.insert(this.container, {top : this.outOfFrame});
 			this.firstCall = 1;
 		};
	
 		positioning = parseInt(this.mover.style.marginLeft) + 5;	
 		$(this.mover).setStyle({"margin": "0 0 0 " + positioning + "px"});
	},
  activateScroll: function (index) { // starts the scroll if it is stopped
		if (this.status == 0) {
		  this.pe = new PeriodicalExecuter(this.doMove.bind(this), this.interval);
			this.status = 1;
		}
	},
	stopScroll: function () {	 // stops the scroll if it is running
	  this.pe.stop();
	  this.status = 0;
	},
	addControlButtons: function() { // INSERTED ELEMENT --- stop/start buttons and containing div with css styles
		var devButtons = 	'<div id="debug_gallery_scroll">'+
											'	<input type="button" onclick="scrollz.activateScroll()"; name="activate_scroll" value="activate scroll" id="activate_scroll">'+
											'	<input type="button" onclick="scrollz.stopScroll()"; name="stop_scroll" value="stop scroll" id="stop_scroll">'+
											'</div>'+
											'<style type="text/css" media="screen">'+
											' 	#debug_gallery_scroll {display:block;position:relative;left:0;top:0;z-index:1000;background:#222;width:auto;margin:0;padding:10px;text-align:center;filter: alpha(opacity=85);filter: progid:DXImageTransform.Microsoft.Alpha(opacity=85);-moz-opacity: .85; opacity:.85;}'+
											'		#activate_scroll:hover, #stop_scroll:hover {color:#09f;}'+
											'</style>';
		Element.insert(document.body, {top:devButtons})
	}
};

/*
		Declare a variable object to contain our instance of the GalleryScroll Class.
		After document is ready create our new GalleryScroll instance by calling new and feeding it the ID of the DOM object that contains the stuff we want to scroll.
*/
//var scrollz;
//Event.observe(window, 'load', function() {
//  scrollz = new GalleryScroll("inner-gallery-list-0", "true");  
//});


Ajax.Responders.register({
  onCreate: function() {
    Ajax.activeRequestCount++;
		if($('content_loading') && Ajax.activeRequestCount>0) {
      Effect.Appear('content_loading',{duration:0.4,queue:'end'});
		};			
  },
  onComplete: function() {
    Ajax.activeRequestCount--;
		if($('content_loading') && Ajax.activeRequestCount==0) {
	    Effect.Fade('content_loading',{duration:0.4,queue:'end'});
		};    
  }
});


/*
  ORIGINAL CODE BELOW ---------------------------------------------------------------------------------------------------------------------------
*/
// var homeLists = [];
// var homeScrollTick = 1;
// var homeScrollTimer = setTimeout("");
// var homeScrollTimerSpeed = 2;
// 
// function check_home_scroll() {
//   var gal = $('inner-gallery');
//   if(gal) {
//     var inner = $('inner-gallery-list-0');
//     width = 0;
//     inner.childElements().each(function(x) {
//       width += x.clientWidth;
//     });
//     //we need at least twice the browser window width
//     var target = width;
//     var count = 0;
//     do {
//       count = target / gal.clientWidth;
//       target *= 2;
//     } while (count < 2);
//     homeLists = new Array(Math.max(2,count^2)); //we need at least two of them so that we can wrap it
//     // alert(homeLists.length);
//     homeLists[0] = inner;
//     for (var i=1; i<homeLists.length; i++) {
//       homeLists[i] = inner.cloneNode(true);
//       homeLists[i].id = 'inner-gallery-list-'+i;
//       homeLists[i].setAttribute('style',"left:"+(i+width));
//       homeLists[i-1].insert({after: homeLists[i]});
//     };
//     doHomeScroll();
//   };
// };

// function doHomeScroll() {
//   for ( var i=0; i<homeLists.length; i++ ) {
//     $('inner-gallery-list-'+i).style.left = parseInt($('inner-gallery-list-'+i).style.left) - homeScrollTick;
//   }
//   homeScrollTimer = setTimeout('doHomeScroll()', homeScrollTimerSpeed);
// }

// Event.observe(window,'load',check_home_scroll);


	function startLoad() {
		Element.hide('content_item');
		Element.show('content_loading');
	}
	
	function stopLoad() {
		Element.hide('content_loading');
		setTimeout("new Effect.Appear('content_item')",300);
	}

// Event.observe(window, 'load', function() {
//  $$('.set-size').each(function(item, index){
//    Event.observe(item, 'click', function(){
//      Element.toggleClassName(item, 'larger-size'); 
//    });
//  });
// });
// 

/***********************************************
* Ultimate Fade-In Slideshow (v1.51): © Dynamic Drive (http://www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit http://www.dynamicdrive.com/ for this script and 100s more.
***********************************************/

var fadearray=new Array() //array to cache fadeshow instances
var fadeclear=new Array() //array to cache corresponding clearinterval pointers

var dom=(document.getElementById) //modern dom browsers
var iebrowser=document.all

function fadeshow(theimages, fadewidth, fadeheight, borderwidth, delay, pause, displayorder){
this.pausecheck=pause
this.mouseovercheck=0
this.delay=delay
this.degree=10 //initial opacity degree (10%)
this.curimageindex=0
this.nextimageindex=1
fadearray[fadearray.length]=this
this.slideshowid=fadearray.length-1
this.canvasbase="canvas"+this.slideshowid
this.curcanvas=this.canvasbase+"_0"
if (typeof displayorder!="undefined")
theimages.sort(function() {return 0.5 - Math.random();}) //thanks to Mike (aka Mwinter) :)
this.theimages=theimages
this.imageborder=parseInt(borderwidth)
this.postimages=new Array() //preload images
for (p=0;p<theimages.length;p++){
this.postimages[p]=new Image()
this.postimages[p].src=theimages[p][0]
}

var fadewidth=fadewidth+this.imageborder*2
var fadeheight=fadeheight+this.imageborder*2

if (iebrowser&&dom||dom) //if IE5+ or modern browsers (ie: Firefox)
document.write('<div id="master'+this.slideshowid+'" style="position:relative;width:'+fadewidth+'px;height:'+fadeheight+'px;overflow:hidden;"><div id="'+this.canvasbase+'_0" style="position:absolute;width:'+fadewidth+'px;height:'+fadeheight+'px;top:0;left:0;filter:progid:DXImageTransform.Microsoft.alpha(opacity=10);opacity:0.1;-moz-opacity:0.1;-khtml-opacity:0.1;background-color:'+fadebgcolor+'"></div><div id="'+this.canvasbase+'_1" style="position:absolute;width:'+fadewidth+'px;height:'+fadeheight+'px;top:0;left:0;filter:progid:DXImageTransform.Microsoft.alpha(opacity=10);opacity:0.1;-moz-opacity:0.1;-khtml-opacity:0.1;background-color:'+fadebgcolor+'"></div></div>')
else
document.write('<div><img name="defaultslide'+this.slideshowid+'" src="'+this.postimages[0].src+'"></div>')

if (iebrowser&&dom||dom) //if IE5+ or modern browsers such as Firefox
this.startit()
else{
this.curimageindex++
setInterval("fadearray["+this.slideshowid+"].rotateimage()", this.delay)
}
}

function fadepic(obj){
if (obj.degree<100){
obj.degree+=10
if (obj.tempobj.filters&&obj.tempobj.filters[0]){
if (typeof obj.tempobj.filters[0].opacity=="number") //if IE6+
obj.tempobj.filters[0].opacity=obj.degree
else //else if IE5.5-
obj.tempobj.style.filter="alpha(opacity="+obj.degree+")"
}
else if (obj.tempobj.style.MozOpacity)
obj.tempobj.style.MozOpacity=obj.degree/101
else if (obj.tempobj.style.KhtmlOpacity)
obj.tempobj.style.KhtmlOpacity=obj.degree/100
else if (obj.tempobj.style.opacity&&!obj.tempobj.filters)
obj.tempobj.style.opacity=obj.degree/101
}
else{
clearInterval(fadeclear[obj.slideshowid])
obj.nextcanvas=(obj.curcanvas==obj.canvasbase+"_0")? obj.canvasbase+"_0" : obj.canvasbase+"_1"
obj.tempobj=iebrowser? iebrowser[obj.nextcanvas] : document.getElementById(obj.nextcanvas)
obj.populateslide(obj.tempobj, obj.nextimageindex)
obj.nextimageindex=(obj.nextimageindex<obj.postimages.length-1)? obj.nextimageindex+1 : 0
setTimeout("fadearray["+obj.slideshowid+"].rotateimage()", obj.delay)
}
}

fadeshow.prototype.populateslide=function(picobj, picindex){
var slideHTML=""
if (this.theimages[picindex][1]!="") //if associated link exists for image
slideHTML='<a href="'+this.theimages[picindex][1]+'" target="'+this.theimages[picindex][2]+'">'
slideHTML+='<img src="'+this.postimages[picindex].src+'" border="'+this.imageborder+'px">'
if (this.theimages[picindex][1]!="") //if associated link exists for image
slideHTML+='</a>'
picobj.innerHTML=slideHTML
}


fadeshow.prototype.rotateimage=function(){
if (this.pausecheck==1) //if pause onMouseover enabled, cache object
var cacheobj=this
if (this.mouseovercheck==1)
setTimeout(function(){cacheobj.rotateimage()}, 100)
else if (iebrowser&&dom||dom){
this.resetit()
var crossobj=this.tempobj=iebrowser? iebrowser[this.curcanvas] : document.getElementById(this.curcanvas)
crossobj.style.zIndex++
fadeclear[this.slideshowid]=setInterval("fadepic(fadearray["+this.slideshowid+"])",50)
this.curcanvas=(this.curcanvas==this.canvasbase+"_0")? this.canvasbase+"_1" : this.canvasbase+"_0"
}
else{
var ns4imgobj=document.images['defaultslide'+this.slideshowid]
ns4imgobj.src=this.postimages[this.curimageindex].src
}
this.curimageindex=(this.curimageindex<this.postimages.length-1)? this.curimageindex+1 : 0
}

fadeshow.prototype.resetit=function(){
this.degree=10
var crossobj=iebrowser? iebrowser[this.curcanvas] : document.getElementById(this.curcanvas)
if (crossobj.filters&&crossobj.filters[0]){
if (typeof crossobj.filters[0].opacity=="number") //if IE6+
crossobj.filters(0).opacity=this.degree
else //else if IE5.5-
crossobj.style.filter="alpha(opacity="+this.degree+")"
}
else if (crossobj.style.MozOpacity)
crossobj.style.MozOpacity=this.degree/101
else if (crossobj.style.KhtmlOpacity)
crossobj.style.KhtmlOpacity=this.degree/100
else if (crossobj.style.opacity&&!crossobj.filters)
crossobj.style.opacity=this.degree/101
}


fadeshow.prototype.startit=function(){
var crossobj=iebrowser? iebrowser[this.curcanvas] : document.getElementById(this.curcanvas)
this.populateslide(crossobj, this.curimageindex)
if (this.pausecheck==1){ //IF SLIDESHOW SHOULD PAUSE ONMOUSEOVER
var cacheobj=this
var crossobjcontainer=iebrowser? iebrowser["master"+this.slideshowid] : document.getElementById("master"+this.slideshowid)
crossobjcontainer.onmouseover=function(){cacheobj.mouseovercheck=1}
crossobjcontainer.onmouseout=function(){cacheobj.mouseovercheck=0}
}
this.rotateimage()
}

