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];}
}

function incSwf(fName,w,h,bgColor) {
	document.write('<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0" width="' + w + '" height="' + h +' ">\n');
	document.write('<param name="allowScriptAccess" value="sameDomain" />\n');
	document.write('<param name="movie" value="' + fName + '" />\n');
	document.write('<param name="quality" value="high" />\n');
	document.write('<param name="wmode" value="opaque" />\n');
	document.write('<param name="loop" value="false" />\n');
	document.write('<param name="menu" value="false" />\n');
	document.write('<param name="bgColor" value="'+ bgColor +'" />\n');
	document.write('<embed src="' + fName + '" width="' + w + '" height="' + h + '" loop="False" wmode="opaque" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" />\n');
	document.write('</embed>\n');
	document.write('</object>\n');
}

function NowYear() {
   var now = new Date();
   var year = now.getFullYear();
   document.write(year);
}

/* Scroll */

//Browser Property
function getBrowserInfo(){ 
	this.majorver = parseInt(navigator.appVersion) ;
	this.agent = navigator.userAgent.toLowerCase() ;
	this.platform = navigator.platform.toLowerCase() ;
	this.mac = ( this.platform.indexOf('mac') != -1 ) ? 1 : 0 ;
	this.win = ( this.platform.indexOf('win') != -1 ) ? 1 : 0 ;

	this.dom1 = ( document.getElementById ) ? 1 : 0 ;
	this.dom2event = ( document.addEventListener && document.removeEventListener ) ? 1 : 0 ;

	this.opera = ( ( this.agent.indexOf('opera') != -1 ) || window.opera ) ? 1 : 0 ; ;
	if ( this.opera ) {
		this.opera5 = this.agent.indexOf('opera 5') ? 1 : 0 ;
		this.opera6 = this.agent.indexOf('opera 6') ? 1 : 0 ;
		this.opera7 = this.agent.indexOf('opera 7') ? 1 : 0 ;
		return this ;
	}
	this.ie = ( ( this.agent.indexOf('msie') != -1 ) && !this.opera ) ? 1 : 0 ;;
	if ( this.ie ) {
		this.ie4 = ( ( this.agent.indexOf('msie 4') != -1 ) && !this.dom1 ) ? 1 :0 ;
		this.ie5 = ( ( this.agent.indexOf('msie 5') != -1 ) && this.dom1 ) ? 1 : 0 ;
		this.ie55 = ( this.ie5 && window.createPopup ) ? 1 : 0 ;
		this.ie6 = ( ( this.agent.indexOf('msie 6') != -1 ) && this.dom1 ) ? 1 : 0 ;
		this.ie6s = ( this.ie6 && ( document.compatMode == "CSS1Compat" ) ) ? 1 : 0 ;
		this.ie4up = ( this.majorver >= 4 ) ? 1 : 0 ;
		this.ie5up = ( ( this.majorver >= 4 ) && !this.ie4 ) ? 1 : 0 ;
		this.ie55up = ( ( this.majorver >= 4 ) && !this.ie4 && !this.ie5 ) ? 1 : 0 ;
		this.ie6up = ( ( this.majorver >= 4 ) && !this.ie4 && !this.ie55 ) ? 1 : 0 ;
		return this ;
	}
	this.net = 	( ( ( this.agent.indexOf('netscape') != -1 ) || 
		( this.agent.indexOf('mozilla') != -1 ) || ( this.agent.indexOf('gecko/') != -1 ) ) && !this.opera ) ? 1 : 0 ;
	if ( this.net ) {
		this.net4 = ( document.layers && !this.dom1 ) ? 1 : 0 ;
		this.net6 = ( ( this.majorver >= 5 ) && this.dom2event ) ? 1 : 0 ;
		this.net4up = ( this.majorver >= 4 ) ? 1 : 0 ;
		this.net6up = ( ( this.majorver >= 5 ) && !this.net4 ) ? 1 : 0 ;
		return this ;
	}
	return this ;
}

	var _bw = new getBrowserInfo;




function getScrollY() {
	if( _bw.net4up || _bw.opera ) { return window.pageYOffset }
	if( _bw.ie6s ) { return document.documentElement.scrollTop }
	if( _bw.ie4up ) { return document.body.scrollTop }
	return 0;
}


//UpScroll処理

var timeID01;
var position;
var upmemory;
var nowposition01;

function Upscroll_Y(){
	position -= position * 0.2;
	nowposition01 = getScrollY();
	if( position <= 1 || nowposition01 > upmemory){
		clearTimeout(timeID01);
		if(nowposition01 > upmemory){
			window.scrollTo(0,nowposition01);
		}else{
			window.scrollTo(0,0);
		}
	}else{
		window.scrollTo(0,position);
		upmemory = Math.ceil(position);
		time_SCLL01();
	}
}


function time_SCLL01() {
	timeID01=setTimeout("Upscroll_Y()",16);
}

function SCLL() {
	upmemory = getScrollY();
	position = getScrollY();
	time_SCLL01();
}


//DownScroll処理

var timeID02;
var distance;
var point;
var move;
var downmemory;
var nowposition02;

function getobjectY(linkname,linkId) {
i = 0;
	// IE 4.0以上
	if( document.all ) { return document.all[linkId].offsetTop }
	// IE5.0 & NN6.0以上
	if( document.getElementById ) { return document.getElementById(linkId).offsetTop }
	// NN4.0
	if( document.layers ){ return document.anchors[linkname].y }
	return 0;
}

function Downscroll_Y(){
	distance = point-getScrollY();
	move += distance * 0.2;
	if( distance <= 1 || nowposition02 == dwonmemory){
		clearTimeout(timeID02);
		window.scrollTo(0,point);
	}else{
		dwonmemory = getScrollY();
		window.scrollTo(0,move);
		nowposition02 = getScrollY();
		time_SCLL02();
	}
}

function time_SCLL02() {
	timeID02=setTimeout("Downscroll_Y()",16);
}

