/** Cache images **/
var mainNav = new Image(); mainNav.src = 'css/nav-hover.gif';
var loading = new Image(); loading.src = 'css/ajax-arrows.gif';
var favOff = new Image(); favOff.src = 'css/fav-off.gif';
var favOn = new Image(); favOn.src = 'css/fav-on.gif';

function fav(params) {
  $('favHart').src = loading.src;
  new XHR({method: 'get',
  onSuccess: function(req) {
    j = Json.evaluate(req);
    if (j) {
      if (j.favorite == 1) {
        $('favHart').src = favOn.src;
      } else {
        $('favHart').src = favOff.src;
      }
    }
  }
  }).send('/?action=BlockFavorite&'+ Object.toQueryString(params));
}

/** Searching **/
var startSearch;
var prevSearchWord = '';
function loadSearchResult(event) {
  var event = new Event(event);
  var elem = $('findField');
  var toElem = $('findResult');

  if (prevSearchWord == elem.value) {
    return;
  }
  if (startSearch) {
    clearTimeout(startSearch);
  }
  if (elem.value.length < 2) {
    searchClear();
    return;
  }

  prevSearchWord = elem.value;
  showSearchResult('<dl><dd id="findLoading"><span class="loading">Ищу "'+ prevSearchWord +'"...</span></dd></dl>');
  startSearch = setTimeout('searchResult(\''+ prevSearchWord +'\')', 700);
}

function searchClear() {
  if (startSearch) {
    clearTimeout(startSearch);
  }
  showSearchResult('-');
}

function searchResult(word) {
  var tagXHR = new XHR({method: 'get',
  onSuccess: function(req) {
    if (req) {
      showSearchResult(req);
    } else {
      searchClear();
    }
  }
  }).send('/?action=BlockFind&findWord='+ word);
  clearTimeout(startSearch);
}

function showSearchResult(html) {
  html = html.trim();
  $('findResult').innerHTML = html ? (html == '-' ? '' : html) : '<dl><dd>Ничего не найдено.</dd></dl>';
}

/** Tag control **/

function loadTTag(event) {
  loadRS(event, $('wrt_tags'), $('tagList'));
}

/** Loading RS **/
var tagSelected = -1;
function loadRS(event, elem, toElem) {
  var event = new Event(event);

  var li = false;
  if (toElem.innerHTML.trim()) {
    li = $ES('li', 'tagList');
  }
  // keys controll
  if (li && event.key == 'up') {
    tagSelected -= (tagSelected < 1) ? 0 : 1;
    li[tagSelected].addClass('white');
    if (tagSelected < li.length - 1) {
      li[tagSelected+1].removeClass('white');
    }
    return;
  }
  if (li && event.key == 'down') {
    tagSelected += (tagSelected < li.length - 1) ? 1 : 0;
    li[tagSelected].addClass('white');
    if (tagSelected > 0) {
      li[tagSelected-1].removeClass('white');
    }
    return;
  }
  if (li && event.key == 'enter') {
    addTTag(elem, li[tagSelected].getAttribute('value'));
    clearTTag(toElem);
    elem.focus();
    return;
  }

  var value = elem.value;

  var lastChar = value.substring(value.length - 1);
  if (lastChar == ',') {
    clearTTag(toElem);
    return true;
  }

  var p = value.lastIndexOf(',');
  var lastWord = p == -1 ? value : value.substring(p + 1);
  lastWord = lastWord.trim();
  if (lastWord.length < 2) {
    clearTTag(toElem);
    return true;
  }

  p = lastWord.lastIndexOf(':');
  var classWord;
  if (p != -1) {
    classWord = lastWord.substring(0,p);
    lastWord = lastWord.substring(p + 1);
    lastWord = lastWord.trim();
    if (lastWord.length < 2) {
      clearTTag(toElem);
      return true;
    }
  }

  var tagXHR = new XHR({method: 'get',
  onSuccess: function(req) {
    req = req.trim();
    if (req) {
      toElem.setHTML(req);
    } else {
      clearTTag(toElem);
    }
  }
  }).send('/?action=BlockFindTagList&findName='+ lastWord + (classWord ? '&className='+ classWord : ''));
}
function clearTTag(elem) {
  elem.setHTML('');
  tagSelected = -1;
}
function addTTag(elem, tagName) {
  var sep = '';
  var value = elem.value.trim();
  if (value.length > 0) {
    sep = ', ';
  }

  // find last word
  var p = value.lastIndexOf(',');
  if (p == -1) {
    value = tagName;
  } else {
    value = value.substring(0, p) +', '+ tagName;
  }

  elem.value = value + ', ';
}

