$(document).ready(function () {
  fixWidthContent();
  updateSpidStat();
  email();
  userContent();
  initControlPreview();
  initDLSlide();
  initNews();
  initNewsFilters();
  initAddress();
  initBookRef();
  initDic();
  initAddressMedPersonales();
  initEdit();
  initPriem();
  initFAQForm();
  initConf();
  initWarnings();
  $(window).resize(fixWidthContent);
});

function initConf() {
  var aann = $('#a-conf-ann');
  if (aann.length) {
    aann.click(function (ev) {
      ev.preventDefault();
      var $$ = $(this);
      if (!$$.hasClass('active')) {
        $('.a-conf').hide();
        $('#conf-ann').slideDown();
        $$.parent().children('a').removeClass('active');
        $$.addClass('active');
      }
    });

    $('#a-conf-program').click(function (ev) {
      ev.preventDefault();
      var $$ = $(this);
      if (!$$.hasClass('active')) {
        $('.a-conf').hide();
        $('#conf-program').slideDown();
        $$.parent().children('a').removeClass('active');
        $$.addClass('active');
      }
    });

    $('#a-conf-reports').click(function (ev) {
      ev.preventDefault();
      if (!$(this).hasClass('c-gray')) {
        var $$ = $(this);
        if (!$$.hasClass('active')) {
          $('.a-conf').hide();
          $('#conf-reports').slideDown();
          $$.parent().children('a').removeClass('active');
          $$.addClass('active');
        }
      }
    });

    var photos = $('#conf-photo-container img').css('cursor', 'pointer'),
        photoNum = $('#photo-num');
    if (photos.length) {

      function photosControl(ev) {
        ev.preventDefault();
        var $$ = $(this),
            ph = $('#conf-photo-container img:visible');
        if ($$.attr('id') == 'photos-prev') {
          ph = ph.slideUp().prev();
          if (!ph.length) {
            ph = $('#conf-photo-container img:last');
          }
          photoNum.text(ph.slideDown().attr('num'));
        } else {
          ph.click();
        }
      }

      photos.hide();
      $(photos.get(0)).show();
      photos.click(function () {
        var n = $(this).slideUp().next();
        if (!n.length) {
          n = $(photos.get(0));
        }
        photoNum.text(n.slideDown().attr('num'));
      });

      $('#photos-prev').click(photosControl);
      $('#photos-next').click(photosControl);
    }
  }
}


function initAddressMedPersonales() {
  var $$ = $('.med-personales');
  if ($$.length) {
    $$.click(function (ev) {
      ev.preventDefault();
      $(this).next('div').slideToggle();
    }).next('div').hide();
  }
}

function initWarnings() {
  var $$ = $('.notice');
  if ($$.length) {
    $$.hide().find('.block-int p:last-child').after($('<span class="right tserif">Перелистнуть</span><div class="clear"></div>'));
    $($$[0]).show();
    $$.find('span').click(function (ev) {
      var n = $(this).parents('.notice').slideUp().next('.notice');
      if (!n.length) {
        n = $($$[0]);
      }
      n.slideDown();
    });
  }
}

function initBookRef() {
  $('#book-ref a').click(function (ev) {
    ev.preventDefault();
    var $body = $('body'), top = $(window).scrollTop();
    $('<div id="popup-close">&nbsp;</div>').prependTo($body).css('top', top + 14).click(closePopup);
    $('<div id="popup" class="r"><img src="'+ $(this).attr('href') +'" alt="" /><a href="'+ $(this).attr('href') +'" class="ext" target="_blank">Открыть в отдельном окне</a></div>')
      .prependTo($body)
      .css('top', top + 30)
      .drag({fixDragToBorder : true})
      .css('backgroundColor', '#eee')
      .css('backgroundPosition', '0 0')
      .find('a.ext').click(closePopup);
    $('<div id="overlay-dark">&nbsp;</div>').prependTo($body).height($body.height()).click(closePopup);
  });
}

function initDic() {
  var $dic = $('.dictionary .h');
  if ($dic.length) {
    $('#dic-filter').keyup(function () {
      $('.dictionary :hidden').show();
      var v = $(this).val();
      if (v) {
        $.each($dic, function (i, x) {
          if ((x.tagName == 'TH' && $(x).text().toLowerCase().substring(0, 1) != v.toLowerCase().substring(0, 1))
           || (x.tagName == 'TD' && ($(x).text().toLowerCase().substring(0, 1) != v.toLowerCase().substring(0, 1) || $(x).text().toLowerCase().indexOf(v.toLowerCase()) == -1))) {
            $(x).parent('tr').hide();
          }
        });
      }
    });
  }
}

