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 ERR_INCORRECT_TERMS = 'You have not agreed to the Terms of Use.';
var regex_mail = new RegExp('^([A-Z0-9._%+-]+)@([A-Z0-9.-]+)\.([A-Z]{2,4})$', 'i');
var reg_autj_error_message = '';
var msie=(window.navigator.appName=='Microsoft Internet Explorer')?1:0;

function expand_review(id){
    new Ajax.Request('/review/full/'+id, {
        method:'get',
        onSuccess: function(transport) {
            $('review_'+id).innerHTML = transport.responseText;
            $('review_'+id).addClassName('full');
        }
    });
}

function vote_review(id, rating) {
    new Ajax.Request('/review/rate/'+id+'/'+(rating == 1 ? '+1' : '-1'), {
        method:'get',
        onSuccess: function (transport) {
            try{
                var json = transport.responseText.toQueryParams();
            }catch(e){
                alert('Something went wrong...');
                return;
            }
            if (json.success == 1) {
                $('karma_'+id).innerHTML = json.extra;
                alert('Thanks for your vote');
                return;
            }

            alert(json.msg.replace(/\+/g, ' '));
            if (json.extra) {
                window.open(json.extra, '_blank').focus();
            }
            if (json.toeval){
            	eval(json.toeval);
            }
        }, onFailure: function(){ alert('Something went wrong...'); }
    });
}

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);
}

function open_authform(type, backward, help_title, help_title2, buy_id, buy_format, buy_price)
{
	backward=(backward == undefined)?document.location:backward;
    $('auth_errors').style.display='none';
    $('reg_login_error').style.display='none';
    $('reg_pass_error').style.display='none';
    $('reg_terms_error').style.display='none';

	jQuery('#buy_id').val(buy_id);
	jQuery('#buy_format').val(buy_format);
	jQuery('#buy_price').val(buy_price);


	if( help_title && help_title.length )
		jQuery('#help_reg_title').html(help_title+'<br /><br />');


	if( help_title2 && help_title2.length )
		jQuery('#help_reg_title2').html(help_title2);


	if(type=='signup' || type=='register')
	{
		indexing_controllers(0);
		toneBody(true);
		$('authform').style.display='block';
		$('signup_form').style.display='block';
		$('login_form').style.display='none';
		$('authform_tab_signup').className='active';
		$('authform_tab_login').className='';
		$('register_backward').value=backward;
		
		jQuery('#reg_login').focus();
		
		return false;
	}
	if(type=='login')
	{
		indexing_controllers(0);
		toneBody(true);
		$('authform').style.display='block';
		$('signup_form').style.display='none';
		$('login_form').style.display='block';
		$('authform_tab_signup').className='';
		$('authform_tab_login').className='active';
		$('auth_backward').value=backward;
		
		jQuery('#login_auth').focus();
		
		return false;
	}
	if(type=='close')
	{
		indexing_controllers(1);
		
		if ($('#signup_form p .note')) {
			$('#signup_form p .note').show();
			if ($('.inv_reg')) {
				$('.inv_reg').remove();
			}
		}
		
		toneBody(false);
		$('authform').style.display='none';

		return false;
	}
	return false;
}

function open_userbar(tab, backward)
{
	if (tab == "register")
	{
		$('registration').show();
		$('authorization').hide();

	}
	else
	{
		$('registration').hide();
		$('authorization').show();



		setTimeout("$('login_auth').focus()", 200);
	}

	try{
		if(backward){
			if (tab == "register")
			{
				$('register_backward').value=backward;
			}
			else
			{
				$('auth_backward').value=backward;
			}
		}
	}catch(e){}

	$('popup_dimmer').setStyle({height: document.body.offsetHeight + 'px'});
	$('popup_dimmer').show();
	if(reg_autj_error_message != ''){
		$('alert_div_reg').innerHTML = reg_autj_error_message;
		$('alert_div_auth').innerHTML = reg_autj_error_message;
		reg_autj_error_message = '';
	}

}

function showTrailer(strTrailerUrl,strSizeType){
	strTrailerUrl = decodeLink(strTrailerUrl);
	$('popup_dimmer').setStyle({height: document.body.offsetHeight + 'px'});
	$('popup_dimmer').show();
	$('trailer_player_position').show();
	if(strSizeType == 'small'){
		var playerWidth = 320;
		var playerHeight = 148;

	}
	if(strSizeType == 'medium'){
		var playerWidth = 640;
		var playerHeight = 284;
	}
	if(strSizeType == 'large'){
		var playerWidth = 720;
		var playerHeight = 320;
	}

	$('player_closer').setStyle({marginLeft: (playerWidth-66) + 'px'});
	$('player_closer').focus();
	$('trailer_player_position').setStyle({left: (document.body.offsetWidth-playerWidth)/2 + 'px'});
	$('trailer_player_position').setStyle({top: 100 + 'px'});

	var flashvars = {file:strTrailerUrl,"m":"video", "uid":"trailer_player", "st":"/player/styles/" + strSizeType + ".txt", width:playerWidth, height:playerHeight};
	var params = {bgcolor:"#ffffff", allowFullScreen:"true", allowScriptAccess:"always"};
	new swfobject.embedSWF("http://movieberry.com/player/uppod.swf", "trailer_player", playerWidth, (playerHeight+35), "9.0.0",false,flashvars, params);
	return false;
}

