/******************************************************/
/*	Description :	Main Site Routines	               /
/*	Version		:	5.4								   /
/*	Date Stamp  :	2/01/08 - JB					   /
/******************************************************/




/*


Main SlideShow Class:

EXAMPLE USAGE:

  new SlideShow('container', { slideDuration: 2 });

*/
var SlideShow = Class.create({
  
  initialize: function(element, options){
    this.element = element;
    this.suppliedOptions = options;
    this.defaultOptions = $H({
      autoPlay:           true,
      slideDuration:      5,
      transitionDuration: 1,
      loop:               true,
      crossFade:          false,
      pauseOnMouseover:   false,
      slidesSelector:     '> *',
      startHidden:        true,
      events: { init: 'dom:loaded', play: 'window:loaded' },
      beforeStart: Prototype.emptyFunction, afterFinish: Prototype.emptyFunction
    });
    
    // assigning the options to internal variables
    this.options = this.defaultOptions.merge(this.suppliedOptions).each(function(option){
      this[option[0]] = option[1];
    }.bind(this));
    
    this.events = $H(this.defaultOptions.get('events')).merge(this.events).toObject();
    
    if (this.autoPlay) {
      this.initEventFunction = function(){
        this.init();
        // only allow the slideShow to observe one 'dom:loaded' event
        if (this.events.init == 'dom:loaded')
          document.stopObserving(this.events.init, this.initEventFunction);
      }.bind(this);
      document.observe(this.events.init, this.initEventFunction);
    }
  },
  
  init: function(){
    if (!$(this.element)) return;
    this.root = $(this.element);
    this.id = this.root.identify();
    this.fireEvent('initializing', { slideShow: this });
    this.slides = $$('#' + String(this.id) + ' ' + String(this.slidesSelector));
    this.loopCount = 0;
    this.slideCount = 0;
    this.slideIndex = 0;
    this.paused = false;
    this.started = false;
    
    this.prep();
    
    this.playEventFunction = function(){
      this.beforeStart();
      this.play();
      if (this.pauseOnMouseover)
        this.root.observe('mouseover', this.pause.bind(this)).observe('mouseout', this.play.bind(this));
      
      // only let window:loaded start the slideShow once
      if (this.events.play == 'window:loaded')
        document.stopObserving(this.events.play, this.playEventFunction);
    }.bind(this);
    document.observe(this.events.play, this.playEventFunction);
    
    this.fireEvent('initialized', { slideShow: this });
  },
  
  prep: function(){
    this.root.makePositioned();
    
    for (var i=0; i < this.slides.length; i++) {
      this.slides[i].setStyle({ position: 'absolute', zIndex: i });
      if (this.startHidden || (!this.startHidden && i != 0))
        this.prepSlide(this.slides[i]);
    };
    this.fireEvent('prepped', { slideShow: this });
  },
  
  prepSlide: function(slide){
    return slide.setStyle({ display: 'none', opacity: 0 });
  },
  
  play: function(e){
    // prevent mousing out from causing the slideShow to start
    if (e && !this.autoPlay && this.pauseOnMouseover && this.loopCount == 0) return;
    
    // prevent against internal mouse movements from triggering a transition
    if (e && this.mouseIsWithinSlideArea(e)) return;
    
    this.started = true;
    this.paused = false;
    this.fireEvent('started', { slideShow: this });
    this.transition();
  },
  
  pause: function(e){
    // if it's not started playing, or if it's already paused, or if the mouse isn't within the slide area return
    if (!this.started || this.paused || (e && !this.mouseIsWithinSlideArea(e))) return;
    
    this.paused = true;
    this.abortNextTransition();
    
    // queue paused test
    // this.setupPausedTest();
    
    this.fireEvent('paused', { slideShow: this });
  },
  
  transition: function(){
    if (this.paused) return;
    if (this.nextTransition) this.nextTransition.stop();
    
    this.coming = this.slides[this.slideIndex];
    this.going = this.coming.previous() || this.slides.last();
    
    var coming = this.coming;
    var going = this.going;
    
    if (this.slideCount > 0 && this.coming == this.slides.first() && this.going == this.slides.last()) {
      this.fireEvent('looped', { slideShow: this });
      this.loopCount++;
      this.afterFinish();
      if (!this.loop) return;
    }
    
    this.slideCount++;
    this.slideIndex++;
    if (this.slideIndex >= this.slides.length) this.slideIndex = 0;
    
    // if not fresh start, fade
    if (going != coming) {
      if (this.crossFade) {
        new Effect.Parallel(
          [new Effect.Appear(coming), new Effect.Fade(going)],
          {
            duration: this.transitionDuration,
            afterFinish: function(){
              this.prepSlide(going);
              this.afterTransitionEffect();
            }.bind(this)
          }
        );
      } else {
        going.fade({
          duration: this.transitionDuration / 2,
          afterFinish: function(){
            this.prepSlide(going);
            coming.appear({
              duration: this.transitionDuration / 2,
              afterFinish: this.afterTransitionEffect.bind(this)
            });
          }.bind(this)
        });
      }
    }
    // fade in the first time
    else {
      coming.appear({
        duration: this.transitionDuration / 2,
        afterFinish: this.afterTransitionEffect.bind(this)
      });
    }
    this.fireEvent('transitioned', { slideShow: this, coming: coming, going: going, loopCount: this.loopCount });
  },
  
  afterTransitionEffect: function(){
    this.scheduleNextTransition();
  },
  
  scheduleNextTransition: function(){
    if (this.slideDuration <= 0) return;
    this.nextTransition = new PeriodicalExecuter(function(nextTransition){
      if (this.paused) return;
      this.transition();
    }.bind(this), this.slideDuration);
  },
  
  abortNextTransition: function(){
    if (this.nextTransition) this.nextTransition.stop();
  },
  
  fireEvent: function(name, memo){
    this.root.fire('SlideShow_' + this.root.id + ':' + name, memo);
  },
  
  mouseIsWithinSlideArea: function(e){
    var offsets = this.root.cumulativeOffset();
    var maxX = offsets.left + this.root.getWidth();
    var minX = offsets.left;
    var maxY = offsets.top + this.root.getHeight();
    var minY = offsets.top;
    
    // minX and the maxY need to be checked like this
    if (minX == e.pointerX() || maxY == e.pointerY()) return false;
    if ($R(minX, maxX).include(e.pointerX()) && $R(minY, maxY).include(e.pointerY())) {
      return true; } else { return false; }
  },
  
  end: function(){
    this.pause();
    document.stopObserving(this.events.play, this.playEventFunction);
    document.stopObserving(this.events.init, this.initEventFunction);
  },
  
  remove: function(){
    this.end();
    this.root.remove();
    this.fireEvent('removed');
  }

});


