function setCheck(state, form)
{
    var form = form ? form : 'mainForm';
    $(form).select('.checkbox input').each(function(i){
        i.checked = state;
    })
}

function setCookie(name, value, expires, path, domain, secure) {
    document.cookie= name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires.toGMTString() : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}

function getCookie(name) {
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1) {
        begin = dc.indexOf(prefix);
        if (begin !== 0) return null;
    } else {
        begin += 2;
    }
    var end = document.cookie.indexOf(";", begin);
    if (end == -1) {
        end = dc.length;
    }
    return unescape(dc.substring(begin + prefix.length, end));
}

function deleteCookie(name, path, domain) {
    if (getCookie(name)) {
        document.cookie = name + "=" +
            ((path) ? "; path=" + path : "") +
            ((domain) ? "; domain=" + domain : "") +
            "; expires=Thu, 01-Jan-70 00:00:01 GMT";
    }
}

function setInputText( id, text )
{
    $(id).value = text;
    $(id).observe('focus',function(event){
       if (text == $(id).value) $(id).value = '';
       $(id).removeClassName('red');
    });
    
    $(id).observe('blur',function(event){
       if ('' == $(id).value) $(id).value = text;
    });
}

/* 
***************************/

function hide_menu(name)
{		
	$$(".menu_table").each(function(item1){
		item1.hide();
	});
	
	/* ================= */		
	$$(".menu_activ").each(function(item2){			
		item2.className='no_menu_activ';
	});
			
	/* ================= */
	$$(".menu_activ_a").each(function(item3){
		//item3.className='no_menu_activ_a';
		item3.removeClassName('menu_activ_a');
		item3.addClassName('no_menu_activ_a');
	});

	/* ================= */
	$$("#menu_top_center span").each(function(item4){
		item4.show();
	});
}

function show_menu (item_menu, span_h)
{       
      $('table_'+item_menu).show();
	  $('li_'+item_menu).className = 'menu_activ';
	  $('a_'+item_menu).removeClassName('no_menu_activ_a');
	  $('a_'+item_menu).addClassName('menu_activ_a');
	  
	  
	  $(span_h).hide();		  
}

var input={

    type: 'input',

    onFocus : function( text, elm )
    {
        elm.value = ( elm.value == text ) ? '' : elm.value;
    },

    onBlur : function( text, elm )
    {
        elm.value = ( elm.value == text || elm.value == ''  ) ? text : elm.value;
    }
}

function add_to_favorite( title, url )
{
	 if (window.sidebar)
	     window.sidebar.addPanel( title, url, '' );
	 else if (window.external)
	     window.external.AddFavorite( url, title );
	 else
	     alert('Sorry, can not add to bookmark!');
}

function tabs (id,userOptions) 
{
    options = {
        topWhitespace:true,
        elementsInRow:5,
        elementWidth:112
    }
    
    Object.extend(options,userOptions || {});
 
    new Control.Tabs( id, {activeClassName:'ui-tabs-selected'});

    var tabList = $$('#' + id + ' li');
    
    if ( tabList.length <= options.elementsInRow )
        return;
    
    var insertAfter = tabList.length % options.elementsInRow;

    if ( !insertAfter )
        return;
        
    element=new Element('li',{'class':'empty','style':'width:' + ( options.elementsInRow - insertAfter ) * options.elementWidth + 'px;height:26px'});
    element.update('&nbsp;');
    tabList[insertAfter].insert({before:element});
}


load = {
    drama:function( page, lang, cat )
    {
        load.execute(cat + '_table' , ROOT + '/drama/' + lang + '/page/' + page + '/category/' + cat + '/index.html' );
    },
    
    anime:function( page )
    {
        load.execute('anime_table' , ROOT + '/anime/page/' + page + '/index.html' );
    },
    
    songs:function( page, lang )
    {
        load.execute('songs_table' , ROOT + '/songs/' + lang + '/page/' + page + '/index.html' );
    },
     
	videos:function( page, lang )
    {
        load.execute('videos_table' , ROOT + '/videos/' + lang + '/page/' + page + '/index.html' );
    },
	 
    setLoading:function(id)
    {
        $(id).update('<tr><td colspan="3" class="loading"><img src="/img/prototype/loading.gif" alt="loading..." /></td></tr>')
    },
    
    execute:function(id, link)
    {
        new Ajax.Updater(id,link,{
            method:'get',
            evalScripts:true,
            onCreate:function(){
                load.setLoading(id);
            }
        });
    }

};

