if (!window.console){ 
	this.console = {log: function() {}};  
}  
/**
 * jQuery.ScrollTo - Easy element scrolling using jQuery.
 * Copyright (c) 2007-2009 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
 * Dual licensed under MIT and GPL.
 * Date: 5/25/2009
 * @author Ariel Flesler
 * @version 1.4.2
 *
 * http://flesler.blogspot.com/2007/10/jqueryscrollto.html
 */
;(function(d){var k=d.scrollTo=function(a,i,e){d(window).scrollTo(a,i,e)};k.defaults={axis:'xy',duration:parseFloat(d.fn.jquery)>=1.3?0:1};k.window=function(a){return d(window)._scrollable()};d.fn._scrollable=function(){return this.map(function(){var a=this,i=!a.nodeName||d.inArray(a.nodeName.toLowerCase(),['iframe','#document','html','body'])!=-1;if(!i)return a;var e=(a.contentWindow||a).document||a.ownerDocument||a;return d.browser.safari||e.compatMode=='BackCompat'?e.body:e.documentElement})};d.fn.scrollTo=function(n,j,b){if(typeof j=='object'){b=j;j=0}if(typeof b=='function')b={onAfter:b};if(n=='max')n=9e9;b=d.extend({},k.defaults,b);j=j||b.speed||b.duration;b.queue=b.queue&&b.axis.length>1;if(b.queue)j/=2;b.offset=p(b.offset);b.over=p(b.over);return this._scrollable().each(function(){var q=this,r=d(q),f=n,s,g={},u=r.is('html,body');switch(typeof f){case'number':case'string':if(/^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(f)){f=p(f);break}f=d(f,this);case'object':if(f.is||f.style)s=(f=d(f)).offset()}d.each(b.axis.split(''),function(a,i){var e=i=='x'?'Left':'Top',h=e.toLowerCase(),c='scroll'+e,l=q[c],m=k.max(q,i);if(s){g[c]=s[h]+(u?0:l-r.offset()[h]);if(b.margin){g[c]-=parseInt(f.css('margin'+e))||0;g[c]-=parseInt(f.css('border'+e+'Width'))||0}g[c]+=b.offset[h]||0;if(b.over[h])g[c]+=f[i=='x'?'width':'height']()*b.over[h]}else{var o=f[h];g[c]=o.slice&&o.slice(-1)=='%'?parseFloat(o)/100*m:o}if(/^\d+$/.test(g[c]))g[c]=g[c]<=0?0:Math.min(g[c],m);if(!a&&b.queue){if(l!=g[c])t(b.onAfterFirst);delete g[c]}});t(b.onAfter);function t(a){r.animate(g,j,b.easing,a&&function(){a.call(this,n,b)})}}).end()};k.max=function(a,i){var e=i=='x'?'Width':'Height',h='scroll'+e;if(!d(a).is('html,body'))return a[h]-d(a)[e.toLowerCase()]();var c='client'+e,l=a.ownerDocument.documentElement,m=a.ownerDocument.body;return Math.max(l[h],m[h])-Math.min(l[c],m[c])};function p(a){return typeof a=='object'?a:{top:a,left:a}}})(jQuery); 
/*! Copyright (c) 2009 Brandon Aaron (http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 * Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers.
 * Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix.
 *
 * Version: 3.0.2
 * 
 * Requires: 1.2.2+
 */

(function($) {

var types = ['DOMMouseScroll', 'mousewheel'];

$.event.special.mousewheel = {
	setup: function() {
		if ( this.addEventListener )
			for ( var i=types.length; i; )
				this.addEventListener( types[--i], handler, false );
		else
			this.onmousewheel = handler;
	},
	
	teardown: function() {
		if ( this.removeEventListener )
			for ( var i=types.length; i; )
				this.removeEventListener( types[--i], handler, false );
		else
			this.onmousewheel = null;
	}
};

$.fn.extend({
	mousewheel: function(fn) {
		return fn ? this.bind("mousewheel", fn) : this.trigger("mousewheel");
	},
	
	unmousewheel: function(fn) {
		return this.unbind("mousewheel", fn);
	}
});


function handler(event) {
	var args = [].slice.call( arguments, 1 ), delta = 0, returnValue = true;
	
	event = $.event.fix(event || window.event);
	event.type = "mousewheel";
	
	if ( event.wheelDelta ) delta = event.wheelDelta/120;
	if ( event.detail     ) delta = -event.detail/3;
	
	// Add events and delta to the front of the arguments
	args.unshift(event, delta);

	return $.event.handle.apply(this, args);
}

})(jQuery);
/* 
 * AlkoDesign
 */

/**
 *  Function that get form with "formId" sent it with AJAX+POST to the "path" and returned result fill the "receiverId"-html
 *
 * @param string formId
 * @param string path
 * @param string receiverId
 */
function sentForm(formId, path, receiverId) {
    var str = $("#" + formId).serialize();console.log(str)
    $.post(path, str, function(data) {
        $("#" + receiverId).html(data);
    });
}    
function refreshIt(id, addr) {
	$.post(addr, "", function(data) {
		$("#" + id).html(data);
	});
}
/**
 *  Function that get form with "formId" sent it with AJAX+POST to the "path" and returned result fill the "receiverId"-html
 *
 * @param string path
 * @param string receiverId
 */
function sentData(path, receiverId) {
    $.post(path, "", function(data) {
        $("#" + receiverId).html(data);
		$("#page_loader").hide(); 
    });
	$("#page_loader").show(); 
}  
function getMainList(id) {
	$.post(str, "", function(data) {
		$("#" + id).append(data);
	});
}  
function topping(number, side) {
	$.post("/main/topping" + side + "/" + number, "", function(data) {
		if (data.split(' ').join('').split("\n").join('') != "") $("#TopObjects").html(data);
		
	});
}

var limit = 100, style = 0, type = 0, word;

function getPeople(styleId, typeId, wordId) {       
	//this.options[this.selectedIndex]
	var style = document.getElementById(styleId).options[document.getElementById(styleId).selectedIndex].value;
	var type = document.getElementById(typeId).options[document.getElementById(typeId).selectedIndex].value;
	var word = document.getElementById(wordId).value;
	path = '/profiles/ajaxFlowLoad/style/' + style + '/type/' + type + '/limit/' + limit + ((word != "")?'/word/' + word:"");    
	id = 'profilesList';
	sentData(path, id);
}

function eventUngo(id) {
	sentData("/event/inviteConfirm/id/" + id);
}

function eventGo(id) {
	sentData("/event/inviteConfirm/id/" + id);
}    
function ratingVoteUp(id, receiverId){
	$('#ration_up').hide(); 
	$('#ration_down').hide();                                    
	$.get('/rating/ajaxVote/id/'+id+'/vote/1', "", function(data) {
        $("#" + receiverId).html(data).addClass('voted');   
    });
	return false;
}
function ratingVoteDown(id, receiverId){
	$('#ration_up').hide(); 
	$('#ration_down').hide(); 
	$.get('/rating/ajaxVote/id/'+id+'/vote/-1', "", function(data) {
        $("#" + receiverId).html(data).addClass('voted') ; 
    });
	return false;
}  
function addFriend(id_account){
	$.ajax({
		type: 'GET',
		url: '/user/addFriend',
		data: {id_account: id_account},
		dataType: "json",
		success: function(data){
			if(data.success && typeof(data.quantity) != 'indefined'){
				$('#buttonInFriends span').html("В друзьях у ("+data.quantity+")");
				$('#buttonAddFriend').hide();
				$('#buttonDelFriend').show();
				$('#buttonInFriends').show();
			}
		}
	});
	return false;
}
function delFriend(id_account){
	$.ajax({
		type: 'GET',
		url: '/user/delFriend',
		data: {id_account: id_account},
		dataType: "json",
		success: function(data){
			if(data.success && typeof(data.quantity) != 'indefined'){
				$('#buttonInFriends span').html("В друзьях у ("+data.quantity+")");
				$('#buttonAddFriend').show();
				$('#buttonDelFriend').hide();
				$('#buttonInFriends').hide();
			}
		}
	});
	return false;
}    
// Подключение к СоцСетям.

