var ERR_TOO_SHORT_LOGIN = 'E-mail must be between 6 and 100 characters.';
var ERR_TOO_SHORT_PASSWORD = 'Password must be between 4 and 12 characters.';
var ERR_INCORRECT_CONFIRM_PASSWORD = 'The password you entered doesn`t match the confirmation password.';
var ERR_INCORRECT_OLD_PASSWORD = 'Old password is invalid.';
var ERR_INCORRECT_MAIL = 'Your E-mail address is invalid.';
var regex_mail = new RegExp('^([A-Z0-9._%+-]+)@([A-Z0-9.-]+)\.([A-Z]{2,4})$', 'i');

var msie=(window.navigator.appName=='Microsoft Internet Explorer')?1:0;

function detectIE6(){
  var browser = navigator.appName;
  var b_version = navigator.appVersion;
  var version = parseFloat(b_version);
  if ((browser == "Microsoft Internet Explorer") && (version <= 6)){
    return true;
  } else return false;
}

function open_authform(type, backward, id_movie, price, help_title, hide_red)
{
	
	if(hide_red)
		$('#gift_card_red_link').css('display', 'none');
	else
		$('#gift_card_red_link').css('display', 'block');
	
	$('#login_form input[name=backward]').val( (backward == undefined)?document.location:backward );
	$('#login_form input[name=id_movie]').val( (id_movie == undefined)?'':id_movie );
	$('#login_form input[name=price_movie]').val( (price == undefined)?'':price );


	if( help_title && help_title.length )
		$('#help_title').html(help_title+'<br /><br />');
	else
		$('#help_title').html('');



	// то бы при открытии авторизации/регистрации при нажатии ТАБ-а не прыгала по всему окну
	if( type == 'signup' || type =='login' )
	{
		$('a').attr('tabindex', '-1');
		$('input').attr('tabindex', '-1');
		$('#login_form input[name=login]').attr('tabindex', '1');
		$('#login_form input[name=pass]').attr('tabindex', '2');
		
		$('#regUsrFrm input[name=login]').attr('tabindex', '1');
		$('#regUsrFrm input[name=pass]').attr('tabindex', '2');
		$('#regUsrFrm input[name=cpass]').attr('tabindex', '3');
		$('#regUsrFrm #rememberme').attr('tabindex', '4');
		$('#regUsrFrm input.btn').attr('tabindex', '5');
		
		
		$('#login_form #rememberme').attr('tabindex', '3');
		$('#login_form input:submit').attr('tabindex', '4');
		
		$('#login_form input[name=login]').focus();
	}
	else if( type == 'close' )
	{
		$('a').attr('tabindex', '1');
		$('input').attr('tabindex', '1');		
	}
	

	if(type=='signup')
	{
		toneBody(true);
		$('#login_form').css('display','none');
		$('#authform, #signup_form').css('display','block');
		$('#authform').find('li').removeClass('active');
		$('#authform_tab_signup').addClass('active');
		
		$('#authform input[name=login]').focus();
		return false;
	}
	if(type=='login')
	{
		toneBody(true);
		$('#signup_form').css('display','none');
		$('#authform, #login_form').css('display','block');
		$('#authform').find('li').removeClass('active');
		$('#authform_tab_login').addClass('active');
		
		
		$('#login_form input[name=login]').focus();
		return false;
	}
	if(type=='close')
	{
		if ($('.inv_reg')) {
			$('.inv_reg').remove();
		}
		toneBody(false);
		$('#authform, #login_form, #signup_form').css('display','none');
	}
	return false;
}

function goWithAuth(url) {
	if (is_authorized == true) {
		location.href=url;
	} else {
		open_authform('login', url);
	}
}