function DownSCLL(linkname,linkId) {
	move = 0;
	dwonmemory = getScrollY();
	point = getobjectY(linkname,linkId);
	if(point==0){
		location.hash = linkname;
	}else{
	time_SCLL02();
	}
}

new function(){
	try{
		if (navigator.userAgent.indexOf("MSIE")!= -1 && navigator.appVersion.indexOf("6.0")!= -1) {//for old ie
			var elements = getElementsByClassName("alphafilter");
			for (var i=0; i<elements.length; i++) {
				var element = elements[i];
				if(element.nodeName=="IMG"){
					var newimg           = document.createElement("b");
					for(var key in element.currentStyle){
						newimg.style[key]=element.currentStyle[key];
					}
					newimg.className     = element.className;
					newimg.style.display = "inline-block";
					newimg.style.zoom = "1";
					newimg.style.width   = element.width;
					newimg.style.height  = element.height;
					newimg.style.styleFloat   = element.align;
					newimg.style.filter  = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src="+element.src+",sizingMethod='scale')";
					newimg.originalSrc = element.src;
					if (element.parentNode.tagName == "A") {
						element.parentNode.style.cursor = "pointer";
						element.parentNode.style.position="relative";
						newimg.style.cursor = "pointer";
					}
					newimg.images = new Image();
					newimg.images.src = element.src;
					element.className.split(/\s+/);
					
					element.parentNode.insertBefore(newimg,element)
					element.style.display="none";
				}else{
					var anchors = element.getElementsByTagName("a");
					for (var j=0; j<anchors.length; j++) {
						var anchor = anchors[j];
						anchor.style.position="relative";
						anchor.style.cursor="pointer";
					}
					var iputs = element.getElementsByTagName("input");
					for (var j=0; j<iputs.length; j++) {
						var iput = iputs[j];
						iput.style.position="relative";
					}
					var iputs = element.getElementsByTagName("textarea");
					for (var j=0; j<iputs.length; j++) {
						var iput = iputs[j];
						iput.style.position="relative";
					}
					var iputs = element.getElementsByTagName("select");
					for (var j=0; j<iputs.length; j++) {
						var iput = iputs[j];
						iput.style.position="relative";
					}
					var  newimg = element.currentStyle.backgroundImage || element.style.backgroundImage;
					newimg.match(/^url[("']+(.*\.png)[)"']+$/i)
					var newimg = RegExp.$1;
					element.style.filter ="progid:DXImageTransform.Microsoft.AlphaImageLoader(src="+newimg+",sizingMethod='scale')";
					element.style.background = "none";
				}
			}
		}
	}catch(e){}
	function imageReplace(){
		var btnClassName = "btn";
		var objAll = document.getElementsByTagName ? document.getElementsByTagName("*") : document.all;
		for (var i = 0; i < objAll.length; i++) {
			var btn=false;
			var eltClass = objAll[i].className.split(/\s+/);
			for (var j = 0; j < eltClass.length; j++) {
				if (eltClass[j] == btnClassName)btn = true;
			}
			if(btn == true){
				if(objAll[i].originalSrc){
					objAll[i].rolloverSrc = objAll[i].originalSrc.replace(/(\.gif|\.jpg|\.png)$/,"_on$1");
						objAll[i].onmouseover = function(){
							this.style.filter ="progid:DXImageTransform.Microsoft.AlphaImageLoader(src="+this.rolloverSrc+",sizingMethod='scale')";
						}
						objAll[i].onmouseout = function(){
							this.style.filter ="progid:DXImageTransform.Microsoft.AlphaImageLoader(src="+this.originalSrc+",sizingMethod='scale')";
						}
				}else{
					if(objAll[i].nodeName=="IMG"){
						objAll[i].originalSrc = objAll[i].src
						objAll[i].rolloverSrc = objAll[i].src.replace(/(\.gif|\.jpg|\.png)$/,"_on$1")
						objAll[i].onmouseover = function(){
							this.src = this.rolloverSrc;
						}
						objAll[i].onmouseout = function(){
							this.src = this.originalSrc;
						}
					}
				}
			}
		}
	}
	function getElementsByClassName(className){
		var i, j, eltClass;
		var objAll = document.getElementsByTagName ? document.getElementsByTagName("*") : document.all;
		var objCN = new Array();
		for (i = 0; i < objAll.length; i++) {
			eltClass = objAll[i].className.split(/\s+/);
			for (j = 0; j < eltClass.length; j++) {
				if (eltClass[j] == className) {
					objCN.push(objAll[i]);
					break;
				}
			}
		}
		return objCN;
	}
	function addEvent(elm,listener,fn){
		try{
			elm.addEventListener(listener,fn,false);
		}catch(e){
			elm.attachEvent("on"+listener,fn);
		}
	}
	addEvent(window,"load",imageReplace)
}

/*
--------------------------------------------------------
dateformat.js - Simple date formatter
Version 1.1 (Update 2008/04/02)

Copyright (c) 2007-2008 onozaty (http://www.enjoyxstudy.com)

Released under an MIT-style license.

For details, see the web site:
 http://www.enjoyxstudy.com/javascript/dateformat/

--------------------------------------------------------
patterns
y : Year         ex. "yyyy" -> "2007", "yy" -> "07"
M : Month        ex. "MM" -> "05" "12", "M" -> "5" "12"
d : Day          ex. "dd" -> "09" "30", "d" -> "9" "30"
H : Hour (0-23)  ex. "HH" -> "00" "23", "H" -> "0" "23"
m : Minute       ex. "mm" -> "01" "59", "m" -> "1" "59"
s : Second       ex. "ss" -> "00" "59", "H" -> "0" "59"
S : Millisecond  ex. "SSS" -> "000" "012" "999", 
                     "SS" -> "00" "12" "999", "S" -> "0" "12" "999"

Text can be quoted using single quotes (') to avoid interpretation.
"''" represents a single quote. 


Useing..

 var fmt = new DateFormat("yyyy/MM/dd HH:mm:ss SSS");

 var str = fmt.format(new Date()); // "2007/05/10 12:21:19 002"
 var date = fmt.parse("2007/05/10 12:21:19 002"); // return Date object

--------------------------------------------------------
*/

var DateFormat = function(pattern) {
  this._init(pattern);
};

DateFormat.prototype = {
  _init: function(pattern) {

    this.pattern = pattern;
    this._patterns = [];

    for (var i = 0; i < pattern.length; i++) {
      var ch = pattern.charAt(i);
      if (this._patterns.length == 0) {
        this._patterns[0] = ch;
      } else {
        var index = this._patterns.length - 1;
        if (this._patterns[index].charAt(0) == "'") {
          if (this._patterns[index].length == 1 
             || this._patterns[index].charAt(this._patterns[index].length - 1) != "'") {
            this._patterns[index] += ch;
          } else {
            this._patterns[index + 1] = ch;
          }
        } else if (this._patterns[index].charAt(0) == ch) {
          this._patterns[index] += ch;
        } else {
          this._patterns[index + 1] = ch;
        }
      }
    }
  },

  format: function(date) {

    var result = [];
    for (var i = 0; i < this._patterns.length; i++) {
      result[i] = this._formatWord(date, this._patterns[i]);
    }
    return result.join('');
  },
  _formatWord: function(date, pattern) {

    var formatter = this._formatter[pattern.charAt(0)];
    if (formatter) {
      return formatter.apply(this, [date, pattern]);
    } else {
      return pattern;
    }
  },
  _formatter: {
    "y": function(date, pattern) {
      // Year
      var year = String(date.getFullYear());
      if (pattern.length <= 2) {
        year = year.substring(2, 4);
      } else {
        year = this._zeroPadding(year, pattern.length);
      }
      return year;
    },
    "M": function(date, pattern) {
      // Month in year
      return this._zeroPadding(String(date.getMonth() + 1), pattern.length);
    },
    "d": function(date, pattern) {
      // Day in month
      return this._zeroPadding(String(date.getDate()), pattern.length);
    },
    "H": function(date, pattern) {
      // Hour in day (0-23)
      return this._zeroPadding(String(date.getHours()), pattern.length);
    },
    "m": function(date, pattern) {
      // Minute in hour
      return this._zeroPadding(String(date.getMinutes()), pattern.length);
    },
    "s": function(date, pattern) {
      // Second in minute
      return this._zeroPadding(String(date.getSeconds()), pattern.length);
    },
    "S": function(date, pattern) {
      // Millisecond
      return this._zeroPadding(String(date.getMilliseconds()), pattern.length);
    },
    "'": function(date, pattern) {
      // escape
      if (pattern == "''") {
        return "'";
      } else {
        return pattern.replace(/'/g, '');
      }
    }
  },

  _zeroPadding: function(str, length) {
    if (str.length >= length) {
      return str;
    }

    return new Array(length - str.length + 1).join("0") + str;
  },


  /// Parser ///
  parse: function(text) {

    if (typeof text != 'string' || text == '') return null;

    var result = {year: 1970, month: 1, day: 1, hour: 0, min: 0, sec: 0, msec: 0};

    for (var i = 0; i < this._patterns.length; i++) {
       if (text == '') return null; // parse error!!
       text = this._parseWord(text, this._patterns[i], result);
       if (text === null) return null; // parse error!!
    }
    if (text != '') return null; // parse error!!

    return new Date(
                result.year,
                result.month - 1,
                result.day,
                result.hour,
                result.min,
                result.sec,
                result.msec);
  },
  _parseWord: function(text, pattern, result) {

    var parser = this._parser[pattern.charAt(0)];
    if (parser) {
      return parser.apply(this, [text, pattern, result]);
    } else {
      if (text.indexOf(pattern) != 0) {
        return null;
      } else {
        return text.substring(pattern.length);
      }
    }
  },
  _parser: {
    "y": function(text, pattern, result) {
      // Year
      var year;
      if (pattern.length <= 2) {
        year = text.substring(0, 2);
        year = year < 70 ? '20' + year : '19' + year;
        text = text.substring(2);
      } else {
        var length = (pattern.length == 3) ? 4 : pattern.length;
        year = text.substring(0, length);
        text = text.substring(length);
      }
      if (!this._isNumber(year)) return null; // error
      result.year = parseInt(year, 10);
      return text;
    },
    "M": function(text, pattern, result) {
      // Month in year

      var month;
      if (pattern.length == 1 && text.length > 1
          && text.substring(0, 2).match(/1[0-2]/) != null) {
        month = text.substring(0, 2);
        text  = text.substring(2);
      } else {
        month = text.substring(0, pattern.length);
        text  = text.substring(pattern.length);
      }
      if (!this._isNumber(month)) return null; // error
      result.month = parseInt(month, 10);
      return text;
    },
    "d": function(text, pattern, result) {
      // Day in month
      var day;
      if (pattern.length == 1 && text.length > 1 
          && text.substring(0, 2).match(/1[0-9]|2[0-9]|3[0-1]/) != null) {
        day  = text.substring(0, 2);
        text = text.substring(2);
      } else {
        day  = text.substring(0, pattern.length);
        text = text.substring(pattern.length);
      }
      if (!this._isNumber(day)) return null; // error
      result.day = parseInt(day, 10);
      return text;
    },
    "H": function(text, pattern, result) {
      // Hour in day (0-23)
      var hour;
      if (pattern.length == 1 && text.length > 1
          && text.substring(0, 2).match(/1[0-9]|2[0-3]/) != null) {
        hour = text.substring(0, 2);
        text = text.substring(2);
      } else {
        hour = text.substring(0, pattern.length);
        text = text.substring(pattern.length);
      }
      if (!this._isNumber(hour)) return null; // error
      result.hour = parseInt(hour, 10);
      return text;
    },
    "m": function(text, pattern, result) {
      // Minute in hour
      var min;
      if (pattern.length == 1 && text.length > 1
          && text.substring(0, 2).match(/[1-5][0-9]/) != null) {
        min  = text.substring(0, 2);
        text = text.substring(2);
      } else {
        min  = text.substring(0, pattern.length);
        text = text.substring(pattern.length);
      }
      if (!this._isNumber(min)) return null; // error
      result.min = parseInt(min, 10);
      return text;
    },
    "s": function(text, pattern, result) {
      // Second in minute
      var sec;
      if (pattern.length == 1 && text.length > 1
          && text.substring(0, 2).match(/[1-5][0-9]/) != null) {
        sec  = text.substring(0, 2);
        text = text.substring(2);
      } else {
        sec  = text.substring(0, pattern.length);
        text = text.substring(pattern.length);
      }
      if (!this._isNumber(sec)) return null; // error
      result.sec = parseInt(sec, 10);
      return text;
    },
    "S": function(text, pattern, result) {
      // Millimsecond
      var msec;
      if (pattern.length == 1 || pattern.length == 2) {
        if (text.length > 2 && text.substring(0, 3).match(/[1-9][0-9][0-9]/) != null) {
          msec = text.substring(0, 3);
          text = text.substring(3);
        } else if (text.length > 1 && text.substring(0, 2).match(/[1-9][0-9]/) != null) {
          msec = text.substring(0, 2);
          text = text.substring(2);
        } else {
          msec = text.substring(0, pattern.length);
          text = text.substring(pattern.length);
        }
      } else {
        msec = text.substring(0, pattern.length);
        text = text.substring(pattern.length);
      }
      if (!this._isNumber(msec)) return null; // error
      result.msec = parseInt(msec, 10);
      return text;
    },
    "'": function(text, pattern, result) {
      // escape
      if (pattern == "''") {
        pattern = "'";
      } else {
        pattern = pattern.replace(/'/g, '');
      }
      if (text.indexOf(pattern) != 0) {
        return null; // error
      } else {
        return text.substring(pattern.length);
      }
    }
  },

  _isNumber: function(str) {
    return /^[0-9]*$/.test(str);
  }
}

$(function () {    
	$('ul.spy1').simpleSpy(5,3700);
	$('ul.spy2').simpleSpy(5,3500);
	setTimeout(function() {
			$('ul.spy3').simpleSpy(5,3800);
		}, 1000);
	
	$('ul.spy4').simpleSpy(5,3400);
	setTimeout(function() {
			$('ul.spy5').simpleSpy(5,3300);
		}, 1000);
	$('ul.spy6').simpleSpy(5,3900);
});
 
(function ($) {
    
$.fn.simpleSpy = function (limit, interval) {
    limit = limit || 5;
    interval = interval || 4000;
    
    return this.each(function () {
        // 1. setup
            // capture a cache of all the list items
            // chomp the list down to limit li elements
        var $list = $(this),
            items = [], // uninitialised
            currentItem = limit,
            total = 0, // initialise later on
            height = $list.find('> li:first').height();
            
        // capture the cache
        $list.find('> li').each(function () {
            items.push('<li>' + $(this).html() + '</li>');
        });
        
        total = items.length;
        
        $list.wrap('<div class="spyWrapper" />').parent().css({ height : height * limit });
        
        $list.find('> li').filter(':gt(' + (limit - 1) + ')').remove();
 
        // 2. effect        
        function spy() {
            // insert a new item with opacity and height of zero
            var $insert = $(items[currentItem]).css({
                height : 0,
                opacity : 0,
                display : 'none'
            }).prependTo($list);
                        
            // fade the LAST item out
            $list.find('> li:last').animate({ opacity : 0}, 1000, function () {
                // increase the height of the NEW first item
                $insert.animate({ height : height }, 1000).animate({ opacity : 1 }, 1000);
                
                // AND at the same time - decrease the height of the LAST item
                // $(this).animate({ height : 0 }, 1000, function () {
                    // finally fade the first item in (and we can remove the last)
                    $(this).remove();
                // });
            });
            
            currentItem++;
            if (currentItem >= total) {
                currentItem = 0;
            }
            
            setTimeout(spy, interval)
        }
        
        spy();
    });
};
    
})(jQuery);

/*
 * Droppy 0.1.2
 * (c) 2008 Jason Frame (jason@onehackoranother.com)
 */
$.fn.droppy = function(options) {
    
  options = $.extend({speed: 250}, options || {});
  
  this.each(function() {
    
    var root = this, zIndex = 1000;
    
    function getSubnav(ele) {
      if (ele.nodeName.toLowerCase() == 'li') {
        var subnav = $('> ul', ele);
        return subnav.length ? subnav[0] : null;
      } else {
        return ele;
      }
    }
    
    function getActuator(ele) {
      if (ele.nodeName.toLowerCase() == 'ul') {
        return $(ele).parents('li')[0];
      } else {
        return ele;
      }
    }
    
    function hide() {
      var subnav = getSubnav(this);
      if (!subnav) return;
      $.data(subnav, 'cancelHide', false);
      setTimeout(function() {
        if (!$.data(subnav, 'cancelHide')) {
          $(subnav).slideUp(options.speed);
        }
      }, 500);
    }
  
    function show() {
      var subnav = getSubnav(this);
      if (!subnav) return;
      $.data(subnav, 'cancelHide', true);
      $(subnav).css({zIndex: zIndex++}).slideDown(options.speed);
      if (this.nodeName.toLowerCase() == 'ul') {
        var li = getActuator(this);
        $(li).addClass('hover');
        $('> a', li).addClass('hover');
      }
    }
    
    $('ul, li', this).hover(show, hide);
    $('li', this).hover(
      function() { $(this).addClass('hover'); $('> a', this).addClass('hover'); },
      function() { $(this).removeClass('hover'); $('> a', this).removeClass('hover'); }
    );
    
  });
  
};


// ColorBox v1.3.6 - a full featured, light-weight, customizable lightbox based on jQuery 1.3
// c) 2009 Jack Moore - www.colorpowered.com - jack@colorpowered.com
// Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php

(function ($) {
	// Shortcuts (to increase compression)
	var colorbox = 'colorbox',
	hover = 'hover',
	TRUE = true,
	FALSE = false,
	cboxPublic,
	isIE = !$.support.opacity,
	isIE6 = isIE && !window.XMLHttpRequest,

	// Event Strings (to increase compression)
	cbox_open = 'cbox_open',
	cbox_load = 'cbox_load',
	cbox_complete = 'cbox_complete',
	cbox_cleanup = 'cbox_cleanup',
	cbox_closed = 'cbox_closed',
	cbox_resize = 'resize.cbox_resize',

	// Cached jQuery Object Variables
	$overlay,
	$cbox,
	$wrap,
	$content,
	$topBorder,
	$leftBorder,
	$rightBorder,
	$bottomBorder,
	$related,
	$window,
	$loaded,
	$loadingBay,
	$loadingOverlay,
	$loadingGraphic,
	$title,
	$current,
	$slideshow,
	$next,
	$prev,
	$close,

	// Variables for cached values or use across multiple functions
	interfaceHeight,
	interfaceWidth,
	loadedHeight,
	loadedWidth,
	element,
	bookmark,
	index,
	settings,
	open,
	active,
	
	// ColorBox Default Settings.	
	// See http://colorpowered.com/colorbox for details.
	defaults = {
		transition: "elastic",
		speed: 350,
		width: FALSE,
		height: FALSE,
		innerWidth: FALSE,
		innerHeight: FALSE,
		initialWidth: "400",
		initialHeight: "400",
		maxWidth: FALSE,
		maxHeight: FALSE,
		scalePhotos: TRUE,
		scrolling: TRUE,
		inline: FALSE,
		html: FALSE,
		iframe: FALSE,
		photo: FALSE,
		href: FALSE,
		title: FALSE,
		rel: FALSE,
		opacity: 0.9,
		preloading: TRUE,
		current: "",
		previous: "",
		next: "",
		close: "close",
		open: FALSE,
		overlayClose: TRUE,
		
		slideshow: FALSE,
		slideshowAuto: TRUE,
		slideshowSpeed: 2500,
		slideshowStart: "start slideshow",
		slideshowStop: "stop slideshow",
		
		onOpen: FALSE,
		onLoad: FALSE,
		onComplete: FALSE,
		onCleanup: FALSE,
		onClosed: FALSE
	};
	
	// ****************
	// HELPER FUNCTIONS
	// ****************
		
	// Convert % values to pixels
	function setSize(size, dimension) {
		dimension = dimension === 'x' ? $window.width() : $window.height();//document.documentElement.clientWidth : document.documentElement.clientHeight;
		return (typeof size === 'string') ? Math.round((size.match(/%/) ? (dimension / 100) * parseInt(size, 10) : parseInt(size, 10))) : size;
	}

	// Checks an href to see if it is a photo.
	// There is a force photo option (photo: true) for hrefs that cannot be matched by this regex.
	function isImage(url) {
		url = $.isFunction(url) ? url.call(element) : url;
		return settings.photo || url.match(/\.(gif|png|jpg|jpeg|bmp)(?:\?([^#]*))?(?:#(\.*))?$/i);
	}
	
	// Assigns functions results to their respective settings.  This allows functions to be used to set ColorBox options.
	function process() {
		for (var i in settings) {
			if ($.isFunction(settings[i]) && i.substring(0, 2) !== 'on') { // checks to make sure the function isn't one of the callbacks, they will be handled at the appropriate time.
			    settings[i] = settings[i].call(element);
			}
		}
		settings.rel = settings.rel || element.rel;
		settings.href = settings.href || element.href;
		settings.title = settings.title || element.title;
	}

	function launch(elem) {
		
		element = elem;
		
		settings = $(element).data(colorbox);
		
		process(); // Convert functions to their returned values.
		
		if (settings.rel && settings.rel !== 'nofollow') {
			$related = $('.cboxElement').filter(function () {
				var relRelated = $(this).data(colorbox).rel || this.rel;
				return (relRelated === settings.rel);
			});
			index = $related.index(element);
			
			// Check direct calls to ColorBox.
			if (index < 0) {
				$related = $related.add(element);
				index = $related.length - 1;
			}
		} else {
			$related = $(element);
			index = 0;
		}
		
		if (!open) {
			open = TRUE;
			
			active = TRUE; // Prevents the page-change action from queuing up if the visitor holds down the left or right keys.
			
			bookmark = element;
			
			bookmark.blur(); // Remove the focus from the calling element.
			
			// Set Navigation Key Bindings
			$(document).bind("keydown.cbox_close", function (e) {
				if (e.keyCode === 27) {
					e.preventDefault();
					cboxPublic.close();
				}
			}).bind("keydown.cbox_arrows", function (e) {
				if ($related.length > 1) {
					if (e.keyCode === 37) {
						e.preventDefault();
						$prev.click();
					} else if (e.keyCode === 39) {
						e.preventDefault();
						$next.click();
					}
				}
			});
			
			if (settings.overlayClose) {
				$overlay.css({"cursor": "pointer"}).one('click', cboxPublic.close);
			}
			
			$.event.trigger(cbox_open);
			if (settings.onOpen) {
				settings.onOpen.call(element);
			}
			
			$overlay.css({"opacity": settings.opacity}).show();
			
			// Opens inital empty ColorBox prior to content being loaded.
			settings.w = setSize(settings.initialWidth, 'x');
			settings.h = setSize(settings.initialHeight, 'y');
			cboxPublic.position(0);
			
			if (isIE6) {
				$window.bind('resize.cboxie6 scroll.cboxie6', function () {
					$overlay.css({width: $window.width(), height: $window.height(), top: $window.scrollTop(), left: $window.scrollLeft()});
				}).trigger("scroll.cboxie6");
			}
		}
		
		$current.add($prev).add($next).add($slideshow).add($title).hide();
		
		$close.html(settings.close).show();
		
		cboxPublic.slideshow();
		
		cboxPublic.load();
	}

	// ****************
	// PUBLIC FUNCTIONS
	// Usage format: $.fn.colorbox.close();
	// Usage from within an iframe: parent.$.fn.colorbox.close();
	// ****************
	
	cboxPublic = $.fn.colorbox = function (options, callback) {
		var $this = this;
		
		if (!$this.length) {
			if ($this.selector === '') { // empty selector means a direct call, ie: $.fn.colorbox();
				$this = $('<a/>');
				options.open = TRUE;
			} else { // else the selector didn't match anything, and colorbox should go ahead and return.
				return this;
			}
		}
		
		$this.each(function () {
			var data = $.extend({}, $(this).data(colorbox) ? $(this).data(colorbox) : defaults, options);
			
			$(this).data(colorbox, data).addClass("cboxElement");
			
			if (callback) {
				$(this).data(colorbox).onComplete = callback;
			}
		});
		
		if (options && options.open) {
			launch($this);
		}
		
		return this;
	};

	// Initialize ColorBox: store common calculations, preload the interface graphics, append the html.
	// This preps colorbox for a speedy open when clicked, and lightens the burdon on the browser by only
	// having to run once, instead of each time colorbox is opened.
	cboxPublic.init = function () {
		
		// jQuery object generator to save a bit of space
		function $div(id) {
			return $('<div id="cbox' + id + '"/>');
		}
		
		// Create & Append jQuery Objects
		$window = $(window);
		$cbox = $('<div id="colorbox"/>');
		$overlay = $div("Overlay").hide();
		$wrap = $div("Wrapper");
		$content = $div("Content").append(
			$loaded = $div("LoadedContent").css({width: 0, height: 0}),
			$loadingOverlay = $div("LoadingOverlay"),
			$loadingGraphic = $div("LoadingGraphic"),
			$title = $div("Title"),
			$current = $div("Current"),
			$slideshow = $div("Slideshow"),
			$next = $div("Next"),
			$prev = $div("Previous"),
			$close = $div("Close")
		);
		$wrap.append( // The 3x3 Grid that makes up ColorBox
			$('<div/>').append(
				$div("TopLeft"),
				$topBorder = $div("TopCenter"),
				$div("TopRight")
			),
			$('<div/>').append(
				$leftBorder = $div("MiddleLeft"),
				$content,
				$rightBorder = $div("MiddleRight")
			),
			$('<div/>').append(
				$div("BottomLeft"),
				$bottomBorder = $div("BottomCenter"),
				$div("BottomRight")
			)
		).children().children().css({'float': 'left'});
		
		$loadingBay = $("<div style='position:absolute; top:0; left:0; width:9999px; height:0;'/>");
		
		$('body').prepend($overlay, $cbox.append($wrap, $loadingBay));
				
		if (isIE) {
			$cbox.addClass('cboxIE');
			if (isIE6) {
				$overlay.css('position', 'absolute');
			}
		}
		
		// Add rollover event to navigation elements
		$content.children()
		.bind('mouseover mouseout', function(){
			$(this).toggleClass(hover);
		}).addClass(hover);
		
		// Cache values needed for size calculations
		interfaceHeight = $topBorder.height() + $bottomBorder.height() + $content.outerHeight(TRUE) - $content.height();//Subtraction needed for IE6
		interfaceWidth = $leftBorder.width() + $rightBorder.width() + $content.outerWidth(TRUE) - $content.width();
		loadedHeight = $loaded.outerHeight(TRUE);
		loadedWidth = $loaded.outerWidth(TRUE);
		
		// Setting padding to remove the need to do size conversions during the animation step.
		$cbox.css({"padding-bottom": interfaceHeight, "padding-right": interfaceWidth}).hide();
		
		// Setup button & key events.
		$next.click(cboxPublic.next);
		$prev.click(cboxPublic.prev);
		$close.click(cboxPublic.close);
		
		// Adding the 'hover' class allowed the browser to load the hover-state
		// background graphics.  The class can now can be removed.
		$content.children().removeClass(hover);
		
		$('.cboxElement').live('click', function (e) {
			if (e.button !== 0 && typeof e.button !== 'undefined') {// checks to see if it was a non-left mouse-click.
				return TRUE;
			} else {
				launch(this);			
				return FALSE;
			}
		});
	};

	cboxPublic.position = function (speed, loadedCallback) {
		var
		animate_speed,
		winHeight = $window.height(),
		// keeps the top and left positions within the browser's viewport.
		posTop = Math.max(winHeight - settings.h - loadedHeight - interfaceHeight,0)/2 + $window.scrollTop(),
		posLeft = Math.max(document.documentElement.clientWidth - settings.w - loadedWidth - interfaceWidth,0)/2 + $window.scrollLeft();
		
		// setting the speed to 0 to reduce the delay between same-sized content.
		animate_speed = ($cbox.width() === settings.w+loadedWidth && $cbox.height() === settings.h+loadedHeight) ? 0 : speed;
		
		// this gives the wrapper plenty of breathing room so it's floated contents can move around smoothly,
		// but it has to be shrank down around the size of div#colorbox when it's done.  If not,
		// it can invoke an obscure IE bug when using iframes.
		$wrap[0].style.width = $wrap[0].style.height = "9999px";
		
		function modalDimensions (that) {
			// loading overlay size has to be sure that IE6 uses the correct height.
			$topBorder[0].style.width = $bottomBorder[0].style.width = $content[0].style.width = that.style.width;
			$loadingGraphic[0].style.height = $loadingOverlay[0].style.height = $content[0].style.height = $leftBorder[0].style.height = $rightBorder[0].style.height = that.style.height;
		}
		
		$cbox.dequeue().animate({width:settings.w+loadedWidth, height:settings.h+loadedHeight, top:posTop, left:posLeft}, {duration: animate_speed,
			complete: function(){
				modalDimensions(this);
				
				active = FALSE;
				
				// shrink the wrapper down to exactly the size of colorbox to avoid a bug in IE's iframe implementation.
				$wrap[0].style.width = (settings.w+loadedWidth+interfaceWidth) + "px";
				$wrap[0].style.height = (settings.h+loadedHeight+interfaceHeight) + "px";
				
				if (loadedCallback) {loadedCallback();}
			},
			step: function(){
				modalDimensions(this);
			}
		});
	};

	cboxPublic.resize = function (object) {
		if(!open){ return; }
		
		var topMargin,
		prev,
		prevSrc,
		next,
		nextSrc,
		photo,
		timeout,
		speed = settings.transition==="none" ? 0 : settings.speed;
		
		$window.unbind(cbox_resize);
		
		if(!object){
			timeout = setTimeout(function(){ // timer allows IE to render the dimensions before attempting to calculate the height
				var $child = $loaded.wrapInner("<div style='overflow:auto'></div>").children(); // temporary wrapper to get an accurate estimate of just how high the total content should be.
				settings.h = $child.height();
				$loaded.css({height:settings.h});
				$child.replaceWith($child.children()); // ditch the temporary wrapper div used in height calculation
				cboxPublic.position(speed);
			}, 1);
			return;
		}
		
		$loaded.remove();
		$loaded = $('<div id="cboxLoadedContent"/>').html(object);
		
		function getWidth(){
			settings.w = settings.w || $loaded.width();
			settings.w = settings.mw && settings.mw < settings.w ? settings.mw : settings.w;
			return settings.w;
		}
		function getHeight(){
			settings.h = settings.h || $loaded.height();
			settings.h = settings.mh && settings.mh < settings.h ? settings.mh : settings.h;
			return settings.h;
		}
		
		$loaded.hide()
		.appendTo($loadingBay)// content has to be appended to the DOM for accurate size calculations.  Appended to an absolutely positioned element, rather than BODY, which avoids an extremely brief display of the vertical scrollbar in Firefox that can occur for a small minority of websites.
		.css({width:getWidth(), overflow:settings.scrolling ? 'auto' : 'hidden'})
		.css({height:getHeight()})// sets the height independently from the width in case the new width influences the value of height.
		.prependTo($content);
		
		$('#cboxPhoto').css({cssFloat:'none'});// floating the IMG removes the bottom line-height and fixed a problem where IE miscalculates the width of the parent element as 100% of the document width.
		
		// Hides SELECT elements in IE6 because they would otherwise sit on top of the overlay.
		if (isIE6) {
			$('select:not(#colorbox select)').filter(function(){
				return this.style.visibility !== 'hidden';
			}).css({'visibility':'hidden'}).one(cbox_cleanup, function(){
				this.style.visibility = 'inherit';
			});
		}
				
		function setPosition (s) {
			cboxPublic.position(s, function(){
				if (!open) { return; }
				
				if (isIE) {
					//This fadeIn helps the bicubic resampling to kick-in.
					if( photo ){$loaded.fadeIn(100);}
					//IE adds a filter when ColorBox fades in and out that can cause problems if the loaded content contains transparent pngs.
					$cbox[0].style.removeAttribute("filter");
				}
				
				//Waited until the iframe is added to the DOM & it is visible before setting the src.
				//This increases compatability with pages using DOM dependent JavaScript.
				if(settings.iframe){
					$loaded.append("<iframe id='cboxIframe'" + (settings.scrolling ? " " : "scrolling='no'") + " name='iframe_"+new Date().getTime()+"' frameborder=0 src='"+settings.href+"' " + (isIE ? "allowtransparency='true'" : '') + " />");
				}
				
				$loaded.show();
				
				$title.show().html(settings.title);
				
				if ($related.length>1) {
					$current.html(settings.current.replace(/\{current\}/, index+1).replace(/\{total\}/, $related.length)).show();
					$next.html(settings.next).show();
					$prev.html(settings.previous).show();
					
					if(settings.slideshow){
						$slideshow.show();
					}
				}
				
				$loadingOverlay.hide();
				$loadingGraphic.hide();
				
				$.event.trigger(cbox_complete);
				if (settings.onComplete) {
					settings.onComplete.call(element);
				}
				
				if (settings.transition === 'fade'){
					$cbox.fadeTo(speed, 1, function(){
						if(isIE){$cbox[0].style.removeAttribute("filter");}
					});
				}
				
				$window.bind(cbox_resize, function(){
					cboxPublic.position(0);
				});
			});
		}
		
		if((settings.transition === 'fade' && $cbox.fadeTo(speed, 0, function(){setPosition(0);})) || setPosition(speed)){}
		
		// Preloads images within a rel group
		if (settings.preloading && $related.length>1) {
			prev = index > 0 ? $related[index-1] : $related[$related.length-1];
			next = index < $related.length-1 ? $related[index+1] : $related[0];
			nextSrc = $(next).data(colorbox).href || next.href;
			prevSrc = $(prev).data(colorbox).href || prev.href;
			
			if(isImage(nextSrc)){
				$('<img />').attr('src', nextSrc);
			}
			
			if(isImage(prevSrc)){
				$('<img />').attr('src', prevSrc);
			}
		}

	};

	cboxPublic.load = function () {
		var href, img, setResize, resize = cboxPublic.resize;
		
		active = TRUE;
		
		/*
		 
		// I decided to comment this out because I can see it causing problems as users
		// really should just set the dimensions on their IMG elements instead,
		// but I'm leaving the code in as it may be useful to someone.
		// To use, uncomment the function and change 'if(textStatus === "success"){ resize(this); }'
		// to 'if(textStatus === "success"){ preload(this); }'
		
		// Preload loops through the HTML to find IMG elements and loads their sources.
		// This allows the resize method to accurately estimate the dimensions of the new content.
		function preload(html){
			var
			$ajax = $(html),
			$imgs = $ajax.find('img'),
			x = $imgs.length;
			
			function loadloop(){
				var img = new Image();
				x = x-1;
				if(x >= 0){
					img.onload = loadloop;
					img.src = $imgs[x].src;
				} else {
					resize($ajax);
				}
			}
			
			loadloop();
		}
		*/
		
		element = $related[index];
		
		settings = $(element).data(colorbox);
		
		//convert functions to static values
		process();
		
		$.event.trigger(cbox_load);
		if (settings.onLoad) {
			settings.onLoad.call(element);
		}
		
		// Evaluate the height based on the optional height and width settings.
		settings.h = settings.height ?
				setSize(settings.height, 'y') - loadedHeight - interfaceHeight :
				settings.innerHeight ?
					setSize(settings.innerHeight, 'y') :
					FALSE;
		settings.w = settings.width ?
				setSize(settings.width, 'x') - loadedWidth - interfaceWidth :
				settings.innerWidth ?
					setSize(settings.innerWidth, 'x') :
					FALSE;
		
		// Sets the minimum dimensions for use in image scaling
		settings.mw = settings.w;
		settings.mh = settings.h;
		
		// Re-evaluate the minimum width and height based on maxWidth and maxHeight values.
		// If the width or height exceed the maxWidth or maxHeight, use the maximum values instead.
		if(settings.maxWidth){
			settings.mw = setSize(settings.maxWidth, 'x') - loadedWidth - interfaceWidth;
			settings.mw = settings.w && settings.w < settings.mw ? settings.w : settings.mw;
		}
		if(settings.maxHeight){
			settings.mh = setSize(settings.maxHeight, 'y') - loadedHeight - interfaceHeight;
			settings.mh = settings.h && settings.h < settings.mh ? settings.h : settings.mh;
		}
		
		href = settings.href;
		
		$loadingOverlay.show();
		$loadingGraphic.show();
		
		if (settings.inline) {
			// Inserts an empty placeholder where inline content is being pulled from.
			// An event is bound to put inline content back when ColorBox closes or loads new content.
			$('<div id="cboxInlineTemp" />').hide().insertBefore($(href)[0]).bind(cbox_load+' '+cbox_cleanup, function(){
				$(this).replaceWith($loaded.children());
			});
			resize($(href));
		} else if (settings.iframe) {
			// IFrame element won't be added to the DOM until it is ready to be displayed,
			// to avoid problems with DOM-ready JS that might be trying to run in that iframe.
			resize(" ");
		} else if (settings.html) {
			resize(settings.html);
		} else if (isImage(href)){
			img = new Image();
			img.onload = function(){
				var percent;
				
				img.onload = null;
				
				img.id = 'cboxPhoto';
				
				$(img).css({margin:'auto', border:'none', display:'block', cssFloat:'left'});
				
				if(settings.scalePhotos){
					setResize = function(){
						img.height -= img.height * percent;
						img.width -= img.width * percent;	
					};
					if(settings.mw && img.width > settings.mw){
						percent = (img.width - settings.mw) / img.width;
						setResize();
					}
					if(settings.mh && img.height > settings.mh){
						percent = (img.height - settings.mh) / img.height;
						setResize();
					}
				}
				
				if (settings.h) {
					img.style.marginTop = Math.max(settings.h - img.height,0)/2 + 'px';
				}
				
				resize(img);
				
				if($related.length > 1){
					$(img).css({cursor:'pointer'}).click(cboxPublic.next);
				}
				
				if(isIE){
					img.style.msInterpolationMode='bicubic';
				}
			};
			img.src = href;
		} else {
			$('<div />').appendTo($loadingBay).load(href, function(data, textStatus){
				if(textStatus === "success"){
					resize(this);
				} else {
					resize($("<p>Request unsuccessful.</p>"));
				}
			});
		}
	};

	// Navigates to the next page/image in a set.
	cboxPublic.next = function () {
		if(!active){
			index = index < $related.length-1 ? index+1 : 0;
			cboxPublic.load();
		}
	};
	
	cboxPublic.prev = function () {
		if(!active){
			index = index > 0 ? index-1 : $related.length-1;
			cboxPublic.load();
		}
	};

	cboxPublic.slideshow = function () {
		var stop, timeOut, className = 'cboxSlideshow_';
		
		$slideshow.bind(cbox_closed, function(){
			$slideshow.unbind();
			clearTimeout(timeOut);
			$cbox.removeClass(className+"off"+" "+className+"on");
		});
		
		function start(){
			$slideshow
			.text(settings.slideshowStop)
			.bind(cbox_complete, function(){
				timeOut = setTimeout(cboxPublic.next, settings.slideshowSpeed);
			})
			.bind(cbox_load, function(){
				clearTimeout(timeOut);	
			}).one("click", function(){
				stop();
				$(this).removeClass(hover);
			});
			$cbox.removeClass(className+"off").addClass(className+"on");
		}
		
		stop = function(){
			clearTimeout(timeOut);
			$slideshow
			.text(settings.slideshowStart)
			.unbind(cbox_complete+' '+cbox_load)
			.one("click", function(){
				start();
				timeOut = setTimeout(cboxPublic.next, settings.slideshowSpeed);
				$(this).removeClass(hover);
			});
			$cbox.removeClass(className+"on").addClass(className+"off");
		};
		
		if(settings.slideshow && $related.length>1){
			if(settings.slideshowAuto){
				start();
			} else {
				stop();
			}
		}
	};

	// Note: to use this within an iframe use the following format: parent.$.fn.colorbox.close();
	cboxPublic.close = function () {
		
		$.event.trigger(cbox_cleanup);
		if (settings.onCleanup) {
			settings.onCleanup.call(element);
		}
		
		open = FALSE;
		$(document).unbind("keydown.cbox_close keydown.cbox_arrows");
		$window.unbind(cbox_resize+' resize.cboxie6 scroll.cboxie6');
		$overlay.css({cursor: 'auto'}).fadeOut('fast');
		
		$cbox
		.stop(TRUE, FALSE)
		.fadeOut('fast', function () {
			$('#colorbox iframe').attr('src', 'about:blank');
			$loaded.remove();
			$cbox.css({'opacity': 1});
			
			try{
				bookmark.focus();
			} catch (er){
				// do nothing
			}
			
			$.event.trigger(cbox_closed);
			if (settings.onClosed) {
				settings.onClosed.call(element);
			}
		});
	};

	// A method for fetching the current element ColorBox is referencing.
	// returns a jQuery object.
	cboxPublic.element = function(){ return $(element); };

	cboxPublic.settings = defaults;

	// Initializes ColorBox when the DOM has loaded
	$(cboxPublic.init);

}(jQuery));

