var deviceIphone = "iphone";
var deviceIpod = "ipod";
var deviceIpad = "ipad";
var deviceS60 = "series60";
var deviceSymbian = "symbian";
var deviceAndroid = "android";

var uagent = navigator.userAgent.toLowerCase();

function detectMobile() {
    if (uagent.search(deviceIphone) > -1)
        return true;
    else if (uagent.search(deviceIpad) > -1)
        return true;
    else if (uagent.search(deviceIpod) > -1)
        return true;
    else if (uagent.search(deviceS60) > -1)
        return true;
    else if (uagent.search(deviceSymbian) > -1)
        return true;
    else if (uagent.search(deviceAndroid) > -1)
        return true;
    else return false;
};

// need to edit jQuery carousel to allow circular plugin to work without gaps

(function($) {    

    // static constructs
    $.tools = $.tools || {version: '1.2.3a'};

    $.tools.scrollable = {

        conf: {
            circular: false,
            clonedClass: 'cloned',
            disabledClass: 'disabled',
            easing: 'swing',
            initialIndex: 0,
            item: null,
            items: '.items',
            keyboard: true,
            mousewheel: false,
            next: '.next',
            prev: '.prev',
            speed: 400,
            vertical: false,
            wheelSpeed: 0,
            itemCount: 4
        }
    };

    // get hidden element's width or height even though it's hidden
    function dim(el, key) {
        var v = parseInt(el.css(key), 10);
        if (v) { return v; }
        var s = el[0].currentStyle;
        return s && s.width && parseInt(s.width, 10);
    }

    function find(root, query) {
        var el = $(query);
        return el.length < 2 ? el : root.parent().find(query);
    }

    var current;

    // constructor
    function Scrollable(root, conf) {

        // current instance
        var self = this,
             fire = root.add(self),
             itemWrap = root.children(),
             index = 0,
             vertical = conf.vertical;

        if (!current) { current = self; }
        if (itemWrap.length > 1) { itemWrap = $(conf.items, root); }//WHY WHY WHY???

        // methods
        $.extend(self, {

            getConf: function() {
                return conf;
            },

            getIndex: function() {
                return index;
            },

            getSize: function() {
                return self.getItems().size();
            },

            getNaviButtons: function() {
                return prev.add(next);
            },

            getRoot: function() {
                return root;
            },

            getItemWrap: function() {
                return itemWrap;
            },

            getItems: function() {
                return itemWrap.children(conf.item).not("." + conf.clonedClass);
            },

            move: function(offset, time) {
        if(conf.circular || (index+offset >= 0) && (index+offset <= self.getSize() - conf.itemCount)){
          return self.seekTo(index + offset, time);
        }else{
          return self;
        }
      },

            next: function(time) {
                return self.move(1, time);
            },

            prev: function(time) {
                return self.move(-1, time);
            },

            begin: function(time) {
                return self.seekTo(0, time);
            },

            end: function(time) {
                return self.seekTo(self.getSize() - conf.itemCount +1, time);
            },

            focus: function() {
                current = self;
                return self;
            },

            addItem: function(item) {
                item = $(item);

                if (!conf.circular)  {
                    itemWrap.append(item);
                } else {
                    $(".cloned:last").before(item);
                    $(".cloned:first").replaceWith(item.clone().addClass(conf.clonedClass));
                }

                fire.trigger("onAddItem", [item]);
                return self;
            },


            /* all seeking functions depend on this */
            seekTo: function(i, time, fn) {

                // avoid seeking from end clone to the beginning
                if (conf.circular && i === 0 && index == -1 && time !== 0) { return self; }

                // check that index is sane
                if (!conf.circular && i < 0 || i > self.getSize() || i < -1) { return self; }

                var item = i;

                if (i.jquery) {
                    i = self.getItems().index(i);
                } else {
                    item = self.getItems().eq(i);
                }

                // onBeforeSeek
                var e = $.Event("onBeforeSeek");
                if (!fn) {
                    fire.trigger(e, [i, time]);
                    if (e.isDefaultPrevented() || !item.length) { return self; }
                }

                var props = vertical ? {top: -item.position().top} : {left: -item.position().left};

                index = i;
                current = self;
                if (time === undefined) { time = conf.speed; }

                itemWrap.animate(props, time, conf.easing, fn || function() {
                    fire.trigger("onSeek", [i]);
                });

                return self;
            }

        });

        // callbacks
        $.each(['onBeforeSeek', 'onSeek', 'onAddItem'], function(i, name) {

            // configuration
            if ($.isFunction(conf[name])) {
                $(self).bind(name, conf[name]);
            }

            self[name] = function(fn) {
                $(self).bind(name, fn);
                return self;
            };
        });

        // circular loop
        if (conf.circular) {
      var cloned1 = null,
          cloned2 = null;

      cloned2 = self.getItems().slice(0,(conf.itemCount)).clone().addClass(conf.clonedClass).appendTo(itemWrap);//first [4] at the end
      cloned1 = self.getItems().slice(-1).clone().addClass(conf.clonedClass).prependTo(itemWrap);//last [4] at the start

            self.onBeforeSeek(function(e, i, time) {

                if (e.isDefaultPrevented()) { return; }

                /*
                    1. animate to the clone without event triggering
                    2. seek to correct position with 0 speed
                */
                if (i == -1) {
                    self.seekTo(cloned1.eq(-1), time, function()  {
                        self.seekTo(self.getSize()-1,0,function(){});
                    });
                    return e.preventDefault();

                } else if (i == self.getSize()) {
                    self.seekTo(cloned2.eq(0), time, function()  {
                        self.begin(0);
                    });
                }

            });

            // seek over the cloned item(s)
            self.seekTo(0, 0);
        }

        // next/prev buttons
        var prev = find(root, conf.prev).click(function() { self.prev(); }),
              next = find(root, conf.next).click(function() { self.next(); });

        if (!conf.circular && self.getSize() > 1) {

            self.onBeforeSeek(function(e, i) {
                window.setTimeout(function() {
                                                        if (!e.isDefaultPrevented()) {
                                                            if(self.getSize() <= conf.itemCount){
                                                                prev.addClass(conf.disabledClass);
                                                                next.addClass(conf.disabledClass);
                                                            }else if(!conf.circular){
                                                              prev.toggleClass(conf.disabledClass, i <= 0);
                                                              next.toggleClass(conf.disabledClass, i >= self.getSize() - conf.itemCount);
                                                            }
                                                        }
                                                    }, 1);
            });
        }

        // mousewheel support
        if (conf.mousewheel && $.fn.mousewheel) {
            root.mousewheel(function(e, delta)  {
                if (conf.mousewheel) {
                    self.move(delta < 0 ? 1 : -1, conf.wheelSpeed || 50);
                    return false;
                }
            });
        }

        if (conf.keyboard)  {
            $(document).bind("keydown.scrollable", function(evt) {
                // skip certain conditions
                if (!conf.keyboard || evt.altKey || evt.ctrlKey || $(evt.target).is(":input")) { return; }
                // does this instance have focus?
                if (conf.keyboard != 'static' && current != self) { return; }

                var key = evt.keyCode;
                if (vertical && (key == 38 || key == 40)) {
                    self.move(key == 38 ? -1 : 1);
                    return evt.preventDefault();
                }

                if (!vertical && (key == 37 || key == 39)) {
                    self.move(key == 37 ? -1 : 1);
                    return evt.preventDefault();
                }
            });
        }

        // initial index
        setTimeout( function(){
                                    var vSeekIdx = Math.min(conf.initialIndex, Math.max(0,(self.getSize() - conf.itemCount)));
                                    self.seekTo(vSeekIdx);
                                },conf.speed);
    }


    // jQuery plugin implementation
    $.fn.scrollable = function(conf) {

        // already constructed --> return API
        var el = this.data("scrollable");
        if (el) { return el; }

        conf = $.extend({}, $.tools.scrollable.conf, conf);

        this.each(function() {
            el = new Scrollable($(this), conf);
            $(this).data("scrollable", el);
        });

        return conf.api ? el: this;

    };
    
})(jQuery);


