/*
 *
 * jqTransform
 * by mathieu vilaplana mvilaplana@dfc-e.com
 * Designer ghyslain armand garmand@dfc-e.com
 *
 *
 * Version 1.0 25.09.08
 * Version 1.1 06.08.09
 * Add event click on Checkbox and Radio
 * Auto calculate the size of a select element
 * Can now, disabled the elements
 * Correct bug in ff if click on select (overflow=hidden)
 * No need any more preloading !!
 * 
 ******************************************** */
 
(function($){

	function rebuild_options() {
	    jQuery('.jqTransformSelectWrapper').each(function(){
		var select = jQuery('select', this);
		if (select.attr('id').indexOf('region_id') === -1) return;
		var display = (select.css('display') == 'none'? 'none': 'block');

		var ul = jQuery('ul', this);
		var wrap = jQuery(this);
		jQuery('li', ul).remove();
		var li = '';
                jQuery('option', select).each(function(i){
		    li += '<li><a href="#" index="'+ i +'">'+ jQuery(this).html() +'</a></li>';
                });
		jQuery(ul).append(li);
                ul.find('a').click(function(e){
		    e.preventDefault();
		    jQuery('a.selected', ul).removeClass('selected');
                    jQuery(this).addClass('selected');
                    select[0].selectedIndex = jQuery(this).attr('index');
		    jQuery('span:eq(0)', wrap).html(jQuery(this).html());
                    ul.hide();
		});

		ul.css("height", "250px");

		if (jQuery('li',ul).length < 20) {
			ul.css("height", "auto");
			ul.css('overflow','hidden');
		} else {
		    ul.css('overflow', 'auto');
		}

                ul.css({display:'none',visibility:'visible'});
        	jQuery('a', ul).first().addClass('selected');
		jQuery(this).css("display", display);
		jQuery('span:eq(0)', wrap).html(jQuery('a.selected', this).html());
	    });
	}

	function rebuild_months() {
            jQuery('.jqTransformSelectWrapper').each(function(){
                var select = jQuery('select', this);

                if (select.attr('id') != 'months_dropdown2') return;
		var wrap = jQuery(this);

                jQuery("#months_dropdown2 option").remove();
		wrap.hide();
		jQuery("#months_dropdown2").hide();

		var year  = String(jQuery("#years_dropdown").val());
		var has_months = false;
		jQuery("#months_dropdown option").each(function(){
		    var rel = String(jQuery(this).attr('rel'));
		    if(year.indexOf(rel) !== -1 || jQuery(this).val() == '') {
			jQuery("#months_dropdown2").append("<option value='"+jQuery(this).val()+"'>"+jQuery(this).text()+"</option>");
		    }
		    if (year.indexOf(rel) !== -1)
			has_months = true;

		    if (has_months) {
			jQuery("#months_dropdown2").val('');
			jQuery("#months_dropdown2").show();
			wrap.show();	
		    }
		});

		var ul = jQuery('ul', wrap);

                jQuery('li', ul).remove();
                var li = '';
                jQuery('option', select).each(function(i){
                    li += '<li><a href="' + jQuery(this).val() + '" index="'+ i +'">'+ jQuery(this).html() +'</a></li>';
                });
                jQuery(ul).append(li);

	        ul.css("height", "250px");

                if (jQuery('li',ul).length < 20) {
                        ul.css("height", "auto");
                        ul.css('overflow','hidden');
                } else {
                    ul.css('overflow', 'auto');
                }

                ul.css({display:'none',visibility:'visible'});
                jQuery('a', ul).first().addClass('selected');
                jQuery('span:eq(0)', wrap).html(jQuery('a.selected', this).html());

                jQuery("a", ul).click(function(){
                    ul.hide();
                });

	    });
	}

	var jqTransformHideSelect = function(oTarget){
	    var ulVisible = $('.jqTransformSelectWrapper ul:visible');
	    ulVisible.each(function(){
		var oSelect = $(this).parents(".jqTransformSelectWrapper:first").find("select").get(0);
		//do not hide if click on the label object associated to the select
		if( !(oTarget && oSelect.oLabel && oSelect.oLabel.get(0) == oTarget.get(0)) ){$(this).scrollTop(0);$(this).hide();}
	    });
        };

	jQuery.fn.jqTransSelect = function(){
		return jQuery(this).each(function(index){
			var $select = jQuery(this);

                        if($select.hasClass('jqTransformHidden')) {return;}
                        if($select.attr('multiple')) {return;}

			var width =$select.outerWidth();
			var display = ($select.css("display") == 'none'? 'none' : 'block');
	                if ($select.hasClass('slimit')) {display = 'inline-block';}

			/* First thing we do is Wrap it */
			var $wrapper = $select
				.addClass('jqTransformHidden')
				.wrap('<div class="jqTransformSelectWrapper field-row"></div>')
				.parent()
				.css({zIndex: 10-index})
			;
			/* Now add the html for the select */
			$wrapper.prepend('<div><span></span><a href="#" class="jqTransformSelectOpen"></a></div><ul></ul>');
			var $ul = $('ul', $wrapper).css('width',width).scrollTop(0).hide();
			/* Now we add the options */
			$('option', this).each(function(i){
				var oLi = $('<li><a href="#" index="'+ i +'">'+ $(this).html() +'</a></li>');
				$ul.append(oLi);
			});
			
			/* Add click handler to the a */
			$ul.find('a').click(function(){
					$('a.selected', $wrapper).removeClass('selected');
					$(this).addClass('selected');	
					/* Fire the onchange event */
					if ($select[0].selectedIndex != $(this).attr('index') && $select[0].onchange) { $select[0].selectedIndex = $(this).attr('index'); $select[0].onchange();}
//					jQuery('select').removeClass('jqTransformHidden');					
					$select[0].selectedIndex = $(this).attr('index');
//					$select[0].click();
//					$select[0].change();

					try {
					    if (RegionUpdater !== undefined) { RegionUpdater.update(); rebuild_options();}
					} catch(err){}

                                        try {
                                            if ($select.attr("id") == "billing:country_id" && billingRegionUpdater !== undefined) { /*jQuery("#billing-buttons-container").show();showBillingAddBlocks();*/ showCorrectTextBoxes('billing'); billingRegionUpdater.update(); rebuild_options();}
                                        } catch(err){}

                                        try {
                                            if ($select.attr("id") == "shipping:country_id" && shippingRegionUpdater !== undefined) {/*jQuery("#shipping-buttons-container").show(); showShippingAddBlocks();*/showCorrectTextBoxes('shipping');shippingRegionUpdater.update(); rebuild_options();}
                                        } catch(err){}

                                        try {
			    		    if (billing !== undefined && $select.attr("id") == "billing-address-select") {billing.newAddress(! $select.val())};
                                        } catch(err){}

                                        try {
                                            if (shipping !== undefined && $select.attr("id") == "shipping-address-select") {shipping.newAddress(! $select.val())};
                                        } catch(err){}


					if($select.attr("id") == "years_dropdown") { rebuild_months(); }

					if($select.attr("id") == "cybersource3dauth_cc_type") { SSCheckedcybersource3dauth(); }
/*
                                        try {
						if($select.attr("id") == "billing:country_id" || $select.attr("id") == "shipping:country_id") {showCorrectTextBoxes('billing');showCorrectTextBoxes('shipping');};
                                        } catch(err){}

                                        try {
//                                            if($select.attr("id") == "shipping:country_id") {showCorrectTextBoxes('shipping')};
					} catch(err){}
*/
					$('span:eq(0)', $wrapper).html($(this).html());
					$ul.scrollTop(0);
					$ul.hide();
					return false;
			});
			/* Set the default */
			$('a:eq('+ this.selectedIndex +')', $ul).click();
			$('span:first', $wrapper).click(function(){$("a.jqTransformSelectOpen",$wrapper).trigger('click');});
		
			/* Apply the click handler to the Open */
			var oLinkOpen = $('a.jqTransformSelectOpen', $wrapper)
				.click(function(){
					$ul.scrollTop(0);
					//Check if box is already open to still allow toggle, but close all other selects
					if( $ul.css('display') == 'none' ) {jqTransformHideSelect();} 
					if($select.attr('disabled')){return false;}

					$ul.slideToggle('fast', function(){					
						var offSet = (jQuery('a.selected', $ul).offset().top - $ul.offset().top);
						$ul.animate({scrollTop: offSet});
					});
					return false;
				})
			;

			// Set the new width
			var iSelectWidth = $select.outerWidth();
			var oSpan = $('span:first',$wrapper);
			var width = $select.outerWidth();
			var newWidth = (iSelectWidth > oSpan.innerWidth())?iSelectWidth:$wrapper.width();
			if (newWidth < 40) {width = String($select.css('width')); if (width.indexOf('px') !== -1) {width = width.replace("px", "")} else {width="220"} } else {width = newWidth}
			if(parseInt(width)<40) {width="220"}
			if(parseInt(width)>600) {width="220"}

			if($select.css('width') == 'auto') {
//				width = String(parseInt(width) + 20);
			}

			if($select.attr('id') == 'qty') width = "55";
			if ($select.attr('id').indexOf('attribute') !== -1 && jQuery.browser.msie) width = "65";

			$wrapper.css('width',width+'px');
			$ul.css('width', String(parseInt(width)-10)+'px');
			oSpan.css('width', String(parseInt(width)-30)+'px');
		
			// Calculate the height if necessary, less elements that the default height
			//show the ul to calculate the block, if ul is not displayed li height value is 0
			$ul.css({display:'block',visibility:'hidden'});
//			var iSelectHeight = ($('li',$ul).length)*($('li:first',$ul).height());//+1 else bug ff
//			(iSelectHeight < $ul.height()) && $ul.css({height:iSelectHeight,'overflow':'hidden'});//hidden else bug with ff

	                $ul.css("height", "250px");

			if (jQuery('li', $ul).length < 20) {
			    $ul.css("height", "auto");
			    $ul.css('overflow','hidden');
			} else {
			    $ul.css('overflow', 'auto');
			}


			$ul.css({display:'none',visibility:'visible'});
		
                        $wrapper.css('margin-top', $select.css("margin-top"));
                        $wrapper.css('margin-bottom', $select.css("margin-bottom"));
                        $wrapper.css('display', display);

                        try {
	                    $wrapper.css('z-index', 'auto');
                        } catch(err){}
		});
	};

	var jqTransformAddDocumentListener = function (){
	    jQuery(document).mousedown(jqTransformCheckExternalClick);
	};

	var jqTransformCheckExternalClick = function(event) {
	   if ($(event.target).parents('.jqTransformSelectWrapper').length === 0) { jqTransformHideSelect($(event.target)); }
	};

       jqTransformAddDocumentListener();


})(jQuery);

jQuery(window).load(function(){
    jQuery('select').jqTransSelect();
    jQuery("#store_locator_form .dhx_combo_box").css('width', '224px');
    jQuery(".dhx_combo_list").css('width', '218px');
    jQuery(".dhx_combo_list").css('height', '175px');

});