function vkAuth(appid, url) {
	window.location.href = url;
//	VK.init({apiId: appid});
//	VK.Auth.login(function(resp) {
//		if (resp.session) {
//			window.location.href = url;
//		}
//	});
}   
function fbsAuth(appid, url) {
	FB.init({appId:appid, cookie:true, status:true, xfbml:true, channelUrl: "http://"+location.host+"/javascript/channel.php"});
	FB.login(function(resp) {
		if (resp.session) {                
 			location.replace(url);  
		}  	
	});
}
(function($) {  	
	$.fn.el_select = function(options) {   		                                                 		
		if(this.is(":hidden")){   
		    if(typeof options === "string" && options == "update"){  
		    	this.siblings(".el_select").detach();
			}else	
				return;
		}     		      				
		// defaults
		var defaults = {
			ajax : false,
			height: -1,
			icons: true	  
		},
		
		maskSelect = null,    
		
		// merge defaults with options in new settings object				
			settings = $.extend({}, defaults, options),
			
			$el_select = this;    
			                                
			if($el_select.is("select")){  
				 maskSelect = this;
			     $el_select = $("<div class='el_select'><div class='btn'/></div>");
				 if(settings.style)	
					 $el_select.css(settings.style);		     
				 var _act = $("<div class='act'/>");
				 var _scD = $("<div class='scrollDiv'/>");
				 var _ul = $("<ul/>");
				 
				 if(!settings.icons){
				 	$el_select.addClass("el_select_noicons");
				 }
				 
				$el_select.width(maskSelect.width() + parseInt(maskSelect.css("paddingLeft")) + parseInt(maskSelect.css("paddingRight")));
				 _scD.width($el_select.width());
			   	 _ul.css("max-width", $el_select.width() - 10);
			   	 _ul.width("auto");
				 
				 
				 $("option", this).each(function(index) {    
				 		var li = $("<li><a rel='"+$(this).val()+"'>"+$(this).text()+"</a></li>");
						if($(this).attr("class")){
							li.attr("class", $(this).attr("class"))
						}
				 		_ul.append(li);
				   		if(maskSelect.val() == $(this).val()){
				   			_act.html($(this).text());
							_act.addClass($(this).attr("class"));	
				   		}   
				  }); 				
				  $el_select.append(_act);  
				  _scD.append(_ul);
				  $el_select.append(_scD);
				  
				 
				 $el_select.insertAfter(this);
			   	 this.hide();  				
			}   
			
		// define key variables
			
			var $list = $el_select.find('ul'),
			$act = $el_select.find('.act'),      
			$btn = $el_select.find('.btn'),
			$scrollDiv = $el_select.find('.scrollDiv'),
			$links = $('a', $list);      
		
		   $scrollDiv.hide();
		   
		   $links.each(function(index) {
		   		$(this).click(function(event){ 
		   			 if(maskSelect != null){
	   			   	 	event.preventDefault();
						maskSelect.val($(this).attr("rel"));
					 //	alert(typeof(maskSelect.attr("onchange")))
						maskSelect.change();
						//maskSelect.attr("onchange")()
					 }
		   			 $act.html($(this).text());
					 $act.css({backgroundImage: $(this).parent().css("backgroundImage"), backgroundPosition: $(this).parent().css("backgroundPosition")});
					 $btn.removeClass("openedListBtn");
					 $scrollDiv.hide();
					 $el_select.removeClass("el_select_opened");
		   		}); 
		  });
		  
		  var k;                 
		                   
		  if(settings.height > 0 && $links.length*20 > settings.height){              
			  	$scrollDiv.css("overflow", "hidden");
				var $scroll = $("<div class='scroll'/>");
				$scroll.height(settings.height - 30);    
			  	$scrollDiv.append($scroll);
				                                
				$scroll.slider({
					orientation: "vertical", 
					min: 0,
					max: 100,
					value: 100,
				   	slide: function( event, ui ) {    	               
				 		$list.css("top", -((100 - ui.value)*k/100));
					},
					change: function(event, ui) { 
					  	$list.css("top", -((100 - ui.value)*k/100));     
					} 
				});        				
				
				$scrollDiv.bind('mousewheel', function(event, delta) {
		            var dir = delta > 0 ? 1 : -1;  
		           // move(dir); 
				   	$scroll.slider("value" , $scroll.slider("value") + dir*15);                      
		            return false;
		        });
				
				$list.css("paddingRight", 24)
		  }else{
		  	   $list.css("position", "relative");
		  }                     
		   
		  $btn.click(function(){
		   		updateScroll(); 
		   });
		   
		   if(maskSelect != null){
				_act.click(function(){
                    updateScroll();
				});
		   }
		   
		   var updateScroll = function(){
					if($scrollDiv.is(":hidden")){
						$btn.addClass("openedListBtn");
                                                                    
						if(settings.height > 0 && $links.length*20 > settings.height){
							$scrollDiv.height(settings.height); 
						} 
						$el_select.addClass("el_select_opened");
						$scrollDiv.show();
						k = ($list.height()+8) - settings.height;
					}else{          
						$btn.removeClass("openedListBtn");
						$scrollDiv.hide();
						$el_select.removeClass("el_select_opened");
					}		   	
		   }     
		return $el_select;   
	};  
})(jQuery);   
/*
	* jReject (jQuery Browser Rejection Plugin)
	* Version 0.7-Beta
	* URL: http://jreject.turnwheel.com/
	* Description: jReject gives you a customizable and easy solution to reject/allowing specific browsers access to your pages
	* Author: Steven Bower (TurnWheel Designs) http://turnwheel.com/
	* Copyright: Copyright (c) 2009-2010 Steven Bower under dual MIT/GPL license.
	* Depends On: jQuery Browser Plugin (http://jquery.thewikies.com/browser)
*/              
(function($) {
	$.reject = function(opts) {
		var opts = $.extend(true,{
			reject : { // Rejection flags for specific browsers
				all: false, // Covers Everything (Nothing blocked)                   
				msie5: true, msie6: true // Covers MSIE 5-6 (Blocked by default)    
				/*
					Possibilities are endless...

					msie: false,msie5: true,msie6: true,msie7: false,msie8: false, // MSIE Flags (Global, 5-8)
					firefox: false,firefox1: false,firefox2: false,firefox3: false, // Firefox Flags (Global, 1-3)
					konqueror: false,konqueror1: false,konqueror2: false,konqueror3: false, // Konqueror Flags (Global, 1-3)
					chrome: false,chrome1: false,chrome2: false,chrome3: false,chrome4: false, // Chrome Flags (Global, 1-4)
					safari: false,safari2: false,safari3: false,safari4: false, // Safari Flags (Global, 1-4)
					opera: false,opera7: false,opera8: false,opera9: false,opera10: false, // Opera Flags (Global, 7-10)
					gecko: false,webkit: false,trident: false,khtml: false,presto: false, // Rendering Engines (Gecko, Webkit, Trident, KHTML, Presto)
					win: false,mac: false,linux : false,solaris : false,iphone: false, // Operating Systems (Win, Mac, Linux, Solaris, iPhone)
					unknown: false // Unknown covers everything else
				*/
			},
			display: [], // What browsers to display and their order (default set below)
			browserInfo: { // Settings for which browsers to display
				firefox: {
					text: 'Firefox 4+', // Text below the icon
					url: 'http://www.mozilla.com/firefox/' // URL For icon/text link
				},
				safari: {
					text: 'Safari 4+',
					url: 'http://www.apple.com/safari/download/'
				},
				opera: {
					text: 'Opera 11+',
					url: 'http://www.opera.com/download/'
				},
				chrome: {
					text: 'Chrome 10+',
					url: 'http://www.google.com/chrome/'
				},
				msie: {
					text: 'IE 8+',
					url: 'http://www.microsoft.com/windows/Internet-explorer/'
				},
				gcf: {
					text: 'Google Chrome Frame',
					url: 'http://code.google.com/chrome/chromeframe/',
					allow: {all: false, msie: true} // This browser option will only be displayed for MSIE
				}
			},
			header: 'Знаете ли вы, что ваш интернет-браузер устарел?', // Header of pop-up window
			paragraph1: 'Ваш браузер устарел, и не могут быть совместимы с нашего сайта.  Список  самых популярных веб-браузеров можно найти ниже.', // Paragraph 1
			paragraph2: 'Просто нажмите на  иконки, позволяющие перейти на страницу загрузки', // Paragraph 2
			close: true, // Allow closing of window
			closeMessage: ''/*'При закрытии этого окна вы признаете, что Ваш опыт на этом сайте может ухудшиться'*/, // Message displayed below closing link
			closeLink: 'Закрыть окно', // Text for closing link
			closeURL: '#', // Close URL
			closeESC: true, // Allow closing of window with esc key
			closeCookie: false, // If cookies should be used to remmember if the window was closed (see cookieSettings for more options)
			// Cookie settings are only used if closeCookie is true
			cookieSettings: {
				path: '/', // Path for the cookie to be saved on (should be root domain in most cases)
				expires: 0 // Expiration Date (in seconds), 0 (default) means it ends with the current session
			},
			imagePath: '/images/browser/', // Path where images are located
			overlayBgColor: '#000', // Background color for overlay
			overlayOpacity: 0.8, // Background transparency (0-1)
			fadeInTime: 'fast', // Fade in time on open ('slow','medium','fast' or integer in ms)
			fadeOutTime: 'fast' // Fade out time on close ('slow','medium','fast' or integer in ms)
		},opts);

		// Set default browsers to display if not already defined
		if (opts.display.length < 1) opts.display = ['firefox','chrome','msie','safari','opera','gcf'];

		// beforeRject: Customized Function
		if ($.isFunction(opts.beforeReject)) opts.beforeReject(opts);

		// Disable 'closeESC' if closing is disabled (mutually exclusive)
		if (!opts.close) opts.closeESC = false;

		// This function parses the advanced browser options
		var browserCheck = function(settings) {
			// Check 1: Look for 'all' forced setting
			// Check 2: Operating System (eg. 'win','mac','linux','solaris','iphone')
			// Check 3: Rendering engine (eg. 'webkit', 'gecko', 'trident')
			// Check 4: Browser name (eg. 'firefox','msie','chrome')
			// Check 5: Browser+major version (eg. 'firefox3','msie7','chrome4')
			return (settings['all'] ? true : false) ||
				(settings[$.os.name] ? true : false) ||
				(settings[$.layout.name] ? true : false) ||
				(settings[$.browser.name] ? true : false) ||
				(settings[$.browser.className] ? true : false);
		};

		// Determine if we need to display rejection for this browser, or exit
		if (!browserCheck(opts.reject)) {
			// onFail: Customized Function
			if ($.isFunction(opts.onFail)) opts.onFail(opts);
			return false;
		}

		// If user can close and set to remmember close, initiate cookie functions
		if (opts.close && opts.closeCookie) {
			var COOKIE_NAME = 'jreject-close'; // Local global setting for the name of the cookie used

			// Cookies Function: Handles creating/retrieving/deleting cookies
			// Cookies are only used for opts.closeCookie parameter functionality
			var _cookie = function(name, value) {
				if (typeof value != 'undefined') {
					var expires = '';

					// Check if we need to set an expiration date
					if (opts.cookieSettings.expires != 0) {
						var date = new Date();
						date.setTime(date.getTime()+(opts.cookieSettings.expires));
						var expires = "; expires="+date.toGMTString();
					}

					// Get path from settings
					var path = opts.cookieSettings.path || '/';

					// Set Cookie with parameters
					document.cookie = name+'='+encodeURIComponent(value == null ? '' : value)+expires+'; path='+path;
				}
				else { // Get cookie value
					var cookie,val = null;

					if (document.cookie && document.cookie != '') {
						var cookies = document.cookie.split(';');

						// Loop through all cookie values
						for (var i = 0; i < cookies.length; ++i) {
							cookie = $.trim(cookies[i]);

							// Does this cookie string begin with the name we want?
							if (cookie.substring(0,name.length+1) == (name+'=')) {
								val = decodeURIComponent(cookie.substring(name.length+1));
								break;
							}
						}
					}

					return val; // Return cookie value
				}
			};

			// If cookie is set, return false and don't display rejection
			if (_cookie(COOKIE_NAME) != null) return false;
		}

		// Load background overlay (jr_overlay) + Main wrapper (jr_wrap) +
		// Inner Wrapper (jr_inner) w/ opts.header (jr_header) +
		// opts.paragraph1/opts.paragraph2 if set
		var html = '<div id="jr_overlay"></div><div id="jr_wrap"><div id="jr_inner"><h1 id="jr_header">'+opts.header+'</h1>'+
		(opts.paragraph1 === '' ? '' : '<p>'+opts.paragraph1+'</p>')+(opts.paragraph2 === '' ? '' : '<p>'+opts.paragraph2+'</p>')+'<ul>';

		var displayNum = 0; // Tracks number of browsers being displayed
		// Generate the browsers to display
		for (var x in opts.display) {
			var browser = opts.display[x]; // Current Browser
			var info = opts.browserInfo[browser] || false; // Browser Information

			// If no info exists for this browser
			// or if this browser is not suppose to display to this user
			if (!info || (info['allow'] != undefined && !browserCheck(info['allow']))) continue;

			var url = info.url || '#'; // URL to link text/icon to
			// Generate HTML for this browser option
			html += '<li id="jr_'+browser+'"><div class="jr_icon"></div>'+
					'<div><a href="'+url+'">'+(info.text || 'Unknown')+'</a></div></li>';
			++displayNum; // Increment number of browser being displayed
		}

		// Close list and #jr_list
		html += '</ul><div id="jr_close">'+
		// Display close links/message if set
		(opts.close ? '<a href="'+opts.closeURL+'">'+opts.closeLink+'</a><p>'+opts.closeMessage+'</p>' : '')+'</div>'+
		// Close #jr_inner and #jr_wrap
		'</div></div>';

		var element = $('<div>'+html+'</div>'); // Create element
		var size = _pageSize(); // Get page size
		var scroll = _scrollSize(); // Get page scroll

		// This function handles closing this reject window
		element.bind('closejr',function() { // When clicked, fadeOut and remove all elements
			if (!opts.close) return false; // Make sure the ability to close is set
			if ($.isFunction(opts.beforeClose)) opts.beforeClose(opts); // Customized Function

			$(this).unbind('closejr'); // Remove binding function

			// Fade out background and modal wrapper
			$('#jr_overlay,#jr_wrap').fadeOut(opts.fadeOutTime,function() {
				$(this).remove(); // Remove element from DOM

				// afterClose: Customized Function
				if ($.isFunction(opts.afterClose)) opts.afterClose(opts);
			});

			$('embed, object, select, applet').show(); // Show elements that were hidden

			if (opts.closeCookie) _cookie(COOKIE_NAME,'true'); // Set close cookie for next run
			return true;
		});

		// Traverse through the DOM and
		// Apply CSS Rules to elements
		element.find('#jr_overlay').css({ // Creates 'background' (div)
			width: size[0],
			height: size[1],
			position: 'absolute',
			top: 0,
			left: 0,
			background: opts.overlayBgColor,
			zIndex: 200,
			opacity: opts.overlayOpacity,
			padding: 0,
			margin: 0
		}).next('#jr_wrap').css({ // Wrapper for our pop-up (div)
			position: 'absolute',
			width: '100%',
			top: scroll[1]+(size[3]/4),
			left: scroll[0],
			zIndex: 300,
			textAlign: 'center',
			padding: 0,
			margin: 0
		}).children('#jr_inner').css({ // Wrapper for inner centered content (div)
			background: '#FFF',
			border: '1px solid #CCC',
			fontFamily: '"Lucida Grande","Lucida Sans Unicode",Arial,Verdana,sans-serif',
			color: '#4F4F4F',
			margin: '0 auto',
			position: 'relative',
			height: 'auto',
			minWidth: displayNum*100,
			maxWidth: displayNum*140,
			width: $.layout.name == 'trident' ? displayNum*155 : 'auto', // min/maxWidth not supported by IE
			padding: 20,
			fontSize: 12
		}).children('#jr_header').css({ // Header (h1)
			display: 'block',
			fontSize: '1.3em',
			marginBottom: '0.5em',
			color: '#333',
			fontFamily: 'Helvetica,Arial,sans-serif',
			fontWeight: 'bold',
			textAlign: 'left',
			padding: 5,
			margin: 0
		}).nextAll('p').css({ // Paragraphs (p)
			textAlign: 'left',
			padding: 5,
			margin: 0
		}).siblings('ul').css({ // Browser list (ul)
			listStyleImage: 'none',
			listStylePosition: 'outside',
			listStyleType: 'none',
			margin: 0,
			padding: 0
		}).children('li').css({ // Browser list items (li)
			background: 'transparent url("'+opts.imagePath+'background_browser.gif") no-repeat scroll left top',
			cusor: 'pointer',
			'float': 'left',
			width: 120,
			height: 122,
			margin: '0 10px 10px 10px',
			padding: 0,
			textAlign: 'center'
		}).children('.jr_icon').css({ // Icons (div)
			width: 100,
			height: 100,
			margin: '1px auto',
			padding: 0,
			background: 'transparent no-repeat scroll left top',
			cursor: 'pointer'
		}).each(function() { // Dynamically sets the icon background image
			var self = $(this);
			self.css('background','transparent url('+opts.imagePath+'browser_'+(self.parent('li').attr('id').replace(/jr_/,''))+'.gif) no-repeat scroll left top');
			self.click(function() {
				window.open($(this).next('div').children('a').attr('href'),'jr_'+Math.round(Math.random()*11));
				return false;
			});
		}).siblings('div').css({ // Text under the browser icon (div)
			color: '#808080',
			fontSize: '0.8em',
			height: 18,
			lineHeight: '17px',
			margin: '1px auto',
			padding: 0,
			width: 118,
			textAlign: 'center'
		}).children('a').css({ // Text link (a)
			color: '#333',
			textDecoration: 'none',
			padding: 0,
			margin: 0
		}).hover(function() { // Underline effect (a:hover)
			$(this).css('textDecoration','underline');
		},function() {
			$(this).css('textDecoration','none');
		}).click(function() { // Make links open in new window (a)
			window.open($(this).attr('href'),'jr_'+Math.round(Math.random()*11));
			return false;
		}).parents('#jr_inner').children('#jr_close').css({ // Close window option (div)
			margin: '0 0 0 50px',
			clear: 'both',
			textAlign: 'left',
			padding: 0,
			margin: 0
		}).children('a').css({ // Close window link (a)
			color: '#000',
			display: 'block',
			width: 'auto',
			margin: 0,
			padding: 0,
			textDecoration: 'underline'
		}).click(function() { // Bind closing event
			$(this).trigger('closejr');

			// If plain anchor is set, return false so there is no page jump
			if (opts.closeURL === '#') return false;
		}).nextAll('p').css({ // Add padding to close link/text
			padding: '10px 0 0 0',
			margin: 0
		});

		// Set focus (fixes ESC key issues with forms and other focus bugs)
		$('#jr_overlay').focus();

		// Hide elements that won't display properly
		$('embed, object, select, applet').hide();

		// Append element to body of document to display
		$('body').append(element.hide().fadeIn(opts.fadeInTime));

		// Handle window resize/scroll events and update overlay dimensions
		$(window).bind('resize scroll',function() {
			var size = _pageSize(); // Get size

			// Update overlay dimensions based on page size
			$('#jr_overlay').css({width: size[0],height: size[1]});

			var scroll = _scrollSize(); // Get page scroll

			// Update modal position based on scroll
			$('#jr_wrap').css({top: scroll[1] + (size[3]/4),left: scroll[0]});
		});

		// Add optional ESC Key functionality
		if (opts.closeESC) {
			$(document).bind('keydown',function(event) {
				// ESC = Keycode 27
				if (event.keyCode == 27) element.trigger('closejr');
			});
		}

		// afterReject: Customized Function
		if ($.isFunction(opts.afterReject)) opts.afterReject(opts);

		return true;
	};

	// Based on compatibility data from quirksmode.com
	var _pageSize = function() {
		var xScroll = window.innerWidth && window.scrollMaxX ? window.innerWidth + window.scrollMaxX :
						(document.body.scrollWidth > document.body.offsetWidth ?
						document.body.scrollWidth : document.body.offsetWidth);

		var yScroll = window.innerHeight && window.scrollMaxY ? window.innerHeight + window.scrollMaxY :
						(document.body.scrollHeight > document.body.offsetHeight ?
						document.body.scrollHeight : document.body.offsetHeight);

		var windowWidth = window.innerWidth ? window.innerWidth :
						(document.documentElement && document.documentElement.clientWidth ?
						document.documentElement.clientWidth : document.body.clientWidth);

		var windowHeight = window.innerHeight ? window.innerHeight :
						(document.documentElement && document.documentElement.clientHeight ?
						document.documentElement.clientHeight : document.body.clientHeight);

		return [
			xScroll < windowWidth ? xScroll : windowWidth, // Page Width
			yScroll < windowHeight ? windowHeight : yScroll, // Page Height
			windowWidth,windowHeight
		];
	};
              

	// Based on compatibility data from quirksmode.com
	var _scrollSize = function() {
		return [
			// scrollSize X
			window.pageXOffset ? window.pageXOffset : (document.documentElement && document.documentElement.scrollTop ? document.documentElement.scrollLeft : document.body.scrollLeft),
			// scrollSize Y
			window.pageYOffset ? window.pageYOffset : (document.documentElement && document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop)
		];
	};
})(jQuery);  
/*
	* jQuery Browser Plugin
	* Version 2.3
	* 2008-09-17 19:27:05
	* URL: http://jquery.thewikies.com/browser
	* Description: jQuery Browser Plugin extends browser detection capabilities and can assign browser selectors to CSS classes.
	* Author: Nate Cavanaugh, Minhchau Dang, & Jonathan Neal
	* Copyright: Copyright (c) 2008 Jonathan Neal under dual MIT/GPL license.
*/
(function($){$.browserTest=function(a,z){var u='unknown',x='X',m=function(r,h){for(var i=0;i<h.length;i=i+1){r=r.replace(h[i][0],h[i][1]);}return r;},c=function(i,a,b,c){var r={name:m((a.exec(i)||[u,u])[1],b)};r[r.name]=true;r.version=(c.exec(i)||[x,x,x,x])[3];if(r.name.match(/safari/)&&r.version>400){r.version='2.0';}if(r.name==='presto'){r.version=($.browser.version>9.27)?'futhark':'linear_b';}r.versionNumber=parseFloat(r.version,10)||0;r.versionX=(r.version!==x)?(r.version+'').substr(0,1):x;r.className=r.name+r.versionX;return r;};a=(a.match(/Opera|Navigator|Minefield|KHTML|Chrome/)?m(a,[[/(Firefox|MSIE|KHTML,\slike\sGecko|Konqueror)/,''],['Chrome Safari','Chrome'],['KHTML','Konqueror'],['Minefield','Firefox'],['Navigator','Netscape']]):a).toLowerCase();$.browser=$.extend((!z)?$.browser:{},c(a,/(camino|chrome|firefox|netscape|konqueror|lynx|msie|opera|safari)/,[],/(camino|chrome|firefox|netscape|netscape6|opera|version|konqueror|lynx|msie|safari)(\/|\s)([a-z0-9\.\+]*?)(\;|dev|rel|\s|$)/));$.layout=c(a,/(gecko|konqueror|msie|opera|webkit)/,[['konqueror','khtml'],['msie','trident'],['opera','presto']],/(applewebkit|rv|konqueror|msie)(\:|\/|\s)([a-z0-9\.]*?)(\;|\)|\s)/);$.os={name:(/(win|mac|linux|sunos|solaris|iphone)/.exec(navigator.platform.toLowerCase())||[u])[0].replace('sunos','solaris')};if(!z){$('html').addClass([$.os.name,$.browser.name,$.browser.className,$.layout.name,$.layout.className].join(' '));}};$.browserTest(navigator.userAgent);})(jQuery);

      
$(document).ready(function(){
	$.reject({
		reject: {
			safari: false, // Apple Safari
			chrome: false, // Google Chrome
			firefox: false, // Mozilla Firefox
			msie: false, msie5: true, msie6: true, msie7: true, msie8: false, // Microsoft Internet Explorer
			opera: false, // Opera
			konqueror: false, // Konqueror (Linux)
			unknown: true // Everything else
		},
		display: ['firefox','chrome','msie','safari','opera'],
		closeCookie: true
	}); 
});



