/*global jQuery*/
String.prototype.htmlentitize = function() {
	return this.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
};

(function($) {
	$.fn.dropdown = function(options) {
		var params = $.extend(true, null, $.fn.dropdown.defaults, options);
		
		return this.each(function() {
			var holderId = params.holderId;
			var select = $(this);
			
			if(!select.is("select")) { return false; }
			
			var choices = select.find("option");
			
			for(var i = 0; i < choices.length; i++) {
				params.entries.push({ text: choices.eq(i).text(), value: choices.eq(i).val() || choices.eq(i).text() });
			}
			
			var selected_text      = choices.filter("[selected]").text() || "";
			var input              = $('<input type="hidden" class="hidden" id="' + select.attr("id") + '" name="' + select.attr("name") + '" value="' + select.val().htmlentitize() + '"/>').insertBefore(select);
			var control            = $('<div class="httpool-dropdown' + (params.className != null ? ' ' + params.className : '') + '" id="' + select.attr("id") + '-div">' + selected_text.htmlentitize() + '</div>').css("cursor", "pointer");
			var initialHolderWidth = 0;
			var holder             = $("div#" + holderId);
			
			//adjust background image position
			var adjustBackgroundImage = function() {
				holder.css({ width: "", display: "inline" });

				var holderWidth = holder.width();
				holder.css({ width: (holderWidth + 20) + "px", display: "block", backgroundPosition: (holderWidth + 12) + "px 4px" });
			}
			
			var resetBoxWidth = function() {
				if(holder.width() < initialHolderWidth) {
					holder.css({
						width: initialHolderWidth + "px",
						backgroundPosition: (initialHolderWidth - 15) + "px 4px"
					});
				}
			};
			
			var removeBox = function() {
				var box = $("ul[name='dropdown_" + select.attr('name') + "']");
				box.slideUp(80).queue(function() { box.remove(); });
			};
			
			//createBox start
			var createBox = function() {
				removeBox();
				var box = '<ul class="httpool-dropdown-box" name="dropdown_' + select.attr('name') + '" style="position:absolute;left:0;top:0;">';
				if(params.includeBlank) {
					box += '<li xvalue="">&nbsp;</li>';
				}
				for(var i = 0; i < params.entries.length; i++) {
					box += '<li xvalue="' + params.entries[i].value + '">' + params.entries[i].text + '</li>';
				}
				box += '</ul>';
				var choices = $(box).appendTo("body").css({
					top:    control.offset().top + control.verticalSize() + "px",
					left:   control.offset().left + "px",
					cursor: "default",
					zIndex: 1e4
				}).hide().slideDown(80);
								
				choices.find("li")
				.click(function() {
					control.text($(this).text());
					input.val($(this).attr("xvalue"));
					input.trigger("change");
					adjustBackgroundImage();
					removeBox();
					$("body").unbind("click");
					return false;
				})
				.hover(
					function() {
						$(this).addClass("active");
						return false;
					},
					function() {
						$(this).removeClass("active");
						return false;
					}
				)
				.css("borderRight", "1px solid #00A6C7");
				
				choices.find("li:last").css("borderBottom", "1px solid #00A6C7");
				
				var l = 0;
				for(var i = 0; i < choices.find("li").length; i++)
					if(choices.eq(i).width() > l)
						l = choices.eq(i).width();

				if(holder.width() > l) {
					var pos = holder.css("backgroundPosition");
					pos     = Number(pos.substring(0, pos.indexOf("px"))) + 4;
				
					choices.find("li").css("width", pos + "px");
				}
				
				initialHolderWidth = l;
			}
			//createBox end
			
			control.click(function() {
				if($("ul[name='dropdown_" + select.attr('name') + "']").length) {
					adjustBackgroundImage();
					removeBox();
					return false;
				} else {
					createBox();
					resetBoxWidth();
					
					$("body").one("click", function() {
						removeBox();
						adjustBackgroundImage();
					});
					
					return false;
				}
			});
			
			select.replaceWith(control);
			
			var holder = $("div#" + holderId);
			
			holder.css({ width: "", display: "inline" });
			
			var holderWidth = holder.width();
			
			holder.css({
				display: "block",
				width: (holderWidth + 20) + "px",
				backgroundPosition: (holderWidth + 12) + "px 4px"
			});
			
			var L = holder.css('left');
			if (L == 'auto') {
				L = '0px';
			}
			holder.css("left", (L.replace("px", "") - holder.horizontalSize()) + "px");
			
			if(holderId == "country-div") {
				$(".country-selection-div").css("left", ($(".country-selection-div").css("left").replace("px", "") - holder.horizontalSize()) + "px");
			}
		});
	}

	$.fn.dropdown.defaults = {
		className: null,
		includeBlank: false,
		entries: []
	};
	
	$.fn.verticalSize = function() {
		var t = this.eq(0);
		if(!t) { return null; }
		return Number(t.css("paddingTop").replace("px", "")) + t.height() + Number(t.css("paddingBottom").replace("px", ""));
	};
	
	$.fn.horizontalSize = function() {
		var t = this.eq(0);
		if(!t) { return null; }
		return Number(t.css("paddingLeft").replace("px", "")) + t.width() + Number(t.css("paddingRight").replace("px", ""));
	};
})(jQuery);
