// 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(); });
			}
		});
	}
});


// 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
// Date: 12th Aug, 2009
// Version: 2.1 {date: 3rd Sep 2009}
// Revision: 25
// 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 GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// msDropDown is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
;(function($) {
	var oldDiv = "";
	$.fn.dd = function(options) {
		$this =  this;
		options = $.extend({
			height:120,
			visibleRows:7,
			rowHeight:23,
			showIcon:true,
			zIndex:9999,
			style:''
		}, options);
		var selectedValue = "";
		var actionSettings ={};
		actionSettings.insideWindow = true;
		actionSettings.keyboardAction = false;
		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'};
		styles = {dd:'dd', ddTitle:'ddTitle', arrow:'arrow', ddChild:'ddChild', disbaled:.30};
		attributes = {actions:"onfocus,onblur,onchange,onclick,ondblclick,onmousedown,onmouseup,onmouseover,onmousemove,onmouseout,onkeypress,onkeydown,onkeyup", prop:"size,multiple,disabled,tabindex"};
		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 elementid+config[id];
	};
	function getOptionsProperties(option) {
		var currentOption = option;
		var styles = $(currentOption).attr("style");
		return styles;
	};
	function matchIndex(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;
	}
	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");
															 arrow = (arrow.length==0) ? "" : '<img src="'+arrow+'" align="left" /> ';
															 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+'"';
															 } 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");
									 arrow = (arrow.length==0) ? "" : '<img src="'+arrow+'" align="left" /> ';									 
									 var sText = $(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 = $("#"+elementid+" option:selected").text();
		var arrow = $("#"+elementid+" option:selected").attr("title");
		arrow = (arrow.length==0 || arrow==undefined || options.showIcon==false) ? "" : '<img src="'+arrow+'" align="left" /> ';
		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 = $("#"+elementid).width();
		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
		if(!ddList)
		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);
		}
		$("#"+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");
		}
		//set out of vision
		if(changeInsertionPoint==false) {
			setOutOfVision();
			addNewEvents(elementid);
		}
		if($("#"+elementid).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();
															  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($("#"+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;				
			};
		};		
	};
	function addNewEvents(id) {
		document.getElementById(id).refresh = function(e) {
			$("#"+this.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 = $("#"+elementid).attr(action);
			if(actionFound!=undefined) {
				switch(action) {
					case "onfocus": 
					$("#"+mainid).bind("mouseenter", function(event) {
													   document.getElementById(elementid).focus();
													   });
					break;
					case "onclick": 
					$("#"+mainid).bind("click", function(event) {
													   document.getElementById(elementid).onclick();
													   });
					break;
					case "ondblclick": 
					$("#"+mainid).bind("dblclick", function(event) {
													   document.getElementById(elementid).ondblclick();
													   });
					break;
					case "onmousedown": 
					$("#"+mainid).bind("mousedown", function(event) {
													   document.getElementById(elementid).onmousedown();
													   });
					break;
					case "onmouseup": 
					//has in closeMe mthod
					$("#"+mainid).bind("mouseup", function(event) {
													   document.getElementById(elementid).onmouseup();
													   //setValue();
													   });
					break;
					case "onmouseover": 
					$("#"+mainid).bind("mouseover", function(event) {
													   document.getElementById(elementid).onmouseover();
													   });
					break;
					case "onmousemove": 
					$("#"+mainid).bind("mousemove", function(event) {
													   document.getElementById(elementid).onmousemove();
													   });
					break;
					case "onmouseout": 
					$("#"+mainid).bind("mouseout", function(event) {
													   document.getElementById(elementid).onmouseout();
													   });
					break;
				};
			};
		};
		
	};
	function setOutOfVision() {
		var sId = getPostID("postElementHolder");
		$("#"+elementid).after("<div style='height:0px;overflow:hidden;position:absolute;' id='"+sId+"'></div>");
		$("#"+elementid).appendTo($("#"+sId));
	};
	function setTitleText(sText) {
		var titletextid = getPostID("postTitleTextID");
		$("#"+titletextid).html(sText);
	};
	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 : 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");				
				//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;
			};
		};
	};
	function setValue() {
		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;
			};
		} 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";
			};
		};
	};
	function openMe() {
		var childid = getPostID("postChildID");
		if(oldDiv!="" && childid!=oldDiv) { 
			$("#"+oldDiv).slideUp("fast");
			$("#"+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($("#"+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) {
															 closeMe();
															}
														 });													  
			$("#"+childid).css({zIndex:options.zIndex});
			$("#"+childid).slideDown("fast");
		if(childid!=oldDiv) {
			oldDiv = childid;
		}
		};
	};
	function closeMe() {
				var childid = getPostID("postChildID");
				$(document).unbind("keydown");
				$(document).unbind("keyup");
				$(document).unbind("mouseup");
				$("#"+childid).slideUp("fast", function(event) {
															checkMethodAndApply();
															$("#"+childid).css({zIndex:'0'});
															});
		
	};
	function checkMethodAndApply() {
		var childid = getPostID("postChildID");
		if($("#"+elementid).attr("onchange")!=undefined) {
			var currentSelectedValue = a_array[$("#"+childid +" a.selected").attr("id")].text;
			if(selectedValue!=currentSelectedValue){document.getElementById(elementid).onchange();};
		}
		if($("#"+elementid).attr("onmouseup")!=undefined) {
			document.getElementById(elementid).onmouseup();
		}
		if($("#"+elementid).attr("onblur")!=undefined) { 
			$(document).bind("mouseup", function(evt) {
												   $("#"+elementid).focus();
												   $("#"+elementid)[0].blur();
												   setValue();
												   $(document).unbind("mouseup");
												});
		};
	};
	function hightlightArrow(ison) {
		var arrowid = getPostID("postArrowID");
		if(ison==1)
			$("#"+arrowid).css({backgroundPosition:'0 100%'});
		else 
			$("#"+arrowid).css({backgroundPosition:'0 0'});
	};
	};
	$.fn.msDropDown = function(properties) {
		var dds = $(this);
		for(var iCount=0;iCount<dds.length;iCount++) {
			var id = $(dds[iCount]).attr("id");
			if(properties==undefined) {
				$("#"+id).dd();
			} else {
				$("#"+id).dd(properties);
			};
		};		
	};
	

	
})(jQuery);
