/*


 */
(function($) {
	var oldDiv = "";
	$.fn.dd = function(options) {
		$this = this;
		options = $.extend( {
			onChange : null,
			onOpen : null,
			onOpened : null,
			height : 120,
			width : 200,
			visibleRows : 7,
			rowHeight : 23,
			showIcon : true,
			zIndex : 9999,
			style : '',
			slideDownSpeed : "fast",
			slideUpSpeed : "fast",
			tip : "image",
			useKeyboard : false
		}, options);
		var selectedValue = "";
		var actionSettings = {};
		actionSettings.insideWindow = false;
		actionSettings.keyboardAction = options.useKeyboard;
		actionSettings.currentKey = null;
		var ddList = false;
		config = {
			postElementHolder : '_msddHolder',
			postID : '_msdd',
			postTitleID : '_title',
			postTitleTextID : '_titletext',
			postChildID : '_child',
			postAID : '_msa',
			postOPTAID : '_msopta',
			postInputID : '_msinput',
			postArrowID : '_arrow',
			postInputhidden : '_inp',
			amado : ''
		};
		styles = {
			dd : 'dd',
			ddTitle : 'ddTitle',
			arrow : 'arrow',
			ddChild : 'ddChild',
			disbaled : .30,
			valueFormat : 'childValue'
		};
		attributes = {
			actions : "onfocus,onblur,onchange,onclick,ondblclick,onmousedown,onmouseup,onmouseover,onmousemove,onmouseout,onkeypress,onkeydown,onkeyup",
			prop : "size,multiple,disabled,tabindex"
		};

		var amad = $(this);

		var amadName = ($(this).attr("name")) ? $(this).attr("name") : "";
		if (amadName != "") {
			$(amad).removeAttr("name");
		}

		var varmi = false;
		var iid = 0;
		while (varmi == false) {
			if ($("#ColorCombobox" + iid).length > 0) {
				iid++;
			} else {
				varmi = true;
			}
		}
		var amadID = ($(amad).attr("id")) ? $(amad).attr("id") : "ColorCombobox" + iid;
		// var elementid = $(this).attr("id");

		var inlineCSS = $(this).attr("style");
		options.style += (inlineCSS == undefined) ? "" : inlineCSS;
		var allOptions = $(this).children();
		ddList = ($(this).attr("size") > 0 || $(this).attr("multiple") == true) ? true : false;
		if (ddList) {
			options.visibleRows = $(this).attr("size");
		}
		var a_array = {};// stores id, html & value etc
		// create wrapper
		createDropDown();
		function getPostID(id) {
			return amadID + config[id];
		}
		function getOptionsProperties(option) {
			var currentOption = option;
			var styles = $(currentOption).attr("style");
			return styles;
		}
		function matchIndex(index) {
			var selectedIndex = $(amad).find("option:selected");
			if (selectedIndex.length > 1) {
				for ( var i = 0; i < selectedIndex.length; i++) {
					if (index == selectedIndex[i].index) {
						return true;
					}
				}
			} else if (selectedIndex.length == 1) {
				if (selectedIndex[0].index == index) {
					return true;
				}
			}
			return false;
		}
		function createATags() {
			var childnodes = allOptions;
			var aTag = "";
			var aidfix = getPostID("postAID");
			var aidoptfix = getPostID("postOPTAID");
			childnodes.each(function(current) {
				var currentOption = childnodes[current];
				// OPTGROUP
					if (currentOption.nodeName == "OPTGROUP") {
						aTag += "<div class='opta'>";
						aTag += "<span style='font-weight:bold;font-style:italic; clear:both;'>" + $(currentOption).attr("label") + "</span>";
						var optChild = $(currentOption).children();
						optChild.each(function(currentopt) {
							var currentOptOption = optChild[currentopt];
							var aid = aidoptfix + "_" + (current) + "_" + (currentopt);
							var arrow = $(currentOptOption).attr("title");
							if (arrow.length == 0) {
								arrow = "";
							} else {
								switch (options.tip) {
									case "color":
										arrow = '<span class="icon"><span class="color" style="background-color:' + arrow + '">&nbsp;</span></span>';
										break;
									case "image":
										arrow = '<span class="icon"><img src="' + arrow + '" /></span>';
										break;
									case false:
									case "":
									case "none":
										arrow = "";
										break;
								}
							}
							var sText = valueFormat($(currentOptOption).text());
							var sValue = $(currentOptOption).val();
							var sEnabledClass = ($(currentOptOption).attr("disabled") == true) ? "disabled" : "enabled";
							a_array[aid] = {
								html : arrow + sText,
								value : sValue,
								text : sText,
								index : currentOptOption.index,
								id : aid
							};
							var innerStyle = getOptionsProperties(currentOptOption);
							if (matchIndex(currentOptOption.index) == true) {
								aTag += '<a href="javascript:void(0);" class="selected ' + sEnabledClass + '"';
							} else {
								aTag += '<a  href="javascript:void(0);" class="' + sEnabledClass + '"';
							}
							;
							if (innerStyle != false)
								aTag += ' style="' + innerStyle + '"';
							aTag += ' id="' + aid + '">';
							aTag += arrow + sText + '</a>';
						});
						aTag += "</div>";

					} else {
						var aid = aidfix + "_" + (current);
						var arrow = $(currentOption).attr("title");
						if (arrow.length == 0 || options.showIcon == false) {
							arrow = "";
						} else {
							switch (options.tip) {
								case "color":
									arrow = '<span class="icon"><span class="color" style="background-color:' + arrow + '">&nbsp;</span></span>';
									break;
								case "image":
									arrow = '<span class="icon"><img src="' + arrow + '" /></span>';
									break;
							}
						}
						var sText = valueFormat($(currentOption).text());
						var sValue = $(currentOption).val();
						var sEnabledClass = ($(currentOption).attr("disabled") == true) ? "disabled" : "enabled";
						a_array[aid] = {
							html : arrow + sText,
							value : sValue,
							text : sText,
							index : currentOption.index,
							id : aid
						};
						var innerStyle = getOptionsProperties(currentOption);
						if (matchIndex(currentOption.index) == true) {
							aTag += '<a href="javascript:void(0);" class="selected ' + sEnabledClass + '"';
						} else {
							aTag += '<a  href="javascript:void(0);" class="' + sEnabledClass + '"';
						}
						if (innerStyle != false)
							aTag += ' style="' + innerStyle + '"';
						aTag += ' id="' + aid + '">';
						aTag += arrow + sText + '</a>';
					}
				});
			return aTag;
		}
		function createChildDiv() {
			var id = getPostID("postID");
			var childid = getPostID("postChildID");
			var sStyle = "";// options.style;
			sDiv = "";
			sDiv += '<div id="' + childid + '" class="' + styles.ddChild + '"';
			if (!ddList) {
				sDiv += (sStyle != "") ? ' style="' + sStyle + '"' : '';
			} else {
				sDiv += (sStyle != "") ? ' style="border-top:1px solid #c3c3c3;display:block;position:relative;' + sStyle + '"' : '';
			}
			sDiv += '>';
			return sDiv;
		}
		function createTitleDiv() {
			var titleid = getPostID("postTitleID");
			var arrowid = getPostID("postArrowID");
			var titletextid = getPostID("postTitleTextID");
			var inputhidden = getPostID("postInputhidden");
			var sText = $(amad).find("option:selected").text();
			sText = (options.showIcon !== false) ? valueFormat(sText) : sText;
			var arrow = $(amad).find("option:selected").attr("title");
			if (arrow == undefined || arrow.length == 0 || options.showIcon == false) {
				arrow = "";
			} else {
				switch (options.tip) {
					case "color":
						arrow = '<span class="icon"><span class="color" style="background-color:' + arrow + '">&nbsp;</span></span>';
						break;
					case "image":
						arrow = '<span class="icon"><img src="' + arrow + '" /></span>';
						break;
				}
			}
			var sDiv = '<div id="' + titleid + '" class="' + styles.ddTitle + '"';
			sDiv += '>';
			sDiv += '<span id="' + arrowid + '" class="' + styles.arrow + '"></span><span class="textTitle" id="' + titletextid + '">' + arrow + sText + '</span></div>';
			return sDiv;
		}
		function createDropDown() {
			var changeInsertionPoint = false;
			var id = getPostID("postID");
			var titleid = getPostID("postTitleID");
			var titletextid = getPostID("postTitleTextID");
			var childid = getPostID("postChildID");
			var arrowid = getPostID("postArrowID");
			var iWidth = options.width != null ? options.width > 0 ? options.width : $("#" + amadID).innerWidth() : false;
			var sStyle = options.style;
			if ($("#" + id).length > 0) {
				$("#" + id).remove();
				changeInsertionPoint = true;
			}
			setMainDiv();
			var sDiv = "";
			sDiv += '<div id="' + id + '" class="' + styles.dd + '"';
			sDiv += '>';
			if (!ddList)
				sDiv += createTitleDiv();
			sDiv += createChildDiv();
			sDiv += createATags();
			sDiv += "</div>";
			sDiv += "</div>";
			if (amadName != "") {
				sDiv += "<input type='hidden' name='" + amadName + "' value='' />";
			}
			$("#" + amadID).append(sDiv);
			if (amadName != "") {
				$("#" + amadID + " [name=" + amadName + "]").val($(amad).val());
			}
			if (iWidth !== false) {
				$("#" + amadID).css("width", iWidth + "px");
			}
			var amadWidth = $("#" + id).outerWidth();
			$("#" + childid).css( {
				minWidth : (amadWidth) + "px"/*,
				left : $("#" + amadID).offset().left*/
			});
			if (allOptions.length > options.visibleRows) {
				var margin = parseInt($("#" + childid + " a:first").css("padding-bottom")) + parseInt($("#" + childid + " a:first").css("padding-top"));
				var iHeight = ((options.rowHeight) * options.visibleRows) - margin;
				$("#" + childid).css("height", iHeight + "px");
			}
			// set out of vision
			if (changeInsertionPoint == false) {
				setOutOfVision();
				addNewEvents(amad);
			}
			if ($(amad).attr("disabled") == true) {
				$("#" + id).css("opacity", styles.disbaled);
			} else {
				applyEvents();
				// add events
				// arrow hightlight
				if (!ddList) {
					$("#" + titleid).bind("mouseover", function(event) {
						hightlightArrow(1);
					});
					$("#" + titleid).bind("mouseout", function(event) {
						hightlightArrow(0);
					});
				}
				// open close events
				$("#" + childid + " a.enabled").bind("click", function(event) {
					event.preventDefault();
					manageSelection(this);
					if (!ddList) {
						$("#" + childid).unbind("mouseover");
						setInsideWindow(false);
						var sText = (options.showIcon == false) ? $(this).text() : $(this).html();
						// sText = valueFormat(sText);
						setTitleText(sText);
						closeMe();
					}
					setValue();
					// actionSettings.oldIndex =
						// a_array[$(this).attr("id")].index;
					});
				$("#" + childid + " a.disabled").css("opacity", styles.disbaled);
				if (ddList) {
					$("#" + childid).bind("mouseover", function(event) {
						if (!actionSettings.keyboardAction) {
							actionSettings.keyboardAction = true;
							$(document).bind("keydown", function(event) {
								var keyCode = event.keyCode;
								actionSettings.currentKey = keyCode;
								if (keyCode == 39 || keyCode == 40) {
									// move to next
									event.preventDefault();
									event.stopPropagation();
									next();
									setValue();
								}
								if (keyCode == 37 || keyCode == 38) {
									event.preventDefault();
									event.stopPropagation();
									// move to previous
									previous();
									setValue();
								}
							});
						}
					});
				}
				$("#" + childid).bind("mouseout", function(event) {
					setInsideWindow(false);
					$(document).unbind("keydown");
					actionSettings.keyboardAction = false;
					actionSettings.currentKey = null;
				});
				if (!ddList) {
					$("#" + titleid).bind("click", function(event) {
						setInsideWindow(false);
						if ($("#" + childid + ":visible").length == 1) {
							$("#" + childid).unbind("mouseover");

						} else {
							$("#" + childid).bind("mouseover", function(event) {
								setInsideWindow(true);
							});
							openMe();
						}
					});
				}
				$("#" + titleid).bind("mouseout", function(evt) {
					setInsideWindow(false);
				})
			}
		}
		function getByIndex(index) {
			for ( var i in a_array) {
				if (a_array[i].index == index) {
					return a_array[i];
				}
			}
		}
		function manageSelection(obj) {
			var childid = getPostID("postChildID");
			if (!ddList) {
				$("#" + childid + " a.selected").removeClass("selected");
			}
			var selectedA = $("#" + childid + " a.selected").attr("id");
			if (selectedA != undefined) {
				var oldIndex = (actionSettings.oldIndex == undefined || actionSettings.oldIndex == null) ? a_array[selectedA].index : actionSettings.oldIndex;
			}
			if (obj && !ddList) {
				$(obj).addClass("selected");
			}
			if (ddList) {
				var keyCode = actionSettings.currentKey;
				if ($(amad).attr("multiple") == true) {
					if (keyCode == 17) {
						// control
						actionSettings.oldIndex = a_array[$(obj).attr("id")].index;
						$(obj).toggleClass("selected");
						// multiple
					} else if (keyCode == 16) {
						$("#" + childid + " a.selected").removeClass("selected");
						$(obj).addClass("selected");
						// shift
						var currentSelected = $(obj).attr("id");

						var currentIndex = a_array[currentSelected].index;
						for ( var i = Math.min(oldIndex, currentIndex); i <= Math.max(oldIndex, currentIndex); i++) {
							$("#" + getByIndex(i).id).addClass("selected");
						}
					} else {
						$("#" + childid + " a.selected").removeClass("selected");
						$(obj).addClass("selected");
						actionSettings.oldIndex = a_array[$(obj).attr("id")].index;
					}
				} else {
					$("#" + childid + " a.selected").removeClass("selected");
					$(obj).addClass("selected");
					actionSettings.oldIndex = a_array[$(obj).attr("id")].index;
				}
			}
		}
		function addNewEvents(id) {
			$(id).refresh = function(e) {
				$(id).dd(options);
			};
		}
		function setInsideWindow(val) {
			actionSettings.insideWindow = val;
		}
		function getInsideWindow() {
			return actionSettings.insideWindow;
		}
		function applyEvents() {
			var mainid = getPostID("postID");
			var actions_array = attributes.actions.split(",");
			for ( var iCount = 0; iCount < actions_array.length; iCount++) {
				var action = actions_array[iCount];
				var actionFound = $(amad).attr(action);
				if (actionFound != undefined) {
					switch (action) {
						case "onfocus":
							$("#" + mainid).bind("mouseenter", function(event) {
								amad.focus();
							});
							break;
						case "onclick":
							$("#" + mainid).bind("click", function(event) {
								$(amad).onclick();
							});
							break;
						case "ondblclick":
							$("#" + mainid).bind("dblclick", function(event) {
								$(amad).ondblclick();
							});
							break;
						case "onmousedown":
							$("#" + mainid).bind("mousedown", function(event) {
								$(amad).onmousedown();
							});
							break;
						case "onmouseup":
							// has in closeMe mthod
							$("#" + mainid).bind("mouseup", function(event) {
								$(amad).onmouseup();
								// setValue();
								});
							break;
						case "onmouseover":
							$("#" + mainid).bind("mouseover", function(event) {
								$(amad).onmouseover();
							});
							break;
						case "onmousemove":
							$("#" + mainid).bind("mousemove", function(event) {
								$(amad).onmousemove();
							});
							break;
						case "onmouseout":
							$("#" + mainid).bind("mouseout", function(event) {
								$(amad).onmouseout();
							});
							break;
					}
				}
			}
		}
		function setOutOfVision() {
			var sId = getPostID("postElementHolder");
			var sDiv = '';
			sDiv += "<div style='height:0px;overflow:hidden;display:none;position:absolute;' id='" + sId + "'></div>"
			$("#" + amadID).append(sDiv);
			$(amad).appendTo($("#" + sId));
		}
		function setTitleText(sText) {
			var titletextid = getPostID("postTitleTextID");
			$("#" + titletextid).html(sText);
		}
		function setMainDiv() {
			var sId = getPostID("amado");
			var sStyle = options.style;
			var sDiv = '';
			// id*
			sDiv += '<div id="' + amadID + '"';
			if ($(amad).attr("id")) {
				sDiv += ' id="' + $(amad).attr("id") + '"';
			}
			// *id
			// class*
			sDiv += ' class="ColorCombobox_Main';
			if ($(amad).attr("class")) {
				sDiv += ' ' + $(amad).attr("class")
			}
			sDiv += '"';
			// *class
			sDiv += (sStyle != "") ? ' style="' + sStyle + '"' : '';
			sDiv += '></div>';
			$(amad).before(sDiv);
			$(amad).appendTo($("#" + sId));
		}
		function next() {
			var titletextid = getPostID("postTitleTextID");
			var childid = getPostID("postChildID");
			var allAs = $("#" + childid + " a.enabled");
			for ( var current = 0; current < allAs.length; current++) {
				var currentA = allAs[current];
				var id = $(currentA).attr("id");
				if ($(currentA).hasClass("selected") && current < allAs.length - 1) {
					$("#" + childid + " a.selected").removeClass("selected");
					$(allAs[current + 1]).addClass("selected");
					// manageSelection(allAs[current+1]);
					var selectedA = $("#" + childid + " a.selected").attr("id");
					if (!ddList) {
						var sText = (options.showIcon == false) ? $(a_array[selectedA].text).html() : a_array[selectedA].html;

						setTitleText(sText);
					}
					if (parseInt(($("#" + selectedA).position().top + $("#" + selectedA).height())) >= parseInt($("#" + childid).height())) {
						$("#" + childid).scrollTop(($("#" + childid).scrollTop()) + $("#" + selectedA).height() + $("#" + selectedA).height());
					}
					break;
				}
			}
		}
		function previous() {
			var titletextid = getPostID("postTitleTextID");
			var childid = getPostID("postChildID");
			var allAs = $("#" + childid + " a.enabled");
			for ( var current = 0; current < allAs.length; current++) {
				var currentA = allAs[current];
				var id = $(currentA).attr("id");
				if ($(currentA).hasClass("selected") && current != 0) {
					$("#" + childid + " a.selected").removeClass("selected");
					$(allAs[current - 1]).addClass("selected");
					var selectedA = $("#" + childid + " a.selected").attr("id");
					if (!ddList) {
						var sText = (options.showIcon == false) ? $(a_array[selectedA].text).html() : a_array[selectedA].html;
						setTitleText(sText);
					}
					if (parseInt(($("#" + selectedA).position().top + $("#" + selectedA).height())) <= 0) {
						$("#" + childid).scrollTop(($("#" + childid).scrollTop() - $("#" + childid).height()) - $("#" + selectedA).height());
					}
					break;
				}
			}
		}
		function valueFormat(girdi) {
			doncek = "<span class='" + styles.valueFormat + "'>" + girdi + "</span>";
			return doncek;
		}
		function setValue() {
			var childid = getPostID("postChildID");
			var allSelected = $("#" + childid + " a.selected");
			if (allSelected.length == 1) {
				// var sText = valueFormat($("#"+childid + "
				// a.selected").text());
				var sText = $("#" + childid + " a.selected").text();
				var selectedA = $("#" + childid + " a.selected").attr("id");
				if (selectedA != undefined) {
					var sValue = a_array[selectedA].value;
					$(amad).selectedIndex = a_array[selectedA].index;
				}
			} else if (allSelected.length > 1) {
				var alls = $("#" + elementid + " > option:selected").removeAttr("selected");
				for ( var i = 0; i < allSelected.length; i++) {
					var selectedA = $(allSelected[i]).attr("id");
					var index = a_array[selectedA].index;
					$(amad).options[index].selected = "selected";
				}
			}
		}
		function openMe() {
			if ($.isFunction(options.onOpen)) {
				var deger = (options.showIcon == true) ? currentSelectedValue : $("#" + childid + " a.selected").find("." + styles.valueFormat).html();
				options.onOpen(iid, $("#" + amadID));
			}
			$("#" + amadID + " ." + styles.dd).addClass("acildi");
			var childid = getPostID("postChildID");
			if (oldDiv != "" && childid != oldDiv) {
				$("#" + oldDiv).slideUp("fast", function() {
					
				});
				$("#" + oldDiv).css( {
					zIndex : '0'
				});
			}
			if ($("#" + childid).css("display") == "none") {
				selectedValue = a_array[$("#" + childid + " a.selected").attr("id")].text;
				$(document).bind("keydown", function(event) {
					var keyCode = event.keyCode;
					if (keyCode == 39 || keyCode == 40) {
						// move to next
						event.preventDefault();
						event.stopPropagation();
						next();
					}
					if (keyCode == 37 || keyCode == 38) {
						event.preventDefault();
						event.stopPropagation();
						// move to previous
						previous();
					}
					if (keyCode == 27 || keyCode == 13) {
						closeMe();
						setValue();
					}
					if ($(amad).attr("onkeydown") != undefined) {
						$(amad).onkeydown();
					}
				});
				$(document).bind("keyup", function(event) {
					if ($(amad).attr("onkeyup") != undefined) {
						// $("#"+elementid).keyup();
						$(amad).onkeyup();
					}
				});
				$(document).bind("mouseup", function(evt) {
					if (getInsideWindow() == false) {
						closeMe();
					}
				});
				$(document).bind("blur", function() {

					// closeMe();

					});
				$("#" + childid).css( {
					zIndex : options.zIndex
				});
				$("#" + childid).slideDown(options.slideDownSpeed, function() {
					if ($.isFunction(options.onOpened)) {
						var deger = (options.showIcon == true) ? currentSelectedValue : $("#" + childid + " a.selected").find("." + styles.valueFormat).html();
						options.onOpened(iid, $("#" + amadID));
					}
				});
				if (childid != oldDiv) {
					oldDiv = childid;
				}
			}
		}
		function closeMe() {

			var childid = getPostID("postChildID");
			$(document).unbind("keydown");
			$(document).unbind("keyup");
			$(document).unbind("mouseup");
			$("#" + childid).slideUp(options.slideUpSpeed, function(event) {
				checkMethodAndApply();
				$("#" + childid).css( {
					zIndex : '0'
				});
			});
			$("#" + amadID + " ." + styles.dd).removeClass("acildi");
		}
		function checkMethodAndApply() {
			var childid = getPostID("postChildID");
			// TODO
			var currentSelectedValue = a_array[$("#" + childid + " a.selected").attr("id")].text;
			var currentSelectedIndex = a_array[$("#" + childid + " a.selected").attr("id")].index;
			var seciliDeger = $(amad).find("option:eq(" + currentSelectedIndex + ")").val();

			if (selectedValue != currentSelectedValue) {
				if (amadName != "") {
					$("[name=" + amadName + "]").val(seciliDeger);
				}
				if ($.isFunction(options.onChange)) {
					var deger = (options.showIcon == true) ? currentSelectedValue : $("#" + childid + " a.selected").find("." + styles.valueFormat).html();
					options.onChange(seciliDeger, deger, iid, $("#" + amadID));
				}
			}

			if ($(amad).attr("onmouseup") != undefined) {
				$(amad).onmouseup();
			}
			if ($(amad).attr("onblur") != undefined) {
				$(document).bind("mouseup", function(evt) {
					$(amad).focus();
					$(amad)[0].blur();
					setValue();
					$(document).unbind("mouseup");
				});
			}
		}
		function hightlightArrow(ison) {

		}
	};
	$.fn.AmadCombobox = function(properties) {
		var dds = $(this);
		$.each(dds, function(a, b) {
			if (properties == undefined) {
				$(b).dd();
			} else {
				$(b).dd(properties);
			}
		});
	};
})(jQuery);
