// Fix for IE background flicker
if($.browser.msie && parseInt($.browser.version) == 6){
	document.execCommand("BackgroundImageCache", false, true);
}


// Font replacement
Cufon.replace('h1, div#homepagePromiseBoxContent label, .adviceBox h2, #promisepageCarbonBoxContent p, #promisepageHelpCol h2, #promisepageMetaCol h2, #adviceCallToActionBoxContent h2, #promisePageSection2 h2, dl.statslist dt');


$( function() {
	
	// Fix PNGs for IE6
	$('.adviceBalloon, .pngFix, #homepageTotaliserBalloons img, #socialNetworkIcons img, #browsePromisesSpeechbubble, #promisepagePromiseCount img, #sheffieldUnitsIllustration').pngFix();
	
	// Add validation to ensure a promise is selected on the homepage
	var homepagePromiseForm = $('#homepagePromiseForm');
	if (homepagePromiseForm.length) {		
		homepagePromiseForm.submit( function(e) {
			if ($('#homepagePromises').val() == '') {
				alert( 'Please select a promise' );
				e.stopPropagation();
				return false;
			} else {
				// Instead of submitting, let's redirect to the page, to preserve a nice URL
				// submission still works, so we can degrade nicely
				window.location.href = "/promise/make/" + $('#homepagePromises').val() ;
				e.stopPropagation();
				return false;
			}
			
			
		});
	};
	
	
	
	// Prepare the "make a promise" form on promise submission page	
	var promiseForm = $('#promiseForm');
	if (promiseForm.length) {		
	
			
		// Insert a tooltip container, and hide it
		$('body').append('<div id="formTooltip">Tooltip</div>');
		$('#formTooltip').hide();
		
		// Remember the initial title value in a data field
		var $textInputs = promiseForm.find('input[type=text]');
		
		// Store the initial title value in a data field
		$textInputs.each( function() {
			$(this).data('tooltip', $(this).attr('title'));
		});
		
		// Attach events to focus and blur of each field
		$textInputs.focus( function () {
			var $this = $(this);
			var pos = $this.offset(); // Get the position of the current field
			var $thisTooltip = $('#formTooltip').text(  $this.data('tooltip')  ).show();	// Set the text of the tooltip and show it		
			$thisTooltip.css( {top: (pos.top - $thisTooltip.height() -20) +'px', left: (pos.left +90 ) + 'px'}); // Move it into position			
		}).blur( function () {
			$('#formTooltip').hide();
		});
				
		// Copy the value from the label to the title field
		var label = $('#promiseForm label');
			
		// For each label...
		label.each( function() {			
			var theField = $(this).attr('for');
			$('#'+theField).attr('title', $(this).text());	// Move the label text to the title	
		});
				
		// Add the auto clear behaviour
		$('#promiseForm input[type=text]').toggleVal();
		
		
		// Add validation
		$('#promiseForm').validate( {
			messages: {
				username: 'Please enter your name.',
				email:  { 
					required: "Please enter your e-mail address.",
       				email: "Your email address must be in the format of name@domain.com"
				},
				terms: 'Please tick the box to indicate you agree.'	
			},
			errorPlacement: function( error, element) {
					
				if (element.attr("id") == "promiseTerms") {
				   error.insertAfter("#promiseGoButton").attr('id', 'checkboxError');
				} else {
				   error.insertAfter(element);
				}
			}
		});
		
		
	};
	
	
	// Autoselect forms with autoSelect class
	$('.autoSelect').autoSelect();
	
	
	// transform select box on homepage
	$("#homepagePromiseForm select").msDropDown({visibleRows: 5, rowHeight: 25});
	
	// Add some keyboard controls; make the homepage dropdown focusable with a tabindex...
	$('.dd').attr('tabindex', '0');
	// Stop other homepage dropdown options being tabbable (accessible with arrow keys instead, consistent with browser default behaviour)
	$('.ddChild a').attr('tabindex', '-1');
	
	// Trigger homepage dropdown on tabbed in
	$('.dd').keyup(function(e) {
		if (e.keyCode == 9 && !$('.ddChild:visible').length ) {			
			$('.ddTitle').click();	
		} 
	}).blur( function(e) {		
		if (!$(e.target).find('.ddChild a').length) {
			$('.ddChild a.selected').click();	
		}
	});

	
	
	// Track clicks on social networking via Google Analytics events
	$('ul#socialNetworkIcons a').click( function() {
		var $this = $(this);
		if (typeof(pageTracker) != 'undefined') {
			// Where are we sending to?
			var destination = $this.find('img').attr('title');
			pageTracker._trackEvent('Social networks', 'Shared', destination);
		}
	});
	
	

	// Display all promises
	if ($('body.allPromisesBody').length) {
		
		// Hide the title, and prepare some other bits for this different screen
		$('h1').addClass('hide');
		$('body').addClass('hasScript');
		$('#groundSignposts').append('<img src="/assets/templates/simp/images/browse-promises-speechbubble.png" alt="Recent promises made by people who want to make a positive difference to Sheffield and our planet. Hover over each balloon to find out more." width="348" height="95" id="browsePromisesSpeechbubble" />');
		$('#browsePromisesSpeechbubble').pngFix();
		$('.loading').hide();		
		$('a.skip:first').after('<div><a class="skip" tabindex="2" href="javascript:toggleView();">Keyboard friendly version</a></div>');
		
		$('body').prepend('<div id="allBalloons"></div>');
		$('body').prepend('<div id="balloonTooltip"><div id="balloonTooltipContent"></div><div id="balloonTooltipFooter"></div></div>');
		
		var $allBalloons = $('#allBalloons'); // Balloon container		
		var $allPromises = $('.singlePromise'); // Promise sources
		var promisesCount = $allPromises.length; // How many promises?
		var numberOfLayers = 3;
		var divisionSize = Math.ceil(promisesCount/numberOfLayers);
		var windowWidth = $(window).width();
			
			
			// Create a balloon for each promise
			$allPromises.each( function(i) {
			
				var $this = $(this);					
					
				// Which layer are we on?
				var layer = Math.floor(i/divisionSize);	
				
				// Which category does this belong to?					
				var category = '';
				if ($this.hasClass('travel')) category = 'travel'; 
				if ($this.hasClass('energy')) category = 'energy';
				if ($this.hasClass('local')) category = 'local';
				
				
				// Define some properties about the layout of this balloon
				var id = 'balloon'+i; // Create an ID for this balloon
				var zindex = ((numberOfLayers-layer)*1000)+i; // Work out a z-index
				
				var balloon = {					
					w: null, // Width (set later)
					h: null, // Height (set later)
					initialX: null, // Initial X position relative to screen (set later)
					initialY: null, // Initial Y position relative to screen (set later)
					layerWidth: null, // The width of this balloon's layer (set later)					
					bubbleOffsetX: null,	// Where to position the tooltip (set later)
					bubbleOffsetY: null,	// Where to position the tooltip (set later)
					entropy: rnd(75,175)
				};
				
				// How big are images (based on current layer)?
				switch (layer) {
					case 0: balloon.w = 123; balloon.h = 152; balloon.layerWidth = windowWidth*2.5; balloon.bubbleOffsetX = 50; balloon.bubbleOffsetY = 30;
					break;
					case 1: balloon.w = 79; balloon.h = 96; balloon.layerWidth = windowWidth*1.8; balloon.bubbleOffsetX = 30; balloon.bubbleOffsetY = 30;
					break;
					case 2: balloon.w = 41; balloon.h = 50; balloon.layerWidth = windowWidth*1.2; balloon.bubbleOffsetX = 18; balloon.bubbleOffsetY = 25;
					break;
				}
				
				// Rollover text
				var rolloverHtml = $this.html();
				var theLink = $this.find('a');
				var linkUrl = theLink.attr('href');
				var linkText = theLink.text();
				
				// Create a div, and put an image inside it along with original HTML. Then insert it into the balloon container
				var newHTML = '<a class="singleBalloon '+category+' layer'+layer+'" style="width: '+balloon.w+'px; height: '+balloon.h+'px" id="'+id+'" tabindex="-1" href="'+linkUrl+'"><img src="/assets/templates/simp/images/plain-balloons/level'+layer+'/'+category+'.png" width="'+balloon.w+'" height="'+balloon.h+'" alt="'+linkText+'" class="balloonImg" /></a>';
				$allBalloons.append(newHTML);
				
				// Hide the original promise HTML
				$this.hide();	
				
				// Reference to the item
				var $id = $('#'+id);
				
				// For IE6
				$id.find('img').pngFix(); 
				
				// Where to position it?
				balloon.initialX = Math.round(rnd(0,balloon.layerWidth));
				balloon.initialY = rnd(0,200);	
				
				// Do the positioning
				$id.css({ zIndex: zindex, left: balloon.initialX+'px', top: balloon.initialY+'px'});
				
				// Store the data so we can access it later
				$id.data('balloon', balloon); 
				
				
				// Attach a mouseover event to each balloon
				$id.mouseover(function() {
					var offset = $(this).addClass('active').offset();					
					$('#balloonTooltipContent').html( rolloverHtml );				
					$('#balloonTooltip').css({top: (offset.top+balloon.h-balloon.bubbleOffsetY)+'px', left: (offset.left+balloon.w-balloon.bubbleOffsetX)+'px' }).show();					
					//$('.singleBalloon').css('opacity', 0.5);
					//$this.css('opacity', 1);
					
				});
				$id.mouseout(function() {
					$(this).removeClass('active');
					$('#balloonTooltip').hide();
				//	$('.singleBalloon').css('opacity', 1);
				})
				//$id.click( function() {
				//	location.href = linkUrl;
				//})
				
				// Trigger the initial event
				$(document).trigger('mousemove');							
				
			});
		
		// Remember the window width
		var windowWidth = $(window).width();

		// Do this every time the mouse moves
		$(document).mousemove( function(e) {
			
				// If we're displaying a list, do nothing
				if ($('body.list').length) {
					return;	
				}
						
				// How far across is the mouse?
				var horizPos = (e.clientX / windowWidth);
				
				// For each balloon
				$('.singleBalloon').each( function() {					
					
					var $this = $(this);
					var balloon = $this.data('balloon');
					
					if (typeof(balloon) == 'undefined') return;
					
					var newX = Math.round( ( (windowWidth - balloon.layerWidth + balloon.w)*horizPos*(balloon.entropy/100) ) + balloon.initialX ) ;
					$this.css('left', newX+'px');
					
					if ($this.hasClass('active')){
						$('#balloonTooltip').css({top: ($this.offset().top+balloon.h-balloon.bubbleOffsetY)+'px', left: (newX+balloon.w-balloon.bubbleOffsetX)+'px' });	
					}					
				});	
							
				e.stopPropagation();
		});

		
	}
	
	 
	
	// Poll?
	if ($('div#easypoll').length) {
		var jseasypoll = new EasyPollAjax("easypoll");	
	}
	
	// Social Media Tray
	// Don't do anything for IE6 or Opera, default, non-scripted functionality is fine
	if((!$.browser.opera) && ((!$.browser.msie) || ($.browser.msie && (parseInt($.browser.version)) != 6))) {
		$("#socialMediaTray").addClass("scripted").after("<div id=\"socialMediaDarken\">&nbsp;</div>");
		$("#socialMediaDarken").hide().css("opacity", "0.0").click(function(evt) {
			$("#socialMediaTray").animate({right: -368}, 300, function() { $(this).removeClass("open"); });
			$("#socialMediaDarken").fadeTo(300, 0.0, function() { $(this).hide(); });
		});

		$("#socialMediaTray .fbLink").click(function(event) {
			event.preventDefault();
			window.open($(this).attr("href"), "fbShare", "toolbar=0,status=0,resizable=1,width=626,height=436");
		});
		
		$("#socialMediaTray h5").click(function(evt) {
			if(parseInt($("#socialMediaTray").css("right")) < 0)
			{
				$("#socialMediaTray").animate({right: 0}, 300, function() { $(this).addClass("open"); });
				$("#socialMediaDarken").show().fadeTo(300, 0.7);
			}
			else
			{
				$("#socialMediaTray").animate({right: -368}, 300, function() { $(this).removeClass("open"); });
				$("#socialMediaDarken").fadeTo(300, 0.0, function() { $(this).hide(); });
			}
		});
	}
	
	// Get Involved ticker
	if($("#getInvolvedTicker").length != 0)
	{
		$($("#getInvolvedTicker li")[0]).addClass("showing");
		
		var advanceTicker = function() {
			$("#getInvolvedTicker li.showing").animate({
				opacity: "0",
				top: "+=40"
			}, "slow", function() {
				$(this).removeClass("showing");
				
				var nxt = $(this).next();
				nxt = (nxt.length == 0) ? $($("#getInvolvedTicker li")[0]) : nxt;
				
				nxt.css({top: "-25px", opacity: 0, display: "block"}).animate({
					opacity: "1",
					top: 0
				}, "fast", function() { $(this).addClass("showing"); });
			});
		};
		
		var timer = setInterval(advanceTicker, 6000);
		$("#getInvolvedTicker ul").mouseenter(function(evt) { clearInterval(timer); }).
			mouseleave(function(evt) { timer = setInterval(advanceTicker, 6000); });
	}
});


