/*
 * 图片切换api
 * */
(function($) {
	$.smallslider=function(elm, options){
	// this 为当前的smallslider对象，为了区别，使用 _this 替换
	var _this = this;
	      _this.elm = elm ;	    // elm 为当前的 DOM对象 ，即使用class="smallslider" 的那个div对象。
	      _this.$elm = $(elm);  // $elm 为elm对象的jquery形式 
	      _this.opts=$.extend({},$.smallslider.defaults, options);	      
              _this.sliderTimer= null ;

	    // 初始化对象
	    _this.init = function()
	    {   
		    _this.$ul = _this.$elm.find('>ul') ;  // 为子元素ul
		    _this.$lis = _this.$elm.find('li') ;  // 为所有ul下子元素li 数组
		    _this.$ims = _this.$elm.find('img') ;  // 为所有li下子元素img 数组
		    _this.itemNums = _this.$lis.length ;
		    _this.width = _this.$elm.width();
		    _this.height = _this.$elm.height();
		    _this.current = 0 ;			// 当前的index索引
		    
		    if(_this.itemNums > 1)
		    {
			if(_this.opts.switchEffect=='ease')
			{
			    _this.$ul.css({
				position:'absolute',
				left:0,
				top: 0
			    });
			    if(_this.opts.switchPath=='left')
			    {
				var width = _this.itemNums *  _this.width;
				_this.$lis.css({
				    'float' : 'left'
				});
				_this.$ul.css({
				    'width' : width
				});
			    }
			    else if(_this.opts.switchPath=='up')
			    {
				var height = _this.itemNums *  _this.height;
				_this.$ul.css({
				    'height' : height
				});
			    }
			}
			else if(_this.opts.switchEffect=='fadeOut')
			{
			    _this.$ul.css({
				position:'relative'
			    });
			    _this.$lis.css({
				position:'absolute',
				zIndex:1
			    }).eq(0).css({
				zIndex:2
			    });
			}
			if(_this.opts.showButtons)
			{
			    _this.createButtons();	// 创建按钮。
			}
			if(_this.opts.showText)
			{
			    _this.createText();	// 创建文字显示。
			}
			if(_this.opts.autoStart)
			{
			    _this.startSlider(1);
			}
			if(_this.opts.onImageStop)
			{
			    _this.onImage();
			}
		    }
	    };
	    _this.createButtons = function()
	    {
		    var buttons='';
		    for(var i=1; i <= _this.itemNums ; i++ ){
			buttons += '<span>'+i+'</span>';
		    }
		    buttons ='<div class="smallslider-btns">' + buttons + '</div>';
		    var left=0,right=0,top =0,bottom=0;
		    var style_btns={};
		    switch(_this.opts.buttonPosition){
			case 'leftTop':
			    left = _this.opts.buttonOffsetX;
			    top  = _this.opts.buttonOffsetY;
			    style_btns={left: left + 'px' , top: top+'px'};
			    break;
			case 'rightTop':
			    right = _this.opts.buttonOffsetX;
			    top  = _this.opts.buttonOffsetY;
			    style_btns={right: right + 'px' , top: top+'px'};
			    break;
			case 'rightBottom':
			    right = _this.opts.buttonOffsetX;
			    bottom = _this.opts.buttonOffsetY;
			    style_btns={right: right + 'px' ,bottom: bottom+'px'};
			    break;
			case 'leftBottom':
			    left = _this.opts.buttonOffsetX;
			    bottom = _this.opts.buttonOffsetY;
			    style_btns={left: left + 'px' ,bottom: bottom+'px'};
			    break;
		    }
		    $(buttons).css(style_btns).appendTo(_this.$elm);
		    _this.$btns = _this.$elm.find('span');
		    _this.$elm.find('span:not(:first)').css({marginLeft: _this.opts.buttonSpace+'px'});
		    _this.$btns.removeClass('current-btn');
		    _this.$btns.eq(0).addClass('current-btn');
		    if(_this.opts.switchMode=='click'){
			_this.$btns.click(function(){
			    var ix = _this.$btns.index($(this));
			    _this.slideTo(ix); // 表示需要切换到哪一张
			});
		    }else if(_this.opts.switchMode=='hover'){
			 _this.$btns.hover(function(){
			    var ix = _this.$btns.index($(this));
			    _this.slideTo(ix);
			});
		    }
	    };

	    // 创建标题标签
	_this.createText = function(){
	    var style_tex={}; 
	    switch(_this.opts.buttonPosition){
		case 'leftTop':
		    style_tex={left:0,	top:0,textAlign:'right'};
		    _this.textPosition = 'top';
		    break;
		case 'rightTop':
		    style_tex={left:0,	top:0,textAlign:'left'};
		    _this.textPosition = 'top';
		    break;
		case 'rightBottom':
		    style_tex={left:0,bottom:0,textAlign:'left'};
		    _this.textPosition = 'bottom';
		    break;
		case 'leftBottom':
		    style_tex={left:0,bottom:0,textAlign:'right'};
		    _this.textPosition = 'bottom';
		    break;
	    }
	    if(_this.opts.textPosition){
		switch(_this.opts.textPosition)
		{
			case 'top':
			    style_tex.left = 0 ;  style_tex.top = 0;
			    break;
			case 'bottom':
			    style_tex.left = 0 ; style_tex.bottom=0 ;
			    break;
		}
		_this.textPosition = _this.opts.textPosition ;
	    }
	    if(_this.opts.textAlign)
	    {
		    style_tex.textAlign =_this.opts.textAlign;
	    }
	    $('<div class="smallslider-tex smallslider-lay"></div>').css(style_tex).css({
		opacity:0.39
	    }).appendTo(_this.$elm);

	    var tex0= _this.$ims.eq(0).attr('alt');
	    if(_this.opts.textLink){
		tex0 = '<a href="'+_this.$ims.eq(0).parent('a').attr('href')+'">'+ tex0+'</a>';
	    }
	    $('<h3 class="smallslider-tex"></h3>').css(style_tex).html(tex0).appendTo(_this.$elm);
	    _this.$h3 = _this.$elm.find('h3');
	    _this.$lay = _this.$elm.find('div.smallslider-lay');
	    _this.$tex = _this.$elm.find('.smallslider-tex');
	};
        _this.onImage =function(){
            _this.$ims.hover(function(){
                _this.stopSlider();
            }, function(){
                _this.slideTo(_this.current+1);
            });
        };

        _this.slideTo = function (index){
            _this.stopSlider(); // 先清掉以前的setTimeout;
            if(index > _this.itemNums -1) index = 0;
	    if(index < 0 ) index = _this.itemNums -1 ;
	    // 切换表示当前元素
            _this.$lis.removeClass('current-li').eq(index).addClass('current-li');
	    if(_this.opts.showButtons)
	    {
		_this.$btns.removeClass('current-btn');
		_this.$btns.eq(index).addClass('current-btn');
	    }
	    _this.slideText(index);
	    var chAttr = '';
	    var iC = 0;
	    switch(_this.opts.switchPath)
	    {	
		case 'left':
		    chAttr = 'left';
		    iC =_this.width ;
		    break;
		case 'up':
		 default :
		    chAttr = 'top';
		    iC = _this.height ;
		    break;
	    }
	    var iCx = -1 * index * iC; // Top或Left 变化量
	    var switchEase = _this.opts.switchEase  ;
            switch( _this.opts.switchEffect){
                case 'fadeOut':
		    _this.$lis.stop(true,false);
                    _this.$lis.css({zIndex:1,opacity:1}).hide();
		    _this.$lis.eq(_this.current).css({zIndex:3}).show();
		    _this.$lis.eq(index).css({zIndex:2}).show();
                    if(_this.current != index)
                    {
                    	_this.$lis.eq(_this.current).fadeOut(_this.opts.switchTime,function(){
				_this.$lis.css({zIndex:1});
				_this.$lis.eq(index).css({zIndex:3,opacity:1}).show();
                   	});
                    }
                    break;
		case 'ease':
		    _this.$ul.stop(true,false);
		    if(chAttr=='top')
			_this.$ul.animate({top : iCx}, {duration: _this.opts.switchTime, easing: switchEase, complete: function(){
			    }
			});
		    else if(chAttr=='left')
			_this.$ul.animate({left : iCx}, {duration: _this.opts.switchTime, easing: switchEase ,complete:function(){
			}});
		    break;
                case 'none':
                default :
                    _this.$lis.eq(_this.current).hide();
                    _this.$lis.eq(index).show();
                    break;
            }
	    _this.current = index ;
            _this.startSlider(index+1);
        };

	// 切换文字
	_this.slideText = function(index)
	{
	    if(_this.opts.showText)
	    {
		    var tex = _this.$ims.eq(index).attr('alt');
		    if(_this.opts.textLink){
			tex = '<a href="'+_this.$ims.eq(index).parent('a').attr('href')+'">'+ tex+'</a>';
		    }
		    _this.$h3.html(tex);
		    if(_this.opts.textSwitch>0){
			var t_path = _this.$h3.height();
			var t_ani1 ={}, t_ani2 ={};
			if(_this.textPosition=='top'){
				t_ani1 = {top : -1*t_path};
				t_ani2 = {top : 0}; 
			 }
			else if(_this.textPosition=='bottom'){
				t_ani1 = {bottom : -1*t_path};
				t_ani2 = {bottom : 0};
			 }
			 if(_this.opts.textSwitch==1) {
				 _this.$h3.stop(true, false).animate(t_ani1, {duration: 200, easing: 'easeOutQuad'}).animate(t_ani2, {duration: 200, easing: 'easeOutQuad'});
			 }else if(_this.opts.textSwitch==2){
				 _this.$tex.stop(true, false).animate(t_ani1, {duration: 200, easing: 'easeOutQuad'}).animate(t_ani2, {duration: 200, easing: 'easeOutQuad'});
				//_this.$lay.animate(t_ani1, {duration: 200, easing: 'easeOutQuad'}).animate(t_ani2, {duration: 200, easing: 'easeOutQuad'});
			 }
		    }
	    }
	};
        
	// 开始切换
        _this.startSlider = function(index){
            // 由第几个序号开始 初始为1
            var st =setTimeout(function(){
                _this.slideTo(index);
            },_this.opts.time);
	    _this.sliderTimer = st ;
        };
	// 停止切换
        _this.stopSlider = function(){
	    //if(_this.opts.switchEffect=='fadeOut') _this.$lis.stop();
	  //  else if(_this.opts.switchEffect=='ease') _this.$ul.stop();
            if(_this.sliderTimer) {
		clearTimeout(_this.sliderTimer);
	    }		
            _this.sliderTimer = null;
        };

	_this.init();
    };

    $.smallslider.defaults={
            time:3000,              // 切换时间间隔，单位毫秒，1秒=1000毫秒
            autoStart:true,         // 是否自动开始播放
	    onImageStop : false , // 鼠标放在图片上时，是否停止播放
            switchMode:'hover',     // 图片切换的方式，click为单击切换，hover为鼠标移动到按钮上时切换
            switchEffect:'fadeOut', // 切换特效,fadeOut, ease, none,
	    switchPath: 'left' , // 切换的方向，可选值为：up ， left ，即向上，向左
	    switchEase : 'easeOutQuart' , // 可选值列表如下
            switchTime: 600,         // 切换时间，单位毫秒，1秒=1000毫秒
            buttonPosition: 'rightBottom', // 按钮位置表示，共有四个值：leftTop，leftBottom, rightTop, rightBottom
            buttonOffsetX:10,             // 水平方向上的按钮偏移位置，指向中心部移动多少，这里是数值，不加px
            buttonOffsetY:4,              // 竖直方向上的按钮偏移位置，指向中心部移动多少，这里是数值，不加px
            buttonSpace:4,           // 按钮之间的间隔 单位为像素，但不要加px
	    showText: true,          // 是否显示标题，如果不显示，则只显示按钮
	    showButtons : true,	    // 是否显示按钮，默认显示
	    textLink : true,          // 是否给显示的标题加上链接，如果为false，则，只显示标题，标题不可单击，链接的地址自动和当前播放到的图片地址一致
	    textSwitch : 0 ,	// 标题是否运动显示，如果为0则不动，1 标题动，2 标题和背景一起动。
	    textPosition: '',		// 标题栏的位置，默认为空，即和按钮的位置一致，取值 top ,  bottom
	    textAlign: ''		// 如果留空，则会默认和按钮位置的相反方向排列，取值：left, center, right
    };

    $.fn.smallslider = function(options){
	    // 遍历由$.smallslider类创建生成的smallslider对象。
	    return this.each(function(i){
				(new $.smallslider(this, options));
	   });
    };
    
})(jQuery);