function initWaves(name, ajax){  
        var num = 1,
        total,
        wave_list = $("."+name+"_list"),
        wave_list2,
        wave_list3,
        wave_list_cont = $("."+name+"_list_cont"),
        slider = $("<div style='position:absolute;left:0;top:0'/>"),
        sliderPos = 0,
        block = false,
        wave_dsc = $(".wave_dsc"),
		txt = $(".txt", wave_dsc),
		in_txt = $(".in_txt", txt),
		btn = $(".btn", wave_dsc),
		act,
		
		wHeight = (name == "wave") ? 160 : 90,
		wWidth = (name == "wave") ? 160 : 150 ;
		                                       
		if(in_txt.height() <= 67){
			btn.hide();	
		}

        var initControl  = function(){
            total = $("img", wave_list).length;
			act = $(".act", wave_list).index();   

            if(total <= 4)
                return;

            var next = $("<a class='next'/>");
            var prev = $("<a class='prev'/>");

            next.click(function(){
                move(num);
            });
            prev.click(function(){
                move(-num)
            });

            wave_list_cont.append(next).append(prev);
            wave_list_cont.css({overflow: "hidden", height: wHeight});
   
			wave_list_cont.bind('mousewheel', function(event, delta) {
	            var dir = delta > 0 ? 1 : -1;  
	            move(dir);                       
	            return false;
	        });   

            wave_list.css({position:"absolute", top: 0, left: 0});

            wave_list2 = wave_list.clone();
            wave_list2.css("left", total*wWidth);

            wave_list3 = wave_list.clone();
            wave_list3.css("left", -total*wWidth);


            slider.append(wave_list);
            slider.append(wave_list2);
            slider.append(wave_list3);
            wave_list_cont.append(slider);

            var links = $("a", wave_list);
            links.each(function(index) {
                $(this).click(function(event){ 
                	if(ajax)
                    	event.preventDefault();
                    selectWave($(this));
                });
            });           
		   
			btn.click(function(){
				moveDsc();
			});
			
			if(act > 3){
	   			slider.css("left", -(act-3)*wWidth);	
			}

        }();
		
		var moveDsc = function(){                         	
			if(btn.hasClass("close_wave_dsc")){   
				txt.animate({
	                height: in_txt.height()
	              }, 500, function() {
	                  btn.removeClass("close_wave_dsc");
	              });   
			}else{                          
				txt.animate({
					height: 63
				  }, 500, function() {
					  btn.addClass("close_wave_dsc");
				  });      
			}    			
		}  
        var selectWave = function(lnk){
            $("li", wave_list).removeClass("act");
            lnk.parent("li").addClass("act");
        } 
        var move = function(num){
            if(!block){
              block = true;
              slider.animate({
                left: '-='+num*wWidth+''
              }, 800, function() {
                  checkPos();
                  block = false;
              });
            }
        }   
        var checkPos = function(){
            sliderPos = slider.position().left;
            if(sliderPos == -wWidth*total || sliderPos == wWidth*total){
                slider.css("left", 0);
            }
        }
    }  