Event.observe(window, 'load', function(e){
  document.fire('window:loaded');
});




//-----------------------------------------------------Stock Macromedia Rollover Code->>

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

//-----------------------------------------------------Stock Macromedia Layer SHow/Hide ->>

function MM_showHideLayers() { //v6.0
  var i,p,v,obj,args=MM_showHideLayers.arguments;
  for (i=0; i<(args.length-2); i+=3) if ((obj=MM_findObj(args[i]))!=null) { v=args[i+2];
    if (obj.style) { obj=obj.style; v=(v=='show')?'visible':(v=='hide')?'hidden':v; }
    obj.visibility=v; }
}	

//-----------------------------------------------------Redirection && thankYou Routines->>
// Vs. 3.0

//	Print Message (...) [USAGE]
//		Outputs code to create the countdown box
//		Params:
	//		[0] ->	Time (milliseconds::1000~1sec)
	//		[1]	->	Foreground Color
var delay=100;
function printMessage(){
	var a=printMessage.arguments;
	var timer=(a[0]!=null)?a[0]:5000; 
	var txtcolor=(a[1]!=null)?a[1]:"black"; 
	
	// Random
		var symbol=".";
		var size=22;
		var bStr="";
		var num_sym=50;
		/* vs.2.0
		// increases .s for more time
		for(var i=0;i<timer;i+=100)
			bStr+=symbol;
		*/
		// vs.3.0
		// increases delay for more time
		for(var i=0;i<num_sym;i++)
			bStr+=symbol;
		delay=Math.ceil(timer/num_sym);
			
	document.write("<p align=\"center\"><strong>Thank you for your submission. <br>We will get back to you as soon as possible </strong><br><br>");
	document.write("<input name=\"rdtxt\" type=\"text\" value=\"Redirecting, Please Wait...\" size=\"23\" class=\"thankyou\"><br>");
	document.write("<input type=\"text\" id=\"timeBox\"  class=\"timebox\" value=\""+bStr+"\" size=\""+size+"\" readonly=\"1\"></p>");
	remDot();
	//	FailSafe -> Redirects after timer + 5 seconds.
	setTimeout("location='/'",(timer+5000));
}