$.smallslider.switchEases = ["easeInQuad", "easeOutQuad", "easeInOutQuad", "easeInCubic", "easeOutCubic",
 "easeInOutCubic", "easeInQuart", "easeOutQuart", "easeInOutQuart", "easeInQuint", "easeOutQuint", "easeInOutQuint",
 "easeInSine", "easeOutSine", "easeInOutSine", "easeInExpo", "easeOutExpo", "easeInOutExpo", "easeInCirc", "easeOutCirc", "easeInOutCirc", "easeInElastic",
 "easeOutElastic", "easeInOutElastic", "easeInBack", "easeOutBack", "easeInOutBack",
 "easeInBounce", "easeOutBounce", "easeInOutBounce"];

// t: current time, b: begInnIng value, c: change In value, d: duration
jQuery.easing['jswing'] = jQuery.easing['swing'];

jQuery.extend( jQuery.easing,
{
	def: 'easeOutQuad',
	swing: function (x, t, b, c, d) {
		//alert(jQuery.easing.default);
		return jQuery.easing[jQuery.easing.def](x, t, b, c, d);
	},
	easeInQuad: function (x, t, b, c, d) {
		return c*(t/=d)*t + b;
	},
	easeOutQuad: function (x, t, b, c, d) {
		return -c *(t/=d)*(t-2) + b;
	},
	easeInOutQuad: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t + b;
		return -c/2 * ((--t)*(t-2) - 1) + b;
	},
	easeInCubic: function (x, t, b, c, d) {
		return c*(t/=d)*t*t + b;
	},
	easeOutCubic: function (x, t, b, c, d) {
		return c*((t=t/d-1)*t*t + 1) + b;
	},
	easeInOutCubic: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t + b;
		return c/2*((t-=2)*t*t + 2) + b;
	},
	easeInQuart: function (x, t, b, c, d) {
		return c*(t/=d)*t*t*t + b;
	},
	easeOutQuart: function (x, t, b, c, d) {
		return -c * ((t=t/d-1)*t*t*t - 1) + b;
	},
	easeInOutQuart: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t*t + b;
		return -c/2 * ((t-=2)*t*t*t - 2) + b;
	},
	easeInQuint: function (x, t, b, c, d) {
		return c*(t/=d)*t*t*t*t + b;
	},
	easeOutQuint: function (x, t, b, c, d) {
		return c*((t=t/d-1)*t*t*t*t + 1) + b;
	},
	easeInOutQuint: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b;
		return c/2*((t-=2)*t*t*t*t + 2) + b;
	},
	easeInSine: function (x, t, b, c, d) {
		return -c * Math.cos(t/d * (Math.PI/2)) + c + b;
	},
	easeOutSine: function (x, t, b, c, d) {
		return c * Math.sin(t/d * (Math.PI/2)) + b;
	},
	easeInOutSine: function (x, t, b, c, d) {
		return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b;
	},
	easeInExpo: function (x, t, b, c, d) {
		return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b;
	},
	easeOutExpo: function (x, t, b, c, d) {
		return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
	},
	easeInOutExpo: function (x, t, b, c, d) {
		if (t==0) return b;
		if (t==d) return b+c;
		if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b;
		return c/2 * (-Math.pow(2, -10 * --t) + 2) + b;
	},
	easeInCirc: function (x, t, b, c, d) {
		return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b;
	},
	easeOutCirc: function (x, t, b, c, d) {
		return c * Math.sqrt(1 - (t=t/d-1)*t) + b;
	},
	easeInOutCirc: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b;
		return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b;
	},
	easeInElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;if ((t/=d)==1) return b+c;if (!p) p=d*.3;
		if (a < Math.abs(c)) {a=c;s=p/4;}
		else s = p/(2*Math.PI) * Math.asin (c/a);
		return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
	},
	easeOutElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;if ((t/=d)==1) return b+c;if (!p) p=d*.3;
		if (a < Math.abs(c)) {a=c;s=p/4;}
		else s = p/(2*Math.PI) * Math.asin (c/a);
		return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b;
	},
	easeInOutElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;if ((t/=d/2)==2) return b+c;if (!p) p=d*(.3*1.5);
		if (a < Math.abs(c)) {a=c;s=p/4;}
		else s = p/(2*Math.PI) * Math.asin (c/a);
		if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
		return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b;
	},
	easeInBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158;
		return c*(t/=d)*t*((s+1)*t - s) + b;
	},
	easeOutBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158;
		return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
	},
	easeInOutBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158;
		if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
		return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
	},
	easeInBounce: function (x, t, b, c, d) {
		return c - jQuery.easing.easeOutBounce (x, d-t, 0, c, d) + b;
	},
	easeOutBounce: function (x, t, b, c, d) {
		if ((t/=d) < (1/2.75)) {
			return c*(7.5625*t*t) + b;
		} else if (t < (2/2.75)) {
			return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
		} else if (t < (2.5/2.75)) {
			return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
		} else {
			return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
		}
	},
	easeInOutBounce: function (x, t, b, c, d) {
		if (t < d/2) return jQuery.easing.easeInBounce (x, t*2, 0, c, d) * .5 + b;
		return jQuery.easing.easeOutBounce (x, t*2-d, 0, c, d) * .5 + c*.5 + b;
	}
});

