/*!
 * 
 */
function addEvent( obj, type, fn ) {
  if ( obj!=null && obj.attachEvent ) {
    obj['e'+type+fn] = fn;
    obj[type+fn] = function(){obj['e'+type+fn]( window.event );}
    obj.attachEvent( 'on'+type, obj[type+fn] );
  } else
	  if(obj!=null)
    {obj.addEventListener( type, fn, false );}
}
(function(window, undefined) {

    var d = window.document, w = window,
        tab_count = 1,
        toString = Object.prototype.toString;
    
    var idea = {
        timers: [],
        clearTimer: function(idx) { // Used to clean up timers used by the idea object
            clearTimeout(idea.timers[idx]);
            idea.timers[idx] = null;
        },
        isArray: function( obj ) { // Check if something is an array
            return toString.call(obj) === "[object Array]";
        },
        trim: function(str) { // Trim the whitespace from both sides of a string
            return str.replace(/^\s+|\s+$/g, '');
        },
        getSiblings: function(elem) { // create an array of all the siblings of an element
            var r = [];
            for(var n = elem.parentNode.firstChild; n; n = n.nextSibling) {
                if(n.nodeType === 1 && n !== elem) {
                    r.push(n);
                }
            }
            return r;
        },
        /* This is not working, but I don't currently know why. I think there is a scope problem * /
        addEvent: function( obj, type, fn ) {
            var i, l;
            if(idea.isArray(obj)) {
                for(i = 0, l = obj.length; i < l; i++) {
                    idea.addEvent(obj[i], type, fn);
                }
            } else {
                type = type.split(' ');
                for(i = 0, l = type.length; i < l; i++) {
                    if ( obj.attachEvent ) {
                        obj['e'+type[i]+fn] = fn;
                        obj[type[i]+fn] = function(){obj['e'+type[i]+fn]( window.event );}
                        obj.attachEvent( 'on'+type[i], obj[type[i]+fn] );
                    } else
                        obj.addEventListener( type[i], fn, false );
                }
            }
        },
        /* Create tabs. Returns the index of the timer. */
        tabs: function(obj, options) {
            var defaults = { // The default options.
                activeTab: 'tab-active',
                activePanel: 'tab-active-panel',
                delay: 0,
                event: 'click',
                before: function() {},
                after: function() {},
                tabs: null,
                panels: null
            }, opts = {};
            
            for(var p in defaults) { // create a new object built from user-defined options and the defaults
                opts[p] = options ? options[p] || defaults[p] : defaults[p];
            }

            var tabs = opts.tabs || obj.getElementsByTagName('ul')[0].getElementsByTagName('a'),
                panels = opts.panels || function() { // If panels is not defined, assume they are children of the object and DIVs
                    var children = obj.childNodes,
                        panels = [];
                    for(var i = 0, l = children.length; i < l; i++) {
                        if(children[i].nodeName.toLowerCase() == 'div') {
                            panels.push(children[i]);
                        }
                    }
                    return panels;
                }(),
                t = idea.timers.push(null),
                timer = t-1,
                activeTabRegex = new RegExp('\\b'+opts.activeTab+'\\b'),
                activePanelRegex = new RegExp("\\b"+opts.activePanel+"\\b");

            for(var i = 0, l = tabs.length; i < l; i++) {
                if( ! tabs[i].id) { // Give the tab an id if it doesn't already have one
                    tabs[i].id = 'tab-'+tab_count++;
                }
                if (panels[i] != null) {
                    panels[i].setAttribute('data-tab', tabs[i].id); // give the panel a reference to the id
                }

                addEvent(tabs[i], opts.event, function(ev) {
                    ev = ev || window.event;
                    ev.stopPropagation ? ev.stopPropagation() : ev.cancelBubble = true;
                    ev.preventDefault ? ev.preventDefault() : ev.returnValue = false;
                    clearTimeout(idea.timers[timer]);
                    idea.timers[timer] = null;
                    opts.before();
                    var self = this;
                    if(opts.delay > 0) {
                        idea.timers[timer] = setTimeout(function() {
                            switchTabs(self);
                        }, opts.delay);
                    } else {
                        switchTabs(self);
                    }
                    opts.after();
                });
            }
            
            return timer;

            // Used to switch the tabs
            function switchTabs(tab) {
                var siblings;
                if(tab.nodeName.toLowerCase() != 'li') {
                    tab.parentNode.className += ' '+opts.activeTab;
                } else {
                    tab.className += ' '+opts.activeTab;
                }
                siblings = idea.getSiblings(tab.nodeName.toLowerCase() == 'li' ? tab : tab.parentNode);
                for(var i = 0, l = siblings.length; i < l; i++) {
                    siblings[i].className = idea.trim(siblings[i].className.replace(activeTabRegex, ''));
                }
                var panel = function() {
                    for(i = 0, l = panels.length; i < l; i++) {
                        if(panels[i].getAttribute('data-tab') == tab.id) {
                            return panels[i];
                        }
                    }
                    return false;
                }();
                if(panel && ! panel.className.match(activePanelRegex)) {
                    panel.className += ' '+opts.activePanel;
                    siblings = idea.getSiblings(panel);
                    for(i = 0, l = siblings.length; i < l; i++) {
                        siblings[i].className = idea.trim(siblings[i].className.replace(activePanelRegex, ''));
                    }
                }
            }
        },
        /* Accordion functionality */
        accordion: function(obj, options) {
            var defaults = {
                activeClass: 'accordion-active',
                delay: 0,
                event: 'click',
                before: function() {},
                after: function() {},
                handle: 'a',
                sections: null
            }, opts = {};

            for(var p in defaults) {
                opts[p] = options ? options[p] || defaults[p] : defaults[p];
            }
            
            var sections = $( obj ).find( '.expanderPlusMinus' ),
            	activeClassRegex = new RegExp('\\b'+opts.activeClass+'\\b');

            for(var i = 0, l = sections.length; i < l; i++) {
                var handle = sections[i].getElementsByTagName(opts.handle)[0];
                if(handle) {
                    handle.setAttribute('data-section-index', i);
                    addEvent(handle, 'click', function(ev) {
                        ev = ev || window.event;
                        ev.stopPropagation ? ev.stopPropagation() : ev.cancelBubble = true;
                        ev.preventDefault ? ev.preventDefault() : ev.returnValue = false;
                        var idx = this.getAttribute('data-section-index');
                        if(sections[idx].className.match(activeClassRegex)) {
                            sections[idx].className = idea.trim(sections[idx].className.replace(activeClassRegex, ' '));
                        } else {
                            sections[idx].className += ' ' + opts.activeClass;
                        }
                        //this.blur(); // Not sure if we need this or not
                    });
                }
            }
        },
        pagingCarousel: function(obj, options) {
            var defaults = {
                autoRotate: false,
                classPrefix: 'paging-carousel',
                itemsPerPage: 5,
                navPos: 'below',
                navTemplate: '<div class="#prefix#-nav">\n\
                    <a href="#" class="#prefix#-prev">prev</a> <span class="#prefix#-text"></span> <a href="#" class="#prefix#-next">next</a>\n\
                </div>',
                startPage: 1,
                text: '#start# - #last# of #total#'
            }, opts = {};

            for(var p in defaults) {
                opts[p] = options ? options[p] || defaults[p] : defaults[p];
            }
            // force first page right now.
            opts.startPage = 1;

            var children = (function(obj) {
                var child = obj.childNodes[0],
                    rArr = [];

                while(child) {
                    if(child.nodeType == 1) {
                        rArr.push(child);
                    }
                    child = child.nextSibling;
                }
                return rArr;
            })(obj),
                itemCount = children.length,
                itemWidth = children[0].offsetWidth,
                parent = obj.parentNode,
                currentPage = opts.startPage,
                totalPages = Math.ceil(itemCount/opts.itemsPerPage);

            if(itemCount <= opts.itemsPerPage) {
                return;
            }

            obj.style.width = itemWidth*children.length+'px';
            obj.className += ' '+opts.classPrefix+'-list';

            var wrap = document.createElement('div');
            wrap.className = opts.classPrefix+'-wrap';

            parent.appendChild(wrap);
            wrap.appendChild(obj);

            var template = opts.navTemplate.replace(/#prefix#/g, opts.classPrefix);

            if(opts.navPos == 'below') {
                parent.innerHTML += template;
            } else {
                parent.innerHTML = template+parent.innerHTML;
            }

            var nav;
            for(var i = 0, l = parent.childNodes.length; i < l; i++) {
                if(parent.childNodes[i].nodeType == 1) {
                    if(parent.childNodes[i].className.match(new RegExp('\\b'+opts.classPrefix+'-nav\\b'))) {
                        nav = parent.childNodes[i];
                    } else if(parent.childNodes[i].className.match(new RegExp('\\b'+opts.classPrefix+'-wrap\\b'))) {
                        wrap = parent.childNodes[i];
                        obj = wrap.getElementsByTagName(obj.nodeName)[0];
                    }
                }
            }
            var text, spans = nav.getElementsByTagName('span');
            for(i = 0, l = spans.length; i < l; i++) {
                if(spans[i].className.match(new RegExp('\\b'+opts.classPrefix+'-text\\b'))) {
                    text = spans[i];
                    updateText(opts.text, text);
                    break;
                }
            }
            var navLinks = nav.getElementsByTagName('a');
            for(i = 0, l = navLinks.length; i < l; i++) {
                if(navLinks[i].className.match(new RegExp('\\b'+opts.classPrefix+'-prev\\b'))) {
                    addEvent(navLinks[i], 'click', function(ev) {
                        ev.preventDefault ? ev.preventDefault() : ev.returnValue = false;
                        if(currentPage != 1) {
                            currentPage--;
                            obj.style.left = parseInt(obj.style.left)+(itemWidth*opts.itemsPerPage)+'px';
                            updateText(opts.text, text);
                        }
                        this.blur();
                    });
                }
                if(navLinks[i].className.match(new RegExp('\\b'+opts.classPrefix+'-next\\b'))) {
                    addEvent(navLinks[i], 'click', function(ev) {
                        ev.preventDefault ? ev.preventDefault() : ev.returnValue = false;
                        if(currentPage != totalPages) {
                            currentPage++;
                            obj.style.left = -(currentPage-1)*(itemWidth*opts.itemsPerPage)+'px';
                            updateText(opts.text, text);
                        }
                        this.blur();
                    });
                }
            }

            function updateText(text, obj) {
                text = text.replace(/#start#/g, (currentPage*opts.itemsPerPage)-(opts.itemsPerPage-1))
                    .replace(/#last#/g, currentPage*opts.itemsPerPage < itemCount ? currentPage*opts.itemsPerPage : itemCount)
                    .replace(/#total#/g, itemCount);
                obj.innerHTML = text;
            }
        }
    };

    // Expose the idea object.
    window.idea = idea;
})(window);


$(document).ready(function() {
	
	$("ul.gallery li").hover(function() { //On hover...
		
		var thumbOver = $(this).find("img").attr("src"); //Get image url and assign it to 'thumbOver'
		
		//Set a background image(thumbOver) on the &lt;a&gt; tag 
		$(this).find("a.thumb").css({'background' : 'url(' + thumbOver + ') no-repeat center bottom'});
		//Fade the image to 0 
		$(this).find("span").stop().fadeTo('normal', 0 , function() {
			$(this).hide() //Hide the image after fade
		}); 
	} , function() { //on hover out...
		//Fade the image to 1 
		$(this).find("span").stop().fadeTo('normal', 1).show();
	});

});

