$(document).ready(function(){
    
    // Remove no-js class
    if ($("body").hasClass("no-js")) {
        $("body").removeClass("no-js");
    }

    $homeSlides = $('ul#home_slides');
    $subSlides = $('body:not(.home) ul.slides');
    
    if ($homeSlides.length > 0) {
        $homeSlides.edSlideshow({ speed: 300, orientation: 'vertical', slideshow: false });
        
        // Log the default slideshow item
        _gaq.push(['_trackEvent', 'Homepage slideshow', 'Default', $("ul#home_slides li.cur h3").text()]);
        
        // Bind a click event for slideshow custom event tracking
        $('div#home_slideshow a.goto').bind('click', function() {
            // User has viewed a new slide, push custom event with slide title
            _gaq.push(['_trackEvent', 'Homepage slideshow', 'Clicked', $("ul#home_slides li.cur h3").text()]);
        });
    }
    if ($subSlides.length > 0) {
        $subSlides.edSlideshow({ speed: 300, orientation: 'horizontal', slideshow: false });
    }

    // COMMON: removes the submit button form the locations filter on the openings page
    // and sets the form to auto sybmit
    $('div#filter input[type="image"]').remove();
    
    $('select[name="locations"]').auto_submit($('div#filter form'));
    $('select[name="locations"]').live("change", function(){
        url = "/careers/vacancies/locations/" + $('select[name="locations"]').val();
        window.location = url;
    });

    $('select#filter_expertise, select#filter_service').live("change", function(){
        url = "/work/projects/expertise/" + $('select#filter_expertise').val() + "/service/" + $('select#filter_service').val();
        window.location = url;
    });

    // slider in the horizons archive page
    $('p.horizon_slider a').slider();

    // COMMON: insert the 'keywords' text into the search text input field
    $('input.keywords').search_text_input();

    // remove border when hovering over navigation items
    $('div#navigation_pri ul li').tidy_nav_hover();

    // validate forms using jquery.validate
    $('form#newsletter_header_form').validate();
    $('div#jobs_email form').validate();
    $('div#news_updates_signup form').validate();
    $('#freeform').validate();


    // hide/show the jobs updates sidebar form
    $('div#jobs_email form').hide();
    $('div#jobs_email').sidebar_slider( );

    // show/hide the newa updates sidebar signup form
    $('div#news_updates_signup form').hide();
    $('div#news_updates_signup').sidebar_slider();

    // show/hide the main signup form
    $('ul#tab_subscribe li a').show_hide( 'div#email_panel', 'Close', $('ul#tab_subscribe li a').html() );        

    // Projects on the 'Our Work' page sidebar
    $('ul#projects_widget').accordion({ 
        active: false, 
        header: 'h3',
        autoHeight: false,
        clearStyle: true,
        alwaysOpen: false
    });

   slideshow_vids(); 

   if ($('#expertise_diagram').length > 0) work_flash();
   
   
   // PROJECTS MAP FUNCTION
   
   function Projects_map(options) {
               
       var that = this, // Scope, lyk        
       options = options || {}; // Get options array
               
       // Function to render map to page
       this.render_map = function() {
           
           // JSON for map styling
           var map_style = new google.maps.StyledMapType([{
               featureType: "administrative",
               elementType: "all",
               stylers: [{ visibility: "off" }]
           }, {
               featureType: "poi",
               elementType: "all",
               stylers: [{ visibility: "off" }]
           }, {
               featureType: "road",
               elementType: "all",
               stylers: [{ visibility: "off" }]
           }, {
               featureType: "transit",
               elementType: "all",
               stylers: [{ visibility: "off" }]
           }, {
               featureType: "water",
               elementType: "labels",
               stylers: [{ visibility: "off" }]
           }, {
               featureType: "landscape",
               elementType: "all",
               stylers: [
                   { hue: "#1F3D58" },
                   { saturation: 70 },
                   { visibility: "on" },
                   { lightness: -70 }
               ]
           }, {
               featureType: "water",
               elementType: "geometry",
               stylers: [
                   { hue: "#e8f1f7" },
                   { saturation: 10 },
                   { lightness: 90 },
                   { gamma: 0},
                   { visibility: "on" }
               ]
           }], {name: "Plain"});

           // Instantiate Google maps object
           that.map = new google.maps.Map(document.getElementById(options.element), {
               backgroundColor: "#f5f8fb",
               disableDefaultUI: true, // Disable default UI
               zoom: 1, // Zoom to level one
               center: new google.maps.LatLng(45, 11), // Centre on US
               mapTypeId: "Plain", // Map type to road
               draggable: false, // Disable dragging
               disableDoubleClickZoom: true, // Disable zooming
               scrollwheel: false // Disable zooming
           });
           
           // Set map type to plain
           that.map.mapTypes.set("Plain", map_style);
           
       };
       
       // Returns JSON for projects 
       this.get_projects = function() {
           
           var projects; // Variable to store projects
           
           $.ajax({
               url: options.json,
               dataType: "json",
               async: false,
               success: function(data) {
                   projects = data; // Assign JSON
               }
           });
           
           return projects; // Return JSON

       };

       this.render_projects = function() {
           
           populate_tooltip = function(project, event) {
               
               // Hide tooltip incase it's already open
               tooltip.hide();
               
                // Find inner div and clear its contents
               tooltip.inner = tooltip.find("div");
               tooltip.inner.html("");
                               
               // Set tooltip contents
               tooltip.inner.append("<h1>" + project.name + "</h1>");
               tooltip.inner.append("<p class=\"meta\">" + project.location + "</p>");
               tooltip.inner.append("<p class=\"desc\">" + project.desc + "</p>");
               if (project.thumbnail) {
                   tooltip.inner.append("<img src=\"" + project.thumbnail + "\" width=\"50\" height=\"50\" />");
               }
               tooltip.inner.append("<p class=\"tools\"><a class=\"close\">Close</a> <a href=\"" + project.project_url + "\" class=\"button\">View this project</a></p>");
               
               // Event listener for tooltip close button
               tooltip.inner.find("a.close").bind('click', function() {
                   tooltip.hide();
                   tooltip.inner.html("");
                   // Loop through all markers and unset them
                   $.each(projects, function(index, value) {                    
                       this.setIcon(options.inactive_marker);
                       this.is_active = false;
                   });
               });
               
               // Set position of tooltip
               // Note: math here is because tooltip is set in the container above the Google map
               tooltip.css("top", event.pixel.y - (tooltip.outerHeight() / 2) + 10);
               
               // Check if there's enough space to render to the right - if not, render left
               if (($("div#projects_map").outerWidth() - event.pixel.x) < 280) {
                                       
                   tooltip.css("left", event.pixel.x - 195);
                   tooltip.addClass("right");
                   
                   
               } else {
                   tooltip.removeClass("right");
                   tooltip.css("left", event.pixel.x + 90);
                   
                   
               }
                                                   
               // Show tooltip
               tooltip.fadeIn("fast");
               
           };
           
           // Get projects from JSON
           var json = that.get_projects(),
           projects = {},
           tooltip = $("div#map_tooltip");
           
           // Hide tooltip
           tooltip.hide();
                   
           // Loop through each project, render to map
           $.each(json, function(i, project) { 
               
               // Create marker
               projects[i] = new google.maps.Marker({
                   position: new google.maps.LatLng(project.lat, project.lng), 
                   map: that.map,
                   icon: options.inactive_marker,
                   cursor: "pointer",
                   optimized: false
               }); 
                               
               // Event listener for mouseover
               google.maps.event.addListener(projects[i], 'mouseover', function() {
                   this.setIcon(options.active_marker);
               });
               
               // Event listener for mouseout
               google.maps.event.addListener(projects[i], 'mouseout', function() {
                   if (!this.is_active) {
                       this.setIcon(options.inactive_marker);
                   }
               });
               
               // Event listener for tooltip
               google.maps.event.addListener(projects[i], 'click', function(event) {
                   
                   this.setIcon(options.active_marker);
                   this.is_active = true;
                   
                   // Loop through all except this marker and unset them
                   $.each(projects, function(index, value) {
                       if (value !== projects[i]) {
                           this.setIcon(options.inactive_marker);
                       }
                   });
                                       
                   // Launch tooltip onclick
                   populate_tooltip(project, event);
                   
               });
               
               // Listeners for the projects grid
               $("ul#clients_listing").find("a#" + project.uid).bind('mouseover', function() {
                   projects[i].setIcon(options.active_marker);
               });
               $("ul#clients_listing").find("a#" + project.uid).bind('mouseout', function() {
                   projects[i].setIcon(options.inactive_marker);
               });
               
           });
           
           // Mouse events for tooltip
           $(document).mouseup(function(e) {
               
               // Don't close if we're on the map tooltip
               $("div#map_tooltip div").mouseup(function() {
                   return false;
               });
               
               // Close if we click on something that's not a marker
               $("div#map_tooltip").hide();
               
               // Unset all markers
               $.each(projects, function(index, value) {
                   this.setIcon(options.inactive_marker);
               });

           });
                       
       };
       
       this.render_map();
       this.render_projects();
       
       // IE 6 to 8 grid fix
       if ($.browser.msie && $.browser.version.substr(0,1) <= 8) {

           $("div#projects_map ul li:nth-child(4n+4)").each(function(index) {
               $(this).css("border-right", "none");
               $(this).css("width", "169px");
           });

       }
       
   }
   
   // Check if we're on contact page
   if ($("div#projects_map").length) {
       var projects_map = new Projects_map({
           element: "map_interface",
           json: "/feeds/projects_map_json",
           active_marker: "/assets/images/site/icons/projects_map/marker_active.png",
           inactive_marker: "/assets/images/site/icons/projects_map/marker_inactive.png"
       });   
   }

});