/*
 * 图片放大
 * */
(function($){
	var opts;

	$.fn.lightbox = function(options){
		// build main options
		opts = $.extend({}, $.fn.lightbox.defaults, options);

		// initalize the lightbox
		$.fn.lightbox.initialize();
		return this.each(function(){
			$(this).click(function(){
				$(this).lightbox.start(this);
				return false;
			});
		});
	};

	// lightbox functions
	$.fn.lightbox.initialize = function(){
		$('#overlay').remove();
		$('#lightbox').remove();
		opts.inprogress = false;
		var outerImage = '<div id="outerImageContainer"><div id="imageContainer"><img id="lightboxImage"><div id="hoverNav"><a href="javascript://" title="' + opts.strings.prevLinkTitle + '" id="prevLink"></a><a href="javascript://" id="nextLink" title="' + opts.strings.nextLinkTitle + '"></a></div><div id="loading"><a href="javascript://" id="loadingLink"><img src="'+opts.fileLoadingImage+'"></a></div></div></div>';
		var imageData = '<div id="imageDataContainer" class="clearfix"><div id="imageData"><div id="imageDetails"><span id="caption"></span><span id="numberDisplay"></span></div><div id="bottomNav">'

		if (opts.displayHelp)
			imageData += '<span id="helpDisplay">' + opts.strings.help + '</span>';

		imageData += '<a href="javascript://" id="bottomNavClose" title="' + opts.strings.closeTitle + '"><img src="'+opts.fileBottomNavCloseImage+'"></a></div></div></div>';

		var string;

		if (opts.navbarOnTop) {
		  string = '<div id="overlay"></div><div id="lightbox">' + imageData + outerImage + '</div>';
		  $("body").append(string);
		  $("#imageDataContainer").addClass('ontop');
		} else {
		  string = '<div id="overlay"></div><div id="lightbox">' + outerImage + imageData + '</div>';
		  $("body").append(string);
		}

		$("#overlay").click(function(){ $.fn.lightbox.end(); }).hide();
		$("#lightbox").click(function(){ $.fn.lightbox.end();}).hide();
		$("#loadingLink").click(function(){ $.fn.lightbox.end(); return false;});
		$("#bottomNavClose").click(function(){ $.fn.lightbox.end(); return false; });
		$('#outerImageContainer').width(opts.widthCurrent).height(opts.heightCurrent);
		$('#imageDataContainer').width(opts.widthCurrent);
	};

	$.fn.lightbox.getPageSize = function(){
		var xScroll, yScroll;

		if (window.innerHeight && window.scrollMaxY) {
			xScroll = window.innerWidth + window.scrollMaxX;
			yScroll = window.innerHeight + window.scrollMaxY;
		} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
			xScroll = document.body.scrollWidth;
			yScroll = document.body.scrollHeight;
		} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
			xScroll = document.body.offsetWidth;
			yScroll = document.body.offsetHeight;
		}

		var windowWidth, windowHeight;

		if (self.innerHeight) { // all except Explorer
			if(document.documentElement.clientWidth){
				windowWidth = document.documentElement.clientWidth;
			} else {
				windowWidth = self.innerWidth;
			}
			windowHeight = self.innerHeight;
		} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
			windowWidth = document.documentElement.clientWidth;
			windowHeight = document.documentElement.clientHeight;
		} else if (document.body) { // other Explorers
			windowWidth = document.body.clientWidth;
			windowHeight = document.body.clientHeight;
		}

		// for small pages with total height less then height of the viewport
		if(yScroll < windowHeight){
			pageHeight = windowHeight;
		} else {
			pageHeight = yScroll;
		}


		// for small pages with total width less then width of the viewport
		if(xScroll < windowWidth){
			pageWidth = xScroll;
		} else {
			pageWidth = windowWidth;
		}

		var arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight);
		return arrayPageSize;
	};

	$.fn.lightbox.getPageScroll = function(){
		var xScroll, yScroll;

		if (self.pageYOffset) {
			yScroll = self.pageYOffset;
			xScroll = self.pageXOffset;
		} else if (document.documentElement && document.documentElement.scrollTop){  // Explorer 6 Strict
			yScroll = document.documentElement.scrollTop;
			xScroll = document.documentElement.scrollLeft;
		} else if (document.body) {// all other Explorers
			yScroll = document.body.scrollTop;
			xScroll = document.body.scrollLeft;
		}

		var arrayPageScroll = new Array(xScroll,yScroll);
		return arrayPageScroll;
	};

	$.fn.lightbox.pause = function(ms){
		var date = new Date();
		var curDate = null;
		do{curDate = new Date();}
		while( curDate - date < ms);
	};

	$.fn.lightbox.start = function(imageLink){

		$("select, embed, object").hide();
		var arrayPageSize = $.fn.lightbox.getPageSize();
		$("#overlay").hide().css({width: '100%', height: arrayPageSize[1]+'px', opacity : opts.overlayOpacity}).fadeIn();
		opts.imageArray = [];
		imageNum = 0;

		var anchors = document.getElementsByTagName( imageLink.tagName);

		// if image is NOT part of a set..
		if(!imageLink.rel || (imageLink.rel == '')){
			// add single image to Lightbox.imageArray
			opts.imageArray.push(new Array(imageLink.href, opts.displayTitle ? imageLink.title : ''));
		} else {
		// if image is part of a set..
			$("a").each(function(){
				if(this.href && (this.rel == imageLink.rel)){
					opts.imageArray.push(new Array(this.href, opts.displayTitle ? this.title : ''));
				}
			})


			for(i = 0; i < opts.imageArray.length; i++){
				for(j = opts.imageArray.length-1; j>i; j--){
					if(opts.imageArray[i][0] == opts.imageArray[j][0]){
						opts.imageArray.splice(j,1);
					}
				}
			}
			while(opts.imageArray[imageNum][0] != imageLink.href) { imageNum++;}
		}

		// calculate top and left offset for the lightbox
		var arrayPageScroll = $.fn.lightbox.getPageScroll();
		var lightboxTop = arrayPageScroll[1] + (arrayPageSize[3] / 10);
		var lightboxLeft = arrayPageScroll[0];
		$('#lightbox').css({top: lightboxTop+'px', left: lightboxLeft+'px'}).show();


		if (!opts.slideNavBar)
			$('#imageData').hide();

		$.fn.lightbox.changeImage(imageNum);

	};

	$.fn.lightbox.changeImage = function(imageNum){
		if(opts.inprogress == false){
			opts.inprogress = true;
			opts.activeImage = imageNum;	// update global var

			// hide elements during transition
			$('#loading').show();
			$('#lightboxImage').hide();
			$('#hoverNav').hide();
			$('#prevLink').hide();
			$('#nextLink').hide();

			if (opts.slideNavBar) { // delay preloading image until navbar will slide up
				// $('#imageDataContainer').slideUp(opts.navBarSlideSpeed, $.fn.doChangeImage);
				$('#imageDataContainer').hide();
				$('#imageData').hide();
				$.fn.doChangeImage();
			} else {
			    $.fn.doChangeImage();
			}
		}
	};

	$.fn.doChangeImage = function(){

		imgPreloader = new Image();

		// once image is preloaded, resize image container
		imgPreloader.onload=function(){
		    var newWidth = imgPreloader.width;
		    var newHeight = imgPreloader.height;


			if (opts.fitToScreen) {
		        var arrayPageSize = $.fn.lightbox.getPageSize();
				var ratio;
				var initialPageWidth = arrayPageSize[2] - 2 * opts.borderSize;
				var initialPageHeight = arrayPageSize[3] - 200;

				if (imgPreloader.height > initialPageHeight)
				{
					newWidth = parseInt((initialPageHeight/imgPreloader.height) * imgPreloader.width);
					newHeight = initialPageHeight;
				}
				else if (imgPreloader.width > initialPageWidth)
				{
					newHeight = parseInt((initialPageWidth/imgPreloader.width) * imgPreloader.height);
					newWidth = initialPageWidth;
				}
			}

			$('#lightboxImage').attr('src', opts.imageArray[opts.activeImage][0])
							   .width(newWidth).height(newHeight);
			$.fn.lightbox.resizeImageContainer(newWidth, newHeight);
		}

		imgPreloader.src = opts.imageArray[opts.activeImage][0];
	}
	
	$.fn.lightbox.end = function(){
		$.fn.lightbox.disableKeyboardNav();
		$('#lightbox').hide();
		$('#overlay').fadeOut();
		$('select, object, embed').show();
	};

	$.fn.lightbox.preloadNeighborImages = function(){
		if((opts.imageArray.length - 1) > opts.activeImage){
			preloadNextImage = new Image();
			preloadNextImage.src = opts.imageArray[opts.activeImage + 1][0];
		}
		if(opts.activeImage > 0){
			preloadPrevImage = new Image();
			preloadPrevImage.src = opts.imageArray[opts.activeImage - 1][0];
		}
	};

	$.fn.lightbox.keyboardAction = function(e){
		if (e == null) { // ie
			var keycode = event.keyCode;
			var escapeKey = 27;
		} else { // mozilla
			var keycode = e.keyCode;
			var escapeKey = e.DOM_VK_ESCAPE;
		}

		var key = String.fromCharCode(keycode).toLowerCase();

		if((key == 'x') || (key == 'o') || (key == 'c') || (keycode == escapeKey)){ // close lightbox
			$.fn.lightbox.end();
		} else if((key == 'p') || (keycode == 37)){ // display previous image
			if(opts.activeImage != 0){
				$.fn.lightbox.disableKeyboardNav();
				$.fn.lightbox.changeImage(opts.activeImage - 1);
			}
		} else if((key == 'n') || (keycode == 39)){ // display next image
			if(opts.activeImage != (opts.imageArray.length - 1)){
				$.fn.lightbox.disableKeyboardNav();
				$.fn.lightbox.changeImage(opts.activeImage + 1);
			}
		}
	};

	$.fn.lightbox.resizeImageContainer = function(imgWidth, imgHeight){
		// get current width and height
		opts.widthCurrent = document.getElementById('outerImageContainer').offsetWidth;
		opts.heightCurrent = document.getElementById('outerImageContainer').offsetHeight;

		// get new width and height
		var widthNew = (imgWidth  + (opts.borderSize * 2));
		var heightNew = (imgHeight  + (opts.borderSize * 2));

		// scalars based on change from old to new
		opts.xScale = ( widthNew / opts.widthCurrent) * 100;
		opts.yScale = ( heightNew / opts.heightCurrent) * 100;

		// calculate size difference between new and old image, and resize if necessary
		wDiff = opts.widthCurrent - widthNew;
		hDiff = opts.heightCurrent - heightNew;

		$('#imageDataContainer').animate({width: widthNew},opts.resizeSpeed,'linear');
		$('#outerImageContainer').animate({width: widthNew},opts.resizeSpeed,'linear',function(){
			$('#outerImageContainer').animate({height: heightNew},opts.resizeSpeed,'linear',function(){
				$.fn.lightbox.showImage();
			});
		});


		// if new and old image are same size and no scaling transition is necessary,
		// do a quick pause to prevent image flicker.
		if((hDiff == 0) && (wDiff == 0)){
			if (jQuery.browser.msie){ $.fn.lightbox.pause(250); } else { $.fn.lightbox.pause(100);}
		}

		$('#prevLink').height(imgHeight);
		$('#nextLink').height(imgHeight);
	};

	$.fn.lightbox.showImage = function(){
		$('#loading').hide();
		$('#lightboxImage').fadeIn("fast");
		$.fn.lightbox.updateDetails();
		$.fn.lightbox.preloadNeighborImages();

		opts.inprogress = false;
	};

	$.fn.lightbox.updateDetails = function(){

		if(opts.imageArray[opts.activeImage][1]){
			$('#caption').html(opts.imageArray[opts.activeImage][1]).show();
		}

		// if image is part of set display 'Image x of x'
		if(opts.imageArray.length > 1){
			var nav_html;

			nav_html = opts.strings.image + (opts.activeImage + 1) + opts.strings.of + opts.imageArray.length;

			// display previous / next text links
			if ((opts.activeImage) > 0) {
				nav_html = '<a title="' + opts.strings.prevLinkTitle + '" href="#" id="prevLinkText">' + opts.strings.prevLinkText + "</a>" + nav_html;
			}

			if ((opts.activeImage + 1) < opts.imageArray.length) {
				nav_html += '<a title="' + opts.strings.nextLinkTitle + '" href="#" id="nextLinkText">' + opts.strings.nextLinkText + "</a>";
			}

			$('#numberDisplay').html(nav_html).show();
		}

		if (opts.slideNavBar) {
		    $("#imageData").slideDown(opts.navBarSlideSpeed);
		} else {
			$("#imageData").show();
		}

		var arrayPageSize = $.fn.lightbox.getPageSize();
		$('#overlay').height(arrayPageSize[1]);
		$.fn.lightbox.updateNav();
	};

	$.fn.lightbox.updateNav = function(){
		$('#hoverNav').show();

		// if not first image in set, display prev image button
		if(opts.activeImage != 0){
			$('#prevLink,#prevLinkText').show().click(function(){
				$.fn.lightbox.changeImage(opts.activeImage - 1); return false;
			});
		}

		// if not last image in set, display next image button
		if(opts.activeImage != (opts.imageArray.length - 1)){
			$('#nextLink,#nextLinkText').show().click(function(){

				$.fn.lightbox.changeImage(opts.activeImage +1); return false;
			});
		}

		$.fn.lightbox.enableKeyboardNav();
	};


	$.fn.lightbox.enableKeyboardNav = function(){
		document.onkeydown = $.fn.lightbox.keyboardAction;
	};

	$.fn.lightbox.disableKeyboardNav = function(){
		document.onkeydown = '';
	};

	$.fn.lightbox.defaults = {
		fileLoadingImage : 'static/image/lightbox/loading.gif',
		fileBottomNavCloseImage : 'static/image/lightbox/closelabel.gif',
		overlayOpacity : 0.8,
		borderSize : 10,
		imageArray : new Array,
		activeImage : null,
		inprogress : false,
		resizeSpeed : 350,
		widthCurrent: 250,
		heightCurrent: 250,
		xScale : 1,
		yScale : 1,
		displayTitle: true,
		navbarOnTop: false,
		slideNavBar: false, // slide nav bar up/down between image resizing transitions
		navBarSlideSpeed: 350,
		displayHelp: false,
		strings : {
			help: ' \u2190 / P - previous image\u00a0\u00a0\u00a0\u00a0\u2192 / N - next image\u00a0\u00a0\u00a0\u00a0ESC / X - close image gallery',
			prevLinkTitle:	'previous image',
			nextLinkTitle:	'next image',
			prevLinkText:	'&laquo; Previous',
			nextLinkText:	'Next &raquo;',
			closeTitle: 	'close image gallery',
			image:			'Image ',
			of:				'of '
		},
		fitToScreen: false		// resize images if they are bigger than window
	};
})(jQuery);