function toneBody(tone)
{
	if (tone == undefined) tone = true;
	var aDiv=document.getElementById('TB_overlay');
	if (tone)
	{
		if(aDiv!=undefined && aDiv.tagName=='DIV') return;

		aDiv=document.createElement("DIV");
		aDiv.id='TB_overlay';
		if(msie)
			aDiv.innerHTML="<iframe scrolling='no' frameborder='0' style='position: absolute; top: 0; left: 0; width: 100%; height: 100%; filter:alpha(opacity=0)'></iframe>";
		document.body.appendChild(aDiv);
	}
	else if(aDiv!=undefined)document.body.removeChild(aDiv);
}
//RANDOM SEARCH STRING
$(document).ready(function(){
	if ('https:' != document.location.protocol && $('#search_str').val() == '' ) {
		if (!detectIE6()) {
			$.post('/hot/ajax', function(result) {
				var data = eval( result );
				var rand = Math.floor( 50 * Math.random() );
				var i = 0;
				for (var key in data)
				{
					if (i == rand)
					{
						data = data[key];
						break;
					}
					i++;
				}
				$('#search_str').attr('placeholder', data['name'] );
			});
		}
	}
});
//END OF RANDOM SEARCH STRING
//popup movie
function open_win(a,movieid,b,item)
{
	var li=a.parentNode.parentNode.parentNode;
	var side='left'
	if(item>4)side='right';

	$.get('/'+movieid+'/?ajax=true&t='+b+'&side='+side, function(data) {
		var div=$('#pop1')[0];
		div.style.top=li.offsetTop + li.offsetParent.offsetTop+'px';
		div.style.left=li.offsetLeft + li.offsetParent.offsetLeft +(b==3 && item>4?-20:0)+ 'px';
		div.style.display='block';
		$('#pop1').html(data);
	});
	return false;
}

function popup_download(obj, movieid, text, func)
{
	var pos = $(obj).position();
	$.get('/'+movieid+'/?ajax=true&t=1&side=left&func='+func+'&text='+text, function(data) {
		var div=$('#pop1')[0];
		div.style.left = (pos.left-70)+'px';
		div.style.top = (pos.top-215)+'px';
		div.style.display='block';
		$('#pop1').html(data);
	});
	return false;
}


var opentype=1;
var opentab='genre';
var cache_tab={};
function opentags(a,b)
{
	$('#the_tags').removeClass('closed');
	$('.tagtabs li').removeClass('active');
	$(a).parent().addClass('active');
	getdata(opentab,b);
	opentype=b;
	return false;
}
function getdata(a,b)
{
	opentab=a;
	if(!cache_tab[a+b]){
		$.get('/'+a+'/'+b+'/?ajax=true',function(data){
			$('#tag_list').css('display','block');
			$('#tab_data').html(data);
			cache_tab[a+b]=data;
			}
		);
	}else{
		$('#tag_list').css('display','block');
		$('#tab_data').html(cache_tab[a+b]);
	}
	return false;
}