function closePlayer(){
	$('trailer_player_position').innerHTML = '<div class="closer"  id="player_closer"><a href="#" onClick="return closePlayer();"></a></div><div id="trailer_player"></div>';
	$('trailer_player_position').hide();
	$('popup_dimmer').hide();
	return false;
}

function close_userbar(tab)
{
	$('popup_dimmer').hide();
	$('authorization').hide();
	$('registration').hide();
	$('alert_div_reg').innerHTML = '';
	$('alert_div_auth').innerHTML = '';
}


function check_registration()
{

    open_dimmer();
	var login = $('reg_login').value;
	var pass  = $('reg_pass').value;
	var cpass = $('reg_cpass').value;
	var terms = $('reg_terms').checked;

	var errors = new Hash();

	if (login.length < 6 || login.length > 100)
	{
		errors.set('login', ERR_TOO_SHORT_LOGIN);
	}
	else if (!regex_mail.test(login))
	{
		errors.set('login', ERR_INCORRECT_MAIL);
	}

	if (pass.length < 4 || pass.length > 12)
	{
		errors.set('pass', ERR_TOO_SHORT_PASSWORD);
	}
	else if (pass != cpass)
	{
		errors.set('pass', ERR_INCORRECT_CONFIRM_PASSWORD);
	}
	if(!terms) errors.set('terms', ERR_INCORRECT_TERMS);

	if (errors.size() == 0)
	{
	    var pre_params = {'login':login, 'pass':pass, 'cpass':cpass, 'terms':terms, 'type':'registration', 'ajax':true};
	    if (jQuery('#invite_hash_input')) {
	    	pre_params.invite_hash = jQuery('#invite_hash_input').val();
	    }
		new Ajax.Request('/user/registration/', {
        	method:'post',
	        parameters:pre_params,
        	onSuccess: function(transport) {

        		if(transport.responseText.length>0) {

                    if(!transport.responseText.match(/error\:true/)){
                        location.href= transport.responseText;
                    }else{
                        msg=eval("("+transport.responseText+")");
                           $('popup_dimmer1').hide();
                           $('reg_login_error').innerHTML = msg.login ? msg.login : '';$('reg_login_error').show();
                           $('reg_pass_error').innerHTML = msg.pass ? msg.pass : '';$('reg_pass_error').show();
                           $('reg_terms_error').innerHTML = msg.terms ? msg.terms : '';$('reg_terms_error').show();
			        }
                }else{
                    location.href="/";
                }
	        }
	    });
	}
	else
	{
		$('reg_login_error').innerHTML = errors.get('login') ? errors.get('login') : '';$('reg_login_error').show();
		$('reg_pass_error').innerHTML = errors.get('pass') ? errors.get('pass') : '';$('reg_pass_error').show();
		$('reg_terms_error').innerHTML = errors.get('terms') ? errors.get('terms') : '';$('reg_terms_error').show();
        $('popup_dimmer1').hide();
	}

	return false;
}

function check_auth()
{
	//$('submit_auth').disabled=true;
    open_dimmer();
	var login = $('login_auth').value;
	var pass  = $('pass_auth').value;
	var rme = $('rme').checked;

	var err = false;

	/*if ((login.length < 6 || login.length > 100) || (!regex_mail.test(login)) || (pass.length < 4 || pass.length > 12))
	{
		err = true;
	}*/

	if (!err)
	{
	    new Ajax.Request('/user/authn/', {
        	method:'post',
	        parameters:{'login':login, 'pass':pass, 'remember':rme, 'type':'auth', 'ajax':true},
        	onSuccess: function(transport) {
        		if(transport.responseText.length>0){

				// buy any from linker
				var link = document.location.toString();
				var patt = '/\\?/';
				
				if( jQuery('#buy_id').val() && jQuery('#buy_format').val() && jQuery('#buy_price').val() )
				{
					if( link.match(patt) )
						link += '&buy_id='+jQuery('#buy_id').val()+'&buy_format='+jQuery('#buy_format').val()+'&buy_price='+jQuery('#buy_price').val();
					else
						link += '?buy_id='+jQuery('#buy_id').val()+'&buy_format='+jQuery('#buy_format').val()+'&buy_price='+jQuery('#buy_price').val();;

					document.location = link;
				}
				else if( jQuery('#auth_backward').val() && !(link.match(patt)) )
					document.location = jQuery('#auth_backward').val();
				else
					document.location.reload();
			}else{
				document.getElementById('auth_errors').style.display = '';
				//$('submit_auth').disabled=false;
                $('popup_dimmer1').hide();
			}
	        }
	    });
	}
	else
	{
		document.getElementById('auth_errors').style.display = '';
        $('popup_dimmer1').hide();
	}

	return false;
}
function open_dimmer(){
    $('popup_dimmer1').setStyle({height: document.getElementById('authform').offsetHeight + 'px', width: document.getElementById('authform').offsetWidth + 'px'});
    $('popup_dimmer1').show();
}
//document.observe('dom:loaded', function () { $('submit_auth').observe('click', check_auth); });