function goToByScroll(id) {
    $('html,body').stop().animate({scrollTop: $("#"+id).offset().top}, 1500, 'swing', function(){ hashUpdateIsActive = true; if (detectMobile()) { simulateFixedPosition(); } });
};

// scrolling controls
var FAST_SCROLL_RATIO = 0.5
var MEDIUM_SCROLL_RATIO = -0.3
var SLOW_SCROLL_RATIO = - 0.2

var historyCallbackIsActive = true; // scroll on hash update
var hashUpdateIsActive = true; // update hash on scroll

// home position = top of window, below header
function shiftSectionParts(id, contentScrollRatio, bgScrollRatio) {
  var elem = $(id);
  if (id == '#contact')
    var distanceBelowHomePosition = $(document).height() - $(window).height() - $(window).scrollTop();
  else
    var distanceBelowHomePosition = elem.offset().top - $('header').outerHeight() - $(window).scrollTop();
  if (contentScrollRatio != 0)
    elem.find('.content').animate({ top: distanceBelowHomePosition * (contentScrollRatio + 1) }, 0, 'easeOutBounce');
  if (bgScrollRatio != 0)
    elem.animate({ backgroundPosition: '50% ' + (distanceBelowHomePosition * (bgScrollRatio + 1)) + 'px' }, 0, 'easeOutBounce');
}

