/// <reference path="jquery-vsdoc.js" />
//*************************************************************************************
// File     : braingnat.js
// Version  : 0.4.9
// Requires : jquery.js (version 1.4.2+)
// Author   : Kyle Weems (ksw)
// Origin   : mindfly.com
// Created  : Jul 29, 2008
// Modified : Sep 07, 2010
// 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.map functions added. Moved to an extension script in 0.4.0
// 0.3.1
// Google.map functions upgraded. Moved to an extension script in 0.4.0
// 0.3.2
// Google.map functions upgraded. Moved to an extension script in 0.4.0
// 0.3.3
// Updated slideshow.ajaxLoadCrossfade as follows:
// slideshow.ajaxLoadCrossfade(file as string, wrapper as string, frontElem as string, slideDuration as integer, fadeSpeed as integer, random as boolean)
// - file is the name of a file that is holding the list of images to rotate
// - wrapper is the CSS selector of the element that holds the image that the slideshow takes place on
// - frontElem is the CSS selector of the image (in relation to the wrapper) that the slideshow takes place on. Default is "img"
// - slideDuration is the time in milliseconds between slides. Default is 5000 ms.
// - fadeSpeed is the time the transition takes. Default is 1000 ms.
// - random determines whether the images rotate in the order loaded, or in random order. Default is false.
// 0.4.0
// BrainGnat.Google has been spun out into a separate script that must be included in projects that make use of it.
// Syntax is the same, it merely exists as an extension now.
// 0.4.5 Added slideshow.panelSlide(panel as string, control as string, defaultPos as integer, activePos as integer)
// - panel is the CSS identifier for the panels used in the slideshow (typically LIs of some sort)
// - control is the css identifier for the "controls" used to select the panels for the slideshow
// - defaultPos is the left offset of the panels while they are hidden
// - activePos is the left offest when a panel is visible
// 0.4.6 
// - Added BrainGnat.fields.clearOnFocus()
// - This function makes it so that input and textarea boxes clear their pre-assigned values if selected, and return them if they're empty when blurred.
// 0.4.7
// - Added BrainGnat.slideshow.listFade(list as string, slideDuration as integer, fadeSpeed as integer) 
// - "list" is the CSS selector for the unordered or ordered list that contains the slideshow.
// - slideDuration is the time in milliseconds that the slides stay on the page
// - fadeSpeed is the time in milliseconds that the slide takes to fade to the next slide.
// 0.4.8
// - Added BrainGnat.slideshow.loadViaSpan(url as string)
// - "url" is the location of a control or file that is capable of listing (dynamically or otherwise) the image contents of a directory.
// - This control will seek out a span that contains the string "bg-gallery", if any exists, it'll search for parameters inside it, and use them to populate a rotator.
// - The valid parameters are: dir, duration, element, fade, random. Dir is the directory for the images. Duration is the length a slide lasts. Element is the wrapper
// - for the rotator. Fade is how quickly a slide fades. Random is whether it is random or not. The format is: <span>bg-gallery dir=/images/ element=#rotator</span>
// - Both dir and element are mandatory in the span. The others are not.
// 0.4.9
// - Added BrainGnat.slideshow.galleryListFader(list as string, duration as integer, fade as integer)
// - list is the css selector for the list that contains the slideshow
// - duration and fade are the milliseconds that the slides last and change, respectively
// - This control creates a caption-enhanced cross-fading slideshow.
var BrainGnat = function() {
    return {
        version: "0.4.9",
        test: function() {
            alert('BrainGnat version ' + BrainGnat.version + ' is loading correctly.');
        },
        setContentHeight: function(verticalOffset) {
            if (!verticalOffset) {
                verticalOffset = 0;
            }
            var minContentHeight = $(window).height() - ($('#branding').height() + $('#site_info').height() + verticalOffset);
            if ($('#content').height() < minContentHeight) {
                $('#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") {
                    $(elem + " " + frontElem).attr("src", imageList[current]);
                } else {
                    $(elem + " " + frontElem).css("background-image", "url(" + imageList[current] + ")");
                }
                if (current >= (listSize - 1)) {
                    $(elem).css("background", "transparent url(" + imageList[0] + ") no-repeat");
                } else {
                    $(elem).css("background", "transparent url(" + imageList[current + 1] + ") no-repeat");
                }
                $(elem + " " + frontElem).animate({ opacity: "1" }, slideDuration).animate({ opacity: "0.01" }, fadeSpeed, function() { $(this).css("opacity", "1"); BrainGnat.slideshow.fadein(elem, imageList, slideDuration, fadeSpeed, current + 1, frontElem) });
            },
            ajaxLoadCrossfade: function(file, wrapper, frontElem, slideDuration, fadeSpeed, random) {
                // 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";
                if (!random || random == null) random = false;
                $.get(file, function(data) {
                    var imageList = data.split("|");
                    imageList.pop();
                    if (random == false) {
                        BrainGnat.slideshow.fadein(wrapper, imageList, slideDuration, fadeSpeed, 0, frontElem);
                    } else {
                        var newList = new Array();
                        var j = 0;
                        while (imageList.length > 0) {
                            var i = Math.floor(Math.random() * imageList.length);
                            newList[j] = imageList[i];
                            j++;
                            if (imageList.length > 1) {
                                for (k = i; k < (imageList.length - 1); k++) {
                                    imageList[k] = imageList[k + 1];
                                }
                            }
                            imageList.pop();
                        }
                        BrainGnat.slideshow.fadein(wrapper, newList, slideDuration, fadeSpeed, 0, frontElem);
                    }
                });

            },
            loadViaSpan: function(url) {
                if ($('span:contains("bg-gallery")').length > 0) {
                    var h = $('span:contains("bg-gallery")').html();
                    var attributes = h.split(" ");
                    var dir = "";
                    var elem = "";
                    var dur = 5000;
                    var fade = 1000;
                    var random = true;
                    for (i = 0; i < attributes.length; i++) {
                        var key = attributes[i].split("=")[0];
                        var value = attributes[i].split("=")[1];
                        switch (key) {
                            case "dir":
                                dir = value;
                                break;
                            case "element":
                                elem = value;
                                break;
                            case "duration":
                                dur = value * 1;
                            case "fade":
                                fade = value * 1;
                            case "random":
                                if (value == "false") {
                                    random = false;
                                }
                                break;
                            default:
                                break;
                        }
                    }
                    BrainGnat.slideshow.ajaxLoadCrossfade(url + dir, elem, null, dur, fade, random);
                    $('span:contains("bg-gallery")').remove();
                }
            },
            listFade: function(list, slideDuration, fadeSpeed) {
                if ($(list + ' li.current').length < 1) {
                    $(list + ' li:last-child').addClass('current');
                } else {
                    $(list + ' .fade').removeClass('fade');
                    var i = $(list + ' .current').index(list + ' li');
                    if (i > 0) {
                        $(list + ' .current').addClass('fade');
                        $(list + ' .fade').animate({ opacity: 0 }, fadeSpeed);

                    } else {
                        $(list + ' li:last-child').animate({ opacity: 1 }, fadeSpeed, function() {
                            $(this).siblings().css({ opacity: 1 });
                        });
                    }
                    if (i > 0) {
                        i--;
                    } else {
                        i = $(list + ' li').length;
                    }
                    $(list + ' .current').removeClass('current');
                    $(list + ' li:eq(' + i + ')').addClass('current');
                }
                var t = setTimeout("BrainGnat.slideshow.listFade('" + list + "', " + slideDuration + ", " + fadeSpeed + " );", (fadeSpeed + slideDuration));

            },
            panelSlide: function(panel, control, defaultPos, activePos) {
                BrainGnat.slideshow.psPanel = panel;
                BrainGnat.slideshow.psControl = control;
                BrainGnat.slideshow.psDefault = defaultPos;
                BrainGnat.slideshow.psActive = activePos;
                $(panel + ':first-child').addClass('current');
                $(control + ':first-child').addClass('active');
                var li = null;
                for (i = 0; i < $(panel).length; i++) {
                    li = $(panel + ':eq(' + i + ')');
                    if (!li.hasClass('current')) {
                        li.css('left', defaultPos + 'px');
                    }
                }
                $(control + ' a').live('click', function() {
                    var p = BrainGnat.slideshow.psPanel;
                    var c = BrainGnat.slideshow.psControl;
                    var dp = BrainGnat.slideshow.psDefault;
                    var da = BrainGnat.slideshow.psActive;
                    if ($(p + '.new').length < 1) {
                        var i = $(c + ' a').index(this);
                        var old_i = $(p).index($(p + '.current'));
                        if (i != old_i) {
                            clearTimeout(t);
                            $(c + '.active').removeClass('active');
                            $(this).parent().addClass('active');
                            var li = $(p + ':eq(' + i + ')');
                            li.addClass('new');
                            li.animate({ left: '0px' }, 1000, 'swing', function() {
                                $(p + '.current').css('left', dp + 'px');
                                $(p + '.current').removeClass('current');
                                $(p + '.new').addClass('current');
                                $(p + '.new').removeClass('new');
                                t = setTimeout("BrainGnat.slideshow.panelSlideAuto();", 10000);
                            });
                        }
                        $(this).blur();
                    }
                    return false;
                });
                t = setTimeout("BrainGnat.slideshow.panelSlideAuto();", 10000);
            },
            panelSlideAuto: function() {
                var p = BrainGnat.slideshow.psPanel;
                var control = BrainGnat.slideshow.psControl;
                var dp = BrainGnat.slideshow.psDefault;
                var da = BrainGnat.slideshow.psActive;
                var c = $(p).index($(p + '.current'));
                var n = c + 1;
                if (n == $(p).length) {
                    n = 0;
                }
                $(control + '.active').removeClass('active');
                $(control + ':eq(' + n + ')').addClass('active');
                c = $(p + ':eq(' + c + ')');
                n = $(p + ':eq(' + n + ')');
                n.addClass('new');
                n.animate({ left: da + 'px' }, 1000, 'swing', function() {
                    c.css('left', dp + 'px');
                    c.removeClass('current');
                    n.addClass('current');
                    n.removeClass('new');
                    t = setTimeout("BrainGnat.slideshow.panelSlideAuto();", 10000);
                });
            },
            galleryListFader: function(list, duration, fade) {
                if (!duration) {
                    duration = 5000;
                }
                if (!fade) {
                    fade = 1000;
                }
                var l = $(list);
                BrainGnat.slideshow.glfList = list;
                BrainGnat.slideshow.glfDuration = duration;
                BrainGnat.slideshow.glfFade = fade;
                l.before("<div id='fader'><img src='' alt=''/><span class='caption'>&nbsp;</span>");
                $('#fader').before("<div id='faderWrapper'></div>");
                $('#faderWrapper').append($('#fader'));
                $('#faderWrapper').append($(list));
                $(list + ' li:first-child').addClass('current');
                $('#fader img').attr('src', $(list + ' .current img').attr('src'));
                $('#fader .caption').html($(list + ' .current img').attr('alt'));
                $('#fader .caption').css({ top: (454 - $('#fader .caption').outerHeight()) + 'px' });
                $('#fader').css('background', "transparent url(" + $(list + ' .current + li img').attr('src') + ") no-repeat left top");
                $(list + ' img').click(function() { BrainGnat.slideshow.galleryListFaderClick($(BrainGnat.slideshow.glfList + ' img').index($(this))); });
                BrainGnat.slideshow.glfTimeout = setTimeout("BrainGnat.slideshow.galleryListFaderAuto();", duration);
            },
            galleryListFaderAuto: function() {
                $('#fader img').animate({ opacity: 0 }, BrainGnat.slideshow.glfFade, function() {
                    var list = BrainGnat.slideshow.glfList;
                    var oc = $(list + ' li.current');
                    var i = $(list + ' li').index(oc);
                    i++;
                    if (i > ($(list + ' li').length - 1)) {
                        i = 0;
                    }
                    oc.removeClass('current');
                    $(list + ' li:eq(' + i + ')').addClass('current');
                    $('#fader img').attr('src', $(list + ' .current img').attr('src'));
                    $('#fader img').css({ opacity: 1 });
                    $('#fader .caption').html($(list + ' .current img').attr('alt'));
                    $('#fader .caption').css({ top: (454 - $('#fader .caption').outerHeight()) + 'px' });
                    if (i < ($(list + ' li').length - 1)) {
                        $('#fader').css('background', "transparent url(" + $(list + ' .current + li img').attr('src') + ") no-repeat left top");
                    } else {
                        $('#fader').css('background', "transparent url(" + $(list + ' li:first-child img').attr('src') + ") no-repeat left top");
                    }
                    BrainGnat.slideshow.glfTimeout = setTimeout("BrainGnat.slideshow.galleryListFaderAuto();", BrainGnat.slideshow.glfDuration);
                });
            },
            galleryListFaderClick: function(i) {
                var list = BrainGnat.slideshow.glfList;
                clearTimeout(BrainGnat.slideshow.glfTimeout);
                $(list + ' .current').removeClass('current');
                $(list + ' li:eq(' + i + ')').addClass('current');
                $('#fader img').attr('src', $(list + ' .current img').attr('src'));
                $('#fader .caption').html($(list + ' .current img').attr('alt'));
                $('#fader .caption').css({ top: (454 - $('#fader .caption').outerHeight()) + 'px' });
                $('#fader').css('background', "transparent url(" + $(list + ' .current + li img').attr('src') + ") no-repeat left top");
                BrainGnat.slideshow.glfTimeout = setTimeout("BrainGnat.slideshow.galleryListFaderAuto();", BrainGnat.slideshow.glfDuration);
            },
            psDefault: null,
            psActive: null,
            psPanel: null,
            psControl: null,
            glfList: null,
            glfDuration: null,
            glfFade: null,
            glfTimeout: null
        },
        fields: {
            preset: new Array(),
            clearOnFocus: function() {
                var f = $('input');
                var counter = 0;
                for (i = 0; i < f.length; i++) {
                    BrainGnat.fields.preset[counter] = $('input:eq(' + i + ')').attr('value');
                    counter++;
                }
                f = $('textarea');
                for (i = 0; i < f.length; i++) {
                    BrainGnat.fields.preset[counter] = $('textarea:eq(' + i + ')').attr('value');
                    counter++;
                }
                $('input').focus(function() {
                    var v = BrainGnat.fields.preset[$('input').index($(this))];
                    if ($(this).attr('value') == v) {
                        $(this).attr('value', '');
                    }
                });
                $('input').blur(function() {
                    var v = BrainGnat.fields.preset[$('input').index($(this))];
                    if ($(this).attr('value') == '') {
                        $(this).attr('value', v);
                    }
                });
                $('textarea').focus(function() {
                    var v = BrainGnat.fields.preset[($('input').length + $('textarea').index($(this)))];
                    if ($(this).attr('value') == v) {
                        $(this).attr('value', '');
                    }
                });
                $('textarea').blur(function() {
                    var v = BrainGnat.fields.preset[($('input').length + $('textarea').index($(this)))];
                    if ($(this).attr('value') == '') {
                        $(this).attr('value', v);
                    }
                });
            }
        },
        stickyList: function() {
            $('.stickyList > li').bind('mouseover', function() {
                $('.stuck').removeClass('stuck');
                if ($(this).children('ul').children().length > 0) {
                    $(this).addClass('stuck');
                }
            });
            $('.stickyList li ul').bind('mouseout', function() {
                $(this).parent().removeClass('stuck');
            });
        },
        randomBackgroundImage: function(elem, imageList) {
            var i = Math.floor(Math.random() * imageList.length);
            $(elem).css({ 'background-image': 'url(' + imageList[i] + ')' });
        },
        randomImage: function(elem, imageList) {
            var i = Math.floor(Math.random() * imageList.length);
            $(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) {
            $(elem + ' .tab').bind('click', function() {
                $(elem + ' .tab').removeClass('active');
                $(elem + ' .tabbedContent').removeClass('show');
                var tabClasses = $(this).attr('class').split(' ');
                for (i = 0; i < tabClasses.length; i++) {
                    if (tabClasses[i] != 'tab') {
                        $(elem + ' .tabbedContent.' + tabClasses[i]).addClass('show');
                    }
                }
                $(this).addClass('active');
            });
        }
    }
} ();


/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Pre-Singleton Functions for pre-0.1.0 Backwards Compatibility 
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////

function setContentHeight(verticalOffset) {
    if (!verticalOffset) {
        verticalOffset = 0;
    }
    var minContentHeight = $(window).height() - ($('#branding').height() + $('#site_info').height() + verticalOffset);
    if ($('#content').height() < minContentHeight) {
        $('#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;
    $(elem + " img").attr("src", imageList[current]);
    if (current >= (listSize - 1)) {
        $(elem).css("background", "transparent url(" + imageList[0] + ") no-repeat");
    } else {
        $(elem).css("background", "transparent url(" + imageList[current + 1] + ") no-repeat");
    }
    $(elem + " img").animate({ opacity: "1" }, slideDuration).animate({ opacity: "0.01" }, fadeSpeed, function() { $(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;
    $.get(file, function(data) { fadeinSlideshow(wrapper, data.split(" "), slideDuration, fadeSpeed); });
}

function stickyList() {
    $('.stickyList > li').bind('mouseover', function() {
        $('.stuck').removeClass('stuck');
        if ($(this).children('ul').children().length > 0) {
            $(this).addClass('stuck');
        }
    });
}
