/* extend jQuery */
/* jquery.imageExists.plugin.js */
(function () {
	var jQuery = window.jQuery,
		outbreak = {};

	function load_script(file, cb) {
		var obj = document.createElement('script'),
			head = document.getElementsByTagName('head')[0];
		obj.type = "text/javascript";
		obj.src = file;
		if (cb) {
			var d = false;
			obj.onload = obj.onreadystatechange = function () {
				if (!d && (!this.readyState || this.readyState === 'loaded' || this.readyState === 'complete')) {
					d = true;
					cb.apply(obj);
					head.removeChild(obj);
				}
			};
		}
		head.appendChild(obj);
		return obj;
	}

	jQuery.extend({
		imageExists: function (src, callbacks) {
			callbacks = jQuery.extend({
				success: null,
				failure: null,
				object: {}
			}, callbacks);
			var img = new Image();
			if (callbacks.success && typeof callbacks.success === 'function') {
				img.onload = function () {
					callbacks.success(callbacks.object);
					img = null;
				};
			}
			if (callbacks.failure && typeof callbacks.failure === 'function') {
				img.onerror = function () {
					callbacks.failure(callbacks.object);
					img = null;
				};
			}
			img.src = src;
		}
	});
	jQuery.fn.extend({
		normalize: function () { // joins adjacent textnodes into one single textnode
			this.each(function (ix) {
				var i = 0, n = null, e = null;
				for (i = this.childNodes.length; i > 0; i -= 1) {
					n = this.childNodes[i];
					if (n === null) {
						continue;
					}
					if (this.childNodes[i - 1].nodeType === 3) {
						e = jQuery(this.childNodes[i - 1]);
						if (n.nodeType === 3) {
							e[0].nodeValue += n.nodeValue;						
							jQuery(n).remove();
						}
					}
				}
			});
			return this;
		},
		cantFind: function (f, fn) { // execute fn if no f is found in the set
			if (this.find(f).size() === 0) {
				this.each(fn);
			}
			return this;
		}
	});
	
	/* use jQuery */
	
	// tools
	jQuery(function ($) {
		// make sure we disable css, hide, show if no styles
		(function ($) {
			var disable = true;
			$('link[rel*=stylesheet]').each(function () {
				if (this.disabled === false && this.href.indexOf('chrome://') < 0) {
					disable = false;
				}
			});
			if (disable) {
				$.fn.css = $.fn.hide = $.fn.show = function () {return this;};
			}
		})($);
		
		// dropdown submits
		$("#archive form")
			.find("select#archive_date").change(function (ev) {
				window.location.href = this.value;
			}).end()
			.find("select#archive_tag").change(function (ev) {
				window.location.href = '/outbreak/?cat=' + this.value;
			}).end()
			.find("input[type=submit]").hide();
		
		// search form
		$("form#searchbox").submit(function (ev) {
			this.q.value = this.s.value;
		});
		
		// fix images...
		(function () {
			var b = $("#body");
			b.find('.fix')
				.find("a img")
					.parent().addClass("img").end()
					.end()
				.find("img").each(function (i) {
					var h = this.offsetHeight, nh = 0;
					if (h) {
						nh = Math.floor(h / 9) * 9 + 4;
						if (nh < h) {
							nh += 9;
						}
						$(this).css('margin-bottom', (nh - h) + 'px');
					}
				}).end()
				.removeClass("fix").end();
			b.find('.zemanta-img a img')
				.parent().addClass('img').end()
				.end();
			b.find(".bigimage")
				.cantFind('.wrapper', function (i) {
					$(this).wrapInner('<div class="wrapper"></div>');
				})
				.find("a img")
					.parent().addClass("img").end()
					.end()
				.find(".wrapper").each(function (i) {
					var h = this.offsetHeight, nh = 0;
					if (h) {
						nh = Math.floor(h / 9) * 9;
						if (nh < h) {
							nh += 9;
						}
						$(this).css('margin-bottom', (nh - h) + 'px');
					}
				})
				.end();
		})();
		// favicons on links
		$(window).load(function (ev) {
			var c = 0;
			$("#links li").each(function () {
				var el = $(this),
					src = el.children().attr('href'),
					i = src.indexOf('/', src.indexOf('://') + 3); // find the / after the ://
				if (i > 0) {
					src = src.substr(0, i); // remove if found
				}
				src += '/favicon.ico'; // add /favicon.ico
				src = 'http://getfavicon.appspot.com/' + src;
				setTimeout(function (src, o) {
					return function () {
						$.imageExists(src, o);
					};
				}(src, {
						object: {el: el, src: src}, 
						success: function (o) {
							o.el.css('background', 'url(' + o.src + ') no-repeat');
						}
					}), (c * 100) + 1);
				c += 1;
			});
		});
	
		/* if we're on the search page add our file as the referer 
		if ($("body.search").size()>0) {
			outbreak.search.options.debug_referrer = window.location.href;
		}*/		
		var keys = $.searchKeys(outbreak.search.options);
		if (keys === null) {
			keys = [];
		}

		// search engine keys highlighter
		(function () {
			var locally = null;
			if (keys.length > 0) {
				locally = document.referrer.indexOf('http://friedcellcollective.net/outbreak') === 0? '' : '<p>You can <a href="javascript:outbreak.search.execute(\'' + keys.join(' ') + '\')">search</a> for the same keywords locally.</p>';
				$("#about").after('<div id="tools" class="box"><h3>Search tools</h3></div>')
					.parent().find("#tools").append('<p>You searched for the following terms that are highlighted in the text: <a href="#" class="key">' + keys.join('</a> <a href="#" class="key">') + '</a>. You can toggle the terms individually by clicking on them or you can <a href="javascript:outbreak.search.toggle()">toggle them all here</a>.</p>' + locally)
					.find("a.key").each(function (i) {
						$(this).addClass('hilite' + (i + 1));
					}).click(function (ev) {
						ev.preventDefault();
						var el = $(this),
							c = el.attr('class'),
							i = c.substr(c.indexOf('hilite'));
						i = i.indexOf(' ') > 0 && i.substr(0, i.indexOf(' '));
						if (!el.hasClass("disabled")) {
							outbreak.search.clear(i);
							el.addClass("disabled");
						} else {
							el.removeClass("disabled");
							outbreak.search.set(i);
						}
		
					});
				outbreak.search.set();
			}
		})();
	
		// compact sidebar
		(function () {
			var modified = false,
				visits = 0;
			if (!$("body.index").size() > 0 || keys.length > 0) { // from search engines
				$("#side > div").hide()
					.filter("#about").show()
					.end().filter("#ads").show()
					.end().filter("#tools").show();
				modified = true;
			}
			// hide about and ads from regular visitors
			visits = parseInt($.cookie("visits"), 10);
			if (isNaN(visits)) {
				visits = 0;
			}
			if (visits > 5) {
				$("#side #about").hide();
				modified = true;
				$("#side #ads").addClass("disabled").hide(); // ads not shown to regulars
				$("#side #jobs").hide();
			}
			$.cookie("visits", visits + 1, {expires: 30, path: '/'});
			// add expanded box
			if (modified && $("#expand").size() === 0) {
				$("#side").prepend('<div id="expand" class="box"><p>You&#8217;re looking at a condensed version of the sidebar &#8212; <a href="javascript:outbreak.expandSidebar()">expand it</a> to reveal all the content.</p></div>');
			}
		})();
	
		// enhance google maps links
		setTimeout(function () {
			function openSmallMap(elm) {
				$(window).unload(window.GUnload);
				if (!window.GBrowserIsCompatible()) {
					return;
				}
				var el = $(elm),
					src = el.attr('href'),
					p = src.split('&'),
					props = {},
					m = null, map = null;
					
				$.each(p, function (i) {
					if (this.indexOf('ll') === 0) {
						props.ll = this.substr(3).split(',');
					} else if (this.indexOf('z') === 0) {
						props.z = parseInt(this.substr(2), 10);
					}
				});
				// create the elements
				m = el.parent().parent().find('.sidemap');
				if (m.size() === 0) {
					m = el.parent().after('<div class="sidemap"></div>').parent().find(".sidemap");
				}
				m.html('<div class="map"></div><p><a href="' + src + '">View Larger Map</a> (<a class="close" href="#">close map</a>)</p>');
				// set the map up
				map = new window.GMap2(m.find(".map").get(0));
				map.setCenter(new window.GLatLng(props.ll[0], props.ll[1]), props.z);
				map.addControl(new window.GSmallMapControl());
				// add the close button
				m.find(".close").click(function (ev) {
					ev.preventDefault();
					$(this).parent().parent().html('');
				});
			}
			$("#side a[href~='http://maps.google']").click(function (ev) {
				var elm = this, t = 0;
				if (typeof window.GMap2 === 'undefined') { // not loaded
					load_script('http://maps.google.com/maps?file=api&v=2&async=2&key=ABQIAAAAGpLi0-hqoha_dC3-tr5gYRQl8sihe3M-9Lg9h9-YsyomiVLpuBQ_NjDX_yXS1gepAG0wyTgDPiKTeA', function () {
						setTimeout(function maps_enabled() {
							t += 1;
							if (typeof window.GMap2 !== 'undefined') {
								openSmallMap(elm);
							} else if (t < 10) {
								setTimeout(maps_enabled, 100);
							}
						}, 1);
					});
				} else {
					openSmallMap(elm);
				}
				ev.preventDefault();
			});
		}, 100);
		
		outbreak.loadwidget('http://www.authenticjobs.com/affiliates/badge.js?aff=d4398', 'authenticjobs-holder');
	});
	
	// outbreak functions
	outbreak = function ($) {
		return {
			expandSidebar: function () {
				$("#side > div").show()
					.filter("#expand").hide()
					.end().filter("#ads.disabled").hide();
			},
			loadwidget: function (src, id) {
				var frameId = 'loadwidget-' + Math.random(), frame = null, doc = null;
				if (id) {
					frame = $('<iframe>');
					frame.name = frame.id = frameId;
					$('body').append(frame);
				} else {
					document.write('<iframe id="' + frameId + '" name="' + frameId + '"></iframe>');
					frame = $('#' + frameId);
				}
				frame.css('display', 'none');
				doc = frame[0].contentWindow.document;
				doc.write('<html><head><title>Widget loader</title><head><body><' + 'script type="text/javascript" src="' + src + '"><' + '/script></body></html>');
				setTimeout(function () {
					var c = $('body *', doc).not('script'), html = '', done = false;
					if (c.size() > 0) {
						$('script', doc).remove();
						html = $('body', doc).html();
						if (html) {
							if (id) {
								frame.remove();
								frame = $('#' + id);
							}
							frame.replaceWith(html);
							done = true;
						}
					}
					if (!done) {
						setTimeout(arguments.callee, 100);
					}
				}, 100);
			},
			search: {
				options: {
					//debug_referrer:'http://www.google.com?q=keep%20using%20bet%20better',
					exact: "partial",
					highlight: "#body"
				},
				execute: function (s) {
					var f = $("form#searchbox").get(0);
					f.s.value = f.q.value = s;
					f.submit();
				},
				clear: function (cls) {
					var el = $("#tools a.key");
					if (cls)  {
						el = el.filter('.' + cls);
					}
					el.addClass("disabled");
					this.clearHighlight(cls);
				},
				set: function () {
					var el = $("#tools a.key"),
						ks = [], i = 0, j = 0, e = null, c = null;
					for (i = 0, j = el.length; i < j; i += 1) {
						e = $(el[i]);
						c = "key";
						if (!e.hasClass("disabled")) {
							ks.push(e.text());
							c += " hilite" + ks.length;
						} else {
							c += " disabled";
						}
						el[i].className = c;
					}
					this.options.keys = ks.join(' ');
					this.clearHighlight();
					$(document).searchHighlight(this.options);
				},
				toggle: function () {
					var el = $("#tools a.key");
					if (el.filter(".disabled").size() > 0) {
						el.removeClass("disabled");
						this.set();
					} else {
						el.addClass("disabled");
						this.clearHighlight();
					}
				},
				clearHighlight: function (cls) {
					cls = cls || 'hilite';
					$("span[@class^=" + cls + "]").each(function () {
						var el = $(this),
							p = this.parentNode;
						el.replaceWith(el.text());
						$(p).normalize();
					});
				}
			}
		};
	}(jQuery);
	window.outbreak = outbreak;
	
	function addCss(cssCode) {
		var styleElement = document.createElement("style");
		styleElement.type = "text/css";
		if (styleElement.styleSheet) {
			styleElement.styleSheet.cssText = cssCode;
		} else {
			styleElement.appendChild(document.createTextNode(cssCode));
		}
		document.getElementsByTagName("head")[0].appendChild(styleElement);
	}
	window.addCss = addCss;
})();