 // Customized javascript code for the Placer County Republican Party 
 // website
 // 

//this is code to underlay shadows on selected areas (NOT YET USED)
Behaviour.register({
  '.textShadow' : function(element) {
    var elem = $(element);
    var outerNode = elem.parentNode;
    var elemshadow = elem.cloneNode(true);
    elemshadow.setAttribute("class", "theTextShadow");
    elemshadow.setAttribute("className", "theTextShadow"); // IE7 hack reqs using className as attribute
    var wrap1 = document.createElement("div");
    wrap1.setAttribute("class", "tswrap1");
    wrap1.setAttribute("className", "tswrap1"); // IE7 hack reqs using className as attribute
    outerNode.insertBefore(wrap1, elem);
    outerNode.removeChild(elem);
    wrap1.appendChild(elemshadow);
    wrap1.appendChild(elem);
  }
});

//
MouseTracker=Class.create(); 
MouseTracker.prototype={ 
  initialize:function(el){ 
    this.el=$(el); 
    this.offParent=el.getOffsetParent();
    this.offParentTop=this.offParent.viewportOffset().top;
    this.offParentHeight=this.offParent.getHeight();
    this.setEvent(); 
  }, 
  setEvent:function(){ 
    Event.observe( 
      this.el, 
      'mousemove', 
      function(event){ 
        var elfired=Event.element(event); 
        this.el.pointerX=Event.pointerX(event); 
        this.el.pointerY=Event.pointerY(event);
        var mouseDelta=this.el.pointerY - this.offParentTop;
        //mDeltaFlt is -0.5 to +0.5 as range for mouse from top to bottom of containing div
        var mDeltaFlt= (mouseDelta - (this.offParentHeight/2))/this.offParentHeight;
        //the following should convert the delta into a range of -25 to +25 ranged non-linearly
        this.el.scrollRange= (mDeltaFlt*mDeltaFlt*mDeltaFlt*200).round();
      }.bindAsEventListener(this) ); 
  } 
} 

//this code creates classes and behaviors that setup a scrolling div on the
//home page of the site for a 'call to action' box
MouseInto=Class.create(); 
MouseInto.prototype={ 
  initialize:function(el){ 
    this.el=$(el); 
    this.setEvent(); 
  }, 
  setEvent:function(){ 
    Event.observe( 
      this.el, 
      'mouseover', 
      function(event){ 
        var el=Event.element(event); 
        this.el.runscroll = 0;  
      }.bindAsEventListener(this) ); 
  } 
} 
MouseOutof=Class.create(); 
MouseOutof.prototype={ 
  initialize:function(el){ 
    this.el=$(el); 
    this.setEvent(); 
  }, 
  setEvent:function(){ 
    Event.observe( 
      this.el, 
      'mouseout', 
      function(event){ 
        var el=Event.element(event); 
        this.el.runscroll = 1;  
      }.bindAsEventListener(this) ); 
  } 
}


Behaviour.register({
  'div.scrollview div.scrollit' : function(element) {
    //attach mouseover to stop and mouseout to restart events
    new MouseInto(element);
    new MouseOutof(element);
    //setup an 'in-div' mouse scrolling event handler
    new MouseTracker(element);
    //create convenience functions to set/get top coordinate
    var setTop = function(topval) {
      element.setStyle( { top: ( topval + 'px' )  } );
    } 
    var getTop = function() {
      return parseFloat( element.getStyle('top') ).round();
    } 
    //setup some reference coordinates and values
    var speed = 1;        
    var offParent = element.getOffsetParent();
    var parentHeight = offParent.getHeight();
    var divHeight = element.getHeight();
    var uplimit = -divHeight + parentHeight -10;
    var origtop = getTop();
    setTop(origtop);// probably not needed but force top to 'integer'
    var downlimit = origtop;
    var direction = 1;
    var counter = 0;
    element.runscroll = 1
    //if the scrolling div is smaller than the parent then do not scroll
    if ( (origtop + divHeight) <= parentHeight ) return;
    //lets setup the 'timer' handler to scroll the content
    new PeriodicalExecuter(function(pe) {
      var datop = getTop();
      var runscroll = element.runscroll;
      if (runscroll>0) {
        //the mouse is out of the scroll area
        if (counter > 0) counter -=1; //lets time a reset on setting direction to non-0
        if (counter == 0 && direction == 0) direction = 1; //restart the scrolling
        bump = speed * direction;
      } else {
        //the mouse is in the scroll area
        counter = 150; //set an ~ 5 sec counter to restart scroll if stopped and then mouse is moved out
        if (element.scrollRange == 0) {
          direction = 0;
        } else {
          direction = (Math.abs(element.scrollRange)/element.scrollRange);
        }
        bump = element.scrollRange;
      }
      var newtop = datop - bump;
      if (newtop <= uplimit ) {
        setTop(uplimit);
        direction = -1;
      } else if (newtop >= downlimit) {
        setTop(downlimit);
        direction = 1;
      } else {
        setTop(newtop);
      }
    }, 0.04);//set timer to refire every 40ms or about 25 times per sec
  }
})


