function extend() {
  var target = arguments[0] || {}, i = 1, length = arguments.length, deep = false, options;

  if (typeof target === "boolean") {
    deep = target;
    target = arguments[1] || {};
    i = 2;
  }

  if (typeof target !== "object" && !isFunction(target))
    target = {};

  if (length == i) {
    return target;
  }

  for (; i < length; i++)
    if ((options = arguments[i]) != null)
      for (var name in options) {
        var src = target[name], copy = options[name];

        if (target === copy)
          continue;

        if (deep && copy && typeof copy === "object" && !copy.nodeType)
          target[name] = extend(deep,
            src || (copy.length != null ? [] : { })
          , copy);

        else if (copy !== undefined)
          target[name] = copy;
      }
  return target;
}


function MessageBox(options){
 var t = this; 
 var defaults = {
    type: "MESSAGE", // "ALERT" || CONFIRM || PROMPT || "DIALOG" || TEXT
    hideOnClick: false,
    title: "Alert",
    width: "410px",
    height: "auto",
    bodyStyle: "",
	contentStyle: "",
    closeButton: false, //  'X' close button in the caption.
    progress: false, //  progress bar.
    modal:false, // user can't do anything until close the message window
    id:false,
	callback:false,
	draggable:false,
	resizable:false
  };

  options = extend(defaults, options);

  var box = document.createElement("div");
  box.className = 'message-box';
  if(options.id){
  	box.id = options.id;
  }
  box.style.display = "none";
  box.style.height = options.height;
  box.style.width = options.width;
  if(parseInt(options.width)<600)
 	 box.style.marginLeft = "-150px";

  
  $(box).css(options.bodyStyle);
  
  $(document).ready(function(){
  	document.body.appendChild(box);
  });

  t.box = box;
  
  if (options.hideOnClick){
  	$(window).bind("click", function(){
		t.hide();
	} )
	$(t.box).click(function(event){
		event.stopPropagation();
	});
  }
  
  var h = "";
  if (options.title) {
      h += "<div class='title-bar'>" +
      ((options.closeButton) ? ("<div class='close-button'></div>") : ("")) +
      options.title +
      "</div>";
  }
  h += "<div class='content-layout " + ((options.type == "TEXT") ? "text-type" : "") + " '></div>" 
    +"<div class='buttons-layout'></div>";
  $(box).append(h);
  $(".content-layout", box).css(options.contentStyle);		
  $('.close-button', box).bind("click", function(){
  	t.hide();
	if(options.callback)
		options.callback();
  });			
}

MessageBox.prototype = {

	content: function(c){
		var t = this;
		$(t.box).children(".content-layout").html(c);
		w = Math.floor(window.innerWidth/2);
 		h = Math.floor(window.innerHeight/2);
		h -= Math.floor($(t.box).outerHeight()/2);
		w -= Math.floor($(t.box).outerWidth()/2+10);
		t.box.style.top = h + $(document).scrollTop()+"px";
		t.box.style.left = w +"px";
		return t;
	},
	
	
	load: function(url){
		var t = this;
		$(t.box).children(".content-layout").load(url, function(){
			w = Math.floor(window.innerWidth/2);
 			h = Math.floor(window.innerHeight/2);
			h -= Math.floor($(t.box).outerHeight()/2);
			w -= Math.floor($(t.box).outerWidth()/2+10);
			t.box.style.top = h + $(document).scrollTop()+"px";
			t.box.style.left = w +"px";
		});
		
		return t;
	},
	
	show: function(arg){
		var t = this;
		$(t.box).show(arg);
		return t;
	},
	
	hide: function(arg){
		var t = this;
		$(t.box).hide(arg);
		return t;
	},
	
	close:function(o){
		var t = this;
		if(o.flash)
			$(t.box).css({'visibility':'hidden'});
		else 
			$(t.box).hide();
		if(o.func)
			o.func();
	},
	
	addButton: function(options, func){
		var t = this;
		var a = document.createElement("div");
		a.className = "button";
		$(t.box).children(".buttons-layout").append(a);
		a.innerHTML = "<div>" + options.label + "</div>";
		$(t.box).children(".buttons-layout")[0].style.display = "block";
		$(a).bind("click", function(){
			func();
		});
		return t;
	},
	
	setOptions: function(options){
		var defaults = {
			hideOnClick: false,
			title: "Alert",
			width: "410px",
			height: "auto",
			bodyStyle: "",
			closeButton: false, //  'X' close button in the caption.
			progress: false, //  progress bar.
			modal: false // user can't do anything until close the message window
		};
			options = extend(defaults, options);
		
		var t = this;
		t.box.style.height = options.height;
		t.box.style.width = options.width;
		$(t.box).html("<div class='title-bar'>" +
		options.title +
		((options.closeButton) ? ("<div class='close-button'></div>") : ("")) +
		"</div>" +
		"<div class='content-layout'></div>" +
		"<div class='buttons-layout'></div>");
		$(t.box).children(".title-bar").children(".close-button").bind("click", function(){
			t.hide();
		});
		return t;
	}
}

