jQuery.fn.extend({
	overlay: function(){
		if(this){
			var overlay = $('.overlay'),
			box = $('.pp-gallery'),
			is_photo = null,
			photo = null,
			photos = null,
			photo_captions = null,
			video = null;
				
			var __init = function(){
				if(box.hasClass('pp-gallery-video')){
					is_photo = false;
				}else{
					is_photo = true;
				}
				
				overlay.click(function(){
					$.historyLoad('close');
				});
			   
				$(document).keydown(function(e){
					if(overlay.is(':visible')){
						switch(e.keyCode){
							case 27:
								closeLayout();
								break;
						};
					}
				});
			}

			var parseHash = function(hash){
				url = __deparam( hash, true );
				if (url['photo'] != undefined){
					photo = parseInt(url['photo']);
					if(photo > 0){
						openGallery();
					}
				}else if(url['video'] != undefined){
					video = parseInt(url['video']);
					if(video > 0){
						openGallery();
					}
				}
			}

			var openGallery = function(){
				showLayout();
				if(is_photo)
				{
					showPhotoBox();
				}
				else
				{
					showVideoBox();
				}
			}

			var showLayout = function(){
				if(overlay.is(':hidden'))
				{
					overlay.show(400);
				}
			}

			var showPhotoBox = function(){
				if(box.find('.pp-gallery-header').length)
				{
					if(box.is(':hidden'))
					{
						initBox();
					}
					showPhoto();
				}
				else
				{
					box.load(document.location.pathname+'data/tpl-overlay_photogallery/', function(){
						if(is_photo){
							photos = box.find('.pp-photo-img');
							photo_captions = box.find('.pp-photo-caption');
							box.find('.ar-l').click(function(){
								curr = photos.index(photos.filter('#photo-'+photo));
								if(curr == 0)
								{
									curr = photos.length-1;
								}else{
									curr = curr-1;
								}
								$.historyLoad('photo='+photos.eq(curr).attr('rel'));
								return false;
							});
							box.find('.ar-r').click(function(){
								curr = photos.index(photos.filter('#photo-'+photo));
								if(curr == (photos.length-1)){
									curr = 0;
								}else{
									curr = curr+1;
								}
								$.historyLoad('photo='+photos.eq(curr).attr('rel'));
								return false;
							});
						}
						initBox();
						showPhoto();
					});
				}
			}

			var showVideoBox = function(){
				box.load(document.location.pathname+'data/'+video+'/tpl-overlay_video/', function(){
					initBox();
					if($('.b-add-comment-form input[name=open_hash]').length){
						$('.b-add-comment-form input[name=open_hash]').val('video='+video);
						$('.b-add-comment').attr('action', document.location.href);
					}
				});
			}
			
			var initBox = function(){
				if($('.link-opencomment').length) {
					$('.link-opencomment').click(function(){
						$(this).parent().parent().toggleClass('active-addcomment');
						return false;
					});
					$('.b-add-comment .close').click(function(){
						$(this).parent().toggleClass('active-addcomment');
						return false;
					});
				}
				if($('#comment_form').length){
					$('#comment_form').submit(function(){
						var result = true;

						if(!$('#comment_name').validatorLength(2,200))
						{
							result = false;
						}
						if(!$('#comment_message').validatorLength(2,2000))
						{
							result = false;
						}
						if(!$('#comment_captcha').validatorLength(5,5))
						{
							result = false;
						}

						if(result)
						{
							$('#comment_form_error').hide();
						}
						else
						{
							$('#comment_form_error').html('Пожалуйста, заполните все поля!').css('color', '#FF5555').show();
						}

						return result;
					});
				}
				box.css({"top":($(document).scrollTop() + 20)});
				box.find('.pp-close').click(function(){
					$.historyLoad('close');
				});
				if(!is_photo){
					swfobject.embedSWF("/webroot/delivery/flash/rr_video_player.swf", "video_player", "426", "345", "9.0.0", false, {video_url: $('.pp-gallery-player').attr('rel'), thumb_url: $('.pp-gallery-player').attr('rev')}, {allowfullscreen: 'true', quality: 'high', background:"#ffffff"});
				}
				box.show(400);
				try{box.find('.vk-social').html(VK.Share.button(box.find('.vk-social').attr('rel'),{type: "button", text: "Сохранить"}));}catch(e){};	
			}

			var showPhoto = function(){
				//632
				$index = box.find('.photo-area__ul li').index(photos.filter('#photo-'+photo).parent().parent());
				box.find('.photo-area__ul').animate({right: ($index*632)+'px', height: photos.filter('#photo-'+photo).parent().parent().css('height')},500);
				box.find('.pp-photo-area').animate({height: photos.filter('#photo-'+photo).parent().parent().css('height')}, 500);
				photo_captions.html(photos.filter('#photo-'+photo).find('img').attr('alt'));
				if($('.b-add-comment-form input[name=open_hash]').length){
					$('.b-add-comment-form input[name=open_hash]').val('photo='+photo);
					$('.b-add-comment').attr('action', document.location.href);
				}
			}
		
			var closeLayout = function(){
				if(overlay.is(':visible')){
					player = 0;
					overlay.hide(400);
					box.hide(400);
				}
			}

			var __popen = function(url, name, w, h){
	             w += 32;
	             h += 96;
	             var win = window.open(url, name, 'width=' + w + ', height=' + h + ', ' +  'location=no, menubar=no, ' + 'status=no, toolbar=no, scrollbars=no, resizable=no');
	             win.resizeTo(w, h);
	             win.focus();
	        }

			var __wopen = function(url){
				window.open(url);
	        }

			var __deparam = function(params, coerce){
				var obj = {}, coerce_types = {
					'true': !0,
					'false': !1,
					'null': null
				};
				$.each( params.replace( /\+/g, ' ' ).split( '|' ), function(j,v){
					var param = v.split( '=' ),
					key = decodeURIComponent( param[0] ),
					val,
					cur = obj,
					i = 0,
					keys = key.split( '][' ),
					keys_last = keys.length - 1;

					if ( /\[/.test( keys[0] ) && /\]$/.test( keys[ keys_last ] ) ) {
						keys[ keys_last ] = keys[ keys_last ].replace( /\]$/, '' );
						keys = keys.shift().split('[').concat( keys );
						keys_last = keys.length - 1;
					} else {
						keys_last = 0;
					}
					if ( param.length === 2 ) {
						val = decodeURIComponent( param[1] );
						if ( coerce ) {
							val = val && !isNaN(val) ? +val
							: val === 'undefined' ? undefined
							: coerce_types[val] !== undefined ? coerce_types[val]
							: val;
						}
						if ( keys_last ) {
							for ( ; i <= keys_last; i++ ) {
								key = keys[i] === '' ? cur.length : keys[i];
								cur = cur[key] = i < keys_last
								? cur[key] || ( keys[i+1] && isNaN( keys[i+1] ) ? {} : [] )
								: val;
							}
						} else {
							if ( $.isArray( obj[key] ) ) {
								obj[key].push( val );
							} else if ( obj[key] !== undefined ) {
								obj[key] = [ obj[key], val ];
							} else {
								obj[key] = val;
							}
						}
					} else if ( key ) {
						obj[key] = coerce
						? undefined
						: '';
					}
				});
				return obj;
			}

			__init();

			return {
				parseHash: function (hash) {
					parseHash(hash);
				},
				closeLayout: function () {
					closeLayout();
				}
			}
		}
	}
});
