var om = om || {};

om.placeholders = function() {
    /*
     * Adapted from http://www.beyondstandards.com/archives/input-placeholders/
     */
    var supported = !!("placeholder" in document.createElement( "input" ));
    if (supported) return;
    $('input[placeholder]').each(function() {
        var placeholder = $(this).attr('placeholder');
        if ($(this).val() == '') $(this).addClass('placeholder').val(placeholder)
        $(this).focus(function() {
            if ($(this).val() == placeholder) $(this).removeClass('placeholder').val('');
            return false;
        }).blur(function() {
            if ($(this).val() == '') $(this).addClass('placeholder').val(placeholder);
        });
    });
    $('form').submit(function() {
        $('input[placeholder]').each(function() {
            var placeholder = $(this).attr('placeholder');
            if ($(this).val() == placeholder) $(this).val('');
        });
    });
};

/**
* Object used to control the basic jquery form validation setting
* @method om.validation
*/
om.validation = {

    //Setting the options for form validation
    init: function() {
        // Validation options
        $('#mailing-list').validate({
            errorPlacement: function(error, element) {
                $(element).parents('li').append(error);
            },
            highlight: function(element, errorClass) {
                $(element).parents('li').addClass(errorClass);
            },
            unhighlight: function(element, errorClass) {
                $(element).parents('li').removeClass(errorClass);
            },
            onsubmit: false,
            focusInvalid: true,
            ignoreTitle: false
        });
    }
};

om.workSlider = {
  
    sliderWidth: 0,
    slideWidth: 940,
    totalSlides: 0,
    currentPosition: 0,
    currentSlide: 0,
    origHeight: 0,

    $viewAllButton: '',
    $viewSlidesButton: '',
    $listContainer: '',
    $list: '',
    $nextSlide: '',
    $prevSlide: '',

    init: function() {
        var self = this;

        this.$listContainer = $('.work-list-container');
        this.$list = this.$listContainer.find('.work-list');
        this.$nextSlide = $('<button />', { 
            'class': 'work-slide-next',
            text: 'Next case study',
            click: function(e){
                e.preventDefault();
                self.nextSlide();
            }
        });
        this.$prevSlide = $('<button />', { 
            'class': 'work-slide-prev work-slide-button-inactive',
            text: 'Previous case study',
            click: function(e){
                e.preventDefault();
                self.prevSlide();
            }
        });

        this.$viewAllButton = $('.sub-navigation li a').eq(0).click(function(e){
            e.preventDefault();
            self.viewAll();
            self.toggleViewStateClasses();
        }).addClass('current');
        this.$viewSlidesButton = $('.sub-navigation li a').eq(1).click(function(e){
            e.preventDefault();
            self.viewSlides();
            self.toggleViewStateClasses();
        });

        this.$listContainer.append(this.$prevSlide).append(this.$nextSlide);
        this.getMainImages();        
        this.$list.wrap($('<div />', {'class': 'work-list-slides-container'}));

        if (Modernizr.history) {
            //this.bindHistoryEvents();
        }
    },

    getMainImages: function() {
        var self = this;

        this.$list.find('li').each(function(i) {

            self.totalSlides++;

            var mainImageURL = $(this).find('a').attr('data-mainUrl');
            var $thumbImage = $(this).find('.work-thumb');
            $('<img />', {
                'class': 'work-main',
                src: mainImageURL
            }).insertAfter($thumbImage);

            $(this).find('a').append($('<p class="work-list-hover">Click for more info</p>'));

        });
    },

    toggleViewStateClasses: function() {
        this.$viewAllButton.toggleClass('current');
        this.$viewSlidesButton.toggleClass('current');
    },

    viewSlides: function() {
        var self = this;
        //set the original height of the list for future ref
        this.origHeight = this.$list.outerHeight();
        this.setSlidePosition(this.currentPosition);
        this.$list.animate({
            height: 0
        }, 400, function() {
            self.$listContainer.addClass('work-list-slides');
            $(this).animate({
                height: '602px'
            }, 400, function() {
                $.scrollTo('.work-list-slides',500,function(){
                    self.$nextSlide.focus();
                });
            });
            self.setSliderWidth();
        });  
        $('body').keydown(function(e) {
            if(e.keyCode == 37) { // left
                self.prevSlide();
            } else if(e.keyCode == 39) { // right
                self.nextSlide();
            }
        });      
    },

    setSliderWidth: function() {
        this.slideWidth = this.$list.find('li').eq(0).outerWidth();
        this.sliderWidth = this.totalSlides*this.slideWidth;
        this.$list.css('width', this.sliderWidth)
    },

    viewAll: function() {
        var self = this;
        console.log(self.origHeight)
        this.$list.animate({
            height: 0
        }, 400, function() {
            self.setSlidePosition(0);
            self.$listContainer.removeClass('work-list-slides');
            $(this).css('width', '');
            $(this).animate({
                height: self.origHeight+'px'
            }, 800);            
        }); 
        $('body').unbind('keydown');
    },

    nextSlide: function() {
        if(this.$nextSlide.hasClass('work-slide-button-inactive')) return;
        this.currentPosition -= this.slideWidth;
        this.currentSlide ++;
        this.setSlidePosition();
    },

    prevSlide: function() {
        if(this.$prevSlide.hasClass('work-slide-button-inactive')) return;
        this.currentPosition += this.slideWidth;
        this.currentSlide --;
        this.setSlidePosition();
    },

    firstSlide: function() {
        this.currentPosition = 0;
        this.setSlidePosition();
    },

    setSlidePosition: function(pos) {
        var newPosition = pos;
        if(newPosition == undefined) newPosition = this.currentPosition;
        if($('html').hasClass('csstransitions')){
            this.$list.css('left', newPosition);    
        } else {
            this.$list.animate({
                left: newPosition
            }, 500);
        }        
        this.setButtonStates();
    },

    setButtonStates: function() {
        if(this.currentPosition == 0) this.$prevSlide.addClass('work-slide-button-inactive');
        else this.$prevSlide.removeClass('work-slide-button-inactive');
        if(this.sliderWidth + this.currentPosition === this.slideWidth) this.$nextSlide.addClass('work-slide-button-inactive');
        else this.$nextSlide.removeClass('work-slide-button-inactive');
    },


    // HTML5 Shizz
    bindHistoryEvents: function() {
        this.$list.find('a').bind('click', this.loadCaseStudy);
        window.addEventListener("popstate", function(e) {
            console.log(e);
        });
    },

    loadCaseStudy: function(e) {
        e.preventDefault();
        var $caseClicked = $(e.target).parent('a'),
            $newCaseStudyContainer = $('<div />', {
                'class': 'new-case-study loading off-screen-right'
            }),
            newCaseStudyTitle = $caseClicked.find('h5').text(),
            targetCaseStudyUrl = '/'+ $caseClicked.attr('href');

        history.pushState('caseStudyDetail', newCaseStudyTitle, targetCaseStudyUrl);

        $('#content').find('article').addClass('work-list-article off-screen-left').end().append($newCaseStudyContainer);
        $newCaseStudyContainer.removeClass('off-screen-right');

        $newCaseStudyContainer.load(targetCaseStudyUrl + ' .layout-2', function() {
            $newCaseStudyContainer.removeClass('loading');
        });

    }

};