/** User **/
function loadRelationship(param) {
  param = param ? '&'+ Object.toQueryString(param) : '';
  var url = '/?action=BlockUserRelationship'+ param +'&t='+ Math.random();
  new Ajax(url, {method: 'get', update:$('uRelationship')}).request();
}

/** Login form **/
var loginBlur;
function showLogin() {
  $('login').effect('margin-top',{duration: 1000,transition: Fx.Transitions.bounceOut}).custom(-60, 0);
  $('login-nav').effect('margin-top',{duration: 1000,transition: Fx.Transitions.bounceOut}).custom(0, -30);
  $('loginInput').focus();
  waitLogin();
}
function showLoginBack() {
  $('login').effect('margin-top',{duration: 500}).custom(0, -60);
  $('login-nav').effect('margin-top',{duration: 1000,transition: Fx.Transitions.bounceOut}).custom(-30, 0);
}
function hideLogin() { loginBlur=setTimeout('showLoginBack()', 1000) }
function waitLogin() { if (loginBlur) { clearTimeout(loginBlur); } }

/** Comment **/
var editorComment;
function addComment(cForm) {
  useCommentNicEdit();

  $('commentSubmit').disabled = true;
  $('commentSubmit').value = 'идёт обработка данных...';

  new Ajax('/',
  {onComplete: function(req) {
    $('divCommentForm').setHTML(req);
    $('commentCaptcha').src = '/?action=Captcha&h='+ Math.random();

    if ($('newComment').innerHTML.trim()) {
      empty = $('no-comments');
      if (empty != false && empty.style.display != 'none') {
        empty.style.display = 'none';
        $('new-comment-shadow').style.display = 'none';
      }
    }

    $('newCommentMark').setHTML($('newCommentMark').innerHTML + $('newComment').innerHTML);
    useCommentNicEdit();
  }, method: 'post', postBody: cForm.toQueryString()}).request();
}

/**
 * Toggle comment editor
 */
function useCommentNicEdit() {
  if (!editorComment) {
    editorComment = new nicEditor({maxHeight : 300, iconsPath : '/js/nicEditorIcons.gif', buttonList : ['bold','italic','underline', 'left', 'center', 'right', 'ol', 'ul', 'strikeThrough','subscript','superscript', 'removeformat', 'indent', 'outdent', 'image', 'upload', 'link', 'unlink']}).panelInstance('commentMsg');
  } else {
    editorComment.removeInstance('commentMsg');
    editorComment = null;
  }
}

/** Rate **/
var rateValueId = 0;
function onCompleteRateComment(req) {
  j = Json.evaluate(req);
  if (j.value == 1 || j.value == 2) {
    $(rateValueId).setHTML(j.value == 1 ? 'отстой' : 'круто');
  } else if (j.error == 2) {
    alert('Вы уже проголосовали');
  } else if (j.error == 1) {
    alert('Возникла ошибка обработки запроса.\nПопробуйте позже.');
  }
}
function onCompleteRateEventPre(req) {
  j = Json.evaluate(req);
  if (j.value == 1 || j.value == 2) {
    $(rateValueId).setHTML(j.value == 1 ? 'не пойду' : 'пойду');
    j.rate = j.rate ? j.rate : 0;
    $('sum-'+rateValueId).setHTML(j.rate);
  } else if (j.error == 2) {
    alert('Вы уже проголосовали');
  } else if (j.error == 1) {
    alert('Возникла ошибка обработки запроса.\nПопробуйте позже.');
  }
}
function onCompleteRateEventPost(req) {
  j = Json.evaluate(req);
  if (j.value == 1 || j.value == 2 || j.value == 3) {
    $(rateValueId).setHTML(j.value == 1 ? 'отстой' : (j.value == 2 ? 'круто' : 'не был'));
    $('sum-'+rateValueId).setHTML(j.rate);
  } else if (j.error == 2) {
    alert('Вы уже проголосовали');
  } else if (j.error == 1) {
    alert('Возникла ошибка обработки запроса.\nПопробуйте позже.');
  }
}
function onCompleteRateInfo(req) {
  j = Json.evaluate(req);
  if (j.value == 1 || j.value == 2) {
    $('rateValue').setHTML(j.value == 1 ? 'отстой' : 'круто');
    rs = $('rateSum');
    if (rs) {
      rs.setHTML(j.rate);
    }
  } else if (j.error == 2) {
    alert('Вы уже проголосовали');
  } else if (j.error == 1) {
    alert('Возникла ошибка обработки запроса.\nПопробуйте позже.');
  }
}

