function toneBody(tone)
{
	if (tone == undefined) tone = true;
	if (tone)
	{
		if($("body").find("#TB_overlay").is("div")) return;
		if(!$.browser.msie) /* если браузер не ИЕ фоном будет div */
			$("body").append("<div id='TB_overlay'></div>");
		else /* иначе добавляем iframe */
			$("body").append("<div id='TB_overlay'><iframe scrolling='no' frameborder='0' style='position: absolute; top: 0; left: 0; width: 100%; height: 100%; filter:alpha(opacity=0)'></iframe></div>");
	}
	else
		$('#TB_overlay').remove();
}

function confirmation(obj, price, backward, song, help_title)
{
	var price_link = price + "";
	backward = backward + '_price' + price_link.replace('.', ':');

	if (song){
		backward = backward + '_song';
		txt = 'song';
	}else{
		txt = 'album';
	}
	if ( typeof(is_authorized) == 'undefined' || !is_authorized)
	{
		open_authform( backward, 'login', help_title );
		return false;
	}

	price = parseFloat(price);
	balance = parseFloat(user.balance);

	if (typeof(unlim) != 'undefined' && unlim) return true;

	if (price == 0) return true;

	if (price <= balance)
		return Buy.confirm(obj, '<h5>Download '+txt+(typeof(obj) ==='object' && $(obj).attr('rel')?' <span>&quot;'+$(obj).attr('rel')+'&quot;</span>':'.')+'</h5><p>Your account will be charged at the rate of <b>$' + price + '</b> for this operation.<p>');
	else {
		if (typeof buy_mmplayer != 'undefined') {
			document.location = '/publication/mmplayer-buy.html';
			return false;
		}
		if ( Buy.confirm('/account/recharge/',"<h5>We are sorry</h5><p>But there are not enough credits on your account.<br>Would you like to add funds now?</p>") )
			location.href='/account/recharge/';
	}
	return false;
}

function loading(show)
{
	if ( $('#TB_overlay').length <= 0 ) return;
	if(show==true)
		$('#TB_overlay').append('<table id="TB_loading" width="100%" height="100%"><tr><td align="center" valign="middle" style="vertical-align:middle;"><img src="/images/loading.gif" border="0"></td></tr></table>');
	else
		$('#TB_loading').remove();
}


function forceSetCookie (name, value, expires, path, domain, secure) {
      document.cookie = name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}

function fAddAlbum ( album_id )
{
	album_id = parseInt(album_id);
	var c = document.cookie.split(';');
	var num = 0; min = 0; min_id = -1; max = -1;
	for (var key in c)
	{
		if (typeof(c[key]) != 'string') continue;
		if (c[key].indexOf('=') == -1 ) continue;
		arr = c[key].split('=');
		if (arr[0].indexOf('album_') != 1) continue;
		id = parseInt( arr[0].substr(7) );
		if ( id == album_id ) return;
		val = parseInt(arr[1]);
		if ( min_id < 0 || min > val )
		{
			min_id = id;
			min = arr[1];
		}
		if (max < val) max = val;
		num++;
	}
	if (num >= 8) forceSetCookie('album_'+min_id, null, -1, '/');
	forceSetCookie('album_'+album_id, max+1, 99999999999, '/');
}
/* Helpdesk */
function helpdesk_create()
{
	$.get('/helpdesk/add/?ajax=true',function(data){
		toneBody();
		$('body').append('<div class="helpdesk-popup" id="newticketform">'+data+'</div>');
	});
	return false;
}
function helpdesk_close()
{
		$('#newticketform').remove();
		toneBody(false);
}
/* Helpdesk */


/* SEARCH HINTS */
function init_search_autocompliter(el)
{
	if(!el)
		el = 's_str';

	// подсказки в всплывающем окне
	$("#"+el).autocomplete('/search/autocomplete/', {
						minChars: 2,
						dataType: 'json',
						selectFirst: false,
						parse: function(data){
							var rows = [];
							if(data)
							{
								for(var i=0; i<data.length; i++){
									//rows[i] = { data:data[i], value:data[i].name, result:data[i].name };
									rows[i] = { data:data[i], value : data[i].count, result: data[i].name };
								}
							}
							return rows;
						},
						formatItem: function(itm){ return itm['name']; }
	}).result(function(event, item) {
		$('#s_str').parent().submit();
	});
}

