﻿var gallery = [];
var $images = []
var getsTitles = false;
var getsScroll = false;
var scrollWidth = 0;
var galleryHeight = 500;
var galleryWidth = 0;
$(document).ready(function() {

    App.Init();

});
var App = {
    Init: function() {

        // Body class
        $('body').addClass('colour-' + (Math.ceil(6 * Math.random())));
        App.SetHeight();

        var mode = null;
        if ($('body.home').length) {
            mode = 'home';
        } else if ($('noscript').length) {
            mode = 'gallery';
        }

        switch (mode) {
            case "home":
                Home.Init();
                break;
            case "gallery":
                Gallery.Init();
                break;
        }

        if ($('form').length) { Form.Init(); }


    },
    SetHeight: function() {
        if ($(window).height() < 800) {
            $('body').addClass('short');
        } else {
            $('body').removeClass('short');
        }
    }
}
var Home = {
    Init: function() {
		$('div.feature-image div.images').innerfade({ speed: 1000, timeout: 6000 });
    }
}
var Form = {
    Init: function() {
        $('input[type="text"], textarea').labelswitch();
        $('input[type="image"]').mouseover(Form.Events.ButtonActive);
        $('input[type="image"]').focus(Form.Events.ButtonActive);
        $('input[type="image"]').mouseout(Form.Events.ButtonInactive);
        $('input[type="image"]').blur(Form.Events.ButtonInactive);
        $('input[type="image"]').click(Form.Events.Validate);
    },
    Events: {
        ButtonInactive: function() {
            $(this).attr('src', $(this).attr('src').replace('-on', '-off'));
        },
        ButtonActive: function() {
            $(this).attr('src', $(this).attr('src').replace('-off', '-on'));
        },
        Validate: function() {
            var blnError = false;
            var $form = $(this).parents('form');
            $form.find('input[type="text"], textarea').each(function() {
                if ($(this).val() == $(this).prev().text()) {
                    $(this).parent().addClass('error');
                    blnError = true;
                } else {
                    $(this).parent().removeClass('error');
                }
            });
            if (blnError) {
                $form.find('p.prompt').addClass('error').text('Please complete all form fields correctly');
                return false;
            }
        }
    }
}
var Gallery = {
    Init: function() {
        getsTitles = !$.browser.msie;
        getsScroll = !($.browser.msie && $.browser.version < 8);
        galleryWidth = $(window).width();
        galleryHeight = getsScroll ? galleryHeight + 20 : galleryHeight + 16;
        $('h1').parent().after('<div id="gallery-wrap"><div id="gallery-loading" style="width:' + galleryWidth + 'px;height:' + galleryHeight + 'px"><span>Loading</span></div><div id="gallery-hide" style="overflow: hidden; width: 0px; height: 0px;"><div id="gallery" style="display:none;width:' + galleryWidth + 'px;height:' + galleryHeight + 'px"><div id="gallery-scroll"></div></div></div></div>');
        $images = $(gallery)[0].images;
        var $galleryScroll = $('#gallery-scroll');
        $('#gallery-scroll').width(0);
        layoutImage(0);
    }
}
function layoutImage(i) {
    var imgWidth = $images[i].width * 1;
    var $galleryScroll = $('#gallery-scroll');
    scrollWidth += imgWidth;
    $galleryScroll.width(scrollWidth);
    $galleryScroll.append('<div class="gallery-image pending" style="width:' + imgWidth + 'px;" />');
    if (i < $images.length - 1) {
        layoutImage(i + 1);
    } else {
        if (getsScroll) {
            $('#gallery').jScrollHorizontalPane();
        }
        var wait = setTimeout(function() {
            $('#gallery-loading').remove();
            if (getsScroll) {
                $('#gallery-hide').replaceWith($('div.jScrollPaneContainer'));
                $('#gallery').fadeIn('slow');
            } else {
                $('#gallery-wrap').replaceWith($('#gallery'));
                $('#gallery').show();
            }
            $('h1').append('<span class="loading">Loading <span>1</span> of ' + $images.length + '</span>');
            loadImage(0);
        }, 1000);
    }
}
function loadImage(i) {
    var imgSrc = $images[i].source;
    var credit = $images[i].credit;
    var galleryImage = new Image();
    var $galleryScroll = $('#gallery-scroll');
    var $divImageContainer = $('#gallery-scroll div.gallery-image:nth-child(' + (i + 1) + ')');
    $('h1 span.loading span').text(i + 1);
    $divImageContainer.removeClass('pending').addClass('loading');
    $(galleryImage).load(function() {
        galleryImage.onload = null;
        if ($images[i].width != galleryImage.width) { 
        	console.log('{"source" : "'+imgSrc+'" , "credit" : "" , "width" : "'+galleryImage.width+'"},');
        	// console.log(i, $images[i].width, galleryImage.width); 
        }
        var $divImage = $('<div class="image" style="display:none;"><img src="' + imgSrc + '" /></div>');
        var $divCaption = $('<div class="caption" style="width:' + galleryImage.width + 'px;display:none;"><p>#' + (i + 1) + (credit == '' ? '' : ': ' + credit) + '</p></div>');
        $divImageContainer.removeClass('loading').append($divImage).append($divCaption);
        $divImage.fadeIn(200, function() {
            if (!getsTitles) { $galleryScroll.find('div.caption').show(); }
            if (i < $images.length - 1) {
                loadImage(i + 1);
            } else {
                finishUp();
            }
        });
    }).attr('src', imgSrc);
}
function finishUp() {
    $('h1 span.loading').fadeOut(500, function() {
        $(this).remove();
    });
    // if (getsTitles) {
    //     $('div.gallery-image').titleize();
    // }

    $(window).wresize(function() {
        App.SetHeight();
        $('#gallery').width($(window).width());
        if (getsScroll) { $('#gallery').jScrollHorizontalPane(); }

    });
}
(function($) {
    $.fn.titleize = function() {
        return this.each(function() {
            var $this = $(this);
            var $jDetails = $(this).find('div.caption');
            var intFadeOutDelay = 500;
            var intFadeSpeed = 500;
            var originalOpacity = $jDetails.css('opacity');
            var init = function() {
                $this.attr('id', 'img' + Math.floor(99999 * Math.random()));
                $this.find('div.caption').hide();
            };
            var showInfo = function() {
                if ($this.hasClass('if')) {
                    return;
                } else if ($this.hasClass('ifi')) {
                    return;
                } else if ($this.hasClass('ifo')) {
                    $jDetails.stop();
                    $jDetails.css('opacity', originalOpacity);
                    $this.removeClass('ifo').addClass('if');
                } else if ($this.hasClass('ifop')) {
                    removePendingStamps();
                    $this.removeClass('ifop').addClass('if');
                } else {
                    fadeInfoIn();
                }
            };
            var hideInfo = function() {
                if ($this.hasClass('if')) {
                    fadeInfoOut();
                } else if ($this.hasClass('ifi')) {
                    var tmrFadeOut = setTimeout(function() {
                        hideInfo();
                    }, intFadeOutDelay);
                    return;
                } else if ($this.hasClass('ifo')) {
                    return;
                } else if ($this.hasClass('ifop')) {
                    return;
                } else {
                    return;
                }
            };
            var fadeInfoIn = function() {
                $this.addClass('ifi');
                $jDetails.fadeIn(intFadeSpeed, function() {
                    $this.removeClass('ifi').addClass('if');
                });
            };
            var fadeInfoOut = function() {
                var strStamp = 's-' + Math.floor(99999 * Math.random());
                removePendingStamps();
                $this.addClass('ifop ' + strStamp).removeClass('if');
                var tmrFadeOut = setTimeout(function() {
                    if (!$this.hasClass('ifop') || !$this.hasClass(strStamp)) { return; }
                    $this.addClass('ifo').removeClass('ifop ' + strStamp);
                    $jDetails.fadeOut(intFadeSpeed, function() {
                        $this.removeClass('ifo');
                        removePendingStamps();
                    });
                }, intFadeOutDelay);
            };
            var removePendingStamps = function() {
                var strClass = $this.attr('class');
                strClass = strClass.replace(/s-[0-9]+/g, '');
                $this.attr('class', strClass);
            }
            init();
            $this.hoverIntent({ sensitivity: 1, interval: 200, over: showInfo, out: hideInfo });
        });
    };
})(jQuery);
/**
* hoverIntent is similar to jQuery's built-in "hover" function except that
* instead of firing the onMouseOver event immediately, hoverIntent checks
* to see if the user's mouse has slowed down (beneath the sensitivity
* threshold) before firing the onMouseOver event.
* 
* hoverIntent r5 // 2007.03.27 // jQuery 1.1.2+
* <http://cherne.net/brian/resources/jquery.hoverIntent.html>
* 
* hoverIntent is currently available for use in all personal or commercial 
* projects under both MIT and GPL licenses. This means that you can choose 
* the license that best suits your project, and use it accordingly.
* 
* // basic usage (just like .hover) receives onMouseOver and onMouseOut functions
* $("ul li").hoverIntent( showNav , hideNav );
* 
* // advanced usage receives configuration object only
* $("ul li").hoverIntent({
*	sensitivity: 7, // number = sensitivity threshold (must be 1 or higher)
*	interval: 100,   // number = milliseconds of polling interval
*	over: showNav,  // function = onMouseOver callback (required)
*	timeout: 0,   // number = milliseconds delay before onMouseOut function call
*	out: hideNav    // function = onMouseOut callback (required)
* });
* 
* @param  f  onMouseOver function || An object with configuration options
* @param  g  onMouseOut function  || Nothing (use configuration options object)
* @author    Brian Cherne <brian@cherne.net>
*/
(function($) {
    $.fn.hoverIntent = function(f, g) {
        // default configuration options
        var cfg = {
            sensitivity: 7,
            interval: 200,
            timeout: 0
        };
        // override configuration options with user supplied object
        cfg = $.extend(cfg, g ? { over: f, out: g} : f);

        // instantiate variables
        // cX, cY = current X and Y position of mouse, updated by mousemove event
        // pX, pY = previous X and Y position of mouse, set by mouseover and polling interval
        var cX, cY, pX, pY;

        // A private function for getting mouse position
        var track = function(ev) {
            cX = ev.pageX;
            cY = ev.pageY;
        };

        // A private function for comparing current and previous mouse position
        var compare = function(ev, ob) {
            ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
            // compare mouse positions to see if they've crossed the threshold
            if ((Math.abs(pX - cX) + Math.abs(pY - cY)) < cfg.sensitivity) {
                $(ob).unbind("mousemove", track);
                // set hoverIntent state to true (so mouseOut can be called)
                ob.hoverIntent_s = 1;
                return cfg.over.apply(ob, [ev]);
            } else {
                // set previous coordinates for next time
                pX = cX; pY = cY;
                // use self-calling timeout, guarantees intervals are spaced out properly (avoids JavaScript timer bugs)
                ob.hoverIntent_t = setTimeout(function() { compare(ev, ob); }, cfg.interval);
            }
        };

        // A private function for delaying the mouseOut function
        var delay = function(ev, ob) {
            ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
            ob.hoverIntent_s = 0;
            return cfg.out.apply(ob, [ev]);
        };

        // A private function for handling mouse 'hovering'
        var handleHover = function(e) {
            // next three lines copied from jQuery.hover, ignore children onMouseOver/onMouseOut
            var p = (e.type == "mouseover" ? e.fromElement : e.toElement) || e.relatedTarget;
            while (p && p != this) { try { p = p.parentNode; } catch (e) { p = this; } }
            if (p == this) { return false; }

            // copy objects to be passed into t (required for event object to be passed in IE)
            var ev = jQuery.extend({}, e);
            var ob = this;

            // cancel hoverIntent timer if it exists
            if (ob.hoverIntent_t) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); }

            // else e.type == "onmouseover"
            if (e.type == "mouseover") {
                // set "previous" X and Y position based on initial entry point
                pX = ev.pageX; pY = ev.pageY;
                // update "current" X and Y position based on mousemove
                $(ob).bind("mousemove", track);
                // start polling interval (self-calling timeout) to compare mouse coordinates over time
                if (ob.hoverIntent_s != 1) { ob.hoverIntent_t = setTimeout(function() { compare(ev, ob); }, cfg.interval); }

                // else e.type == "onmouseout"
            } else {
                // unbind expensive mousemove event
                $(ob).unbind("mousemove", track);
                // if hoverIntent state is true, then call the mouseOut function after the specified delay
                if (ob.hoverIntent_s == 1) { ob.hoverIntent_t = setTimeout(function() { delay(ev, ob); }, cfg.timeout); }
            }
        };

        // bind the function to the two event listeners
        return this.mouseover(handleHover).mouseout(handleHover);
    };
})(jQuery);