function initWaves2(name){  
        var num = 4,
        total,
        wave_list = $("."+name+"_list"),
        wave_list_cont = $("."+name+"_list_cont"),
		scrollDiv = $('#'+name+'ScrollDiv'),
		slider = scrollDiv,
        wave_dsc = $(".wave_dsc"),
		txt = $(".txt", wave_dsc),
		act,
		block = false;
		wHeight = $('img', wave_list).height();
		wWidth = $('img', wave_list).width();
		
        var initControl  = function(){
            total = $("img", wave_list).length;
			act = $(".act", wave_list).index();   

            if(total <= 4)
                return;

			scrollDiv.css({postition: 'relative', overflowX: 'scroll'});

            var next = $("<a class='next'/>");
            var prev = $("<a class='prev'/>");

            next.click(function(){
                move(num);
            });
            prev.click(function(){
                move(-num)
            });

            wave_list_cont.append(next).append(prev);
            wave_list_cont.css({overflow: "hidden", height: wHeight+16});
			
			wave_list_cont.bind('mousewheel', function(event, delta) {
	            var dir = delta > 0 ? num : -num;  
	            move(dir);                       
	            return false;
	        });   

            wave_list.css({position:"relative", top: 0, left: 0});
            slider.append(wave_list);
            wave_list_cont.append(slider);

            var links = $("a", wave_list);
            links.each(function(index) {
                $(this).click(function(event){ 
                	
                });
            });           
		   
			if(act > 3){
	   			$(scrollDiv).scrollTo(wWidth*(act-1), 0, {axis:'x'} );
			}
        }();
		 
        var move = function(num){
			if(block == false){
				block = true;
				if(num > 0)
					$(scrollDiv).scrollTo('+='+wWidth*Math.abs(num), 800, {axis:'x', onAfter:function(){block = false}} );
				else
					$(scrollDiv).scrollTo('-='+wWidth*Math.abs(num), 800, {axis:'x', onAfter:function(){block = false}} );
			}
        }   
    }  


/*
 * $('#photosScrollDiv').scrollTo('+=100', 800, {axis:'x'} )
 **/

/****************PlayList**********************/
jQuery.fn.reverse = function() {
    return this.pushStack(this.get().reverse(), arguments);
};
       
var jsPlayerReady = false;   

var myPlayer = null;
var myPlayList = null;

function isPlayerReady() {    
	jsPlayerReady = true; 
	
	setTimeout(function(){sendToPlayerActionScript("getList");}, 10);
	
	return jsPlayerReady;
}

function thisMovie(movieName) {
   /*	 if ($.browser.name == "msie") {
		 return window[movieName];
	 } else {         */
		 return document.getElementById(movieName)//document[movieName];
	 //}
 }

function sendToPlayerActionScript(func, value) {		  					
  	  if ($.browser.name == "msie" /*|| BrowserDetect.browser.indexOf("Safari") != -1*/) {
  		  thisMovie("iemyPlayer").sendToActionScript(func, value);
	 } else {     
		  thisMovie("myPlayer").sendToActionScript(func, value);
  	 }
}
 
function sendToPlayerJavaScript(func, value) {     
	El_objects.myPlayer[func](value);
}         

$(window).unload( function () { 
	sendToPlayerActionScript("unloadPage");   
} ); 

var El_objects = {  
 	myPlayList : null,
  	myPlayer : null,
	lastListUrl : "",
	listLoaded: false
}

var PlayList = function(element){ 
	
	var test = function(){                    
		if (!element || El_objects.myPlayList!=null){ 
			return;
		}
	}()   
	
    var element = $("#"+element),
		items = $("li", element),
		openList = $(".openList", $("#player")),
		instance = this,
		playList_clear = $(".playList_clear", element),
		playingTrack,
		actItem,
		_ul,
		_scD = $("<div class='scrollDiv'/>"),
		$scroll = $("<div class='scroll'/>"),
		k = 0;  
		
	var initVars = function(){
			instance.empty = true;    
			playingTrack = -1;
			actItem = null;
			instance.listID = {};			
			instance.list = []; 			
		}
		
	var sendPlaylistToFlash = function(){   
			sendToPlayerActionScript("addPlaylist", instance.list);
			setScroll();
	}
	
	var setScroll = function(){         
			
		  var ul = $("ul", _scD);
		  if(items.length > 5){   
		  		k = (items.length - 5)*32;  
				_scD.addClass("actScroll");	
		  }else{                    
				_scD.removeClass("actScroll");
		  }
	}

	var addTrackToPlayer = function(o){    			
			instance.stopAll();
			if(playingTrack == o.id){
				El_objects.myPlayer.stop(false);
				playingTrack = -1;
				return;	
			}         
			playingTrack = o.id;   
			actItem = $("."+o.id, element);  		 			
			actItem.addClass("playing");                                          		
	  		El_objects.myPlayer.play(o); 
		}
		
	var delTrackFromPlayList = function(el){
			var el = el.parents('li');                                                    
		    var id = el.attr("class").split(" ")[0];    
			if(playingTrack == id){
				sendToPlayerActionScript("stopSound"); 			    
		  		El_objects.myPlayer.setTitle("");
		  		El_objects.myPlayer.toogleMode();
				playingTrack = -1;
				El_objects.myPlayer.initVars();   
			} 
			
			for(var i=0; i < instance.list.length; i++){
				if(instance.list[i].id == id){     
					instance.list.splice(i, 1);
					break;
				}
			}                           
			delete instance.listID[id];
			el.detach();    
			if($("li", element).length == 0){
				clearPlayList();	
			}   
			items = $("li", element);
			
			sendPlaylistToFlash();
		}
		
		var clearPlayList = function(){  
			El_objects.myPlayer.stop(true);                                        
			openList.toggleClass("openedListBtn");     
			element.slideUp("slow", function() {
			    $("ul", element).detach();
				items = $("li", element);
			});  
			initVars();  
			
			sendPlaylistToFlash(); 
		}              	                               
		this.empty = true;
		this.listID = {};  
		this.list = [];      		
		this.listOpened = false; 
		this.timer = null;                       
		
		this.addTrackToPlaylist = function(o, all, loadPlaylist){      
                                                                      
			if(this.listID[o.id] == 1){     
	  			addTrackToPlayer(o);  
	   			return;
			}                  
			this.listID[o.id] = 1;
			
			this.list.push(o);
		    
			var name = $("<div/>");
			var span = $("<span/>").html(o.name);  

			var audioPlayBtn = $("<a class='audioPlayBtn' title='Играть'/>");
			audioPlayBtn.click(function() {     
				addTrackToPlayer(o);
			}); 
			
			var playList_delete = $("<a class='playList_delete' title='Удалить из плейлиста'/>");
			playList_delete.click(function() {     
				delTrackFromPlayList($(this));
			});   
        
			name.append(span);
			name.append(playList_delete);
 
			var item = $("<li class='"+o.id+"' title='"+o.url+"'/>")
			item.append(audioPlayBtn); 							
			item.append(name);     
			if(this.empty){ 
				if($("ul", element).length < 1){
					_ul = $("<ul>");      
					$(_scD).prepend(_ul);
				}				
				playList_clear.show(); 
				openList.show();    
  				El_objects.myPlayer.setTitle("");                     
			}			
			this.empty = false;
								
			$("ul", element).prepend(item);
			items = $("li", element);	
			
			if(!loadPlaylist){
	 			addTrackToPlayer(o);   
			}
			    
			if(!all){                 
				element.slideDown("slow");
				openList.addClass("openedListBtn");
				sendPlaylistToFlash(); 
				$scroll.slider("value", 100);
			}                  
		}    
		this.setList = function(data){ 
			
			if(El_objects.listLoaded)
				return;     
            El_objects.listLoaded = true;        
				                			                                  
		 	for(var i=0; i < data.list.length; i++){     
				instance.addTrackToPlaylist({id: data.list[i].id, name: data.list[i].name, url: data.list[i].url}, true, true);
		 	} 
                 
	   		El_objects.myPlayer.setVolume(data.vol)
			if(data.isPlaying && data.track != null){ 
				data.track.pos = data.pos; 
	   			addTrackToPlayer(data.track);	
			}          
			setScroll();
		}       
		this.isEmpty = function(){
			return instance.empty;
		}
		       
		this.stopAll = function(){
			items.removeClass("playing");	
		}
		
        this.setPlayingTrack = function(o){       
			$("."+o.id, element).addClass("playing");                   
		}  
		this.getFirstTrack = function(){
			if(this.list.length == 0){
	   //			alert("Лист пустой");
				return;
			} 
			playingTrack = this.list[0].id;     		 			
			$("."+this.list[0].id, element).addClass("playing");                                          		
	  		El_objects.myPlayer.play(this.list[0]);
		}
		
		this.getNext = function(){     
			var next = actItem.next();
			if(next.length > 0){
				var o = {id: next.attr("class"), name: next.text(), url: next.attr("title")};
				addTrackToPlayer(o);
			}
		}  	  
		this.addAll = function(id){
				var items = $("li", $("div[id^="+id+"]"));  
                      
				items.reverse().each(function(index) {  
					instance.addTrackToPlaylist({id: $(this).attr("id"), name: $(this).text(), url: $(this).attr("file")}, true);
			 	}); 
				element.slideDown("slow");
				openList.addClass("openedListBtn");
				
				sendPlaylistToFlash(); 
		}   
		this.toogle = function(){
			if(element.is(":hidden") && !instance.empty){  
				element.slideDown("slow");
				instance.listOpened = true;
			}else{                      
				element.slideUp("slow");
				instance.listOpened = false;
			}
		}    
		var setStyle = function(){ 
			                               
			var toog = false;       
			
			if(items.length > 0)
				instance.empty = false;      
                      
			playList_clear.click(function() {     
				clearPlayList();
			});  	                     
				
			element.mouseleave(function() {       
				var el = $(this);      
				toog = false;    
				
				instance.timer = setInterval(
				    function(){         
						if(!toog && instance.listOpened){
							element.slideUp("slow");
							toog = false; 							
						}	
						timer = false;
					}, 3000
				); 				
			}); 
			element.mouseover(function() { 
				toog = true; 
				instance.listOpened = true;    
				instance.timer = clearInterval(instance.timer);    
			});
			
			
			$scroll.slider({
					orientation: "vertical", 
					min: 0,
					max: 100,
					value: 100,
				   	slide: function( event, ui ) {    	             
				 	   	_ul.css("top", -((100 - ui.value)*k/100));
					},
					change: function(event, ui) { 
						_ul.css("top", -((100 - ui.value)*k/100));                              
					} 
				});
				
			_scD.bind('mousewheel', function(event, delta) {
		            var dir = delta > 0 ? 1 : -1;   
				   	$scroll.slider("value" , $scroll.slider("value") + dir*15);                      
		            return false;
		    });
			
			_scD.append($scroll);
			element.prepend(_scD)
		}();  
};  
var Player = function(element){   
	                   
		var element = $("#"+element),  
		
		instance = this,  
	
		muted = false,  
		track = {},   
		
		audioPlayBtn = $(".audioPlayBtn", element),
		
		volume = 30,
		temp_vol = -1,
		deltaVolume = 5,
		
		openList = $(".openList", element),
		title = $(".player_title", element),
		
		
		player_mute = $(".player_mute", element),
		volumeBar = $(".volumeBar", element),
		
		player_slider = $(".player_knob" ).slider({
												value: volume, 
												min:0, 
												max:100,
												orientation: 'vertical',
											 	slide: function(event, ui) {
										   			volume = ui.value;
										   			player_mute.removeClass("player_muteOn");
										   			sendToPlayerActionScript("setVolume", volume); 
												},
												change: function(event, ui) { 
													volume = ui.value; 
									   				sendToPlayerActionScript("setVolume", volume);
												}}),
		player_snd_up = $(".player_snd_up", element),
		player_snd_down = $(".player_snd_down", element);      

		this.stopped = true;
		
		this.initVars = function(){
			muted = false;
			instance.stopped = true;
			track = {};
		}
		
		this.initSoundControl = function(){   
			var volumeBarIsShow = false;	
		         
			 player_mute.click(function(){   
			 		if(muted){ 
			 			$(this).removeClass("player_muteOn");   
						player_slider.slider("value" , temp_vol);
						sendToPlayerActionScript("setVolume", temp_vol);			 			
			 		}else{ 
			 		 	temp_vol = volume
			 			$(this).addClass("player_muteOn");
						player_slider.slider("value" , 0);
						sendToPlayerActionScript("setVolume", 0);
			 		}
					muted = !muted;	
			 });
			 
			 player_mute.mouseover(function(){   
			 	if(volumeBar.is(":hidden")){ 
				 	volumeBarIsShow = true;
			 		volumeBar.show();
			 	}			
			 });
			 
			 player_mute.mouseleave(function(){
			 	volumeBarIsShow = false; 
			 	setTimeout(function(){if(!volumeBarIsShow)volumeBar.hide();}, 1000);		
			 });
			 volumeBar.mousemove(function(){ 
			 		volumeBarIsShow = true;  
			 });
			 volumeBar.mouseleave(function(){ 
			 		volumeBarIsShow = false;
			 		volumeBar.hide();   	
			 });
			  
			 player_snd_up.click(function(){
			 		instance.soundLevel(deltaVolume);		
			 });	
			 player_snd_down.click(function(){
			 		instance.soundLevel(-deltaVolume);
			 });  
			 
			 openList.click(function(){    
			 			$(this).toggleClass("openedListBtn");
		  	 			El_objects.myPlayList.toogle();      
			 });
			 title.click(function(){   
			 			openList.toggleClass("openedListBtn");
			 			El_objects.myPlayList.toogle();       
			 });
		 
			 
			 if(El_objects.myPlayList.isEmpty){
			 	title.html("<span>Плейлист пуст</span>");
				openList.hide();	
			 }
		}	
		this.setTitle = function(str){
			  	title.html("<span>"+str+"</span>"); 
		}    
		this.setVolume = function(vol){     
				setTimeout(function(){ 
					if(!isNaN(vol))
						player_slider.slider("value" , vol*100);
					else
						player_slider.slider("value" , volume); 				 
				}, 100)  
		}   
		this.soundLevel = function(delta){ 
			 volume += delta;
			 volume = (volume > 100) ? 100 : volume;
			 volume = (volume < 0) ? 0 : volume;
			 player_slider.slider("value" , volume);
			 if(volume > 0 && player_mute.hasClass("player_muteOn")){
			 	player_mute.removeClass("player_muteOn");	
			 }else if(volume == 0){
			 	player_mute.addClass("player_muteOn");
			 }
		}       
		this.modeAction = function(){
			if(this.stopped){
				sendToPlayerActionScript("stopSound");	
			} else{
				title.html("<span>"+track.name+"</span>");
				El_objects.myPlayList.setPlayingTrack(track);    
	  			sendToPlayerActionScript("playSound", track);
				sendToPlayerActionScript("setVolume", volume);
				$.get("/media/incview/id/"+parseInt(track.id.substring(6)))
			}
		}    
		this.toogleMode = function(){     
			this.stopped = !this.stopped;
			audioPlayBtn.toggleClass("playerStop"); 			
			if(this.stopped)
				El_objects.myPlayList.stopAll();          
		}         
		
		this.stop = function(clear){ 
			if(clear){
				sendToPlayerActionScript("stopSound");
				sendToPlayerActionScript("empty");
				instance.initVars();
				audioPlayBtn.removeClass("playerStop");
		  		title.html("<span>Плейлист пуст</span>");
				openList.hide();  
				return;
			}
			instance.toogleMode();
			instance.modeAction();
		}     
		this.play = function(o){  
			openList.show();                  
			if(track.id == o.id){
				instance.toogleMode();
				instance.modeAction();
			}else{
				track = o;
				if(this.stopped){
					instance.toogleMode();
					instance.modeAction();	
				}else{
					instance.modeAction();
				}
			}                                                     
		}      		
		this.soundCompleteHandler = function(){
			instance.stop(false);
			El_objects.myPlayList.getNext();
		}
		
		this.setPlaylist = function(list){
			El_objects.myPlayList.setList(list);
		}
		this.IOErrorEvent = function(){
			instance.stop(false);
		}
		
		var init = function(){   
			if (!element || El_objects.myPlayer!=null) return;
		  			
			audioPlayBtn.click(function() {  
							if(track.id == undefined){
								El_objects.myPlayList.getFirstTrack();
								return;   
							}
							instance.toogleMode();
							instance.modeAction();
						});
			instance.initSoundControl();    			   
		}()	
	   		
};                                                                 