/*
function alert (msg){
	var box = new MessageBox({
		type : "ALERT",
		title: "Системное сообщение",
		width: "auto",
		height: "auto",
		closeButton:true,
		hideOnClick:false
	});
	box.content(msg);
	box.addButton({label:"Отмена"}, function(){
		box.hide();
	});
	box.addButton({label:"Ок"}, function(){
		box.hide();
	});
	box.show();
}*/


function info(o){
	return '<a href="javascript:;" '
			+ ((o.id)?'id="'+o.id+'"':'')+'" '
			+((o.style)?(" style=\""+o.style+"\""):('')) 
			+ ((o.url)?' onclick="instruction(\''+o.title+'\', \''+o.url+'\')"':'')
			+ ' class="info-prompt ' + ((!o.url)?"plain-text":"") +'"'
			+ '">' + o.title + '<div></div></a>';
}

function instruction(title, url){
	var box = new MessageBox({
		type : "TEXT",
		title: title,
		width: "500px",
		height: "auto",
		closeButton:true,
		hideOnClick:false
	});
	box.box.style.marginLeft="-100px";
	box.load(url);
	box.show();
}



paging = {
	init: function(options){
		this.options = options;
		this.pageNumber = options.curPage;
		return this;
	},
	
	build: function(obj){
		var t = this;
		var nPages = Math.ceil(t.options.nElems / t.options.itemsPerPage);
		if (!nPages || nPages < 2) 
			return;
		var h = '';
		if (t.pageNumber > 0) 
			h += '<span class="previousPage ' + t.options.color + 'Text"><a href="javascript:;">Влево</a></span>';
		else 
			h += '<span class="previousPage unactive">Влево</span>';
		
		h += '<span class="numbers">';
		var startPage = 0;
		if (nPages > 7) {
			if (t.pageNumber > 1) {
				startPage = t.pageNumber - 2;
			}
			
			if (t.pageNumber > nPages - 6) {
				startPage = nPages - 7;
			}
		}
		var j = 0;
		var flag = 0;
		for (i = startPage; i < nPages; i++) {
			if (nPages <= 7) {
				if (i == t.pageNumber) {
					h += '<span class="pageNumber ' + t.options.color + '">' + (i + 1) + '</span>';
				}
				else {
					h += '<a href="javascript:;" class="pageNumber">';
					h += i + 1;
					h += '</a>';
				}
			}
			else {
			
				if (startPage + 2 < nPages / 2) {
					if (i == t.pageNumber) {
						h += '<span class="pageNumber ' + t.options.color + '">' + (i + 1) + '</span>';
					}
					else {
						if ((nPages > 7 && j < 6) || i == nPages - 1) {
							h += '<a href="javascript:;" class="pageNumber">';
							h += i + 1;
							h += '</a>';
						}
						else {
							if (flag == 0) {
								h += '<span class="pageNumber">...</span>';
								flag = 1;
							}
						}
					}
				}
				else {
					if (flag == 0) {
						h += '<a href="javascript:;" class="pageNumber">1</a>';
						h += '<span class="pageNumber">...</span>';
						flag = 1;
					}
					if (i == t.pageNumber) {
						h += '<span class="pageNumber ' + t.options.color + '">' + (i + 1) + '</span>';
					}
					else {
						if (nPages > 7 && j > 0) {
							h += '<a href="javascript:;" class="pageNumber">';
							h += i + 1;
							h += '</a>';
						}
					}
				}
				j++;
			}
		}
		h += '</span>';
		if (t.pageNumber == nPages - 1) 
			h += '<span class="nextPage unactive">Вправо</span>';
		else 
			h += '<span class="nextPage ' + t.options.color + 'Text "><a href="javascript:;">Вправо</a></span>';
		h += info({title:"Нажмите Ctrl и → одновременно", style:'top:-40px; left:10px;'});
		
		return h;
		
	},
	
	addEvents: function(obj){
		var t = this;
		$(obj + ' a.pageNumber').click(function(){
			t.pageNumber = $(this).html() * 1 - 1;
			var parsedHash = location.hash.split('/');
			var rexp = /p[0-9]*/;
			for (i = 0; i < parsedHash.length; i++) {
				if (rexp.test(parsedHash[i])) {
					parsedHash[i] = 'p' + t.pageNumber;
					break;
				}
			}
			if (i == parsedHash.length) 
				goToUrl(location.hash + '/p' + t.pageNumber);
			else 
				goToUrl(parsedHash.join('/'));
		});
		
		$(obj + ' .nextPage a').click(function(){
			t.pageNumber = $(obj + ' span.pageNumber').html() * 1;
			var parsedHash = location.hash.split('/');
			var rexp = /p[0-9]*/;
			for (i = 0; i < parsedHash.length; i++) {
				if (rexp.test(parsedHash[i])) {
					parsedHash[i] = 'p' + t.pageNumber;
					break;
				}
			}
			if (i == parsedHash.length) 
				goToUrl(location.hash + '/p' + t.pageNumber);
			else 
				goToUrl(parsedHash.join('/'));
		});
		
		$(obj + ' .previousPage a').click(function(){
			t.pageNumber = $(obj + ' span.pageNumber').html() * 1 - 2;
			var parsedHash = location.hash.split('/');
			var rexp = /p[0-9]*/;
			for (i = 0; i < parsedHash.length; i++) {
				if (rexp.test(parsedHash[i])) {
					parsedHash[i] = 'p' + t.pageNumber;
					break;
				}
			}
			if (i == parsedHash.length) 
				goToUrl(location.hash + '/p' + t.pageNumber);
			else 
				goToUrl(parsedHash.join('/'));
		});
		
		document.onkeydown = function(event){
			if (window.event) 
				event = window.event;
			if (event.ctrlKey) {
				switch (event.keyCode ? event.keyCode : event.which ? event.which : null) {
					case 0x25:
						$(obj + ' .previousPage a').trigger('click');
						break;
					case 0x27:
						$(obj + ' .nextPage a').trigger('click');
						break;
				}
			}
		}
	}
}


