if (!Ext.isSafari5) {
	Ext.isSafari5 = Ext.isSafari && /version\/5/.test(navigator.userAgent.toLowerCase());
}

Ext.Element.prototype.isVisible = function () {
	 return !this.isStyle("visibility", "hidden") && !this.isStyle("display", "none");
}

Ext.Element.prototype.center = function () {
	this.setTop((Spire.screen.height / 2) - (this.getHeight() / 2));
	this.setLeft((Spire.screen.width / 2) - (this.getWidth() / 2));
}

Ext.namespace("Spire", "Spire.app");

Spire.screen = {
	width: function () {
		if (!Ext.isIE) {
			return window.innerWidth;
		} else {
			return document.body.clientWidth;
		}
	}(),
	height: function () {
		if (!Ext.isIE) {
			return window.innerHeight;
		} else {
			return document.body.clientHeight;
		}
	}()
}

Spire.onLoad = function (fnc) {
	if (typeof window.addEventListener != "undefined") {
		window.addEventListener( "load", fnc, false );
	} else if (typeof window.attachEvent != "undefined") {
		window.attachEvent( "onload", fnc );
	} else {
		if ( window.onload != null ) {
			var oldOnload = window.onload;
			window.onload = function (e) {
				oldOnload(e);
				window[fnc]();
			};
		} else {
			window.onload = fnc;
		}
	}
}

Spire.app.Tabs = function () {
	var id = 0;
	return {
		init: function () {
			var tabPanels = Ext.query(".tab-panel");
			
			Ext.each(tabPanels, function (tp) {
				var widget = Ext.fly(tp).findParent(".widget");
				
				var tabs = Ext.query("li", tp);
				var content = Ext.query(">.bd", widget);
				
				for (var x = 0; x < tabs.length; x++) {
					tabs[x].id = "tab-button-" + id;
					
					content[x].id = "tab-content-" + id;
					content[x] = Ext.get(content[x]);
					content[x].addClass("tab-content");
					
					if (Ext.fly(tabs[x]).hasClass("active")) {
						content[x].addClass("tab-content-show");
					}
					
					id = id + 1;
				}
			});
			
			var tabs = Ext.query(".tab-panel li");
			var content = Ext.query("")
			
			Ext.select(".tab-panel").on("click", function(e, t) {
				e.preventDefault();
				
				Ext.get(t).radioClass("active");
				
				Ext.get("tab-content-" + t.id.split("-").pop()).radioClass("tab-content-show");
			}, null, {
				delegate: "li"
			});
		}
	}
}();

Ext.onReady(Spire.app.Tabs.init, Spire.app.Tabs);

Spire.app.Menu = function () {
	var showTimeout = 0;
	var hideTimeout = 0;
	var delay = 250;
	
	var Menu = function (el) {
		this.el = Ext.get(el);
		
		this.ui = {};
		
		this.ui.parent = this.el.findParent("li");
		this.ui.link = Ext.get(Ext.query("a", this.ui.parent)[0]);
		
		this.init();
	}
	
	Menu.prototype = {
		init: function () {
			this.ui.link.on("mouseover", this.show, this);
			this.ui.link.on("mouseout", this.hide, this);
			
			var subOptions = Ext.query("li", this.ui.parent);
			
			Ext.each(subOptions, function (el) {
				el = Ext.get(el);
				
				el.on("mouseover", this.cancelTimeout, this);
				el.on("mouseout", this.hide, this);
			}, this);
			
			//Ext.select("li", this.ui.parent).on("mouseover", this.cancelTimeout, this).on("mouseout", this.hide, this);
		},
		hideAll: function () {
			Ext.select("#hd .nav ul ul").hide();
		},
		show: function () {
			this.hideAll();
			
			this.cancelTimeout();
			
			showTimeout = setTimeout((function () {
				this.el.show();
			}).createDelegate(this), delay);
		},
		hide: function () {
			this.cancelTimeout();
			
			hideTimeout = setTimeout(this.hideAll.createDelegate(this), delay);
		},
		cancelTimeout: function () {
			clearTimeout(hideTimeout);
			clearTimeout(showTimeout);
		}
	};
	
	return {
		init: function () {
			var subMenu = Ext.query("#hd .nav ul ul");
			
			Ext.each(subMenu, function (el) {
				var menu = new Menu(el);
			});
		}
	}
}();

