var airbag = {
	config : {
		imgs : "/-/img/"
	},

	/*
		Onload functionality
	*/
	init : function() {
		var c = airbag;

		$(document).ready(function() {
			c.addForms("form#add-specialty, form#add-network");
			c.tabs.init();
			c.tooltips.init();
			c.tableGraphs();
			c.fixorz();
			c.loadMedia();
			c.ratings.init();
			c.favorites.init();
			c.specialties.init();
			c.tagaddition.init();
			c.innerLabel.init();
		});
	},

	/*
		Add form
	*/
	addForms : function(sForms) {
		var c = airbag;
		var oAddForms = $(sForms);

		if (oAddForms) {
			oAddForms.each(function() {
				var oForm = $(this);
				var oNav = c.modNav($(oForm));
				var oItem = c.modNavItem($(oNav), "add", "ico-add.gif");

				$(oItem).toggle(
					function() {
						$(oForm).slideDown("fast");
					},
					function() {
						$(oForm).slideUp("fast");
					}
				);
				$(oForm).hide();
			})
		}
	},

	/*
		Module navigation - create the nav (if needed), then add additional items
	*/
	modNav : function(el) {
		var oHead = $(el).parents("div.mod").children("div.head");
		if ($(oHead).find("ul").length > 0) {
			var oNav = $(oHead).children("ul");
		} else {
			var oNav = $(oHead).append("<ul></ul>").children("ul");
		}

		return $(oNav);
	},

	modNavItem : function(oList, sClass, sImg) {
		var c = airbag;
		$(oList).append("<li><a href='#' class='" + sClass + "'><img src='" + c.config.imgs + sImg + "' alt='' /></a></li>");

		var oItem = $(oList).find("a." + sClass);

		return $(oItem);
	},

	/*
		Miscellaneous (and superfluous) cosmetic patches
	*/
	fixorz : function() {
		/*
			Remove margin from #additional .mod, if there's only one
		*/
		var aMods = $("#additional .mod");
		if ($(aMods).length == 1) {
			$(aMods).addClass("sole");
		}

		/*
			IE-specific PNG fix
		*/
		$('img[@src$=.png], input.image, #additional ul.nav-sub li.current a').ifixpng();
	},

	/*
		Media
	*/
	loadMedia : function() {
		if ($("#player").length > 0) {
			var so = new SWFObject("/-/flash/player.swf","mpl","429","240","9");
			so.addParam("allowscriptaccess","always");
			so.addParam("allowfullscreen","true");
			so.addParam("loop", "false")
			so.addParam("flashvars","&file=/images/uploads/intro-video.flv&image=/img/video-preview.jpg");
			so.write("player");
		}
	},

	/*
		Tabs
	*/
	tabs : {
		init : function() {
			var oAllTabs = $(".sections > ul.section-nav");
			if (oAllTabs) {
				$("ul.section-nav > li:first-child").addClass("first");
				$("ul.section-nav > li:last-child").addClass("last");
				oAllTabs.tabs();
			}
		    $("ul.nav_ul").supersubs({
	            extraWidth: 2
	        }).superfish({
	            autoArrows: false,
	            speed: 300
	        }); 
			$(".nav_ul ul").each(function() {
				$(this).find("li:last").addClass("last");
			});
		}
	},

	/*
		Table graphs
	*/
	tableGraphs : function() {
		var oTd = $("table.bar td").each(function() {
			var iTxt = parseInt($(this).text());
			if (iTxt < 10) {
				$(this).prepend("<span>&nbsp;</span>").addClass("slim");
			} else {
				$(this).wrapInner("<span></span>");
			}

			iTxt = (iTxt >= 2.75) ? iTxt - 2.75 : iTxt;

			$(this).children("span").css("width", iTxt + "%");
		});
	},

	/*
		Form tooltips
	*/
	tooltips : {
		init : function() {
			var c = airbag;
			var d = c.tooltips;

			$("a.info").toggle(
				function() {
					d.open($(this));
				},
				function() {
					d.close($(this));
				}
			);
			$("ol.tips").hide();
		},
		open : function(oEl) {
			var sId = $(oEl).attr("href").substr(1);
			var sTip = $("li#" + sId).html();

			if (sTip) {
				var oTd = $(oEl).parent();
				var oDiv = $(oTd).children("div.wrap");
				if ($(oDiv).length == 0) {
					$(oTd).wrapInner("<div class='wrap'></div>");
				}
				$(oEl).parent("div").prepend("<div class='info'>" + sTip + "</div>").hide().slideDown("fast");
			}
		},
		close : function(oEl) {
			var oTd = $(oEl).parents("td");
			var oInfo = $(oEl).siblings("div.info").slideUp("fast", function() {
				$(this).remove();
			});
			// var oWrap = $(oTd).children("div.wrap");
			// $(oTd).html($(oWrap).html());
		}
	},

		/*
			Star ratings
		*/
		ratings : (function () {
			// private variables
			var _responses;

			_responses = {
				duplicate : 'Duplicate submissions are not allowed.',
				success   : 'Your rating has been successfully submitted.'
			};

			// private methods
			var _addEventHandlers, _handleResponse;

			/**
			 * Add onclick event handler to rating link
			 */
			_addEventHandlers = function () {
				$('ul.star-rating li a').click(function () {
					var id;

					// show loading GIF
					$('ul.star-rating').addClass('stars-loading');

					id = $($('.rating form input[name=entry_id]')[0]).val();

					// set hidden field with rating to the value clicked
					$($('.rating form input[name=rating]')[0]).val(this.innerHTML);

					// make ajax request
					$($('.rating form')[0]).ajaxSubmit({
						success : function (data) {
							_handleResponse(data, id);
						}
					});

					// prevent form from being submitted
					return false;
				});
			};

			/**
			 * Handle the response from saving a rating
			 * @param string data Response string
			 * @param int    id   ID of the entry
			 */
			_handleResponse = function (data, id) {

				// rating successful
				if (data.indexOf(_responses.success) > -1) {
					// fetch new average
					$.get('/includes/rating/' + id, function (data) {
						var ul;
						ul = $('.rating ul')[0];

						// hide loading GIF - relocated this into the successful area to make it go faster.
						$('ul.star-rating').removeClass('stars-loading');

						$(ul).removeClass();
						// update classname with new average
						$(ul).addClass('rated-' + data);

						$(ul).addClass('star-rating');
					});
				// duplicate rating submitted
				} else if (data.indexOf(_responses.duplicate) > -1) {
					// alert user?  allow updates to rating?

					// hide loading GIF - duplicated this because we had some lag and i moved the other copy inside the success area.
					$('ul.star-rating').removeClass('stars-loading');

				} else {
					// are there error conditions we should be handling?
				}

			};

			// public methods
			return {
				init: function () {
					_addEventHandlers();
				}
			};
		})(),


		/*
			Specialties
		*/
		specialties : (function () {
			var _addEventHandlers

			/**
			 * Add onclick event handler to specialty add button
			 */
			_addEventHandlers = function () {

				$('#add-button').click(function () {

					// create the text addition for the list

					var itemtext = $('#sel-spec-list')[0].options[$('#sel-spec-list')[0].selectedIndex].text;
					if(itemtext != "Select a Specialty") {
						
						var speclist = $("#specialty-tag-list").html();				
						if(speclist !== "") {
							var separate = ", ";
						}
						else {
							var separate = "";
						}
						var fullspeclist = speclist + separate + "<a href='#'>" + itemtext + "</a>";
						$("#specialty-tag-list").html(fullspeclist);


						// create an input field for each addition
						var itemvalue;
						itemvalue = $("#sel-spec-list").val();

						$("#hidden-specs").append("<input type='hidden' name='category[]' value='" + itemvalue + "' />");

						// reset dropdown
						document.getElementById('sel-spec-list').selectedIndex = 0;

					}





				});
			};
			// public methods
			return {
				init: function () {
					_addEventHandlers();
				}
			};
		})(),		

		/*
			tags
		*/
		tagaddition : (function () {
			var _addEventHandlers

			/**
			 * Add onclick event handler to tags add button
			 */
			_addEventHandlers = function () {
				$('#add-tag-button').click(function () {

					var tagvalue;
					tagvalue = $("#tag-field").val();

					// create the text addition
					$(".tags").append("<li><a href=''>" + tagvalue + "</a></li>");

					// create an input field for each addition
					$("#entry-tags").append(tagvalue + "\n");

					$("#tag-field").val("");


				});
			};
			// public methods
			return {
				init: function () {
					_addEventHandlers();
				}
			};
		})(),		


			/*
				Favorites
			*/
			favorites : (function () {
				// private variables
				var _responses, _links, _rgxp, _saveURL;

				// snippets of return messages we can use to determine the result of the action
				// NOTE: these will need to be updated if they are changed in the database
				_responses = {
					success_add    : 'successfully added',
					success_delete : 'successfully deleted'
				};

				// TODO: change the "unsave" link to whatever it needs to be
				_links = {
					add : ['<a href="/includes/save/', '', '"><input type="image" value="Save post" src="/-/img/btn-save-post.gif"/></a>'],
					ldg : '<img src="/-/img/ajax-loader-white.gif" alt="Loading..." class="loader" />',
					del : ['<a href="/includes/save/', '', '/delete"><input type="image" value="Unsave post" src="/-/img/btn-unsave-post.gif"/></a>']
				};

				// regular expression to match the entry_id
				_rgxp = /save\/([0-9]+)/;

				// private methods
				var _addEventHandler, _handleResponse;

				/**
				 * Add onclick event handler to save/unsave link
				 */
				_addEventHandler = function () {
					var link, href, id;

					link = $('div.my-actions > p a')[0];

					if ('undefined' !== typeof link) {
						href = link.href;
						id   = href.match(_rgxp)[1];

						$(link).click(function () {
							// change button to loading image
							$('div.my-actions > p').html(_links.ldg);

							// make ajax request
							$.get(href, function (data) {
								_handleResponse(data, id);
							});

							// prevent link from being followed
							return false;
						});
					}
				};

				/**
				 * Handle the response from saving or unsaving a favorite
				 * @param string data Response string
				 * @param int    id   ID of the entry
				 */
				_handleResponse = function (data, id) {
					if (data.indexOf(_responses.success_add) > -1) {
						_links.del[1] = id;
						$('div.my-actions > p').html(_links.del.join(''));
						_addEventHandler();
					} else {
						_links.add[1] = id;
						$('div.my-actions > p').html(_links.add.join(''));
						_addEventHandler();
					}
				};

				// public methods
				return {
					init : function () {
						_addEventHandler();
					}
				}
			})(),
			
			/**
			 * Adds "in-field labels" to input fields with the class .inner-label
			 *
			 * @author	Stephen Lewis <stephen@experienceinternet.co.uk>
			 * @date	11th March 2010
			 */

			innerLabel : (function() {

				// Private methods.

				function _enhanceInputs() {
					
					$('body').addClass('enhanced');		// Generally useful.

					$('input.inner-label').each(function() {
						fieldId = this.id;
						$input = $(this);
						$label = $input.prev('label[for=' +fieldId +']');
						
						if ($label.length > 0 && $input.val() == '') {
							$input.val($label.text());
						}
						
						$input.focus(function(e) {
							$i = $(e.target);
							$l = $i.prev('label[for=' +e.target.id +']');
							
							if ($i.val() == $l.text()) {
								$i.val('');
							}
						});
						
						$input.blur(function(e) {
							$i = $(e.target);
							$l = $i.prev('label[for=' +e.target.id +']');
							
							if ($i.val() == '') {
								$i.val($l.text());
							}
						});

					});

				};


				// Public methods.
				return {init : function() {
					_enhanceInputs();
				}};

			})()
		};

		airbag.init();