function ban240x400(l){
		h = "<div class='banner240x400'>";
			h += "<div class='topPerformers'>"+l+"</div>";
			h += "<div class='bannerLayout'>";
			var RndNum4NoCash = Math.round(Math.random() * 1000000000);
			//RLE
			//h+='<iframe src="http://ad.adriver.ru/cgi-bin/erle.cgi?sid=153800&bn=0&target=blank&bt=22&pz=0&rnd='+ RndNum4NoCash +'" frameborder=0 vspace=0 hspace=0 width=240 height=400  marginwidth=0 marginheight=0 scrolling=no></iframe>';
			
			//Kavanga
			//h+='<iframe onload="" id="kgItem" src="http://a.kavanga.ru/3604/getCode?p1=bfed&amp;p2=u&amp;p3=a&amp;p4=a&amp;pct=a&amp;pfc=a&amp;pfb=a&amp;pr='+ RndNum4NoCash +'" frameBorder="0" width="240" height="400" marginWidth="0" marginHeight="0" scrolling="no" style="border: 0px; margin: 0px; padding: 0px;"></iframe>';
			//Our Banners
			/*src = "/media/banners/240x400/banner_0" + Math.floor((10-4)*Math.random()+1)+".swf";
					if ($.browser.msie || $.browser.webkit ) {
						h += "<object classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000' codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=10,0,0,0' width='240' height='400'><param name='movie' value='"+src+"'><param name='menu' value=false><param name='quality' value='high'><param name='allowScriptAccess' value='sameDomain'><param name='bgcolor' value=#ffffff></object>";
					} else{
						h += "<embed style='margin-left:3px;' src='"+src+"' menu='false' quality='high' wmode='transparent' bgcolor='#ffffff' allowScriptAccess='sameDomain'  width='240' height='400' TYPE='application/x-shockwave-flash' PLUGINSPAGE='http://www.macromedia.com/go/getflashplayer'></embed>"
					}*/
			
			h+='<iframe src="http://b.kavanga.ru/exp?sid=1459&bt=5&bn=1&bc=3&ct=1&pr=' + Math.round(Math.random()*100000) + '&pt=b&pd=' + addate.getDate() + '&pw=' + addate.getDay() + '&pv=' + addate.getHours() + '&prr=' + afReferrer + '" frameBorder="0" width="240" height="400" marginWidth="0" marginHeight="0" scrolling="no" style="border: 0px; margin: 0px; padding: 0px; width: 240px; height: 400px;"><\/iframe>';
//			h+="<a  href='http://vkontakte.ru/app1864459_1000'><img src='/media/banners/240x400/vkitter.gif'/></a>";
//			h+="<a  href='http://inwhite.su/priglashenie-na-koncerty-v-moskve-i-pitere/'><img src='/media/banners/240x400/inwhite.jpg'/></a>";
			h += "</div>";
	    h += "</div>";
	return h;
}