function selectTab(season_id) {
    $('season_tab_' + selected_season_id).removeClassName('current');
    $('season_tab_' + season_id).addClassName('current');
    $('season_tab_' + selected_season_id).addClassName('noclass');
    selected_season_id = season_id;
    container = $('episodes');
    series_block = container.getElementsByTagName('li');
    series_block_count = series_block.length;
	var real_episodes_height = 0;

    for (var i = 0 ; i != series_block_count; i++) {
        tab_id = parseInt(series_block[i].id.match(/([0-9]+)$/)[1]);
        tab_season_id = parseInt(series_block[i].getAttribute('name').match(/([0-9]+)$/)[1]);
        if (season_id == tab_season_id) {
            $('season_block_id_' + tab_id).show();
			real_episodes_height += $('season_block_id_' + tab_id).offsetHeight;
        } else {
            $('season_block_id_' + tab_id).hide();
        }
    }
    var seasons_heights  = $('seasons').offsetHeight;
    var episodes_heights = $('episodes').offsetHeight;
    if (episodes_heights < seasons_heights) {
        var ua = navigator.userAgent.toLowerCase();
        if (ua.indexOf('msie') != -1 && ua.indexOf('opera') == -1) {
            $('episodes').style.height = seasons_heights + 15 + 'px';
        } else {
            $('episodes').style.minHeight = seasons_heights + 15 + 'px';
       }
    }
    if(real_episodes_height > episodes_heights){
    	var ua = navigator.userAgent.toLowerCase();
    	if (ua.indexOf('msie') != -1 && ua.indexOf('opera') == -1) {
	    	$('episodes').style.height = '';
    	}
    }
}

function selectAllSeries(season_id,invers,set) {
	if(set)$('season_box_' + season_id).checked=$('all_seasons').checked;
	else
	{
		if(!invers)$('season_box_' + season_id).checked = ($('season_box_' + season_id).checked) ? false : true;
		else $('season_box_' + season_id).checked = ($('season_box_' + season_id).checked) ? true : false;
	}
    container = $('episodes');
    series_block = container.getElementsByTagName('li');
    series_block_count = series_block.length;
    for (var i = 0 ; i != series_block_count; i++) {
        tab_id = parseInt(series_block[i].id.match(/([0-9]+)$/)[1]);
        tab_season_id = parseInt(series_block[i].getAttribute('name').match(/([0-9]+)$/)[1]);
        if (season_id == tab_season_id) {
            $('sbox_' + tab_id).checked = $('season_box_' + season_id).checked;
        }
    }
    updatePrices(1);
}
function checkSeasons()
{
	var season_box=$('seasons').select("[type='checkbox']");
	for(var i=0;i<season_box.length;i++)
	{
		id=parseInt(season_box[i].id.match(/([0-9]+)$/)[1]);
		var series=$('episodes').select("li[name='season_block_"+id+"']");
		var ser_sell=0;
		for(var j=0;j<series.length;j++)
			if($('sbox_'+parseInt(series[j].id.match(/([0-9]+)$/)[1])).checked)ser_sell++;
			else break;
		$('season_box_' + id).checked=(ser_sell==series.length)?true:false;
	}
}
function selectAllSeasons(set)
{
	var season_box=$('seasons').select("[type='checkbox']");
	if(set)
	{
		for(var i=0;i<season_box.length;i++)selectAllSeries(parseInt(season_box[i].id.match(/([0-9]+)$/)[1]),0,1);
	}
	else
	{
		var season_sel=0;
		for(var i=0;i<season_box.length;i++)if(season_box[i].checked)season_sel++;else break;
		$('all_seasons').checked=(season_sel==season_box.length)?true:false;
	}
}
var count_files = 0;

