/*
 * Plugin for jQuery
 * Author: Aleksey Rybitskyi
 * Name: abigimage
 * Author's site: http://najdem.com/ http://arybitskyi.com/
 * You can use this script by GPL license
 */
;jQuery.fn.abigimage = function(settings){
	$.abigimage_o = this;
	
	//Setting load_info to defaults
	$.abigimage_o.load_info = {
		loaded:		0,
		loading:	0,
		errors:		0,
		complete:	false,
		start_load:	false,
		images:		{}
	};
	
	//Some variables
	$.abigimage_o.vars = {};
	
	//Setting "to do list"
	$.abigimage_o.to_do_list = {};
	
	//Setting "to do list"
	$.abigimage_o.keypress_list = {};
	
	//Setting images list
	$.abigimage_o.image_list = {};
	
	//Settings
	$.abigimage_o.settings = jQuery.extend({
		text_preload_image:			'Loading image...',
		text_close:					'close [x]'
	},settings);
	
	//Setting big and small images
	if($.abigimage_o.attr('bigsrc'))
		$.abigimage_o.settings.bigsrc = $.abigimage_o.attr('bigsrc');
	else
		return false;
	if($.abigimage_o.attr('smallsrc'))
		$.abigimage_o.settings.smallsrc = $.abigimage_o.attr('smallsrc');
	else
		return false;
	
	//Actions
	//OnFocus
	$.abigimage_o.focus(function(){
		$.abigimage_o.blur();
	});
	//OnClick
	$.abigimage_o.click(function(){
		
		//Showing preload image
		showPreload($.abigimage_o.settings.text_preload_image);
		
		if(!$.abigimage_o.load_info.complete){
			//Loading small and large image
			loadImage($.abigimage_o.settings.bigsrc,'bigimage',true);
			loadImage($.abigimage_o.settings.smallsrc,'smallimage',true);
		}
		else{
			//Show Images
			displayImages();
		}
		
		$.abigimage_showed = true;
		
		return false;
	});
	//Document
	//MouseMove
	//MouseUp
	//MouseDown
	//KeyUp
	//KeyDown
	if(!$.abigimage_handlers){
		$.abigimage_handlers = true;
		//Interval for getting keypress
		$.abigimage_o.vars.keypress_interval = setInterval(function(){
			if(!$.abigimage_showed)return false;
			for(var i in $.abigimage_o.keypress_list)
				switch(i){
					case 'moveBig_up':
						moveBig(0,-10,false);
					break;
					case 'moveBig_down':
						moveBig(0,10,false);
					break;
					case 'moveBig_left':
						moveBig(-10,0,false);
					break;
					case 'moveBig_right':
						moveBig(10,0,false);
					break;
				}
		},50);
		$(document)
		.mousemove(mouseMove)
		.mouseup(function(){
			$('body').css('cursor','default');
			$.abigimage_mousedown_big = false;
			$.abigimage_mousedown_small = false;
		})
		.keyup(function(e){
			switch(e.keyCode){
				case 27:
					hideMe();
					return false;
				break;
				case 38:
					//Move Up
					removeAction('moveBig_up');
					return false;
				break;
				case 40:
					//Move Down
					removeAction('moveBig_down');
					return false;
				break;
				case 37:
					//Move Left
					removeAction('moveBig_left');
					return false;
				break;
				case 39:
					//Move Right
					removeAction('moveBig_right');
					return false;
				break;
			}
			return true;
		})
		.keydown(function(e){
			switch(e.keyCode){
				case 38:
					//Move Up
					addAction('moveBig_up','up');
					return false;
				break;
				case 40:
					//Move Down
					addAction('moveBig_down','down');
					return false;
				break;
				case 37:
					//Move Left
					addAction('moveBig_left','left');
					return false;
				break;
				case 39:
					//Move Right
					addAction('moveBig_right','right');
					return false;
				break;
			}
			return true;
		});
	}
	
	//Builds, Shows preload background with text
	function showPreload(text){
		hideAll();
		//Checking elements
		if($('#abigimage_background').size()==0)
			$('body').append('<div id="abigimage_background" style="position:absolute;left:0px;top:0px;display:none;z-index:100;width:'+$('body').width()+'px;height:'+$('body').height()+'px;background:#000000;"></div>');
		$('#abigimage_background').html('');
		if($('#abigimage_content').size()==0)
			$('body').append('<div id="abigimage_content" style="position:absolute;left:0px;top:0px;display:none;z-index:101;overflow:hidden;width:'+$('body').width()+'px;height:'+$('body').height()+'px;"></div>');
		$('#abigimage_content').html('<div id="abigimage_content_inner" style="overflow:hidden;position:absolute;cursor:move;"></div>');
		if($('#abigimage_pleloader').size()==0)
			$('body').append('<div id="abigimage_pleloader" style="position:absolute;left:0px;top:0px;display:none;z-index:101;text-align:center;"></div>');
		$('#abigimage_pleloader').html(text+'...');
		if($('#abigimage_smallimage').size()==0)
			$('body').append('<div id="abigimage_smallimage" style="position:absolute;right:10px;bottom:10px;display:none;z-index:102;"></div>');
		$('#abigimage_smallimage').html('');
		if($('#abigimage_smallimage_cover').size()==0)
			$('body').append('<div id="abigimage_smallimage_cover" style="position:absolute;right:10px;bottom:10px;display:none;z-index:103;background:#000000;cursor:move;"></div>');
		$('#abigimage_smallimage_cover').html('');
		if($('#abigimage_close').size()==0){
			$('body').append('<div id="abigimage_close" style="position:absolute;right:10px;top:10px;display:none;z-index:101;cursor:pointer;">'+$.abigimage_o.settings.text_close+'</div>');
			$('#abigimage_close').click(function(){
				hideMe();
			});
		}
		$('#abigimage_pleloader').css({left:($('body').width()-$('#abigimage_pleloader').width())/2,top:($('body').height()-$('#abigimage_pleloader').height())/2});
		$('#abigimage_background').css({opacity:0}).show().animate({opacity:0.9},200).add('#abigimage_close').add('#abigimage_content').add('#abigimage_pleloader').show();
	}
	
	//Hide Me
	function hideMe(){
		$('#abigimage_close').add('#abigimage_content').add('#abigimage_pleloader').add('#abigimage_smallimage').add('#abigimage_smallimage_cover').remove();
		$('#abigimage_background').animate({opacity:0.9},200,function(){
			$(this).hide();
			showAll();
		});
		$.abigimage_showed = false;
	}
	
	//Display Images
	function displayImages(){
		$('#abigimage_pleloader').hide();
		var imagebig = new Image();
		imagebig.src = $.abigimage_o.settings.bigsrc;
		var imagesmall = new Image();
		imagesmall.src = $.abigimage_o.settings.smallsrc;
		$.abigimage_o.image_list['bigimage'] = {node: imagebig};
		$.abigimage_o.image_list['smallimage'] = {node: imagesmall};
		$('#abigimage_smallimage').html('').append(imagesmall).show();
		$('#abigimage_content_inner').css({width:($('body').width()-2*(imagesmall.width+20))<imagebig.width?($('body').width()-2*(imagesmall.width+20)):imagebig.width+'px',height:$('body').height()-20+'px'});
		$('#abigimage_content_inner').css({left:($('body').width()-$('#abigimage_content_inner').width())/2+'px',top:'10px'});
		$('#abigimage_content_inner').html('').append(imagebig);
		$('#abigimage_content_inner').mousedown(function(e){
			$('body').css('cursor','move');
			$(this).find('img').attr('pre_left',parseInt($(this).find('img').css('margin-left'))).attr('pre_top',parseInt($(this).find('img').css('margin-top')));
			$.pageX = e.pageX;
			$.pageY = e.pageY;
			$.abigimage_mousedown_big = true;
			return false;
		});
		$('#abigimage_smallimage').mousedown(function(){
			return false;
		});
		$('#abigimage_smallimage_cover').mousedown(function(e){
			$('body').css('cursor','move');
			$(this).attr('pre_right',parseInt($(this).css('right'))).attr('pre_bottom',parseInt($(this).css('bottom')));
			$.pageX = e.pageX;
			$.pageY = e.pageY;
			$.abigimage_mousedown_small = true;
			return false;
		});
		$('#abigimage_smallimage_cover').css({width:Math.ceil(imagesmall.width*$('#abigimage_content_inner').width()/imagebig.width)+'px',height:Math.ceil(imagesmall.height*$('#abigimage_content_inner').height()/imagebig.height)+'px',opacity:0.5}).show();
		$('#abigimage_smallimage_cover').mousedown(function(){
			return false;
		});
		syncBigToSmall();
	}
	
	//sync small to big
	function syncSmallToBig(){
		var marginLeft,marginTop;

		marginLeft = -Math.ceil(($.abigimage_o.image_list['smallimage'].node.width - ($('#abigimage_smallimage_cover').width() + (parseInt($('#abigimage_smallimage_cover').css('right')) - 10)))/$.abigimage_o.image_list['smallimage'].node.width*$.abigimage_o.image_list['bigimage'].node.width);
		if(marginLeft>0)marginLeft = 0;
		if(marginLeft<-($.abigimage_o.image_list['bigimage'].node.width-$('#abigimage_content_inner').width()))
			marginLeft = -($.abigimage_o.image_list['bigimage'].node.width-$('#abigimage_content_inner').width());
		$('#abigimage_content_inner img').css({marginLeft:marginLeft+'px'});

		marginTop = -Math.ceil(($.abigimage_o.image_list['smallimage'].node.height - ($('#abigimage_smallimage_cover').height() + (parseInt($('#abigimage_smallimage_cover').css('bottom')) - 10)))/$.abigimage_o.image_list['smallimage'].node.height*$.abigimage_o.image_list['bigimage'].node.height);
		if(marginTop>0)marginTop = 0;
		if(marginTop<-($.abigimage_o.image_list['bigimage'].node.height-$('#abigimage_content_inner').height()))
			marginTop = -($.abigimage_o.image_list['bigimage'].node.height-$('#abigimage_content_inner').height());
		$('#abigimage_content_inner img').css({marginLeft:marginLeft+'px',marginTop:marginTop+'px'});
	}
	
	//sync big to small
	function syncBigToSmall(){
		var right,bottom;
		
		right = Math.abs(parseInt($('#abigimage_content_inner img').css('margin-left')) / $('#abigimage_content_inner').width() * $('#abigimage_smallimage_cover').width());
		if(isNaN(right))right = 0;
		if(right<0)right = 0;
		if(right>$('#abigimage_smallimage img').width()-$('#abigimage_smallimage_cover').width())
			right = $('#abigimage_smallimage img').width()-$('#abigimage_smallimage_cover').width();
		right = $('#abigimage_smallimage img').width() - right - $('#abigimage_smallimage_cover').width();
		$('#abigimage_smallimage_cover').css('right',(right+10+'px'));
		
		bottom = Math.abs(parseInt($('#abigimage_content_inner img').css('margin-top')) / $('#abigimage_content_inner').height() * $('#abigimage_smallimage_cover').height());
		if(isNaN(bottom))bottom = 0;
		if(bottom<0)bottom = 0;
		if(bottom>$('#abigimage_smallimage img').height()-$('#abigimage_smallimage_cover').height())
			bottom = $('#abigimage_smallimage img').height()-$('#abigimage_smallimage_cover').height();
		bottom = $('#abigimage_smallimage img').height() - bottom - $('#abigimage_smallimage_cover').height();
		$('#abigimage_smallimage_cover').css({right:right+10+'px',bottom:bottom+10+'px'});
	}
	
	//move big image
	function moveBig(dX,dY,mouse){
		if(mouse){
			var
				marginTop = parseInt($('#abigimage_content_inner img').attr('pre_top'))+dY,
				marginLeft = parseInt($('#abigimage_content_inner img').attr('pre_left'))+dX;
		}
		else{
			var
				marginTop = parseInt($('#abigimage_content_inner img').css('margin-top'))-dY,
				marginLeft = parseInt($('#abigimage_content_inner img').css('margin-left'))-dX;
		}
		if(isNaN(marginLeft))marginLeft = 0;
		if(isNaN(marginTop))marginTop = 0;
		if(marginLeft>0)marginLeft = 0;
		if(marginTop>0)marginTop = 0;
		if(marginLeft<-($($.abigimage_o.image_list.bigimage.node).width()-$('#abigimage_content_inner').width()))
			marginLeft = -($($.abigimage_o.image_list.bigimage.node).width()-$('#abigimage_content_inner').width());
		if(marginTop<-($($.abigimage_o.image_list.bigimage.node).height()-$('#abigimage_content_inner').height()))
			marginTop = -($($.abigimage_o.image_list.bigimage.node).height()-$('#abigimage_content_inner').height());
		$('#abigimage_content_inner img').css({marginTop:marginTop+'px',marginLeft:marginLeft+'px'});
		syncBigToSmall();
	}

	//mouse move
	function mouseMove(e){
		var
			dX = e.pageX - $.pageX,
			dY = e.pageY - $.pageY;
		if($.abigimage_mousedown_big){
			moveBig(dX,dY,true);
			return false;
		}
		if($.abigimage_mousedown_small){
			var
				right = parseInt($('#abigimage_smallimage_cover').attr('pre_right'))-dX,
				bottom = parseInt($('#abigimage_smallimage_cover').attr('pre_bottom'))-dY;
			if(right<10)right = 10;
			if(bottom<10)bottom = 10;
			if(right>($.abigimage_o.image_list['smallimage'].node.width-$('#abigimage_smallimage_cover').width()+10))
				right = $.abigimage_o.image_list['smallimage'].node.width-$('#abigimage_smallimage_cover').width()+10;
			if(bottom>($.abigimage_o.image_list['smallimage'].node.height-$('#abigimage_smallimage_cover').height()+10))
				bottom = $.abigimage_o.image_list['smallimage'].node.height-$('#abigimage_smallimage_cover').height()+10;
			$('#abigimage_smallimage_cover').css({right:right+'px',bottom:bottom+'px'});
			syncSmallToBig();
		}
		if($.abigimage_showed)return false;
	}
	
	//check for image load
	function checkImageLoad(){
		if($.abigimage_o.load_info.complete){
			displayImages();
			return false;
		}
		if(!$.abigimage_o.load_info.start_load)return false;
		if($.abigimage_o.load_info.errors){
			$('#abigimage_pleloader').html('Error while loading...');
			return false;
		}
		else if($.abigimage_o.load_info.loading){
			return false;
		}
		else if($.abigimage_o.load_info.loaded&&!$.abigimage_o.load_info.loading){
			$.abigimage_o.load_info.complete = true;
			displayImages();
		}
	}
	
	//hide all elements except abigimage
	function hideAll(){
		$.abigimage_o.vars.body_scroll = $(document).scrollTop();
		$('#page').add('#page_shadow_left').add('#page_shadow_right').add('#page_shadow_bottom').hide();
		$.no_shadows = true;
	}
	
	//show all elements except abigimage
	function showAll(){
		$('#page').add('#page_shadow_left').add('#page_shadow_right').add('#page_shadow_bottom').show();
		$(document).scrollTop($.abigimage_o.vars.body_scroll);
		$.no_shadows = false;
		//Выравниваем #page по центру
		$('#page').css({left:($('body').width()-$('#page > table').width())/2+'px',position:'absolute'});
		if($.abigimage_o.settings.afterShow)
			$.abigimage_o.settings.afterShow();
	}
	
	//execute actions
	function execActions(){
		for(var i=0;i<$.abigimage_o.vars.actions.length;i++)
			switch($.abigimage_o.vars.actions[i].action){
				case 'scrollToPosition':
					scrollToPosition($.abigimage_o.vars.actions[i].value);
				break;
				case 'scrollToItemByIndex':
					scrollToItemByIndex($.abigimage_o.vars.actions[i].value);
				break;
				case 'scrollToItemById':
					scrollToItemById($.abigimage_o.vars.actions[i].value);
				break;
			}
	}
	
	//add action to do each 50 msec
	function addAction(action,value){
		$.abigimage_o.keypress_list[action] = value;
	}
	
	//removes action to do 50 msec
	function removeAction(action){
		if($.abigimage_o.keypress_list[action])delete($.abigimage_o.keypress_list[action]);
	}
	
	//load image
	function loadImage(src,image_id,started){
		if(started!=undefined){
			$.abigimage_o.load_info.start_load = true;
		}
		if(typeof $.abigimage_o.image_list == 'undefined')
			$.abigimage_o.image_list = {};
		var image = {};
		image.node = new Image();
		image.loaded = 0;
		$.abigimage_o.load_info.loading++;
		image.node.onload = function(){
			image.loaded = 2;
			$.abigimage_o.load_info.loading--;
			$.abigimage_o.load_info.loaded++;
			checkImageLoad();
		}
		image.node.onabort = function(){
			image.loaded = 1;
			$.abigimage_o.load_info.loading--;
			$.abigimage_o.load_info.errors++;
			checkImageLoad();
		}
		image.node.src = src;
		$.abigimage_o.image_list[image_id] = image;
		return image;
	}
	return this;
};
