//*************************************************************************************
// File     : braingnat.js
// Version  : 0.3.3
// Requires : jquery.js (version 1.3.2+)
// Author   : Kyle Weems (ksw)
// Origin   : mindfly.com
// Created  : July 29, 2008
// Modified : August 3, 2009
// Purpose  : BrainGnat - A collection of handy solutions and functions for problems and 
//            desired functionality for client websites by Mindfly.
//*************************************************************************************

/* List of methods */

// 0.0.1
// setContentHeight 	- Adjusts height of page content to make it fit in browser.
// 0.0.5
// stickyList			- Gives list items the class 'stuck' when they are hovered over and in lists with the '.stickyList' class.
// 0.1.0
// slideshow.fadein  	- Loops a series of images in a slideshow.
// slideshow.ajaxLoadCrossfade 	- Ajax call to a document that lists the images for use in a slideshow
// 0.1.4
// randomBackgroundImage- Add a randomly selected background image from a provided array to the provided element.
// randomImage          - Set the source of the provided image tag to the a randomly selecte image from the provided array.
// 0.1.5
// html5Shiv            - Fixes IE to support CSS styling of HTML5 elements
// 0.2.0
// setTabs              - Adds tab functionality to given section where tabs have class 'tab' and content of tabs has class 'tabbedContent'
// 0.3.0
// Google               - New namespace for Google mashups
// Google.map           - New namespace for Google maps mashups
// Google.map.load(elem)- Loads elem (defined by css selecor). If selector is for more than one element, only selects the first one.
// Google.map.addMarker(latlng,info) - Loads point defined by latlng and adds a marker. If info has a value, puts it in an info bubble.
// Google.map.addMarkerByAddress(address,info) - loads point defined by address and adds a marker. If info has a value, puts it in a info bubble.
// Google.map.setCenterByAddress(address) - sets the center of map to a provided address.
// Google.map.loadFromHCard(card, map, zoom) - Loads a map, gets the address from an hcard and sets a marker there, and if zoom is provided, zooms to that level.
// 0.3.1
// Google.map.addDirections(elem) - Sets elem as a direction pane for a google map
// Google.map.getDirections(to, from) - Inserts into directions pane created through .addDirections() a series of directions to address "to" from address "from".