function updatePrices(not_select) {

    checkSeasons();
	if(!not_select)selectAllSeasons();
	count_files  = 0;

    var size_hd     = 0;
    var size_divx    = 0;
    var size_hqdivx  = 0;
    var size_ipod    = 0;

    var price_hd    = 0;
    var price_divx   = 0;
    var price_hqdivx = 0;
    var price_ipod   = 0;

    var count = {};
    var selected = '';

    var hideHd    = false;
    var hideDivx   = false;
    var hideIpod   = false;
    var hideHQDivX = false;

    $('issetHd').hide();
    $('emptyHd').show();
    $('issetDivx').hide();
    $('emptyDivx').show();
    $('issetIpod').hide();
    $('emptyIpod').show();
    //$('issetHQDivX').hide();
    //$('emptyHQDivX').show();

	$('hd_ul').className = 'fnex';
    //$('hq_ul').className = 'fnex';
    $('divx_ul').className = 'fnex';
    $('ipod_ul').className = 'fnex';


    $('tab-hd').className = str_replace(' fnex','',$('tab-hd').className) + ' fnex';
    //$('tab-hqdivx').className = str_replace(' fnex','',$('tab-hqdivx').className) + ' fnex';
    $('tab-divx').className = str_replace(' fnex','',$('tab-divx').className) + ' fnex';
    $('tab-ipod').className = str_replace(' fnex','',$('tab-ipod').className) + ' fnex';

    container = $('episodes');
    series_block = container.getElementsByTagName('li');
    series_block_count = series_block.length;

    for (var i = 0 ; i != series_block_count; i++) {
        serie_id      = parseInt(series_block[i].id.match(/([0-9]+)$/)[1]);
        tab_season_id = parseInt(series_block[i].getAttribute('name').match(/([0-9]+)$/)[1]);
        serie = series.get(serie_id);
        if ($('sbox_' + serie_id).checked) {
        	if (selected == '') {
        	    selected = serie_id;
        	} else {
        	    selected += ',' + serie_id;
        	}

            if (serie.size_hd) {
			    size_hd += serie.size_hd;
		    } else {
		        hideHd = true;
		    }
		    if (serie.size_divx) {
			    size_divx += serie.size_divx;
		    } else {
		        hideDivx = true;
		    }
		    if (serie.size_ipod) {
			    size_ipod += serie.size_ipod;
		    } else {
		        hideIpod = true;
		    }
		    if (serie.size_hqdivx) {
			    size_hqdivx += serie.size_hqdivx;
		    } else {
		        hideHQDivX = true;
		    }
		    if (serie.size_hd || serie.size_divx || serie.size_ipod || serie.size_hqdivx) {
		        count_files++;
		        count[tab_season_id] = count[tab_season_id] == undefined ? 1 : count[tab_season_id]+1;
		    }
        }
    }
    if (acctype=='6' || acctype=='5' || acctype=='4') {
		hideHd=true;
		hideDivx=true;
		hideIpod=true;
		hideHQDivX=true;
	}

    $('pk_hd').value='';
	$('pt_divx').value='';
	$('pk_ipod').value='';
	//$('pk_hqdivx').value='';
    if(!hideHd)
    	$('pk_hd').value=selected;
    if(!hideDivx)
    	$('pk_divx').value=selected;
    if(!hideIpod)
    	$('pk_ipod').value=selected;
   // if(!hideHQDivX)
    //	$('pk_hqdivx').value=selected;

    container = $('seasons');
    seasons_block = container.getElementsByTagName('li');
    seasons_block_count = seasons_block.length;
    for (var i = 0 ; i != seasons_block_count; i++) {
        tab_id = parseInt(seasons_block[i].id.match(/([0-9]+)$/)[1]);
        $('episodes_count_link_' + tab_id).innerHTML = count[tab_id] != undefined ? '(' + count[tab_id] + ')': '';
    }
    $('size_hd').innerHTML    = size_hd.toFixed(2) + ' MB';
    $('size_divx').innerHTML   = size_divx.toFixed(2) + ' MB';
    $('size_ipod').innerHTML   = size_ipod.toFixed(2) + ' MB';
    //$('size_hqdivx').innerHTML = size_hqdivx.toFixed(2) + ' MB';

    if (size_hd) {
        var summ_hd = serie.price_hd*count_files;
        $('price_hd').innerHTML    = '$' + serie.price_hd.toFixed(2) + ' x ' + count_files;
        $('summ_hd').innerHTML     = '$' + summ_hd.toFixed(2);
        $('pt_hd').value           = summ_hd.toFixed(2);
        if (hideHd == false) {
           $('issetHd').show();
           $('emptyHd').hide();
		   $('hd_ul').className = '';
           $('tab-hd').className = str_replace(' fnex','',$('tab-hd').className);
        }
    } else {
        $('price_hd').innerHTML = '$' + serie.price_hd.toFixed(2);
        $('summ_hd').innerHTML  = '$0.00';
        $('pt_hd').value        = 0;
        $('issetHd').hide();
        $('emptyHd').show();
    }

    if (size_divx) {
        var summ_divx = serie.price_divx*count_files;
        $('price_divx').innerHTML    = '$' + serie.price_divx.toFixed(2) + ' x ' + count_files;
        $('summ_divx').innerHTML     = '$' + summ_divx.toFixed(2);
        $('pt_divx').value           = summ_divx.toFixed(2);
        if (hideDivx == false) {
            $('issetDivx').show();
            $('emptyDivx').hide();
			$('divx_ul').className = '';
            $('tab-divx').className = str_replace(' fnex','',$('tab-divx').className);
        }
    } else {
        $('price_divx').innerHTML = '$' + serie.price_divx.toFixed(2);
        $('summ_divx').innerHTML  = '$0.00';
        $('pt_divx').value        = 0;
        $('issetDivx').hide();
        $('emptyDivx').show();
    }

    if (size_ipod) {
        var summ_ipod = serie.price_ipod*count_files;
        $('price_ipod').innerHTML    = '$' + serie.price_ipod.toFixed(2) + ' x ' + count_files;
        $('summ_ipod').innerHTML     = '$' + summ_ipod.toFixed(2);
        $('pt_ipod').value           = summ_ipod.toFixed(2);
        if (hideIpod == false) {
            $('issetIpod').show();
            $('emptyIpod').hide();
			$('ipod_ul').className = '';
            $('tab-ipod').className = str_replace(' fnex','',$('tab-ipod').className);
        }
    } else {
        $('price_ipod').innerHTML = '$' + serie.price_ipod.toFixed(2);
        $('summ_ipod').innerHTML  = '$0.00';
        $('pt_ipod').value        = 0;
        $('issetIpod').hide();
        $('emptyIpod').show();
    }

    if (size_hqdivx) {
        var summ_hqdivx = serie.price_hqdivx*count_files;
        $('price_hqdivx').innerHTML    = '$' + serie.price_hqdivx.toFixed(2) + ' x ' + count_files;
        $('summ_hqdivx').innerHTML     = '$' + summ_hqdivx.toFixed(2);
        $('pt_hqdivx').value           = summ_hqdivx.toFixed(2);
        if (hideHQDivX == false) {
            //$('issetHQDivX').show();
           // $('emptyHQDivX').hide();
			$('hq_ul').className = '';
            $('tab-hqdivx').className = str_replace(' fnex','',$('tab-hqdivx').className);
        }
    } else {
        //$('price_hqdivx').innerHTML = '$' + serie.price_hqdivx.toFixed(2);
        //$('summ_hqdivx').innerHTML  = '$0.00';
        //$('pt_hqdivx').value        = 0;
        //$('issetHQDivX').hide();
        //$('emptyHQDivX').show();
    }

}