/*
 * AJAX提交
 * */
(function($) {
	$.fn.ajaxSubmit = function(options) {
	    if (!this.length) {
	        log('ajaxSubmit: skipping submit process - no element selected');
	        return this;
	    }
	    if (typeof options == 'function')
	        options = { success: options };
	    options = $.extend({
	        url:  this.attr('action') || window.location.toString(),
	        type: this.attr('method') || 'GET'
	    }, options || {});
	    var veto = {};
	    this.trigger('form-pre-serialize', [this, options, veto]);
	    if (veto.veto) {
	        log('ajaxSubmit: submit vetoed via form-pre-serialize trigger');
	        return this;
	    }
	    if (options.beforeSerialize && options.beforeSerialize(this, options) === false) {
	        log('ajaxSubmit: submit aborted via beforeSerialize callback');
	        return this;
	    }    
	   
	    var a = this.formToArray(options.semantic);
	    if (options.data) {
	        options.extraData = options.data;
	        for (var n in options.data) {
	          if(options.data[n] instanceof Array) {
	            for (var k in options.data[n])
	              a.push( { name: n, value: options.data[n][k] } )
	          }  
	          else
	             a.push( { name: n, value: options.data[n] } );
	        }
	    }
	    if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) {
	        log('ajaxSubmit: submit aborted via beforeSubmit callback');
	        return this;
	    }    
	    this.trigger('form-submit-validate', [a, this, options, veto]);
	    if (veto.veto) {
	        log('ajaxSubmit: submit vetoed via form-submit-validate trigger');
	        return this;
	    }    
	    var q = $.param(a);
	
	    if (options.type.toUpperCase() == 'GET') {
	        options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q;
	        options.data = null;  // data is null for 'get'
	    }
	    else
	        options.data = q; // data is the query string for 'post'
	
	    var $form = this, callbacks = [];
	    if (options.resetForm) callbacks.push(function() { $form.resetForm(); });
	    if (options.clearForm) callbacks.push(function() { $form.clearForm(); });
	    if (!options.dataType && options.target) {
	        var oldSuccess = options.success || function(){};
	        callbacks.push(function(data) {
	            $(options.target).html(data).each(oldSuccess, arguments);
	        });
	    }
	    else if (options.success)
	        callbacks.push(options.success);
	
	    options.success = function(data, status) {
	        for (var i=0, max=callbacks.length; i < max; i++)
	            callbacks[i].apply(options, [data, status, $form]);
	    };
	    var files = $('input:file', this).fieldValue();
	    var found = false;
	    for (var j=0; j < files.length; j++)
	        if (files[j])
	            found = true;
	   if (options.iframe || found) { 
	       if ($.browser.safari && options.closeKeepAlive)
	           $.get(options.closeKeepAlive, fileUpload);
	       else
	           fileUpload();
	       }
	   else
	       $.ajax(options);
	    this.trigger('form-submit-notify', [this, options]);
	    return this;
	    function fileUpload() {
	        var form = $form[0];
	        if ($(':input[name=submit]', form).length) {
	            alert('Error: Form elements must not be named "submit".');
	            return;
	        }
	        var opts = $.extend({}, $.ajaxSettings, options);
			var s = jQuery.extend(true, {}, $.extend(true, {}, $.ajaxSettings), opts);
	        var id = 'jqFormIO' + (new Date().getTime());
	        var $io = $('<iframe id="' + id + '" name="' + id + '" />');
	        var io = $io[0];
	        if ($.browser.msie || $.browser.opera) 
	            io.src = 'javascript:false;document.write("");';
	        $io.css({ position: 'absolute', top: '-1000px', left: '-1000px' });
	        var xhr = { // mock object
	            aborted: 0,
	            responseText: null,
	            responseXML: null,
	            status: 0,
	            statusText: 'n/a',
	            getAllResponseHeaders: function() {},
	            getResponseHeader: function() {},
	            setRequestHeader: function() {},
	            abort: function() { 
	                this.aborted = 1; 
	                $io.attr('src','about:blank'); // abort op in progress
	            }
	        };
	        var g = opts.global;
	        if (g && ! $.active++) $.event.trigger("ajaxStart");
	        if (g) $.event.trigger("ajaxSend", [xhr, opts]);
			if (s.beforeSend && s.beforeSend(xhr, s) === false) {
				s.global && jQuery.active--;
				return;
	        }
	        if (xhr.aborted)
	            return;
	        var cbInvoked = 0;
	        var timedOut = 0;
	        var sub = form.clk;
	        if (sub) {
	            var n = sub.name;
	            if (n && !sub.disabled) {
	                options.extraData = options.extraData || {};
	                options.extraData[n] = sub.value;
	                if (sub.type == "image") {
	                    options.extraData[name+'.x'] = form.clk_x;
	                    options.extraData[name+'.y'] = form.clk_y;
	                }
	            }
	        }
	        setTimeout(function() {
	            var t = $form.attr('target'), a = $form.attr('action');
	            $form.attr({
	                target:   id,
	                method:   'POST',
	                action:   opts.url
	            });
	            if (! options.skipEncodingOverride) {
	                $form.attr({
	                    encoding: 'multipart/form-data',
	                    enctype:  'multipart/form-data'
	                });
	            }
	            if (opts.timeout)
	                setTimeout(function() { timedOut = true; cb(); }, opts.timeout);
	            var extraInputs = [];
	            try {
	                if (options.extraData)
	                    for (var n in options.extraData)
	                        extraInputs.push(
	                            $('<input type="hidden" name="'+n+'" value="'+options.extraData[n]+'" />')
	                                .appendTo(form)[0]);
	            
	                $io.appendTo('body');
	                io.attachEvent ? io.attachEvent('onload', cb) : io.addEventListener('load', cb, false);
	                form.submit();
	            }
	            finally {
	                $form.attr('action', a);
	                t ? $form.attr('target', t) : $form.removeAttr('target');
	                $(extraInputs).remove();
	            }
	        }, 10);
	        function cb() {
	            if (cbInvoked++) return;
	            io.detachEvent ? io.detachEvent('onload', cb) : io.removeEventListener('load', cb, false);
	            var operaHack = 0;
	            var ok = true;
	            try {
	                if (timedOut) throw 'timeout';
	                var data, doc;
	                doc = io.contentWindow ? io.contentWindow.document : io.contentDocument ? io.contentDocument : io.document;
	                if (doc.body == null && !operaHack && $.browser.opera) {
	                    operaHack = 1;
	                    cbInvoked--;
	                    setTimeout(cb, 100);
	                    return;
	                }
	                xhr.responseText = doc.body ? doc.body.innerHTML : null;
	                xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc;
	                xhr.getResponseHeader = function(header){
	                    var headers = {'content-type': opts.dataType};
	                    return headers[header];
	                };
	                if (opts.dataType == 'json' || opts.dataType == 'script') {
	                    var ta = doc.getElementsByTagName('textarea')[0];
	                    xhr.responseText = ta ? ta.value : xhr.responseText;
	                }
	                else if (opts.dataType == 'xml' && !xhr.responseXML && xhr.responseText != null) {
	                    xhr.responseXML = toXml(xhr.responseText);
	                }
	                data = $.httpData(xhr, opts.dataType);
	            }
	            catch(e){
	                ok = false;
	                $.handleError(opts, xhr, 'error', e);
	            }
	            if (ok) {
	                opts.success(data, 'success');
	                if (g) $.event.trigger("ajaxSuccess", [xhr, opts]);
	            }
	            if (g) $.event.trigger("ajaxComplete", [xhr, opts]);
	            if (g && ! --$.active) $.event.trigger("ajaxStop");
	            if (opts.complete) opts.complete(xhr, ok ? 'success' : 'error');
	            setTimeout(function() {
	                $io.remove();
	                xhr.responseXML = null;
	            }, 100);
	        };
	        function toXml(s, doc) {
	            if (window.ActiveXObject) {
	                doc = new ActiveXObject('Microsoft.XMLDOM');
	                doc.async = 'false';
	                doc.loadXML(s);
	            }
	            else
	                doc = (new DOMParser()).parseFromString(s, 'text/xml');
	            return (doc && doc.documentElement && doc.documentElement.tagName != 'parsererror') ? doc : null;
	        };
	    };
	};
	$.fn.ajaxForm = function(options) {
	    return this.ajaxFormUnbind().bind('submit.form-plugin',function() {
	        $(this).ajaxSubmit(options);
	        return false;
	    }).each(function() {
	        // store options in hash
	        $(":submit,input:image", this).bind('click.form-plugin',function(e) {
	            var form = this.form;
	            form.clk = this;
	            if (this.type == 'image') {
	                if (e.offsetX != undefined) {
	                    form.clk_x = e.offsetX;
	                    form.clk_y = e.offsetY;
	                } else if (typeof $.fn.offset == 'function') { // try to use dimensions plugin
	                    var offset = $(this).offset();
	                    form.clk_x = e.pageX - offset.left;
	                    form.clk_y = e.pageY - offset.top;
	                } else {
	                    form.clk_x = e.pageX - this.offsetLeft;
	                    form.clk_y = e.pageY - this.offsetTop;
	                }
	            }
	            // clear form vars
	            setTimeout(function() { form.clk = form.clk_x = form.clk_y = null; }, 10);
	        });
	    });
	};
	// ajaxFormUnbind unbinds the event handlers that were bound by ajaxForm
	$.fn.ajaxFormUnbind = function() {
	    this.unbind('submit.form-plugin');
	    return this.each(function() {
	        $(":submit,input:image", this).unbind('click.form-plugin');
	    });
	
	};
	$.fn.formToArray = function(semantic) {
	    var a = [];
	    if (this.length == 0) return a;
	
	    var form = this[0];
	    var els = semantic ? form.getElementsByTagName('*') : form.elements;
	    if (!els) return a;
	    for(var i=0, max=els.length; i < max; i++) {
	        var el = els[i];
	        var n = el.name;
	        if (!n) continue;
	
	        if (semantic && form.clk && el.type == "image") {
	            // handle image inputs on the fly when semantic == true
	            if(!el.disabled && form.clk == el)
	                a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
	            continue;
	        }
	
	        var v = $.fieldValue(el, true);
	        if (v && v.constructor == Array) {
	            for(var j=0, jmax=v.length; j < jmax; j++)
	                a.push({name: n, value: v[j]});
	        }
	        else if (v !== null && typeof v != 'undefined')
	            a.push({name: n, value: v});
	    }
	
	    if (!semantic && form.clk) {
	        // input type=='image' are not found in elements array! handle them here
	        var inputs = form.getElementsByTagName("input");
	        for(var i=0, max=inputs.length; i < max; i++) {
	            var input = inputs[i];
	            var n = input.name;
	            if(n && !input.disabled && input.type == "image" && form.clk == input)
	                a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
	        }
	    }
	    return a;
	};
	$.fn.formSerialize = function(semantic) {
	    //hand off to jQuery.param for proper encoding
	    return $.param(this.formToArray(semantic));
	};
	$.fn.fieldSerialize = function(successful) {
	    var a = [];
	    this.each(function() {
	        var n = this.name;
	        if (!n) return;
	        var v = $.fieldValue(this, successful);
	        if (v && v.constructor == Array) {
	            for (var i=0,max=v.length; i < max; i++)
	                a.push({name: n, value: v[i]});
	        }
	        else if (v !== null && typeof v != 'undefined')
	            a.push({name: this.name, value: v});
	    });
	    //hand off to jQuery.param for proper encoding
	    return $.param(a);
	};
	$.fn.fieldValue = function(successful) {
	    for (var val=[], i=0, max=this.length; i < max; i++) {
	        var el = this[i];
	        var v = $.fieldValue(el, successful);
	        if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length))
	            continue;
	        v.constructor == Array ? $.merge(val, v) : val.push(v);
	    }
	    return val;
	};
	$.fieldValue = function(el, successful) {
	    var n = el.name, t = el.type, tag = el.tagName.toLowerCase();
	    if (typeof successful == 'undefined') successful = true;
	
	    if (successful && (!n || el.disabled || t == 'reset' || t == 'button' ||
	        (t == 'checkbox' || t == 'radio') && !el.checked ||
	        (t == 'submit' || t == 'image') && el.form && el.form.clk != el ||
	        tag == 'select' && el.selectedIndex == -1))
	            return null;
	
	    if (tag == 'select') {
	        var index = el.selectedIndex;
	        if (index < 0) return null;
	        var a = [], ops = el.options;
	        var one = (t == 'select-one');
	        var max = (one ? index+1 : ops.length);
	        for(var i=(one ? index : 0); i < max; i++) {
	            var op = ops[i];
	            if (op.selected) {
	                // extra pain for IE...
	                var v = $.browser.msie && !(op.attributes['value'].specified) ? op.text : op.value;
	                if (one) return v;
	                a.push(v);
	            }
	        }
	        return a;
	    }
	    return el.value;
	};
	$.fn.clearForm = function() {
	    return this.each(function() {
	        $('input,select,textarea', this).clearFields();
	    });
	};
	$.fn.clearFields = $.fn.clearInputs = function() {
	    return this.each(function() {
	        var t = this.type, tag = this.tagName.toLowerCase();
	        if (t == 'text' || t == 'password' || tag == 'textarea')
	            this.value = '';
	        else if (t == 'checkbox' || t == 'radio')
	            this.checked = false;
	        else if (tag == 'select')
	            this.selectedIndex = -1;
	    });
	};
	$.fn.resetForm = function() {
	    return this.each(function() {
	        // guard against an input with the name of 'reset'
	        // note that IE reports the reset function as an 'object'
	        if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType))
	            this.reset();
	    });
	};
	$.fn.enable = function(b) { 
	    if (b == undefined) b = true;
	    return this.each(function() { 
	        this.disabled = !b 
	    });
	};
	$.fn.selected = function(select) {
	    if (select == undefined) select = true;
	    return this.each(function() { 
	        var t = this.type;
	        if (t == 'checkbox' || t == 'radio')
	            this.checked = select;
	        else if (this.tagName.toLowerCase() == 'option') {
	            var $sel = $(this).parent('select');
	            if (select && $sel[0] && $sel[0].type == 'select-one') {
	                // deselect all other options
	                $sel.find('option').selected(false);
	            }
	            this.selected = select;
	        }
	    });
	};
	function log() {
	    if ($.fn.ajaxSubmit.debug && window.console && window.console.log)
	        window.console.log('[jquery.form] ' + Array.prototype.join.call(arguments,''));
	};
})(jQuery);

