var count = 0;
var menu = 4;
var nowSlide;
var SecondLink;
var ServiceSlide;


$(function(){

  setTimeout(function() {
    $('#bg').hide(); // прячем загрузившийся бг
    $('#preloader').hide(); // убираем прелоадер
    $('#content').fadeIn(1, function(){ // показываем контент
      setTimeout(loadBaseMain, 500); // небольшая задержка перед итемами, чтоб не дергалось
    });
  }, 20); // сколько будет длиться окошко с загрузкой
  

  // загружаем основной контент
  function loadBaseMain () {
    
    $('#logo-main').animate({right: '60px'}, 300, function(){
      // проверяем на какой урл зашли калбэком--------------------V
      $('#contact-main').animate({right: '60px'}, 300, checkHref);
      $('#footer').animate({left: '60px'}, 300);
      
    });
  }
  
  // свистоперделка анимации для каждого пункта меню
  $("div.menu").each(function () {
    $(this).hover(function () {
      $(this).animate({marginLeft: "15px"}, 200);
    },function () {
      $(this).animate({marginLeft: "0"}, 200);
    });
  });

  $("div.prolog").each(function () {
    $(this).hover(function () {
      $(this).animate({marginLeft: "-15px"}, 200);
    },function () {
      $(this).animate({marginLeft: "0"}, 200);
    });
  });

  $("li.top-menu").each(function () {
    $(this).hover(function () {
      $(this).animate({marginRight: "10px"}, 200);
    },function () {
      $(this).animate({marginRight: "0px"}, 200);
    });
  });

  $("li.work-item").each(function () {
    $(this).hover(function () {
      $(this).animate({opacity: 1}, 200);
    },function () {
      $(this).animate({opacity: 0.5}, 200);
    });
  });

  $("li.work-item").each(function () {
    
    $("li#"+$(this).attr("id")).tooltip({
      track: true,
      delay: 50,
      fade: 250,
      showURL: false,
      extraClass: "works-tip",
      bodyHandler: function() {
        return $("div#"+$(this).attr("id")).html();
      }
    });

    $("a#"+$(this).attr("id")).fancybox({
      'titleShow'       : false,
      'transitionIn'    : 'elastic',
      'transitionOut'   : 'elastic',
      'titlePosition'   : 'over',
      'padding': 0,
      'title': '',
      'showCloseButton': false,
      'scrolling':  'auto'
    });
    
  });

  $('.send').click(function(){
    $('.message_ok').html('<img src="/images/ico/load_cont.gif" /> &nbsp Сообщение отправляется!');
    $.ajax({
      type: 'POST',
      url: '/mail.php',
      data: {
        name: $('#name').val(),
        email: $('#email').val(),
        message: $('#message').val()
      },
      success: function (data) {
        $('#name').val('');
        $('#email').val('');
        $('#message').val('');
        $('.message_ok').html('Ваше сообщение успешно отправленно!');
      }
    });

//    $.post('/mail.php', {
//      name: $('#name').val(),
//      email: $('#email').val(),
//      message: $('#message').val()
//    });
    
  })

  
});


// проверка линка
function checkHref()
{
  // смотрим где находимся

  var link = document.location.href.match('#[A-Za-z0-9]{1,}');

  checkSecondHref();

  // если зашли не с главной, проверяем че грузить
  if (link != null) { 
    switch(link.toString())
    {
    case '#about':
      loadAbout();
      break;
    case '#service':
      loadService();
      break;
    case '#works':
      loadWorks();
      break;
    case '#contacts':
      loadContacts();      
      break;
    case '#cost':
      loadCost();
      initInteractive();
      break;
    }
  // зашли с главной, грузим главную
  } else {
    loadMain();
  }

}

  function checkSecondHref()
  {
    var TempLink = document.location.href.match('#[A-Za-z0-9]{1,}/[A-Za-z0-9]{1,}');
    if (TempLink != null) {
      SecondLink = TempLink.toString().match('/[A-Za-z0-9]{1,}');
    }
  }

// загрузка следующего слайда
function loadNext(next) {
  switch(next)
  {
  case 'main':
    loadMain();
    break;
  case 'about':
    loadAbout();
    break;
  case 'service':
    loadService();
    break;
  case 'works':
    loadWorks();
    break;
  case 'contacts':
    loadContacts();
    break;
  case 'cost':
    loadCost();
    break;
  }
}

