function getCookie( name ) {
    var start = document.cookie.indexOf( name + "=" );
    var len = start + name.length + 1;
    if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
        return null;
    }
    if ( start == -1 ) return null;
    var end = document.cookie.indexOf( ';', len );
    if ( end == -1 ) end = document.cookie.length;
    return unescape( document.cookie.substring( len, end ) );
}

function SetCookie(cookieName,cookieValue,nDays,path) {
 var today = new Date();
 var expire = new Date();
 if (nDays==null || nDays==0) nDays=1;
 expire.setTime(today.getTime() + 3600000*24*nDays);
 document.cookie = cookieName+"="+escape(cookieValue)
                 + ";expires="+expire.toGMTString()
                 + ';path='+path
                 + ';domain='+cookie_domain
}


function toggleBox(listname){

    var divname = listname+"_list";
    var display = $("#"+divname).css('display');
    if (display == 'none') {
        $("#"+divname).css({display: 'block'});
        $("#"+divname+"_arrow").html("<img src=\""+global_path+"/images/arr1.gif\" />");
        SetCookie('__ll'+listname, 1, null, '/');
    } else if (display == 'block') {
        $("#"+divname).css({display: 'none'});
        $("#"+divname+"_arrow").html("<img src=\""+global_path+"/images/arr1l.gif\" />")
        SetCookie('__ll'+listname, 0, null, '/');
    }
    return false;
}


function toggleHotLyrics(mode){
    if (mode != 0 && mode!= 1) mode = 0;
    $("#ht_load").show();
    $.ajax({
        type:"POST",
        url:global_path+mode+"/getHotLyrics.html",
        dataType:"plain",
        success:function(data,textStatus){
                $("#hotLyricsDiv").html(data);
                if (mode == 1) { $("#ht_today_i").hide(); $("#ht_today_l").show(); $("#ht_all_l").hide(); $("#ht_all_i").show(); }
                else { $("#ht_today_l").hide(); $("#ht_today_i").show(); $("#ht_all_i").hide(); $("#ht_all_l").show(); }
                $("#ht_load").hide();
            },
        error:function(data,textStatus){ alert("Error");$("#ht_load").hide(); }
    });

}

function toggleAlign(mode){
    $("#lyrics_text").css({'text-align':mode});
    globalAlign = mode;
    saveLyricsMode();
}

function toggleLyricsFont(obj){
    var font = obj.options[obj.selectedIndex].value;
    $("#lyrics_text").css({'font-family':font});
    globalFontFamily = font;
    saveLyricsMode();
    makeScroller();
}
function toggleLyricsSize(obj){
    var size = obj.options[obj.selectedIndex].value;
    $("#lyrics_text").css({'font-size':size+'px'});
    globalFontSize = size;
    saveLyricsMode();
    makeScroller();
}
function saveLyricsMode(){
    SetCookie('_llAlign',globalAlign,100,'/');
    SetCookie('_llFontFamily',globalFontFamily,100,'/');
    SetCookie('_llFontSize',globalFontSize,100,'/');
}
function saveScrollSpeed(){
  SetCookie('_llSpeed',scrollChange,100,'/');
}

/** Rate and stars functions **/
function mouseMove(ev) {
    ev = ev || window.event;
    var target   = ev.target || ev.srcElement;
    var mousePos = getPosition(ev);
    var pos = findPos(target);
    var x = mousePos.x - pos[0];

    //podmien klasy
    if(x>=0 && x<=16) target.className = "star1";
    else if(x>=17 && x<=32) target.className = "star2";
    else if(x>=33 && x<=48) target.className = "star3";
    else if(x>=49 && x<=64) target.className = "star4";
    else if(x>=66 && x<=80) target.className = "star5";
}

function stars(element,current_class) {
    element.onmousemove = mouseMove;
    element.onmouseout = function(){this.className = current_class;}
    element.onmousedown = clickStar;
}