Ext.onReady(Spire.app.Menu.init, Spire.app.Menu);

Spire.app.Template = function () {
	var attachEvents = function (id, def) {
		var el = Ext.get(id);
		
		if (el) {
			el.on("focus", function (e) {
				e = e.getTarget();
				if (e.value === def) {
					e.value = "";
				}
			});
			el.on("blur", function (e) {
				e = e.getTarget();
				if (e.value === "") {
					e.value = def;
				}
			});
		}
	}
	
	return {
		init: function () {
			attachEvents("login-email", "Email");
			attachEvents("login-password", "Password");
		}
	}
}();

Ext.onReady(Spire.app.Template.init, Spire.app.Template);

Spire.app.Share = function () {
	return {
		init: function () {
			Ext.each(Ext.query(".share"), function (el) {
				el = Ext.get(el);

				el.on("click", function (e) {
					e.preventDefault();
					
					addthis_sendto();
				});
			});
		}
	}
}();

Ext.onReady(Spire.app.Share.init, Spire.app.Share);

Spire.app.Pager = function () {
	return {
		init: function () {
			if (Ext.get("go-to-page")) {
				Ext.get("go-to-page").on("click", function () {
					var index = Ext.get("desired-page").dom.selectedIndex;
					var page = Ext.get("desired-page").dom.options[index].value;
					var urlSplit = (document.location+"").split("#");
					var suffix = "";
					
					if (urlSplit.length > 1 || (document.location+"").split("?").length > 1) {
						if (urlSplit[1] == "topic-list") {
							var suffix = "#topic-list";
						}
						
						var urlPieces = urlSplit[0].replace('&lastpost=1', '').split("?")[1].split("&");
						
						if (urlPieces[urlPieces.length-1].match("page")) {
							urlPieces.pop();
						}
						if (urlPieces.length > 0) {
							document.location = (document.location+"").split("?")[0] + "?" + urlPieces.join("&") + "&page=" + page + suffix;
						} else {
							document.location = (document.location+"").split("?")[0] + "?page=" + page + suffix;
						}
					} else {
						document.location = (document.location+"")+ "?page=" + page + suffix;
					}
				});
			}
		}
	}
}();

Ext.onReady(Spire.app.Pager.init, Spire.app.Pager);
/*
Spire.app.BrowserDetect = function () {
	var supportedBrowsers = [
		"IE8",
		"IE9",
		"IE10",
		"Gecko3",
		"Gecko4",
		"Chrome",
		"Safari3",
		"Safari4",
		"Safari5",
		"Safari6",
		"Opera"
	];
	
	var notSupportedBrowsers = {
		"Gecko": "Firefox 1, please <a href='http://www.getfirefox.com' target='_blank'>update Firefox</a>",
		"Gecko2": "Firefox 2, please <a href='http://www.getfirefox.com' target='_blank'>update Firefox</a>",
		"IE6": "Internet Explorer 6, please download <a href='http://www.google.com/chrome' target='_blank'>Google Chrome</a>, <a href='http://www.getfirefox.com' target='_blank'>Mozilla Firefox</a>, or <a href='http://www.microsoft.com/windows/internet-explorer/worldwide-sites.aspx' target='_blank'>update Internet Explorer</a>",
		"IE7": "Internet Explorer 7, please download <a href='http://www.google.com/chrome' target='_blank'>Google Chrome</a>, <a href='http://www.getfirefox.com' target='_blank'>Mozilla Firefox</a>, or <a href='http://www.microsoft.com/windows/internet-explorer/worldwide-sites.aspx' target='_blank'>update Internet Explorer</a>",
		"Safari2": "Safari 2, please <a href='http://www.apple.com/safari/download/' target='_blank'>update Safari</a>"
	};
	
	var isSupported = function () {
		for (var x = 0; x < supportedBrowsers.length; x++) {
			if (Ext["is" + supportedBrowsers[x]]) {
				return true;
			}
		}
		
		return false;
	}
	
	var getBrowserName = function () {
		for (var x in notSupportedBrowsers) {
			if (Ext["is" + x]) {
				return notSupportedBrowsers[x];
			}
		}
		
		return "your current browser, please find an update on <a href='http://www.google.com' target='_blank'>google</a>";
	}
	
	return {
		init: function () {
			if (!isSupported()) {
				Ext.get("browser-name").update(getBrowserName());
				Ext.get("browser-warning").setStyle("display", "block");
			}
		}
	}
}();

Ext.onReady(Spire.app.BrowserDetect.init, Spire.app.BrowserDetect);*/