function findParentInDOMTree(parentName, element)
{
    var parent = element.parentNode;
    if (element.id == parentName) 
        return 1;
		while ((parent) && (parent.id != parentName) && (parent.id != 'mainLayout')) {
			parent = parent.parentNode;
		}
		if (parent) {
			if (parent.id == 'mainLayout') 
				return 0;
			else 
				return 1;
		}
		return 0;
}


/**********сокращаем длинные названия*************/
function cropStr(str, maxlen){
	if(!str)
		return;
	if (str.length > maxlen) {
		str = str.substr(0, maxlen - 4);
		str += '...';
	}
	return(str);
}

/****************Дорабатываем jQuery функцией замены элементов))*******************/
$.fn.replaceWith = function(html) {
	return this.after(html).remove();
}


/********************Генерация html полоски трека***********************/

function generateTrackLine(opts){
	var performer = cropStr(opts.performer, opts.tooltipLen);
	var song = cropStr(opts.title, opts.tooltipLen);
	var tooltip = opts.performer + ' - ' + opts.title;
	if(tooltip == performer + ' - ' + song)
		tooltip = '';				
	var h = '';
	if (opts.columns) {
		if(!opts.even)
			h += '<' + opts.element + '	';
		else
			h += '<' + opts.element + '	style="float:right;"';
	} else
		h += '<' + opts.element + '	';	
	h += ' class="trackLine ' + opts.addClass + '" title="' + tooltip + '">';
	
	h += "<a id='" + opts.trackId + "' href='javascript:;' class='playButton " + opts.color + "'></a>";
	
	h += "<a href='/#performers/" + opts.performerId + "' class='performer'>" + performer + "</a><span style='float:left;'>&nbsp;-&nbsp;</span><a class='songTitle' href='/#tracks/" + opts.trackId + "'>" + song + "</a>";
	h += "<div class='length'>" + opts.trackLength + "</div>";
	if (loginFuncs.isLogin>0) {
		/*h += "<a href='javascript:;' class='plusButton'"
		if (window.opera) 
			h += " style='margin-bottom:6px;'";
		h += "></a>";*/
	}
	if (!opts.ownerNick) {
		h += '<a href="javascript:;" class="delTrack"></a>';
	}	
	h += "</" + opts.element + ">";
	return h;
}


