(function(){
	function addEvent(obj,type,fn){
		if(obj.addEventListener)
		obj.addEventListener(type,fn,false);
		else if(obj.attachEvent)
		obj.attachEvent('on'+type,fn);
		else obj['on'+type]=fn;		
	}

	
	function removeEvent(obj,type,fn){
		if(obj.removeEventListener)
		obj.removeEventListener(type,fn,false);
		else if(obj.detachEvent)
		obj.detachEvent('on'+type,fn);	
		else obj['on'+type]='';	
	}

	function $(obj){
		return document.getElementById(obj);
	}

	function extend(opt1,opt2){
		if(!opt1)return opt2;
		for(var key in opt2){
		if(!opt2.hasOwnProperty(key))continue;
		if(opt1[key])
		opt2[key]=opt1[key];
		}
		return opt2;
	}
	function contentLoad(fn){
if (document.addEventListener) {
	document.addEventListener("DOMContentLoaded", fn, false);

} else if (/MSIE/i.test(navigator.userAgent)) {
document.write("<script id='__ie_onload' defer src='javascript:void(0);'><\/script>");
var script = document.getElementById("__ie_onload");
	script.onreadystatechange = function() {
		if (this.readyState == 'complete') {
			fn();
		}
	}

} else if (/WebKit/i.test(navigator.userAgent)) {
	var _timer = setInterval( function() {
		if (/loaded|complete/.test(document.readyState)) {
			clearInterval(_timer);
			fn();
		}
	}, 10);

} else {
	window.onload = function(e) {
		fn();
	}
}
}
	window['Box']={};
	window['Box']['$']=$;
	window['Box']['addEvent']=addEvent;
	window['Box']['removeEvent']=removeEvent;
	window['Box']['extend']=extend;
	window['Box']['contentLoad']=contentLoad;
})();

