jQuery.jQueryRandom = 0;
jQuery.extend(jQuery.expr[":"],
{
    random: function(a, i, m, r) {
        if (i == 0) {
            jQuery.jQueryRandom = Math.floor(Math.random() * r.length);
        };
        return i == jQuery.jQueryRandom;
    }
});



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, '/');
}

/* Helpdesk */
function helpdesk_create()
{
	jQuery.get('/helpdesk/add/?ajax=true',function(data){
		toneBody();
		jQuery('body').append('<div style="position:fixed;top:50%;z-index:99999999;left:50%;margin:-250px 0 0 -386px" id="newticketform">'+data+'</div>');
	});
	return false;
}
function helpdesk_close()
{
		jQuery('#newticketform').remove();

		if( $('authform').style.display != 'block' )
			toneBody(false);
}
/* Helpdesk */


// SEARCH HELP WINDOW (autocompleter)
function init_search_autocompliter()
{
	//
	jQuery("#s_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 itm['name']; }
	}).result(function(event, item) {
		$('#s_str').parent().submit();
	});
}

// promo scroller
function PromoScroller() {
	jQuery('#fix').scrollFollow({speed: 0,offset: 60});
}

// @add 11.10.2011 check autoshow reg form
function autoshow_reg_form() {
	if(location.href != '') {
		var find = location.href.indexOf('#showregform');
		if (find>0) open_authform('signup');
	}
}

jQuery(document).ready(function(){
	init_search_autocompliter();
	PromoScroller(); // promo
	autoshow_reg_form(); // show reg form by link http://movieberry.com/#showregform
});

var Buy = {
	  allow : function(w){
			switch(w){
				  case "view" : return "view";
				  default : return w;
			}
	  },
	  confirmation : function(href, name, price, t){
			type = t || false;
			if(type) $('film-window-cancel').hide();
			params = href.match(/\/basket\/buy(.*)\/\?pk=(.*)&backward=(.*)_movie(.*)/i);
			toneBody(true);
			return false;
	  },
	  film_window_close : function(){
			$('film-window').style.display='none';
			toneBody(false);
			return false;
	  },
	  confirm : function(h, mess, t){
			type = t || false;
			$('film-window-content').innerHTML = mess;
			if(typeof(h)!=='object') jQuery('#film-window-ok').attr('href',h);
			else{
				if(jQuery(h).attr('href')) jQuery('#film-window-ok').attr('href',jQuery(h).attr('href'));
				else jQuery('#film-window-ok').one('click', function(){ h.submit(); return false; });
			}
			if(type) {
				  $('film-window-ok').href="#";
				  jQuery('#film-window-ok').one('click', function(){ Buy.film_window_close(); return false; }); 
				  $('film-window-cancel').hide();
			}
			toneBody(true);
			$('film-window').style.display='block';
			return false;
	  }
}


function set_hd_movies_informer_by_main(hd_movies)
{
	var rand_numbbers = [], my_rand=0;
	
	var x=0, i=0;
	while( rand_numbbers.length < 10 )
	{
		my_rand = Math.floor(Math.random()*hd_movies_informer_list.length);
		i=0;
		jQuery(rand_numbbers).each(function(k,v){
			if( v==my_rand )
				i=1;
		});
		if( !i )
			rand_numbbers[rand_numbbers.length] = my_rand;
	}
	
	var content='';
	
	var key = 1;
	content = '<ul class="the_list list_big">';
	jQuery(hd_movies).each(function(k,v){
		i=false;
		jQuery(rand_numbbers).each(function(k1,v1){ if( v1==k ) i=1; });
		if( i )
		{
			i = false;
			
			content += '<li><div class="image_wrapper"><div class="gradient"><div class="sr">'+
								'<div class="rating"><p>'+v.imdb_rating+'</p></div>'+
								'<a href="/'+v.tag+'/"><img src="'+v.img_domain+v.cover+'" alt=""></a>'+
								'</div>'+
								'</div>'+
							'</div>'+
							'<div class="pusher"></div><p class="title"><a href="'+v.tag+'">'+v.name+'</a></p>'+
							'<p class="date-country">'+((v.release_dttm)?(v.release_dttm+', '):(''))+' '+v.country+'</p>'+
						'</li>';
			
			if( key==2 )
			{
				content += '</ul><ul class="the_list list_big">';
				key=1;
			}
			else key++;
		}
	});
	content += '</ul>';
	
	jQuery('#hd_movies_informer_inner').html(content);
}

//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';
		jQuery("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_bg"><div class="card_act">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/giftcard/">My Gift Сards</a>.<br><br>Thank you for using movieberry.com!<span>Free<br> Bonus</span><div class="bottom"><a class="btn" href="'+this.activate_link+'">Activate now!</a><a class="close" href="javascript:GiftCardPopup.toggle();">Close</a></div></div></div>';
		jQuery('body').append(tpl);
		toneBody(true);
		this.showed=true;
	}
	this.hide = function() {
		jQuery('.card_act_bg').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();
	}
};


jQuery(document).ready(function(){
	detectInviteRequest();
	GiftCardPopup.check();
});