/************************* окошко подтверждения*******************/
function confirmAlert(){
   // this.oObservable = new Observable();		
	this.object = 0;
	
	this.setObject = function(obj){
		this.object = obj;
	};	
}

confirmAlert.EVENT_TYPE_CLOSE = 'close';

confirmAlert.prototype = {
    attachObserver : 	function(
      					  sEventType,
 					       mObserver
  					      ) {

  					 /*     this.oObservable.attachObserver(
 					          sEventType,
					          mObserver
				            );*/

					    },

					    detachObserver : function(
					        sEventType,
					        mObserver
					        ) {

				        this.oObservable.detachObserver(
				            sEventType,
				            mObserver
			            );

					    },	
	openWnd :	function(message, func){
					var t=this;
					var al = document.getElementById('messageAlertContent');
					if(!al){
						var h = '';
						if (navigator.appVersion.indexOf('MSIE 6.0') == -1) {
							h = '<div class="top_sh" style="width:198px"></div>';
							h += '<div class="right_sh" style="height:65px"></div>';
							h += '<div class="left_sh"  style="height:65px"></div>';
							h += '<div class="bottom_sh" style="width:198px"></div>';
							h += '<div class="top_left_sh"></div>';
							h += '<div class="top_right_sh"></div>';
							h += '<div class="bottom_right_sh"></div>';
							h += '<div class="bottom_left_sh"></div>';
						}
						h += '<div style="background-color:#fff;width:212px;height:79px;padding:0;">';
						h += '<div id="header" class="header"><a id="close" href="javascript:;"></a></div>';
						h += "<div id='messageAlertContent' class='content'>"+ message;
						h += "</div><div class='buttons'>";		
						h += "<a class='OKButton' href='javascript:;'></a><span class='or'>или</span>";
						h += "<a class='cancelButton' href='javascript:;'></a>";
						h += "</div>";		
						h += "</div>";
		
						$('#messageAlert').html(h);
					}
					$('#messageAlert').css('display', 'block');				
					$('#messageAlert').draggable({ handle: 'div.header'});
			        $('#messageAlert a.OKButton').bind("click", function(){
						func();
						t.closeWnd();
			        });
				    $('#messageAlert a.cancelButton').bind("click", function(){
						t.closeWnd();
				    });		
				    $('#messageAlert #close').bind("click", function(){
						t.closeWnd();
				    });			
				},
	closeWnd :	function(){
					if ($('#messageAlert').css('display') == 'block') {
						$('#messageAlert').css('display', 'none');
				        $('#messageAlert a.OKButton').unbind("click");
					    $('#messageAlert a.cancelButton').unbind("click");
					    $('#messageAlert #close').unbind("click");
						this.oObservable.notify(confirmAlert.EVENT_TYPE_CLOSE);
					}
				}
};

var cAlert = new confirmAlert();

cAlert.attachObserver(
    confirmAlert.EVENT_TYPE_CLOSE,
	    function() { 
			if($('#currentPlaylist').css('display')!='block')
				$('#playlists .highlighted').removeClass('highlighted');
	    }
    );

/************************* окошко, всплывающее по плюсику*******************/
function plusPopUp(){
	this.object = 0;
	this.data = 0;
	this.setObject = function(obj){
		this.object = obj;
	};	
	this.setData = function(data){
		this.data = data;
	};		
}