var Simplebox=(function(){
var overlay,tmp,outer,inner,loading,nav_close,nav_left,nav_right,busy=false,selectedArray,selectedIndex,opts;
var loadingTimer, loadingFrame = 1;
var shadow=20, imgLoader=new Image;
var imageRegExp = /\.(jpg|gif|png|bmp|jpeg)(.*)?$/i, swfRegExp = /[^\.]\.(swf)\s*$/i;
var preLoadImgs=[];
var defaults={
		padding				:	10,
		margin				:	20,
		width				:	560,
		height				:	340,
		cyclic				:	false,

		overlayShow			:	true,
		hideOnOverlayClick	:	true,
		hideOnContentClick	:	false,

		swf					:	{ wmode: 'transparent' },

		titleShow			:	true,
		titlePosition		:	'inside',	// 'outside', 'inside' or 'over'
		titleFormat			:	null,

		autoScale			:	true,
		autoDimensions		:	true,

		showCloseButton		:	true,
		showNavArrows		:	true,
		enableEscapeButton	:	true,
		overlayColor		:   '#888888',
		overlayOpacity		:	'0.6'
	}



function abort(){
		loading.style.display='none';
		imgLoader.onerror = imgLoader.onload = null;
	
	}

function cancel(){
if (busy) return;
	busy = true;
	abort();
	busy = false;
}


function close(){
	if(busy)return;
	abort();
	preLoadImgs=[];
	Box.removeEvent(document,'keydown',documentKey);
	nav_close.style.display='none';
	nav_left.style.display='none';
	nav_right.style.display='none';
	if (opts.hideOnContentClick)
		Box.removeEvent(inner,'click',close);
	if (opts.hideOnOverlayClick)
		Box.removeEvent(overlay,'click',close);

	overlay.style.display='none';
	outer.style.display='none';
	inner.innerHTML='';
	if(Box.$('simple-title'))
	Box.$('simple-title').parentNode.removeChild(Box.$('simple-title'));
	}


function init(){
	tmp=document.createElement('div');
	document.body.appendChild(tmp);
	tmp.id='simple-tmp';
	
	loading=tmp.cloneNode(false);	
	loading.id='simple-loading';
	loading.appendChild(document.createElement('div'));
	document.body.appendChild(loading);

	overlay=tmp.cloneNode(false);
	overlay.id='simple-overlay';
	document.body.appendChild(overlay);
	outer=tmp.cloneNode(false);
	outer.id='simple-outer';
	document.body.appendChild(outer);
	
	inner=tmp.cloneNode(false);
	inner.id='simple-inner';
	outer.appendChild(inner);
	
	nav_close=document.createElement('a');
	nav_close.id='simple-close';
	outer.appendChild(nav_close);
	
	nav_left=document.createElement('a');
	nav_left.id='simple-left';
	var ico_left=document.createElement('span');
	ico_left.className='simple-ico';
	ico_left.id='simple-left-ico';
	nav_left.appendChild(ico_left);
	outer.appendChild(nav_left);

	nav_right=document.createElement('a');
	nav_right.id='simple-right';
	var ico_right=document.createElement('span');
	ico_right.className='simple-ico';
	ico_right.id='simple-right-ico';
	nav_right.appendChild(ico_right);
	outer.appendChild(nav_right);

	Box.addEvent(nav_close,'click',close);
	Box.addEvent(nav_left,'click',prev);
	Box.addEvent(nav_right,'click',next);
	Box.addEvent(loading,'click',cancel);
	
	
	}


function start(){
abort();
var obj=selectedArray[selectedIndex];
opts.title=obj.title || '';
if(!obj.href) return;

	if (obj.href.match(imageRegExp)) {
			opts.type = 'image';

			} else if (obj.href.match(swfRegExp)) {
				opts.type = 'swf';

			}
			else opts.type = '';
	if(!opts.type)
	return
	
	switch (opts.type){
		case 'image':
		busy=false;
		showActivity();
			if(!preLoadImgs[selectedIndex]){
				imgLoader=new Image;
				imgLoader.onload = function() {
					imgLoader.onerror = null;
					imgLoader.onload = null;
					preLoadImgs[selectedIndex]=imgLoader;
					processImage();
				}
				imgLoader.src = obj.href;
			}
			else {	imgLoader=preLoadImgs[selectedIndex];
				if(imgLoader.complete){
				processImage();
				}
				else imgLoader.onload = function() {
					imgLoader.onerror = null;
					imgLoader.onload = null;
					processImage();
				}
			}
				
				break;
		case 'swf':	var str = '';
				var emb = '';

			str += '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="' + opts.width + '" height="' + opts.height + '"><param name="movie" value="' + obj.href + '"></param>';

				for(var key in opts.swf){
		if(!opts.swf.hasOwnProperty)	continue;
		str += '<param name="' + key + '" value="' + opts.swf[key] + '"></param>';
		emb += ' ' + key + '="' + opts.swf[key] + '"';
				
		}
		str += '<embed src="' + obj.href + '" type="application/x-shockwave-flash" width="' + opts.width + '" height="' + opts.height + '"' + emb + '></embed></object>';

		tmp.innerHTML=str;
		show();
		break;
	}
	


	}




function processImage(){
	busy=true;
	tmp.innerHTML='';
	opts.width	= imgLoader.width;
	opts.height	= imgLoader.height;
	imgLoader.alt=opts.title;
	tmp.appendChild(imgLoader);
	show();
	}

function show(){
	loading.style.display='none';
		opts.final_pos = getZoomTo();
		processTitle();
		inner.style.width = opts.width+'px';
		inner.style.height = opts.height+'px';
		inner.innerHTML = tmp.innerHTML;
		outer.style.left = opts.final_pos.left+'px';
		outer.style.top = opts.final_pos.top+'px';
		outer.style.width = opts.final_pos.width+'px';
		outer.style.height = opts.final_pos.height+'px';
	if (outer.style.display != 'block') {
		nav_close.style.display='none';
		nav_left.style.display='none';
		nav_right.style.display='none';
		if(opts.overlayShow){
		overlay.style.backgroundColor = opts.overlayColor;
		overlay.style.opacity = opts.overlayOpacity;
overlay.style.filter = 'alpha(opacity=' + Math.ceil(opts.overlayOpacity*100) + ')';
		overlay.style.display = 'block';
		}
		inner.style.left = opts.padding+'px';
		inner.style.top = opts.padding+'px';
		outer.style.display = 'block';
		}
	finish();
}


function finish(){
if(Box.$('simple-title'))
Box.$('simple-title').style.display='block';
	if (opts.showCloseButton)
		 nav_close.style.display='block';
	if (opts.hideOnContentClick)
		Box.addEvent(inner,'click',close);
	if (opts.hideOnOverlayClick && opts.overlayShow)
		Box.addEvent(overlay,'click',close);
	if(selectedArray.length>1)
		simpleSetNavigation();
	busy = false;
	preloadImages();
}

function getBrowserWindowSize() {
    var de = document.documentElement;
    return {
        'width':(
            window.innerWidth 
            || (de && de.clientWidth ) 
            || document.body.clientWidth),
        'height':(
            window.innerHeight 
            || (de && de.clientHeight ) 
            || document.body.clientHeight)
    }
}

function get_viewport(){
	var win=getBrowserWindowSize();
	return [win.width,win.height,document.documentElement.scrollLeft ||    document.body.scrollLeft,document.documentElement.scrollTop || document.body.scrollTop];
}

function getZoomTo(){
	var view=get_viewport();
	var to={};
	var margin = opts.margin;
	var resize = opts.autoScale;
	var double_padding=opts.padding*2;
	var horizontal_space= margin * 2, vertical_space= margin * 2 ;
	if (opts.width.toString().indexOf('%') > -1) {
			to.width = ((view[0] * parseFloat(opts.width)) / 100) ;
			resize = false;

		} else {
			to.width = opts.width + double_padding;
		}

		if (opts.height.toString().indexOf('%') > -1) {
			to.height = ((view[1] * parseFloat(opts.height)) / 100) ;
			resize = false;

		} else {
			to.height = opts.height + double_padding;
		}
	
	if (resize && (to.width > (view[0] - horizontal_space) || to.height > (view[1] - vertical_space))) {
			
				horizontal_space	+= double_padding;
				vertical_space		+= double_padding;

				var ratio = Math.min(Math.min( view[0] - horizontal_space, opts.width) / opts.width, Math.min( view[1] - vertical_space, opts.height) / opts.height);

				to.width	= Math.round(ratio * (to.width	- double_padding)) + double_padding;
				to.height	= Math.round(ratio * (to.height	- double_padding)) + double_padding;

		
		}

	to.left=view[2]+(view[0]-to.width)*0.5;
	to.top=view[3]+(view[1]-to.height)*0.5;
	if (opts.autoScale == false) {
			to.top	= Math.max(view[3] + margin, to.top);
			to.left	= Math.max(view[2] + margin, to.left);
		}
	return to;
	}

function processTitle(){
if(Box.$('simple-title'))
Box.$('simple-title').parentNode.removeChild(Box.$('simple-title'));
if(!opts.titleShow) return;

var title = opts.title;
if(!title) return;

title = typeof (opts.titleFormat) === 'function' ? opts.titleFormat(title, selectedArray, selectedIndex, opts) : format_title(title);

var simple_title=document.createElement('div');
simple_title.id='simple-title';
simple_title.className='simple-title-'+opts.titlePosition;
simple_title.innerHTML=title;
simple_title.style.width=opts.width+'px';
simple_title.style.paddingLeft=opts.padding+'px';
simple_title.style.paddingRight=opts.padding+'px';

document.body.appendChild(simple_title);
switch (opts.titlePosition) {
	case 'inside':	opts.final_pos.height += simple_title.offsetHeight - opts.padding;
					break;
	case 'over':
				simple_title.style.bottom=opts.padding+'px';
			break;
default:
			simple_title.style.bottom =(simple_title.offsetHeight * -1)+'px';
			break;
	}
outer.appendChild(simple_title);
simple_title.style.display='none';

}
function format_title(title){
if (title && title.length) {
			switch (opts.titlePosition) {
				case 'inside':
					return title;
				break;

				case 'over':
					return '<span id="simple-title-over">' + title + '</span>';
				break;

				default:
					return '<span id="simple-title-wrap"><span id="simple-title-left"></span><span id="simple-title-main">' + title + '</span><span id="simple-title-right"></span></span>';
				break;
			}
		}

		return false;
}


function simpleSetNavigation(){
	Box.addEvent(document,'keydown',documentKey);
	if (!opts.showNavArrows) return;

		if ((opts.cyclic && selectedArray.length > 1) || selectedIndex != 0) {
			nav_left.style.display='block';
		}

		if ((opts.cyclic && selectedArray.length > 1) || selectedIndex != (selectedArray.length -1)) {
			nav_right.style.display='block';
		}
}

function documentKey(e){
		var event=e || window.event;
			if (e.keyCode == 27 && opts.enableEscapeButton) {
				e.preventDefault();
				close();

			} else if (e.keyCode == 37) {
				e.preventDefault();
				prev();

			} else if (e.keyCode == 39) {
				e.preventDefault();
				next();
			}
		
	}
function prev(){
	return pos( selectedIndex - 1);
	}


function next(){
	return pos( selectedIndex + 1);
	}


function pos(pos){
	
		if (pos > -1 && selectedArray.length > pos) {
			selectedIndex = pos;
			start();
		}

		if ( opts.cyclic &&  selectedArray.length > 1 && pos < 0) {
			selectedIndex = selectedArray.length - 1;
			start();
		}

		if (opts.cyclic && selectedArray.length > 1 && pos >=  selectedArray.length) {
			selectedIndex = 0;
			start();
		}
	
	}
function animate_loading() {
		if (loading.style.display!='block'){
			clearInterval(loadingTimer);
			return;
		}

		loading.childNodes[0].style.top= (loadingFrame * -40) + 'px';

		loadingFrame = (loadingFrame + 1) % 12;
	}


function preloadImages(){
if ((selectedArray.length -1) > selectedIndex && !preLoadImgs[selectedIndex + 1]) {
			var href = selectedArray[ selectedIndex + 1 ].href;

			if (typeof href !== 'undefined' && href.match(imageRegExp)) {
				var objNext = new Image();
				objNext.src = href;
				preLoadImgs[selectedIndex + 1 ]=objNext;
			}
		}

		if (selectedIndex > 0 && !preLoadImgs[selectedIndex - 1]) {
			var href = selectedArray[ selectedIndex - 1 ].href;

			if (typeof href !== 'undefined' && href.match(imageRegExp)) {
				var objPre = new Image();
				objPre.src = href;
				preLoadImgs[selectedIndex - 1 ]=objPre;
			}
		}

}


function showActivity(){
	clearInterval(loadingTimer);

		loading.style.display='block';
		loadingTimer = setInterval(animate_loading, 66);
	}

return {
	arr:[],
	init:function(){init();},
	handle:function(node){
		Box.addEvent(node,'click',function(e){
		Simplebox.arr=[];
		var index;
		if(this.rel=='simplebox'){
		Simplebox.arr.push(this);
		index=0;
		}
		else {
		var a=document.getElementsByTagName('a');
		for(var i=0,len=a.length;i<len;++i){
			if(a[i].rel=='simplebox_group')
			Simplebox.arr.push(a[i]);
		}
		for(var i=0,len=Simplebox.arr.length;i<len;++i){
			if(Simplebox.arr[i]==this)
				index=i;		
		}
		}
			if (busy) return;
			busy = true;
		Simplebox.register(index);
		var event=e || window.event;
		event.preventDefault();
		});
	},
	register:function(i){
		Simplebox.construct(i);
	},
	construct:function(index,options){
		selectedArray=Simplebox.arr;
		selectedIndex=index;
		opts=Box.extend(options,defaults);
		start();
	}
}

})();