om.tweets = {  

    username: "orchardonline",

    numberOfTweets: 1,

    init: function() {
        var $tweetWidget = $('.widget-twitter');
        this.$tweetList = $('#tweet-list');
        this.numberOfTweets = $tweetWidget.data('number-tweets');
        this.username = $tweetWidget.data('twitter-account');
        $(".tweet-list-placeholder").html('Talking to the Twitter internets&hellip;');
        this.pullTweets();
    },

    pullTweets: function() {

        var self = this,
            url = 'http://twitter.com/statuses/user_timeline/' + this.username + '.json?callback=?',
            params = {
                count: this.numberOfTweets
            };

        this.$tweetList.append($('<ul/>'))

        $.getJSON(url, params, function (json) {
            var tmp;
            $.each(json, function (i, tweet) {
                tmp = self.tweetify(tweet.text);
                self.$tweetList.find('ul').append(
                    $('<li>', { 'html': '<p>' + tmp + '</p><p class="tweet-list-time">' + getTime.relative(tweet.created_at) + ' via ' + tweet.source + '</p>' })
                );
            });
        }).error(function() { 
            self.$tweetList.html('<p>Don&rsquo;t judge us, but something broke. <a href="http://twitter.com/intent/orchardonline">Follow us here in the meantime</a>.</p>'); 
        }).complete(function() { 
            $(".tweet-list-placeholder").fadeOut().remove(); 
        });

        this.tweetify = function (str) {
            return str.replace(/(https?:\/\/\S+)/gi, '<a href="$1">$1</a>').replace(/(^|\s)@(\w+)/g, '$1<a href="http://twitter.com/$2">@$2</a>').replace(/(^|\s)#(\w+)/g, '$1<a href="http://search.twitter.com/search?q=%23$2">#$2</a>');
        };
    }    

}

om.flickr = function() {
    var $flickrWidget = $('.widget-flickr');
        $flickrList = $('<ul />', { 'class': 'flickr-list'});
    
    $flickrWidget.append($flickrList).find('p').remove();        

    $flickrList.jflickrfeed({
        limit: 9,
        qstrings: {
            id: '28929443@N07'
        },
        itemTemplate: '<li><a href="{{link}}" target="_blank"><img src="{{image_s}}" alt="{{title}}" /></a></li>'
    }, function(data) {
        $flickrList.addClass('flickr-list-loaded');
        if($('html').hasClass('ie6') || $('html').hasClass('ie7') || $('html').hasClass('ie8')) { 
            $flickrList.find('li:nth-child(3n)').addClass('end-of-row');
        }
    });
}

om.jobsList = {

    $jobList: '',
    $jobDetailsButton: '',

    init: function() {
        $jobList = $('.job-list');
        this.insertLinks();
        $jobList.find('.job-detail-action').eq(0).trigger('click');
    },

    insertLinks: function() {
        var self = this;

        this.$jobDetailsButton = $('<a />', {
            'class': 'job-detail-action',
            href: '#',
            text: 'show details'
        });

        $jobList.find('.job-details').each(function(i){
            self.$jobDetailsButton.clone().insertAfter($(this));
            $(this).addClass('job-details-closed');
        });

        $jobList.find('.job-detail-action').click(function(e){
            e.preventDefault();
            self.toggleJobDetails(e);
        });
    },

    toggleJobDetails: function(e) {
        var isClosed = $(e.target).prev().hasClass('job-details-closed');
        if (isClosed) {
            $(e.target).prev().removeClass('job-details-closed');
            $(e.target).text('hide details');            
        } else {
            $(e.target).prev().addClass('job-details-closed');
            $(e.target).text('show details');
        }
        
    }
}

om.miniPanelCarousel = {
    
    numberOfSlides: 0,
    widthOfCarousel: 0,
    widthOfSlide: 290,
    currentPosition: 0,
    sliderTimer: '',

    $carousel: '',
    $list: '',
    $nextLink: $('<a />',{
        'class': 'panel-carousel-next',
        text: 'Next',
        href: '#',
        click: function(e){
            e.preventDefault();
            om.miniPanelCarousel.nextSlide();
            om.miniPanelCarousel.clearTimer();
        }
    }),
    $prevLink: $('<a />',{
        'class': 'panel-carousel-prev',
        text: 'Previous',
        href: '#',
        click: function(e){
            e.preventDefault();
            om.miniPanelCarousel.prevSlide();
            om.miniPanelCarousel.clearTimer();
        }
    }),

    init: function() {
        var self = this;
        this.$carousel = $('.widget-panel-carousel');
        this.$list = this.$carousel.find('.panel-carousel-list');
        this.insertControls();
        this.prepSlides();
        this.sliderTimer = window.setInterval(self.nextSlideTrigger, 3000);
    },

    insertControls: function() {
        var self = this;
        var $controlsList = $('<ul />', { 'class': 'panel-carousel-controls' });
        $controlsList.insertAfter(this.$carousel.find('h4'));
        $controlsList.append($('<li />').append(this.$nextLink));
        $controlsList.append($('<li />').append(this.$prevLink));
    },

    prepSlides: function() {
        this.$list.wrap($('<div />', { 'class': 'panel-carousel-wrapper' }));
        this.numberOfSlides = this.$list.find('li').length;
        this.widthOfCarousel = this.widthOfSlide * this.numberOfSlides;
        this.$list.css({'width': this.widthOfCarousel});
    },

    nextSlideTrigger: function() {
        om.miniPanelCarousel.nextSlide();
    },

    nextSlide: function() {
        this.currentPosition -= this.widthOfSlide;
        if(this.currentPosition == -(this.widthOfCarousel)) this.currentPosition = 0;
        this.setCurrentPosition();
    },

    prevSlide: function() {
        this.currentPosition += this.widthOfSlide;
        if(this.currentPosition > 0) this.currentPosition = -(this.widthOfCarousel - this.widthOfSlide);
        this.setCurrentPosition();
    },

    setCurrentPosition: function() {
        if($('html').hasClass('csstransitions')){
            this.$list.css('left', this.currentPosition);    
        } else {
            this.$list.animate({
                left: this.currentPosition
            }, 300);
        }
    },

    clearTimer: function() {
        clearInterval(this.sliderTimer);
    }

}

om.heroCarousel = {
    
    noOfSlides: 0,
    widthOfSlide: 960, //include guttering
    widthOfSlider: 0,
    currentSlide: 1,
    sliderTimer: '',

    $sliderContainer: '',
    $slider: '',
    $pager: $('<ul />', {
        'class': 'hero-slider-pager'
    }),
    $pagerItem: $('<a />', { 
        'class': 'hero-slider-pager-action',
        href: '#'
    }),

    init: function() {
        var self = this;
        this.$sliderContainer = $('.hero-slider-container');
        this.$slider = $('.homepage-hero-list');
        this.setSlider();
        if(this.noOfSlides == 1) return;
        this.$sliderContainer.wrap($('<div class="hero-slider-wrapper" />'));
        this.buildPager();
        this.setTimer();
    },

    setSlider: function() {
        this.widthOfSlide = this.$slider.find('.homepage-hero').eq(0).outerWidth() + 20;
        this.noOfSlides = this.$slider.find('.homepage-hero').length;
        this.widthOfSlider = this.noOfSlides * this.widthOfSlide;
        this.$slider.css('width', this.widthOfSlider);

        this.$slider.find('.homepage-hero').each(function(){
            $(this).find('a').append($('<p class="work-list-hover">Click for more info</p>'));
        });
    },

    buildPager: function() {
        var self = this;
        this.$pager.insertBefore(this.$sliderContainer);
        for (var i = 0; i < this.noOfSlides; i++) {
            this.$pager.append($('<li />').append(this.$pagerItem.clone().text('slide ' + (i+1))));
        };
        this.$pager.find('.hero-slider-pager-action').click(function(e){
            e.preventDefault();
            self.clearTimer();
            var clickedIndex = self.$pager.find('.hero-slider-pager-action').index($(this));
            self.pickSlide(clickedIndex+1);
        });
        this.$pager.find('.hero-slider-pager-action').eq(0).addClass('current');
        this.$pager.css('width', this.noOfSlides*16);
    },

    pickSlide: function(i) {
        this.currentSlide = i;
        this.$pager.find('.hero-slider-pager-action').removeClass('current');
        this.$pager.find('.hero-slider-pager-action').eq(i-1).addClass('current');
        this.showSlide();
    },

    showSlide: function() {
        var newLeft = (this.widthOfSlide*(this.currentSlide-1));
        if(newLeft >= this.widthOfSlider) newLeft = 0;
        if($('html').hasClass('csstransitions')){
            this.$slider.css('left', -newLeft);    
        } else {
            this.$slider.animate({
                left: -newLeft
            }, 300);
        }        
    },

    clearTimer: function() {
        window.clearInterval(om.heroCarousel.sliderTimer);
        this.setTimer();
    },

    setTimer: function() {
        om.heroCarousel.sliderTimer = window.setInterval(function(){
            om.heroCarousel.incrementSlide()
        }, 6000);
    },

    incrementSlide: function() {
        var newIndex = om.heroCarousel.currentSlide+1; 
        if(newIndex > om.heroCarousel.noOfSlides) newIndex = 1;
        om.heroCarousel.pickSlide(newIndex);

    }

}

/**
* Object used to control the map functionality.
* @method om.map
*/
om.map = {
    
    MAP_DEFAULTS: '',
    map: '',
    orchardMarker: '',
    aroundUsMarkers : [],
    aroundUsData: '',

    $showOfficeButton: '',
    $showWhatsAroundButton: '',

    /**
    * Method to initalise the map in page
    * @method init
    */
    init: function(el) {
        var self = this,
            mapDomID = $(el).attr('id');
                
        //set instance of map with target id
        this.makeMap(mapDomID);

        //bind events to the sub nav links
        //lack of classes on CMS version, detect via position.
        this.$showOfficeButton = $('.contact .sub-navigation a').eq(1).click(function(e) {
            e.preventDefault();
            self.showOfficeInMap();
        });
        this.$showWhatsAroundButton = $('.contact .sub-navigation a').eq(2).click(function(e) {
            e.preventDefault();
            self.showWhatsAroundInMap();
        });

        //show the office in the map
        this.showOfficeInMap();
        //grab the whats around us JSON object
        this.getWhatsAroundUs();

    },

    /**
    * Method used to initialise a map when used in a drawer context, cut down version
    * @method mapDrawerInit
    * @param dom element for map
    */
    mapDrawerInit: function(el) {
        var self = this,
            mapDomID = $(el).attr('id');
                
        //set instance of map with target id
        this.makeMap(mapDomID);

        //show the office in the map
        this.showOfficeMarker();
    },

    /**
    * Method used to convert html to a map based on a dom element id
    * @method makeMap
    * @param dom element id
    */
    makeMap: function(id) {
        var self = this;
        ;
        //map defaults
        this.MAP_DEFAULTS = {
            zoom: 16,
            center: new google.maps.LatLng(-33.881524, 151.2144835), // Surry Hills
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            streetViewControl: true,
            scaleControl: true,
            mapTypeControlOptions: {
                mapTypeIds: ['orchardChrome']
            }
        };

        // object used to contain all the style variables for the map chrome
        // read up here http://bestfromgoogle.blogspot.com/2011/05/style-google-maps-make-ur-map-look-cool.html
        var styles = [
            {
                featureType: "road",
                elementType: "geometry",
                stylers: [
                    { hue: "#d7c6a3" },
                    { saturation: -40 },
                    { lightness: 0 }
                ]
            },
            {
                featureType: "road.artery",
                elementType: "geometry",
                stylers: [
                    { hue: "#d7c6a3" },
                    { saturation: -40 },
                    { lightness: -5 }
                ]
            },
            {
                featureType: "landscape",
                elementType: "geometry",
                stylers: [
                    { hue: "#ece5d4" },
                    { saturation: 0 },
                    { lightness: 0 }
                ]
            },
            {
                featureType: "all",
                elementType: "labels",
                stylers: [
                    { visibility: "on" },
                    { saturation: -100 },
                    { lightness: 0 }
                ]
            },
            {
                featureType: "transit",
                elementType: "all",
                stylers: [
                    { visibility: "off" }
                ]
            },
            {
                featureType: "administrative",
                elementType: "all",
                stylers: [
                    { hue: "#e9e0cc"},
                    { saturation: 30 },
                    { lightness: 0 }
                ]
            }
        ];
        //Set new map with map defaults
        this.map = new google.maps.Map(document.getElementById(id), this.MAP_DEFAULTS);

        //style that map with it's options
        var styledMapOptions = {
            name: "Orchard"
        };
        //new map style type
        var orchardMapType = new google.maps.StyledMapType(styles, styledMapOptions);
        //set map types and id
        this.map.mapTypes.set('orchardChrome', orchardMapType);
        this.map.setMapTypeId('orchardChrome');
    },

    /**
    * Method used to show the whats aournd us markers on the map
    * @method showWhatsAroundUs
    */
    showWhatsAroundInMap: function() {
        var self = this;
        //Show markers
        this.showWhatAroundMarkers();
        //set nav current
        this.$showWhatsAroundButton.addClass('current');
        this.$showOfficeButton.removeClass('current');
    },

    /**
    * Method used to create the markers on the map for whats around us
    * @method showWhatAroundMarkers
    */
    showWhatAroundMarkers: function() {
        //remove the current around us markers
        if (this.aroundUsMarkers != '') {
            this.aroundUsMarkers = this.removeMarkers(this.aroundUsMarkers);
        }
        console.log(this.aroundUsData);
        //create a marker for each object in the JSON for points around us and add them to the public variable aroundUsMarkers
        for (var i = 0; i < this.aroundUsData.length; i++) {
            //new google location
            var markerLocation = new google.maps.LatLng(this.aroundUsData[i].Latitude, this.aroundUsData[i].Longitude);
            //add marker to array of markers
            this.aroundUsMarkers[i] = this.createMarker(this.aroundUsData[i].ImageUrl, new google.maps.Size(52, 52), '/themes/orchard/images/shadow.orchard.png', new google.maps.Size(1, 1), markerLocation);
        };
        //update the map bounds
        this.updateMapBoundsToAroundUs();
    },

    /**
    * Method used to show the office location
    * @method showOfficeInMap
    */
    showOfficeInMap: function() {
        //show the office
        this.showOfficeMarker();
        //set the nav
        this.$showWhatsAroundButton.removeClass('current');
        this.$showOfficeButton.addClass('current');
    },

    /**
    * Mehtod used to cerate the office location marker
    * @method showOfficeMarker
    */
    showOfficeMarker: function() {
          //remove old office marker just in case
        if (this.orchardMarker != '') {
            google.maps.event.clearInstanceListeners(this.orchardMarker);                   
            this.orchardMarker.setMap(null);
            this.orchardMarker = null;
        }
        //remove other markers on the map
        if (this.aroundUsMarkers != '') {
            //clear the around us markers
            this.aroundUsMarkers = this.removeMarkers(this.aroundUsMarkers);
        }
        //new google location
        var orchardLocation = new google.maps.LatLng('-33.881524', '151.2144835');
        //set zoom level, center the map and pan to the marker if it's been moved
        this.map.setZoom(16);
        this.map.setCenter(orchardLocation);
        this.map.panTo(orchardLocation);
        //create the orchard marker
        this.orchardMarker = this.createMarker('/themes/orchard/images/marker.orchard.png', new google.maps.Size(110, 64), '/themes/orchard/images/shadow.orchard.png', new google.maps.Size(64, 64), orchardLocation);
    },

    /**
    * Method used to create a marker for the map
    * @method createMarker
    * @param url for image, size of image, url of shadow, size of shadow, location of marker
    * @return google map marker
    */
    createMarker: function(markerImageUrl, iconSize, shadowImageUrl, shadowSize, location) {        
        var markerOptions = {
            position: location,
            map: this.map,
            icon: this.createMarkerImage(markerImageUrl, iconSize),
            shadow: this.createShadowImage(shadowImageUrl, shadowSize)
        };        
        var marker = new google.maps.Marker(markerOptions);
        return marker;
    },

    /**
    * Method used to create the marker shadow
    * @method createShadowImage
    * @param url of shadow image, size
    * @return map marker image for the marker shadow
    */
    createShadowImage: function(url, size) {
        //if no size set a default size
        if (size == undefined) size = new google.maps.Size(64, 64);
        //ancor the shadow to the middle
        var anchor = new google.maps.Point(0, size.height);
        return new google.maps.MarkerImage(url, size, null, anchor);
    },

    /**
    * Method used to create the marker image for the markers
    * @method createMarkerImage
    * @param url of marker image, size of marker
    * @return google maps marker image
    */
    createMarkerImage: function(url, size) {
        //if no size set default size
        if (size == undefined) size = new google.maps.Size(110, 64);
        return new google.maps.MarkerImage(url, size);
    },

    /**
    * Method to remove a set of markers from the map using an array of markers
    * @method removeMarkers
    * @param array of markers to remove
    * @return empty array
    */
    removeMarkers: function(markers) {
        if (markers != []) {
            //For each marker clear all the event listeners
            for (var i in markers) {
                google.maps.event.clearInstanceListeners(markers[i]);
                markers[i].setMap(null);
                markers[i] = null
            }
        }
        //return an empty array to replace with
        return [];
    },

    /**
    * Method used to set the map bounds to show all plotted markers on the map absed on their position
    * @method updateMapBoundsToAroundUs
    */
    updateMapBoundsToAroundUs: function() {
        //create a new map bounds
        mapBounds = new google.maps.LatLngBounds(); 
        //for each marker on the map for aorund us get the position and update the bounds
        for (var i = 0; i < this.aroundUsMarkers.length; i++) {
            mapBounds.extend(this.aroundUsMarkers[i].getPosition());
        }    
        //update bounds with our location too
        mapBounds.extend(this.orchardMarker.getPosition());
        //fit the map to those bounds
        this.map.fitBounds(mapBounds);
    },

    /**
    * Method to perform an ajax call to grab the JSON for the around us points
    * @method getWhatsAroundUs
    */
    getWhatsAroundUs: function() {
        var self = this;
        $.ajax({
            url: '/whatsaround',
            success: function(data, textStatus, XMLHttpRequest) {
                //set the public data variable to result
                self.aroundUsData = data;
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                //if an error hide the option to show whats around us
                self.$showWhatsAroundButton.hide();
            }
        });
    }
}

/**
* Object to control the drawer functinality in the footer
* @method om.footerDrawers
*/
om.footerDrawers = { 

    //defaults used for the heights of the drawers
    defaults: {
        googleDrawerHeight: 460,
        subscribeDrawerHeight: 220
    },

    $drawer: '',
    $closeButton: '',

    /**
    * Method used to initialise the drawers
    * @method init
    */
    init: function() {
        var self = this;
        $closeButton = $('.button-close-drawer').click(function(e){
            e.preventDefault();
            var $drawerToClose = $(e.target).parents('.footer-drawer');
            self.closeDrawer($drawerToClose);
        });
    },

    /**
    * Method used to toggle the drawer
    * @method toggle
    * @param drawer that you are toggling
    */
    toggle: function(drawer) {
        var $drawerToToggle = $(drawer);
        if ($drawerToToggle.hasClass('footer-drawer-open')) {
            this.closeDrawer($drawerToToggle);
        } else {
            this.openDrawer($drawerToToggle);
        }
    },

    /**
    * Method used to open a drawer
    * @method openDrawer
    * @param drawer to open
    */
    openDrawer: function(drawer) {
        var $drawerToOpen = $(drawer),
            targetHeight = this.defaults.googleDrawerHeight;

        if($drawerToOpen.hasClass('subscribe-drawer')) {
            var bodyWidth = $('body').width();
            if(bodyWidth < 480) {
                targetHeight = 550;
            } else if(bodyWidth < 960) {
                targetHeight = 290;
            } else {
                targetHeight = this.defaults.subscribeDrawerHeight;
            }
            
            $.scrollTo('.footer-wrapper', 200, function(){
                $drawerToOpen.addClass('footer-drawer-open').focus().animate({
                    height: targetHeight
                }, 150, 'easeInCubic');
            }); 
            return;
        }

        $drawerToOpen.addClass('footer-drawer-open').focus().animate({
            height: targetHeight
        }, 150, 'easeInCubic');
    },

    /**
    * Method used to close a drawer
    * @method closeDrawer
    * @param drawer to close
    */
    closeDrawer: function(drawer) {
        var $drawerToClose = $(drawer);
        $drawerToClose.animate({
            height: 0
        }, 150, 'easeInCubic', function(){
            $drawerToClose.removeClass('footer-drawer-open');
            if($drawerToClose.hasClass('subscribe-drawer')) {
                $('.action-subscribe').focus();
            } else {
                $('.view-in-google-maps').focus();
            }
        });
    }
}

/**
* Object used to submit the mailing list form
* @method om.subscribe
*/
om.subscribe = {

    //setting to test if the form is currently being submitted
    isSubmitting: false,

    /**
    * Method used to validate the subscription form
    * @method validate
    * @param form to validate
    */
    validate: function(form) {
        if(this.isSubmitting) return

        this.isSubmitting = true;
        var $group = $(form);
        var isValid = true;
        $group.find(':input').each(function (i, item) {
            if($(item).val() === $(item).attr('placeholder')) $(item).val('');
            if (!$(item).valid()) isValid = false;
            om.placeholders();
        });
        //if the form is valid, post the form
        if (isValid) {
            this.post($group);  
        }  else {
            this.isSubmitting = false;
        }
    },

    /**
    * Method used to post the form data to the server and deal with the response
    * @method post
    * @param form that is being posted
    */
    post: function(form) {
        //add a spinner for loading
        var el = document.getElementById('footer-mailing-list'),
            spinner = new Spinner(om.spinner.opts).spin(el),
            action = $(form).attr('action');

        //animate the form
        $(form).find('ol').animate({
            'margin-top': 870
        }, 200, 'easeOutCubic', function(){
            $(this).remove();
        });
        var formSubmitted = false;;
        //post the form and data
        $.ajax({
            data: $(form).serialize(),
            type: 'POST',
            dataType: 'application/json',
            url: action,
            success: function(data, textStatus, XMLHttpRequest) {
                var formData = data;
                formSubmitted = formData.Success;
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {              
                formSubmitted = false;
            },
            complete: function(XMLHttpRequest, textStatus) {
                setTimeout(function() { 
                    //stop the spinner
                    spinner.stop(); 

                    //create a holding place and add a message dependin gon the response
                    var $messageHolder = $('<div />', { 'class': 'message-container' })
                    if(formSubmitted != 'false') {
                        $messageHolder.addClass('success-message').html('<p>Nice work! No really, we promise we won&rsquo;t spam you.</p>');
                        setTimeout(function() { om.footerDrawers.closeDrawer($('.subscribe-drawer')); }, 4000);
                    } else {
                        $messageHolder.addClass('error-message').html('<p>We&rsquo;re sorry, but there was a problem with sending us that information. How about you <a href="mailto:hello@orchardmarketing.com.au">email us instead</a>?</p>');
                        $(form).next().focus();
                    }
                    //insert the message and animate it
                    $messageHolder.insertAfter($(form).find('h2')).animate({
                        'margin-top': 20
                    }, 200, 'easeOutCubic');
                    
                }, 2000);                
                //set the flag to false
                this.isSubmitting = false;
            }
        });
    }
}

//Spin.js options
om.spinner = {

    opts: {
        lines: 12, // The number of lines to draw
        length: 7, // The length of each line
        width: 2, // The line thickness
        radius: 8, // The radius of the inner circle
        color: '#000', // #rbg or #rrggbb
        speed: 1, // Rounds per second
        trail: 100, // Afterglow percentage
        shadow: false // Whether to render a shadow
    }

}

om.orientationSwitch = function() {
    //set orientation variable
    var supportsOrientationChange = 'onorientationchange' in window,
        supportsResizeChange = 'resize' in  window,
        orientationEvent = '';
    
    if(supportsOrientationChange) {
        orientationEvent = 'orientationchange'
    } else if (supportsResizeChange) {
        orientationEvent = 'resize'
    }

    if(orientationEvent != '') {
        window.addEventListener(orientationEvent, function() {
            if($('.work-list-slides').length) { 
                om.workSlider.setSliderWidth();
                om.workSlider.firstSlide();
            }
            if($('.hero-slider-container').length) {
                om.heroCarousel.setSlider();
                om.heroCarousel.pickSlide(1);
            }            
        }, false);
    }
}

/**
* Method used to scroll the side bar in the casse study page
* @method caseStudyAside
*/
om.caseStudyAside = function() {
    if(!$('html.no-touch').length) return;
    var $window = $(window);
    var $main = $('.work #content aside');
    var mainTop = $main.offset().top;
    var needToScroll = false;
    var atTheBottom = false;
    var timer;
    $window.scroll(function(){

        var scrollTop = $window.scrollTop();
        if(($main.position().top-mainTop) > ($main.parent().outerHeight()-$main.height()) && $main.position().top > ($main.parent().outerHeight()-$main.height())) atTheBottom = true;
        else atTheBottom = false;
        if((mainTop - scrollTop) < 11 || mainTop < scrollTop ) needToScroll = true;
        else needToScroll = false;

        if(needToScroll && !atTheBottom) {
            $main.addClass('sticky-side');
        } else if(atTheBottom){
            $main.addClass('sticky-side-stuck');
        } else {
            $main.removeClass('sticky-side');
            $main.removeClass('sticky-side-stuck');
        }
        
    }).trigger('scroll');
    
}

window.onerror = function(msg, url, linenumber) {
    console.log('error:', msg, linenumber, url);
    _gaq.push(['_trackEvent',
        'Exception ' + msg, //event category
        msg + ' ' + linenumber, //event action
        url //event label
    ]);
}

om.init = function() {
    $('html').removeClass('no-js').addClass('ready');
    if($('body').hasClass('ie6') || $('body').hasClass('ie7') || $('body').hasClass('ie8')) $('.work-list li:nth-child(3n)').addClass('end-of-row'); //dirty ie hack

    om.placeholders();
    if($('.widget-twitter').length) om.tweets.init();
    if($('.work-list').length && $('body').outerWidth() > 480) om.workSlider.init();
    if($('.widget-flickr').length) om.flickr();
    if($('.job-list').length) om.jobsList.init();
    if($('.widget-panel-carousel').length && $('body').outerWidth() > 980) om.miniPanelCarousel.init();
    if($('.hero-slider-container').length && $('.hero-slider-container:visible').length) om.heroCarousel.init();
    if($('#google-map').length) om.map.init($('#google-map'));
    if($('.footer-drawer').length) om.footerDrawers.init();
    om.validation.init();
    om.orientationSwitch();
    //if($('.work .layout-2').length && $('body').outerWidth() > 980) om.caseStudyAside();
    //odd events
    $('.view-in-google-maps').click(function(e){
        e.preventDefault();
        if($('#google-map').length) return;
        om.footerDrawers.toggle($('.map-drawer'));
        om.map.mapDrawerInit($('#google-map-footer'));
    });
    $('.action-subscribe').click(function(e){
        e.preventDefault();
        om.footerDrawers.toggle($('.subscribe-drawer'));
    });
    //form submission
    $('#mailing-list').submit(function() { 
        om.subscribe.validate(this);
        return false;
    });            
};

$(function(){
    om.init();
});