/*
* Displays a cross-fading slideshow
* Option:default
* 	uri : [], // an array of image URIs
*		interval : 5, // seconds for each slide to be visible
*		duration : 1, // duration of fade efefct
*		fps : 50, // frames per second of slide effect; shouldn't need to adjust this
*		crossfade : true // if you don't want a cross-fade set this to false and it'll do a fade out - fade in , instead.
*/
var Slideshow = Class.create();


Slideshow.prototype = {
	initialize : function(elm, options) {
		this.elmid = elm;
		this.counter = 0;
		this.loaded = false;
		this.options = Object.extend({
			uri : [],
			interval : 5,
			duration : 1,
			fps : 50,
			crossfade : true
		}, options || {})
		this.options.uri = $A(this.options.uri);
		//this scrambles the image array each time a page loads
		this.options.uri.sort(function(){return (Math.round(Math.random())-0.5); });
		if ( (Math.round(Math.random())-0.5) < 0 )  this.options.uri.reverse();
		this.options.uri.sort(function(){return (Math.round(Math.random())-0.5); });
		//now load the first image
    // var firstSlide = $(document.createElement('div'));
    // firstSlide.className = 'slide-image';
    // firstSlide.style.backgroundImage = 'url('+this.options.uri[this.options.uri.length-1]+')';
    // this.elm.appendChild(firstSlide);
    //setup a start call on Dom load or window load
    if(FastInit) {
     FastInit.addOnLoad(this.start.bind(this));
    } else {
     Event.observe(window, 'load', this.start.bind(this));
    }
	},
	firstpic: function() {
	  imgsrc = this.options.uri[this.options.uri.length-1];
	  return imgsrc;
	},
	start: function() {
	  this.elm = $(this.elmid);
    //    while (this.elm.hasChildNodes()) {
    //   this.elm.removeChild(this.elm.firstChild);
    // }
    
	  //this is a hack to remove 'spurious' text nodes inside the element
    while (this.elm.firstChild.nodeType == 3) {
      this.elm.removeChild(this.elm.firstChild);
    }
    while (this.elm.lastChild.nodeType == 3) {
      this.elm.removeChild(this.elm.lastChild);
    }
    //debugger;
		new PeriodicalExecuter(this.cycle.bind(this), this.options.interval); 
	},
	cycle: function() {
		var elm = this.elm;
		var opt = this.options;
		if(this.counter++ == opt.uri.length) {
			this.counter = 1
			this.loaded = true;
		}
		count = this.counter;
		var next = document.createElement('img');
		next.src = this.options.uri[count-1];
		if(!this.loaded) {
			var preload = document.createElement('img');
			preload.src = this.options.uri[count]; 
		}
		//console.log(next.src);
		if(this.options.crossfade) {
			var currentSlide;
			if(elm.firstChild) {
				currentSlide = elm.firstChild;
			} else {
				currentSlide = document.createElement('div');
				elm.appendChild(currentSlide);
			}
			var nextSlide = $(document.createElement('div'));
			nextSlide.className = 'slide-image';
			nextSlide.style.backgroundImage = 'url('+next.src+')';
			nextSlide.setOpacity(0);
			elm.appendChild(nextSlide);
			new Effect.Parallel([new Effect.Fade(currentSlide,{sync:true}),
				new Effect.Appear(nextSlide,{sync:true})],
				{duration: opt.duration, fps: opt.fps, afterFinish : function() {Element.remove(currentSlide)}}
			);
		} else {
			new Effect.Fade(elm, { 
				duration: opt.duration, 
				fps: opt.fps, 
				afterFinish: function() {
					elm.style.backgroundImage = 'url('+next.src+')';
					new Effect.Appear(elm, {
							duration: opt.duration,
							fps: opt.fps,
							queue:'end'
					});
				} 
			})
		}
	}
};


//center the menubar 
Behaviour.register({
  '#MenuBar1' : function(element) {
    var mwidth = element.clientWidth;
    var pwidth = element.parentNode.clientWidth;
    $(element).setStyle( { 
      paddingLeft: ( ((pwidth-mwidth)/2) + 'px' )  
    } );
    $(element.parentNode).setStyle( { 
      visibility: 'visible'  
    } );
  }
}) 
Behaviour.register({
  '#MenuBarPGOP' : function(element) {
    el = $(element)
    // new Spry.Widget.MenuBar(el.id, {
    //           imgDown:"/javascripts/SpryAssets/SpryMenuBarDownHover.gif", 
    //           imgRight:"/javascripts/SpryAssets/SpryMenuBarRightHover.gif"});
    var mwidth = el.clientWidth;
    var pwidth = el.parentNode.clientWidth;
    el.setStyle( { 
      paddingLeft: ( ((pwidth-mwidth)/2) + 'px' )  
    } );
    $(el.parentNode).setStyle( { 
      visibility: 'visible'  
    } );
  }
}) 

//this function can be called with a img url string to start a preload
function preloadImg(s) {
  var img = new Image();
  img.src = s;
}

//get the internet explorer version
function getInternetExplorerVersion()
// Returns the version of Internet Explorer or a -1
// (indicating the use of another browser).
{
  var rv = -1; // Return value assumes failure.
  if (navigator.appName == 'Microsoft Internet Explorer')
  {
    var ua = navigator.userAgent;
    var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
    if (re.exec(ua) != null)
      rv = parseFloat( RegExp.$1 );
  }
  return rv;
}