plusPopUp.prototype = {
	openWnd :	function(object){
					var t=this;
					t.setObject(object);
					var coords = getPosition(object.parentNode);		/*получаем координаты плюсика, чтобы задать координаты списку*/
					if (findParentInDOMTree('currentPlaylist', object)) {
						coords = getPosition(object.parentNode);		/*получаем координаты плюсика, чтобы задать координаты списку*/
					}					
					var popup = document.getElementById('plusPopUp');
					if(popup.style.display != 'none'){		/*прячем, если такой список уже открыт*/
						popup.style.display = 'none'
					}
					var offsX = 2;
					var offsY = 0;
					if(findParentInDOMTree('currentPlaylist', object)){
						offsX = $('#currentPlaylist').css('left');
						offsY = $('#currentPlaylist').css('top');
						offsX = offsX.substr(0, offsX.length - 2)*1 + 107;
						offsY = offsY.substr(0, offsY.length - 2)*1 - 6;
					}
					if(findParentInDOMTree('leftContent', object)){
						offsX = 42;
					}
					if(findParentInDOMTree('performersLayout', object)){
						offsX = 38;
					}
					if(findParentInDOMTree('performerSongs', object)){
						offsX = -4;
					}
					if(findParentInDOMTree('albumsLayout', object)){
						offsX = 35;
					}									
					if($(object).parent().parent().parent()[0].className == 'charts-page'){
						offsX = -9;
					}									
					if(findParentInDOMTree('longTrack', object)){
						offsX = 318;
					}
	
					$(popup).css('left', coords.x + offsX*1 + 66 + 'px');
					$(popup).css('top', coords.y + offsY*1  + 'px');					
					$('#plusPopUp').css('display', 'block');
				},
	refreshContent: function(){
					var t=this;
					var h = '';
					h += "<div class='head' class='popupPlus'></div>";
					if(!playlists.jSData)
						return;
					h += "<span style='background-color:#565656;border-bottom:1px solid #6f6f6f;padding:1px 59px 1px 5px;color:#b0b0b0;'>Добавить трек в плейлист:</span>";						
					if (playlists.jSData.playlists.length > 3) {
						h += '<a class="upArrow"></a>';
					}		
					h += '<div class="cont">'								
					h += '<ul class="items">';
					for(i =0; i<playlists.jSData.playlists.length;i++){
						h += "<li>";
						h += "<a id='" + playlists.jSData.playlists[i].id + "' href='javascript:;'>" + playlists.jSData.playlists[i].name + "</a>";
						h += "</li>";
					}
					h += '</ul>';
					h += '</div>';
					if(playlists.jSData.playlists.length>3)
						h += '<a class="downArrow"></a>';
					$('#plusPopUp').html(h);
					$("#plusPopUp div.cont").scrollable({
						items:'ul.items',
						vertical:true,
						nextPage:'a.downArrow',
						prevPage:'a.upArrow',
						size: 3
					});	
					$('#plusPopUp .items a').bind("click", function(){
						if (!tracklists[this.id]) {
							tracklists[this.id] = new trackList();
						}
						var tLine = $(t.object).parent();
						var length = $(tLine.children('.length')[0]).html();
						var title = $(tLine.children('.songTitle')[0]).html();
						var trackId = $(tLine.children('.playButton')[0])[0].id;
						var performer = $(tLine.children('.performer')[0]).html();												
						track = '[{"id":"' + trackId + '", ';
						track += '"performer":"' + performer + '", ';
						track += '"title":"' + title + '", ';
						track += '"trackLength":"' + length + '"}]';
						tracklists[this.id].addSong(track, this.id);
						t.closeWnd();
					});
				},
	closeWnd :	function(){
					$('#plusPopUp').css('display', 'none');
				}
};

var pPopup = new plusPopUp();

function parseId(str){
	return str.substr(3, str.length - 3)
}


function Set_Cookie( name, value, expires, path, domain, secure )
{
// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );

/*
if the expires variable is set, make the correct
expires time, the current script below will set
it for x number of days, to make it for hours,
delete * 24, for minutes, delete * 60 * 24
*/
	if ( expires )
	{
		expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );

	document.cookie = name + "=" +escape( value ) +
	( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
	( ( path ) ? ";path=" + path : "" ) +
	( ( domain ) ? ";domain=" + domain : "" ) +
	( ( secure ) ? ";secure" : "" );
}

function Get_Cookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f

	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );


		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
}

