//// асинхронная загрузка, поэтому не ждем документа
  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-22457588-1']);
  _gaq.push(['_setDomainName', 'designcapital.ru']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script');ga.type = 'text/javascript';ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0];s.parentNode.insertBefore(ga, s);
  })();


$(document).ready(function(){
    
// подгрузка блока заказа    
order_block = $('#order');
if (order_block.length == 1) {
    
jQuery.ajax({ 
      url: '/feedback/feedback.html',
      dataType: "html",
      success: function( data ) {
          
                order_block.html(data).wrap('<div id="order_wrap">');
                
                // клик по кнопке заказа
                $('#but_zakaz').click(function(){
                    $('#order_wrap').slideToggle(500);
                    var window_height = $(window).height(); 
                    var block_center = order_block.offset().top + 190
                    var scroll_to = block_center - (window_height/2);
                    jQuery('html, body').animate({scrollTop: scroll_to}, 500);
                    return false;
                })
                
                
                
                var ref = jQuery(location).attr('href');
                // субмит блока заказа
                $('#form_order').submit(function(e){

                        e.preventDefault();

                        $(this).ajaxSubmit({
                                beforeSubmit: validate,
                                dataType: 'json',
                                data: {ref: ref},
                                success: function(data){
                                    if (data.code == 1) {
                                        order_block.fadeOut(1200);
                                        log_order('Заявка отправлена.<br/>Мы позвоним вам в рабочее время.<br/> <a id="reset_order" href="">Сделать еще один заказ</a>', true)
                                        
                                        $('#reset_order').click(function(){
                                            order_block.fadeIn(500);
                                            $('#log_order').hide();
                                            return false;
                                        })
                                        
                                    }
                                    else
                                    {
                                        log_order('WTF!? У нас ошибка на сервере!<br/>Это значит, что заявка не дошла до нас. Пожалуйста, позвоните или напишите нам!', false)
                                    }
                                }
                        })
                        
                        function log_order(text, success){
                            order_block.before('<div id="log_order"></div>');
                            if (!success) 
                                $('#log_order').addClass('alarm_log');
                            $('#log_order').html(text).fadeIn(3000);
                        }
                        
                })
      }
  })
}


    
// всплывание картинок в большом размере
$('div.line_port img').each(function(){
    img = $(this);
//    img.wrap('<span/>');
    // копируем картинки
    img.clone().addClass('big').insertAfter(this);
    img.addClass('sm');
    
    // options
    var distance = 10;
    var time = 450;
    var hideDelay = 0;
    
    var hideDelayTimer = null;
    
    // tracker
    var beingShown = false;
    var shown = false;
    
    var trigger = img;
    var popup = img.next().css('opacity', 0);

    // set the mouseover and mouseout on both element
    $([trigger.get(0), popup.get(0)]).mouseover(function () {
      // stops the hide event if we move from the trigger to the popup element
      if (hideDelayTimer) clearTimeout(hideDelayTimer);

      // don't trigger the animation again if we're being shown, or already visible
      if (beingShown || shown) {
        return;
      } else {
        beingShown = true;

        // reset position of popup box
        popup.css({
          top: '-265px',
          left: '-95px',
          display: 'block' // brings the popup back in to view
        })

        // (we're using chaining on the popup) now animate it's opacity and position
        .animate({
          top: '-=' + distance + 'px',
          opacity: 1
//          width: '376px'
        }, time, 'swing', function() {
          // once the animation is complete, set the tracker variables
          beingShown = false;
          shown = true;
        });
      }
    }).mouseout(function () {
      // reset the timer if we get fired again - avoids double animations
      if (hideDelayTimer) clearTimeout(hideDelayTimer);
      
      // store the timer so that it can be cleared in the mouseover if required
      hideDelayTimer = setTimeout(function () {
        hideDelayTimer = null;
        popup.animate({
          top: '-=' + distance + 'px',
          opacity: 0
//          width: '346px'
        }, time, 'swing', function () {
          // once the animate is complete, set the tracker variables
          shown = false;
          // hide the popup entirely after the effect (opacity alone doesn't do the job)
          popup.css('display', 'none');
        });
      }, hideDelay);
    });
  });
    
// переключатьель видимости блоков
$('a.switch').click(function(){
    id = $(this).attr('data-block');
    $('#'+id).slideToggle();
    if ($(this).html() == 'Скрыть подробности')
        $(this).html('Показать подробности');
    else
        $(this).html('Скрыть подробности');
    return false;
})
    
// new hero fadin
$('#hero_arch, #hero_design').prepend('<div class="hover"></div>').each(function(){
  var $span = $('.hover', this).css('opacity', 1);
  $(this).hover(function (){
    $span.stop().fadeTo(1200, 0);
  }, function () {
    $span.stop().fadeTo(2000, 1);
  });
});

$('#port_mosaic').on('mouseenter', 'a', function(){
    $(this).next().stop().animate({"opacity": "1"},  500);
});
$('#port_mosaic').on('mouseleave', 'a', function(){
    $(this).next().stop().animate({"opacity": "0"},  500);
});


//$('table.port_mosaic a').hover(function(){
//    $(this).siblings('span').stop().animate({"opacity": "1"},  "3000");
//},
//function() {
//    $(this).siblings('span').animate({"opacity": "0"},  "3000");
//});

//    $(this).siblings('span').toggleClass('mosaic_hover');
//});

//$('div.galera').each(function(){
//    
//    var galera = $(this);
//    var delay = 3;
//    
//    // ищем максимальную высоту изображения и количество картинок
//    
//    var img = $("img:first", this); // Get my img elem
////    var pic_real_width;
//    var pic_real_height;
//    $("<img/>") // Make in memory copy of image to avoid css issues
//        .attr("src", $(img).attr("src"))
//        .load(function() {
//            
////            pic_real_width = this.width;   // Note: $(this).width() will not
//            pic_real_height = this.height; // work for in memory images.
//            
//            var gal_height = pic_real_height;
//            var gal_pic_count = 0;
//
////            console.log('gal_height',gal_height);
//
//            var free_vert_space = gal_pic_count * 5;
//            var tumb_height = (gal_height - free_vert_space) / gal_pic_count;
//
//
//            galera.append('<div style="height:'+gal_height+'px" class="gal_tablo"></div>');
//            galera.append('<div class="gal_tumbs"></div>');
////            galera.after('<div style="clear:left;height:20px"></div>');
//
//            var i=0;
//            $('a', galera).each(function(){
//                i++;
//                var ancor = $(this);
//                ancor.attr('gid',i).css('position','absolute').appendTo(galera.find("div.gal_tablo"))
//                            .hide()
//                            .find('img').clone().attr('gid',i)
//                            .appendTo( galera.find("div.gal_tumbs") )
//                            .show()
//                            .wrap('<span style="height:'+tumb_height+'px" />')
//                            ;
//                if (i == 1)
//                    ancor.show();
//            })
//            
//            $('div.gal_tumbs').on('img','click',function(){
//                var tumb = $(this);
//                var gid = tumb.attr('gid');
//
//                // снимаем выделение с тамбов и устанавливаем на текущий
//                $('div.gal_tumbs img', galera).each(function(){
//                    $(this).css('opacity','0.4');
//                });
//                
//                tumb.css('opacity','1');
//
//                // проверяем чтобы не кликалось по той же картинке
//                if (galera.find('a:visible').attr('gid') !== gid) {
//                    // скрываем одну и показываем другую одновременно (кроссдзолв)
//                    galera.find('a:visible').fadeOut(500);
//                    galera.find('a[gid="'+gid+'"]').fadeIn(500);
//                }
//
//
//            })
//        });    
//    
//})




$('div.portfolio').each(function(){
    
    // загрузка последовательная
    
    var portfolio = $(this);
    var colvo = $(this).find('img').size();
//    portfolio.prepend('<div id="wait" />');
    
//    portfolio.find(img).each(function())

    // высота изображения
    var first_img = $("img:first", this); // Get my img elem
    
    load_next( first_img );
    function load_next(img){
        var src = img.attr('data-src');
        img.attr('src',src).load(function(){
            var gid = $(this).attr('data-gid');
            $('#t'+gid).attr('src',src);
            var next_img = $(this).next('img');
            if ( next_img.length )
                load_next(next_img);
        })
    }
    
            gal_height = first_img.attr('data-h');
            tumb_width = first_img.attr('data-tw');
            
            portfolio.append('<div style="height:'+gal_height+'" class="gal_tablo"></div>');
            portfolio.append('<div class="gal_tumbs"></div>');
            var tablo = $('div.gal_tablo', portfolio); 
            var tumbs = $('div.gal_tumbs', portfolio); 
            if (colvo == 1) {
                tumbs.hide();
                portfolio.append('<div class="gal_tumbs_wraper"></div>');
                
            }

            var i=0;
            $('img', portfolio).each(function(){
                i++;
                var img = $(this);
                img.attr({'id':'b'+i, 'data-gid':i}).css('position','absolute').appendTo( tablo )
                            .clone()
                            .attr({'id':'t'+i,'data-gid':i, 'alt':''})
                            .css('position','static')
                            .appendTo( tumbs )
                            .show()
                            ;
                if (i == 1) {
                    img.show();
                    $('#t1').addClass('act');
                }
            })
            
            
            var fire_timer;
            tablo.on('click', 'img', function(){
                set_next_port_item( $(this) );
                auto_change_item();
            })
            
            tumbs.on('click', 'img', function(){
                set_port_item( $(this) );
                auto_change_item();
            })

            auto_change_item();
            
            function auto_change_item() {
                    // сохранияем смету в БД с задержкой
                    clearTimeout(fire_timer);
                    fire_timer = setTimeout(function(){set_next_port_item(false);}, 4000);
                return true;
            }
            function set_port_item(tumb){
                gid = tumb.attr('data-gid');
                
                // снимаем выделение с тамбов и устанавливаем на текущий
                tumbs.find('img.act').removeClass('act');
                tumb.addClass('act');

                // проверяем чтобы не кликалось по той же картинке
                var visible_img = tablo.find('img:visible');
                var next_gid = visible_img.attr('data-gid');
                if (next_gid != gid) {
                    // скрываем одну и показываем другую одновременно (кроссдзолв)
//                    visible_img.fadeOut(100);
//                    $('#b'+ gid).fadeIn(100);
                    visible_img.hide();
                    $('#b'+ gid).show();
                }
            }
                
            function set_next_port_item(click_image){
                if (click_image === false) {
                    var gid = tumbs.find('.act').attr('data-gid');
                    var click_image = $('#b'+gid);
                    auto_change_item();
                }
                else
                    var gid = click_image.attr('data-gid');
                    
                if ( parseInt(gid) < colvo ) 
                    next_gid = parseInt(gid)+1;
                else 
                    next_gid = 1;

                // снимаем выделение с тамбов и устанавливаем на текущий
                tumbs.find('img.act').removeClass('act');
                $('#t'+next_gid).addClass('act');
                // если есть следующая картинка (чтобы не мигало)
                if (next_gid != gid) {
                    // скрываем одну и показываем другую одновременно (кроссдзолв)
//                    click_image.fadeOut(100);
//                    $('#b'+ next_gid).fadeIn(100);
                    click_image.hide();
                    $('#b'+ next_gid).show();
                }
            }
            
})


$('div.hero').each(function(){
    
    var heros = $(this);
    var height = heros.attr('data-height');
    var dot;
    var gid = 1;
    
    // ищем максимальную высоту изображения и количество картинок
    
//    galera.append('<div style="height:'+gal_height+'px" class="gal_tablo"></div>');
//    galera.after('<div style="clear:left;height:20px"></div>');
    heros.append('<br/><div style="padding-top:'+height+'px" class="hero_dots"></div>');
    var dots = heros.find('div.hero_dots');

    var i=0;
    $('a', heros).each(function(){
        i++;
        var ancor = $(this);
        ancor
            .attr('data-gid',i)
            .css('position','absolute')
        if (i != 1) 
            ancor.hide()
                    
        if (i == 1) {
            dots.append('<a class="act" data-gid="'+i+'" href="">'+i+'</a>');
            dot = dots.find('a.act')
        }
        else
            dots.append('<a data-gid="'+i+'" href="">'+i+'</a>');
    })

    dots.delegate('a','click',function(){
        dot = $(this);
        gid = dot.attr('data-gid');
        
        //Reset Timer
        clearInterval(play); //Stop the rotation
        change_hero(); //Trigger rotation immediately
        return false;
    }) 
    
    
    //Paging  and Slider Function
    change_hero = function(){
        
        // снимаем выделение с точек и устанавливаем на текущий
        dots.find('a').removeClass('act');
        dot.addClass('act');

        // проверяем чтобы не кликалось по той же точке
        if (heros.children('a:visible').attr('data-gid') !== gid) {
            // скрываем одну и показываем другую одновременно (кроссдзолв)
            heros.children('a:visible').fadeOut(250);
            heros.children('a[data-gid="'+gid+'"]').fadeIn(250);
        }
    }; 

    //Rotation  and Timing Event
    rotate_hero = function(){
        play = setInterval(function(){ //Set timer - this will repeat itself every 7 seconds
            dot = dots.find('a.act').next(); //Move to the next paging
            if ( dot.length === 0) { //If paging reaches the end...
                dot = dots.find('a:first'); //go back to first
            }
            gid = dot.attr('data-gid');
            change_hero(); //Trigger the paging and slider function
        }, 3000); //Timer speed in milliseconds (7 seconds)
    };

    rotate_hero(); //Run function on launch
    
    //On Hover
    dots.find('a').hover(function() {
        clearInterval(play); //Stop the rotation
    }, function() {
        rotate_hero(); //Resume rotation timer
    });	

})

$('.spah').hide();


// всплывающие подсказки
//$(function () {
//  $('#home_folio li').each(function () {
//    // options
//    var distance = 2;
//    var time = 250;
//    var hideDelay = 300;
//
//    var hideDelayTimer = null;
//
//    // tracker
//    var beingShown = false;
//    var shown = false;
//    
//    var trigger = $('a', this);
//    var popup = $('div', this).css('opacity', 0);
//
//    // set the mouseover and mouseout on both element
//    $([trigger.get(0), popup.get(0)]).mouseover(function () {
//      // stops the hide event if we move from the trigger to the popup element
//      if (hideDelayTimer) clearTimeout(hideDelayTimer);
//
//      // don't trigger the animation again if we're being shown, or already visible
//      if (beingShown || shown) {
//        return;
//      } else {
//        beingShown = true;
//
//        // reset position of popup box
//        popup.css({
//          top: -100,
//          left: -10,
//          display: 'block' // brings the popup back in to view
//        })
//
//        // (we're using chaining on the popup) now animate it's opacity and position
//        .animate({
//          top: '-=' + distance + 'px',
//          opacity: 1
//        }, time, 'swing', function() {
//          // once the animation is complete, set the tracker variables
//          beingShown = false;
//          shown = true;
//        });
//      }
//    }).mouseout(function () {
//      // reset the timer if we get fired again - avoids double animations
//      if (hideDelayTimer) clearTimeout(hideDelayTimer);
//      
//      // store the timer so that it can be cleared in the mouseover if required
//      hideDelayTimer = setTimeout(function () {
//        hideDelayTimer = null;
//        popup.animate({
//          top: '-=' + distance + 'px',
//          opacity: 0
//        }, time, 'swing', function () {
//          // once the animate is complete, set the tracker variables
//          shown = false;
//          // hide the popup entirely after the effect (opacity alone doesn't do the job)
//          popup.css('display', 'none');
//        });
//      }, hideDelay);
//    });
//  });
//});

function hide_teasers() {

        var teasers = $('.teasers');
        var temp_width = 0;
	var teasers_w = 0;

        teasers.each(function() {

            teasers_w = $(this).width();
            temp_width = 0;

            $(this).find('.teaser').each(function() {
                temp_width = temp_width + $(this).width();
                if (temp_width > teasers_w - 10)
                    $(this).hide();
                else
                    $(this).show();
            });
        });
}

    if($('.teasers').size() > 0)
    {
            $('.teasers').children('img').wrap('<span class="teaser"/>');
            $('.teasers').children('a').wrap('<span class="teaser"/>');
            hide_teasers();
            $(window).resize(hide_teasers);
    }


   $('div.slide_open').hide().before('<br/>&nbsp; &nbsp; <a href="" class="slide_ancor">Раскрыть больше примеров</a>');

   if($('a.slide_ancor').size() > 0) {
       $('a.slide_ancor').live('click', function(){

           $(this).next('div').slideToggle();

           if ( $(this).html() == 'Раскрыть больше примеров' )
               {
                   $(this).html('Скрыть примеры')
               }
               else
               {
                   $(this).html('Раскрыть больше примеров')
               }
           return false;
       })
   }

//$(".iframe").fancybox({
//        'speedIn': 480,
//        'speedOut': 350,
//        'overlayOpacity': 0.4,
//        'width': 475,
//        'height': 485,
////        'transitionIn': 'elastic',
//        'overlayColor': '#000',
//        'hideOnContentClick': false,
//        'centerOnScroll': true
//});

$('#searchform').submit(function(){
     search_str = $('#query').val();
     if(search_str == '') return false;
     $('#searchform').attr('action', '/search.html?query='+encodeURIComponent(search_str) );
});

    //CTRL
    e2_ctrl_navi = function (event) {
      if (window.event) event = window.event
      var target = event.target ? event.target.tagName : event.srcElement ? event.srcElement.tagName : ''
      //if (/textarea|input/i.test (target)) return
      if (event.ctrlKey) {
        var link = null
        if (37 == event.keyCode) link = document.getElementById ('ctrl_prev')
        if (39 == event.keyCode) link = document.getElementById ('ctrl_next')
        if (link && link.href) location.href = link.href
      }
    }

    if (document.addEventListener) {
      document.addEventListener ('keyup', e2_ctrl_navi, false)
    }
    else
    if (document.attachEvent) {
      document.attachEvent ('onkeydown', e2_ctrl_navi)
    }


// тестирование форм плагин validity
// делаем новый тип вывода:
(function(){

    // We'll decide to install our custom output mode under the name 'custom':
    $.validity.outputs.custom = {

        // In this case, the start function will just reset the inputs:
        start:function(){

            $("input, textarea")
                .removeClass('fail');
            $('span.error').remove();    
//            $obj
//                .removeClass('fail');
                
        },

        end:function(results) {
            // If not valid and scrollTo is enabled, scroll the page to the first error.
//            if (!results.valid && $.validity.settings.scrollTo) {
//                return;
//                document.body.scrollTop = $("." + $.validity.outputs.tooltip.tooltipClass)
//                    .offset()
//                    .top;
//            }
        },

        // Our raise function will display the error and animate the text-box:
        raise:function($obj, msg){

            $obj.focus();
            // Make the JavaScript alert box with the message:
//            alert(msg);
            $obj
                .before('<span class="error">'+msg+'</span>').show(1500);

            // Animate the border of the text box:
            $obj
                .addClass('fail');

        },

        // Our aggregate raise will just raise the error on the last input:
        raiseAggregate:function($obj, msg){

            this.raise($($obj.get($obj.length - 1)), msg);

        }
    }
})();


function validate(){
    $.validity.start();
    
    var email = $('#liam');
    var phone = $('#phone');
    phone.assert( ! (email.val() == '' &&  phone.val() == '') , 'Укажите телефон или почту' );
    $("#name").require( 'Укажите имя' );
    $("#textar").require( 'Напишите что-нибудь' );
    $("#liam").match('email', 'Ошибка в адресе');
    
    var result = $.validity.end();
    
    return result.valid 
}

// Now enable the output mode we just installed.
$.validity.setup({outputMode:'custom'});


//$.validity.setup({outputMode:'modal'});



$('#callback_form').validity(function() {
    // Required and has to be a number.
    $("#call_phone").require('Укажите телефон');
});

});  //document ready
