var regex_mail = new RegExp('^([A-Z0-9._%+-]+)@([A-Z0-9.-]+)\.([A-Z]{2,4})$', 'i');
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 buy_conformation(price)
{
	if(typeof(wonder_pricemult)!='undefined' && wonder_pricemult>0)
	{
		price2=((1-wonder_pricemult)*price).toFixed(2);
		return confirm('This item costs $'+price+'. You have '+(wonder_pricemult*100)+'% Wondertime discount and your account will be charged $'+price2);
	}
	else
	{
		return confirm('Your account will be charged at the rate of $' + price + ' for this operation.');
	}
}
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 update_user_auth_balance(p)
{
	var balance = $('#user_auth_balance_span').html();

	if(typeof(wonder_pricemult)!='undefined' && wonder_pricemult>0)
		p=((1-wonder_pricemult)*p).toFixed(2);

	$('#user_auth_balance_span').html( (balance - p).toFixed(2) );
}

function setCookie (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) setCookie('album_'+min_id, null, -1, '/');
	setCookie('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();

		if( $('#_auth_form').css('display') == 'block' )
			return;

		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) {
		$('#search_form').submit();
	});
}

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


function get_linker_invite()
{
	// Checking linker by window.location.href
	var full_linker = window.location.href.split('?');
	
	if( !full_linker[1] ) return;
	
	var par_linker = full_linker[1].toString().split('&');
	var arr;
	for( i in par_linker )
	{
		if(par_linker[i])
		{
			arr = new Array();
			arr = par_linker[i].toString().split('=');
			if( arr[0] == 'invite_link' )
				break;
		}
	}
	//alert(arr[0]);
	if( arr[0] != 'invite_link' )
		return;
	
	// Check auth user
	if( is_authorized ) return;
	
	// Open registration window
	_authform.open('/account/','signup','Registration by Invite link!');
}

function check_new_invites()	// deprecated 09.11.2011
{
	/*
	if( !is_authorized ) return;
	//return _authform.open('','login');
	
	$.get('/account/invite/checknew/', function(data) {
		if(data)
			alert(data);
	});
	*/

}


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 tracklis');
		$(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';
		$("body").append(script);
		InvFrnd.inviteDetector();
	}
}

//@add:15.12.2011 - SMS prechecker
function checkAlloPayRedirect() {
	$.get('/account/recharge/?ajax=1&checksms=1',function(data){
		var result=jQuery.parseJSON(data);
		if (result) {
			location.href='/account/mmplayer/';
		} else {
			alert('Not enough money on your account. Please refill balance.');
			location.href='/account/recharge/';
		}
	});
}

//@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 id="giftcard_popup" style="display: block;" class="card_act"><div class="card_act_l"><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><span>Dear customer,</span><br><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="/account/gift/">My Gift Сards</a>.<br><br><br>Thank you for using mp3eagle.com.<a class="btn" href="'+this.activate_link+'">Activate now!</a></div></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();
});