function Delete_Cookie( name, path, domain ) {
	if ( Get_Cookie( name ) ) document.cookie = name + "=" +
	( ( path ) ? ";path=" + path : "") +
	( ( domain ) ? ";domain=" + domain : "" ) +
	";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

function friend(id, obj){
	$.get('/user/makefriend/'+id, function(){
		$(obj).replaceWith("<a href='javascript:;' onclick='unfriend("+id+", this)'>Убрать из друзей</a>");
	});
}

function unfriend(id, obj){
	$.get('/user/removefriend/'+id, function(){
		$(obj).replaceWith("<a href='javascript:;' onclick='friend("+id+", this)'>Добавить в друзья</a>");
	});
}

function sendTrackToPlayer(obj, color){
	load_track_in_player("/track/get/" + obj.id + "/");
	$(obj).parent().children().css('display', 'none');
	$(obj).parent().children('.playButton').css('display', 'block');
	$(obj).parent().append('<span class="addedTrackIco">Трек добавлен в плейлист</span>');
	$(obj).parent().find('.addedTrackIco').fadeIn(500);
	$(obj).parent().animate({
		'backgroundColor':color
		}, 500, function(){
			setTimeout(function(){
				$(obj).parent().find('.addedTrackIco').remove();
				$(obj).parent().children().fadeIn(500);
				$(obj).parent().animate({
					'backgroundColor':'#888888'
				}, 500);
			}, 1000);
		});
}

function getPosition(e) {
    var left = 0;
    var top  = 0;

    while ((e.offsetParent)&&(e.parentNode.id!='mainLayout')) {
		if (e.id != 'dynamicRightContent') {
			left += e.offsetLeft;
			top += e.offsetTop;
		}
		if (findParentInDOMTree('leftContent', e)) {
			e = e.offsetParent;
		}
		else 
			e = e.parentNode;
		if (e.id == 'mainLayout') {
			break;
		}
    }
 
    return {x:left, y:top};
}

/*
 * всплывающая подсказка при наведении
 * у элементов должен быть id формата буква + номер по списку, чтобы найти его данные в объекте
 * options: {
 * 				obj - родительский элемент, в котором все происходит. 
 * 				hoverObj - элементы, при наведении на которые появляется подсказка.
 * 				data - объект, из которого будут браться подписи
 * 				field1, field2 - поля объекта data из которых берутся подписи
 * 				initTop, initLeft - отступы слева/сверху
 * 				objectWidth, objectHeight - ширина, высота шага
 * 				perLine - сколько объектов в строке
 * 				invert - если 1, то в первой половине строки подсказка правосторонняя, во второй - левосторонняя
 * 				title - заголовок для нижнего поля
 * 				callback - для случаев, когда нужен другой обработчик
 * 			}
 */

function commonToolTip(options){
	var h = '';
	h += '<div class="usersTooltip">';
	h += '<span class="cont">';
	h += '<span class="nick"></span>';
	h += '<span class="karma"></span>';
	h += '</span>';
	h += '<span class="tale"></span></div>';
	$(options.obj).append(h);
	options.hoverObj = options.obj + " " + options.hoverObj;
	
	$(options.hoverObj).bind("mouseover", function(){
		if (!options.callback) {
			id = this.id.substr(1, this.id.length);
			$(options.obj + " .usersTooltip .nick").html(eval("options.data[id]." + options.field1));
			if(options.field2 == 'karma')
				$(options.obj + " .usersTooltip .karma").html(((options.title)?(options.title):("Карма: ")) + eval("options.data[id]." + options.field2));
			if(options.field2 == 'status')
				$(options.obj + " .usersTooltip .karma").html(((options.title)?(options.title):("")) + eval("options.data[id]." + options.field2));
			offs = options.initLeft + options.objectWidth * (id % options.perLine);			
			if(options.invert){
				if((id%options.perLine)<Math.round(options.perLine/2)){
					$(options.obj + " .usersTooltip .tale").addClass("lefter");
				} else {
					$(options.obj + " .usersTooltip .tale").removeClass("lefter");
					offs -= 150;
				}
			}
			$(options.obj + " .usersTooltip").css("left", offs + "px");
			offs = options.initTop + options.objectHeight * Math.floor(id / options.perLine);
			$(options.obj + " .usersTooltip").css("top", offs + "px");
			$(options.obj + " .usersTooltip").css("display", "block");
		} else {
			options.callback(this);
		}
	});
				
	$(options.hoverObj).bind("mouseout", function(){
		$(options.obj + ' .usersTooltip').css("display", "none");
	});
}