/*
 * 导航下拉菜单api
 * */
var ddsmoothmenu={
	transition: {overtime:200, outtime:200}, //duration of slide in/ out animation, in milliseconds
	//下拉菜单阴影
	shadow: {enable:false, offsetx:0, offsety:0},
	detectwebkit: navigator.userAgent.toLowerCase().indexOf("applewebkit")!=-1, //detect WebKit browsers (Safari, Chrome etc)
	detectie6: document.all && !window.XMLHttpRequest,
	getajaxmenu:function($, setting){ //function to fetch external page containing the panel DIVs
		var $menucontainer=$('#'+setting.contentsource[0]) //reference empty div on page that will hold menu
		$menucontainer.html("Loading Menu...")
		$.ajax({
			url: setting.contentsource[1], //path to external menu file
			async: true,
			error:function(ajaxrequest){
				$menucontainer.html('Error fetching content. Server Response: '+ajaxrequest.responseText)
			},
			success:function(content){
				$menucontainer.html(content)
				ddsmoothmenu.buildmenu($, setting)
			}
		})
	},
	buildmenu:function($, setting){
		var smoothmenu=ddsmoothmenu
		var $mainmenu=$("#"+setting.mainmenuid+">ul") //reference main menu UL
		$mainmenu.parent().get(0).className=setting.classname || "ddsmoothmenu"
		var $headers=$mainmenu.find("ul").parent()
		$headers.hover(
			function(e){
				$(this).children('a:eq(0)').addClass('selected')
			},
			function(e){
				$(this).children('a:eq(0)').removeClass('selected')
			}
		)
		$headers.each(function(i){ //loop through each LI header
			var $curobj=$(this).css({zIndex: 100-i}) //reference current LI header
			var $subul=$(this).find('ul:eq(0)').css({display:'block'})
			this._dimensions={w:this.offsetWidth, h:this.offsetHeight, subulw:$subul.outerWidth(), subulh:$subul.outerHeight()}
			this.istopheader=$curobj.parents("ul").length==1? true : false //is top level header?
			$subul.css({top:this.istopheader && setting.orientation!='v'? this._dimensions.h+"px" : 0})
	//		$curobj.children("a:eq(0)").css(this.istopheader? {paddingRight: smoothmenu.arrowimages.down[2]} : {}).append( //add arrow images
	//			'<img src="'+ (this.istopheader && setting.orientation!='v'? smoothmenu.arrowimages.down[1] : smoothmenu.arrowimages.right[1])
	//			+'" class="' + (this.istopheader && setting.orientation!='v'? smoothmenu.arrowimages.down[0] : smoothmenu.arrowimages.right[0])
	//			+ '" style="border:0;" />'
	//		)
			if (smoothmenu.shadow.enable){
				this._shadowoffset={x:(this.istopheader?$subul.offset().left+smoothmenu.shadow.offsetx : this._dimensions.w), y:(this.istopheader? $subul.offset().top+smoothmenu.shadow.offsety : $curobj.position().top)} //store this shadow's offsets
				if (this.istopheader)
					$parentshadow=$(document.body)
				else{
					var $parentLi=$curobj.parents("li:eq(0)")
					$parentshadow=$parentLi.get(0).$shadow
				}
				this.$shadow=$('<div class="ddshadow'+(this.istopheader? ' toplevelshadow' : '')+'"></div>').prependTo($parentshadow).css({left:this._shadowoffset.x+'px', top:this._shadowoffset.y+'px'})  //insert shadow DIV and set it to parent node for the next shadow div
			}
			$curobj.hover(
				function(e){
					var $targetul=$(this).children("ul:eq(0)")
					this._offsets={left:$(this).offset().left, top:$(this).offset().top}
					var menuleft=this.istopheader && setting.orientation!='v'? 0 : this._dimensions.w
					menuleft=(this._offsets.left+menuleft+this._dimensions.subulw>$(window).width())? (this.istopheader && setting.orientation!='v'? -this._dimensions.subulw+this._dimensions.w : -this._dimensions.w) : menuleft //calculate this sub menu's offsets from its parent
					if ($targetul.queue().length<=1){ //if 1 or less queued animations
						$targetul.css({left:menuleft+"px", width:this._dimensions.subulw+'px'}).animate({height:'show',opacity:'show'}, ddsmoothmenu.transition.overtime)
						if (smoothmenu.shadow.enable){
							var shadowleft=this.istopheader? $targetul.offset().left+ddsmoothmenu.shadow.offsetx : menuleft
							var shadowtop=this.istopheader?$targetul.offset().top+smoothmenu.shadow.offsety : this._shadowoffset.y
							if (!this.istopheader && ddsmoothmenu.detectwebkit){ //in WebKit browsers, restore shadow's opacity to full
								this.$shadow.css({opacity:1})
							}
							this.$shadow.css({overflow:'', width:this._dimensions.subulw+'px', left:shadowleft+'px', top:shadowtop+'px'}).animate({height:this._dimensions.subulh+'px'}, ddsmoothmenu.transition.overtime)
						}
					}
				},
				function(e){
					var $targetul=$(this).children("ul:eq(0)")
					$targetul.animate({height:'hide', opacity:'hide'}, ddsmoothmenu.transition.outtime)
					if (smoothmenu.shadow.enable){
						if (ddsmoothmenu.detectwebkit){ //in WebKit browsers, set first child shadow's opacity to 0, as "overflow:hidden" doesn't work in them
							this.$shadow.children('div:eq(0)').css({opacity:0})
						}
						this.$shadow.css({overflow:'hidden'}).animate({height:0}, ddsmoothmenu.transition.outtime)
					}
				}
			) //end hover
		}) //end $headers.each()
		$mainmenu.find("ul").css({display:'none', visibility:'visible'})
	},
	init:function(setting){
		if (typeof setting.customtheme=="object" && setting.customtheme.length==2){ //override default menu colors (default/hover) with custom set?
			var mainmenuid='#'+setting.mainmenuid
			var mainselector=(setting.orientation=="v")? mainmenuid : mainmenuid+', '+mainmenuid
			document.write('<style type="text/css">\n'
				+mainselector+' ul li a {background:'+setting.customtheme[0]+';}\n'
				+mainmenuid+' ul li a:hover {background:'+setting.customtheme[1]+';}\n'
			+'</style>')
		}
		this.shadow.enable=(document.all && !window.XMLHttpRequest)? false : this.shadow.enable //in IE6, always disable shadow
		jQuery(document).ready(function($){ //ajax menu?
			if (typeof setting.contentsource=="object"){ //if external ajax menu
				ddsmoothmenu.getajaxmenu($, setting)
			}
			else{ //else if markup menu
				ddsmoothmenu.buildmenu($, setting)
			}
		})
	}
} //end ddsmoothmenu variable