function NewComfirmation(form_to_submit, help_title, series_format){
	if(confirmation(form_to_submit.price_total.value, '','', help_title, series_format, form_to_submit)){
		form_to_submit.submit();
	}
}



function str_replace(search, replace, subject) {
	return subject.split(search).join(replace);
}

function decodeLink(str){
	url = '';
	for(i=0;i<str.length;i++){
		url = url + String.fromCharCode(str.charCodeAt(i)-1);
	}
	return url;
}


function getPreview(str){
	document.location = decodeLink(str);
	return false;
}
function ShowFullStory(){
	$('short_story').hide();
	$('full_story').show();
}


function getBodyScrollTop()
{
  return self.pageYOffset || (document.documentElement && document.documentElement.scrollTop) || (document.body && document.body.scrollTop);
}



function getBodyScrollLeft()
{
  return self.pageXOffset || (document.documentElement && document.documentElement.scrollLeft) || (document.body && document.body.scrollLeft);
}




function open_post() {
  if (!is_authorized) {
    reg_autj_error_message = "You have to register or log in to add a comment.";
      $('auth_backward').value = backward;
      open_userbar('login');
      return;
  }
 // var top = document.viewport.getScrollOffsets()['top'];
  //var height = document.viewport.getHeight();
   $('postbox').show();
  $('postbox_litter').show();
  $('postbox_post').show();
  $('postbox_litter').setStyle({height: document.body.offsetHeight + 'px'});
 // $('postbox_post').setStyle({top: (top + height/2 - 250) + 'px'});

 nRealTop = getBodyScrollTop();
 	$('postbox_post').setStyle({top: (nRealTop + 150) + 'px'});

 // $('review_title').focus();
}

function close_post(){
	$('postbox_litter').hide();
	$('postbox_post').hide();
	$('postbox').hide();
}



// Dan JS START
_authform = new Object();