function rate(param, type) {
  rateValueId = type;
  $(type == 1 ? 'rateValue' : type).setHTML('обработка...');
  new Ajax('/?action=BlockRate&'+ Object.toQueryString(param),
  {method: 'get', onComplete: (type == 1 ? onCompleteRateInfo : onCompleteRateComment)}).request();
}
function rateEvent(param, id, type) {
  rateValueId = id;
  $(id).setHTML('обработка...');
  new Ajax('/?action=BlockRate&'+ Object.toQueryString(param),
  {method: 'get', onComplete: (type == 1 ? onCompleteRateEventPost : onCompleteRateEventPre)}).request();
}


/** UPLOAD **/
uploadFileStart = function(fileObj) {
  var divProgress = '<div class="uploadProgress" id="prg'+ fileObj.name +'">0%</div>';
  var divName = '<div class="uploadName">'+ fileObj.name +' '+ (fileObj.size/1024).toInt() +'Kb</div>';
  $("uploadProcess").setHTML($("uploadProcess").innerHTML + divName + divProgress);
}
uploadProgress = function(fileObj, bytesLoaded) {
  var value = Math.ceil((bytesLoaded / fileObj.size) * 100) +'%';
  $('prg'+ fileObj.name).style.width = value;
  $('prg'+ fileObj.name).setHTML(value);
}
var pepIdx = 0;
var pepSize = 6;
uploadFileComplete = function(fileObj) {
  var preXHR = new XHR({method: 'get',
  onSuccess: function(req) {
    j = Json.evaluate(req);
    if (j && j.path) {
      var non = $('uploadPreviewNone');
      if (non) {
        non.style.display = 'none';
      }
      $('uploadPreview').style.display = '';
      var im = $ES('img','uploadPreview')[pepIdx];
      im.src = j.path;
      pepIdx++;
      pepIdx = pepIdx == pepSize ? 0 : pepIdx;
    }
  }
  }).send('/?action=BlockUploadPhotoPath&fn='+ fileObj.name);
}
uploadFileCancelled = uploadQueueComplete = uploadCancel = function() {
  $('uploadBTN').value = 'залить фотки';
}
uploadError = function(error,errorFile,errorCode) {
  var msg = '';
  switch(error) {
  case -10:
    msg = "HTTP ошибка, сервер вернул код ошибки: " + errorCode;
    break;
  case -20:
    msg = "Обработчик не найден.";
    break;
  case -30:
    msg = "Ошибка доступа к файлу. I/O ошибка.";
    break;
  case -40:
    msg = "Ошибка безопасности.";
    break;
  case -50:
    msg = 'Размер файла слишком велик.\nДопустим размер не более 400 Kb.\nПопробуйте уменьшить размеры фото.';
    break;
  }
  
  alert("Возникли проблемы с файлом "+ errorFile.name +":\n\n" + msg);
}