function clickStar(ev) {
    ev = ev || window.event;
    var target   = ev.target || ev.srcElement;
    var mousePos = getPosition(ev);
    var pos = findPos(target);
    var x = mousePos.x - pos[0];

    var rate;

    //zbadaj ocene
    if(x>=0 && x<=16) rate=1;
    else if(x>=17 && x<=32) rate=2;
    else if(x>=33 && x<=48) rate=3;
    else if(x>=49 && x<=64) rate=4;
    else if(x>=66 && x<=80) rate=5;
    var cont = target.parentNode;
    var link_id = target.id;
    cont.innerHTML = "<img src=\""+global_path+"/images/ajax-loader.gif\" />";
    $.get( global_path+"ajax_rate_lyric.plain?lyric_id="+link_id+"&rate="+rate, null, function(obj){
        if(obj=="error") {
            cont.innerHTML = '<div class="homeRate">There was an error try again later</div>';
            return;
        }
    var parts = obj.split("-");
    var new_rate = parseFloat(parts[0]);
    var klasa = "star"+Math.round(new_rate);
    cont.innerHTML = '<div style="float:left;position:relative;top:-4px;left:3px;" class="'+klasa+'" title="'+new_rate+'"></div><div style="float:left;">('+parts[1]+' votes)</div>';
     })
}

function getPosition(e) {
    e = e || window.event;
    var cursor = {x:0, y:0};
    if (e.pageX || e.pageY) {
        cursor.x = e.pageX;
        cursor.y = e.pageY;
    }
    else {
        var de = document.documentElement;
        var b = document.body;
        cursor.x = e.clientX +
            (de.scrollLeft || b.scrollLeft) - (de.clientLeft || 0);
        cursor.y = e.clientY +
            (de.scrollTop || b.scrollTop) - (de.clientTop || 0);
    }
    return cursor;
}
function findPos(obj) {
    var curleft = curtop = 0;
    if (obj.offsetParent) {
        curleft = obj.offsetLeft
        curtop = obj.offsetTop
        while (obj = obj.offsetParent) {
            curleft += obj.offsetLeft
            curtop += obj.offsetTop
        }
    }
    return [curleft,curtop];
}

function addToFavourites(songId,songName){

    $("#a_fav_link").hide();
    $.get( global_path+"add_to_favourites.plain?lyric_id="+songId, null, function(obj){
      if(obj=="Already added") {
        cont = $("#a_fav_box").get(0);
        $("#a_fav_box").show();
        cont.innerHTML = 'Already added';
            return;
      }
      if(obj=="Success") {
        if (favouritesCounter == 0)  $("#fav_empty").hide();
            favouritesCounter++;
            cont = $("#a_fav_box").get(0);
            $("#a_fav_box").show();
            cont.innerHTML = 'Added successfully';

            var li_element = document.createElement('li');
            var a1_element = document.createElement('a');
            var a2_element = document.createElement('a');
            var img_element = document.createElement('img');
            var br_element = document.createElement('br');

            $(a1_element).attr('href', global_path+ 'song/'+songId+','+songName.replace(' ','-')+'.html');
            $(a1_element).css('float', 'left');
            $(a1_element).append(document.createTextNode(songName));

            $(img_element).attr('src', global_path +'/images/delete_tag.gif');
            $(img_element).css('float', 'right');

            $(a2_element).append(img_element);
            $(a2_element).css('cursor','pointer');
            $(a2_element).get(0).onclick = function(e) {  remFromFavs(songId) };

            $(li_element).attr('id','favouritesItem_'+songId);
            $(li_element).append(a1_element);
            $(li_element).append(a2_element);
            $(li_element).append(br_element);

            $(br_element).css('clear','both');

          $('#favouritesList').append(li_element);
            return;
        }
        if(obj=="error") {
          cont = $("#a_fav_box").get(0);
          $("#a_fav_box").show();
            cont.innerHTML = 'There was an error, please try again later';
            return;
        }
    });
}

function remFromFavs(songId){
    $.get( global_path+"ajax_remove_from_favourites.plain?lyric_id="+songId, null, function(obj){
        if(obj=="error") {
            alert('There was an error while removing try again later');
            return;
        }

        $('#favouritesList').get(0).removeChild($("#favouritesItem_"+songId).get(0));
        favouritesCounter--;
        if (favouritesCounter == 0) $("#fav_empty").show();
        try{
        if (currentSong == songId){
          $("#a_fav_box").hide();
          $("#a_fav_link").show();
        }
        }catch(e) {}
     })


}