// закрытие текущего слайда, открытие нового
function closeThis(next) {
  switch(nowSlide)
  {
  case 'about':
    closeAbout(next);
    break;
  case 'service':
    closeService(next);
    break;
  case 'main':
    closeMain(next);
    break;
  case 'works':
    closeWorks(next);
    break;
  case 'contacts':
    closeContacts(next);
    break;
  case 'cost':
    closeCost(next);
    break;
  }
}


////////////////////////////////////////////////////////
////////////////////////////////////////////////////////

function loadMain() {

  
  $('#five').animate({left: '300px'}, 300, load);
  function load() {$('#four').animate({left: '300px'}, 300, load1);}
  function load1() {$('#three').animate({left: '300px'}, 300, load2);}
  function load2() {$('#two').animate({left: '300px'}, 300, load3);}
  function load3() {$('#one').animate({left: '300px'}, 300, load4);}
  function load4() {$('.prolog').animate({left: "80px"}, 200, load5);}
  function load5() {$("#bg").fadeIn('slow');}
  nowSlide = 'main';
  
}

function closeMain(next) {
  // Убираем фон
  $("#bg").fadeOut(500, function() {

    $('.prolog').animate({left: '-250px'}, 200, function(){
      // Проходимся по меню и приказываем им уйти
      $("div.menu").each(function () {
        //если оно ушло, прибавляем счетчик, как только он равен кол-ву меню, показываем следующий слайд
        $(this).animate({left: '-400px'}, 300, function(){
          count += 1;
          if (count == menu) {
            loadNext(next);
          }
        });
      });
    });
  });
}

////////////////////////////////////////////////////////
////////////////////////////////////////////////////////

function loadAbout(){

  $('.top-about').hide();

  $('#one-header').animate({marginLeft: '60px'}, 300, function(){
    $('#one-content').animate({marginLeft: '60px'}, 300);
  });

  $('#top-menu').animate({right: '60px'}, 300);    
  nowSlide = 'about';
}

function closeAbout(next) {
  count = 0;
  $('#top-menu').animate({right: '-200px'}, 300);
  $('#one-header').animate({marginLeft: '-300px'}, 300);
  $('#one-content').animate({marginLeft: '-1000px'}, 300, function() {
    $('.top-about').show();
    loadNext(next);
  });
//  $('#back').animate({right: '-200px'}, 300);
}

////////////////////////////////////////////////////////
////////////////////////////////////////////////////////

function loadService(){

  $('.top-service').hide();
  
  checkSecondHref();

  $("li.service-menu").each(function () {
    $(this).removeClass('active');
  });
  $("div#service-text").each(function () {
    $(this).animate({marginLeft: "-1000px"}, 200);
  });


  if (SecondLink != null)
  {
    switch(SecondLink.toString())
    {
    case '/one':
      $("li.sone").addClass('active');
      $(".service-one").animate({marginLeft: '0px'}, 200);
      ServiceSlide = 'one';
      break;
    case '/two':
      $("li.stwo").addClass('active');
      $(".service-two").animate({marginLeft: '0px'}, 200);
      ServiceSlide = 'two';
      break;
    case '/three':
      $("li.sthree").addClass('active');
      $(".service-three").animate({marginLeft: '0px'}, 200);
      ServiceSlide = 'three';
      break;
    case '/four':
      $("li.sfour").addClass('active');
      $(".service-four").animate({marginLeft: '0px'}, 200);
      ServiceSlide = 'four';
      break;
    }
  } else {
    $("li.sone").addClass('active');
    $(".service-one").animate({marginLeft: '0px'}, 200);
  }

  $('#two-header').animate({marginLeft: '60px'}, 300, function(){
    $('#two-content').animate({marginLeft: '60px'}, 300);
  });

  $('#top-menu').animate({right: '60px'}, 300);
  nowSlide = 'service';
}

function closeService(next) {
  count = 0;
  $('#top-menu').animate({right: '-200px'}, 300);
  $('#two-header').animate({marginLeft: '-300px'}, 300);
  $('#two-content').animate({marginLeft: '-1000px'}, 300, function() {
    $('.top-service').show();
    loadNext(next);
  });
}

function SlideService(next) {
  if (next != ServiceSlide)
  {
    $(".service-"+ServiceSlide).animate({marginLeft: "-1000px"}, 200, function(){
      $(".service-"+next).animate({marginLeft: "0px"}, 200);
    });
    $('li.s'+ServiceSlide).removeClass('active');
    $('li.s'+next).addClass('active');
    ServiceSlide = next;
  } else {
    return false;
  }

}

