/* 
 * Change gallery images using Ajax instead of a full page relaod.
 * 
 * Interupts the default click action (reload page with ?start=n appended) before
 * pulling base url and ?start value from the 'href' attribute of the clicked link.
 *
 * When passed to jQuery.get() Silverstripe returns HTML to replace the current
 * image gallery.
 */

jQuery(document).ready(function(){
    jQuery(".gallery-header a").live('click', function(event) {
        // Prevent default link action (full reload of page with $_GET['start'] set)
        event.preventDefault();
        // Split the href attribute of the clicked link into an array
        // containing the base url and all $_GET[] data.
        var url_array = jQuery(this).attr("href").split("?");
        //The first item in the array will be the tarket URL
        var url = url_array[0];
        //Split apart any $_GET[] variables in the second array item.
        var start_raw = url_array[1].split("&");
        // Itterate through the variables to find 'start' and it's value
        for(var i = 0; i < start_raw.length; i++)
        {
            // Split apart the variable into key/value.
            start_split = start_raw[i].split('=');
            // Check if key is start, if so clean and validate then exit for() loop.
            if(start_split[0] == 'start'){
                var startNum = parseInt(start_split[1], 10);
                // Reset startNum to 0 if parseInt returns NaN
                if (startNum == NaN){startNum = 0;}
                break;
            }
        }
        // Animated gif to indicate loading content. Call using .html
        //var ajax_load = "<img class='loading' src='mysite/img/load.gif' alt='loading...'>";

        // Make AJAX request using the url and 'start' value from above.
        // This will trigger silverstripe to return the new gallery content.
        jQuery.get(url, {start: startNum},
            // After success use new content to replace the current content and animate.
            function(data){
                // Sets the speed of animations.
                var speed = 400;
                /*
                 * Filter is used because both .gallery-header and .gallery-body are on the root level.
                 * .html() is appended I need the contents of the matched elements and not the containing divs.
                 */
                var head = jQuery(data).filter('.gallery-header').html();
                var body = jQuery(data).filter('.gallery-body').html();
                jQuery(".gallery-body").fadeTo(speed, 0,
                    function(){
                        jQuery('.gallery-body').fadeTo(speed, 1).html(body);
                        jQuery('.gallery-header').html(head);
                    });
            }
        );
    });
});