var count = 0;
var countonline = 0;
var files = '/components/chat/frontend.php';
var lastTime = 0;
var plsound = false;  

    function createCookie(name,value,days) {
      if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
      }
      else var expires = "";
      document.cookie = name+"="+value+expires+"; path=/";
    }


    function readCookie(name) {
      var nameEQ = name + "=";
      var ca = document.cookie.split(';');
      for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
      }
      return null;
    }


    function eraseCookie(name) {
      createCookie(name,"",-1);
    }
    

    function leavechat(){
      document.forms['exitform'].submit();
    }

    function PlaySound(filename){
     // $('#daddy-shoutbox-list').append('<BGSOUND SRC="' + filename + '" LOOP="1">');
      $('#daddy-shoutbox-list').append('<embed src="' + filename + '" autostart="true" hidden="true">');
    }

    function sound_toggle(){
      plsound = !plsound;
      imgsound = document.getElementById('soundimg');
      if(plsound){
        imgsound.src = '/components/chat/images/sound.gif';
      }else{
        imgsound.src = '/components/chat/images/nosound.gif';
      }
    }

        function prepare(response) {
          count++;
      listprefix= (response.display!='')?'arrive_':'';
      listprefix = (response.privat)?'private_':listprefix;
          var string = '<div class="'+listprefix+'shoutbox-list" id="list-'+count+'">'
              + '<span class="shoutbox-list-time">'+response.time+'</span>'
              + '<span class="'+listprefix+'shoutbox-list-nick" id="'+response.uid+'">'+response.nickname+'</span><small>'+response.to+'</small>'
              + '<span class="shoutbox-list-message"'+response.display+' style="color: '+response.bgcolor+';">'+response.message+'</span>'
              +'</div>';
        if (response.to.indexOf('<strong>')>-1 && plsound) PlaySound('/components/chat/sound/message.wav');
          return string;
        }
        
    function prepareonline(response) {
          countonline++;
          var string = '<div class="shoutbox-onlinelistlist" id="onlinelist-'+countonline+'" style="background-image: url(/components/chat/images/status/'+response.status+'.gif);">'
        + '<a href="/users/'+response.login+'" target="_blank" title="Профиль пользователя">'+response.usrimage+'</a>'
              + '<span class="shoutbox-online-nick" id="'+response.id+'">'+response.nickname+'</span>'
        + '<br><span class="shoutbox-online-status">'+response.status+'</span>'
        + '</div>';
          
          return string;
        }

        function success(response, status)  { 
          if(status == 'success') {
            lastTime = response.lasttime;
            $('#daddy-shoutbox-response').html('<img src="/components/chat/images/accept.png" />');
            $('#daddy-shoutbox-list').append(prepare(response));
            
            $('#list-'+count).fadeIn('slow');
      $('#list-'+count+" .private_shoutbox-list-nick").click(add_to);
      $('#list-'+count+" .shoutbox-list-nick").click(add_to);
      $('#list-'+count+" .shoutbox-list-time").click(function () {
          var saytext = $('input[@name=message]').attr('value');
          $('input[@name=message]').attr('value', saytext+' {'+$(this).text()+'}').focus();
        });
      //$('input[@name=message]').attr('value', '').focus();
      var wtop = $('#wrap').attr("scrollHeight");
      $('#wrap').attr({scrollTop:wtop});
            timeoutID = setTimeout(refresh, chatrefresh * 1000);
          }
        }
        


        function validate(formData, jqForm, options) {
          for (var i=0; i < formData.length; i++) { 
              if (!formData[i].value) {
                  alert('Please fill in all the fields'); 
                  //$('input[@name='+formData[i].name+']').css('background', 'red');
                  return false; 
              } 
          } 
      $('input[@name=message]').attr('value', '').focus();
      $('#tolist').empty();
      //$("#privat").attr("checked","");
          $('#daddy-shoutbox-response').html('<img src="/components/chat/images/loader.gif" />');
          clearTimeout(timeoutID);
        }

    function online_json(json){
      $('#daddy-online-list').html('');
            if(json.length) {
      countonline = 0;
              for(i=0; i < json.length; i++) {
                $('#daddy-online-list').append(prepareonline(json[i]));
        $('#onlinelist-'+countonline+" .shoutbox-online-nick").click(add_to);
              }
        var wtop = $('#wrap').attr("scrollHeight");
        $('#wrap').attr({scrollTop:wtop});
            }
    }

    function getonline() {
      $.ajax( { data: "action=online&uid="+user_id+"&auth="+userauth+"&toroom="+room} );
          //$.getJSON(files+'frontend.php?action=online&uid='+user_id, online_json);
          timeoutIDonline = setTimeout(getonline, onlinerefresh * 1000);
        }

    function add_to(){
      $('#tolist').append('<li><input type="checkbox" name="tolist[]" id="tolistchk" value="'
        +$(this).attr('id')+'" checked onClick="$(this).parent().remove();">'+$(this).text()+' </li>');
      $('input[@name=message]').focus();
    }

    function refresh_json(json){
        if(json.length) {
              for(i=0; i < json.length; i++) {
                $('#daddy-shoutbox-list').append(prepare(json[i]));
                $('#list-' + count).fadeIn(200);
        $('#list-'+count+" .shoutbox-list-nick").click(add_to);
        $('#list-'+count+" .private_shoutbox-list-nick").click(add_to);
        $('#list-'+count+" .arrive_shoutbox-list-nick i").click(add_to);
        $('#list-'+count+" .shoutbox-list-time").click(function () {
          var saytext = $('input[@name=message]').attr('value');
          $('input[@name=message]').attr('value', saytext+' {'+$(this).text()+'}').focus();
        });
              }
        plsound = true;
              var j = i-1;
              lastTime = json[j].lasttime;
        
        var wtop = $('#wrap').attr("scrollHeight");
        $('#wrap').attr({scrollTop:wtop});
            }
    }

    function success_json(json){
      switch(json.action) {
        case 'view':
        if(json.prtdata)
          refresh_json(json.prtdata);
          break;
        case 'online':
        if(json.prtdata)
          online_json(json.prtdata);
          break;
      }
    }

    function prepare_change_room(){
      lastTime = 0;
      plsound = false;
      room = $('#room').val();
      $('#daddy-shoutbox-list').empty();
      $('daddy-online-list').empty();
      clearTimeout(timeoutID);
      var roomid = $('#room').val();
      $('#fromroom').val(roomid);
      $('#exitroom').val(roomid);
      $('#toroom').val(roomid);
      timeoutID = setTimeout(refresh, 100);
      clearTimeout(timeoutIDonline);
      timeoutIDonline = setTimeout(getonline, 100);
    }

    function success_change_room(){
      $('input[@name=message]').focus();
      //alert('');
    }

        function refresh() {
      $.ajax( { data: "action=view&time="+lastTime+"&uid="+user_id+"&auth="+userauth+"&toroom="+room} );
          //$.getJSON(files+'frontend.php?action=view&time='+lastTime+'&userid='+user_id+'&auth='+userauth, refresh_json);          
          timeoutID = setTimeout(refresh, chatrefresh * 1000);      
        }

        function set_status(mystatus){
      $.ajax({ data: "action=status&status="+mystatus+"&uid="+user_id+"&auth="+userauth });
      //$.get(files+'frontend.php?status='+mystatus+'&uid='+user_id+'&userauth='+userauth);
      clearTimeout(timeoutIDonline);
      timeoutIDonline = setTimeout(getonline, 100);
    }
        // wait for the DOM to be loaded 
        $(document).ready(function() {
      $.ajaxSetup({
        cache:    false,
        type:     "POST",
        url:    files,
        dataType:   'json',
        success: success_json
      });     
            var options = { 
              dataType:       'json',
              beforeSubmit:   validate,
              success:        success
            }; 
            $('#daddy-shoutbox-form').ajaxForm(options);
      $('#changeroom').ajaxForm({beforeSubmit:prepare_change_room, success:success_change_room});
            timeoutID = setTimeout(refresh, 100);
      
      timeoutIDonline = setTimeout(getonline, 200);
      $('#chattoolbar ul li').hover(
              function() {
            $('#room').hide();
                  $(this).find('ul:first').fadeIn();
            $(this).addClass("chattoolbar_hilite");
            
              },
              function() {   
            $('#room').show();          
                  $(this).find('ul:first').fadeOut('fast');
            $(this).removeClass("chattoolbar_hilite");            
              }
          );
      $('#chattoolbar ul li ul .status').click( function(){
        set_status($(this).attr('id'));
        $('#mystatusimg').attr('src',$(this).find('img:first').attr('src'));
        $('#chattoolbar ul li ul').fadeOut('fast');
      });
      
      
      $('#chatcolor ul li').click( function(){
      var bgcolor = $(this).css('background-color');
        $('#chatcolor').find('div:first').css('background-color',bgcolor);
        $('#message').css('color',bgcolor);
        $('#inputcolor').val(bgcolor);
        createCookie('chatcolor',bgcolor,360);
        $('#chatcolor ul').fadeOut('fast');
      });
      var bgcolor = readCookie('chatcolor');
      if (bgcolor){
        $('#chatcolor').find('div:first').css('background-color',bgcolor);
        $('#message').css('color',bgcolor);
        $('#inputcolor').val(bgcolor);
      }
        });