$(document).ready(function(){

    if ($.browser.msie) {
        $('#best').hover(
            function(){
                $(this).children('ul').show();
            },
            function(){
                $(this).children('ul').hide();
            }
        );
    }
    $("#nav-upload, #add").hover(
      function() {
        $("a#add").stop().animate({bottom: 32},166);
      },
      function() {
        $("a#add").stop().animate({bottom: 18},166);
      }
    );

    setPlayerButtonsBehav();

    $('.clearField')
        .focus(function(){
            if ($(this).css('font-style') == 'italic')
            {
                clearFieldVar = $(this).val();
                $(this).css({'color': 'black',
                             'font-style' : 'normal'})
                       .val('');

            }
        })
        .blur(function(){
            if ($(this).val() == '')
            {
                $(this).css({'color': '#CCC',
                             'font-style' : 'italic'})
                       .val(clearFieldVar);

            }
        });

    playinarow = $.cookie('playinarow');

    if ($.browser.opera) {
        // loading twice
        // first via html object to have playing in row on the next page
        // second via swfobject to have no troubles with first click
        var flashvars = {"uid":"uppodplayer","st":"http://mp3ritm.com/styles/audio.txt?1","file":"http://mp3ritm.com/styles/audio.txt?1"};
        var params = {allowScriptAccess:"always",wmode:"transparent"}; var attributes={id:"uppodplayer"};
        new swfobject.embedSWF("http://mp3ritm.com/swf/uppod.swf", "uppodplayer", "635", "27", "9.0.0", false, flashvars, params,attributes);
    }

    $uppodplayerWrapper = $('#uppodplayerWrapper');

    document.onkeydown = NavigateThrough;
    function NavigateThrough (event) {
        if (!document.getElementById) return;
        if (window.event) event = window.event;
        if (event.ctrlKey) {
            switch (event.keyCode ? event.keyCode : event.which ? event.which : null)
            {
                case 0x25:
                    if (typeof curPage != 'undefined' && toAir) {
                        if (curPage != 1) {
                            location.href = 'page' + (curPage - 1);
                        }
                    }
                break;
                case 0x27:
                    if (typeof curPage != 'undefined') {
                        if (curPage + 1 <= pagesNum) {
                            if (typeof toAir != 'undefined' && toAir) {
                                location.href = '/air/page' + (curPage + 1);
                            } else {
                                location.href = 'page' + (curPage + 1);
                            }
                        }
                    }
                break;
            }
        }
    }

});

function setPlayerButtonsBehav() {
    $(".playerControlsPlay").hover(
      function() {
        var thisPlayerId = $(this).attr('id').slice(5);
            if (playing == 'playing' && curPlayerId == thisPlayerId) {
          $(this).css('background','url(/imgs/play.png) -31px 26px');
        } else {
          $(this).css('background','url(/imgs/play.png) 0 26px');
        }
      },
      function() {
        var thisPlayerId = $(this).attr('id').slice(5);
            if (playing == 'playing' && curPlayerId == thisPlayerId) {
          $(this).css('background','url(/imgs/play.png) -31px 0');
        } else {
          $(this).css('background','url(/imgs/play.png) 0 0');
        }
      }
    )
    .click(function(){
       startPlaying($(this).attr('id').slice(5), 'click');
    });

    $('.votePlus, .votePlusCover, .voteMinus, .voteMinusCover').click(function(){
        $(this).parent('.voteControls').css('visibility', 'hidden');
    });
    $('.ieVotePlus, .ieVoteMinus').click(function(){
        $(this).parent('.ieVoting').css('visibility', 'hidden');
    });

    $('#closeAirMessage').click(function(){
         $.cookie('closeAirMessage', true, {'expires':100000});
         $('.message').hide();
    });
    $('#closeAddMessage').click(function(){
         $.cookie('closeAddMessage', true, {'expires':100000});
         $('.message').hide();
    });

    $('li.chartControl a').click(function(){
        $(this).parents('.tabs').children('li').removeClass('active');
        $(this).parent('.chartControl').addClass('active');
    });

    $('#checkInARow').change(function(){
        if (!$(this).attr('checked')) {
            $.cookie('playinarow', false, {path: '/', expires: 100000});
            playinarow = 'false';
            $('#checkInARow').removeAttr('checked');
        } else {
            $.cookie('playinarow', true, {path: '/', expires: 100000});
            $('#checkInARow').attr('checked', 'checked');
            playinarow = 'true';
        }
    });
    $('#playInARow span').click(function(){
        if (!$('#checkInARow').attr('checked')) {
            $.cookie('playinarow', true, {path: '/', expires: 100000});
            $('#checkInARow').attr('checked', 'checked');
            playinarow = 'true';
        } else {
            $.cookie('playinarow', false, {path: '/', expires: 100000});
            playinarow = 'false';
            $('#checkInARow').removeAttr('checked');
        }
    });
}