// Controls for toggling the balloon/list all promises view
function toggleView() {
	if ($('body.list').length) {
		showBalloons();
	} else {
		showList();
	}
}
function showList() {
	$('body').addClass('list').removeClass('balloons');
	$('#allBalloons, #browsePromisesSpeechbubble').hide();
	$('#allPromises div').show();
}
function showBalloons() {
	$('body').addClass('balloons').removeClass('list');
	$('#allBalloons, #browsePromisesSpeechbubble').show();
	$('#allPromises div').hide();
}


function rnd(theMin,theMax) {	
	var range = theMax - theMin;
	return  Math.floor(Math.random()*(range+1)) + theMin;
}



/**
* toggleVal
* Have auto clearing text in a form field
*/
(function($) {
	$.fn.toggleVal = function(focusClass) {
		
	return this.each(function() {
		
		var theEl = this;	// The element with the focus class
		var theField = 	$(this);	// Extend it for Jquery
		
		if (theField.attr('type') != 'text') { return; }
			
		// What is the title?
		var theDefaultTitle = theField.attr('title');		
		
		// If the form field is initially empty, insert the title as a label
		if (theField.val() == '') {
			theField.val(theDefaultTitle);
		}
		
		// Attach events to focus and blur events
		theField.focus(function() {								
			// clear value if current value is the title
			if(theField.val() == theDefaultTitle) { theField.val(""); }			
			// if focusClass is set, add the class
			if(focusClass) { theField.addClass(focusClass); }
		}).blur(function() {
			// restore to the default value if current value is empty
			if(theField.val() == "") { theField.val(theDefaultTitle); }			
			// if focusClass is set, remove class
			if(focusClass) { theField.removeClass(focusClass); }
		});
		
		theField.data('defaultTitle', theDefaultTitle);
		
		// If the form is submitted but the value is the default, clear it so it isn't submittted
		theField.parents('form').submit(function() {	
							if(theField.val() == theDefaultTitle) { theField.val(""); }
											   });
	});
	};
})(jQuery);