var active_player = false;
function slideshow_vids() {
    var $videos = $('div.slideshow .media_holder'),
        $slideshow_controls = $('ul.slideshow_controls li a');

    if ($videos.length == 0) {
        return false;
    }

    $videos.find('a.play').click(function(event) {
        event.preventDefault();

        var youtube = $(this).attr('href')
            $replace = $(this).parent().next('div.media_player'),
            $image = $(this).prev('img'),
            width = $image.width(),
            height = $image.height();

        $(this).parent().hide();
        $(this).closest('li').find('div.info').hide();
        active_player = $replace.attr('id');


        jwplayer(active_player).setup({
            file: youtube,
            width: width,
            height: height,
            autostart: true,
            modes: [
                { type: "html5" },
                { type: "flash", src: "/assets/tools/jwplayer/player.swf" }
            ]
            
        });

    });

    $slideshow_controls.click(function(){
        if (active_player) {
            jwplayer(active_player).remove();
            $('div.slideshow div.media_holder:hidden').show();
        }
    });

}

/// BEING FUNCTIONS SPECIFIC TO H&S --------------------------


/**
*
* Show/Hide
* -----------------
* Toggle slides and item, and chnages the html() of
* the clicked item to the specified value
*
* @return $(this) obj
*/
$.fn.sidebar_slider = function() {
    container = $(this);
    $('h2,h3', this).click( function() {
        $(this).next('form').slideToggle(500);
    } );
    return $(this);
};