function setPrimaryPhoto(id_gallery, id_photo){
	var data = {id_gallery: id_gallery, id_photo: id_photo};
	$.ajax({
		type: 'GET',
		url: '/gallery/setprimaryphoto',
		data: data,
		dataType: "json"
	});
}
function deletePhoto(id_photo){
	$('#photo'+id_photo).hide();
	var data = {id_photo: id_photo};
	$.ajax({
		type: 'GET',
		url: '/gallery/deletePhoto',
		data: data,
		dataType: "json"
	});  
}         
function dialog_insert_video(id, file, poster, name, width, height){ 
	
	if(!El_objects.myPlayer.stopped){
		El_objects.myPlayer.stop();
	}	

   	$('#dialog_vid').dialog({dialogClass: 'jui_login_form', width: width+25, resizable:false, draggable:false, modal: true, position: ['center', 50], open: function(event, ui) {
		$('#dialog_vid').html('<object id="video_player'+id+'" type="application/x-shockwave-flash" data="/files/visual/player/uppod.swf" width="'+width+'" height="'+height+'"><param name="allowFullScreen" value="true" /><param name="allowScriptAccess" value="always" /><param name="wmode" value="transparent" /><param name="movie" value="/files/visual/player/uppod.swf" /><param name="flashvars" value="uid=video_player'+id+'&amp;st=/files/visual/player/video76-770.txt&amp;m=video&amp;file='+file+'&amp;poster='+poster+'" /></object><div class="dialog_video_name">'+name+'</div>');
	 setTimeout(function(){
	 	uppodSend('video_player'+id, 'play');
		$.get("/media/incview/id/"+id);
	 }, 1000);            
    }});
}  
$(window).scroll(function () { 
      if($(window).scrollTop() == 0){
      	$(".bottomBar").fadeOut("slow");
      }else if($(".bottomBar").is(":hidden") && $(window).scrollTop() >= 40){
      	$(".bottomBar").fadeIn("slow");
      }               
}); 
var $waypoint_loading = $("<img class='waypoint_loading' src='/images/loading.gif' width='100' height='20'/>");

function initUpload(rnd, list_content_url) {                  
	addListScrollEvent($('#prefoot-' + rnd), rnd, list_content_url);  
}

function addListScrollEvent(el, rnd, new_list_content_url){                 
	
	
	opts = {
		offset: '100%'
	};

	el.waypoint(function(event, direction) {   
		
		list_content_url = (new_list_content_url == undefined) ? list_content_url : list_media_url;
		
	    if(list_content_url == El_objects.lastListUrl)
			return;
			
		El_objects.lastListUrl = list_content_url;
		
		el.waypoint('remove');                         
		$waypoint_loading.insertAfter("#items-" + rnd);
		$.get(list_content_url, {dataType: "text"}).success(function(data) {   
 		  ///костыль для комментов  		
			if(rnd == "comment"){
				$('#items-' + rnd).append($("#items-comment", data).html());
			}else{  		
				$('#items-' + rnd).append(data);
			}
			
			$(".ui-widget-overlay").height(Math.max(document.documentElement.scrollHeight,document.body.scrollHeight));
			
  			$waypoint_loading.detach();                   
			el.waypoint(opts);
			
		}).error(function(){
			$waypoint_loading.detach();
		});                    
	}, opts);	 
}

function initScrollEvent(el, callback){                     
	opts = {
		offset: '100%'
	};   
	el.waypoint(function(event, direction) {  
		el.waypoint('remove');                         
		callback();
	}, opts);	 
}



function myAjax(elementName, url, dataType, responseContainer, data, dataMethod){ 
	var container = $('#'+responseContainer+'');
	$("#page_loader").show();

	$.ajax({
		url: url,
		dataType: dataType,     
		success: function(data){      
			El_objects.lastListUrl = "";
			setTimeout(function(){dataMethod(data, container)}, 10);
			$("#page_loader").hide();
		},                 
		error: function(jqXHR, textStatus, errorThrown) {      
			console.log(jqXHR);
			$("#page_loader").hide();
//			alert(errorThrown);
		}                        		  
	});
}


function load_page(url){          
	 myAjax(null, url, "html", "ajaxContent", null, ajaxHTML);                
}  

var $body = $(document.body);       
var noBinding = false;

(function(window,undefined){              
	
	// Prepare our Variables
	var
		History = window.History,
		$ = window.jQuery,
		document = window.document,
		$content = $("#ajaxContent");
                                               
                                                   
	// Check to see if History.js is enabled for our Browser
	if ( !History ) {        
		return false;
	}

	// Wait for Document
	$(function(){                       
			
		// Prepare Variables
		var $body = $(document.body),
		rootUrl = History.getRootUrl().substr(0, History.getRootUrl().length -1);
		
		// Internal Helper
		$.expr[':'].internal = function(obj, index, meta, stack){
			// Prepare
			var $this = $(obj);	   
			if($this.attr('rel') != undefined && $this.attr('rel').indexOf("noajax") > -1){
				return false;
			} 
			
			return ($this.attr('href') != undefined && $this.attr('href').indexOf("#") != 0 && $this.attr('href') != "" && $this.attr('href').indexOf("http://") < 0 && $this.attr('href').indexOf("/edit") < 0 && $this.attr('href').indexOf("/create") < 0 && $this.attr('href').indexOf("javascript:") < 0); 
		}; 
		
		// При первом запуске, запускаем AJAX на получение содержимого страницы
		//не перегружаем главную страницу и страницы редактирования/добавления/регистранции/и связаные с соц.сетями
		if (History.getLastSavedState().url != _basePageHref && !History.getLastSavedState().url.match(/\/edit|\/create|\/registration|\/recover|\/social|\/search/gi)) {
			myAjax(null, History.getLastSavedState().url, "html", "ajaxContent", null, ajaxHTML);
		}
                
		/*
		alert("0" + location.href.indexOf(History.getRootUrl()+"#") + 
		"\n1" + History.getLastSavedState().url +
		"\n2" + History.getRootUrl() +
		"\n3" + location.href +
		"\n4" + History.getBaseUrl() +
		"\n5" + History.getPageUrl() +
		"\n6" + History.getBasePageUrl() +
		"\n7" + History.getFullUrl(History.getLastSavedState().url));
		 */
				
		// Ajaxify Helper
		$.fn.ajaxify = function(){   

			// Prepare
			var $this = $(this);
			$this.find('a:internal').live('click', function(event) {

				if ($(this).attr('href').indexOf('mailto:') >= 0 || $(this).attr('href').indexOf('callto:') >= 0) {
					return true;
				}
				
				event.preventDefault(); 
				
				// Prepare         
				var $this = $(this),
					url = rootUrl + $(this).attr('href'),  					 
					title = $this.attr('title')||null;    
				
				// Если Internet Explorer
				if($.browser.name == "msie" && (location.href.indexOf("/edit") >= 0 || location.href.indexOf("/create") >= 0 || location.href.indexOf("/registration") >= 0 || location.pathname.charAt(1)!="#" )){ 
					var toUrl = $(this).attr('href');

					// Вырезаем передний слэш для IE чтобы все ссылки были одинаковые если мы находимся на главной страницы
					if (toUrl.charAt(0) == '/') {
						toUrl = toUrl.substr(1, toUrl.length);
					}
					
					// Проверяем находимся ли мы в индексе или нет
					if (location.href.indexOf(History.getRootUrl()+"#") == 0) {											
						// Запускаем сохранение истории и переадресацию на новую страницу
						var currentState = History.extractState(rootUrl + '/#' + toUrl,true);
						var newState = History.createStateObject(currentState.data,currentState.title,currentState.url),
						newStateHash = History.getHashByState(newState);						
						History.setHash(newStateHash,false);
					} else {
						location.replace(rootUrl+"/#"+toUrl);
					}
					return;											
					
					
				}           
				noBinding = true;  
			


				// Continue as normal for cmd clicks etc
				if ( event.which == 2 || event.metaKey ) {return true;}
                                              
                // Ajaxify this link 
				if($.browser.name == "msie"){           
					History.pushState(null,null,url);
				}else{
	 	   			History.pushState(null,title,url);
				}    		                             
				myAjax(null, url, "html", "ajaxContent", null, ajaxHTML);
				
				return false;
			});              
	     
			// Chain
			return $this;                          
		};

		// Ajaxify our Internal Links
		if($.cookie('ajaxify') == null || $.cookie('ajaxify')==0)
		$body.ajaxify();         

		// Hook into State Changes
		$(window).bind('statechange',function(){               
			// Prepare Variables
			var State = History.getState(),
				url = State.url;    
			if(!noBinding)
   	 	   		myAjax(null, url, "html", "ajaxContent", null, ajaxHTML); 

		});

	});

})(window); // end closure

                 
// HTML Helper
var documentHtml = function(html){
	// Prepare
	var result = String(html)
		.replace(/<\!DOCTYPE[^>]*>/i, '')
		.replace(/<(html|head|body|title|meta|script)([\s\>])/gi,'<div class="document-$1"$2')
		.replace(/<\/(html|head|body|title|meta|script)\>/gi,'</div>')
	;            
	// Return
	return result;
};