_authform.forgetOpen = function()
{
	new Ajax.Request('/user/forget/show', {
		onSuccess: function(response){
			$('authform').hide();
                        var div = document.createElement('div');
                        div.setAttribute('id', '_auth_form_forget');
			div.innerHTML = response.responseText;
			window.document.body.appendChild(div);
		}
	});
}

_authform.forgetClose = function()
{
	$('_auth_form_forget').remove();
	toneBody(false);
}

_authform.forgetSend = function()
{
        if( $('preloader_forgot_password').getStyle('visibility') != 'hidden' )
          return;

	$('preloader_forgot_password').setStyle({visibility: 'visible'});

	new Ajax.Request('/user/forget/forget', { method: 'post', parameters: { login: $('FORGET_INPUT_ROW').value, type: "forget" }, onSuccess: function(r) { $('_auth_form_forget').innerHTML = r.responseText; } });
}

function open_forget( type, backward ) {_authform.forgetOpen();}



function indexing_controllers(i)
{
	if( !i ){
		jQuery('*').attr('tabindex', '-1');
		jQuery('input').attr('tabindex', '-1');
		jQuery('#login_auth').attr('tabindex', '1');
		jQuery('#reg_login').attr('tabindex', '1');
		jQuery('#reg_pass').attr('tabindex', '2');
		jQuery('#reg_cpass').attr('tabindex', '3');
		jQuery('#reg_terms').attr('tabindex', '4');
		
		jQuery('#pass_auth').attr('tabindex', '2');
		jQuery('#reg_cpass').attr('tabindex', '3');
		jQuery('#rme').attr('tabindex', '4');
		jQuery('#submit_auth').attr('tabindex', '5');
	}
	else{
		jQuery('a').attr('tabindex', '1');
		jQuery('input').attr('tabindex', '1');
	}
}

function close_only_auth_form()
{
	$('authform').style.display='none'; 
}

// Dan JS END


function goWithAuth(url) {
	if (is_authorized == true) {
		location.href=url;
	} else {
		open_authform('login', url);
	}
}



// @add:13.01.2012
// new price calculation
var Serial = new function() {
	
	this.seas_sel = new Array();
	this.seas_all = new Array();
	this.epis_sel = new Array();
	this.epis_all = new Array();
	this.size = {
		hd:0,
		divx:0,
		ipod:0
	};
	this.price = {
		hd:0,
		divx:0,
		ipod:0
	};
	this.btnshow = {
		hd:true,
		divx:true,
		ipod:true
	}
	
	
	// -------- seasons ---------
	
	// 
	this.check_seasons = function() {
		
	}
	
	//get all seasons
	this.get_seasons = function() {
		var _s = jQuery('#seasons input:checkbox');
		this.seas_all=[];
		for(var i=0;i<_s.length;i++) {
			var item = {
				i:i,
				id:jQuery(_s[i]).attr('id')
			};
			item.id = parseInt(item.id.match(/([0-9]+)$/)[1]);
			this.seas_all[i] = item;
		}
		return true;
	}
	
	
	
	// ------------ episodes -------------
	
	// get all episodes 
	this.get_episodes = function() {
		var _e = jQuery('#episodes input:checkbox');
		this.epis_all=[];
		for(var i=0;i<_e.length;i++) {
			var item = {
				i:i,
				id:jQuery(_e[i]).attr('id'),
				checked:false,
				season:0
			}
			item.id = parseInt(item.id.match(/([0-9]+)$/)[1]);
			item.checked=jQuery(_e[i]).attr('checked');
			var _seas = jQuery('#season_block_id_'+item.id).attr('name'); 
			if (_seas) {
				item.season = parseInt(_seas.match(/([0-9]+)$/)[1]);
			}
			this.epis_all[i] = item;
		}
		return true;
	}
	
	// get all selected episodes
	this.get_selected_episodes = function() {
		var _e = jQuery('#episodes input:checkbox');
		this.epis_sel=[];
		for(var i=0;i<_e.length;i++) {
			var item = {
				i:i,
				id:jQuery(_e[i]).attr('id'),
				checked:false,
				season:0
			}
			item.id = parseInt(item.id.match(/([0-9]+)$/)[1]);
			item.checked=jQuery(_e[i]).attr('checked');
			var _seas = jQuery('#season_block_id_'+item.id).attr('name');
			if (_seas) {
				item.season = parseInt(_seas.match(/([0-9]+)$/)[1]);
			}
			if (item.checked==true) {
				this.epis_sel[this.epis_sel.length] = item;
			}
		}
		return true;
	}
	
	//get episodes for some season
	this.get_episodes_by_season = function(season_id) {
		var _e = jQuery('#episodes li[name="season_block_'+season_id+'"]');
		this.epis_sel=[];
		for(var i=0;i<_e.length;i++) {
			var item = {
				i:i,
				id:jQuery(_e[i]).attr('id')
			}
			item.id = parseInt(item.id.match(/([0-9]+)$/)[1]);
			this.epis_sel[i] = item;
		}
		return true;
	}
};