function remDot(){
	b=document.getElementById("timeBox");
	if(b.value.length>0){
		b.value=b.value.substr(0,b.value.length-1);
		setTimeout("remDot()",parseInt(delay));
	}else{
		location='index.jsp';
		rd=document.getElementById("rdtxt");
		rd.value="Redirecting";
	}
}


//----------------------------------------------------------------------------------Bookmark Page->>
// v1.0 [IE][RH]

//	bookmark_init (...) [USAGE]
//		Creates bookmark link for IE browsers only
//		@Params:
	//		[0] ->	string1  	-> Link Template
	//		[1]	->	string2		-> Non-Compliant Output
		// 	[EXAMPLE]	[bookmark_init("[ :Bookmark Us: ]","");]
		//		string1 = "[ :Bookmark Us: ]"
		//		string2 = ''
		//			on  IE: a link that says 'Bookmark Us'
		//			not IE: nothing output
		
function bookmark_init(string1,string2){
	if ((navigator.appName == "Microsoft Internet Explorer") && (parseInt(navigator.appVersion) >= 4)){
		s1p=string1.split(/:/);
		outStr=s1p[0] + '<a href="javascript:bookmark();" class="A_mini">' +s1p[1]+ '</a>' + s1p[2];
	}else
		outStr=string2;
	document.write(outStr);
}

function bookmark()
{
	url=location.href;
	title=document.title;
	window.external.AddFavorite(url,title)
}

//----------------------------------------------------------------------------------Remove Border From Flash->>


function flashBorder(){
	objects = document.getElementsByTagName("object");
	for (var i = 0; i < objects.length; i++)
	{
		objects[i].outerHTML = objects[i].outerHTML;
	}
}


//---------------------------------------------------------------------------New Bookmark Us Link->>

function favoris() {
			var url=location.href;
			var title=document.title;
			var ua=navigator.userAgent.toLowerCase();
			var isSafari=(ua.indexOf('webkit')!=-1);
			var isMac=(ua.indexOf('mac')!=-1);
			var buttonStr=isMac?'Command/Cmd':'CTRL';
/*            if ( navigator.appName != 'Microsoft Internet Explorer' ){
                        window.sidebar.addPanel(title,url,""); 
            } else { 
                        window.external.AddFavorite(url,title); 
            } 
*/

			if ( navigator.appName == 'Microsoft Internet Explorer' ){
				window.external.AddFavorite(url,title);
			} else if ( navigator.appName == 'Netscape' ) { 
				
				if ( isSafari ) { // Firefox, Netscape, Safari, iCab
					alert('You need to press '+buttonStr+' + D to bookmark our site.');
				} else if ( isMac ) { // IE5/Mac and Safari 1.0
					alert('You need to press Command/Cmd + D to bookmark our site.');    
				} else {
					window.sidebar.addPanel(title,url,"");
				}
				
//			}  else if ( navigator.appName == 'Opera' ) { 
//				alert('In order to bookmark this site you need to do so manually '+ 'through your browser.');
			} else {
					alert('In order to bookmark this site you need to do so manually '+ 'through your browser.');
				}
}

// EOF;


//------------------------------------------------------------------------Java Drop Down Menu->>

// Copyright 2006-2007 javascript-array.com

var timeout	= 500;
var closetimer	= 0;
var ddmenuitem	= 0;

// open hidden layer
function mopen(id)
{	
	// cancel close timer
	mcancelclosetime();

	// close old layer
	if(ddmenuitem) ddmenuitem.style.visibility = 'hidden';

	// get new layer and show it
	ddmenuitem = document.getElementById(id);
	ddmenuitem.style.visibility = 'visible';

}
// close showed layer
function mclose()
{
	if(ddmenuitem) ddmenuitem.style.visibility = 'hidden';
}

// go close timer
function mclosetime()
{
	closetimer = window.setTimeout(mclose, timeout);
}

// cancel close timer
function mcancelclosetime()
{
	if(closetimer)
	{
		window.clearTimeout(closetimer);
		closetimer = null;
	}
}

// close layer when click-out
document.onclick = mclose; 


//------------------------------------------------------------ Spam Proof E-Mail Links (See Wiki)

function emailMe(name,url){
	
	document.write("<a href=\"mailto:" + name + "@" + url + "\">" + name + "@" + url + "</a>");
	
}