function startPlaying(playerId, startedBy) {   
   $cPlayId = $('#cPlay'+playerId);
   if (playing == 'paused' || playing == 'stopped')
   {     
     if (startedBy == 'click') {
        $cPlayId.css('background','url(/imgs/play.png) -31px 26px');
     } else {
        $cPlayId.css('background','url(/imgs/play.png) -31px 0px');
     }     
     if (playerId != curPlayerId) {           
           playing = 'playing';
           $uppodplayerWrapper.css({
              width: 1,
              height: 1
           });
           initPlayer(playerId, startedBy);
           if (curPlayerId) {
              $("#cPlay"+curPlayerId).css('background','url(/imgs/play.png) 0 0');
           }
           curPlayerId = playerId;
     } else {           
           playing = 'playing';
           uppodSend('uppodplayer', 'play');
     }     
   }
   else if (playing == 'playing')
   {     
     if (playerId == curPlayerId) {
          uppodSend('uppodplayer','pause');
          $cPlayId.css('background','url(/imgs/play.png) 0 26px');
          playing = 'paused';
      } else {
          $cPlayId.css('background','url(/imgs/play.png) -31px 26px');
          playing = 'playing';
          $uppodplayerWrapper.css({
              width: 1,
              height: 1
          });          
          initPlayer(playerId, startedBy);
          if (curPlayerId) {
            $("#cPlay"+curPlayerId).css('background','url(/imgs/play.png) 0 0');
          }
          curPlayerId = playerId;
      }
   }
    if (startedBy == 'auto' && typeof previousIds != 'undefined') {
      for (var k in previousIds) {
        if (previousIds[k] == currentIds[curPlayerId-1]) {
            startPlaying(curPlayerId+1, 'auto');
            break;
        }
      }
    }
}

function initPlayer(thisPlayerId, startedBy)
{
    $uppodplayerWrapper.css({
       top: $('#playerContainer'+thisPlayerId).offset().top - 1,
       left: $('#playerContainer'+thisPlayerId).offset().left
    });

    if (typeof document.getElementById('uppodplayer').sendToUppod == 'function') {
      uppodSend('uppodplayer','file:'+audiofiles[thisPlayerId-1]);
      setTimeout('showPlayer()', 150);
    } else {
      setTimeout('initPlayer('+thisPlayerId+', "'+startedBy+'")', 300);
    }
}
function showPlayer() {
  $uppodplayerWrapper.css({
    width: 635,
    height: 27
  });
}

function showVideo(id) {

   $uppodplayerWrapper.css({
      width: 1,
      height: 1
   });

    if (curVideoId) {
        $('#video'+curVideoId).html('');
    }
    if (id == curVideoId) { // toggle
        curVideoId = 0;
    } else {
        $('#video'+id).html(videoCodes[id-1]);
        curVideoId = id;
    }

    if (curPlayerId) {
        $uppodplayerWrapper.css({
           top: $('#playerContainer'+curPlayerId).offset().top - 1,
           left: $('#playerContainer'+curPlayerId).offset().left
        });
        showPlayer();
    }
}

function openChart(period) {
    $('#chartDay, #chartWeek, #chartMonth, #chartYear').hide();
    $('#chart'+period).show();
    $.cookie('period', period, {'expires':100000});
}

function sendFormTo(adr) {
    var form = $('#reg');
    form.attr('action', adr);
    form.submit();
}

function vote(userUploadedId, mp3Id, value) {
    $.ajax({
        type: "POST",
        url: "/mp3/vote/",
        data: 'value=' + value + '&mp3Id=' + mp3Id + '&userUploadedId=' + userUploadedId,
        success: function (data) {
            var vote = eval('(' + data + ')');
            var voteArea = $('#voteA'+vote.mp3Id);
            var rating = parseInt(voteArea.text()) + vote.value;
            voteArea.text(rating);
            if (rating > 0) {
                voteArea.css('color', '#ABCF19');
            } else {
                voteArea.css('color', '#999999');
            }
        }
    });
}

function showOpenIDForm() {
    $('#standartForm').hide();
    $('#openIDForm').show();
    $('#changingForms').html('<a href="javascript:showStandartForm()" class="pseudoLink">Стандартная</a>');
}
function showStandartForm() {
    $('#openIDForm').hide();
    $('#standartForm').show();
    $('#changingForms').html('<img src="/imgs/openid.gif" alt="" /> <a href="javascript:showOpenIDForm()" class="pseudoLink">OpenID</a>');
}
function showOpenIDFormFull() {
    $('#standartFormFull').hide();
    $('#openIDFormFull').show();
    $('#changingFormsFull').html('<a href="javascript:showStandartFormFull()" class="pseudoLink">Стандартная</a>');
}
function showStandartFormFull() {
    $('#openIDFormFull').hide();
    $('#standartFormFull').show();
    $('#changingFormsFull').html('<img src="/imgs/openid.gif" alt="" /> <a href="javascript:showOpenIDFormFull()" class="pseudoLink">OpenID</a>');
}

function nextPageList() {
    previousIds = [];
    for (var n in currentIds) {
        if (n != 'indexOf') {
            previousIds[n] = currentIds[n];
        }
    }
    $.ajax({
        url: (toAir ? '/index/' : '') + "page" + (curPage+1),
        success: function (data) {
            if (data.length) {
                $('#primary-content').html(data);
                setPlayerButtonsBehav();
                scroll(0,0);
                startPlaying(1, 'auto');
            }
        }
    });
}

/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') {
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString();
        }
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