////////////////////////////////////////////////////////
////////////////////////////////////////////////////////

function loadWorks(){

  $('.top-works').hide();

  $('#three-header').animate({marginLeft: '60px'}, 300, function(){
    $('#three-content').animate({marginLeft: '60px'}, 300);
  });

  $('#logo-main').animate({right: '-200px'}, 300, function()
    {
      if (!$.browser.msie)
        {
          $('#canvaszone').html('<canvas id="canvas-logo"></canvas>');
          canvasDo();
          $('#canvas-logo').animate({right: '0'}, 500);
        }
      else
        {
          $('#logo-main').animate({right: '60px'}, 500);
        }
    });
  
 

  $('#top-menu').animate({right: '60px'}, 300);
  nowSlide = 'works';
}

function closeWorks(next) {
  count = 0;
  $('#canvas-logo').animate({right: '-600px'}, 800, function(){
    $("#canvas-logo").remove();
    $('#logo-main').animate({right: '60px'}, 500);
  });
  $('#top-menu').animate({right: '-200px'}, 300);
  $('#three-header').animate({marginLeft: '-300px'}, 300);
  $('#three-content').animate({marginLeft: '-1000px'}, 300, function() {
    $('.top-works').show();
    loadNext(next);
  });
}

////////////////////////////////////////////////////////
////////////////////////////////////////////////////////

function loadCost()
  {
    $('.top-cost').hide();
    $('#four-header').animate({marginLeft: '60px'}, 300, function()
      {
        $('#four-content').animate({marginLeft: '60px'}, 300);
      });
    if (!$.browser.msie)
      {
        setTimeout(function()
          {
            $('#top-menu').animate({right: '60px'}, 300);
            nowSlide = 'cost';
          }, 16000);
      }
    else
      {
        $('#top-menu').animate({right: '60px'}, 300);
        $("#text-cost").show();
      }
  }

function closeCost(next) {
  count = 0;
  $('#top-menu').animate({right: '-200px'}, 300);
  $('#four-header').animate({marginLeft: '-300px'}, 300);
  $('#four-content').animate({marginLeft: '-1000px'}, 300, function() {
    $('.top-cost').show();
    loadNext(next);
  });
}

////////////////////////////////////////////////////////
////////////////////////////////////////////////////////

function loadContacts(){

  $('.top-contacts').hide();

  $('#five-header').animate({marginLeft: '60px'}, 300, function(){
    $('#five-content').animate({marginLeft: '60px'}, 300);
  });

  $('#top-menu').animate({right: '60px'}, 300);
  nowSlide = 'contacts';
}

function closeContacts(next) {
  count = 0;
  $('#top-menu').animate({right: '-200px'}, 300);
  $('#five-header').animate({marginLeft: '-300px'}, 300);
  $('#five-content').animate({marginLeft: '-1000px'}, 300, function() {
    $('.top-contacts').show();
    loadNext(next);
  });
}


////////////////////////////////////////////////////////
////////////////////////////////////////////////////////