function ajaxHTML(data, container){           
	
		noBinding = false;     

// Fetch the scripts
		var $data = $(documentHtml(data)),
		contentSelector = '#ajaxContent', 
		$content = $(contentSelector).filter(':first'),
 		contentNode = $content.get(0),  					
		$hScripts = ('head', $data).find('.document-script'),
		$hStyles = ('head', $data).find('link[rel=stylesheet]'),
		$dataBody = $data.find('.document-body:first'),
		$dataContent = $dataBody.find(contentSelector).filter(':first'),
		contentHtml, $scripts;    
		
		// Fetch the scripts
		$scripts = $dataContent.find('.document-script');   

		if ( $scripts.length ) {
			$scripts.detach();
		}
		
		// Fetch the content
		contentHtml = $dataContent.html() || $data.html();
		if (!contentHtml) {
//			document.location.href = url;
			return false;
		}                                    
		// Update the content       
		container.html(contentHtml);
		
		// Update the title
		document.title = $data.find('.document-title:first').text();
		try {
			document.getElementsByTagName('title')[0].innerHTML = document.title.replace('<','&lt;').replace('>','&gt;').replace(' & ',' &amp; ');
		}
		catch ( Exception ) { }     

		// Fetch the headStyles       
	  	var hStylesArr = [];
		$hStyles.each(function(){               
			 hStylesArr.push($(this).attr("href")) 
		}); 
		
		$('head').find('link[rel=stylesheet]').each(function(){
			for(var i=0; i < hStylesArr.length; i++){
				if($(this).attr("href") == hStylesArr[i]){
					hStylesArr.splice(i, 1);	
				}
			}
		});
		
		for(var i = 0; i < hStylesArr.length; i++){                          
			var link = document.createElement( 'link' );
			link.rel = 'stylesheet';
			link.href = hStylesArr[i];
			$("head").append(link);   
		} 
		
		
		// Fetch the headScripts                    
	  	var hScriptsArr = [];
		$hScripts.each(function(){
   //			 console.log($(this).attr("src"));
			 if($(this).attr("src") != undefined)
			 	hScriptsArr.push($(this).attr("src")) 
		}); 
		
		$('head').find('script').each(function(){
			for(var i=0; i < hScriptsArr.length; i++){
				if($(this).attr("src") == hScriptsArr[i]){
					hScriptsArr.splice(i, 1);	
				}
			}
		});
		
		for(var i = 0; i < hScriptsArr.length; i++){                         
			var script = document.createElement( 'script' );
			script.type = 'text/javascript';
			script.src = hScriptsArr[i];
			$("head").append(script);   
		}	         		
		
	    // Add the scripts  
  		var scr = "<script>";
		$scripts.each(function(){   
			scr += $(this).html()+"\n"
		});
		scr += "</script>";			
		
		/// add #userButtons                                                        
		$("#userButtons").html($("#userButtons",$data).html())
		       
	    container.append($(scr)); 
		
		var newUrl = History.getState().url;
		if(newUrl.indexOf("/photo/") < 0)                		
   			$.scrollTo(0, 200, {duration: 800,easing:'swing'});
}      

