/*==============================================
 ready
==============================================*/
$(function(){

var ie = (function(){var undef,v=3,div=document.createElement('div'),all=div.getElementsByTagName('i');while(div.innerHTML='<!--[if gt IE '+(++v)+']><i></i><![endif]-->',all[0]);return v>4 ? v:undef;}());

/*----------------------------------------------
 body class switch
----------------------------------------------*/
$.bodyClassSwitch = function(option){
	var saved_class, current_class;
	option = $.extend({
		trigger : '.class_switcher',
		path    : '/',
		expires : 365,
		defname : ''
	}, option);

	function _setClass(classname){
		if(!classname) return;
		current_class = $('body').data('current_class') || '';
		$.cookie('body_class',classname,{expires:option.expires, path:option.path});
		$('body').data('current_class',classname).removeClass(current_class).addClass(classname);
	}

	function init(){
		saved_class = $.cookie('body_class') || option.defname;
		_setClass(saved_class);
		$(option.trigger).click(function(){
			_setClass($(this).attr('class'));
			return false;
		});
	}

	init();
};

/*----------------------------------------------
 scroll to top
----------------------------------------------*/
$.scrollToTop = function(option){
	option = $.extend({
		target  : "a[href*='top']",
		x       : 0,
		y       : 0
	}, option);

	function init(){
		$(option.target).click(function(){
			window.scrollTo(option.x, option.y);
			return false;
		});
	}

	init();
};

/*----------------------------------------------
 external link
----------------------------------------------*/
$.externalLink = function(option){
	option = $.extend({
		target : "a.external,a[rel='external']"
	}, option);

	function init(){
		$(option.target).click(function(){
			window.open(this.href,'');
			return false;
		});
	}

	init();
};

/*----------------------------------------------
 image roll over
----------------------------------------------*/
$.imageRollOver = function(option){
	var obj = obj || {};
	option = $.extend({
		target  : 'img.swap, input.swap',
		suffix  : '_on',
		exclude : '_current'
	}, option);

	function init(){
		$(option.target)
		.not("[src*='" + option.suffix + ".']")
		.not("[src*='" + option.exclude + ".']")
		.each(function(){
			var src  = this.src;
			var osrc = src.replace(new RegExp('('+option.suffix+')?(\.gif|\.jpg|\.png)$'),option.suffix+"$2");
			obj[src] = new Image();
			obj[src+'_d'] = new Image();
			obj[src].src = osrc;
			obj[src+'_d'].src = src;
			$(this).hover(function(){
				this.src = obj[src].src;
			},function(){
				this.src = obj[src+"_d"].src;
			});
		});
	}

	init();
};

/*----------------------------------------------
 set current
----------------------------------------------*/
$.setCurrent = function(option){
	var pathname;
	option = $.extend({
		dirlevel  : 0,
		classname : 'current',
		imageswap : false,
		suffix    : '_on'
	}, option);

	function _pathToDir(path,lv){
		var ary  = path.replace(new RegExp('/?(index\..{2,4})?$'),'').split('/'),
		    dir  = (lv > 0) ? ary.splice(0, lv+1).join('/') : ary.join('/');
		return dir;
	};

	function init(){
		pathname = _pathToDir(location.pathname, option.dirlevel);
		$(option.target).each(function(){
			var $self = $(this);
			var href = _pathToDir($self.attr('href'), option.dirlevel);
			if(href === pathname){
				$self.addClass(option.classname);
				if(option.imageswap){
					$self.find('img').each(function(){
						var csrc = $(this).attr('src').replace(new RegExp('('+option.suffix+')?(\.gif|\.jpg|\.png)$'),option.suffix+"$2")
						$(this).attr('src', csrc);
					});
				}
			}
		});
	}

	init();
};

/*----------------------------------------------
 add clear lines
----------------------------------------------*/
$.fn.addClearLines = function(cols){
	var clearLine = function(){
		return $('<span></span>').css({
			display  : 'block',
			clear    : 'both',
			overflow : 'hidden',
			height   : 0
		});
	};
	return this.each(function(){
		ie < 9 ? $(this).append(clearLine()).children(':nth-child('+cols+'n)').after(clearLine())
		       : $(this).children(':nth-child('+cols+'n+1)').css({clear:'both'});
	});
}

/*----------------------------------------------
 open toggle
----------------------------------------------*/
$.fn.openToggle = function(option){
	var reqH, base = $(this), target;
	option = $.extend({
		minH     : 0,
		trigger  : '.toggle_trigger',
		target   : '.toggle_content',
		onlyopen : false
	}, option);
	
	function _open(my_target, my_base){
		if(option.onlyopen){
			base.filter('.opened').find(option.trigger).trigger('click');
		}
		reqH = my_target.get(0).scrollHeight;
		my_target.stop().animate({height:reqH},'normal',function(){
			my_base.removeClass('closed').addClass('opened');
			my_target.css({height:''});
		});
	}
	
	function _close(my_target, my_base){
		my_target.stop(true,true).animate({height:option.minH},'normal',function(){
			my_base.removeClass('opened').addClass('closed');
		});
	}
	
	$(option.trigger,base).click(function(){
		this.blur();
		my_base   = $(this).closest(base);
		my_target = my_base.find(option.target);
		(my_target.height() === option.minH) ? _open(my_target, my_base) : _close(my_target, my_base);
		return false;
	});
	
	return this;
};

/*----------------------------------------------
 equal heights
----------------------------------------------*/
var eqHeightsObj   = [];
var eqHeightsGroup = 0;
var eqHeightInitialized = false;

$.fn.eqHeights = function(cols, is_parent, targets){
	var $items = (targets)   ? this.find(targets)
	           : (is_parent) ? this.children()
						               : this,
	    len = $items.length, h, max_h = 0, i, j;
	if(!cols) cols = $items.length;
	$.merge(eqHeightsObj,$items);
	for(i = 0; i < Math.ceil(len/cols); i++) {
		j = i * cols;
		max_h = 0;
		_setHeight($items.slice(j, j+cols).addClass('eqHeightsGroup'+eqHeightsGroup++));
	}
	
	function _setHeight($self){
		var h, max_h = 0, i;
		return $self.each(function(){
			h = $(this).css({height:'auto'}).height();
			if(h > max_h) max_h = h;
		}).height(max_h);
	}
	
	function _keepHeight(){
		var $sp = $('<span>&nbsp;</span>').hide().appendTo('body'), last_h = 0;
		setInterval(function(){
			current_h = $sp.height();
			if(last_h !== current_h){
				for(i=0; i<eqHeightsGroup; i++){
					_setHeight($(eqHeightsObj).filter('.eqHeightsGroup'+i));
				}
			}
		},1500);
	}
	
	if(!eqHeightInitialized){
		eqHeightInitialized = true;
		_keepHeight();
	}		
	return this;
};

/*----------------------------------------------
 popup image
----------------------------------------------*/
$.fn.popupImage = function (){
	$(this).click(function(){
		var href = this.href;
		var img = new Image();
		img.onload = function(){
			var w = img.width+30,
			    h = img.height+30;
			if(screen.availWidth){
				if(w+120 > screen.availWidth){
					w = screen.availWidth - 120;
				}
				if(h+120 > screen.availHeight){
					h = screen.availHeight - 120;
				}
			}
			var x = ((screen.availWidth || screen.width) - w) / 2,
					y = ((screen.availHeight || screen.height) - h) / 2;
			var pop_img = window.open('','','menubar=0,toolbar=0,location=0,titlebar=0,status=0,resizable=0,scrollbars=1,left='+x+',top='+y+',width='+w+',height='+h);
			if(pop_img){
				pop_img.window.document.open();
        pop_img.window.document.write('<html><body style="margin:0;padding:0;border:0;"><table border=0 cellspacing=0 cellpadding=0 width=100% height=100%><tr><td style="border:none; vertical-align:middle; text-align:center; width:100%; height:100%;"><img src="'+href+'" alt="" onclick="window.close()" style="cursor:pointer;" /></td></tr></table></body></html>');
			  pop_img.window.document.close();
			}
		};
		img.src = href;
		return false;
	});
};

/*----------------------------------------------
 ie fix
----------------------------------------------*/
if(ie < 7){
	try{document.execCommand("BackgroundImageCache", false, true);}catch(e){}
}

});