function closePopup() {
  $('#overlay-dark').remove();
  $('#popup').remove();
  $('#popup-close').remove();
}

function initPriem() {
  var $docs = $('.zapis-doctors .doc em');
  if ($docs.length) {
    $docs.click(function (ev) {
      ev.preventDefault();
      var $p = $(this).parent('.doc');
      if (!$p.hasClass('active')) {
        $('.doc.active').removeClass('active');
      }
      $p.toggleClass('active');
      if ($p.hasClass('active')) {
        initPriemBusyList($p);
      }
    });

    $('.zapis-doctors .doc .cancel span').click(function (ev) {
      ev.preventDefault();
      var $$ = $(this).parent(),
          $$$ = $$.parents('table');

      $$.html('<small>Обработка заявки...</small>');
      $.getJSON('/a/Spid_Priem/',
                {
                  'did' : $$$.attr('rel'),
                  'do' : 'cancel'
                },
                function (j) {
                  if (j.err) {
                    console.log(j.err);
                    $$.html('<small>Ошибка на сервере,<br />попробуйте позже</small>');
                  } else {
                    $$$.parent('.doc').remove();
                  }
                });
    });

    $('.zapis-doctors .doc .submit span').click(function (ev) {
      ev.preventDefault();
      var $$ = $(this).parent(),
          $$$ = $$.parents('table'),
          d = $$$.find('select[name=dateDoctor] option:selected'),
          t = $$$.find('select[name=timeDoctor]').val();

      $$$.find('select').attr('disabled', true);

      $$.html('<small>Обработка заявки...</small>');
      $.getJSON('/a/Spid_Priem/',
                {
                  'did' : $$$.attr('rel'),
                  'date' : d.val(),
                  'time' : t,
                  'do' : 'save'
                },
                function (j) {
                  if (j.err) {
                    console.log(j.err);
                    t = '<small>Ошибка на сервере,<br />попробуйте позже</small>';
                    if (j.err == 1) {
                      t = '<small>Извините!<br />Данное время приема уже занято</small>';
                    }
                  } else {
                    t = 'Мы ждём Вас<br />'+ d.text() +' в '+ t;
                  }
                  $$.html(t);
                });
    });

    $('.zapis-doctors .doc select[name=dateDoctor]').change(function () {
      var $p = $(this).parents('.doc');
      $p.find('select[name=timeDoctor]').val('');
      $p.find('.submit span').hide();
      initPriemBusyList($p);
    });

    $('.zapis-doctors .doc select[name=timeDoctor]').change(function () {
      var $$ = $(this),
          span = $$.parents('table').find('.submit span');
      if ($$.val()) {
        span.slideDown();
      } else {
        span.hide();
      }
    });
  }
}

function initPriemBusyList($doc) {
  if (priemBusyList) {
    var c = $doc.children('.zap').attr('rel'),
        dateVal = $doc.find('select[name=dateDoctor] option:selected').val();

    if (c && dateVal) {
      var ops = $doc.find('select[name=timeDoctor] option');
      ops.attr('disabled', false);
      c = 'c'+ c;
      dateVal = 'd'+ dateVal.replace('.', '_', 'g');
      if (priemBusyList.hasOwnProperty(c) && priemBusyList[c].hasOwnProperty(dateVal)) {
        var t = priemBusyList[c][dateVal].replace('_', ':').substring(1);
        $.each(ops, function () {
          op = $(this);
          if (op.val() == t) {
            op.attr('disabled', true);
          }
        });
      }
    }
  }
}

function fixWidthContent() {
  var $$ = $('.container');
  if ($$.length) {
    var w = $(window).width();
    // Контейнер
    if (w > 1280 || w < 1000) {
      w = w > 1280 ? 1280 : 1000;
      $('.container').width(w);
    } else {
      $('.container').width('100%');
    }
    // Основной контен
    $('.content').width(w - 570);
  }
}

function email() {
  $('.email').each(function () {
    $(this).text($(this).text().replace('[at]', '@'));
    $(this).attr('href', 'mailto:'+ $(this).text());
  });
}

function initAddress() {
  var k = $('#countryId');
  if (k) {
    k.change(function () {
      location.href = '/address/'+ $(this).val() +'/';
    });
    $('#cityId').change(function () {
      location.href = '/address/'+ k.val() +'/'+ $(this).val() +'/';
    });
  }
}