/**
* autoSelect
* Automatically select the contents of a form field when clicked - just add the autoSelect method to any jQuery object
*/
(function($) {	 
	$.fn.autoSelect = function(){		
		return this
			.each(function() {
				$(this).click( function() { this.select(); });
			})			
	};	
})(jQuery);








/**
 * --------------------------------------------------------------------
 * jQuery-Plugin "pngFix"
 * Version: 1.2, 09.03.2009
 * by Andreas Eberhard, andreas.eberhard@gmail.com
 *                      http://jquery.andreaseberhard.de/
 *
 * Copyright (c) 2007 Andreas Eberhard
 * Licensed under GPL (http://www.opensource.org/licenses/gpl-license.php)
 *
 * Changelog:
 *    09.03.2009 Version 1.2
 *    - Update for jQuery 1.3.x, removed @ from selectors
 *    11.09.2007 Version 1.1
 *    - removed noConflict
 *    - added png-support for input type=image
 *    - 01.08.2007 CSS background-image support extension added by Scott Jehl, scott@filamentgroup.com, http://www.filamentgroup.com
 *    31.05.2007 initial Version 1.0
 * --------------------------------------------------------------------
 * @example $(function(){$(document).pngFix();});
 * @desc Fixes all PNG's in the document on document.ready
 *
 * jQuery(function(){jQuery(document).pngFix();});
 * @desc Fixes all PNG's in the document on document.ready when using noConflict
 *
 * @example $(function(){$('div.examples').pngFix();});
 * @desc Fixes all PNG's within div with class examples
 *
 * @example $(function(){$('div.examples').pngFix( { blankgif:'ext.gif' } );});
 * @desc Fixes all PNG's within div with class examples, provides blank gif for input with png
 * --------------------------------------------------------------------
 */