/**
*
* Show/Hide
* -----------------
* Toggle slides and item, and chnages the html() of
* the clicked item to the specified value
*
* @return $(this) obj
*/
$.fn.show_hide = function( the_item, althtml, orightml ) {
    $(this).click(function(){
        $(the_item).slideToggle('fast');
        $(this).toggleClass('open').toggleClass('closed');
            if( $(this).html() !== althtml) {
        $(this).html(althtml);
        } else {
            $(this).html(orightml);
        }
        return false;
    });
    return $(this);
};


/**
*
* Slideshow
* -----------------
*
* @return $(this) obj
*/
$.fn.slideshow = function( path ) { 
    var slideshow_div = $(this);
    $('li.ss_next a, li.ss_prev a', this).live('click', function(){
        trgts = $(this).attr('href').split('/');
        trgt = trgts[trgts.length - 1];         
        $('img',slideshow_div).fadeOut('slow', function(){
            slideshow_div.load(path+' div.ss:eq('+trgt+')', function(){});
        });
        return false;
    });
    return $(this);
};


/**
*
* Tidy Navigation Hover States
* -----------------
* Adds a class to the next element to 'this' parent
* the css for the class will remove the unsighlty border
* on the next element.
*
* @return $(this) obj
*/
$.fn.tidy_nav_hover = function() {
    var element_to_change = $(this).parent().next();
    $('a', this).hover(function(){
        element_to_change.addClass('hover_next');
    }, function(){
        element_to_change.removeClass('hover_next');
    });
    return $(this);
};


/**
*
* Slider
* ------
* This function is quite markup specific (currently used in the horizons section)
* I'm not sure if it's worth making it more re-usable. Probably not.
*
* @return $(this) obj
*/
$.fn.slider = function() {
    $(this).next('ul').hide();
    $('a', this).click(function(){
        $(this).parent().parent().next('ul').slideToggle('slow');
        return false;
    });
    return $(this);
};

/**
 * Flash on work page
 */
 function work_flash() {
     var so = new SWFObject("/assets/flash/diagram.swf", "expertise_diagram", "310", "310", "6", "#FFFFFF");
    so.addParam("wmode","transparent");
    so.addVariable("waterLink", "/work/expertise/water");
    so.addVariable("stormwaterLink", "/work/expertise/stormwater");
    so.addVariable("combinedLink", "/work/expertise/combined-sewer-overflows");
    so.addVariable("wastewaterLink", "/work/expertise/wastewater");
    so.addVariable("biosolidsLink", "/work/expertise/biosolids-residuals");
    so.addVariable("reclamationLink", "/work/expertise/reclamation-reuse");
    so.addVariable("sustainabilityLink", "/work/expertise/sustainability");
    so.write("expertise_diagram");
 }