function fetchNextAudioResults(page,mode,id){
  $("#audioNextIndicator").css("display","inline");
    $.get( global_path+"ajax_get_next_audio_results.html?page="+page+"&mode="+mode+"&id="+id, null, function(obj){
        if(obj=="error") {
            alert('There was an error while removing try again later');
            return;
        }

        $("#audioResultsArtist").css('height','190px');
        $("#audioResultsArtist").css('visibility','hidden');
        $("#audioResultsArtist").html(obj);
        $("#audioResultsArtist").css('visibility','visible');
        $("#audioNextIndicator").hide();
     })
}
function fetchNextVideoResults(page,mode,id){
  $("#videoNextIndicator").css("display","inline");
  $.get( global_path+"ajax_get_next_video_results.html?page="+page+"&mode="+mode+"&id="+id, null, function(obj){
        if(obj=="error") {
            alert('There was an error while removing try again later');
            return;
        }


        $("#videoResultsArtist").css('height','305px');
        $("#videoResultsArtist").css('visibility','hidden');
        $("#videoResultsArtist").html(obj);
        $("#videoResultsArtist").css('visibility','visible');
        $("#videoNextIndicator").hide();
     })
}

/** Lyrics scrolling **/
var leftToScroll = 0;
var barHeight = 300;
var indicatorHeight = 30;
var scrollChange  = 0;
var currentStep   = 0;
var currentScroll = 0;
var scrollStatus  = 0;
var currentBarTop = 0;
var barTopStep    = 0;
var lastIntTop    = -1;
var lastChange    = -1;
var currentAnim;
var firstEnter = true;
function makeScroller(){
    leftToScroll  = parseInt($("#lyrics_text").height())+20;
    var position = findPos( $("#lyrics_text").get(0) );
    if (leftToScroll < barHeight) {
        barHeight = Math.max(leftToScroll,200);
    }
    barTopStep = barHeight / leftToScroll;
	$("#scroller_background").css({'height':parseInt(barHeight+indicatorHeight)+'px','top':position[1]+currentScroll+80+'px','left':position[0]+$("#lyrics_text").width()+10+'px'}).show();
	$("#scroller_indicator").css( {'height':indicatorHeight+'px'}).show();
	$("#scroller_indicator").Draggable( {axis:'vertically',zIndex : 5001 , opacity:0.8,containment:'parent',ghosting:false,onDrag:scrollDrag} );

	bgPosition = findPos( $("#scroller_background").get(0) );
	$("#scroll_options_fld").css({'top':bgPosition[1]-65+'px','left':bgPosition[0]+'px' }).show();

	if (firstEnter){
		firstEnter = false;
		$("#scroll_pl_st").bind("click",function(e){
	        startScroll();return false;
	    }
	    );
		$(window).bind("resize" , function(e){
	         makeScroller();
	     } );
	}
}

function startScroll(){
    scrollStatus = 1;
    if (scrollChange == 0) scrollChange = 1;
    currentStep = 200/(scrollChange);
    currentAnim = setInterval('scrollStep()',currentStep);
    $("#scroll_pl_st").html('<img src="'+global_path+'/images/player_pause.gif" />');
    $("#scroll_pl_st").unbind("click");
    $("#scroll_pl_st").bind("click",function(e){
    	stopScroll();return false;
    }
    );
}
function stopScroll(){
    scrollStatus = 0;
    if (currentAnim != undefined) clearInterval(currentAnim);
    $("#scroll_pl_st").html('<img src="'+global_path+'/images/player_play.gif" />');
    $("#scroll_pl_st").unbind("click");
    $("#scroll_pl_st").bind("click",function(e){
        startScroll();return false;
    }
    );
}