function check_auth(thi)
{
	var th = $(thi);

	$('input[type="submit"]',th)[0].disabled = true;
	var login = $('input[name="login"]', th).val();
	var pass  = $('input[name="pass"]', th).val();
	var err = false;


	if (login.length < 6 || login.length > 100) err=ERR_TOO_SHORT_LOGIN;
    	else if(!regex_mail.test(login)) err=ERR_INCORRECT_MAIL;
    	else if(pass.length < 4 || pass.length > 12) err=ERR_TOO_SHORT_PASSWORD;

	if (!err)
	{
		$.post('/user/authn/', {'login':login, 'pass':pass, 'type':'auth', 'backward': $('#login_form input[name=backward]').val(), 'ajax':true},
        	function(data) {
        		if(data=="TRUE"){
					var ids = new Array();
					var ids_assoc = new Array();
					$('input:checked[id^=sbox_]').each(function(){
						if( ids_assoc[this.value] != '111' )
						{
							ids[ids.length] = this.value;
							ids_assoc[this.value] = '111';
						}
					});

					var simple_id = $('#login_form input[name=id_movie]').val();
					var simple_price = $('#login_form input[name=price_movie]').val();
					if(simple_id)
						ids[ids.length] = simple_id;

					var back_link = $('#login_form input[name=backward]').val().toString();
					
					var loc_link_str = document.location+"";
					if( ids.length > 0 && !loc_link_str.match(/\/search\//i))
					{
						var locat = location.href + '?ids=' + ids.join(':') + '&q=' + $('#login_form input[name=backward]').val() + ((simple_price)?("&p="+escape(simple_price)):(''));
						location.href = locat;
					}
					else if( ids.length > 0 && loc_link_str.match(/\/search\//i))
					{
						var locat = location.href + '&buy_id=' + ids.join(':') + '&buy_format=' + $('#login_form input[name=backward]').val() + ((simple_price)?("&buy_price="+escape(simple_price)):(''));
						location.href = locat;						
					}
					else if( back_link.length > 0 )
						location.href = back_link;
					else
						location.reload();
			    }else{
				    $('.auth_errors',th).html("Incorrect login or password").show();
				    $('input[type="submit"]',th)[0].disabled = false;

	            }
            },
	    'text');
	}
	else
	{
		$('.auth_errors',th).html(err).show();
        	$('input[type="submit"]',th)[0].disabled = false;
	}

	return false;
}


var latest_onpage=2;
var latest_tab=1;
var latest_period=2;

function select_latest_tab(obj,tab)
{
	latest_tab=tab;
	$('.grey_tabs').children().removeClass('active');
	$(obj).parent().parent().parent().addClass('active');
	select_get_page(1);
	return false;
}
function select_latest_onpage(obj,onpage)
{
	latest_onpage=onpage;
	$(obj).parent().parent().children().removeClass(function(a,b){ return (b=='float_right active'?'active':'');});
	$(obj).parent().addClass('active');
	select_get_page(1);
	return false;
}
function select_latest_period(obj,period)
{
	latest_period=period;
	$(obj).parent().parent().children().removeClass(function(a,b){ return (b=='active'?b:'');});
	$(obj).parent().addClass('active');
	select_get_page(1);
	return false;
}
function select_get_page(page)
{//&page='+page

	$.get('/latest/'+latest_tab+'/'+latest_period+'/'+latest_onpage+'/?ajax=true',function(data){
		$('#latests').html(data);
	});
	return false;
}

function confirmation1(obj,price,format,id_movie,help_title){
	
	if (is_authorized)
	{
		if(typeof(wonder_pricemult)!='undefined' && wonder_pricemult>0)
		{
			var price2=price*(1-wonder_pricemult);
			//if(confirm('This item costs $'+price+'. You have '+(wonder_pricemult*100)+'% Wondertime discount and your account will be charged $'+price2))
			//	location.href=$(obj).attr('href');
			return Buy.confirm(obj, '<p>This item costs <b>$'+price+'</b>. You have '+(wonder_pricemult*100)+'% Wondertime discount and your account will be charged <b>$'+price2+'</b></p>');
		}
		else
		{
			if(gl_user_balance>=price)
			{
				//if( confirm('Your account will be charged at the rate of $' + price + ' for this operation.') )
				//	location.href=$(obj).attr('href');
				if (price==0) {price='FREE';}
				else price = '$'+price;
				if( format == 'buyView' || format == 'View' ) {
					return Buy.confirm(obj, totalResult+'<p>Your account will be charged at the rate of <b>' + price + '</b> for this operation.</p>', '<h5>Watch online <span>'+($(obj).attr('rel')?'&quot;'+$(obj).attr('rel')+'&quot;':'')+'</span></h5>');
				} else {
					return Buy.confirm(obj, totalResult+'<p>Your account will be charged at the rate of <b>' + price + '</b> for this operation.</p>', '<h5>Download <span>'+($(obj).attr('rel')?'&quot;'+$(obj).attr('rel')+'&quot;':'')+'</span></h5>');
				}
			}
			else
				location.href = '/account/recharge/';
		}
	}
	else
	{
		var loc_link_str = document.location+"";
		
		if(format)
		{
			open_authform( 'login', format, id_movie, price, help_title );
		}
		else
		{
			open_authform( 'login','','','', help_title);
		}
		//location.href='/publication/welcome';
		return false;
	}
}

//get episodes count (@add 14.10.2011)
var is_download_series = 0;
function movies_selected_count() {
	if (is_download_series > 0) {
		var cnt = 1;
		if (checked_series_ids) {
			return limit_points();
		} else cnt = 1;
		return cnt;
	} return 1;
}


function confirmation(obj,price,format,id_movie, help_title,action)
{
//!! важно. отправляем в нижнем регистре!!! 
// @add: а вот хер, в верхнем регистре в /basket/buy<lowercase>/ проскакивает мимо и приходит по дефолту hqdivx
upformat=format;
format  = format.toLowerCase();

//if (format == 'view'){format = 'ipod';}
if (!action){action = 'download';}
//FOR SERIES=============================================================================
        var res = '';
        totalResult = '';
// Определим сериал ли это:

        var chosenEpisode       = jQuery('.container_checkboxes_series input:checkbox:checked');
        // Если сериал, то:
        if(chosenEpisode.length > 0){
            var stringEpisodsIds = '';
            // Формат в сериях передается криво. Поправим:
            format  = format.slice(3);

            // Найдем ID отмеченных эпизодов.
            chosenEpisode.each(function(){
                var episodId    = jQuery(this).attr('id').slice(5);
                stringEpisodsIds    = episodId+','+stringEpisodsIds;
            });
            stringEpisodsIds    = stringEpisodsIds.slice(0,-1);

            totalResult = '';
            var totalSum    = 0;

            $.ajax({
                    url:'/basket/getBadLinks/?movieIds='+stringEpisodsIds+'&type='+format+'&buyType='+action,
                    async:false,
                    success:function(res_my){res=res_my;}
            });


            if(res != ''){
                var badMovieS    = res.split('=');
                var oneMovie;
                var oneMovieName;
                var oneMovieSeason;
                var oneMovieEpisod;

                for(i=0;i<badMovieS.length; i++){
                    oneMovie        = badMovieS[i].split('#');
                    oneMovieName    = oneMovie[0];
                    oneMovieSeason  = oneMovie[1];
                    oneMovieEpisod  = oneMovie[2];
                    totalSum        = oneMovie[3];

                    totalResult  = totalResult+'<p>Episod '+oneMovieName+ ' at number '+oneMovieEpisod+' of season '+oneMovieSeason+'</p>';
                    price = totalSum; // Цена реальная, с вычетом недокача.
                }

                if (totalSum == 0 || totalSum == '0'){
                    return Buy.confirm('',"<h5>Sorry, but due to technical update this movie is not available at the moment. Please, try again later. Thank you.</h5>","",true);
                    return false;
                }
                totalResult = '<h5>The next episode can not be loaded:</h5>'+totalResult+'<p>You can download them later.</p>';
            }

//alert(totalResult);
//return false;
//FOR SERIES=============================================================================
        }
        else{
        //FOR MOVIE=============================================================================

                $.ajax({
                        url:'/basket/getBadLinks/?movieIds='+id_movie+'&type='+format+'&buyType='+action,
                        async:false,
                        success:function(res_my){res=res_my;}
                });

            if(res != ''){
                return Buy.confirm('',"<h5>Sorry, but due to technical update this movie is not available at the moment. Please, try again later. Thank you.</h5>","",true);
            }
        //FOR MOVIE=============================================================================
        }


	if(!action)action="download";
	if(!is_authorized)return confirmation1(obj,price,upformat,id_movie,help_title);
	var moviescnt = movies_selected_count(); //@mod 17.10.2011
	$.post('/user/get/',{action:'getDownloadRest',want:moviescnt},function(data) {
		if (parseInt(data)>=0) { // data - dimention between current and limit
			
			$.post('/user/get/',{action:'getMyDownloadsCount'},function(data) {
				if(parseInt(data,10)>0) {
					//if(confirm("Movie is available for downloading."))
					//	location.href = obj.href;
					//return false;
					return Buy.confirm(obj, "<p>Movie is available for downloading.</p>");
				}else
				{
					$.ajax({url:"/account/checkBasket/" + id_movie + "/" + action + '/' + format + '/',
						   async: false,
						   success: function(data){
								if(parseInt(data)>0)
								{
									if(action == 'view')
										return Buy.confirm("/account/view/#"+id_movie,'<h5>You have already purchased this movie. You can view it at <b>"View online"</b> page. Would you like to start watching this movie now?</h5>','<h5>View Online</h5>');
									else
										return Buy.confirm("/account/download/",'<h5>You have already purchased this movie. Would you like to go to <b>"Downloads"</b> page now?</h5>','<h5>Download</h5>');
								}
								else
									return confirmation1(obj,price,format,id_movie,help_title);
								
							}
					});
		//			return confirmation1(obj,price,format,id_movie,help_title);
				}
			});
		} else {
			alert('Sorry, due to technical reasons and in order to provide better service and high speed downloads we limit daily download by 50 videos per day. Sorry for inconvenience.');
		}
	});

	return false;
}
function forgotform(type)
{
	if(type==undefined) type='open';
	if(type=='open')
	{
		toneBody(true);
		$('#authform, #login_form, #signup_form').css('display','none');
		$('body').append('<div id="forgotform" class="window"></div>');
		$.post('/user/forget?ajax=true',function(data){
			$('#forgotform').html(data);
		});
	}
	if(type=='close')
	{
		toneBody(false);
		$('#forgotform').remove();
	}
	return false;
}
/* Helpdesk */
function helpdesk_create()
{
	open_authform('close');
	$.get('/helpdesk/add/?ajax=true',function(data){
		toneBody();
		jQuery('body').append('<div style="position:fixed;top:50%;z-index:99999999;left:50%;margin:-270px 0 0 -550px" id="newticketform">'+data+'</div>');
	});
	return false;
}
function helpdesk_close()
{
		$('#newticketform').remove();
		toneBody(false);
}
/* Helpdesk */







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 fAddMovie ( movie_id )
{
	movie_id = parseInt(movie_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('movie_') != 1) continue;
		id = parseInt( arr[0].substr(7) );
		if ( id == movie_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 >= 10) setCookie('movie_'+min_id, null, -1, '/');
	setCookie('movie_'+movie_id, max+1, 99999999999, '/');
}

// SEARCH HELP WINDOW (autocompleter)
function init_search_autocompliter()
{	 
	// подсказки в всплывающем окне
	$("#search_str").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 '<span class="searcher_hint_counter">'+itm['count']+'</span>'+itm['name']; }
	}).result(function(event, item) {
			$('#search_str').parent().parent().parent().parent().submit();
	});
}

$(document).ready(function(){
	init_search_autocompliter();
});


function JS_dump(obj) {
    var out = '';
    for (var i in obj) {
        out += i + ": " + obj[i] + "\n";
    }

    alert(out);

    // or, if you wanted to avoid alerts...

    var pre = document.createElement('pre');
    pre.innerHTML = out;
    document.body.appendChild(pre)
}

/////////////////////////////////////


var Buy = {
	  film_window_close : function(){
			$('#film-window').hide();
			toneBody(false);
			return false;
	  },
	  confirm : function(h, mess, head, t){
			type = t || false;
			head = head || '';
			$('#film-window-content').html(mess);
			$('#film-window-content-h').html(head);
			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; });
			}
			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;
	  }
}

