var rotated = false;

var timerPath;
var paper;
var sliderPause = false;
var slideTime = 10000;
var       startTime = 0;
var       pauseTime = 0;

var getCurrentTime = function() {var d = new Date();return d.getTime();}

var resumeSlider = function() {$('#sliderInner').cycle('resume');$('#sliderInner').cycle('next');sliderPause = false;}



function pauseSlider() {
         $('#sliderInner').cycle('pause');
         timerPath.stop();
         //timerPath.hide();
         sliderPause = true;
         pauseTime = getCurrentTime() - startTime;
      //console.log(pauseTime);
}

function unpauseSlider() {
         if(sliderPause) {
            setTimeout ( resumeSlider, slideTime-pauseTime);
            //timerPath.show();
            timerPath.animate({arc: [1, 1, 10]}, slideTime-pauseTime);
         }
}


function showMovie() {
   if(rotated) {
      document.getElementById('video').api("api_pause");
      

      $('#showreel').css('height','264px');
      $('.videoContent').css({top: -6000});
      if($.browser.msie && ($.browser.version == '8.0' || $.browser.version == '7.0')) {
         $('body').addClass("IEVideoFix");
         $('#mainContent .projectsListNavigation').show();
         //$('.videoContentUpper').show().css({rotate: '-60deg'});
         $('#rotateCurtain, #rotateCurtainTop').hide();
         if($.browser.version == '7.0') {
            $('#pageTop').css({"height":"237px"});
            $('#pageTop .sectionTitle').css({"margin-bottom":"14px"});
         }
         $('.pageContent').css({rotate: '0deg'}).attr('style',' ');
         if($( '#slider' ).length) {
            //$( '#slider' ).data( 'nivoslider' ).start();
            unpauseSlider();
         }
      } else {
         $('.pageContent').stop().animate({rotate: '0deg'},2000, function() {
            $('#rotateCurtain, #rotateCurtainTop').hide();
            $('.pageContent').css({rotate: '0deg'}).attr('style',' ');
            if($( '#slider' ).length) {
               //$( '#slider' ).data( 'nivoslider' ).start();
               unpauseSlider();
            }
         });
         $('.videoContentUpper').stop().show().animate({rotate: '-60deg'},2000);
      }
   } else {
      //442px -273px

      $('#showreel').css('height','41px');
      $('#rotateCurtain, #rotateCurtainTop').show();

      if($.browser.msie && ($.browser.version == '8.0' || $.browser.version == '7.0')) {
         $('body').removeClass("IEVideoFix");
         $('.pageContent').transform({origin: ['444px','-274px']});
         $('.pageContent').css({rotate: '60deg'});
         $('.videoContent').css({top: 0});
         //$('.videoContentUpper').css({rotate: '0deg'});
         if($.browser.version == '7.0') {
            $('#mainContent .projectsListNavigation').hide();
            $('#pageTop').css({"height":"275px"});
            $('#pageTop .sectionTitle').css({"margin-bottom":"49px"});
         }
         if($( '#slider' ).length) {
            pauseSlider();
         }
      } else {
         if($( '#slider' ).length) {
            pauseSlider();
         }
         $('.videoContentUpper').stop().animate({rotate: '0deg'},2000, function(){
            $('.videoContent').css({top: 0});
         });
         $('.pageContent').stop().animate({rotate: '60deg'},2000);
      }
      

   }
   rotated = !rotated;
   return false;
}