function changeScroll(change){
    if (scrollChange < 1 && change == -1) return false;
    if(change == -1) scrollChange--;
    else if (lastChange!=-1){ scrollChange = lastChange; lastChange = -1; } else  if (scrollChange < 10)scrollChange++;
    if (scrollChange == 0) { scrollStatus=0;  return false; if (currentAnim != undefined) clearInterval(currentAnim);}
    $("#cur_speed").html(scrollChange); saveScrollSpeed();
    if (scrollStatus == 1)
    {
        currentStep = 200/(scrollChange);
        if (currentAnim != undefined) clearInterval(currentAnim);
        currentAnim = setInterval('scrollStep()',currentStep);
    }
    return false;
}

function scrollStep(){
  if (scrollStatus == 1){
    currentScroll++;
    var newTop = parseInt($("#lyrics_text").css('top')) - 1;
    $("#lyrics_text").css('top',newTop+'px');
    currentBarTop+=barTopStep;
    if (parseInt(currentBarTop) > lastIntTop){
        lastIntTop = parseInt(currentBarTop);
        $("#scroller_indicator").css('top',lastIntTop+'px');
    }
  }
  if(currentScroll>leftToScroll) {
        $("#lyrics_text").css('top','0px');
        $("#scroller_indicator").css('top','0px');
        currentBarTop = 0;
        lastIntTop    = 0;
        currentScroll = 0;
    }
}

var wasActive = false;
function overScroll(m_status){
	if (m_status == 0 && scrollStatus == 1)
	{
	   scrollStatus = m_status;
	   wasActive = true;
	}
	else if (m_status == 1 && wasActive){
	   scrollStatus = m_status;
       wasActive = false;
	}
}

function scrollDrag(x,y){
	var dy = parseInt( y / barTopStep );
	currentBarTop = y;
    lastIntTop    = y;
    currentScroll = dy;
    $("#lyrics_text").css('top', -dy + 'px');
}


//Sortable divs in right panel
var newBoxesOrder = '';

function makeBoxesSortable()
{
    $(document).ready(
    function () {
        $('#sort_div').Sortable(
            {
                accept :        'sortableitem',
                helperclass :   'sorthelper',
                activeclass :   'sortableactive',
                opacity:        0.8,
                revert:         true,
                fit      : false,
                tolerance:      'pointer',
                fx  : 200,
                axis : 'vertically',
                handle : '.boxes_draggable_handler',
                onStop : getCurrentBoxesOrder
            }
        )
    }
    );
}

var oldBoxesOrder = '1-2';
function getCurrentBoxesOrder()
{
    var sortable_ids = {'favourites_sortable':1,'lastwatched_sortable':2};
    var boxes_count = 2;
    var boxes_order = new Array();

    for(i=0; i<boxes_count; i++)
    {
        try
        {
            boxes_order[i] = sortable_ids[$('#sort_div').children().get(i).id];
        }
        catch(e) {}
    }
    newBoxesOrder =  boxes_order.join('-');
    if (newBoxesOrder != '1-2' && newBoxesOrder != '2-1') newBoxesOrder = '1-2';
    if (oldBoxesOrder != newBoxesOrder )
    {
        oldBoxesOrder = newBoxesOrder;
        SetCookie('lyrics_right_panel',newBoxesOrder,100,'/');
    }
}

function clearLastWatched(){
      $("#clwi").show();
      $.get( global_path+"clear_last_watched.plain", null, function(obj){
      $("#clwi").hide();
        if(obj=="error") {
            alert('There was an error, please try again later');
            return;
        }
        $("#lw_content").html('Last watched list is empty.');
     })
}

function showShortcutLinks() {
    var display = $("#shortcutmenu").css('display');
    if (display == 'none') {
        var left = getElementLeft('shortcut_link');
        var top = getElementTop('shortcut_link');
        var height = document.getElementById('shortcut_link').offsetHeight;
        top = top + height+10;
        $("#shortcutmenu").css({display: "block", top: top, left: left});
    } else if (display == 'block') {
        $("#shortcutmenu").css({display: 'none'});
    }
}

document.onclick = windowClick;