function initNewsFilters() {
  var ff = $('#filter-f');
  if (ff.length) {
    var url = location.href;
    url = url.indexOf('?') == -1 ? url+'?' : url.substring(0, url.indexOf('?')+1);

//    fy.change(function () {
//      location.href = url +'y='+ $(this).attr('value');
//    });
//
//    $('#filter-month').change(function () {
//      location.href = url +'m='+ $(this).attr('value');
//    });

    ff.change(function () {
      location.href = url + ($(this).attr('value') ? 'f='+ $(this).attr('value') : '');
    });
  }
}

var currentNews;
function initNews() {
  var ns = $('.news-item A');
  if (ns.length) {
    ns.click(function (ev) {
      ev.preventDefault();
      if (currentNews) {
        currentNews.slideUp().prev('.news-item').show();;
      }
      currentNews = $(this).parent('.news-item').hide().next('.news-item-full');
      currentNews.slideDown();
    });

    $('.news-item-full A').click(function (ev) {
      if ($(this).parent('.edit').length) {
        return true;
      }

      ev.preventDefault();
      currentNews = null;
      $(this).parent('.news-item-full').hide().prev('.news-item').show();
    });
  }
}

var dlSlidePrev;
function initDLSlide() {
  dlSlidePrev = $('dl.dl-slider dd.first');
  $('dl.dl-slider dt a').click(function (ev) {
    ev.preventDefault();
    var dt = $(this).parent('dt'),
        close = dt.hasClass('active');
    if (dlSlidePrev) {
      dlSlidePrev.slideToggle();
      dlSlidePrev.prev().removeClass('active');
      dlSlidePrev = null;
    }
    if (!close) {
      dlSlidePrev = dt.addClass('active').next();
      dlSlidePrev.slideToggle();
    }
  });
}

var cpSpace = 10, cpEasySpeed = 700;
function initControlPreview() {
  var list = $('.cp-list');
  if (list.length) {
    $('A.cp-prev').click(function (ev) {
      ev.preventDefault();
      slideControlPreview(1);
    });
    $('A.cp-next').click(function (ev) {
      ev.preventDefault();
      slideControlPreview(-1);
    });
    list.find('A').click(function (ev) {
      ev.preventDefault();
      initVideo(this);
    });
    initVideo(list.find('A:first'));
  }
}

function initVideo($a) {
  $a = $($a);
  var videoColor = 'be1e2d',
      attr = $a.attr('href').substring(1).split('|'),
      $$ = $('#video-player-container'),
      edit = $('.edit-video A');
      
  $$.children().remove();
  $$.flash({
    src : 'http://vimeo.com/moogaloop.swf',
    width : attr[2],
    height : attr[3],
    flashvars : {
      clip_id : attr[1],
      server : 'vimeo.com',
      show_title : 0,
      show_byline : 0,
      show_portrait : 0,
      color : videoColor,
      fullscreen : 1
    }
  });

  $$.prev('div.h').children('em').text($a.attr('title'));
  $a.addClass('active').siblings('A').removeClass('active');
  
  if (edit.length) {
    edit.attr('href', edit.attr('href').replace(/\d+$/g, attr[0]));
  }
}

function slideControlPreview(dir) {
  var speed = dir * ($('.cp-container').width() + cpSpace),
      list = $('.cp-list'),
      aList = $('.cp-list a');
      toLeft = list.position().left + speed,
      wList = -1 * aList.length * (aList.width() + cpSpace);

  if (dir == -1) {
    if ((toLeft + speed) < wList) {
      toLeft = toLeft == wList ? 0 : (wList - speed);
    }
  }

  if (toLeft > 0) {
    toLeft = (toLeft != Math.abs(speed)) ? 0 : (wList + speed);
  }

  list.animate({left: toLeft}, cpEasySpeed);
}



var spidStat;
function updateSpidStat() {
  spidStat = spidStat ? (1 + parseInt(spidStat)) : $('#spidStat').attr('rel');
  var s = $('#spidStat span');
  if (s.length) {
//    alert(s);
    var t = spidStat.toString(), z = '0000000';
    t = (t.length < 7 ? z.substr(0, 7-t.length) : '') + t;
    $.each(s, function (i, span) {
      $(span)
        .removeClass('n0 n1 n2 n3 n4 n5 n6 n7 n8 n9')
        .addClass('n'+ t.substring(i, i+1));
    });
    setTimeout(updateSpidStat, 12500);
  }
}

function initEdit() {
  $('.edit').mouseover(function () {
    $(this).prev('p').css('outline', '1px solid red');
  }).mouseout(function () {
    $(this).prev('p').css('outline', '0');
  });
}


function userContent() {
  initAuthForm2();
  initUCControls();
}