jQuery(function($) {
   Froogaloop.init();

   //$('a[href^=#]').smoothScroll({afterScroll: function() {$(this).blur();}});
   //$('html').smoothScroll();

   if(!$.browser.msie || ($.browser.msie && $.browser.version == '9.0')) {
      $('.pageContent').transform({origin: ['444px','-274px']});
      $('.videoContentUpper').transform({origin: ['444px', '-275px'], rotate: '0deg'}).animate({rotate: '-60deg'},0);
   }

   $('.videoContentInner').click(function(){
      if(rotated) {showMovie();}
      return false;
   })
   $('#showreel, .videoContentInner img, #rotateCurtain, #rotateCurtainTop, .IEcuratin').click(showMovie);

   if($('#slider-wrapper').length) {
        paper = Raphael("timer", 60, 60);
        paper.customAttributes.arc = function (value, total, R) {
            var alpha = 360 / total * value,
                a = (90 - alpha) * Math.PI / 180,
                x = 20 + R * Math.cos(a),
                y = 20 - R * Math.sin(a),
                //color = "hsb(".concat(Math.round(R) / 200, ",", value / total, ", .75)"),
                path;
            if (total == value) {
                path = [["M", 20, 20 - R], ["A", R, R, 0, 1, 1, 19.99, 20 - R]];
            } else {
                path = [["M", 20, 20 - R], ["A", R, R, 0, +(alpha > 180), 1, x, y]];
            }
            return {path: path, stroke:"#dcdcdc"};
        };
        timerPath = paper.path().attr({stroke: "#fff", "stroke-width": 2});

        function showTimer(time){
            timerPath.attr({arc: [0.01, 1, 10]});
            timerPath.animate({arc: [1, 1, 10]}, time);
        }



      $.fn.cycle.transitions.curtain = function($cont, $slides, opts) {
         var d = opts.direction || 'right';
         var w = $cont.css('overflow','Hidden').width();
         var h = $cont.height();
         opts.before.push(function(curr, next, opts) {
            $.fn.cycle.commonReset(curr,next,opts,true,true,true);
            //opts.animOut.width = 0;
            curr.style.zIndex = 5;
            next.style.zIndex = 7;
            opts.cssBefore.width = 0;
            opts.animIn.width = w;
            //next.style.width = "7px";
            //opts.animOut.left = w;
            //opts.cssBefore.left = w;
            //$('img', curr).animate({right: w}, 1000, 'linear', function(){$('img', curr).css({right: '0'});});
         });
         opts.animIn.left = 0;
         opts.animIn.top = 0;
         opts.cssBefore.top = 0;
         opts.cssBefore.left = 0;
      };

      $('#sliderInner').hover(pauseSlider, unpauseSlider);

      $('#sliderInner').cycle({
         fx: 'curtain',
         direction: 'right',
       	timeout: slideTime,
         easing: 'linear',
         next: '.nivo-nextNav',
         prev: '.nivo-prevNav',
         fastOnEvent: 1000,
         manualTrump: false,
         speed: 1000,
         before: function(curr, next, opts) {
            opts.animOut.opacity = 1;
            showTimer(slideTime);
            startTime = getCurrentTime();
         },
         onPrevNextEvent: function() {
            if(sliderPause) {
               $('#sliderInner').cycle('resume');
               timerPath.show();
               showTimer(slideTime);
               sliderPause = false;
            }
         }
      });
        /*$('#sliderInner').nivoSlider({
            effect:'slideInRight',
            controlNav: false,
            directionNavHide: false,
            animSpeed: 500,
            pauseTime: 2000,
            //directionNavHide: false,
            afterLoad: function(){
                showTimer(8000);
            },
            beforeChange: function(){
                showTimer(8000);
            },
            pauseStart: function(){
               timerPath.stop();
               timerPath.hide();
            },
            pauseEnd: function(){
               timerPath.show();
               timerPath.attr({arc: [0.01, 1, 10]});
               timerPath.animate({arc: [1, 1, 10]}, 8000);
            }
        });*/
   }

   var navigationClickable = true;

   /*$('#contactLink').click(function(){
      $('#projectsListCurtain').hide().fadeTo(speed, opacity, callback)
      return false;
   });*/

   $('.projectsListNavigation a').bind('click', function(e){
      e.preventDefault();
      $(this).blur();
      if(navigationClickable && !$(this).parent().hasClass('inactive')) {
         navigationClickable = false;
         $('#projectsListCurtain').fadeTo('slow',0.7);
         $('.projectsListIndicator').fadeTo('slow',1);
         $.get(this.href, function(data) {
            //setTimeout(function() {
               var newList = $(data);
               $('#projectsList').append(newList);
               var nextLink = $('#nextLink');
               var prevLink = $('#prevLink');
               if(nextLink.val() == "#") {
                  $('.projectsListNavigation .next').addClass('inactive');
               } else {
                  $('.projectsListNavigation .next').removeClass('inactive');
               }
               if(prevLink.val() == "#") {
                  $('.projectsListNavigation .prev').addClass('inactive');
               } else {
                  $('.projectsListNavigation .prev').removeClass('inactive');
               }
               $('.projectsListNavigation .next a').attr('href',nextLink.val());
               $('.projectsListNavigation .prev a').attr('href',prevLink.val());
               nextLink.remove();
               prevLink.remove();
               $('#projectsList ul').stop().animate({
                  left: (newList.hasClass('next') ? '-=542' : '+=542')
               }, 1000, function(){
                  $('#projectsListCurtain').fadeOut('fast');
                  $('.projectsListIndicator').fadeOut('fast');
                  navigationClickable = true;
                  $this = $(this);
                  if($this.hasClass('current')) {
                     $(this).remove();
                  } else {
                     $this.addClass('current');
                  }
               });
            //},1000);
         });
      }
   })

   $('body').height($('.pageContent').height());
});


$(document).ready(function() {
  function filterPath(string) {
  return string
    .replace(/^\//,'')
    .replace(/(index|default).[a-zA-Z]{3,4}$/,'')
    .replace(/\/$/,'');
  }
  var locationPath = filterPath(location.pathname);
  var scrollElem = scrollableElement('html', 'body');

  $('a[href^=#]').each(function() {
    var thisPath = filterPath(this.pathname) || locationPath;
    if (  locationPath == thisPath
            && (location.hostname == this.hostname || !this.hostname)
            && this.hash.replace(/#/,'') ) {
      var $target = $(this.hash), target = this.hash;

      if (target) {
        var targetOffset = $target.offset().top;
        $(this).click(function(event) {
          event.preventDefault();
          $(scrollElem).animate({scrollTop: targetOffset}, 400);
        });
      }
    }
  });

  // use the first element that is "scrollable"
  function scrollableElement(els) {
    for (var i = 0, argLength = arguments.length; i <argLength; i++) {
      var el = arguments[i],
          $scrollElement = $(el);
      if ($scrollElement.scrollTop()> 0) {
        return el;
      } else {
        $scrollElement.scrollTop(1);
        var isScrollable = $scrollElement.scrollTop()> 0;
        $scrollElement.scrollTop(0);
        if (isScrollable) {
          return el;
        }
      }
    }
    return [];
  }

});
