/**
 * @name: dd.js
 * @author: Marghoob Suleman - http://www.marghoobsuleman.com/
 * @version: 1.0 
 * @date: March 09, 2009 
 * @updated: March 20, 2009
 * @category: Javascript Custom Component
 * @copyright (c) 2009 Marghoob Suleman (http://www.giftlelo.com/)
 */
MSDropDown = {
	settings: {
				theme:'blue', //will use later
				autoHide:'off', //will use later
				offClass:'aOff',
				onClass:'aOn',
				maintainHeight:0,
				idpostfixmain:'_ms',
				idpostfixchild:'_child',
				idpostfixa:'_msa',
				idposttitle: '_title',
				idhidden: '_input',
				showTitle:true,
				visibleRows:10 //will use later
			  },
	styles: {
			ddclass:'msDropDown',
			childclass:'msDropDown_Child',
			/*arrow: 'msdropdown/dd_arrow.gif',*/
			arrowclass: 'msArrow',
			titleclass: 'msDropdownTitle'
			},
	selected: new Object(),
	zIndex:999,
	insideWindow:false,
	ddfunction:new Array('onchange', 'click', 'onfocus'),//will use later
	dp_array:{},
	currentDiv:'',
	init: function(byID) {
		this.selected = new Object();
		this.dp_array = new Object();
		//make cutomdropdowns
		this.makeCustomDropDowns(byID);
	},
	showTitle: function(show) {
		this.settings.showTitle = show;
	},
	getShowTitle: function() {
		return this.settings.showTitle;
	},
	setVisibleRows: function(rows) {
		this.settings.visibleRows = rows;
	},
	getVisibleRows: function() {
		return this.settings.visibleRows;
	},
	makeCustomDropDowns: function(byID) {
			var dps = this.getAllDropDown(byID);
			var total = dps.length;
			for(var iCount=0;iCount<total;iCount++) {
				var currentSelect = dps[iCount];
				if(currentSelect.id!=undefined) {
					var prop = new Array();
					if($("#"+currentSelect.id).attr("onchange")!=undefined) {
						var onchange = $("#"+currentSelect.id).attr("onchange");
						prop["onchange"] = onchange;
					}
					//console.debug("onchange " + typeof onchange)
					//format dropdown
					var width = $(currentSelect).width();
					var height = $(currentSelect).height();
					$(currentSelect).css({width:width+'px'})
					
					var oOptions = $("#"+currentSelect.id +"> *");
					var totalOptions = oOptions.length;
					//internal counter
					for(var optionCount=0;optionCount<totalOptions;optionCount++) {
						var currentOption = oOptions[optionCount];
						var values = this.getOptionsProperties(currentOption);
						prop.push(values);
						//alert(prop);						
					}
					prop["id"] = currentSelect.id;
					
					prop["position"]= $("#"+currentSelect.id).position();
					prop["width"]= $("#"+currentSelect.id).width();
					prop["height"]= $("#"+currentSelect.id).height();
					//store
					this.store(currentSelect.id, prop);
				}
			}
			//Make
			this.makeAdropDown();			
	},
	setOutOfVision: function(id) {
		$("#"+id).css({position:'absolute', left:'-500px', top:'-500px'});
	},
	makeAdropDown: function(byId) {
		
		var alldps = this.getdps();
		var idMain = this.settings.idpostfixmain;
		var idChild = this.settings.idpostfixchild;
		var idhidden = this.settings.idhidden;
		var idA = this.settings.idpostfixa;
		var idtitle = this.settings.idposttitle;
		var ddclass = this.styles.ddclass;
		var childclass = this.styles.childclass;
		var arrowclass = this.styles.arrowclass;
		var arrow = this.styles.arrow;
		var titleclass = this.styles.titleclass;
		var counter = 0;
		for(i in alldps) {
			var id = i;
			//hide original dropdown
			this.setOutOfVision(id);
			
			var values = alldps[i];
			//make a dropdown
			var position = values.position;
			var width = (values.width)+ 'px';
			var titlewidth = values.width  - 18 + 'px';
			//console.debug(id, " position.top " + position.top + " position.left  " + position.left)
			var top = position.top + 'px'; //remove 100 when finalize
			var left = position.left + 'px';
			var dd_id = id+idMain+counter;
			var childid = dd_id+idChild;
			var titleid = dd_id+idtitle;
			var hiddeninput = dd_id+idhidden;
			var onchange = values.onchange;
			//alert(onchange)
			//make main holder //
			var childheight = '';
			//alert("values.length " + values.length)
			if(values.length>this.getVisibleRows()) childheight = '120';
			var ddhtml = "";
			var zIndex = this.zIndex--;
			ddhtml += "<div id='"+dd_id+"' class='"+ddclass+"' style='position:absolute;width:"+width+"281px; ;top:"+top+";left:"+left+";z-Index:"+zIndex+"' >"; //main div
			ddhtml += "<div class='cursorpointer' onclick=\"MSDropDown.openDropDown('"+dd_id+"')\"><div class='"+arrowclass+"'></div><div style='width:251px"+"' class='"+titleclass+"' id='"+titleid+"'>Loading...</div><input type='text' value='' id='"+hiddeninput+"' name='"+hiddeninput+"' /> </div>";//title div
			ddhtml += "<div id='"+childid+"' class='coloredScroll "+childclass+"' style='width:"+(values.width+2)+"px'>" //child div
			var ahtml = "";
			//create a tag
			var sValue = "";
			for(var aCount=0;aCount<values.length;aCount++) {
				var curretna = values[aCount];
				var aID = dd_id+"_a_"+aCount;
				var value = curretna.value;
				if(aCount==0) 
				var selectedID =  aID;
				var text = curretna.text;
				var selected = curretna.selected;
				if(selected=='selected') {
					sValue = text;
					selectedID = aID;
				}
				var icon = curretna.icon;
				var img = "";
				var sTitle = (this.getShowTitle() == true) ? text : '';
				//alert("icon " + icon)
				if(icon != undefined) img = "<img class='icon' align='left' src='"+icon+"' />";
				ahtml += "<a id='"+aID+"' title='"+sTitle+"' style='display:block' href='javascript:void(0);' onclick=\"MSDropDown.setSelected('"+dd_id+"', '"+text+"', '"+aID+"')\">"+img + text+"</a>" //a tag
			}
			sValue = (sValue=='') ? values[0].text : sValue;
			ddhtml += ahtml;
			ddhtml += "</div>" //child div end
			ddhtml += "</div>" //main div end			
			counter++;
			$("body").append(ddhtml);
			if(childheight!='') $("#"+childid).css({ overflowY:'scroll', overflowX:'hidden', height:childheight+'px'});
			//selected
			$("#"+titleid).html(sValue);
			//console.debug("id " + id + " selectedID " + selectedID)
			this.manageSelection(id, selectedID);
			this.setOutOfVision(hiddeninput);
		}
		
	},
	manageSelection: function(id, selected) {
		if(this.selected[id]==undefined) {
			this.selected[id] = {selected:selected, previous:selected}
		}

		this.selected[id].selected = selected;		
		if(this.selected[id].previous != this.selected[id].selected) { 
			$("#"+ this.selected[id].previous).removeClass('selected');
		}
		$("#"+ this.selected[id].selected).addClass('selected');
		this.selected[id].previous = this.selected[id].selected;
	},
	getOptionsProperties: function(option) {
		//returns : options, selected, icons
		var currentOption = option;
		var prop = new Object();
		prop["text"] = currentOption.text;
		//if(currentOption.hasAttributes) {
			var attribs = currentOption.attributes; 
			var total = attribs.length;
			for(iCount=0;iCount<total;iCount++) {
				var att = attribs[iCount];
				prop[att.nodeName] = att.nodeValue;
			}
		//}
		return prop;
	},
	store: function(id, prop) {
		this.dp_array[id] = prop;
	},
	getdps: function(byID) {
		return (byID==undefined) ? this.dp_array : this.dp_array[byID];
	},
	getAllDropDown: function(byID) {
		//will work later
		return (byID==undefined) ? $("body select") : $(byID);
	},
	setSelected: function(id, value, aID) {
		var parentID = id.split("_")[0];
		this.selected[parentID].current = aID;
		var sID = id;
		var oPorop = prop;
		var targetDiv = sID+this.settings.idposttitle //"_title";
		var hiddeninput = sID+this.settings.idhidden;
		var prop = this.getdps(parentID);
		//eval()(value, prop);
		$("#"+parentID).val(value);
		$("#"+parentID).focus(); 
		//check if there is onchange method;
		if($("#"+parentID).attr("onchange")!=undefined)
			document.getElementById(parentID).onchange();
		// make a hidden input for focus :)
		//eval(prop.onchange)(value);
		$("#"+targetDiv).text(value);
		$("#"+hiddeninput).val(value);
		$("#"+hiddeninput).focus();
		this.manageSelection(parentID, aID);
		//alert(this.selected[parentID].current);
		this.closeDropDown();
	},
	openDropDown:function(id) {
		//$("#city").text = "Delhi";
		var prentDiv = id;
		var position = $("#"+prentDiv).position();
		//console.debug("prentDiv " + prentDiv + " position " + position.left, position.top)
		var childPosTop = $("#"+prentDiv).height() + parseInt($("#"+prentDiv).css("padding-top")) + 'px';
		//var position = $("#dropdownid_msuniqueid").position();
		var childDiv = id+="_child";
		//console.debug($("#"+prentDiv).width() + " " + $("#"+childDiv).width())
		var parentWidth = parseInt($("#"+prentDiv).width());
		var childWidth = parseInt($("#"+childDiv).width());
		if(childWidth  < parentWidth) {
			$("#"+childDiv).css({width:$("#"+prentDiv).width()+'px'});
			//console.debug($("#"+prentDiv).width() + " " + $("#"+childDiv).width());
		}
		this.currentDiv = childDiv;
		$("#"+childDiv).css({position:'absolute', top:childPosTop, left:'-1px'})
		$("#"+childDiv).slideDown("fast");
		$("#"+childDiv).mouseover(function(e) {
									MSDropDown.setInsideWindow(true);
									})
		$("#"+childDiv).mouseout(function(e) {
									MSDropDown.setInsideWindow(false);
									})
		$(document).mouseup(function(e) {
									if(MSDropDown.insideWindow==false) 
									   MSDropDown.closeDropDown();
								   })
	},
	setInsideWindow: function(set) {
		this.insideWindow = set;
	},
	closeDropDown: function() {
		$("#"+this.currentDiv).slideUp("fast");
	}
	
}

//how to call
/*
$(document).ready(function(e) {
						   MSDropDown.init();
						   }
				  )
*/