function initAuthForm2() {
  $('#auth-link').click(function (ev) {
    ev.preventDefault();
    $('#auth-form').slideToggle();
  });

  $('#auth-form form').submit(function (ev) {
    $('#auth-form .err').remove();
    var login = $(this).find('input[name=login]').val();
    if (!$(this).find('input[name=password]').val()) {
      $(this).prepend('<div class="err">Введите пароль</div>');
      ev.preventDefault();
    }
    if (!login || login.indexOf('@') == -1 || login.indexOf('.') == -1) {
      $(this).prepend('<div class="err">Введите корректно e-mail</div>');
      ev.preventDefault();
    }
  });
}

function initAuthForm() {
  var $a = $('#auth-in');
  if ($a.length) {
    var $f = $('#auth-in-form');
    $a.click(function (ev) {
      ev.preventDefault();
      $f.slideDown();
    });
    $('#auth-form-cancel').click(function (ev) {
      ev.preventDefault();
      $f.hide();
    });
    $f.submit(function () {
      var inp = $f.find('input[name=login]');
      if (!inp.val()) {
        alert('Введите email');
        inp.focus();
        return false;
      }
      inp = $f.find('input[name=password]');
      if (!inp.val()) {
        alert('Введите пароль');
        inp.focus();
        return false;
      }
      return true;
    });
  }
}

function initUCControls() {
  $('#user-content-add-entity').change(function (ev) {
    ev.preventDefault();
    var $$ = $(this), en = $$.val();
    if (en) {
      location.href = $$.attr('href') + en;
    }
  });
}

function initFAQForm() {
  $$ = $('#faqForm');
  if ($$) {
    $.each($$.find('.inp'), function (i, v) {
      v = $(v);
      v.attr('old', v.val()).focus(function () {
        v.val('').addClass('active');
      });
    });

    $$.submit(function () {
      var i = $$.find('input[name=name]');
      if (!i.val() || i.val() == i.attr('old')) {
        alert('Введите имя.');
        return false;
      }

      i = $$.find('textarea');
      if (!i.val() || i.val() == i.attr('old')) {
        alert('Введите вопрос.');
        return false;
      }
      
      return true;
    })
  }

  $.each($('.faq-edit'), function (i, a) {
    $(a).click(createFAQEditForm);
  });

  $.each($('.faq-reply'), function (i, a) {
    $(a).click(createFAQReplyForm);
  });

  $.each($('.faq-rem'), function (i, a) {
    $(a).click(function (ev) {
      if (confirm('Уверены, что хотите удалить?')) {
        return true;
      }
      ev.preventDefault();
    });
  });

  // SEARCH
  if ($('#faqSearch').length) {
    var val = $('#faqSearch .inp').val().toLowerCase(),
        i, l = val.length;
    if (val) {
      $.each($('.quest'), searchFAQ);
      $.each($('.resp'), searchFAQ);
    }

    function searchFAQ(i, p) {
      p = $(p);
      t = p.text().toLowerCase();
      i = t.indexOf(val)
      if (i != -1) {
        p.html(t.substring(0, i) +'<b>'+ val +'</b>'+ t.substring(i + l));
      }
    }
  }
}

function createFAQEditForm(ev) {
  ev.preventDefault();
  var $$ = $(ev.target),
      replyForm = '<form action="/" method="post">'
                + '<input type="hidden" name="action" value="Spid_FAQ" />'
                + '<input type="hidden" name="id" value="'+ $$.attr('rel') +'" />'
                + '<textarea name="question" class="f"></textarea>'
                + '<input type="submit" name="edit" value="Сохранить" />'
                + '</form>';

  if ($$.hasClass('active')) {
    $$.text('Редактировать').removeClass('active').prev('form').remove();
  } else {
    $$.text('Отменить').addClass('active').before($(replyForm))
      .prev('form').hide().slideDown()
      .children('textarea').val($$.parent().prev().text()).focus();
  }
}

function createFAQReplyForm(ev) {
  ev.preventDefault();
  var $$ = $(ev.target),
      replyForm = '<form action="/" method="post">'
                + '<input type="hidden" name="action" value="Spid_FAQ" />'
                + '<input type="hidden" name="id" value="'+ $$.attr('rel') +'" />'
                + '<textarea name="answer" class="f"></textarea>'
                + '<input type="submit" name="reply" value="Ответить" />'
                + '</form>';

  if ($$.hasClass('active')) {
    var label = $$.hasClass('faq-reply-edit') ? 'Редактировать ответ' : 'Ответить';
    $$.text(label).removeClass('active').next('form').remove();
  } else {
    var f = $$.text('Отменить').addClass('active').after($(replyForm))
              .next('form').hide().slideDown()
              .children('textarea').focus();
              
    if ($$.hasClass('faq-reply-edit')) {
      f.val($$.parent().prev().text());
    }
  }
}