$(document).ready(function(){
	init_search_autocompliter();
});
/* SEARCH HINTS END */


function locate_or_auth(url)
{
	if( !is_authorized )
	{
		open_authform( url, 'login' );
		return;
	}

	document.location = url;
}

var Buy = {
	  film_window_close : function(){
			$('#film-window').hide();
			toneBody(false);
			return false;
	  },
	  confirm : function(h, mess, t){
	  		//@add: 17.01.2012
	  		if (typeof buy_mmplayer != 'undefined') {
				document.location = '/publication/mmplayer-buy.html';
				return false;
			}
			type = t || false;
			$('#film-window-content').html(mess);
			if(typeof(h)!=='object') $('#film-window-ok').attr('href',h);
			else{
				if($(h).attr('href')) $('#film-window-ok').attr('href',$(h).attr('href'));
				else $('#film-window-ok').one('click', function(){ h.submit(); return false; });
			}
			$('#film-window-cancel').show();
						
			if(type) {
				  $('#film-window-ok').attr('href',"#");
				  $('#film-window-ok').one('click', function(){ Buy.film_window_close(); return false; }); 
				  $('#film-window-cancel').hide();
			}
			toneBody(true);
			$('#film-window').show();
			return false;
	  }
}

function toggle_albumtracks_download(el, id)
{
	if( !$('table#toggle_albumtracks_bl_'+id).html() )
	{
		$.get('/account/getbaskettracksbyalbum/'+id+'/',function(data){
			$('#block_album_tracks_'+id).html(data);
			$('table#toggle_albumtracks_bl_'+id).css('display', 'block');
			$('span', el).html('Hide tracklist');
			$(el).addClass('show');		
		});
		return;
	}
	
	
	if( $('table#toggle_albumtracks_bl_'+id).css('display') == 'block' )
	{
		$('table#toggle_albumtracks_bl_'+id).css('display', 'none');
		$('span', el).html('Show tracklist');
		$(el).removeClass('show');
		//Show tracklis
	}
	else
	{
		$('table#toggle_albumtracks_bl_'+id).css('display', 'block');
		$('span', el).html('Hide tracklist');
		$(el).addClass('show');		
		//Hide tracklist
	}
}

//Detection invite
function detectInviteRequest() {
	if (location.href.indexOf('#invite:')>0) {
		var script = document.createElement( 'script' );
		script.type = 'text/javascript';
		script.src = '/js/invite-friends.js?r='+Math.floor(Math.random()*10000);
		$("body").append(script);
		InvFrnd.inviteDetector();
	}
}

//@add:21.12.2011
function goWithAuth(url) {
	if (is_authorized == true) {
		location.href=url;
	} else {
		backward=url;
		_authform.open(url,'login');
	}
}

//Remote Giftcard not activated message
var GiftCardPopup = new function() {
	this.exist = false;
	this.showed = false;
	this.activate_link='';
	this.show = function() {
		var tpl='<div style="display:block;" id="giftcard_popup" class="card_act"><div class="card_act_r"><div class="card_act_m"><p class="closer"><img alt="X" onclick="GiftCardPopup.toggle()" src="/images/authreg_popup_closer.gif"></p>Dear customer!<br><br>You have not activated your <a href="http://filmous.com">filmous.com</a> Gift Card! It was a FREE bonus for our Christmas offer.<br><br><a href="'+this.activate_link+'">Activate your card now and get a lot of FREE credits</a>  or do it later in <a href="'+this.activate_link+'">My Gift Сards</a>.<br><br>Thank you for using mp3fiesta.com.<a class="btn" href="'+this.activate_link+'">Activate now!</a></div></div></div>';
		$('body').append(tpl);
		toneBody(true);
		this.showed=true;
	}
	this.hide = function() {
		$('#giftcard_popup').remove();
		toneBody(false);
		this.showed=false;
	}
	this.toggle = function() {
		if (this.exist) {
			if (!this.showed) {
				this.show();
			} else this.hide();
		}
	}
	this.check = function() {
		if (typeof rgiftcard_show != 'undefined') {
			this.exist=rgiftcard_show;
			this.showed=false;
			this.activate_link = rgiftcard_activate_url;
		}
		this.toggle();
	}
};

$(document).ready(function(){
	detectInviteRequest();
	GiftCardPopup.check();
});
