/**********************************************************************************************
!!! 1. файл автоматически копируется из Vko.Common.BusinessLogic.js_resources !!!
!!! 2. PreBuildEvent проверяет имя солюшена и копирует этот файл только для солюшена Vko !!!
!!! 3. TFS не почувствует изменения файлов, скопированных на PreBuildEvent в сайты, поэтому 
нужно вручную зачекинить *site\js\all.js после изменения этого файла !!!
***********************************************************************************************/

(function($){
	
	$.extend($.fn, {
		png: function(){
			if($.browser.msie && $.browser.version < 7){
				this.each( function(){
					if(this.tagName == 'IMG') {
						if (/\.png$/.test(this.src)) {
							src = this.src;
							this.src = "/e.gif";
						}
					}else{
						src = this.currentStyle.backgroundImage
								.match(/url\("(.+\.png)"\)/i);
						if(src){
							src = src[1];
							this.runtimeStyle.backgroundImage = "none";
						}
						
						var re_scale_mode = /iesizing\-(\w+)/;
						var m = re_scale_mode.exec(this.className);

						var scale_mode = (m) ? m[1] : 'crop';

						if(src)
							this.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"
								+ src + "',sizingMethod='" + scale_mode + "')";
					}
				});
			}
			return this;
		}
	});
	
	$(document).ready(function(){
		$('.ie6-png').png();
	});
	
	intCSS = function(el, prop) {
		return parseInt($(el).css(prop))||0;
	};

	Number.prototype.roundTo = function(to){
		return Math.round(this/to)*to;
	}	
	
	$.extend(Array.prototype, {
		min: function(){
			return Math.min.apply({},this);
		},
		
		max: function(){
			return Math.max.apply({},this);
		},
		
		sum: function(){
			for(var i = 0, sum = 0; i < this.length; sum += this[i++]);
			return sum;
		},
		
		swap: function(a, b){
			if(!this[a] || !this[b]) return false;
			var i = this[a];
			this[a] = this[b];
			this[b] = i;
			
			return true;
		}
	});
	
	/*
		слои контролируют порядок появления всех всплывающих вещей (попапы, выпадающие меню, дейтпикеры и тп),
		управляют кнопкой Esc (закрывается только верхний слой),
		отключают табуляцию в нижних слоях и в документе, если есть верхние слои
	*/
	
	$.layers = (function(){
		var _zindex = 99999,
			_layers = {},
			_index = 1;
		
		//	по ескейпу выполняем функцию, которая пришла в аргументе esc из последнего слоя
		$(document).bind('keydown.layers', function(e){
			if(e.keyCode == 27){
				for(var i in _layers);
				
				if(_layers[i] && _layers[i].esc && $.isFunction(_layers[i].esc)) _layers[i].esc();
			}
		});
		
		//	IE7,8 на radiobutton не действует tabindex = -1, обработаетм его отдельно
		
		if($.browser.msie)
			$(document).ready(function(){
				$('input[type="radio"]').bind('focus', function(){
					if($(this).attr('underlayer'))
						this.blur();
				});
			});
		
		
		//	добавляем слой в список слоев
		__push = function(elements, esc){
			
			//	расставляем глобально z-index
			elements.each(function(){
				this.style.zIndex = _zindex++;
			}).addClass('layer-' + _index);
			
			//	отключаем tab-навигацию у нижних слоев
			var disablians = $('a, input, textarea, button, select').filter(function(){
				var $this = $(this);
				if($this.is(':hidden') || $this.is('[underlayer]') || $this.closest('.layer-' + _index).length) return false;
				var tabindex = parseInt($this.attr('tabindex'));
				if(tabindex >= 0){
					$this.attr('tabindex', '-1').attr('underlayer', tabindex);
					return true;
				}
				return false;
			});
			
			_layers[_index] = {
				elements: elements,
				esc: esc,
				disablians: disablians
			};
			_index++;

			return _index -1;
		};
		
		__pop = function(index){
			if(!index) index = _index-1;
			
			_layers[index].elements.removeClass('layer-' + _index);
			_layers[index].disablians.each(function(){
				var $this = $(this),
					tabindex = $this.attr('underlayer');
					
				$this.attr('tabindex', tabindex).removeAttr('underlayer');
			});
			
			delete _layers[index];
		}
		
		return {
			push: __push,
			pop: __pop
		}
	})();
	
	
	_resizeOverlays= function(overlays){
		overlays.hide();
		$('iframe.overlay-iframe').hide();
		
		setTimeout(function(){
			if ($.browser.msie && $.browser.version < 7) {
				var scrollWidth = Math.max(
					document.documentElement.scrollWidth,
					document.body.scrollWidth
				);
				var offsetWidth = Math.max(
					document.documentElement.offsetWidth,
					document.body.offsetWidth
				);

				if (scrollWidth < offsetWidth) 
					var width =  $(window).width() + 'px';
				else var width = scrollWidth + 'px';
				
			} else var width = $(document).width() + 'px';
			
			if ($.browser.msie && $.browser.version < 7) {
				var scrollHeight = Math.max(
					document.documentElement.scrollHeight,
					document.body.scrollHeight
				);
				var offsetHeight = Math.max(
					document.documentElement.offsetHeight,
					document.body.offsetHeight
				);

				if (scrollHeight < offsetHeight) 
					var height = $(window).height() + 'px';
				else var height = scrollHeight + 'px';
				
			} else var height = $(document).height() + 'px';
			
			overlays.each(function(){
				var $this = $(this),
					iframe = $this.data('overlay-iframe');
				
				$this.width(width);
				$this.height(height);
				if(iframe){
					iframe.width(width);
					iframe.height(height);
				}
			});
			overlays.show();
			$('iframe.overlay-iframe').show();
		}, 0);
		
	};
	
	$(window).resize(function(){
		_resizeOverlays($('.overlay'));
	});

	$.overlay = function(options){
		var settings = $.extend({ color: '#000', opacity: .5 }, options);
		var div = $('<div class="overlay" />').css({
			'position': 'absolute',
			'left': 0,
			'top': 0,
			'background-color': settings.color,
			'opacity': settings.opacity
		});
		
		
		if ($.browser.msie && $.browser.version < 7){
			var iframe = $('<iframe class="overlay-iframe" />').css({
				'position': 'absolute',
				'left': 0,
				'top': 0,
				'opacity': 0
			});
			
			div.data('overlay-iframe', iframe);
		}
		
		_resizeOverlays(div);
		
		return div;
	};
	
	$.extend($.fn, {
		popup: function(options){
			return this.each(function(){
				if($(this).data('popup')){
					var popup = $(this).data('popup');
					$.extend(true, popup.settings, options);
				}else $(this).data('popup', new Popup(this, options));
			});
		},
		
		
		placeholder: function(){
			var handleInput = function(input){
				if(!input.attr('disabled')){
					
					if($.browser.safari){
						if(!input.val().length)
							input.addClass('placeholder');
					} else {
						if(!input.val().length)
							input.hide().data('input-clone').show();
					}
					
				}
			};

			this.each(function(){
				var $this = $(this);
				
				if(!$.browser.safari){
					$this.wrap('<div></div>');
					var div = $this.parent(),
						clone = $('<input type="text" class="input-login" value="'+$this.attr('placeholder')+'" />').
							addClass('placeholder').
							attr('style', $this.attr('style')).
							hide().
							data('input-original', $this).
							appendTo(div);
					$this.data('input-clone', clone);
					$this.add(clone).insertAfter(div);
					div.remove();
					
					clone.focus(function(){
						$(this).hide().data('input-original').show().focus();
					});
					
					handleInput($this);
					
				} else {
					if(!$this.val().length)
						$this.addClass('placeholder');
				}
				
				//handleInput($this);
				
			});
			
			
			
			this.focus(function(){
				var input = $(this);
				if($.browser.safari){
					input.removeClass('placeholder');
				}
				
			}).blur(function(){
				var input = $(this);
				if($.browser.safari){
					if(!input.val().length)
						input.addClass('placeholder');
				}else handleInput(input);
			});

		}
	});
	
	$(document).ready(function(){
		$('input[placeholder]').placeholder();
	});

	Popup = function(elem, options){
		this.elem = $(elem);
		this.settings = $.extend(true, {
			esc: true,
			close: false,
			dd: false,
			width: '400px',
			container: 'body'
		}, options);
		
		this.div = $('<div class="popup"><table cellspacing="0" class="popup-table">\
			<thead>\
				<tr>\
					<td class="l png"></td>\
					<td class="c png"></td>\
					<td class="r png"></td>\
				</tr>\
			</thead>\
			<tbody>\
				<tr>\
					<td class="l png"></td>\
					<td class="c png">\
						<div class="popup-content"></div>\
					</td>\
					<td class="r png"></td>\
				</tr>\
			</tbody>\
			<tfoot>\
				<tr>\
					<td class="l png"></td>\
					<td class="c png"></td>\
					<td class="r png"></td>\
				</tr>\
			</tfoot>\
			</table>').appendTo(this.settings.container).css({
				width: this.settings.width
		});
		
		this.div.find('td.png').png();
		
		this.content = this.div.find('.popup-content').append(this.elem);
		
		if(this.settings.close){
			this.closeButton = $('<div class="popup-close-button" />').
				appendTo(this.div).
				click((function(popup){
					return function(){
						popup.close()
					}
				})(this));
		}
		
		if(this.settings.dd){
			this.div.dd({
				position: 'absolute',
				delay: 200
			});
		}
		
	};
	
	$.extend(Popup.prototype, {
		open: function(){
			
			if($('.popup:visible').length) return false;
			this.overlay = $.overlay({opacity: 0});
			this.overlay.appendTo(this.settings.container);
			if(this.overlay.data('overlay-iframe'))
				this.overlay.data('overlay-iframe').insertBefore(this.overlay);
			
			this.div.show();
			this.center();
			
			var tabDependats = this.elem.find('input, select, textarea, a, button').not(':hidden').not('.date, .date-button').each(function(i){
				$(this).attr('tabindex', i+1);
				if(!i)this.focus();
			});

			
			var popup = this;
			/*$(window).bind('scroll', function(){
				popup.center();
			});*/
			$(window).bind('resize.popup', function(){
				popup.center();
			});
			
			this.layer = $.layers.push(
				this.overlay.add(this.overlay.data('overlay-iframe')).add(this.div),
				this.settings.esc ? (function(popup){return function(){popup.close()}})(this) : null
			);
			
		},
		
		close: function(){
			$.layers.pop(this.layer);
			this.div.hide();
			if(this.overlay.data('overlay-iframe'))
				this.overlay.data('overlay-iframe').remove();
			this.overlay.remove();
			
			//$(window).unbind('scroll.popup');
			$(window).unbind('resize.popup');
		},
		
		center: function(){
			var el = this.div,
				win = $(window),
				doc = $(document);
			
			el.css({
				top: Math.max(10, Math.round(win.height()/2 + doc.scrollTop() - el.height()/2)) + 'px',
				left: Math.max(10, Math.round(win.width()/2 + doc.scrollLeft() - el.width()/2)) + 'px'
			});
		}
	});
	
	//	togglers initialization
	$(document).ready(function(){
		$('a.toggler').each(function(){
			var
				$this = $(this),
				panel = $this.parent().next('.toggler-panel'),
				update = function(){
					if($this.is('.toggler-opened')){
						panel.show();
					}else{
						panel.hide();
					}
					
				};

			update();
			
			$this.click(function(){
				$this.toggleClass('toggler-opened');
				update();
				
				return false;
			});
		});
	});


})(jQuery);


