/**
 * jQuery lightBox plugin
 * This jQuery plugin was inspired and based on Lightbox 2 by Lokesh Dhakar (http://www.huddletogether.com/projects/lightbox2/)
 * and adapted to me for use like a plugin from jQuery.
 * @name jquery-lightbox-0.5.js
 * @author Leandro Vieira Pinho - http://leandrovieira.com
 * @version 0.5
 * @date April 11, 2008
 * @category jQuery plugin
 * @copyright (c) 2008 Leandro Vieira Pinho (leandrovieira.com)
 * @license CC Attribution-No Derivative Works 2.5 Brazil - http://creativecommons.org/licenses/by-nd/2.5/br/deed.en_US
 * @example Visit http://leandrovieira.com/projects/jquery/lightbox/ for more informations about this jQuery plugin
 */

// Offering a Custom Alias suport - More info: http://docs.jquery.com/Plugins/Authoring#Custom_Alias
(function($) {
	/**
	 * $ is an alias to jQuery object
	 *
	 */
	$.fn.lightBox = function(settings) {
		// Settings to configure the jQuery lightBox plugin how you like
		settings = jQuery.extend({
			// Configuration related to overlay
			overlayBgColor: 		'#000',		// (string) Background color to overlay; inform a hexadecimal value like: #RRGGBB. Where RR, GG, and BB are the hexadecimal values for the red, green, and blue values of the color.
			overlayOpacity:			0.8,		// (integer) Opacity value to overlay; inform: 0.X. Where X are number from 0 to 9
			// Configuration related to navigation
			fixedNavigation:		false,		// (boolean) Boolean that informs if the navigation (next and prev button) will be fixed or not in the interface.
			// Configuration related to images
			imageLoading:			'images/lightbox-ico-loading.gif',		// (string) Path and the name of the loading icon
			imageBtnPrev:			'images/lightbox-btn-prev.gif',			// (string) Path and the name of the prev button image
			imageBtnNext:			'images/lightbox-btn-next.gif',			// (string) Path and the name of the next button image
			imageBtnClose:			'images/lightbox-btn-close.jpg',		// (string) Path and the name of the close btn
			imageBtnBuy:			'images/lightbox-btn-buy.jpg',		    // (string) Path and the name of the buy btn
			imageBtnStar:			'img/star.jpg',			
			imageBlank:				'images/lightbox-blank.gif',			// (string) Path and the name of a blank image (one pixel)
			// Configuration related to container image box
			containerBorderSize:	10,			// (integer) If you adjust the padding in the CSS for the container, #lightbox-container-image-box, you will need to update this value
			containerResizeSpeed:	400,		// (integer) Specify the resize duration of container image. These number are miliseconds. 400 is default.
			// Configuration related to texts in caption. For example: Image 2 of 8. You can alter either "Image" and "of" texts.
			txtImage:				'Изображение',	// (string) Specify text "Image"
			txtOf:					'от',		// (string) Specify text "of"
			// Configuration related to keyboard navigation
			keyToClose:				'c',		// (string) (c = close) Letter to close the jQuery lightBox interface. Beyond this letter, the letter X and the SCAPE key is used to.
			keyToPrev:				'p',		// (string) (p = previous) Letter to show the previous image
			keyToNext:				'n',		// (string) (n = next) Letter to show the next image.
			// Don´t alter these variables in any way
			imageArray:				[],
			activeImage:			0,
			intervalID:				0
		},settings);
		// Caching the jQuery object with all elements matched
		var jQueryMatchedObj = this; // This, in this context, refer to jQuery object
		/**
		 * Initializing the plugin calling the start function
		 *
		 * @return boolean false
		 */
		function _initialize() {
			_start(this,jQueryMatchedObj); // This, in this context, refer to object (link) which the user have clicked
			return false; // Avoid the browser following the link
		}
		/**
		 * Start the jQuery lightBox plugin
		 *
		 * @param object objClicked The object (link) whick the user have clicked
		 * @param object jQueryMatchedObj The jQuery object with all elements matched
		 */
		function _start(objClicked,jQueryMatchedObj) {
			// Hime some elements to avoid conflict with overlay in IE. These elements appear above the overlay.
			$('embed, object, select').css({ 'visibility' : 'hidden' });
			// Call the function to create the markup structure; style some elements; assign events in some elements.
			_set_interface();
			// Unset total images in imageArray
			settings.imageArray.length = 0;
			// Unset image active information
			settings.activeImage = 0;
			// We have an image set? Or just an image? Let´s see it.
//			if ( jQueryMatchedObj.length == 1 ) {
//				settings.imageArray.push(new Array(objClicked.getAttribute('href'),objClicked.getAttribute('title')));
//			} else {
				// Add an Array (as many as we have), with href and title atributes, inside the Array that storage the images references		
				for ( var i = 0; i < jQueryMatchedObj.length; i++ ) {
					settings.imageArray.push(jQueryMatchedObj[i].getAttribute('id'));
				}
//			}
			while ( settings.imageArray[settings.activeImage] != objClicked.getAttribute('id') ) {
				settings.activeImage++;
			}
			//console.log(settings.activeImage);
			// Call the function that prepares image exibition
			_set_image_to_view();
		}

		function _set_interface() {
			// Apply the HTML markup into body tag
			$('body').append(
				'<div id="jquery-overlay"></div>'
				+'<div id="jquery-lightbox">'
					+'<div id="lightbox-container">'
						+'<div id="lightbox-left-container">'
							+'<div id="lightbox-container-image-box">'
								+'<div id="lightbox-container-image">'
									+'<img id="lightbox-image" />'
									+'<div style="" id="lightbox-nav">'
										+'<a id="lightbox-nav-btnPrev"></a>'
										+'<a id="lightbox-nav-btnNext"></a>'
									+'</div>'
									+'<div id="lightbox-loading">'
										+'<a href="#" id="lightbox-loading-link">'
											+'<img src="' + settings.imageLoading + '" />'
										+'</a>'
									+'</div>'
								+'</div>'
							+'</div>'
							+'<div id="lightbox-container-image-data-box">'
								+'<div id="lightbox-container-image-data">'
									+'<div id="lightbox-image-details">'
										+'<span id="lightbox-image-details-caption"></span>'
										+'<form name="price">'
										+'<div id="exclusiveUntile"></div>'
										+'<table id="rf_table" border="0" cellpadding="2" cellspacing="2" class="table_data" style="float:left;margin-right:15px">'
											+'<tr>'
												+'<th class="table_data" colspan="4">'
													+'Royalty Free'
												+'</th>'
											+'</tr>'
											+'<tr>'
												+'<th class="table_data">'
												+'</th>'										
												+'<th class="table_data">'
													+'Резолюция'	
												+'</th>'
												+'<th class="table_data">'
													+'Размери (см)'
												+'</th>'
												+'<th class="table_data">'
													+'Кредити'
												+'</th>'																				
											+'</tr>'
										+'</table>'
										+'<div id="group_text">Тази снимка е част от група, всички кредити и периоди се отнасят за цялата гупа</div>'
										+'<table id="ex_table" border="0" cellpadding="2" cellspacing="2" class="table_data" style="float:left">'
											+'<tr>'
												+'<th class="table_data" colspan="3">'
													+'Exclusive'
												+'</th>'
											+'</tr>'
											+'<tr>'
												+'<th class="table_data">'
												+'</th>'										
												+'<th class="table_data">'
													+'Период (месец)'	
												+'</th>'
												+'<th class="table_data">'
													+'Кредити'
												+'</th>'																				
											+'</tr>'
										+'</table>'
										+'<table id="ex_table_info" border="0" cellpadding="2" cellspacing="2" class="table_data" style="float:left;margin-left:10px">'
											+'<tr>'
												+'<th class="table_data" colspan="2">'
													+'Информация за фотографията'
												+'</th>'
											+'</tr>'
											+'<tr>'										
												+'<th class="table_data">'
													+'Резолюция'	
												+'</th>'
												+'<th class="table_data">'
													+'Размери (см)'
												+'</th>'																				
											+'</tr>'
										+'</table>'
										+'</form>'
										+'<div id="owned_ex">Вие притежавате тази снимка</div>'
										+'<div id="owned_rf">Вие притежавате тази снимка ако искате да я купите exclusive кликнете <a href="#" onclick="$(\'#ex_table\').show();$(\'#owned_rf\').hide();$(\'#lightbox-btnBuy\').show();">тук</a></div>'
										+'<table id="table_bottom" width="100%" height="50px" cellpadding="0" cellspacing="0" style="float:left">'
											+'<tr>'
												+'<td align="left">'
													+'<a href="#" id="lightbox-btnBuy">'
														+'<img src="' + settings.imageBtnBuy + '" />'
													+'</a>'
												+'</td>'
												+'<td align="center" style="text-align: center">'
													+'<span id="lightbox-image-details-currentNumber"></span>'
												+'</td>'
												+'<td align="right">'
													+'<div id="lightbox-secNav">'
														+'<a href="#" id="lightbox-secNav-btnClose">'
															+'<img src="' + settings.imageBtnClose + '" />'
														+'</a>'
													+'</div>'
												+'</td>'
											+'</tr>'
										+'</table>'									
									+'</div>'
								+'</div>'
							+'</div>'
						+'</div>'
						+'<div id="lightbox-right-container" style="float: left; width: 0px; height: 100px; background-color: #FFF;" />'
					+'</div>'
				+'</div>'
			);	
			
			$("#lightbox-btnBuy").click(
				function()
				{
					//var test=$(".test");
					var data='';
					if(document.price.radiogroup.length!=undefined)
					{
						//console.log(document.price.radiogroup.length);
						for (i=0;i<document.price.radiogroup.length;i++) 
						{	
							if (document.price.radiogroup[i].checked) 
								data = document.price.radiogroup[i].value;
						}
					}
					else if (document.price.radiogroup.checked) 
						data = document.price.radiogroup.value;
					
//					for(i=0;i<test.length;i++)
//						console.log(test[i]);
					//console.log("Data: "+data);
					//console.log("group-images-container: "+$('#group-images-container a').length)
					
					if($('#group-images-container a').length>'0')
						text = 'Искате ли да купите снимките от тази група?';
					else
						text = 'Искате ли да купите тази снимка?';	
					
					Boxy.ask(text, ["Купуване", "Изход"],
						function(val) {
							if(val=='Купуване')
                              {
                                //alert('lightbox call buyImage');
								buyImage(settings.imageArray[settings.activeImage],data);
                              }
			    		}, {title: ""
					});
				}
			);
			
			// Get page sizes
			var arrPageSizes = ___getPageSize();
			// Style overlay and show it
			$('#jquery-overlay').css({
				backgroundColor:	settings.overlayBgColor,
				opacity:			settings.overlayOpacity,
				width:				arrPageSizes[0],
				height:				arrPageSizes[1]
			}).fadeIn();
			// Get page scroll
			var arrPageScroll = ___getPageScroll();
			// Calculate top and left offset for the jquery-lightbox div object and show it
			$('#jquery-lightbox').css({
				top:	arrPageScroll[1] + (arrPageSizes[3] / 10),
				left:	arrPageScroll[0],
				width:	arrPageSizes[0]
			}).show();
			// Assigning click events in elements to close overlay
//			$('#jquery-overlay,#jquery-lightbox').click(function() {
//				_finish();									
//			});
			// Assign the _finish function to lightbox-loading-link and lightbox-secNav-btnClose objects
			$('#lightbox-loading-link,#lightbox-secNav-btnClose').click(function() {
				_finish();
				return false;
			});
			// If window was resized, calculate the new overlay dimensions
			$(window).resize(function() {
				// Get page sizes
				var arrPageSizes = ___getPageSize();
				// Style overlay and show it
				$('#jquery-overlay').css({
					width:		arrPageSizes[0],
					height:		arrPageSizes[1]
				});
				// Get page scroll
				var arrPageScroll = ___getPageScroll();
				// Calculate top and left offset for the jquery-lightbox div object and show it
				$('#jquery-lightbox').css({
					top:	arrPageScroll[1] + (arrPageSizes[3] / 10),
					left:	arrPageScroll[0],
					width:	arrPageSizes[0]
				});
			});
		}
		/**
		 * Prepares image exibition; doing a image´s preloader to calculate it´s size
		 *
		 */
		function _set_image_to_view() 
		{ 
			// show the loading

			if(settings.intervalID!=0)
			{
				clearInterval(settings.intervalID);
				settings.intervalID=0;
			}

			// Show the loading
			$('#lightbox-loading').show();
			if ( settings.fixedNavigation ) {
				$('#lightbox-image,#lightbox-container-image-data-box,#lightbox-image-details-currentNumber').hide();
			} else {
				// Hide some elements
				$('#lightbox-image,#lightbox-nav,#lightbox-nav-btnPrev,#lightbox-nav-btnNext,#lightbox-container-image-data-box,#lightbox-image-details-currentNumber').hide();
			}
			
			var container=$("#lightbox-container");
			var containerLeft=$("#lightbox-left-container");
			var containerRight=$("#lightbox-right-container");
			
			container.css({width: '100%'});
			containerLeft.css({'width': 'auto'});
			containerLeft.css({'float': 'none'});
			containerLeft.css({'margin': '0 auto'});
			containerRight.empty().css({height: 0, width: 0});
			
			// Image preload process
			var objImagePreloader = new Image();
			objImagePreloader.onload = function() {
				$('#lightbox-image').attr('src','get_image.php?id='+settings.imageArray[settings.activeImage]+'&size=3');
				// Perfomance an effect in the image container resizing it
				_resize_container_image_box(objImagePreloader.width,objImagePreloader.height);
				//	clear onLoad, IE behaves irratically with animated gifs otherwise
				objImagePreloader.onload=function(){};
			};
			objImagePreloader.src = 'get_image.php?id='+settings.imageArray[settings.activeImage]+'&size=3';
		};
		/**
		 * Perfomance an effect in the image container resizing it
		 *
		 * @param integer intImageWidth The image´s width that will be showed
		 * @param integer intImageHeight The image´s height that will be showed
		 */
		function _resize_container_image_box(intImageWidth,intImageHeight) 
		{
			// Get current width and height
			var intCurrentWidth = $('#lightbox-container-image-box').width();
			var intCurrentHeight = $('#lightbox-container-image-box').height();
			// Get the width and height of the selected image plus the padding
			var intWidth = (intImageWidth + (settings.containerBorderSize * 2)); // Plus the image´s width and the left and right padding value
			var intHeight = (intImageHeight + (settings.containerBorderSize * 2)); // Plus the image´s height and the left and right padding value
			// Diferences
			var intDiffW = intCurrentWidth - intWidth;
			var intDiffH = intCurrentHeight - intHeight;

			// Perfomance the effect
			$('#lightbox-container-image-box').animate({ width: intWidth, height: intHeight },settings.containerResizeSpeed,function() { _show_image(); });
			if ( ( intDiffW == 0 ) && ( intDiffH == 0 ) ) {
				if ( $.browser.msie ) {
					___pause(250);
				} else {
					___pause(100);	
				}
			} 

			$('#lightbox-container-image-data-box').css({ width: intImageWidth });
			$('#lightbox-nav-btnPrev,#lightbox-nav-btnNext').css({ height: intImageHeight + (settings.containerBorderSize * 2) });
		};

//		function _update_size_container_image_box(intImageWidth,intImageHeight) 
//		{
//			// Get current width and height
//			var intCurrentWidth = $('#lightbox-container-image-box').width();
//			var intCurrentHeight = $('#lightbox-container-image-box').height();
//			// Get the width and height of the selected image plus the padding
//			var intWidth = (intImageWidth + (settings.containerBorderSize * 2)); // Plus the image´s width and the left and right padding value
//			var intHeight = (intImageHeight + (settings.containerBorderSize * 2)); // Plus the image´s height and the left and right padding value
//			// Diferences
//			var intDiffW = intCurrentWidth - intWidth;
//			var intDiffH = intCurrentHeight - intHeight;
//			// Perfomance the effect
//			$('#lightbox-container-image-box').animate({ width: intWidth, height: intHeight },settings.containerResizeSpeed,function() { _update_image(); });
//			if ( ( intDiffW == 0 ) && ( intDiffH == 0 ) ) {
//				if ( $.browser.msie ) {
//					___pause(250);
//				} else {
//					___pause(100);	
//				}
//			} 
//			$('#lightbox-container-image-data-box').css({ width: intImageWidth });
//			$('#lightbox-nav-btnPrev,#lightbox-nav-btnNext').css({ height: intImageHeight + (settings.containerBorderSize * 2) });
//		};
//
//		function _update_image() {
//			$('#lightbox-loading').hide();
//			$('#lightbox-image').fadeIn();
//		};
//
		/**
		 * Show the prepared image
		 *
		 */
		function _show_image() 
		{
			var container=$("#lightbox-container");
			container.css({width: $('#lightbox-container-image-box').width()});
			
			$('#lightbox-loading').hide();
			$('#lightbox-image').fadeIn(function() {
				_show_image_data();
				_set_navigation();
			});
			_preload_neighbor_images();
		};
		/**
		 * Show the image information
		 *
		 */
		function _show_image_data() {
			$('#lightbox-image-details-caption').hide();
			
			// $("#rf_table").remove("#pricing_row")
			// $("#ex_table").remove("#pricing_row")
			$("tr.pricing_row").remove();
//			$('#rf_table').remove("#pricing_row");
//			$('#ex_table').remove("#pricing_row");
						
			$('#rf_table').hide();
			$('#ex_table').hide();
			$('#group_text').hide();
			$('#lightbox-btnBuy').hide();
			$('#owned_ex').hide();
			$('#owned_rf').hide();
			$('#exclusiveUntile').empty();
			$('#exclusiveUntile').hide();
			$('#ex_table_info').hide();			
			
			
			var container=$("#lightbox-container");
			var containerLeft=$("#lightbox-left-container");
			var containerRight=$("#lightbox-right-container");
			
			var startWidth=$("#lightbox-container-image-box").width();

			//container.css({width: startWidth});
			containerLeft.css({'float': 'left'});
			containerLeft.css({'margin': 0});

			$.getJSON("get_image_attribs.php?id="+settings.imageArray[settings.activeImage], 
				function(json)
				{
					
					var IMAGE_TYPE_ROYALTYFREE=2;
					var IMAGE_TYPE_EXCLUSIVE=3;

					var priceHTML="";
					var priceHTMLEX="";
					var imginfoEX="";
					var bgColor="";
					
					if(json.description)
						$('#lightbox-image-details-caption').html('<code>'+json.description+'</code>').show();
					
					//console.log("owned: "+json.owned);
					//console.log("state: "+json.state);
					if(json.owned && json.state==IMAGE_TYPE_EXCLUSIVE && !json.exclusiveUntil)	
					{
						//console.log('json.exclusiveUntil: '+json.exclusiveUntil);
						$('#owned_rf').show();
						for(i=0;i<json.pricingEX.length;i++)
							{
	
								if(i%2==0)
									bgColor="#ededed"
								else
									bgColor="#ffffff"
									
								priceHTMLEX+=
									'<tr class="pricing_row" bgcolor="'+bgColor+'">'
										+'<td>'
											+'<input type="radio" name="radiogroup" value="'+json.pricingEX[i].period+'"/>'
										+'</td>'
										+'<td>'
											+json.pricingEX[i].period
										+'</td>'
										+'<td>'
											+json.pricingEX[i].credits
										+'</td>'
									+'</tr>'
							}
						$("#ex_table").append(priceHTMLEX);
						$('#ex_table').hide();						
					}	
					else if(json.owned)
						$('#owned_ex').show();

						
					if(json.exclusiveUntil && !json.owned)	
					{
						$("#exclusiveUntile").append('Tази снимка е купена exclusive до: <code>'+json.exclusiveUntil+'</code>');
						$('#exclusiveUntile').show();
					}
					
					$("#fav_span").remove();
					//$("#fav_span").hide();
					if(json.fav_img!=null)
						if(!json.fav_img)
							$("#lightbox-secNav").append('<div id="fav_span"><a href="#" class="save_img" onclick="saveImage('+settings.imageArray[settings.activeImage]+')"><img id="fav'+settings.imageArray[settings.activeImage]+'_" src="img/favboximg.jpg" border="0"></a><a href="#"  class="save_img" onclick="dellImage('+settings.imageArray[settings.activeImage]+')"><img  id="favimg'+settings.imageArray[settings.activeImage]+'_" src="img/favboximgon.jpg" border="0" style="display:none"></a></span>');
						else
							$("#lightbox-secNav").append('<div id="fav_span"><a href="#" class="save_img" onclick="dellImage('+settings.imageArray[settings.activeImage]+')"><img id="favimg'+settings.imageArray[settings.activeImage]+'_" class="save_img" src="img/favboximgon.jpg" border="0"></a><a href="#" class="save_img" onclick="saveImage('+settings.imageArray[settings.activeImage]+')"><img id="fav'+settings.imageArray[settings.activeImage]+'_" src="img/favboximg.jpg" border="0" style="display:none"></a></span>');
																
					if(!json.owned)
					{
						var imageResolution;
						var imageRatio;
						var imageIsPortrait=false;
						var i,j=0,width,height;
						
						
						
						if(json.width<json.height)
						{
							imageIsPortrait=true;
							imageRatio=json.height/json.width;
							imageResolution=json.width;
						}
						else
						{
							imageRatio=json.width/json.height;
							imageResolution=json.height;
						}
						
						
						//console.log("state: "+json.state)

						if(json.state==IMAGE_TYPE_ROYALTYFREE)
						{
							//Martin - ot nai-goliamata kam nai-malkata
							//for(i= 0; i<json.pricing.length;i++)
							//alert(json.pricing.length);
							bgColor='#ededed';
							
							for(i=parseInt(json.pricing.length)-1;i>=0;i--)
							{
								//console.log("Test");
								if(json.pricing[i].resolution<=imageResolution)
								{
										
//									if(imageIsPortrait)
//									{
//										width=json.pricing[i].resolution;
//										height=Math.round(width*imageRatio);
//									}
//									else
//									{
//										height=json.pricing[i].resolution;
//										width=Math.round(height*imageRatio);
//									}

									priceHTML+=
										'<tr class="pricing_row" bgcolor="'+bgColor+'">'
											+'<td>'
												+'<input type="radio" class="test" name="radiogroup" value="'+json.pricing[i].resolution+'"/>'
											+'</td>'
											+'<td>'
												+json.width+" x "+json.height
												+" ("+Math.round((json.width*json.height/10000))/100+" MP)"
											+'</td>'
											+'<td>'
												+Math.round((json.width/json.pricing[i].dpi)*2.54)+" x "+Math.round((json.height/json.pricing[i].dpi)*2.54)+' @ '+json.pricing[i].dpi+' dpi'
											+'</td>'
											+'<td>'
												+json.pricing[i].credits
											+'</td>'
										+'</tr>'
									//Martin - da se pokazva samo edin rezultat	
									break;		
								}

							}
							
							
							if(!priceHTML)
							{
								priceHTML+=
									'<tr class="pricing_row" bgcolor="'+bgColor+'">'
										+'<td>'
											+'<input type="radio" class="test" name="radiogroup" value="'+json.pricing[0].resolution+'"/>'
										+'</td>'
										+'<td>'
											+json.width+" x "+json.height
											+" ("+Math.round((json.width*json.height/10000))/100+" MP)"
										+'</td>'
										+'<td>'
											+Math.round((json.width/json.pricing[0].dpi)*2.54)+" x "+Math.round((json.height/json.pricing[0].dpi)*2.54)+' @ '+json.pricing[0].dpi+' dpi'
										+'</td>'
										+'<td>'
											+json.pricing[0].credits
										+'</td>'
									+'</tr>'
							}	
							
							$("#rf_table").append(priceHTML);
							$('#rf_table').show();
							//$('#lightbox-btnBuy').show();
							
						}
						else if(json.state==IMAGE_TYPE_EXCLUSIVE)
//						{
						{
							//console.log("Test"+json.state+" "+IMAGE_TYPE_ROYALTYFREE);
							for(i=0;i<json.pricingEX.length;i++)
							{
	
								if(i%2==0)
									bgColor="#ededed"
								else
									bgColor="#ffffff"
									
								priceHTMLEX+=
									'<tr class="pricing_row" bgcolor="'+bgColor+'">'
										+'<td>'
											+'<input type="radio" name="radiogroup" value="'+json.pricingEX[i].period+'"/>'
										+'</td>'
										+'<td>'
											+json.pricingEX[i].period
										+'</td>'
										+'<td>'
											+json.pricingEX[i].credits
										+'</td>'
									+'</tr>';
									

							}
						}
						else if(json.group)
						{
							$('#group_text').show();
							for(i=0;i<json.pricingEX.length;i++)
							{
	
								if(i%2==0)
									bgColor="#ededed"
								else
									bgColor="#ffffff"
									
								//credits=Math.round((json.pricingEX[i].credits*json.group.length)-((json.pricingEX[i].credits*json.group.length)*json.discount)/100)
								//alert(json.pricingEX[i].credits)
								priceHTMLEX+=
									'<tr class="pricing_row" bgcolor="'+bgColor+'">'
										+'<td>'
											+'<input type="radio" name="radiogroup" value="'+json.pricingEX[i].period+'"/>'
										+'</td>'
										+'<td>'
											+json.pricingEX[i].period
										+'</td>'
										+'<td>'
											+json.pricingEX[i].credits
										+'</td>'
									+'</tr>'
							}							
						}
						
						
						if(json.state!=IMAGE_TYPE_ROYALTYFREE && json.state!=IMAGE_TYPE_EXCLUSIVE)
						{
							imginfoEX+=
								'<tr class="pricing_row" bgcolor="#ededed">'
									+'<td>'
										+json.width+' x '+json.height
										+" ("+Math.round((json.width*json.height/10000))/100+" MP)"
									for(n=parseInt(json.pricing.length)-1;n>=0;n--)
									{
										//console.log(n+' '+json.pricing[n].resolution+' <= '+imageResolution)
										if(json.pricing[n].resolution<=imageResolution)
										{
											//console.log(n)
											imginfoEX+=
											'<td>'
												+Math.round((json.width/json.pricing[n].dpi)*2.54)+" x "+Math.round((json.height/json.pricing[n].dpi)*2.54)+' @ '+json.pricing[n].dpi+' dpi'
											+'</td>'
											break;
										}
									}
									

								imginfoEX+=										
								'</tr>';	
							//console.log("Test"+json.state+" "+IMAGE_TYPE_ROYALTYFREE);	
							
							$("#ex_table_info").append(imginfoEX);
							$('#ex_table_info').show();
							
							
						}
						else if(json.state!=IMAGE_TYPE_ROYALTYFREE)
						{	
							//console.log("width: "+json.width);		
							imginfoEX+=
								'<tr class="pricing_row" bgcolor="#ededed">'
									+'<td>'
										+json.width+' x '+json.height
										+" ("+Math.round((json.width*json.height/10000))/100+" MP)"
									for(n=parseInt(json.pricing.length)-1;n>=0;n--)
									{
										//console.log(n+' '+json.pricing[n].resolution+' <= '+imageResolution)
										if(json.pricing[n].resolution<=imageResolution)
										{
											//console.log(n)
											imginfoEX+=
											'<td>'
												+Math.round((json.width/json.pricing[n].dpi)*2.54)+" x "+Math.round((json.height/json.pricing[n].dpi)*2.54)+' @ '+json.pricing[n].dpi+' dpi'
											+'</td>'
											break;
										}
									}
									

								imginfoEX+=										
								'</tr>';	
							//console.log("Test"+json.state+" "+IMAGE_TYPE_ROYALTYFREE);	
							$("#ex_table").append(priceHTMLEX);
							$('#ex_table').show();
							
							$("#ex_table_info").append(imginfoEX);
							$('#ex_table_info').show();
							
							
						}	
						
						//alert("da"+json.fav_img)
						if((json.state==IMAGE_TYPE_ROYALTYFREE || json.state==IMAGE_TYPE_EXCLUSIVE) && json.can_buy_picture)							
							$('#lightbox-btnBuy').show();
//						}	
					}
					
					
					$('#lightbox-container-image-data-box').slideDown('fast',
						function()
						{
//							if(containerRight.height()>=$("#lightbox-container-image-box").height())
//								containerRight.css({height: containerLeft.height()});
							if(json.group)
								if(json.group.length>1)
								{
									
									var endWidth=startWidth+120;
									
									var counter=0;
									var repeatCount=10;
									var currentWidth=startWidth;
									settings.intervalID=setInterval(
										function()
										{
											if(settings.intervalID==0)
												return true;
												
											counter++;
											if(counter>repeatCount)
											{
												if(settings.intervalID!=0)
												{
													clearInterval(settings.intervalID);
													settings.intervalID=0;
												}
												container.css({width: endWidth});
												containerRight.css({height: containerLeft.height()});
												containerRight.css({width: endWidth-startWidth});
												
												
												var groupScrollIntervalID=0;
												var GROUP_IMAGES_SCROLL_SIZE=7;
														
												//ToDO scroll
												jQuery('<a><img src="img/up_group.jpg" style="margin: 5px auto"/></a>').appendTo(containerRight).hover(
													function()
													{
														var imgContainer=$("#group-images-container");
														var groupImagesPanel=$("#group-images-panel");
														
														if(groupScrollIntervalID)
														{
															clearInterval(groupScrollIntervalID);
															groupScrollIntervalID=0;
														}
														
														if(imgContainer.get(0).offsetTop<0)
														{
															groupScrollIntervalID=setInterval(function() {
																if(imgContainer.get(0).offsetTop+GROUP_IMAGES_SCROLL_SIZE>=0) //Stop scrolling, scrollable content is less then scrolling window
																{
																	clearInterval(groupScrollIntervalID);
																	groupScrollIntervalID=0;

																	imgContainer.css({"top": 0});
																	return false;
																}

																imgContainer.css({"top": imgContainer.get(0).offsetTop+GROUP_IMAGES_SCROLL_SIZE});

															} ,1);
														}
														
													},
													function() {
														if(groupScrollIntervalID)
														{
															clearInterval(groupScrollIntervalID);
															groupScrollIntervalID=0;
														}
													}
												);
												jQuery('<div id="group-images-panel" style="overflow: hidden; position: relative;"><div id="group-images-container" style="position: relative;"/></div>').appendTo(containerRight).css({height: containerLeft.height()-60});
												var imgContainer=$("#group-images-container");
												
												jQuery('<a ><img src="img/down_group.jpg" style="margin: 5px auto"/></a>').appendTo(containerRight).hover(
													function()
													{
														var imgContainer=$("#group-images-container");
														var groupImagesPanel=$("#group-images-panel");
														
														if(groupScrollIntervalID)
														{
															clearInterval(groupScrollIntervalID);
															groupScrollIntervalID=0;
														}
														
														if(groupImagesPanel.height()<(imgContainer.height()+imgContainer.get(0).offsetTop))
														{
															groupScrollIntervalID=setInterval(
																function()
																{
																	if(groupImagesPanel.height()+GROUP_IMAGES_SCROLL_SIZE>=(imgContainer.height()+imgContainer.get(0).offsetTop)) //Stop scrolling, scrollable content is less then scrolling window
																	{
																		clearInterval(groupScrollIntervalID);
																		groupScrollIntervalID=0;
																		
																		imgContainer.css({"top": -imgContainer.height()+groupImagesPanel.height()});
																		return false;
																	}
																	
																	imgContainer.css({"top": imgContainer.get(0).offsetTop-GROUP_IMAGES_SCROLL_SIZE});
																	
																}
															,1);
														}
														
													},
													function() {
														if(groupScrollIntervalID) {
															clearInterval(groupScrollIntervalID);
															groupScrollIntervalID=0;
														}
													}
												);
								
												i=0;
												var desiredPos=0;
												var groupImageID=json.group[i++];
												var objImagePreloader = new Image();
												objImagePreloader.onload = function() {
													var isGroupImageSelected=settings.imageArray[settings.activeImage] == groupImageID
													var groupImage=jQuery('<a style="position: relative; display: block;"><img src="'+objImagePreloader.src+'" id="'+groupImageID+'" class="groupImage" style="'+(isGroupImageSelected?'margin: 0px auto; border: 2px solid #999999; padding: 3px':'margin: 5px auto;')+'" /></a>').hide().appendTo(imgContainer).fadeIn();
	
													var groupImagesPanel=$("#group-images-panel");
													if(isGroupImageSelected)
														desiredPos=groupImagesPanel.height()/2-(groupImage.get(0).offsetTop+groupImage.height()/2);

													if(i<json.group.length) {
														groupImageID=json.group[i++];
														objImagePreloader.src = 'get_image.php?id='+groupImageID+'&size=1';
													}
													else {
														imgContainer.animate({"top": desiredPos>0?0:(desiredPos<(groupImagesPanel.height()-imgContainer.height())?groupImagesPanel.height()-imgContainer.height():desiredPos)});
														
														objImagePreloader.onload=function(){};
														
														$("img.groupImage").bind('click',
															function() 
															{
																settings.imageArray[settings.activeImage]=this.id;
																_set_image_to_view();
																
																return false;
															} );
													}
													
													return false;
												};
												objImagePreloader.src = 'get_image.php?id='+groupImageID+'&size=1';
												
												
						 						return true;
											}
											
											currentWidth+=(endWidth-currentWidth)/2;
											container.css({width: currentWidth});
											containerLeft.css({width: startWidth});
											containerRight.css({height: containerLeft.height()});
											containerRight.css({width: currentWidth-startWidth-1});
											
											return true;
										}
									,5);
								}
						}
					);
				}
			);

//			if ( settings.imageArray[settings.activeImage][1] ) {
//				$('#lightbox-image-details-caption').html(settings.imageArray[settings.activeImage][1]).show();
//			}
			// If we have a image set, display 'Image X of X'
			if ( settings.imageArray.length > 1 ) {
				$('#lightbox-image-details-currentNumber').html(settings.txtImage + ' ' + ( settings.activeImage + 1 ) + ' ' + settings.txtOf + ' ' + settings.imageArray.length).show();
			}		
		}
		/**
		 * Display the button navigations
		 *
		 */
		function _set_navigation() {
			$('#lightbox-nav').show();

			// Instead to define this configuration in CSS file, we define here. And it´s need to IE. Just.
			$('#lightbox-nav-btnPrev,#lightbox-nav-btnNext').css({ 'background' : 'transparent url(' + settings.imageBlank + ') no-repeat' });
			
			// Show the prev button, if not the first image in set
			if ( settings.activeImage != 0 ) {
				if ( settings.fixedNavigation ) {
					$('#lightbox-nav-btnPrev').css({ 'background' : 'url(' + settings.imageBtnPrev + ') left 15% no-repeat' })
						.unbind()
						.bind('click',function() {
							settings.activeImage = settings.activeImage - 1;
							_set_image_to_view();
							return false;
						});
				} else {
					// Show the images button for Next buttons
					$('#lightbox-nav-btnPrev').unbind().hover(function() {
						$(this).css({ 'background' : 'url(' + settings.imageBtnPrev + ') left 15% no-repeat' });
					},function() {
						$(this).css({ 'background' : 'transparent url(' + settings.imageBlank + ') no-repeat' });
					}).show().bind('click',function() {
						settings.activeImage = settings.activeImage - 1;
						_set_image_to_view();
						return false;
					});
				}
			}
			
			// Show the next button, if not the last image in set
			if ( settings.activeImage != ( settings.imageArray.length -1 ) ) {
				if ( settings.fixedNavigation ) {
					$('#lightbox-nav-btnNext').css({ 'background' : 'url(' + settings.imageBtnNext + ') right 15% no-repeat' })
						.unbind()
						.bind('click',function() {
							settings.activeImage = settings.activeImage + 1;
							_set_image_to_view();
							return false;
						});
				} else {
					// Show the images button for Next buttons
					$('#lightbox-nav-btnNext').unbind().hover(function() {
						$(this).css({ 'background' : 'url(' + settings.imageBtnNext + ') right 15% no-repeat' });
					},function() {
						$(this).css({ 'background' : 'transparent url(' + settings.imageBlank + ') no-repeat' });
					}).show().bind('click',function() {
						settings.activeImage = settings.activeImage + 1;
						_set_image_to_view();
						return false;
					});
				}
			}
			// Enable keyboard navigation
			_enable_keyboard_navigation();
		}
		/**
		 * Enable a support to keyboard navigation
		 *
		 */
		function _enable_keyboard_navigation() {
			$(document).keydown(function(objEvent) {
				_keyboard_action(objEvent);
			});
		}
		/**
		 * Disable the support to keyboard navigation
		 *
		 */
		function _disable_keyboard_navigation() {
			$(document).unbind();
		}
		/**
		 * Perform the keyboard actions
		 *
		 */
		function _keyboard_action(objEvent) {
			// To ie
			if ( objEvent == null ) {
				keycode = event.keyCode;
				escapeKey = 27;
			// To Mozilla
			} else {
				keycode = objEvent.keyCode;
				escapeKey = objEvent.DOM_VK_ESCAPE;
			}
			// Get the key in lower case form
			key = String.fromCharCode(keycode).toLowerCase();
			// Verify the keys to close the ligthBox
			if ( ( key == settings.keyToClose ) || ( key == 'x' ) || ( keycode == escapeKey ) ) {
				_finish();
			}
			// Verify the key to show the previous image
			if ( ( key == settings.keyToPrev ) || ( keycode == 37 ) ) {
				// If we´re not showing the first image, call the previous
				if ( settings.activeImage != 0 ) {
					settings.activeImage = settings.activeImage - 1;
					_set_image_to_view();
					_disable_keyboard_navigation();
				}
			}
			// Verify the key to show the next image
			if ( ( key == settings.keyToNext ) || ( keycode == 39 ) ) {
				// If we´re not showing the last image, call the next
				if ( settings.activeImage != ( settings.imageArray.length - 1 ) ) {
					settings.activeImage = settings.activeImage + 1;
					_set_image_to_view();
					_disable_keyboard_navigation();
				}
			}
		}
		/**
		 * Preload prev and next images being showed
		 *
		 */
		function _preload_neighbor_images() {
			if ( (settings.imageArray.length -1) > settings.activeImage ) {
				objNext = new Image();
				objNext.src = 'get_image.php?id='+settings.imageArray[settings.activeImage + 1]+'&size=3';
			}
			if ( settings.activeImage > 0 ) {
				objPrev = new Image();
				objPrev.src = 'get_image.php?id='+settings.imageArray[settings.activeImage - 1]+'&size=3';
			}
		}
		/**
		 * Remove jQuery lightBox plugin HTML markup
		 *
		 */
		function _finish() {
			$('#jquery-lightbox').remove();
			$('#jquery-overlay').fadeOut(function() { $('#jquery-overlay').remove(); });
			// Show some elements to avoid conflict with overlay in IE. These elements appear above the overlay.
			$('embed, object, select').css({ 'visibility' : 'visible' });
		}
		/**
		 / THIRD FUNCTION
		 * getPageSize() by quirksmode.com
		 *
		 * @return Array Return an array with page width, height and window width, height
		 */

		function ___getPageSize() {
			var xScroll, yScroll;
			
			//console.log("innerWidth: "+window.innerWidth+", scrollMaxX: "+window.scrollMaxX+", scrollWidth: "+document.body.scrollWidth+", offsetWidth: "+document.body.offsetWidth);
			//console.log("innerHeight: "+window.innerHeight+", scrollMaxY: "+window.scrollMaxY+", scrollHeight: "+document.body.scrollHeight+", offsetHeight: "+document.body.offsetHeight);
			//console.log("self.innerWidth: "+self.innerWidth+", clientWidth: "+document.documentElement.clientWidth+", body.clientWidth: "+document.body.clientWidth);
			//console.log("self.innerHeight: "+self.innerHeight+", clientHeight: "+document.documentElement.clientHeight+", body.clientHeight: "+document.body.clientHeight);
			
			//patch: Smash
			pageWidth=Math.max(
				(window.innerWidth && window.scrollMaxX?(window.innerWidth + window.scrollMaxX - (window.scrollMaxY && window.innerWidth && document.documentElement && document.documentElement.clientWidth?window.innerWidth-document.documentElement.clientWidth:0)):0),
				document.documentElement && document.documentElement.clientWidth?document.documentElement.clientWidth:0,
				document.body?document.body.clientWidth:0,
				document.body.scrollWidth,
				document.body.offsetWidth
			)
			pageHeight=Math.max(
				(window.innerHeight && window.scrollMaxY?(window.innerHeight + window.scrollMaxY - (window.scrollMaxX && window.innerHeight && document.documentElement && document.documentElement.clientHeight?window.innerHeight-document.documentElement.clientHeight:0)):0),
				document.documentElement && document.documentElement.clientHeight?document.documentElement.clientHeight:0,
				document.body?document.body.clientHeight:0,
				document.body.scrollHeight,
				document.body.offsetHeight
			)
			
			windowWidth=Math.max(
				(window.innerWidth && window.scrollMaxX?(window.innerWidth - (window.scrollMaxY && window.innerWidth && document.documentElement && document.documentElement.clientWidth?window.innerWidth-document.documentElement.clientWidth:0)):0),
				document.documentElement && document.documentElement.clientWidth?document.documentElement.clientWidth:0,
				document.body?document.body.clientWidth:0
			)
			windowHeight=Math.max(
				(window.innerHeight && window.scrollMaxY?(window.innerHeight - (window.scrollMaxX && window.innerHeight && document.documentElement && document.documentElement.clientHeight?window.innerHeight-document.documentElement.clientHeight:0)):0),
				document.documentElement && document.documentElement.clientHeight?document.documentElement.clientHeight:0,
				document.body?document.body.clientHeight:0
			)

			arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight);
			return arrayPageSize;
		};
		/**
		 / THIRD FUNCTION
		 * getPageScroll() by quirksmode.com
		 *
		 * @return Array Return an array with x,y page scroll values.
		 */
		function ___getPageScroll() {
			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;	
			}
			arrayPageScroll = new Array(xScroll,yScroll);
			return arrayPageScroll;
		};
		 /**
		  * Stop the code execution from a escified time in milisecond
		  *
		  */
		 function ___pause(ms) {
			var date = new Date(); 
			curDate = null;
			do { var curDate = new Date(); }
			while ( curDate - date < ms);
		 };
		// Return the jQuery object for chaining. The unbind method is used to avoid click conflict when the plugin is called more than once
		return this.unbind('click').click(_initialize);
	};
})(jQuery); // Call and execute the function immediately passing the jQuery object