Spire.app.KeepAlive = function () {
	var keepAlive = function () {
		Ext.Ajax.request({
			url: webRoot + "/lib/ajax/keep-alive.php",
			success: function () {
				keepAlive.defer(90000);
			}
		});
	}
	
	return {
		init: function(){
			if (Spire.loggedIn) {
				keepAlive.defer(90000);
			}
		}
	}
}();

Ext.onReady(Spire.app.KeepAlive.init, Spire.app.KeepAlive);

Spire.app.BBCode = function () {
	return {
		init: function () {
			if (Ext.get("viewBBCode")) {
				Ext.get("viewBBCode").on("click", function(e) {
					e.preventDefault();
					window.open(webRoot+"/lib/html/bbcode.html","mywindow","width=816,height=692,scrollbars=1");
				});
			}
		}
	}
}();

Ext.onReady(Spire.app.BBCode.init, Spire.app.BBCode);

Spire.app.LightBBCode = function () {
	return {
		init: function () {
			if (Ext.get("viewLightBBCode")) {
				Ext.get("viewLightBBCode").on("click", function(e) {
					e.preventDefault();
					window.open(webRoot+"/lib/html/light-bbcode.html","mywindow","width=816,height=692,scrollbars=1");
				});
			}
		}
	}
}();

Ext.onReady(Spire.app.LightBBCode.init, Spire.app.LightBBCode);

Spire.app.Confirm = function () {
	return {
		init: function () {
			Ext.select(".confirm").on("click", function (e) {
				el = e.getTarget();
				var msg = Ext.get(el).dom.rel;
				if (msg.length < 1) {
					msg = "Are you sure you want to do that?";
				}
				if (!confirm(msg)) {
					e.preventDefault();
				}
			});
		}
	}
}();

Ext.onReady(Spire.app.Confirm.init, Spire.app.Confirm);

Spire.app.Form = function () {
	return {
		init: function () {
			Ext.select(".click-disable").on("click", function (e) {
				el = e.getTarget();
				setTimeout(function () {
					el.disabled = true;
				}, 10);
			});
		}
	}
}();

Ext.onReady(Spire.app.Form.init, Spire.app.Form);

Spire.app.DropdownMenu = function () {
	return {
		init: function () {
			Ext.select(".dropdown-menu").on("click", function (e) {
				var span = Ext.get(e.getTarget());
				var dropdownMenu = Ext.get(span.findParent('.dropdown-menu'));
				
				if (span.hasClass('selected')) {
					span.removeClass('selected');
				} else {
					span.addClass('selected');
				}
				
				var element = dropdownMenu.child('.shadow');
				if (element.isVisible()) {
					element.hide();
				} else {
					element.show();
				}
			});
		}
	}
}();

Ext.onReady(Spire.app.DropdownMenu.init, Spire.app.DropdownMenu);