function windowClick() {
    var display = $("#shortcutmenu").css('display');
    if (display == 'block') {
        $("#shortcutmenu").css({display: 'none'});
    }
    try
    {
        var display = $("#mygroupsmenu").css('display');
        if (display == 'block') {
            $("#mygroupsmenu").css({display: 'none'});
        }
    }
    catch(e)
    {}
}
function getElementTop(Elem)
{
    if(document.getElementById) {
        var elem = document.getElementById(Elem);
    } else if (document.all) {
        var elem = document.all[Elem];
    }
    yPos = elem.offsetTop;
    tempEl = elem.offsetParent;
    while (tempEl != null) {
        yPos += tempEl.offsetTop;
        tempEl = tempEl.offsetParent;
    }
    return yPos;
}

function getElementLeft(Elem)
{

        var elem;
        if(document.getElementById) {
            var elem = document.getElementById(Elem);
        } else if (document.all){
            var elem = document.all[Elem];
        }
        xPos = elem.offsetLeft;
        tempEl = elem.offsetParent;
        while (tempEl != null) {
            xPos += tempEl.offsetLeft;
            tempEl = tempEl.offsetParent;
        }
        return xPos;
}

function blackout(){

    $("#blackout").css( {
                       'top' :'0px',
                         'left':'0px',
                         'height':$(document).height()+'px',
                         'width' :$(document).width()+'px'
                         }).show();
}
function centerElement(element){
  var halfHorizontal = parseInt(($(window).width() - $(element).width())/2);
    var halfVertical   = parseInt(($(window).height() - $(element).height())/2);
    $(element).css( {'top':halfVertical+'px','left':halfHorizontal+'px'} );
}

function showEmbedVideo(id){
  blackout();
  var thumbsList = '';
  $(".thumbVideo").each(
                         function(index){
                              var eid = $(this).attr('id').replace('th_','');
                              if (eid != id) {
                                var etitle = $(this).attr('title');
                                var src =  $(this).children().attr('src');
                                thumbsList+= '<img src="'+src+'" onmouseover="tt(this,1);" onmouseout="tt(this,0);" title="'+etitle+'" style="cursor:pointer;width:60px;height:50px;margin-left:5px;" onclick="showEmbedVideo(\''+eid+'\');return false;" />';
                              }
                         }
  );
    $("#videoOther").html(thumbsList);

  var code = $("#ve_"+id).get(0).value;
  code += '<br /><a href="http://video.filestube.com/video,'+id+'.html">See that video on http://video.filstube.com</a><br /><br />';
    $("#videoContainer").html(code);
    centerElement($("#videoWindow").get(0));
    $("#videoWindow").show();
    $(window).bind("resize" , function(e){
         blackout();
         centerElement($("#videoWindow").get(0));
     } );
}
function closeEmbedVideo(){
  $(window).unbind("resize");
    $("#blackout").hide();
    $("#videoWindow").hide();
}

function tt(element,action){
    if (action ==  1)
        $(element).css({'opacity':0.6,'-moz-opacity':0.6,'filter' : 'alpha(opacity=60)' })
    else
       $(element).css({'opacity':1.0,'-moz-opacity':1.0,'filter' : 'alpha(opacity=100)' })
}

function showEmbedVideoLyrics(id){
    var code = $("#ve_"+id).get(0).value;
    code = '<div id="videoBar">' +
    		'<img src="'+global_path+'/images/delete_tag.gif" onclick="closeEmbedVideoLyrics();return false;" style="cursor:pointer;float:right;" title="Close this window" onmouseover="tt(this,1);" onmouseout="tt(this,0);" />' +
    		'</div>'+code;

    code += '<br /><a style="margin:0px auto;" href="http://video.filestube.com/video,'+id+'.html">See that video on http://video.filstube.com</a><br /><br />';
    code += 'Share link : <input type="text" value="'+currentAddr+'?sv='+id+'" style="width:97%;" readonly="readonly"  onclick="this.select();" />';
    $("#embedVideoLyrics").html(code).show();
    window.location = window.location.href.replace("/#videoAnchor","").replace("#videoAnchor","")+"#videoAnchor";
    makeScroller();
}

function closeEmbedVideoLyrics(){
	$("#embedVideoLyrics").hide();
	makeScroller();
}