function canvasDo ()
{
    var canvas = $("#canvas-logo");
    var canvasHeight;
    var canvasWidth;
    var ctx;
    var dt = 0.1;
    var pointCollection;


  function getColor() {
    var hexs = ["#ed9d33","#d44d61","#4f7af2","#ef9a1e","#4976f3","#269230","#1f9e2c","#1c48dd","#2a56ea","#3355d8","#36b641","#2e5def","#d53747","#eb676f","#f9b125","#de3646","#2a59f0","#eb9c31","#c41731","#d82038","#5f8af8","#efa11e","#2e55e2","#4167e4","#0b991a","#4869e3","#3059e3","#10a11d","#cf4055","#cd4359","#2855ea","#ca273c","#2650e1","#4a7bf9","#3d65e7","#f47875","#f36764","#1d4eeb","#698bf1","#fac652","#ee5257","#cf2a3f","#5681f5","#4577f6","#f7b326","#2b58e8","#facb5e","#e02e3d","#f16d6f","#507bf2","#5683f7","#3158e2","#f0696c","#3769f6","#6084ef","#2a5cf4","#f4716e","#f8c247","#e74653","#ec4147","#4876f1","#ef5c5c","#2552ea","#4779f7","#4b78f1","#f4716e","#f4716e","#f4716e","#ed9d33","#3769f6",];
   // var hexs = ["#fff"];
    var hex = hexs[Math.floor(Math.random()*hexs.length)];
    return hex;
  }

    function initcanvas() {

        updateCanvasDimensions();

        var g = [
              new Point(2, 4, 1, 8, getColor()),   new Point(79, 4, 1, 8, getColor()),
              new Point(11, -2, 1, 4, getColor()), new Point(88, -2, 1, 4, getColor()),
              new Point(13, 4, 1, 3, getColor()),  new Point(90, 4, 1, 3, getColor()),
              new Point(21, 0, 1, 6, getColor()),  new Point(98, 0, 1, 6, getColor()),
              new Point(30, 0, 1, 7, getColor()),  new Point(107, 0, 1, 7, getColor()),
              new Point(41, 0, 1, 5, getColor()),  new Point(118, 0, 1, 5, getColor()),
              new Point(37, 9, 1, 4, getColor()),  new Point(114, 9, 1, 4, getColor()),
              new Point(48, 9, 1, 6, getColor()),  new Point(125, 9, 1, 6, getColor()),
              new Point(40, 15, 1, 3, getColor()), new Point(117, 15, 1, 3, getColor()),
              new Point(47, 24, 1, 9, getColor()), new Point(124, 24, 1, 9, getColor()),
              new Point(2, 15, 1, 4, getColor()),  new Point(79, 15, 1, 4, getColor()),
              new Point(-8, 14, 1, 6, getColor()), new Point(69, 14, 1, 6, getColor()),
              new Point(-8, 14, 1, 6, getColor()), new Point(69, 14, 1, 6, getColor()),
              new Point(-1, 24, 1, 6, getColor()), new Point(76, 24, 1, 6, getColor()),
              new Point(-11, 24, 1, 4, getColor()),new Point(66, 24, 1, 4, getColor()),
              new Point(-8, 33, 1, 5, getColor()), new Point(69, 33, 1, 5, getColor()),
              new Point(2, 33, 1, 4, getColor()),  new Point(79, 33, 1, 4, getColor()),
              new Point(-3, 41, 1, 3, getColor()), new Point(74, 41, 1, 3, getColor()),
              new Point(8, 43, 1, 7, getColor()),  new Point(85, 43, 1, 7, getColor()),
              new Point(18, 40, 1, 3, getColor()), new Point(95, 40, 1, 3, getColor()),
              new Point(18, 47, 1, 4, getColor()), new Point(95, 47, 1, 4, getColor()),
              new Point(28, 43, 1, 7, getColor()), new Point(105, 43, 1, 7, getColor()),
              new Point(38, 32, 1, 3, getColor()), new Point(115, 32, 1, 3, getColor()),
              new Point(34, 36, 1, 2, getColor()), new Point(111, 36, 1, 2, getColor()),
              new Point(41, 40, 1, 6, getColor()), new Point(118, 40, 1, 6, getColor()),
              new Point(51, 38, 1, 5, getColor()), new Point(128, 38, 1, 5, getColor()),
			  
			  
			  
              new Point(50, 50, 1, 7, getColor()), new Point(67, 1, 1, 7, getColor()),
              new Point(40, 50, 1, 4, getColor()), new Point(67, -12, 1, 8, getColor()),
              new Point(42, 57, 1, 3, getColor()), new Point(63, -22, 1, 4, getColor()),
              new Point(39, 62, 1, 2, getColor()), new Point(75, -7, 1, 3, getColor()),
              new Point(49, 65, 1, 8, getColor()), new Point(70, -27, 1, 6, getColor()),
              new Point(52, 78, 1, 5, getColor()), new Point(72, -31, 1, 5, getColor()),
              new Point(42, 76, 1, 4, getColor()), new Point(63, -32, 1, 4, getColor()),
              new Point(39, 69, 1, 2, getColor()), new Point(63, -36, 1, 2, getColor()),
    ];


    gLength = g.length;
        for (var i = 0; i < gLength; i++) {
            g[i].curPos.x = (canvasWidth - 195) + g[i].curPos.x;
            g[i].curPos.y = 60 + g[i].curPos.y;

            g[i].originalPos.x = (canvasWidth - 195) + g[i].originalPos.x;
            g[i].originalPos.y = 60 + g[i].originalPos.y;
        };

        pointCollection = new PointCollection();
        pointCollection.points = g;

        initEventListeners();
        timeout();

    }

    function initEventListeners() {
        $(window).bind('resize', updateCanvasDimensions).bind('mousemove', onMove);

        canvas.get(0).ontouchmove = function(e) {
            e.preventDefault();
            onTouchMove(e);
        };

        canvas.get(0).ontouchstart = function(e) {
            e.preventDefault();
        };
    }

    function updateCanvasDimensions() {
        canvas.attr({height: $(window).height(), width: $(window).width()});
        canvasWidth = canvas.width();
        canvasHeight = canvas.height();

        draw();
    }

    function onMove(e) {
        if (pointCollection)
            pointCollection.mousePos.set(e.pageX, e.pageY);
    }

    function onTouchMove(e) {
        if (pointCollection)
            pointCollection.mousePos.set(e.targetTouches[0].pageX, e.targetTouches[0].pageY);
    }

    function timeout() {
        draw();
        update();

        setTimeout(function() { timeout() }, 30);
    }

    function draw() {
        var tmpCanvas = canvas.get(0);

        if (tmpCanvas.getContext == null) {
            return;
        }

        ctx = tmpCanvas.getContext('2d');
        ctx.clearRect(0, 0, canvasWidth, canvasHeight);

        if (pointCollection)
            pointCollection.draw();
    }

    function update() {
        if (pointCollection)
            pointCollection.update();
    }

    function Vector(x, y, z) {
        this.x = x;
        this.y = y;
        this.z = z;

        this.addX = function(x) {
            this.x += x;
        };

        this.addY = function(y) {
            this.y += y;
        };

        this.addZ = function(z) {
            this.z += z;
        };

        this.set = function(x, y, z) {
            this.x = x;
            this.y = y;
            this.z = z;
        };
    }

    function PointCollection() {
        this.mousePos = new Vector(0, 0);
        this.points = new Array();

        this.newPoint = function(x, y, z) {
            var point = new Point(x, y, z);
            this.points.push(point);
            return point;
        };

        this.update = function() {
            var pointsLength = this.points.length;

            for (var i = 0; i < pointsLength; i++) {
                var point = this.points[i];

                if (point == null)
                    continue;

                var dx = this.mousePos.x - point.curPos.x;
                var dy = this.mousePos.y - point.curPos.y;
                var dd = (dx * dx) + (dy * dy);
                var d = Math.sqrt(dd);

                if (d < 150) {
                    point.targetPos.x = (this.mousePos.x < point.curPos.x) ? point.curPos.x - dx : point.curPos.x - dx;
                    point.targetPos.y = (this.mousePos.y < point.curPos.y) ? point.curPos.y - dy : point.curPos.y - dy;
                } else {
                    point.targetPos.x = point.originalPos.x;
                    point.targetPos.y = point.originalPos.y;
                }

                point.update();
            }
        };

        this.draw = function() {
            var pointsLength = this.points.length;
            for (var i = 0; i < pointsLength; i++) {
                var point = this.points[i];

                if (point == null)
                    continue;

                point.draw();
            }
        };
    }

    function Point(x, y, z, size, colour) {
        this.colour = colour;
        this.curPos = new Vector(x, y, z);
        this.friction = 0.8;
        this.originalPos = new Vector(x, y, z);
        this.radius = size;
        this.size = size;
        this.springStrength = 0.1;
        this.targetPos = new Vector(x, y, z);
        this.velocity = new Vector(0.0, 0.0, 0.0);

        this.update = function() {
            var dx = this.targetPos.x - this.curPos.x;
            var ax = dx * this.springStrength;
            this.velocity.x += ax;
            this.velocity.x *= this.friction;
            this.curPos.x += this.velocity.x;

            var dy = this.targetPos.y - this.curPos.y;
            var ay = dy * this.springStrength;
            this.velocity.y += ay;
            this.velocity.y *= this.friction;
            this.curPos.y += this.velocity.y;

            var dox = this.originalPos.x - this.curPos.x;
            var doy = this.originalPos.y - this.curPos.y;
            var dd = (dox * dox) + (doy * doy);
            var d = Math.sqrt(dd);

            this.targetPos.z = d/100 + 1;
            var dz = this.targetPos.z - this.curPos.z;
            var az = dz * this.springStrength;
            this.velocity.z += az;
            this.velocity.z *= this.friction;
            this.curPos.z += this.velocity.z;

            this.radius = this.size*this.curPos.z;
            if (this.radius < 1) this.radius = 1;
        };

        this.draw = function() {
            ctx.fillStyle = this.colour;
            ctx.beginPath();
            ctx.arc(this.curPos.x, this.curPos.y, this.radius, 0, Math.PI*2, true);
            ctx.fill();
        };
    }

    initcanvas();
}