// jQuery UI Dialog 1.8.14           
(function(c,l){var m={buttons:true,height:true,maxHeight:true,maxWidth:true,minHeight:true,minWidth:true,width:true},n={maxHeight:true,maxWidth:true,minHeight:true,minWidth:true},o=c.attrFn||{val:true,css:true,html:true,text:true,data:true,width:true,height:true,offset:true,click:true};c.widget("ui.dialog",{options:{autoOpen:true,buttons:{},closeOnEscape:true,overlayClick:false,closeText:"close",dialogClass:"",draggable:true,hide:null,height:"auto",maxHeight:false,maxWidth:false,minHeight:150,minWidth:150,modal:false,
position:{my:"center",at:"center",collision:"fit",using:function(a){var b=c(this).css(a).offset().top;b<0&&c(this).css("top",a.top-b)}},resizable:true,show:null,stack:true,title:"",width:300,zIndex:1E3},_create:function(){this.originalTitle=this.element.attr("title");if(typeof this.originalTitle!=="string")this.originalTitle="";this.options.title=this.options.title||this.originalTitle;var a=this,b=a.options,d=b.title||"&#160;",e=c.ui.dialog.getTitleId(a.element),g=(a.uiDialog=c("<div></div>")).appendTo(document.body).hide().addClass("ui-dialog ui-widget ui-widget-content ui-corner-all "+
b.dialogClass).css({zIndex:b.zIndex}).attr("tabIndex",-1).css("outline",0).keydown(function(i){if(b.closeOnEscape&&i.keyCode&&i.keyCode===c.ui.keyCode.ESCAPE){a.close(i);i.preventDefault()}}).attr({role:"dialog","aria-labelledby":e}).mousedown(function(i){a.moveToTop(false,i)});a.element.show().removeAttr("title").addClass("ui-dialog-content ui-widget-content").appendTo(g);var f=(a.uiDialogTitlebar=c("<div></div>")).addClass("ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix").prependTo(g),
h=c('<a href="#"></a>').addClass("ui-dialog-titlebar-close ui-corner-all").attr("role","button").hover(function(){h.addClass("ui-state-hover")},function(){h.removeClass("ui-state-hover")}).focus(function(){h.addClass("ui-state-focus")}).blur(function(){h.removeClass("ui-state-focus")}).click(function(i){a.close(i);return false}).appendTo(f);(a.uiDialogTitlebarCloseText=c("<span></span>")).addClass("ui-icon ui-icon-closethick").text(b.closeText).appendTo(h);c("<span></span>").addClass("ui-dialog-title").attr("id",
e).html(d).prependTo(f);if(c.isFunction(b.beforeclose)&&!c.isFunction(b.beforeClose))b.beforeClose=b.beforeclose;f.find("*").add(f).disableSelection();b.draggable&&c.fn.draggable&&a._makeDraggable();b.resizable&&c.fn.resizable&&a._makeResizable();a._createButtons(b.buttons);a._isOpen=false;c.fn.bgiframe&&g.bgiframe()},_init:function(){this.options.autoOpen&&this.open()},destroy:function(){var a=this;a.overlay&&a.overlay.destroy();a.uiDialog.hide();a.element.unbind(".dialog").removeData("dialog").removeClass("ui-dialog-content ui-widget-content").hide().appendTo("body");
a.uiDialog.remove();a.originalTitle&&a.element.attr("title",a.originalTitle);return a},widget:function(){return this.uiDialog},close:function(a){var b=this,d,e;if(false!==b._trigger("beforeClose",a)){b.overlay&&b.overlay.destroy();b.uiDialog.unbind("keypress.ui-dialog");b._isOpen=false;if(b.options.hide)b.uiDialog.hide(b.options.hide,function(){b._trigger("close",a)});else{b.uiDialog.hide();b._trigger("close",a)}c.ui.dialog.overlay.resize();if(b.options.modal){d=0;c(".ui-dialog").each(function(){if(this!==
b.uiDialog[0]){e=c(this).css("z-index");isNaN(e)||(d=Math.max(d,e))}});c.ui.dialog.maxZ=d}return b}},isOpen:function(){return this._isOpen},moveToTop:function(a,b){var d=this,e=d.options;if(e.modal&&!a||!e.stack&&!e.modal)return d._trigger("focus",b);if(e.zIndex>c.ui.dialog.maxZ)c.ui.dialog.maxZ=e.zIndex;if(d.overlay){c.ui.dialog.maxZ+=1;d.overlay.$el.css("z-index",c.ui.dialog.overlay.maxZ=c.ui.dialog.maxZ)}a={scrollTop:d.element.attr("scrollTop"),scrollLeft:d.element.attr("scrollLeft")};c.ui.dialog.maxZ+=
1;d.uiDialog.css("z-index",c.ui.dialog.maxZ);d.element.attr(a);d._trigger("focus",b);return d},open:function(){if(!this._isOpen){var a=this,b=a.options,d=a.uiDialog;a.overlay=b.modal?new c.ui.dialog.overlay(a):null;a._size();a._position(b.position);d.show(b.show);a.moveToTop(true);b.modal&&d.bind("keypress.ui-dialog",function(e){if(e.keyCode===c.ui.keyCode.TAB){var g=c(":tabbable",this),f=g.filter(":first");g=g.filter(":last");if(e.target===g[0]&&!e.shiftKey){f.focus(1);return false}else if(e.target===
f[0]&&e.shiftKey){g.focus(1);return false}}});c(a.element.find(":tabbable").get().concat(d.find(".ui-dialog-buttonpane :tabbable").get().concat(d.get()))).eq(0).focus();a._isOpen=true;a._trigger("open");return a}},_createButtons:function(a){var b=this,d=false,e=c("<div></div>").addClass("ui-dialog-buttonpane ui-widget-content ui-helper-clearfix"),g=c("<div></div>").addClass("ui-dialog-buttonset").appendTo(e);b.uiDialog.find(".ui-dialog-buttonpane").remove();typeof a==="object"&&a!==null&&c.each(a,
function(){return!(d=true)});if(d){c.each(a,function(f,h){h=c.isFunction(h)?{click:h,text:f}:h;var i=c('<button type="button"></button>').click(function(){h.click.apply(b.element[0],arguments)}).appendTo(g);c.each(h,function(j,k){if(j!=="click")j in o?i[j](k):i.attr(j,k)});c.fn.button&&i.button()});e.appendTo(b.uiDialog)}},_makeDraggable:function(){function a(f){return{position:f.position,offset:f.offset}}var b=this,d=b.options,e=c(document),g;b.uiDialog.draggable({cancel:".ui-dialog-content, .ui-dialog-titlebar-close",
handle:".ui-dialog-titlebar",containment:"document",start:function(f,h){g=d.height==="auto"?"auto":c(this).height();c(this).height(c(this).height()).addClass("ui-dialog-dragging");b._trigger("dragStart",f,a(h))},drag:function(f,h){b._trigger("drag",f,a(h))},stop:function(f,h){d.position=[h.position.left-e.scrollLeft(),h.position.top-e.scrollTop()];c(this).removeClass("ui-dialog-dragging").height(g);b._trigger("dragStop",f,a(h));c.ui.dialog.overlay.resize()}})},_makeResizable:function(a){function b(f){return{originalPosition:f.originalPosition,
originalSize:f.originalSize,position:f.position,size:f.size}}a=a===l?this.options.resizable:a;var d=this,e=d.options,g=d.uiDialog.css("position");a=typeof a==="string"?a:"n,e,s,w,se,sw,ne,nw";d.uiDialog.resizable({cancel:".ui-dialog-content",containment:"document",alsoResize:d.element,maxWidth:e.maxWidth,maxHeight:e.maxHeight,minWidth:e.minWidth,minHeight:d._minHeight(),handles:a,start:function(f,h){c(this).addClass("ui-dialog-resizing");d._trigger("resizeStart",f,b(h))},resize:function(f,h){d._trigger("resize",
f,b(h))},stop:function(f,h){c(this).removeClass("ui-dialog-resizing");e.height=c(this).height();e.width=c(this).width();d._trigger("resizeStop",f,b(h));c.ui.dialog.overlay.resize()}}).css("position",g).find(".ui-resizable-se").addClass("ui-icon ui-icon-grip-diagonal-se")},_minHeight:function(){var a=this.options;return a.height==="auto"?a.minHeight:Math.min(a.minHeight,a.height)},_position:function(a){var b=[],d=[0,0],e;if(a){if(typeof a==="string"||typeof a==="object"&&"0"in a){b=a.split?a.split(" "):
[a[0],a[1]];if(b.length===1)b[1]=b[0];c.each(["left","top"],function(g,f){if(+b[g]===b[g]){d[g]=b[g];b[g]=f}});a={my:b.join(" "),at:b.join(" "),offset:d.join(" ")}}a=c.extend({},c.ui.dialog.prototype.options.position,a)}else a=c.ui.dialog.prototype.options.position;(e=this.uiDialog.is(":visible"))||this.uiDialog.show();this.uiDialog.css({top:0,left:0}).position(c.extend({of:window},a));e||this.uiDialog.hide()},_setOptions:function(a){var b=this,d={},e=false;c.each(a,function(g,f){b._setOption(g,f);
if(g in m)e=true;if(g in n)d[g]=f});e&&this._size();this.uiDialog.is(":data(resizable)")&&this.uiDialog.resizable("option",d)},_setOption:function(a,b){var d=this,e=d.uiDialog;switch(a){case "beforeclose":a="beforeClose";break;case "buttons":d._createButtons(b);break;case "closeText":d.uiDialogTitlebarCloseText.text(""+b);break;case "dialogClass":e.removeClass(d.options.dialogClass).addClass("ui-dialog ui-widget ui-widget-content ui-corner-all "+b);break;case "disabled":b?e.addClass("ui-dialog-disabled"):
e.removeClass("ui-dialog-disabled");break;case "draggable":var g=e.is(":data(draggable)");g&&!b&&e.draggable("destroy");!g&&b&&d._makeDraggable();break;case "position":d._position(b);break;case "resizable":(g=e.is(":data(resizable)"))&&!b&&e.resizable("destroy");g&&typeof b==="string"&&e.resizable("option","handles",b);!g&&b!==false&&d._makeResizable(b);break;case "title":c(".ui-dialog-title",d.uiDialogTitlebar).html(""+(b||"&#160;"));break}c.Widget.prototype._setOption.apply(d,arguments)},_size:function(){var a=
this.options,b,d,e=this.uiDialog.is(":visible");this.element.show().css({width:"auto",minHeight:0,height:0});if(a.minWidth>a.width)a.width=a.minWidth;b=this.uiDialog.css({height:"auto",width:a.width}).height();d=Math.max(0,a.minHeight-b);if(a.height==="auto")if(c.support.minHeight)this.element.css({minHeight:d,height:"auto"});else{this.uiDialog.show();a=this.element.css("height","auto").height();e||this.uiDialog.hide();this.element.height(Math.max(a,d))}else this.element.height(Math.max(a.height-
b,0));this.uiDialog.is(":data(resizable)")&&this.uiDialog.resizable("option","minHeight",this._minHeight())}});c.extend(c.ui.dialog,{version:"1.8.14",uuid:0,maxZ:0,getTitleId:function(a){a=a.attr("id");if(!a){this.uuid+=1;a=this.uuid}return"ui-dialog-title-"+a},
overlay:function(a){
	this.$el=c.ui.dialog.overlay.create(a);
	if(a.options.overlayClick)
		this.$el.click(function(){a.close()});
	}
});

c.extend(c.ui.dialog.overlay,{instances:[],oldInstances:[],maxZ:0,events:c.map("focus,mousedown,mouseup,keydown,keypress,click".split(","),function(a){return a+".dialog-overlay"}).join(" "),
create:function(a){if(this.instances.length===0){setTimeout(function(){c.ui.dialog.overlay.instances.length&&c(document).bind(c.ui.dialog.overlay.events,function(d){if(c(d.target).zIndex()<c.ui.dialog.overlay.maxZ)return false})},1);c(document).bind("keydown.dialog-overlay",function(d){if(a.options.closeOnEscape&&d.keyCode&&d.keyCode===c.ui.keyCode.ESCAPE){a.close(d);d.preventDefault()}});c(window).bind("resize.dialog-overlay",c.ui.dialog.overlay.resize)}var b=(this.oldInstances.pop()||c("<div></div>").addClass("ui-widget-overlay")).appendTo(document.body).css({width:this.width(),
height:this.height()});c.fn.bgiframe&&b.bgiframe();this.instances.push(b);return b},destroy:function(a){var b=c.inArray(a,this.instances);b!=-1&&this.oldInstances.push(this.instances.splice(b,1)[0]);this.instances.length===0&&c([document,window]).unbind(".dialog-overlay");a.remove();var d=0;c.each(this.instances,function(){d=Math.max(d,this.css("z-index"))});this.maxZ=d},height:function(){var a,b;if(c.browser.msie&&c.browser.version<7){a=Math.max(document.documentElement.scrollHeight,document.body.scrollHeight);
b=Math.max(document.documentElement.offsetHeight,document.body.offsetHeight);return a<b?c(window).height()+"px":a+"px"}else return c(document).height()+"px"},width:function(){var a,b;if(c.browser.msie){a=Math.max(document.documentElement.scrollWidth,document.body.scrollWidth);b=Math.max(document.documentElement.offsetWidth,document.body.offsetWidth);return a<b?c(window).width()+"px":a+"px"}else return c(document).width()+"px"},resize:function(){var a=c([]);c.each(c.ui.dialog.overlay.instances,function(){a=
a.add(this)});a.css({width:0,height:0}).css({width:c.ui.dialog.overlay.width(),height:c.ui.dialog.overlay.height()})}});c.extend(c.ui.dialog.overlay.prototype,{destroy:function(){c.ui.dialog.overlay.destroy(this.$el)}})})(jQuery);
;



function setcookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}
function eraseCookie(name) {
	createCookie(name,"",-1);
}
function menuToogle(){                                                  
	
	var toogleLinks = function(its){                    
		for (var i=0; i<its.length; i++){
			its[i].className = '';
			//document.getElementById(its[i].rel).style.display='none';
			$("#"+its[i].rel).fadeOut();
		}	
	}	   
	var its = document.getElementById("e2e4").getElementsByTagName('a');     
	if(readCookie('calendar_tabs-1')!==null){
		for (var i=0; i<its.length; i++){
			its[i].className = '';
			document.getElementById(its[i].rel).style.display = 'none';
		}
	}
	for (var i=0; i<its.length; i++){		                           
		if(readCookie('calendar_tabs-1')!==null && its[i].rel == readCookie('calendar_tabs-1')) {
			its[i].className = 'act';
			document.getElementById(its[i].rel).style.display = 'block';
		}
		its[i].onclick = function(){
			toogleLinks(its);
			this.className = 'act';
			//document.getElementById(this.rel).style.display='block';
			$("#"+this.rel).delay("400").fadeIn();
			setcookie('calendar_tabs-1',this.rel,7);
			return false;	
		}
	}
}         

var showHDimage = function(url, w, h){  
	var hd_container = $("<div id='hd_photo' style='display: none'/>");  
	$("body").append(hd_container);		     
	hd_container.dialog({dialogClass: 'jui_create_form', width: (w+35), height: (h+35), resizable: false, position: ["center", "center"], modal: true, overlayClick:true, open: function(){  			
		hd_container.html($('<img src='+url+' width='+w+' height='+h+' />'));          
	}, close: function(){
		$(this).remove();
	}});
	hd_container.click(function(){
		$(this).dialog("close");
		$(this).remove();	
	});
}

var answerComment = function(el, area, val){
	var xx = $(el).parents('.txt').offset().left;
	var yy = $(el).parents('.txt').offset().top + $(el).parents('.txt').height() - $(window).scrollTop() + 20;      	
	                                               
  	yy = ((yy + 176) > $(window).height()) ? ($(el).parents('.txt').offset().top - $(window).scrollTop() - 176) : yy;
	
	$('.overflow_comment').removeClass('overflow_comment');     
	                                  
	area.val(val); 
	
	$('#dialog_comment_form').dialog({
			dialogClass: 'jui_login_form',
			modal: false,
			resizable: false,
			position: [xx,yy],
			width: 296,
			close: function(event, ui){$('.overflow_comment').removeClass('overflow_comment');},
			open: function(event, ui) {							 	
			}
		}); 
	$(el).parents('.txt').addClass('overflow_comment');
}

var removeComment = function(el, area, val){
	if(window.confirm("Удалить комментарий?")){
		$.get("/comment/ajaxRemove", {id: val}, function(data){$("#c"+val).hide()});
	}
}
	 
var showGoogleMap = function(data, form){
    	var googlemap_container = $("<div id='googlemap_container' style='width: 780px; height: 480px; display: none'/>");  	
    	var gogle_map = $("<div id='googleMap' style='width:765px;height:460px;display:none'/>");
		$("body").append(googlemap_container.append(gogle_map));		     
		googlemap_container.dialog({dialogClass: 'jui_create_form', width: 800, height: 500, resizable: false, position: ["center", "center"], modal: true, overlayClick:true, open: function(){ 
			if(form){           
				console.log(data)
				initGoogleMap(form, data);
			}else
				initGoogleMap(form, {name: '<h3>'+data.name+'</h3><br/>'+data.address+'', coords: data.coords});            
		}, close: function(){
			$(this).remove();
		}});
		googlemap_container.click(function(){
	//		$(this).dialog("close");
	 //		$(this).remove();	
		}); 
}         
	
var blockForm = function(id){ 
	$('#form_login').hide(); 
	$('#form_loader').show(); 
	$('#login_authoring').show(); 
	$('#login_reg_btn').hide();                  
	$('#login_soc').hide();
}
var unBlockForm = function(id){
	$('#form_login').show(); 
	$('#form_loader').hide(); 
	$('#login_authoring').hide(); 
	$('#login_reg_btn').show(); 
	$('#login_soc').show(); 
}