var BrainGnat = function() {
    return {
        version: "0.3.1",
        test: function() {
            alert('BrainGnat version ' + BrainGnat.version + ' is loading correctly.');
        },
        setContentHeight: function(verticalOffset) {
            if (!verticalOffset) {
                verticalOffset = 0;
            }
            var minContentHeight = jQuery(window).height() - (jQuery('#branding').height() + jQuery('#site_info').height() + verticalOffset);
            if (jQuery('#content').height() < minContentHeight) {
                jQuery('#content').height(minContentHeight);
            }
        },
        slideshow: {
            fadein: function(elem, imageList, slideDuration, fadeSpeed, current, frontElem) {
                var listSize = imageList.length;
                if (!current || current >= listSize) current = 0;
                if (!frontElem) frontElem = "img";
                if (!slideDuration) slideDuration = 5000;
                if (!fadeSpeed) fadeSpeed = 1000;
                if (frontElem == "img") {
                    jQuery(elem + " " + frontElem).attr("src", imageList[current]);
                } else {
                    jQuery(elem + " " + frontElem).css("background-image", "url(" + imageList[current] + ")");
                }
                if (current >= (listSize - 1)) {
                    jQuery(elem).css("background", "transparent url(" + imageList[0] + ") no-repeat");
                } else {
                    jQuery(elem).css("background", "transparent url(" + imageList[current + 1] + ") no-repeat");
                }
                jQuery(elem + " " + frontElem).animate({ opacity: "1" }, slideDuration).animate({ opacity: "0.01" }, fadeSpeed, function() { jQuery(this).css("opacity", "1"); BrainGnat.slideshow.fadein(elem, imageList, slideDuration, fadeSpeed, current + 1, frontElem) });
            },
            ajaxLoadCrossfade: function(_imglist, wrapper, frontElem, slideDuration, fadeSpeed) {
                // This function makes use of the .NET files: imageList.aspx, imageList.aspx.vb which can be found in proofs.
                if (!slideDuration) slideDuration = 5000;
                if (!fadeSpeed) fadeSpeed = 1000;
                if (!frontElem) frontElem = "img";
                var imageList = _imglist.split("|"); 
				imageList.pop(); 
				BrainGnat.slideshow.fadein(wrapper, imageList, slideDuration, fadeSpeed, 0, frontElem);
            }
        },
        stickyList: function() {
            jQuery('.stickyList > li').bind('mouseover', function() {
                jQuery('.stuck').removeClass('stuck');
                if (jQuery(this).children('ul').children().length > 0) {
                    jQuery(this).addClass('stuck');
                }
            });
            jQuery('.stickyList li ul').bind('mouseout', function() {
                jQuery(this).parent().removeClass('stuck');
            });
        },
        randomBackgroundImage: function(elem, imageList) {
            var i = Math.floor(Math.random() * imageList.length);
            jQuery(elem).css({ 'background-image': 'url(' + imageList[i] + ')' });
        },
        randomImage: function(elem, imageList) {
            var i = Math.floor(Math.random() * imageList.length);
            jQuery(elem).attr('src', imageList[i]);
        },
        html5Shiv: function() {
            var shivstring = "section|article|aside|header|footer|nav|dialog|figure|audio|video|embed|m|meter|time|canvas|command|datagrid|details|datalist|datatemplate|rule|nest|event-source|output|progress";
            var shiv = shivstring.split('|');
            for (i = 0; i < shiv.length; i++) {
                document.createElement(shiv[i]);
            }
        },
        setTabs: function(elem) {
            jQuery(elem + ' .tab').bind('click', function() {
                jQuery(elem + ' .tab').removeClass('active');
                jQuery(elem + ' .tabbedContent').removeClass('show');
                var tabClasses = jQuery(this).attr('class').split(' ');
                for (i = 0; i < tabClasses.length; i++) {
                    if (tabClasses[i] != 'tab') {
                        jQuery(elem + ' .tabbedContent.' + tabClasses[i]).addClass('show');
                    }
                }
                jQuery(this).addClass('active');
            });
        },
        Google: {
            map: {
                // Using BrainGnat.Google.map requires a MAP API Key included before this script in the project.
                load: function(elem, mapnumber) {
                    m = mapnumber;
                    if (m == null) {
                        m = 0;
                    }
                    if (GBrowserIsCompatible()) {
                        var domElem = jQuery(elem).get(0);
                        BrainGnat.Google.map.data[m] = new GMap2(domElem);
                        // BrainGnat.Google.map.data[m].addControl(new GLargeMapControl());
                        BrainGnat.Google.map.data[m].addControl(new GSmallMapControl());
                        // BrainGnat.Google.map.data[m].addControl(new GMapTypeControl());
                    } else {
                        alert('Error: BGGM1 - There was an issue loading the Google map.');
                    }
                },
                addDirections: function(elem) {
                    var directionsPanel = jQuery(elem).get(0);
                    BrainGnat.Google.map.directions = new GDirections(BrainGnat.Google.map.data, directionsPanel);
                },
                addMarker: function(latLng, info, m) {
                    var marker = new GMarker(latLng);
                    BrainGnat.Google.map.data[m].addOverlay(marker);
                    if (!info) { } else {
                        marker.openInfoWindowHtml(info);
                    }
                },
                addMarkerByAddress: function(address, info, mapcenter) {
                    m = mapcenter;
                    geocoder = new GClientGeocoder();
                    geocoder.getLatLng(address, function(point) {
                        if (!point) {
                            alert('Error: BGGM2 - Provided address does not exist.');
                        } else {
                            var marker = new GMarker(point);
                            BrainGnat.Google.map.data.addOverlay(marker);
                            if (!info) { } else {
                                marker.openInfoWindowHtml(info);
                            }
                        }
                    });
                },
                getDirections: function(to, from) {
                    geocoder = new GClientGeocoder();
                    geocoder.getLatLng(from, function(point) {
                        if (!point) {
                            alert('Error: BGGM2 - Provided address does not exist. Please make sure to include city, state, and zip code.');
                        } else {

                            BrainGnat.Google.map.directions.load("from: " + point + " to: " + to);
                        }
                    });
                },
                setCenterByAddress: function(address, zoom, mapnumber) {
                    if (!mapnumber) {
                        mapnumber = 0;
                    }
                    if (!zoom) {
                        zoom = 13;
                    }
                    m = mapnumber;
                    geocoder = new GClientGeocoder();
                    geocoder.getLatLng(address, function(point) {
                        if (!point) {
                            // alert('Error: BGGM2 - Provided address does not exist.');
                        } else {
                            var compare = address.substr(0, 5)
                            for (i = 0; i < jQuery('#dealerList .vcard .street-address').length; i++) {
                                if (compare == jQuery('#dealerList .vcard .street-address:eq(' + i + ')').html().substr(0, 5)) {
                                    BrainGnat.Google.map.addMarker(point, null, i);
                                    BrainGnat.Google.map.data[i].setCenter(point, zoom);
                                }
                            }

                        }
                    });
                },
                loadFromHCard: function(card, map, zoom, marker, mapnumber) {
                    if (!zoom || zoom == null) {
                        zoom = 13;
                    }
                    if (!mapnumber || mapnumber == null) {
                        mapnumber = 0;
                    }
                    if (!marker && marker != false) {
                        marker = null;
                    }
                    m = mapnumber;
                    BrainGnat.Google.map.load(map, m);
                    var address = "";
                    address += jQuery(card + ' .street-address').text();
                    address += ' ' + jQuery(card + ' .locality').text();
                    address += ', ' + jQuery(card + ' .region').text();
                    address += ' ' + jQuery(card + '.postal-code').text();
                    BrainGnat.Google.map.setCenterByAddress(address, zoom, m);
                    /*if (marker == null) {*/

                    /*} else if (marker == false) {
                    BrainGnat.Google.map.addMarkerByAddress(address);
                    } else {
                    BrainGnat.Google.map.addMarkerByAddress(address, marker);
                    }*/
                },
                data: Array(),
                directions: null
            }
        }
    }
} ();