Spire.app.NetworkBar = function () {
	var checkRemember = function (el) {
			if (el.hasClass('checkbox-selected')) {
				el.removeClass('checkbox-selected');
				Ext.get('remember-hidden').dom.value = '0';
			} else {
				el.addClass('checkbox-selected');
				Ext.get('remember-hidden').dom.value = '1';
			}
		};
		
	return {
		init: function () {
			Ext.select('.login-container .bd .remember').on('click', function (e) {
				var el = Ext.get(e.getTarget());
				var el = el.child('.checkbox');
				checkRemember(el);
			});
			Ext.select('.login-container .bd .checkbox').on('click', function (e) {
				checkRemember(Ext.get(e.getTarget()));
			});
			Ext.select('.login').on('click', function (e) {
				e.preventDefault();
				var el = Ext.get(e.getTarget());
				if (el.hasClass('container-selected')) {
					el.removeClass('container-selected');
					Ext.get('login-container').hide();
				} else {
					el.addClass('container-selected');
					Ext.get('login-container').show();
				}
			});
		}
	}
}();

Ext.onReady(Spire.app.NetworkBar.init, Spire.app.NetworkBar);

/*
 * Ext Lightbox
 */

Ext.ns('Ext.ux');

Ext.ux.Lightbox = (function(){
    var els = {},
        images = [],
        activeImage,
        initialized = false,
        selectors = [];

    return {
        overlayOpacity: 0.85,
        animate: true,
        resizeSpeed: 8,
        borderSize: 10,
        labelImage: "Image",
        labelOf: "of",

        init: function() {
            this.resizeDuration = this.animate ? ((11 - this.resizeSpeed) * 0.15) : 0;
            this.overlayDuration = this.animate ? 0.2 : 0;

            if(!initialized) {
                Ext.apply(this, Ext.util.Observable.prototype);
                Ext.util.Observable.constructor.call(this);
                this.addEvents('open', 'close');
                this.initMarkup();
                this.initEvents();
                initialized = true;
            }
        },

        initMarkup: function() {
            els.shim = Ext.DomHelper.append(document.body, {
                tag: 'iframe',
                id: 'ux-lightbox-shim'
            }, true);
            els.overlay = Ext.DomHelper.append(document.body, {
                id: 'ux-lightbox-overlay'
            }, true);
            
            var lightboxTpl = new Ext.Template(this.getTemplate());
            els.lightbox = lightboxTpl.append(document.body, {}, true);

            var ids =
                'outerImageContainer imageContainer image hoverNav navPrev navNext loading loadingLink ' +
                'outerDataContainer dataContainer data details caption imageNumber bottomNav navClose';

            Ext.each(ids.split(' '), function(id){
                els[id] = Ext.get('ux-lightbox-' + id);
            });
			
			els.overlay.setVisibilityMode(Ext.Element.DISPLAY);
			els.lightbox.setVisibilityMode(Ext.Element.DISPLAY);
			els.shim.setVisibilityMode(Ext.Element.DISPLAY);
			
            els.overlay.hide();
            els.shim.hide();
            els.lightbox.hide();

            var size = (this.animate ? 250 : 1) + 'px';
            els.outerImageContainer.setStyle({
                width: size,
                height: size
            });
        },

        getTemplate : function() {
            return [
                '<div id="ux-lightbox">',
                    '<div id="ux-lightbox-outerImageContainer">',
                        '<div id="ux-lightbox-imageContainer">',
                            '<img id="ux-lightbox-image">',
                            '<div id="ux-lightbox-hoverNav">',
                                '<a href="#" id="ux-lightbox-navPrev"></a>',
                                '<a href="#" id="ux-lightbox-navNext"></a>',
                            '</div>',
                            '<div id="ux-lightbox-loading">',
                                '<a id="ux-lightbox-loadingLink"></a>',
                            '</div>',
                        '</div>',
                    '</div>',
                    '<div id="ux-lightbox-outerDataContainer">',
                        '<div id="ux-lightbox-dataContainer">',
                            '<div id="ux-lightbox-data">',
                                '<div id="ux-lightbox-details">',
                                    '<span id="ux-lightbox-caption"></span>',
                                    '<span id="ux-lightbox-imageNumber"></span>',
                                '</div>',
                                '<div id="ux-lightbox-bottomNav">',
                                    '<a href="#" id="ux-lightbox-navClose"></a>',
                                '</div>',
                            '</div>',
                        '</div>',
                    '</div>',
                '</div>'
            ];
        },

        initEvents: function() {
            var close = function(ev) {
                ev.preventDefault();
                this.close();
            };

            els.overlay.on('click', close, this);
            els.loadingLink.on('click', close, this);
            els.navClose.on('click', close, this);

            els.lightbox.on('click', function(ev) {
                if(ev.getTarget().id == 'ux-lightbox') {
                    this.close();
                }
            }, this);

            els.navPrev.on('click', function(ev) {
                ev.preventDefault();
                this.setImage(activeImage - 1);
            }, this);

            els.navNext.on('click', function(ev) {
                ev.preventDefault();
                this.setImage(activeImage + 1);
            }, this);
        },

        register: function(sel, group) {
            if(selectors.indexOf(sel) === -1) {
                selectors.push(sel);

                Ext.fly(document).on('click', function(ev){
                    var target = ev.getTarget(sel);

                    if (target) {
                        ev.preventDefault();
                        this.open(target, sel, group);
                    }
                }, this);
            }
        },

        open: function(image, sel, group) {
            group = group || false;

            var viewSize = this.getViewSize();
            els.overlay.setStyle({
                width: viewSize[0] + 'px',
                height: viewSize[1] + 'px'
            });
            els.shim.setStyle({
                width: viewSize[0] + 'px',
                height: viewSize[1] + 'px'
            }).show();

            els.overlay.fadeIn({
                duration: this.overlayDuration,
                endOpacity: this.overlayOpacity,
                callback: function() {
                    images = [];

                    var index = 0;
                    if(!group) {
                        images.push([image.href, image.title]);
                    }
                    else {
                        var setItems = Ext.query(sel);
                        Ext.each(setItems, function(item) {
                            if(item.href) {
                                images.push([item.href, item.title]);
                            }
                        });

                        while (images[index][0] != image.href) {
                            index++;
                        }
                    }

                    // calculate top and left offset for the lightbox
                    var pageScroll = Ext.fly(document).getScroll();

                    var lightboxTop = pageScroll.top + (Ext.lib.Dom.getViewportHeight() / 10);
                    var lightboxLeft = pageScroll.left;
                    els.lightbox.setStyle({
                        top: lightboxTop + 'px',
                        left: lightboxLeft + 'px'
                    }).show();

                    this.setImage(index);
                    
                    this.fireEvent('open', images[index]);                                        
                },
                scope: this
            });
        },

        setImage: function(index){
            activeImage = index;
                      
            this.disableKeyNav();            
            if (this.animate) {
                els.loading.show();
            }

            els.image.hide();
            els.hoverNav.hide();
            els.navPrev.hide();
            els.navNext.hide();
            els.dataContainer.setOpacity(0.0001);
            els.imageNumber.hide();

            var preload = new Image();
            preload.onload = (function(){
                els.image.dom.src = images[activeImage][0];
                this.resizeImage(preload.width, preload.height);
            }).createDelegate(this);
            preload.src = images[activeImage][0];
        },

        resizeImage: function(w, h){
            var wCur = els.outerImageContainer.getWidth();
            var hCur = els.outerImageContainer.getHeight();

            var wNew = (w + this.borderSize * 2);
            var hNew = (h + this.borderSize * 2);

            var wDiff = wCur - wNew;
            var hDiff = hCur - hNew;

            var queueLength = 0;

            if (hDiff != 0 || wDiff != 0) {
                els.outerImageContainer.syncFx()
                    .shift({
                        height: hNew,
                        duration: this.resizeDuration
                    })
                    .shift({
                        width: wNew,
                        duration: this.resizeDuration
                    });
                queueLength++;
            }

            var timeout = 0;
            if ((hDiff == 0) && (wDiff == 0)) {
                timeout = (Ext.isIE) ? 250 : 100;
            }

            (function(){
                els.hoverNav.setWidth(els.imageContainer.getWidth() + 'px');

                els.navPrev.setHeight(h + 'px');
                els.navNext.setHeight(h + 'px');

                els.outerDataContainer.setWidth(wNew + 'px');

                this.showImage();
            }).createDelegate(this).defer((this.resizeDuration*1000) + timeout);
        },

        showImage: function(){
            els.loading.hide();
            els.image.fadeIn({
                duration: this.resizeDuration,
                scope: this,
                callback: function(){
                    this.updateDetails();
                }
            });
            this.preloadImages();
        },

        updateDetails: function(){
            els.details.setWidth((els.data.getWidth(true) - els.navClose.getWidth() - 10) + 'px');
            
            els.caption.update(images[activeImage][1]);

            els.caption.show();
            if (images.length > 1) {
                els.imageNumber.update(this.labelImage + ' ' + (activeImage + 1) + ' ' + this.labelOf + '  ' + images.length);
                els.imageNumber.show();
            }

            els.dataContainer.syncFx()
                .slideIn('t', {
                    duration: this.resizeDuration/2
                })
                .fadeIn({
                    duration: this.resizeDuration/2,
                    scope: this,
                    callback: function() {
                        var viewSize = this.getViewSize();
                        els.overlay.setHeight(viewSize[1] + 'px');
                        this.updateNav();
                    }
                })
        },

        updateNav: function(){
            this.enableKeyNav();

            els.hoverNav.show();

            // if not first image in set, display prev image button
            if (activeImage > 0)
                els.navPrev.show();

            // if not last image in set, display next image button
            if (activeImage < (images.length - 1))
                els.navNext.show();
        },

        enableKeyNav: function() {
            Ext.fly(document).on('keydown', this.keyNavAction, this);
        },

        disableKeyNav: function() {
            Ext.fly(document).un('keydown', this.keyNavAction, this);
        },

        keyNavAction: function(ev) {
            var keyCode = ev.getKey();

            if (
                keyCode == 88 || // x
                keyCode == 67 || // c
                keyCode == 27
            ) {
                this.close();
            }
            else if (keyCode == 80 || keyCode == 37){ // display previous image
                if (activeImage != 0){
                    this.setImage(activeImage - 1);
                }
            }
            else if (keyCode == 78 || keyCode == 39){ // display next image
                if (activeImage != (images.length - 1)){
                    this.setImage(activeImage + 1);
                }
            }
        },

        preloadImages: function(){
            var next, prev;
            if (images.length > activeImage + 1) {
                next = new Image();
                next.src = images[activeImage + 1][0];
            }
            if (activeImage > 0) {
                prev = new Image();
                prev.src = images[activeImage - 1][0];
            }
        },

        close: function(){
            this.disableKeyNav();
            els.lightbox.hide();
            els.overlay.fadeOut({
                duration: this.overlayDuration
            });
            els.shim.hide();
            this.fireEvent('close', activeImage);
        },

        getViewSize: function() {
            return [Ext.lib.Dom.getViewWidth(true), Ext.lib.Dom.getViewHeight(true)];
        }
    }
})();

Ext.onReady(Ext.ux.Lightbox.init, Ext.ux.Lightbox);

Ext.ux.Lightbox.register('a[href$=.jpg]');
Ext.ux.Lightbox.register('a[href$=.jpeg]');
Ext.ux.Lightbox.register('a[href$=.gif]');
Ext.ux.Lightbox.register('a[href$=.png]');