/* online */


///////////////////// FP ////////////////////////////////

function initFP()
{
	if(navigator.appName.indexOf("Microsoft")!=-1)
	{
		fvp=document.getElementById(movieName);
		if( typeof fvp.init != "function" ){
			fvp=window[movieName];
		}
	} else {
		//fvp=(navigator.appName.indexOf("Microsoft") != -1)?window[movieName]:document[movieName];
		fvp=document[movieName];
		if( typeof fvp.init != "function" ) return;
	}
	fvp.init(current_id,movies[current_id].link,series_id);
}


//////////////////////// FP Trailer //////////////////////////
//function dump(el){var msg = '';for(i in el){if(el[i]) msg+=i+': '+el[i]+'\n';} return msg;}

function isFlashInstalled() {
    if (swfobject.hasFlashPlayerVersion("9.0.18")) return true;
}

function jwlink(link) {
	var chr='';
	var out='';
	for(var i=0;i<link.length;i++) {
		chr=link.charCodeAt(i);
		out += String.fromCharCode(chr-1);
	}
	return out;
}

function init_onload_FP(id, mlink)
{
	$('#trailer_player_fp').html('<div id="fp"></div>');
	var flashvars = { 'autostart':"0",'is_series':"0",'site':"1" };
	var params = { id:"fp", bgcolor:"#000000", allowFullScreen:"true", allowScriptAccess:"always",wmode:"opaque",play:"true",loop:"true" };
	
	if (isFlashInstalled()) {
		if (msie) {
			showOrHidePlayerTrailers(true);
			jwplayer("fp").setup({ 
				flashplayer: "/js/jwplayer.swf", 
				autostart: false,
				duration: 57,
				file: jwlink(mlink), 
				height: 392, 
				width: 901,
				events: {
					onComplete: function() {
						showOrHidePlayerTrailers(true);
					}
				}
			});
		} else {
			new swfobject.embedSWF("/js/fp.swf", 'fp', 901, 392, "9.0.0",false,flashvars, params,false,
				function(o){
					try_init_FP_trailer(id, mlink);
				 });
		}
	} else alert('Please install Flash player');
}
var timer = null;
var init_times = 0;
function try_init_FP_trailer(id, mlink)
{
	fvp=document.getElementById('fp');
	if( typeof fvp.init != "function" ){
		init_times++;
		if (init_times < 100) {
			setTimeout(function(){ try_init_FP_trailer(id, mlink); },100);
			return;
		} else {
			alert('Sorry, Flash Player not loaded correctly.');
			return;
		}
	}
	init_times=0;
	fvp.init(id,mlink,0);
	showOrHidePlayerTrailers(true);
}