/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Pre-Singleton Functions for pre-0.1.0 Backwards Compatibility 
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////

function setContentHeight(verticalOffset) {
    if (!verticalOffset) {
        verticalOffset = 0;
    }
    var minContentHeight = jQuery(window).height() - (jQuery('#branding').height() + jQuery('#site_info').height() + verticalOffset);
    if (jQuery('#content').height() < minContentHeight) {
        jQuery('#content').height(minContentHeight);
    }
}

function fadeinSlideshow(elem, imageList, slideDuration, fadeSpeed, current) {
    var listSize = imageList.length;
    if (!current || current >= listSize) current = 0;
    if (!slideDuration) slideDuration = 5000;
    if (!fadeSpeed) fadeSpeed = 1000;
    jQuery(elem + " img").attr("src", imageList[current]);
    if (current >= (listSize - 1)) {
        jQuery(elem).css("background", "transparent url(" + imageList[0] + ") no-repeat");
    } else {
        jQuery(elem).css("background", "transparent url(" + imageList[current + 1] + ") no-repeat");
    }
    jQuery(elem + " img").animate({ opacity: "1" }, slideDuration).animate({ opacity: "0.01" }, fadeSpeed, function() { jQuery(this).css("opacity", "1"); fadeinSlideshow(elem, imageList, slideDuration, fadeSpeed, current + 1) });
}

function ajaxLoadCrossfade(file, wrapper, slideDuration, fadeSpeed) {
    if (!slideDuration) slideDuration = 5000;
    if (!fadeSpeed) fadeSpeed = 1000;
    jQuery.get(file, function(data) { fadeinSlideshow(wrapper, data.split(" "), slideDuration, fadeSpeed); });
}

function stickyList() {
    jQuery('.stickyList > li').bind('mouseover', function() {
        jQuery('.stuck').removeClass('stuck');
        if (jQuery(this).children('ul').children().length > 0) {
            jQuery(this).addClass('stuck');
        }
    });
}

function rotateImage() {
    BrainGnat.slideshow.ajaxLoadCrossfade('images/st_banner08.jpg|images/st_banner07.jpg|images/st_banner06.jpg|images/st_banner05.jpg|images/st_banner04.jpg|images/st_banner03.jpg|images/st_banner02.jpg|images/st_banner01.jpg', '#banner', 'img', 5000, 1000);
}

addLoadEvent(rotateImage);