(function($) {

jQuery.fn.pngFix = function(settings) {

	// Settings
	settings = jQuery.extend({
		blankgif: 'blank.gif'
	}, settings);

	var ie55 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 5.5") != -1);
	var ie6 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 6.0") != -1);

	if (jQuery.browser.msie && (ie55 || ie6)) {

		//fix images with png-source
		jQuery(this).find("*").andSelf().filter("img[src$=.png]").each(function() {

			jQuery(this).attr('width',jQuery(this).width());
			jQuery(this).attr('height',jQuery(this).height());

			var prevStyle = '';
			var strNewHTML = '';
			var imgId = (jQuery(this).attr('id')) ? 'id="' + jQuery(this).attr('id') + '" ' : '';
			var imgClass = (jQuery(this).attr('class')) ? 'class="' + jQuery(this).attr('class') + '" ' : '';
			var imgTitle = (jQuery(this).attr('title')) ? 'title="' + jQuery(this).attr('title') + '" ' : '';
			var imgAlt = (jQuery(this).attr('alt')) ? 'alt="' + jQuery(this).attr('alt') + '" ' : '';
			var imgAlign = (jQuery(this).attr('align')) ? 'float:' + jQuery(this).attr('align') + ';' : '';
			var imgHand = (jQuery(this).parent().attr('href')) ? 'cursor:hand;' : '';
			if (this.style.border) {
				prevStyle += 'border:'+this.style.border+';';
				this.style.border = '';
			}
			if (this.style.padding) {
				prevStyle += 'padding:'+this.style.padding+';';
				this.style.padding = '';
			}
			if (this.style.margin) {
				prevStyle += 'margin:'+this.style.margin+';';
				this.style.margin = '';
			}
			var imgStyle = (this.style.cssText);

			strNewHTML += '<span '+imgId+imgClass+imgTitle+imgAlt;
			strNewHTML += 'style="position:relative;white-space:pre-line;display:inline-block;background:transparent;'+imgAlign+imgHand;
			strNewHTML += 'width:' + jQuery(this).width() + 'px;' + 'height:' + jQuery(this).height() + 'px;';
			strNewHTML += 'filter:progid:DXImageTransform.Microsoft.AlphaImageLoader' + '(src=\'' + jQuery(this).attr('src') + '\', sizingMethod=\'scale\');';
			strNewHTML += imgStyle+'"></span>';
			if (prevStyle != ''){
				strNewHTML = '<span style="position:relative;display:inline-block;'+prevStyle+imgHand+'width:' + jQuery(this).width() + 'px;' + 'height:' + jQuery(this).height() + 'px;'+'">' + strNewHTML + '</span>';
			}

			jQuery(this).hide();
			jQuery(this).after(strNewHTML);

		});

		// fix css background pngs
		jQuery(this).find("*").andSelf().each(function(){
			var bgIMG = jQuery(this).css('background-image');
			if(bgIMG.indexOf(".png")!=-1){
				var iebg = bgIMG.split('url("')[1].split('")')[0];
				jQuery(this).css('background-image', 'none');
				jQuery(this).get(0).runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + iebg + "',sizingMethod='scale')";
			}
		});
		
		//fix input with png-source
		jQuery(this).find("input[src$=.png]").each(function() {
			var bgIMG = jQuery(this).attr('src');
			jQuery(this).get(0).runtimeStyle.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader' + '(src=\'' + bgIMG + '\', sizingMethod=\'scale\');';
   		jQuery(this).attr('src', settings.blankgif)
		});
	
	}
	
	return jQuery;

};

})(jQuery);







/**
 * Script part for EasyPoll Snippet.
 * Enables the Poll to be updated via AJAX
 * Rewritten to use jQuery by nick crossland
 *
 * @author banal
 * @version 0.2 (2008-02-08)
 */
 
 
 var EasyPollAjax = function(identifier) {
	 
	
	// Make sure we're getting valid arguments
	if(typeof identifier != 'string'){
		alert('EasyPoll Constructor: invalid arguments');
		return;
	};
	
	// Modify this value 
	if($('#'+identifier)){
		$('#'+identifier + 'ajx').val('1');
	};
	
	var $theForm = $('#'+identifier +'form');	
	
	
	/** register a button to fire a ajax request */
	var registerButton = function(button){
		
		if(button == 'submit' || button == 'result'){
						
			var $theButton = $('#'+identifier + button);
			
			if(!$theButton.length){ return; };

			$theButton.click( function(e){
				
				e.stopPropagation();
				e.preventDefault();
				
				// Have they selected an option?
				if (button == 'submit' && !$theForm.find(':checked').length) {
					alert('Please choose an option to vote for');
					return false;	
				}
				
				$.post(	$theForm.attr('action'), 
						$theForm.serialize() + '&' + button + '=1',
						function ( data, status) {
							$('#'+identifier).html(data);
							registerButton('vote');
						}
				);
				
				return false;
			});
		} else if (button == 'vote') {
						
			$('#'+identifier + button).click( function(){
				history.go(0);
			});
			
		}
		
	}
	
	registerButton('submit');	
	registerButton('result');

 }
 
 
 
// MSDropDown - jquery.dd.js
// author: Marghoob Suleman - Search me on google
// Date: 12th Aug, 2009
// Version: 2.3 {date: 12 June 2010}
// Revision: 28
// web: www.giftlelo.com | www.marghoobsuleman.com
/*
// msDropDown is free jQuery Plugin: you can redistribute it and/or modify
// it under the terms of the either the MIT License or the Gnu General Public License (GPL) Version 2
*/
;(function($) {
   var msOldDiv = ""; 
   var dd = function(element, options)
   {
		var sElement = element;
		var $this =  this; //parent this
		var options = $.extend({
			height:120,
			visibleRows:7,
			rowHeight:23,
			showIcon:true,
			zIndex:9999,
			mainCSS:'dd',
			useSprite:false,
			onInit:'',
			style:''
		}, options);
		this.ddProp = new Object();//storing propeties;
		var selectedValue = "";
		var actionSettings ={};
		actionSettings.insideWindow = true;
		actionSettings.keyboardAction = false;
		actionSettings.currentKey = null;
		var ddList = false;
		var config = {postElementHolder:'_msddHolder', postID:'_msdd', postTitleID:'_title',postTitleTextID:'_titletext',postChildID:'_child',postAID:'_msa',postOPTAID:'_msopta',postInputID:'_msinput', postArrowID:'_arrow', postInputhidden:'_inp'};
		var styles = {dd:options.mainCSS, ddTitle:'ddTitle', arrow:'arrow', ddChild:'ddChild', ddTitleText:'ddTitleText', disabled:.30, ddOutOfVision:'ddOutOfVision'};
		var attributes = {actions:"focus,blur,change,click,dblclick,mousedown,mouseup,mouseover,mousemove,mouseout,keypress,keydown,keyup", prop:"size,multiple,disabled,tabindex"};
		this.onActions = new Object();
		var elementid = $(sElement).attr("id");
		var inlineCSS = $(sElement).attr("style");
		options.style += (inlineCSS==undefined) ? "" : inlineCSS;
		var allOptions = $(sElement).children();
		ddList = ($(sElement).attr("size")>0 || $(sElement).attr("multiple")==true) ? true : false;
		if(ddList) {options.visibleRows = $(sElement).attr("size");};
		var a_array = {};//stores id, html & value etc
		
	var getPostID = function (id) {
		return elementid+config[id];
	};
	var getOptionsProperties = function (option) {
		var currentOption = option;
		var styles = $(currentOption).attr("style");
		return styles;
	};
	var matchIndex = function (index) {
		var selectedIndex = $("#"+elementid+" 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;
	};
	var createA = function(currentOptOption, current, currentopt, tp) {
		var aTag = "";
		//var aidfix = getPostID("postAID");
		var aidoptfix = (tp=="opt") ? getPostID("postOPTAID") : getPostID("postAID");		
		var aid = (tp=="opt") ? aidoptfix+"_"+(current)+"_"+(currentopt) : aidoptfix+"_"+(current);
		var arrow = "";
		var clsName = "";
		if(options.useSprite!=false) {
		 clsName = ' '+options.useSprite+' '+currentOptOption.className;
		} else {
		 arrow = $(currentOptOption).attr("title");
		 arrow = (arrow.length==0) ? "" : '<img src="'+arrow+'" align="absmiddle" /> ';																 
		};
		//console.debug("clsName "+clsName);
		var sText = $(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+clsName+'"';
		} else {
		aTag += '<a  href="javascript:void(0);" class="'+sEnabledClass+clsName+'"';
		};
		if(innerStyle!==false && innerStyle!==undefined) {
		aTag +=  " style='"+innerStyle+"'";
		};
		aTag +=  ' id="'+aid+'">';
		aTag += arrow + '<span class="'+styles.ddTitleText+'">' +sText+'</span></a>';
		return aTag;
	};
	var createATags = function () {
		var childnodes = allOptions;
		if(childnodes.length==0) return "";
		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];
															 aTag += createA(currentOptOption, current, currentopt, "opt");
															});
									 aTag += "</div>";
									 
								 } else {
									 aTag += createA(currentOption, current, "", "");
								 };
								 });
		return aTag;
	};
	var createChildDiv = function () {
		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;
	};

	var createTitleDiv = function () {
		var titleid = getPostID("postTitleID");
		var arrowid = getPostID("postArrowID");
		var titletextid = getPostID("postTitleTextID");
		var inputhidden = getPostID("postInputhidden");
		var sText = "";
		var arrow = "";
		if(document.getElementById(elementid).options.length>0) {
			sText = $("#"+elementid+" option:selected").text();
			arrow = $("#"+elementid+" option:selected").attr("title");
		};
		//console.debug("sObj	 "+sObj.length);
		arrow = (arrow.length==0 || arrow==undefined || options.showIcon==false || options.useSprite!=false) ? "" : '<img src="'+arrow+'" align="absmiddle" /> ';
		var sDiv = '<div id="'+titleid+'" class="'+styles.ddTitle+'"';
		sDiv += '>';
		sDiv += '<span id="'+arrowid+'" class="'+styles.arrow+'"></span><span class="'+styles.ddTitleText+'" id="'+titletextid+'">'+arrow + '<span class="'+styles.ddTitleText+'">'+sText+'</span></span></div>';
		return sDiv;
	};
	var applyEventsOnA = function() {
		var childid = getPostID("postChildID");
			$("#"+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();
															 //alert("sText "+sText);
															  setTitleText(sText);
															  //$this.data("dd").close();
															  $this.close();
														 };
														 setValue();
														 //actionSettings.oldIndex = a_array[$($this).attr("id")].index;
														 });		
	};
	var createDropDown = function () {
		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 = $("#"+elementid).width();
		iWidth = iWidth+2;//it always give -2 width; i dont know why
		var sStyle = options.style;
		if($("#"+id).length>0) {
			$("#"+id).remove();
			changeInsertionPoint = true;
		};
		var sDiv = '<div id="'+id+'" class="'+styles.dd+'"';
		sDiv += (sStyle!="") ? ' style="'+sStyle+'"' : '';
		sDiv += '>';
		//create title bar
		sDiv += createTitleDiv();
		//create child
		sDiv += createChildDiv();
		sDiv += createATags();
		sDiv += "</div>";
		sDiv += "</div>";
		if(changeInsertionPoint==true) {
			var sid =getPostID("postElementHolder");
			$("#"+sid).after(sDiv);
		} else {
			$("#"+elementid).after(sDiv);
		};
		if(ddList) {
			var titleid = getPostID("postTitleID");	
			$("#"+titleid).hide();
		};
		
		$("#"+id).css("width", iWidth+"px");
		$("#"+childid).css("width", (iWidth-2)+"px");
		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");
		} else if(ddList) {
			var iHeight = $("#"+elementid).height();
			$("#"+childid).css("height", iHeight+"px");
		};
		//set out of vision
		if(changeInsertionPoint==false) {
			setOutOfVision();
			addRefreshMethods(elementid);
		};
		if($("#"+elementid).attr("disabled")==true) {
			$("#"+id).css("opacity", styles.disabled);
		};
		applyEvents();
		//add events
		//arrow hightlight
		$("#"+titleid).bind("mouseover", function(event) {
												  hightlightArrow(1);
												  });
		$("#"+titleid).bind("mouseout", function(event) {
												  hightlightArrow(0);
												  });
			//open close events
		applyEventsOnA();
		$("#"+childid+ " a.disabled").css("opacity", styles.disabled);
		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;});
		$("#"+titleid).bind("click", function(event) {
											  setInsideWindow(false);
												if($("#"+childid+":visible").length==1) {
													$("#"+childid).unbind("mouseover");
												} else {
													$("#"+childid).bind("mouseover", function(event) {setInsideWindow(true);});
													//alert("open "+elementid + $this);
													//$this.data("dd").openMe();
													$this.open();
												};
											  });
		$("#"+titleid).bind("mouseout", function(evt) {
												 setInsideWindow(false);
												 });
		if(options.showIcon && options.useSprite!=false) {
			setTitleImageSprite();
		};
	};
	var getByIndex = function (index) {
		for(var i in a_array) {
			if(a_array[i].index==index) {
				return a_array[i];
			};
		};
		return -1;
	};
	var manageSelection = function (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($("#"+elementid).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;				
			};
			//isSingle
		};		
	};
	var addRefreshMethods = function (id) {
		//deprecated
		var objid = id;
		document.getElementById(objid).refresh = function(e) {
			 $("#"+objid).msDropDown(options);
		};
	};
	var setInsideWindow = function (val) {
		actionSettings.insideWindow = val;
	};
	var getInsideWindow = function () {
		return actionSettings.insideWindow;
	};
	var applyEvents = function () {
		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 = $("#"+elementid).attr(action);
			var actionFound = has_handler(action);//$("#"+elementid).attr(action);
			//console.debug(elementid +" action " + action , "actionFound "+actionFound);
			if(actionFound==true) {
				switch(action) {
					case "focus": 
					$("#"+mainid).bind("mouseenter", function(event) {
													   document.getElementById(elementid).focus();
													   //$("#"+elementid).focus();
													   });
					break;
					case "click": 
					$("#"+mainid).bind("click", function(event) {
													   //document.getElementById(elementid).onclick();
													   $("#"+elementid).trigger("click");
													   });
					break;
					case "dblclick": 
					$("#"+mainid).bind("dblclick", function(event) {
													   //document.getElementById(elementid).ondblclick();
													   $("#"+elementid).trigger("dblclick");
													   });
					break;
					case "mousedown": 
					$("#"+mainid).bind("mousedown", function(event) {
													   //document.getElementById(elementid).onmousedown();
													   $("#"+elementid).trigger("mousedown");
													   });
					break;
					case "mouseup": 
					//has in close mthod
					$("#"+mainid).bind("mouseup", function(event) {
													   //document.getElementById(elementid).onmouseup();
													   $("#"+elementid).trigger("mouseup");
													   //setValue();
													   });
					break;
					case "mouseover": 
					$("#"+mainid).bind("mouseover", function(event) {
													   //document.getElementById(elementid).onmouseover();													   
													   $("#"+elementid).trigger("mouseover");
													   });
					break;
					case "mousemove": 
					$("#"+mainid).bind("mousemove", function(event) {
													   //document.getElementById(elementid).onmousemove();
													   $("#"+elementid).trigger("mousemove");
													   });
					break;
					case "mouseout": 
					$("#"+mainid).bind("mouseout", function(event) {
													   //document.getElementById(elementid).onmouseout();
													   $("#"+elementid).trigger("mouseout");
													   });
					break;					
				};
			};
		};
		
	};
	var setOutOfVision = function () {
		var sId = getPostID("postElementHolder");
		$("#"+elementid).after("<div class='"+styles.ddOutOfVision+"' style='height:0px;overflow:hidden;position:absolute;' id='"+sId+"'></div>");
		$("#"+elementid).appendTo($("#"+sId));
	};
	var setTitleText = function (sText) {
		var titletextid = getPostID("postTitleTextID");
		$("#"+titletextid).html(sText);		
	};
	var next = function () {
		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 : 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;
			};
		};
	};
	var previous = function () {
		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");				
				//manageSelection(allAs[current-1]);
				var selectedA = $("#"+childid + " a.selected").attr("id");
				if(!ddList) {
					var sText = (options.showIcon==false) ? a_array[selectedA].text : a_array[selectedA].html;
					setTitleText(sText);
				};
				if(parseInt(($("#"+selectedA).position().top+$("#"+selectedA).height())) <=0) {
					$("#"+childid).scrollTop(($("#"+childid).scrollTop()-$("#"+childid).height())-$("#"+selectedA).height());
				};
				break;
			};
		};
	};
	var setTitleImageSprite = function() {
		if(options.useSprite!=false) {
			var titletextid = getPostID("postTitleTextID");
			var sClassName = document.getElementById(elementid).options[document.getElementById(elementid).selectedIndex].className;
			if(sClassName.length>0) {
				var childid = getPostID("postChildID");
				var id = $("#"+childid + " a."+sClassName).attr("id");
				var backgroundImg = $("#"+id).css("background-image");
				var backgroundPosition = $("#"+id).css("background-position");
				var paddingLeft = $("#"+id).css("padding-left");
				if(backgroundImg!=undefined) {
					$("#"+titletextid).find("."+styles.ddTitleText).attr('style', "background:"+backgroundImg);
				};
				if(backgroundPosition!=undefined) {
					$("#"+titletextid).find("."+styles.ddTitleText).css('background-position', backgroundPosition);
				};
				if(paddingLeft!=undefined) {
					$("#"+titletextid).find("."+styles.ddTitleText).css('padding-left', paddingLeft);	
				};
				$("#"+titletextid).find("."+styles.ddTitleText).css('background-repeat', 'no-repeat');				
				$("#"+titletextid).find("."+styles.ddTitleText).css('padding-bottom', '2px');
			};
		};		
	};
	var setValue = function () {
		//alert("setValue "+elementid);
		var childid = getPostID("postChildID");
		var allSelected = $("#"+childid + " a.selected");
		if(allSelected.length==1) {
			var sText = $("#"+childid + " a.selected").text();
			var selectedA = $("#"+childid + " a.selected").attr("id");
			if(selectedA!=undefined) {
				var sValue = a_array[selectedA].value;
				document.getElementById(elementid).selectedIndex = a_array[selectedA].index;
			};
			//set image on title if using sprite
			if(options.showIcon && options.useSprite!=false)
				setTitleImageSprite();
		} 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;
				document.getElementById(elementid).options[index].selected = "selected";
			};
		};
		//alert(document.getElementById(elementid).selectedIndex);
		var sIndex = document.getElementById(elementid).selectedIndex;
		$this.ddProp["selectedIndex"]= sIndex;
		//alert("selectedIndex "+ $this.ddProp["selectedIndex"] + " sIndex "+sIndex);
	};
	var has_handler = function (name) {
		// True if a handler has been added in the html.
		if ($("#"+elementid).attr("on" + name) != undefined) {
			return true;
		};
		// True if a handler has been added using jQuery.
		var evs = $("#"+elementid).data("events");
		if (evs && evs[name]) {
			return true;
		};
		return false;
	};
	var checkMethodAndApply = function () {
		var childid = getPostID("postChildID");
		if(has_handler('change')==true) {
			//alert(1);
			var currentSelectedValue = a_array[$("#"+childid +" a.selected").attr("id")].text;
			if(selectedValue!=currentSelectedValue){
				$("#"+elementid).trigger("change");
			};
		};
		if(has_handler('mouseup')==true) {
			$("#"+elementid).trigger("mouseup");
		};
		if(has_handler('blur')==true) { 
			$(document).bind("mouseup", function(evt) {
												   $("#"+elementid).focus();
												   $("#"+elementid)[0].blur();
												   setValue();
												   $(document).unbind("mouseup");
												});
		};
	};
	var hightlightArrow = function(ison) {
		var arrowid = getPostID("postArrowID");
		if(ison==1)
			$("#"+arrowid).css({backgroundPosition:'0 100%'});
		else 
			$("#"+arrowid).css({backgroundPosition:'0 0'});
	};
	var setOriginalProperties = function() {
		//properties = {};
		//alert($this.data("dd"));
		for(var i in document.getElementById(elementid)) {
			if(typeof(document.getElementById(elementid)[i])!='function' && document.getElementById(elementid)[i]!==undefined && document.getElementById(elementid)[i]!==null) {
				$this.set(i, document.getElementById(elementid)[i], true);//true = setting local properties
			};
		};
	};
	var setValueByIndex = function(prop, val) {
			if(getByIndex(val) != -1) {
				document.getElementById(elementid)[prop] = val;
				var childid = getPostID("postChildID");
				$("#"+childid+ " a.selected").removeClass("selected");
				$("#"+getByIndex(val).id).addClass("selected");
				var sText = getByIndex(document.getElementById(elementid).selectedIndex).html;
				setTitleText(sText);				
			};
	};
	var addRemoveFromIndex = function(i, action) {
		if(action=='d') {
			for(var key in a_array) {
				if(a_array[key].index == i) {
					delete a_array[key];
					break;
				};
			};
		};
		//update index
		var count = 0;
		for(var key in a_array) {
			a_array[key].index = count;
			count++;
		};
	};
	/************* public methods *********************/
	this.open = function() {
		if(($this.get("disabled", true) == true) || ($this.get("options", true).length==0)) return;
		var childid = getPostID("postChildID");
		if(msOldDiv!="" && childid!=msOldDiv) { 
			$("#"+msOldDiv).slideUp("fast");
			$("#"+msOldDiv).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) {
														//$this.data("dd").close();
														$this.close();
														setValue();
													};
													if($("#"+elementid).attr("onkeydown")!=undefined) {
															document.getElementById(elementid).onkeydown();
														};														
													   });
			$(document).bind("keyup", function(event) {
													if($("#"+elementid).attr("onkeyup")!=undefined) {
														//$("#"+elementid).keyup();
														document.getElementById(elementid).onkeyup();
													};												 
												 });

					$(document).bind("mouseup", function(evt){
															if(getInsideWindow()==false) {
															//alert("evt.target: "+evt.target);
															 //$this.data("dd").close();
															 $this.close();
															};
														 });													  
			$("#"+childid).css({zIndex:options.zIndex});
			$("#"+childid).slideDown("fast", function() {
													  if($this.onActions["onOpen"]!=null) {
														  eval($this.onActions["onOpen"])($this);
													  };
													  });
		if(childid!=msOldDiv) {
			msOldDiv = childid;
		};
		};
	};
	this.close = function() {
				var childid = getPostID("postChildID");
				$(document).unbind("keydown");
				$(document).unbind("keyup");
				$(document).unbind("mouseup");
				$("#"+childid).slideUp("fast", function(event) {
															checkMethodAndApply();
															$("#"+childid).css({zIndex:'0'});
															if($this.onActions["onClose"]!=null) {
														  		eval($this.onActions["onClose"])($this);
													  		};
															});
		
	};
	this.selectedIndex = function(i) {
		$this.set("selectedIndex", i);
	};
	//update properties
	this.set = function(prop, val, isLocal) {
		//alert("- set " + prop + " : "+val);
		if(prop==undefined || val==undefined) throw {message:"set to what?"}; 
		$this.ddProp[prop] = val;
		if(isLocal!=true) { 
			switch(prop) {
				case "selectedIndex":
					setValueByIndex(prop, val);
				break;
				case "disabled":
					$this.disabled(val, true);
				break;
				case "multiple":
					document.getElementById(elementid)[prop] = val;
					ddList = ($(sElement).attr("size")>0 || $(sElement).attr("multiple")==true) ? true : false;	
					if(ddList) {
						//do something
						var iHeight = $("#"+elementid).height();
						var childid = getPostID("postChildID");
						$("#"+childid).css("height", iHeight+"px");					
						//hide titlebar
						var titleid = getPostID("postTitleID");
						$("#"+titleid).hide();
						var childid = getPostID("postChildID");
						$("#"+childid).css({display:'block',position:'relative'});
						applyEventsOnA();
					}
				break;
				case "size":
					document.getElementById(elementid)[prop] = val;
					if(val==0) {
						document.getElementById(elementid).multiple = false;
					};
					ddList = ($(sElement).attr("size")>0 || $(sElement).attr("multiple")==true) ? true : false;	
					if(val==0) {
						//show titlebar
						var titleid = getPostID("postTitleID");
						$("#"+titleid).show();
						var childid = getPostID("postChildID");
						$("#"+childid).css({display:'none',position:'absolute'});
						var sText = "";
						if(document.getElementById(elementid).selectedIndex>=0) {
							var aObj = getByIndex(document.getElementById(elementid).selectedIndex);
							sText = aObj.html;
							manageSelection($("#"+aObj.id));
						}; 
						setTitleText(sText);
					} else {
						//hide titlebar
						var titleid = getPostID("postTitleID");
						$("#"+titleid).hide();
						var childid = getPostID("postChildID");
						$("#"+childid).css({display:'block',position:'relative'});						
					};
				break;
				default:
				try{
					//check if this is not a readonly properties
					document.getElementById(elementid)[prop] = val;
				} catch(e) {
					//silent
				};				
				break;
			};
		};
		//alert("get " + prop + " : "+$this.ddProp[prop]);
		//$this.set("selectedIndex", 0);
	};
	this.get = function(prop, forceRefresh) {
		if(prop==undefined && forceRefresh==undefined) {
			//alert("c1 : " +$this.ddProp);
		 	return $this.ddProp;
		};
		if(prop!=undefined && forceRefresh==undefined) {
			//alert("c2 : " +$this.ddProp[prop]);
			return ($this.ddProp[prop]!=undefined) ? $this.ddProp[prop] : null;
		};
		if(prop!=undefined && forceRefresh!=undefined) {
			//alert("c3 : " +document.getElementById(elementid)[prop]);
			return document.getElementById(elementid)[prop];
		};
	};
	this.visible = function(val) {
		var id = getPostID("postID");
		if(val==true) {
			$("#"+id).show();
		} else if(val==false) {
			$("#"+id).hide();
		} else {
			return $("#"+id).css("display");
		};
	};
	this.add = function(opt, index) {
		var objOpt = opt;
		var sText = objOpt.text;
		var sValue = (objOpt.value==undefined || objOpt.value==null) ? sText : objOpt.value;
		var img = (objOpt.title==undefined || objOpt.title==null) ? '' : objOpt.title;
		var i = (index==undefined || index==null) ? document.getElementById(elementid).options.length : index;
		document.getElementById(elementid).options[i] = new Option(sText, sValue);
		if(img!='') document.getElementById(elementid).options[i].title = img;
		//check if exist
		var ifA = getByIndex(i);
		if(ifA != -1) {
			//replace
			var aTag = createA(document.getElementById(elementid).options[i], i, "", "");
			$("#"+ifA.id).html(aTag);
			//a_array[key]
		} else {
			var aTag = createA(document.getElementById(elementid).options[i], i, "", "");
			//add
			var childid = getPostID("postChildID");
			$("#"+childid).append(aTag);
			applyEventsOnA();
		};
	};	
	this.remove = function(i) {
		document.getElementById(elementid).remove(i);
		if((getByIndex(i))!= -1) { $("#"+getByIndex(i).id).remove();addRemoveFromIndex(i, 'd');};
		//alert("a" +a);
		if(document.getElementById(elementid).length==0) {
			setTitleText("");
		} else {
			var sText = getByIndex(document.getElementById(elementid).selectedIndex).html;
			setTitleText(sText);
		};
		$this.set("selectedIndex", document.getElementById(elementid).selectedIndex);
	};
	this.disabled = function(dis, isLocal) {
		document.getElementById(elementid).disabled = dis;
		//alert(document.getElementById(elementid).disabled);
		var id = getPostID("postID");
		if(dis==true) {
			$("#"+id).css("opacity", styles.disabled);
			$this.close();
		} else if(dis==false) {
			$("#"+id).css("opacity", 1);
		};
		if(isLocal!=true) {
			$this.set("disabled", dis);
		};
	};
	//return form element
	this.form = function() {
		return (document.getElementById(elementid).form == undefined) ? null : document.getElementById(elementid).form;
	};
	this.item = function() {
		//index, subindex - use arguments.length
		if(arguments.length==1) {
			return document.getElementById(elementid).item(arguments[0]);
		} else if(arguments.length==2) {
			return document.getElementById(elementid).item(arguments[0], arguments[1]);
		} else {
			throw {message:"An index is required!"};
		};
	};
	this.namedItem = function(nm) {
		return document.getElementById(elementid).namedItem(nm);
	};
	this.multiple = function(is) {
		if(is==undefined) {
			return $this.get("multiple");
		} else {
			$this.set("multiple", is);
		};
		
	};
	this.size = function(sz) {
		if(sz==undefined) {
			return $this.get("size");
		} else {
			$this.set("size", sz);
		};		
	};	
	this.addMyEvent = function(nm, fn) {
		$this.onActions[nm] = fn;
	};
	this.fireEvent = function(nm) {
		eval($this.onActions[nm])($this);
	};
	//end 
	var updateCommonVars = function() {
		$this.set("version", $.msDropDown.version);
		$this.set("author", $.msDropDown.author);
	};
	var init = function() {
		//create wrapper
		createDropDown();
		//update propties
		//alert("init");
		setOriginalProperties();
		updateCommonVars();
		if(options.onInit!='') {
			eval(options.onInit)($this);
		};
		
	};
	init();
	};
	//static
	$.msDropDown = {
		version: 2.3,
		author: "Marghoob Suleman",
		create: function(id, opt) {
			return $(id).msDropDown(opt).data("dd");
		}
	};
	$.fn.extend({
	        msDropDown: function(options)
	        {
	            return this.each(function()
	            {
	               //if ($(this).data('dd')) return; // need to comment when using refresh method - will remove in next version
	               var mydropdown = new dd(this, options);
	               $(this).data('dd', mydropdown);
	            });
	        }
	    });
		   
})(jQuery);