var tagMenu = {
  init: function(){
    this.idList = '';
    this.url = '/?action='+this.action;
    
    this.parseLocation();
    this.updateLinks();
    this.updatePagination();
    this.updateOrder();
  },

  parseLocation: function() {
    var l = location.href, pos = bbPos = l.indexOf(this.paramName), val;
    if (pos != -1) {
      val = l.substring(pos+11);
      pos = val.indexOf('&');
      val = val.substring(0, (pos == -1 ? val.length : pos));
      this.idList = val;
    }
  },
  
  updateLinks: function() {
    var notAll = false;
    $ES('li', this.targetList).each(function(li) {
      var id = li.getAttribute('id');
      if (id && this.idList.test(li.getAttribute('id'))) {
        notAll = true;
        li.addClass('active');
      }
      
      if (!id && notAll) {
        li.removeClass('active');
      }
      
      li.onclick = function() {
        if (li.hasClass('active')) {
          li.removeClass('active');
        } else {
          li.addClass('active');
          
          if (li.hasClass('nav-all')) {
            this.clearLI(li.getParent().getChildren());
          }
        }
        
        this.page = '';
        this.updateAll(li.getParent());
      }.bind(this);
    }, this);
  },
  
  clearLI: function(list) {
    list.each(function(li) {
      if (!li.hasClass('nav-all') && li.hasClass('active')) {
        li.removeClass('active');
      }
    });
  },
  
  updateAll: function(ul) {
    var idList = '', all = 0, ch = ul.getChildren();
    ch.each(function(li) {
        if (li.hasClass('active') && !li.hasClass('nav-all')) {
          idList += (idList != '' ? '-' : '') + li.getAttribute('id');
          all++;
        }
        
        if (li.hasClass('nav-all')) {
          if (all == ch.length - 1 || !all) {
            idList = '';
            li.addClass('active');
            
            if (all == ch.length - 1) {
              this.clearLI(ch);
            }
          } else {
            li.removeClass('active');
          }
        }
      }, this);
    
    this.updateList(idList);
  },
  
  updateList: function(idList) {
    idList = idList ? '&'+ this.paramName +'='+idList : '';
    page = this.page ? '&page='+ this.page : '';
    order = this.order ? '&'+ this.orderParam +'='+ this.order : '';
    new XHR({method: 'get',
        onSuccess: function (req) {
          $(this.targetBlock).innerHTML = req;
          this.updatePagination();
        }.bind(this)
      }).send(this.url + idList + page + order);
  },
  
  updatePagination: function() {
    $$('.pagination a').each(function(a) {
      a.onclick = function() {
        l = a.href;
        this.page = l.substring(l.indexOf('page=')+ 5).toInt();
        this.updateAll($(this.targetList));
        location.hash = this.targetList;
        return false;
      }.bind(this)
    }.bind(this));
  },
  
  updateOrder: function() {
    $$('#'+ this.orderList +' span').each(function(span) {
      span.onclick = function() {
        if (this.order == span.getAttribute('order')) {
          return false;
        }
        $$('#'+ this.orderList +' span').each(function(s){
          if (!s.hasClass('non-active')) {
            s.addClass('non-active');
          }
        });
        span.removeClass('non-active');
        this.order = span.getAttribute('order');
        this.updateAll($(this.targetList));
        return false;
      }.bind(this)
    }.bind(this));
  }
};

// Calendar tuning
function tuneCalendar(cal) {
  cal.setMonthNames('Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь');
  cal.setDayHeaders('Вс', 'Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб');
  cal.setWeekStartDay(1);
  cal.setTodayText('сегодня');
}

// block More
function setBlockMore() {
  $$('.more-link').each(function(a) {
    if (!a.getAttribute('activated')) {
      a.onclick =  function() {
        a.getParent().getParent().style.display = 'none';
        bMore = $E('.b-g-rheader', a.getParent().getParent().getParent());
        bMore.style.overflow = 'visible';
        bMore.style.height = '100%';
        return false;
      }
      a.setAttribute('activated', true);
    }
  });
}

var tracksURL;
function getTracks(id) {
  if (id) {
    tracksURL= '/?action=GrabMP3&CDReview='+ id +'&j='+$('jjj').value;
    $('progressBarTracks').innerHTML = 'Идёт скачивание... <img src="/css/ajax-spinner.gif" alt="..." />';
  }
  
  if (tracksURL) {
    new XHR({
      method: 'get',
      onSuccess: successTracks
    }).send(tracksURL);
  } else {
    $('progressBarTracks').innerHTML = 'Ошибка! URL не задан';
  }
}

function successTracks(req) {
    var j = Json.evaluate(req),
        status = parseInt(j.status),
        st = ''+j.status,
        msg = 'Статус '+ status;

    if (status < 0) {
      msg = 'Ошибка '+ status;
    } else {
      var skip = 0, rs = 0, all = 0;
      if (status > 2000) {
        skip = parseInt(st.substring(0, st.length - 4));
        rs = st.substring(st.length - 3);
      } else {
        rs = st.substring(1);
      }
      rs = rs[0] == '0' ? rs.substring(1) : rs;
      rs = rs[0] == '0' ? rs.substring(1) : rs;
      rs = parseInt(rs);
      all = skip + rs;
      
      msg = (all >= j.tracks
              ? 'Готово!'
              : 'Скачено: '+ parseInt(all/j.tracks*100) +'% ('+ all +' из '+ j.tracks +') ... <img src="/css/ajax-spinner.gif" alt="..." />');
    }
    
    $('progressBarTracks').innerHTML = msg;
    if (all < j.tracks) {
      getTracks();
    }
}