loadMirror=function(mirror_id, code)
{
    
    if ( typeof(imagesize) == 'undefined' )
        imagesize = 'small';
	

    
    var obj ='<object id="flashObject" type="application/x-shockwave-flash" data="' + code + '" >' +
			'<param name="movie" value="' + code + '"></param>' +
			'<param name="allowfullscreen" value="true"/>' +
    		'<param name="allowscriptaccess" value="always"/>' +
			
		     '</object>';
	
    $('flashPlayer').update( obj );

    if ( imagesize == 'small' )
        setDimension( 450, 360 );
    else
        setDimension( 800, 640 );

    $$('ul#mirrors li a').each(function(i){
       i.removeClassName('sel');
    });

    if ( $('mirror-' + mirror_id ) )
        $('mirror-' + mirror_id ).addClassName('sel');
    
    if ( $('size-switcher') )
    {
        $('size-switcher').stopObserving();
        $('size-switcher').observe('click', function(event){
            if ( $('size-switcher').innerHTML.include('Larger') ){
                $('size-switcher').update('Smaller');
                imagesize='big';
                setDimension( 800, 640 );
				$('flashPlayer').setStyle({ width: '805px', height: '645px' });
				$('right_player_cont').setStyle({ paddingTop: '660px' });
            }else{
                $('size-switcher').update('Larger');
                setDimension( 450, 360 );
                imagesize='small';
				$('flashPlayer').setStyle({ width: '450px', height: '360px' });
				$('right_player_cont').setStyle({ paddingTop: '0px' });
            }
       });
    }
       
   if ( $('fullscreen-link') )
   {
       $('fullscreen-link').stopObserving();
       $('fullscreen-link').observe('click', function(event){
            var dim = document.viewport.getDimensions();
            setDimension( 450, 360 );
            imagesize='small';
            $('flashPlayer').setStyle({ width: '450px', height: '360px' });
            $('size-switcher').update('Larger');
            $('right_player_cont').setStyle({ paddingTop: '0px' });
            var fobj ='<object width="' + ( dim.width - 100 ) + '" height="' + ( dim.height-100 ) + '" type="application/x-shockwave-flash" data="' + code + '" >' +
    			'<param name="movie" value="' + code + '"></param>' +
    			'<param name="allowfullscreen" value="true"/>' +
    			'<param name="allowscriptaccess" value="always"/>' +
    			'<param name="bgcolor" value="#000000"/>' +
    			'<param name="quality" value="high"/>' +
    		     '</object>';
        	$('fullscreen-swf').update(fobj);    
        	$('fullscreen-area').show(); 
			
			

//            Lightview.show({
//              href: code,
//              options: {
//                  width: window.innerWidth - 100, 
//                  height: window.innerHeight - 100
//              }
//            });
        });
   }
}

function setDimension(w,h)
{
    if ( $('flashObject') ) {
        $('flashObject').width = w;
        $('flashObject').height = h;
    }

    if ( $('flashObjectEmbed') ) {
        $('flashObjectEmbed').width = w;
        $('flashObjectEmbed').height = h;
    }
}

function loadPart( part_id )
{
    new Ajax.Request(ROOT + '/ajax/parts/load/id/' + part_id + '/',{ 
        method:'get',
        onComplete:function(transport)
        {
            $$('ul#parts li a').each(function(i){
               i.removeClassName('sel');
            });
            
            var response = transport.responseJSON;
            loadPartComments( part_id );
            $('part-' + response.title ).addClassName('sel');
            
            $('flashPlayer').update();
            $('mirrors').update();
            var i = 0;

            if ( response.mirrors.length > 1 )
                $('mirrors-list').show();
            else
                $('mirrors-list').hide();
                
            $('part_title').update(response.title);
            
            if(response.next_part)
            {
                $('next_part').show();
                
                $('next_part').update('<a href="#' + response.next_part.id + '" class="link_next" onclick="loadPart(' + response.next_part.id + ');return false;">Watch next part</a>');
            }
            else
            {
                $('next_part').hide();
                $('next_part').update('&nbsp;');
            }
            
            response.mirrors.each(function(mirror){
                i++;
                $('mirrors').insert("<li><a href=\"#\" id=\"mirror-" + mirror.id + "\" onclick=\"loadMirror('" + mirror.id + "', '" + mirror.code + "');return false;\" " + ((i==1) ? 'class="sel"' : '' ) + " >Mirror " + i + "</a> </li>");
                $('ref_mirror_id').value = mirror.id;
                if ( mirror.is_default )
                    loadMirror(mirror.id, mirror.code);
            });
        }
    });

}

function loadPartComments( part_id )
{
        var instance = Comment.prototype;

        var link = ROOT + '/ajax/comments/load/type/part/id/' + part_id + '/page/1/';
        
        new Ajax.Updater(
           instance.elements.main,
           link,
           {
                onCreate: function(){
                    $(instance.elements.main).update('<div class="loading"><img src="/img/loading.gif"></div>');
                },
                onSuccess: function(){
                    //$('comments').scrollTo();
                    
                    $('comments_curr_page').value = 1;
                    
                    
                }
           }
        );
    $('comments').show();
    $('comment_ref').value = 'part';
    $('comment_ref_id').value = part_id;
    comment.reloadCaptcha( 'part' + part_id );
}


function reloadCaptcha ( key, id )
{
    $(id).src = '/index/captcha/key/' + key +  '?' + (new Date()).getTime();
};

function initLanguageTabs()
{
    $$('.ui-tabs-nav li a').each(function(a){
        a.observe('click',function(event){

           var lang = a.getAttribute('href').gsub(/^[^\_]+_/, '');
           var type = a.className.gsub(/\s*ui\-tabs\-selected\s*/, '');
           var tbody = type + '_' + lang + '_data';

           if ( !$(tbody) || !$(tbody).empty() )
                return;
                
            new Ajax.Updater(tbody,ROOT + '/ajax/' + type + '/get/' + lang,{
                    method:'get',
                    evalScripts:true,
                    onCreate:function(){
                        $(tbody).update('<tr><td colspan="2" class="loading"><img src="/img/prototype/loading.gif" alt="loading..." /></td></tr>')
                    }
                }
            );
        });
    });
}