function showOrHidePlayerTrailers(bool)
{
	$('#trailer_player_fp').css('width', ((bool)?(901):(1))+'px');
	$('#trailer_player_fp').css('height', ((bool)?(392):(1))+'px');
	
	if( bool )
	{
		toneBody(true);
		$('.closer_trailer_FP').show();
	}
	else
	{
		toneBody(false);
		$('.closer_trailer_FP').hide();
		if (msie) {
			jwplayer("fp").remove();
		}
		$('#trailer_player_fp').html('');
	}
}
/////////////////////////////////////////////////////////////////


function playmovie(movie_id)
{
	$('div[class="cnt cnt-visited"]',$('div.online-cnt')[0]).removeClass('cnt-visited').find('h2').remove();
	$('#'+movie_id).addClass('cnt-visited').find('h1').before('<h2>now playing</h2>');
	$('li.mrg','.flash').html('Time left to watch this movie online '+movies[movie_id].time+' hours');
	$('li.mrg','.flash').prev().html('<p>'+movies[movie_id].title+'</p>'+movies[movie_id].genres+', produced in '+movies[movie_id].year+', '+movies[movie_id].country+'</li>');
	current_id=movie_id;
	$('#nowlink1').attr('href','#'+movie_id);
	$('#nowlink2').attr('href','#'+movie_id);
	fvp.play(current_id,movies[current_id].link,series_id);
}
function playNext()
{
	if($('input','.niceCheck').attr('checked')==false)
	{
		fvp.replay();
		return;
	}
	var find=0;
	for(i in movies)
	{
		if(movies[i].trackid==(trackid+1)){find=2;current_id=i;break;}
	}
	if(find==2)playmovie(current_id);
	else fvp.replay();
}