// Controls for serial page 
// rewrite using jQuery
var SerialControls = new function() {
	
	this.current_season_id = 0;
	this.episodes_block_height=0;	
	
	// check or uncheck one episode
	this.sel_episode = function() {
		this.update_labels();
	}
	
	// check or uncheck one season
	this.sel_season = function(id) {
		this.opentab_season(id);
		var action=false;
		if (jQuery('#season_box_'+id).attr('checked')==true) {
			action=true;
		}
		jQuery('#season_box_'+id).attr('checked',action);
		Serial.get_episodes_by_season(id);
		for (var i=0;i<Serial.epis_sel.length;i++) {
			jQuery('#sbox_' + Serial.epis_sel[i].id).attr('checked',action);
		}
		this.update_labels();
	}
	
	// open season tab
	this.opentab_season = function(id) {
		jQuery('#season_tab_' + this.current_season_id).removeClass('current');
		jQuery('#season_tab_' + this.current_season_id).addClass('noclass');
		jQuery('#season_tab_' + id).addClass('current');
		this.current_season_id = id;
		Serial.get_episodes_by_season(this.current_season_id);
		jQuery('#episodes li').hide(); // hide all
		for (var i=0;i<Serial.epis_sel.length;i++) {
			id = Serial.epis_sel[i].id;
			jQuery('#season_block_id_' + id).show(); // show only for that season
			this.episodes_block_height += jQuery('#season_block_id_' + id).offsetHeight;
		}
		this.fix_block_height(); // correct height for episodes block
	}
	
	// check or uncheck all seasons
	this.sel_all = function() {
		var action = false;
		var state = false;
		if (jQuery('#all_seasons').attr('checked')==true) {
			action = true; // check all
		} // else uncheck all
		Serial.get_episodes();
		for (var i=0;i<Serial.epis_all.length;i++) {
			jQuery('#sbox_' + Serial.epis_all[i].id).attr('checked',action);
		}
		Serial.get_seasons();
		for (var i=0;i<Serial.seas_all.length;i++) {
			jQuery('#season_box_' + Serial.seas_all[i].id).attr('checked',action);
		}
		this.update_labels();
	}
	
	// update labels
	this.update_labels = function() {
		jQuery('hd_ul').addClass('fnex');
		jQuery('divx_ul').addClass('fnex');
		jQuery('ipod_ul').addClass('fnex');
		jQuery('tab-hd').addClass('fnex');
		jQuery('tab-divx').addClass('fnex');
		jQuery('tab-ipod').addClass('fnex');
		Serial.get_selected_episodes();
		count_files = 0;
		var count = {};
		var selected = '';
		Serial.btnshow.hd=true;
		Serial.btnshow.divx=true;
		Serial.btnshow.ipod=true;
		Serial.price.hd=0;
		Serial.price.divx=0;
		Serial.price.ipod=0;
		Serial.size.hd=0;
		Serial.size.divx=0;
		Serial.size.ipod=0;
		for (var i=0;i<Serial.epis_sel.length;i++) {
			serie = series.get(Serial.epis_sel[i].id); // from price
			if (Serial.epis_sel[i].checked) {
				if (selected == '') {
	        	    selected = Serial.epis_sel[i].id;
	        	} else {
	        	    selected += ',' + Serial.epis_sel[i].id;
	        	}
			}
			if (serie.size_hd) {
			    Serial.size.hd += serie.size_hd;
		    } else {
		        Serial.btnshow.hd = false;
		    }
		    if (serie.size_divx || serie.size_hqdivx) {
		    	if (serie.size_hqdivx) {
		    		Serial.size.divx += serie.size_hqdivx;
		    	} else {
		    		Serial.size.divx += serie.size_divx;
		    	}
		    } else {
		        Serial.btnshow.divx = false;
		    }
		    if (serie.size_ipod) {
			    Serial.size.ipod += serie.size_ipod;
		    } else {
		        Serial.btnshow.ipod = false;
		    }
		    if (serie.size_hd || serie.size_divx || serie.size_ipod) {
		        count_files++;
		        if (count[Serial.epis_sel[i].season] == undefined) {
		        	count[Serial.epis_sel[i].season] = 1;
		        } else {
		        	count[Serial.epis_sel[i].season]++;
		        }
		    }
		}
		if (acctype=='6' || acctype=='5' || acctype=='4') { //hide for accounts 
			Serial.btnshow.hd=false;
			Serial.btnshow.divx=false;
			Serial.btnshow.ipod=false;
		}
		$('pk_hd').value='';
		$('pt_divx').value='';
		$('pk_ipod').value='';
		if (Serial.btnshow.hd==true) {
			$('pk_hd').value=selected;
		}
		if (Serial.btnshow.divx==true) {
			$('pk_divx').value=selected;
		}
		if (Serial.btnshow.ipod==true) {
			$('pk_ipod').value=selected;
		}
		// calculate selected episodes
		Serial.get_seasons();
		for (var i=0;i<Serial.seas_all.length;i++) {
			var _count = '';
			if (count[Serial.seas_all[i].id] != undefined) {
				_count = '(' + count[Serial.seas_all[i].id] + ')';
			}
			jQuery('#episodes_count_link_' + Serial.seas_all[i].id).html(_count);
		}
		//set sizes lables
		jQuery('#size_hd').text(Serial.size.hd.toFixed(2)+' MB');
		jQuery('#size_divx').text(Serial.size.divx.toFixed(2)+' MB');
		jQuery('#size_ipod').text(Serial.size.ipod.toFixed(2)+' MB');
		
		if (Serial.size.hd > 0) {
			var summ_hd = serie.price_hd * count_files;
			jQuery('#price_hd').text('$'+serie.price_hd.toFixed(2) + ' x ' + count_files);
			jQuery('#summ_hd').text('$'+summ_hd.toFixed(2));
			jQuery('#pt_hd').val(summ_hd.toFixed(2));
			if (Serial.btnshow.hd==true) {
				jQuery('#issetHd').show();
				jQuery('#emptyHd').hide();
				jQuery('#hd_ul').removeClass('fnex');
				jQuery('#tab-hd').removeClass('fnex');
			}
		} else {
			jQuery('#price_hd').text('$'+serie.price_hd.toFixed(2));
			jQuery('#summ_hd').text('$0.00');
			jQuery('#pt_hd').value = 0;
	        jQuery('#issetHd').hide();
	        jQuery('#emptyHd').show();
		}
		if (Serial.size.divx > 0) {
			var summ_divx = serie.price_divx * count_files;
			jQuery('#price_divx').text('$'+serie.price_divx.toFixed(2) + ' x ' + count_files);
			jQuery('#summ_divx').text('$'+summ_divx.toFixed(2));
			jQuery('#pt_divx').val(summ_divx.toFixed(2));
			if (Serial.btnshow.divx ==true) {
				jQuery('#issetDivx').show();
				jQuery('#emptyDivx').hide();
				jQuery('#divx_ul').removeClass('fnex');
				jQuery('#tab-divx').removeClass('fnex');
			}
		} else {
			jQuery('#price_divx').text('$'+serie.price_divx.toFixed(2));
			jQuery('#summ_divx').text('$0.00');
			jQuery('#pt_divx').value = 0;
	        jQuery('#issetDivx').hide();
	        jQuery('#emptyDivx').show();
		}
		if (Serial.size.ipod > 0) {
			var summ_ipod = serie.price_ipod * count_files;
			jQuery('#price_ipod').text('$'+serie.price_ipod.toFixed(2) + ' x ' + count_files);
			jQuery('#summ_ipod').text('$'+summ_ipod.toFixed(2));
			jQuery('#pt_ipod').val(summ_ipod.toFixed(2));
			if (Serial.btnshow.ipod ==true) {
				jQuery('#issetIpod').show();
				jQuery('#emptyIpod').hide();
				jQuery('#ipod_ul').removeClass('fnex');
				jQuery('#tab-ipod').removeClass('fnex');
			}
		} else {
			jQuery('#price_ipod').text('$'+serie.price_ipod.toFixed(2));
			jQuery('#summ_ipod').text('$0.00');
			jQuery('#pt_ipod').value = 0;
	        jQuery('#issetIpod').hide();
	        jQuery('#emptyIpod').show();
		}
	}

	
	// fix height of block with episodes list
	this.fix_block_height = function() {
		var seasons_heights  = jQuery('#seasons').offsetHeight;
	    var episodes_heights = jQuery('#episodes').offsetHeight;
	    if (episodes_heights < seasons_heights) {
	        var ua = navigator.userAgent.toLowerCase();
	        if (ua.indexOf('msie') != -1 && ua.indexOf('opera') == -1) {
	            jQuery('#episodes').css('height',seasons_heights + 15);
	        } else {
	        	jQuery('#episodes').css('minHeight',seasons_heights + 15);
	       }
	    }
	    if(this.episodes_block_height > episodes_heights){
	    	var ua = navigator.userAgent.toLowerCase();
	    	if (ua.indexOf('msie') != -1 && ua.indexOf('opera') == -1) {
		    	jQuery('#episodes').css('height','');
	    	}
	    }
	}
} 
