$(function(){

    $('.item .close').show();
    $('.item .order').show();

    var height = [];
    $('.item .container').each(function(i){
        height[i] = Math.ceil(($(this).height() + 10) / 135) * 135 - 10;
    });
    $.fn.minimize = function()
    {
        return this.find('.container').animate(
            {
                width:  '400px',
                height: '125px'
            },
            function(){
                $(this).parent('.item').addClass('min');
            }
        );
    };
    $.fn.maximize = function()
    {
        return this.each(function(){
            var i = $('.item').index(this);
            $(this).find('.container').animate({ width: '810px', height: height[i]+'px' });
            $(this).removeClass('min');
        });
    };

    $('.item').addClass('min');
    $('.item .container').width('400px')
                         .height('125px');

    $('.item').click(function(e){
        if ($(this).hasClass('min') && e.target.tagName != 'A') {
            $('.item:not(.min)').minimize();
            $(this).maximize();
        }
    });
    $('.item .close').click(function(e){
        $(this).parents('.item').minimize();
    });
    $('.item .order a').click(function(e){
        $('.layer').before('<div id="jquery-overlay"></div>');
        var arrPageSizes = ___getPageSize();
        $('#jquery-overlay').css({
          backgroundColor:	'#000',
          opacity:			0.8,
          width:				arrPageSizes[0],
          height:				arrPageSizes[1]
        }).fadeIn();
        var arrPageScroll = ___getPageScroll();
        $('.layer').css({
          top:	arrPageScroll[1] + (arrPageSizes[3] / 10),
          //left:	arrPageScroll[0]
        }).show();
        $('#jquery-overlay').click(function() {
          $('.layer').hide();
          $('#jquery-overlay').fadeOut(function() { $('#jquery-overlay').remove(); });
        });
        $(window).resize(function() {
          var arrPageSizes = ___getPageSize();
          $('#jquery-overlay').css({
            width:		arrPageSizes[0],
            height:		arrPageSizes[1]
          });
          var arrPageScroll = ___getPageScroll();
          $('.layer').css({
            top:	arrPageScroll[1] + (arrPageSizes[3] / 10),
            //left:	arrPageScroll[0]
          });
        });
        $('.layer .accept').removeClass('loader').addClass('disabled');
        $('.layer .calendar').show();
        $('.layer .form').show();
        $('.layer .message').hide();
        $('.layer .form .title span').text($(this).parent().prevAll('.preview').children('h1').text());
        selected = [];
        $('.layer .calendar').jCal({
            //selectedBG:     'rgb(0, 143, 214)',                         // default bgcolor for selected date cell
            //defaultBG:      'rgb(255, 255, 255)',                       // default bgcolor for unselected date cell
            dayOffset:      1,                                          // 0=week start with sunday, 1=week starts with monday
            forceWeek:      false,                                      // true=force selection at start of week, false=select days out from selected day
            dow:            ['Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб', 'Вс'],        // days of week - change this to reflect your dayOffset
            ml:             ['Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь'],
            dCheck:         function (day) {
                        return !in_array(day, reserved);
                    },
            callback:       function (day) {
                        if (in_array(day, selected)) {
                            $('.selectedDay').removeClass('selectedDay');
                            delete_from_array(day, selected);
                        } else {
                            selected.push(day);
                        }
                        for (i in selected) {
                            $('div[id*=d_' + (selected[i].getMonth() + 1) + '_' + selected[i].getDate() + '_' + selected[i].getFullYear() + ']').addClass('selectedDay');
                        }
                        check_accept();
                    }
        });
        e.preventDefault();
    });
    $('.item').each(function(){
        $('.gallery a', this).lightBox({
            // Configuration related to navigation
            fixedNavigation:		false,		// (boolean) Boolean that informs if the navigation (next and prev button) will be fixed or not in the interface.
            // Configuration related to images
            imageLoading:			'/theme/img/lightbox-ico-loading.gif',		// (string) Path and the name of the loading icon
            imageBtnPrev:			'/theme/img/lightbox-btn-prev.gif',			// (string) Path and the name of the prev button image
            imageBtnNext:			'/theme/img/lightbox-btn-next.gif',			// (string) Path and the name of the next button image
            imageBtnClose:			'/theme/img/lightbox-btn-close.gif',		// (string) Path and the name of the close btn
            imageBlank:				'/theme/img/lightbox-blank.gif',			// (string) Path and the name of a blank image (one pixel)
            // Configuration related to texts in caption. For example: Image 2 of 8. You can alter either "Image" and "of" texts.
            txtImage:				'Фото',	// (string) Specify text "Image"
            txtOf:					'из'		// (string) Specify text "of"
        });
    });

    $('.layer .close').click(function(){
      $('#jquery-overlay').fadeOut(function() { $('#jquery-overlay').remove(); });
        $('.layer').hide();
    });

    $('.layer input').change(check_accept);
    $('.layer .accept a').click(function(e){
      e.preventDefault();
      if ($(this).parent().hasClass('disabled')) {
        return;
      }
      $(this).parent().addClass('loader');
      var dates = [];
      for (i in selected) {
        dates.push('dates[]='+encodeURIComponent(selected[i]));
      }
      $.post(
          '/mail.html',
          'name='+encodeURIComponent($('.layer input.name').val())+
            '&phone='+encodeURIComponent($('.layer input.phone').val())+
            '&email='+encodeURIComponent($('.layer input.email').val())+
            '&address='+encodeURIComponent($('.layer .title span').text())+
            '&'+dates.join('&'),
          function(response){
            $('.layer .calendar').hide();
            $('.layer .form').hide();
            $('.layer .message').show();
          }
      );
    });

    var date = new Date();
    var reserved = [];
    // резервируем все прошедшие дни в этом месяце
    for (i = 1; i < date.getDate(); i++) {
        reserved.push(new Date((date.getMonth()+1)+'/'+i+'/'+date.getFullYear()));
    }
    var selected = [];
    function in_array(el, arr) {
        for (i in arr) {
            if (arr[i].toString() == el.toString()) {
                return true;
            }
        }
        return false;
    }
    function delete_from_array(el, arr) {
        for (i in arr) {
            if (arr[i].toString() == el.toString()) {
                delete arr[i];
                return true;
            }
        }
        return false;
    }
    function check_accept() {
        if ($('.layer input.name').val() &&
            $('.layer input.phone').val()) {

          $('.layer .accept').removeClass('disabled');
        } else {
          $('.layer .accept').addClass('disabled');
        }
    }

    function ___getPageSize() {
      var xScroll, yScroll;
      if (window.innerHeight && window.scrollMaxY) {
        xScroll = window.innerWidth + window.scrollMaxX;
        yScroll = window.innerHeight + window.scrollMaxY;
      } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
        xScroll = document.body.scrollWidth;
        yScroll = document.body.scrollHeight;
      } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
        xScroll = document.body.offsetWidth;
        yScroll = document.body.offsetHeight;
      }
      var windowWidth, windowHeight;
      if (self.innerHeight) {	// all except Explorer
        if(document.documentElement.clientWidth){
          windowWidth = document.documentElement.clientWidth;
        } else {
          windowWidth = self.innerWidth;
        }
        windowHeight = self.innerHeight;
      } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
        windowWidth = document.documentElement.clientWidth;
        windowHeight = document.documentElement.clientHeight;
      } else if (document.body) { // other Explorers
        windowWidth = document.body.clientWidth;
        windowHeight = document.body.clientHeight;
      }
      // for small pages with total height less then height of the viewport
      if(yScroll < windowHeight){
        pageHeight = windowHeight;
      } else {
        pageHeight = yScroll;
      }
      // for small pages with total width less then width of the viewport
      if(xScroll < windowWidth){
        pageWidth = xScroll;
      } else {
        pageWidth = windowWidth;
      }
      arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight);
      return arrayPageSize;
    };

  function ___getPageScroll() {
    var xScroll, yScroll;
    if (self.pageYOffset) {
      yScroll = self.pageYOffset;
      xScroll = self.pageXOffset;
    } else if (document.documentElement && document.documentElement.scrollTop) {	 // Explorer 6 Strict
      yScroll = document.documentElement.scrollTop;
      xScroll = document.documentElement.scrollLeft;
    } else if (document.body) {// all other Explorers
      yScroll = document.body.scrollTop;
      xScroll = document.body.scrollLeft;
    }
    arrayPageScroll = new Array(xScroll,yScroll);
    return arrayPageScroll;
  };

});