function set_comments_by_movie(movie_id, page, bool)
{
		$.get('/mp4/comments/'+movie_id+'/'+page+'/', function(data) {
			$('#movie_comments').html(data);
		});
		if( !bool )
			document.location.hash = 'comments';
}

function add_ball_to_movie_comment(comment_id, ball)
{
	$.get('/mp4/commentraiting/?comment_id='+comment_id+'&ball='+ball, function(data) {
		if( data )
			$('#comment_ball_'+comment_id).html(data);
			if( data < 0 )
				$('#comment_ball_'+comment_id).parent().parent().addClass('active_comment');
			else
				$('#comment_ball_'+comment_id).parent().parent().removeClass('active_comment');
	});
}

function openMovieComment_form(bool)
{
	$("input[name=usr_name]", "#add_comment_form").val('');
	$("textarea[name=comment]", "#add_comment_form").val('');
	$("#hide_err_comment", "#add_comment_form").hide();
	
	if( bool )
	{
		toneBody(true);
		$('#popup_add_movie_comment').show();
	}
	else
	{
		toneBody(false);
		$('#popup_add_movie_comment').hide();
	}
	
}

function add_movie_comment()
{
	var text = $("textarea[name=comment]", "#add_comment_form").val().trim();
	
	if( !text.length )
	{
		$("#hide_err_comment", "#add_comment_form").show();
		return;
	}
	
	$.post("/mp4/comments/"+$("input[name=movie_id]", "#add_comment_form").val()+"/", $("#add_comment_form").serialize(),
		
		function(data) {
			if( data )
			{
				//alert(data);
				set_comments_by_movie($("input[name=movie_id]", "#add_comment_form").val(), 1)
				openMovieComment_form(false);
			}
		}
		
	);
}