function fbsGetUrl(appid, id) {
	fbsid = id;
	FB.init({
		appId  : appid,
		status : true, // check login status
		cookie : true, // enable cookies to allow the server to access the session
		xfbml  : true  // parse XFBML
	});
	FB.getLoginStatus(function(response) {
		if (response.session) {
			if (response.session.uid != "") {
				document.getElementById(fbsid).value = "http://facebook.com/profile.php?id=" + response.session.uid;
			}
		}
	});
}  
function vkGetUrl(appid, id) {
	vkid = id;
	VK.init({
		apiId: appid
	});
	
	VK.Auth.login(function (response) {
		if (response.session) {
			if (response.session.mid != "") {
				document.getElementById(vkid).value = "http://vkontakte.ru/id" + response.session.mid;;
			}
		}
	});
}       
function updateSocial(type, appid, path, id) {
	if (type == "fbs") {
		FB.init({
			appId  : appid,
			status : true, // check login status
			cookie : true, // enable cookies to allow the server to access the session
			xfbml  : true  // parse XFBML
		});
		FB.getLoginStatus(function(response) {
			if (response.session) {
				if (response.session.uid != "") {
					$.post(path + "/uid/" + response.session.uid, "", function(data) {
						$("#" + id).html(data);
					});
				}
			}
		});
	} else if (type == "vk") {
		VK.init({
			apiId: appid
		});

		VK.Auth.login(function (response) {
			if (response.session) {
				if (response.session.mid != "") {
					$.post(path + "/uid/" + response.session.mid, "", function(data) {
						$("#" + id).html(data);
					});
				}
			}
		});
	}
}
var profiles_search_timeout;
function updateProfiles(typeId, wordId) {
	var type = document.getElementById(typeId).options[document.getElementById(typeId).selectedIndex].value;
	//var order = document.getElementById(orderId).options[document.getElementById(orderId).selectedIndex].value;
	var word = document.getElementById(wordId).value;
	var cat = $(".mTabs2 .act").attr("id");
	var cat_id = cat.substr(3, 1);
	path = '/profiles/ajaxFlowLoad/cat/'+ cat_id + '/type/' + type + '/limit/' + limit + ((word != "" && word != "поиск")?'/word/' + word:"");    
	id = 'profilesList';
	clearTimeout(profiles_search_timeout);
	profiles_search_timeout = setTimeout('sentData(path, id)', 500);
}    
function updateProfilesCategory(catId) {
	path = '/profiles/ajaxFlowLoad/cat/' + catId + '/limit/' + limit;
	path_select = '/profiles/ajaxLoadSelect/cat/' + catId;
	id = 'profilesList';
	id_select = 'type';
	sentData(path, id);
	$.post(path_select, "", function(data) {
        $("#" + id_select).html(data);
		$('.el_select.el_select_noicons').remove();
		$('#type').show();
		$('#type').el_select({height: 150, width: 130, icons: false});
		$("#page_loader").hide(); 
    });
	$("#page_loader").show(); 
	$(".mTabs2 li").attr("class", "");
	$("#cat"+catId).attr("class", "act");
	$("#rating_sort").attr("class", "sort");
	$("#abc_sort").attr("class", "sort act");
}
function updateProfilesOrder(order) {
	var cat = $(".mTabs2 .act").attr("id");
	var cat_id = cat.substr(3, 1);
	path = '/profiles/ajaxFlowLoad/cat/' + cat_id + '/order/' + order + '/limit/' + limit;   
	id = 'profilesList';
	sentData(path, id);
	if (order == 'abc') {
		$("#rating_sort").attr("class", "sort");
		$("#abc_sort").attr("class", "sort act");
	} else {
		$("#abc_sort").attr("class", "sort");
		$("#rating_sort").attr("class", "sort act");
	}
}
function eventInvReject(id_event) {
	$.ajax({
		type: 'GET',
		url: '/event/inviteReject',
		data: {id_event: id_event},
		dataType: "json",
		success: function(data){
			if(data.url){
				sentData('/event/updateViewEventInvites/id_event/' + id_event, 'refreshable');
			}
		}
	});
}  
function eventInvConfirm(id_event) {
	$.ajax({
		type: 'GET',
		url: '/event/inviteConfirm',
		data: {id_event: id_event},
		dataType: "json",
		success: function(data){
			if(data.url){
				sentData('/event/updateViewEventInvites/id_event/' + id_event, 'refreshable');
			}
		}
	});
}    
function deleteElement(type, id, removeId) {
	$.ajax({
		type: 'GET',
		url: '/' + type + '/delete/agree/true/partial/true',
		data: {id: id},
		dataType: "json",
		success: function(data){
			$("#" + removeId).remove();
		}
	});
} 
function eventInvite(id_event){
	$.ajax({
		type: 'GET',
		url: '/event/invite',
		data: {id_event: id_event, all: true},
		dataType: "json",
		success: function(data){
			$dialog = $("#all-invite-message").dialog({dialogClass: 'flash_window', modal: true, resizable: false});
			$("#all-invite-message a").click(function(){
				$dialog.dialog('close');
			});
			sentData('/event/updateViewEventInvites/id_event/' + id_event, 'refreshable');
		}
	});
}
//AndRefresh
function eventInviteConfirmAndRefresh(id_event, id, path){
	$.ajax({
		type: 'GET',
		url: '/event/inviteConfirm',
		data: {id_event: id_event},
		dataType: "json",
		success: function(data){
			if(data.url){
				refreshIt(id, path);
			}
		}
	});
}
function eventInviteRejectAndRefresh(id_event, id, path){
	$.ajax({
		type: 'GET',
		url: '/event/inviteReject',
		data: {id_event: id_event},
		dataType: "json",
		success: function(){
			refreshIt(id, path);
		}
	});
} 
function eventInviteConfirm(id_event){
	$.ajax({
		type: 'GET',
		url: '/event/inviteConfirm',
		data: {id_event: id_event},
		dataType: "json",
		success: function(data){
			if(data.url){
				$('#event_invites_conteiner').append($("<a class='account_link' href='"+data.url+"'>"+data.text+"</a>"));
				$('#event_invites_buttons').hide();
			}
		}
	});
}
function eventInviteReject(id_event){
	$.ajax({
		type: 'GET',
		url: '/event/inviteReject',
		data: {id_event: id_event},
		dataType: "json",
		success: function(){
			$('#event_invites_buttons').hide();
		}
	});
}

function eventAttachMember(select_name){
	var select = window[select_name], counter = $('#event_members_list').children().length, coll;
	if(select.getText() != ''){
		coll = $('#event_members_list input');
		var text = select.getText().substr(0,select.getText().length-1).split(",");
		var ids = select.getValue().substr(0,select.getValue().length-1).split(",");
		for (el in text) {
			for(var i = 0; i < coll.length; i++){
				if(coll[i].name.match(/\[id_account]/i) != null && coll[i].value == ids[el]
					|| coll[i].name.match(/\[name\]/i) != null && coll[i].value == text[el]){
					return false;
				}
			}
			var li = '<li class="ui-state-default">'
				+'<input id="Event-members_-'+counter+'-id" type="hidden" name="Event[members_]['+counter+'][id]" value="0"/>'
				+'<input type="hidden" name="Event[members_]['+counter+'][id_account]" value="'+ids[el]+'"/>'
				+'<input type="hidden" name="Event[members_]['+counter+'][name]" value="'+text[el]+'"/>'
				+text[el]
				+'<a class="ui-icon ui-icon-close" title="Удалить" onclick="eventDetachMember(\'Event-members_-'+counter+'-id\')">X</a>'
				+'</li>';
			$('#event_members_list').append(li);
			counter++;
		}
		select.reset();
	}
	return false;
}
function eventDetachMember(button){
	var f = $('#'+button), name = f.attr('name');
	f.parent().hide();
	name = name.replace("[id]", "[id_delete]");
	f.attr('name', name);
}


function eventDeleteMember(id) {
	$.ajax({
		type: 'post',
		url: '/event/DeleteMember',
		data: {id: id},
		success: function(){
			$("#member_"+id).remove();
		}
	});
}

/**
 * Отправляет ajax запрос на сервер и выводить в диалоговое окно сообщение.
 * Если пользователь отметил сам себя, то добавляем имя в список (HTML приходит в ответе от сервера )
 */
function createMark(id_photo, select_name){
	var select = window[select_name];
	if(!id_photo || !select) return;
	$.ajax({
		type: 'GET',
		url: '/gallery/CreateMark',
		data: {id_account: select.getValue(), id_photo: id_photo, area_x1: 0, area_y1: 0, area_x2: 0, area_y2: 0},
		dataType: "json",
		success: function(data){
			if(data.success && data.message){
				$('#CreateMarkReportDialog p').text(data.message);
				$('#CreateMarkReportDialog').dialog({
					dialogClass: 'flash_window', 
					modal: true, 
					resizable: false, 
					draggable: false
				});
			}
			/* Добавляем имя в список если вернули html */
			if(data.success && data.html){
				$('#MarkedUserList').show();
				$('#MarkedUserList ul').append(data.html);
			}
		}
	});
	select.reset();
	$('#CreateMarkDialog').hide();
}
/**
 * Отправляет запрос подтверждающий отметку на фото и скрывает кнопку
 */
function confirmMark2(button, id_photo){
	$.ajax({
		type: 'GET',
		url: '/gallery/ConfirmMark',
		data: {id_photo: id_photo, from: 'photo_page'},
		dataType: "json",
		success: function(data){
			if(data.success){
				$(button).hide();
			}
		}
	});  	                                    
}
/**
 * Отправляет запрос удаляющий отметку на фото и скрывает запись из списка
 */
function deleteMark2(id_item, id_photo){
	$.ajax({
		type: 'GET',
		url: '/gallery/DeleteMark',
		data: {id_photo: id_photo, from: 'photo_page'},
		dataType: "json",
		success: function(data){
			if(data.success){
				$(id_item).hide();
			}
		}
	});  
}  
function confirmMark(id_item, id_photo){
	var data = {id_photo: id_photo};
	$.ajax({
		type: 'GET',
		url: '/gallery/ConfirmMark',
		data: data,
		dataType: "html",
		success: function(data){             
		   	$("#picturesContainer").html(data);    
		},
		error: function(jqXHR, textStatus, errorThrown){ }  
	});  	                                    
}    
function deleteMark(id_item, id_photo){
	var data = {id_photo: id_photo};
	$.ajax({
		type: 'GET',
		url: '/gallery/DeleteMark',
		data: data,
		dataType: "html",
		success: function(data){
			$("#picturesContainer").html(data);
		}
	});  
}  
function waveAttachAccount(select_name){
	var select = window[select_name], coll;
	if(select.getValue() != '' && select.getValue() != 0){
		coll = $('#event_members_list input[type=hidden]');
		for(var i = 0; i < coll.length; i++){
			if(coll[i].value == select.getValue()){
				return false;
			}
		}
		var li = '<li class="ui-state-default">'
			+'<input type="hidden" name="Wave[accounts][]" value="'+select.getValue()+'"/>'
			+select.getText()
			+'<a class="ui-icon ui-icon-close" title="Удалить" onclick="waveDetachAccount(this)">X</a>'
			+'</li>';
		$('#event_members_list').append(li);
		select.reset();
	}
	return false;
}  
function waveDetachAccount(button){
	$(button).parent().detach();
	return false;
}  
function orgAttachMember(select_name){
	var select = window[select_name], counter = $('#user_members_list').children().length, coll;
	if(select.getText() != ''){
		coll = $('#user_members_list input');
		for(var i = 0; i < coll.length; i++){
			if(coll[i].name.match(/\[id_account]/i) != null && coll[i].value == select.getValue()
				|| coll[i].name.match(/\[name\]/i) != null && coll[i].value == select.getText()){
				return false;
			}
		}
		var li = '<li class="ui-state-default">'
			+'<input id="User-members_-'+counter+'-id" type="hidden" name="User[members_]['+counter+'][id]" value="0"/>'
			+'<input type="hidden" name="User[members_]['+counter+'][id_account]" value="'+select.getValue()+'"/>'
			+'<input type="hidden" name="User[members_]['+counter+'][name]" value="'+select.getText()+'"/>'
			+select.getText()
			+'<a class="ui-icon ui-icon-close" title="Удалить" onclick="orgDetachMember(\'User-members_-'+counter+'-id\')">X</a>'
			+'</li>';
		$('#user_members_list').append(li);
		select.reset();
	}
	return false;
}
function orgDetachMember(button){
	var f = $('#'+button), name = f.attr('name');
	f.parent().hide();
	name = name.replace("[id]", "[id_delete]");
	f.attr('name', name);
}
      