function shiftAllSections() {
  shiftSectionParts('#section_home',         MEDIUM_SCROLL_RATIO, SLOW_SCROLL_RATIO);
  shiftSectionParts('#section_what_we_do',   SLOW_SCROLL_RATIO,   0);
  shiftSectionParts('#section_how_we_do_it', MEDIUM_SCROLL_RATIO, SLOW_SCROLL_RATIO);
  shiftSectionParts('#section_our_platform', SLOW_SCROLL_RATIO,   0);
  shiftSectionParts('#section_the_result',   MEDIUM_SCROLL_RATIO, SLOW_SCROLL_RATIO);
  shiftSectionParts('#section_about_us',     SLOW_SCROLL_RATIO,   0);
  shiftSectionParts('#section_clients',      0,                   SLOW_SCROLL_RATIO);
  shiftSectionParts('#section_contact',      SLOW_SCROLL_RATIO,   0);
}

function historyCallback(hash) {
  if (historyCallbackIsActive)
    switch(hash) {
      case 'home':
      case 'what_we_do':
      case 'how_we_do_it':
      case 'our_platform':
      case 'the_result':
      case 'about_us':
      case 'clients':
      case 'contact':
        goToByScroll(hash.replace(/^/, 'mark_'));
    }
  return false;
}

function updateHash() {
  var scrollPosition = $(window).scrollTop();
  if (hashUpdateIsActive) {
    historyCallbackIsActive = false;
    if      (scrollPosition < ($('#section_home').offset().top         + $('#section_home').height() / 2))         window.location.hash = 'home';
    else if (scrollPosition < ($('#section_what_we_do').offset().top   + $('#section_what_we_do').height() / 2))   window.location.hash = 'what_we_do';
    else if (scrollPosition < ($('#section_how_we_do_it').offset().top + $('#section_how_we_do_it').height() / 2)) window.location.hash = 'how_we_do_it';
    else if (scrollPosition < ($('#section_our_platform').offset().top + $('#section_our_platform').height() / 2)) window.location.hash = 'our_platform';
    else if (scrollPosition < ($('#section_the_result').offset().top   + $('#section_the_result').height() / 2))   window.location.hash = 'the_result';
    else if (scrollPosition < ($('#section_about_us').offset().top     + $('#section_about_us').height() / 2))     window.location.hash = 'about_us';
    else if (scrollPosition < ($('#section_clients').offset().top      + $('#section_clients').height() / 2))      window.location.hash = 'clients';
    else                                                                                                           window.location.hash = 'contact';
  }
}

function updateContactSectionHeight() {
  var height = $(window).height() - 45;
  if (height < 550) height = 550;
  $('#section_contact').css('height', height + 'px');
  $('#section_contact .content').css('height', height + 'px');
}

// align Meet The Family tab with right edge of #container
function placeMeetTheFamily() {
  var tabPositionRight = ($(window).width() - $('#container').width())/2;
  $('#meetTheFam').css('right', tabPositionRight).show();
}

// Set fixed position and animation for Meet The Family tab
var tabFlag = 'closed'
function animateMeetTheFamily() {
  if (tabFlag == 'open') {
    $('#meetTheFam').css('width', '365px');
    $('#meetTheFamContent').animate({'right' : '0'}, 'fast');
    tabFlag = 'closed'
  }
  else {
    tabFlag = 'open'
    $('#meetTheFamContent').animate({'right' : '-302px'}, 'fast', function(){ $('#meetTheFam').css('width', '60px'); });
 }
}

// enable scrolling animation for non-mobile devices
function enableScrollingAnimation() {
  $(window).scroll(shiftAllSections);
  shiftAllSections();
};

function simulateFixedPosition(e) {
  var id = window.location.hash.toString().replace(/\#/,'#section_');
  var navPosition = (id && e.type !== 'scroll') ? $(id).position().top - 45  : $(window).scrollTop() - 45;
  $('#stickyHeader').css('top', navPosition + 'px');
  $('#meetTheFam, #drawerHide').css('top', (navPosition + 200) + 'px');
};

$(document).ready(function(){
  CFInstall.check({mode: "overlay"}); // check for Chrome Frame

  $.history.init(historyCallback);
  
  $("a[rel='history']").click(function(){
    historyCallbackIsActive = true;
    hashUpdateIsActive = false;
    $.history.load(this.href.replace(/^.*#/, ''));
    return false;
  });

  $('#drawerTab').click(animateMeetTheFamily)

  
  $('.scrollable').scrollable({ circular: true, speed: 8000, easing: 'linear' }).autoscroll({ autoplay: true, interval: 0});

  // Parallax scrolling and fixed-position elements
  if (detectMobile() || ($.browser.msie && $.browser.version == 6)) {
    $('#stickyHeader, #meetTheFam').css('position', 'absolute');
    $('#meetTheFam').show();
    $('a').click(simulateFixedPosition);
    $(window).scroll(simulateFixedPosition);
    $(window).resize(simulateFixedPosition);
    $(window).load(simulateFixedPosition);
  }
  else {
    enableScrollingAnimation();
    $(window).resize(placeMeetTheFamily);
    placeMeetTheFamily();
  }

  $(window).scroll(updateHash);

  $(window).resize(updateContactSectionHeight);
  
  updateContactSectionHeight();
});