function remove_tmp_tips() {
	$('span.tmp_dom_tips_el').remove();
}

function show_my_tips(text, bool, x, y)
{
	if(!bool)
	{
		setTimeout("remove_tmp_tips()", 1000);
		return;
	}
	
	if($('.tmp_dom_tips_el'))
		$('<span class="tmp_dom_tips_el" style="left:'+x+'px; top:'+y+'px">'+text+'</span>').appendTo('body');
}



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;
		}
	}
	
	if( arr[0] != 'invite_link' )
		return;
	
	// Check auth user
	if( is_authorized ) return;
	
	// Open registration window
	open_authform('signup','/account/','','','Registration by Invite link!<input type="hidden" name="invite_link" value="'+arr[1]+'">', 1);
}

function check_new_invites()
{
	if( !is_authorized ) return;
	/*
	$.get('/account/invite/checknew/', function(data) {
		if(data)
			Buy.confirm($('<a href="/account/payments/"></a>'), "<p>"+data+"</p>", '<h5>You get the Bonus!</h5>');
	});
	*/

}

//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();
	}
}

//Remote Giftcard not activated message
var GiftCardPopup = new function() {
	this.exist = false;
	this.showed = false;
	this.activate_link='';
	this.show = function() {
		var tpl='<div class="card_act"><div class="card_act_r"><div class="card_act_m"><a class="close" href="javascript:GiftCardPopup.toggle();"></a>Dear customer, <br><br>You have not activated your <a href="http://mp3eagle.com">Mp3Eagle Gift Card</a>! It was a FREE bonus for our Christmas offer. <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>Thank you for using filmous.com!<a class="btn" href="'+this.activate_link+'">Activate now!</a></div></div></div>';
		jQuery('body').append(tpl);
		toneBody(true);
		this.showed=true;
	}
	this.hide = function() {
		jQuery('.card_act').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();
});
