/*
 * jQuery dropdown plugin
 * based on Sadri Sahraoui's selectbox (brainfault.com)
 */
jQuery.fn.extend({
	dropdown: function(options) {
		return this.each(function() {
			var d = new jQuery.dropdown(this, options);
            return d;
		});
	}
});


/* pawel maziarz: work around for ie logging */
if (!window.console) {
	var console = {
		log: function(msg) {
	 }
	}
}
/* */

jQuery.dropdown = function(selectobj, options) {

	var opt = options || {};
	opt.inputClass = opt.inputClass || "dropdown";
	opt.containerClass = opt.containerClass || "dropdown-wrapper";
	opt.hoverClass = opt.hoverClass || "current";
	opt.currentClass = opt.selectedClass || "selected"
	opt.debug = opt.debug || false;
    opt.dataSource = opt.dataSource || false;
    var current_id;
    var current_index;

	var elm_id = selectobj.id;
    if (!selectobj.id) {
        var elm_id = selectobj.name;
    }
	var active = -1;
	var inFocus = false;
	var hasfocus = 0;
    var rebuilding = 0;
	//jquery object for select element
	var $select = $(selectobj);
	// jquery container object
	var $container = false;
	//jquery input object
	var $input = setupInput(opt);
    var $input_container = $(document.createElement('div'));

    //$container.hide();
    if (window[$select.attr('dropdown')]) {
        opt.dataSource = window[$select.attr('dropdown')];
        opt.dataIndex = window[$select.attr('dropdown') + '_index'];
    }

	init();

	$input
	.click(function(){
    if (!inFocus) {
          $container.toggle();
		}
	})
	.focus(function(){
	   if (!$container || $container.not(':visible')) {
	       inFocus = true;
	       buildDropdown();
           $container.show();
           $container.focus();
	   }
	})
	.keydown(function(event) {
		switch(event.keyCode) {
			case 38: // up
				event.preventDefault();
				moveSelect(-1);
				break;
			case 40: // down
				event.preventDefault();
				moveSelect(1);
				break;
			//case 9:  // tab
			case 13: // return
				event.preventDefault(); // seems not working in mac !
				$('li.'+opt.hoverClass).trigger('click');
				break;
			case 27: //escape
			  hideMe();
			  break;
		}
	});

    $input_container.click(function(){
       if (!$container || $container.not(':visible')) {
           inFocus = true;
           buildDropdown();
           $container.show();
           $container.focus();
       }
       else {
        $container.hide();
       }
    })

	function hideMe() {
		hasfocus = 0;
        inFocus = false;
		$container.hide();
	}

	function init() {
        var initial_width = $select.get(0).offsetWidth;
        var initial_height = $select.get(0).offsetHeight;
        $input_container.addClass('input_container');
        $input_container.width( initial_width - 2);
        $input.width( initial_width - 10);
        if ($.browser.msie) {
            $input.width( initial_width - 15);
            $input_container.css('padding', '0px');
            $input_container.css('padding-right', '7px');
        }
        //
        //$input.height( initial_height);
        $input_container.addClass($select.attr('class'));
        $input.addClass($select.attr('class'));
        $input_container.append($input);

        if (!opt.dataSource) {
            //if (!$container) {
            //    setupContainer(opt);
            //}
            //$container.append(getSelectOptions($input.attr('id'))).hide();
            //var width = $input_container.css('width');
            //$container.width(width);

        }
        else {
            var selected_index = $select.attr('id_val');
            if (typeof opt.dataIndex[selected_index] != "undefined") {
                var text = opt.dataSource[opt.dataIndex[selected_index]].Sub[selected_index].Name;
                var value = selected_index;
                var options   = document.createElement('option');
                options.value = value;
                options.appendChild(document.createTextNode(text));
                $select.empty();
                $select.append(options);
                $select.val(value);
                current_id = value;
                current_index = opt.dataIndex[value];
            }
        }
        $input.val($('option[selected]', $select).text());
        $input.attr('id_val', $select.val());
        // hide select and append newly created elements
        $select.hide().before($input_container); //.before($container);
        $select.change(dochange);


    }

    function dochange() {
        //
        $input.val($select.text());
        $input.attr('id_val', $select.val());
    }

    function buildDropdown(page_id, previndex) {
        var selected_index = $select.val();
        var content;
        var source;
        if (!$container) {
            setupContainer(opt);
        }
        $container.html('');
        if (opt.dataSource) {
            if (typeof page_id == 'undefined' && typeof opt.dataIndex[selected_index] != "undefined" ) {
                page_id = opt.dataIndex[selected_index];
                var previndex = 0;
                source = opt.dataSource[page_id].Sub;
            }
            else if (page_id && page_id > 0) {
                source = opt.dataSource[page_id].Sub;
            }
            else {
                source = opt.dataSource;

            }

            content = getArrayContent($input.attr('id'), source, previndex);
        }
        else {
            content = getSelectOptions($input.attr('id'));
        }
        $container.html(content);
        $container.focus();
        var width = $input_container.get(0).offsetWidth;
        if (width > $container.get(0).offsetWidth) {
            $container.width(width + 20);
        }
        // hack due to floater positioning bug
        if ($('#floater-parent').css('display') != 'block') {
            var x = $input_container.offset().left;
            var y = $input_container.offset().top + $input_container.height();
            $container.css('top', y + 2 +'px');
            $container.css('left', x + 'px');
        }
        else {
            $container.css('top', '');
            $container.css('left','');
        }

    }

	function setupContainer(options) {
		var container = document.createElement("div");
		$container = $(container);
		$container.attr('id', elm_id+'_container');
		$container.addClass(options.containerClass);
        $select.before($container).hide();
        $container.focus();
        $container.blur(function() {
            if ($container.is(':visible') && hasfocus > 0 ) {
                if(opt.debug) console.log('container visible and has focus');
                //$container.focus();
            } else {
                hideMe();
            }
        }).mouseover(function() { hasfocus = 1; $container.focus()})
        .mouseout(function(){ hasfocus = -1});
	}

	function setupInput(options) {
		var input = document.createElement("input");
		var $input = $(input);
		$input.attr("id", elm_id+"_input");
		$input.attr("type", "text");
		$input.addClass(options.inputClass);
		$input.attr("autocomplete", "off");
		$input.attr("readonly", "readonly");
		$input.attr("tabIndex", $select.attr("tabindex")); // "I" capital is important for ie

		return $input;
	}

	function moveSelect(step) {
		var lis = $("li", $container);
		if (!lis) return;

		active += step;

		if (active < 0) {
			active = 0;
		} else if (active >= lis.size()) {
			active = lis.size() - 1;
		}

		lis.removeClass(opt.hoverClass);

		$(lis[active]).addClass(opt.hoverClass);
	}

	function setCurrent() {
		var li = $("li."+opt.currentClass, $container).get(0);
		var ar = (''+li.id).split('_');
		var el = ar[ar.length-1];
        var value = $(li).attr('id_val');
        var text = $(li).text();
        if (opt.dataSource) {
            current_id = value;
            current_index = opt.dataIndex[value];
            var options   = document.createElement('option');
            options.value = value;
            options.appendChild(document.createTextNode(text));
            $select.empty();
            $select.append(options);
        }
		$select.val(value);
        $select.trigger('change');
        $input.val(text);
		return true;
	}

	// select value
	function getCurrentSelected() {
		return $select.val();
	}

	// input value
	function getCurrentValue() {
		return $input.val();
	}

    function getArrayContent (parentid, arr, previndex)
    {
        var ul = document.createElement('ul');
        var selected_id = $select.val();
        if (typeof previndex != 'undefined') {
            var back = document.createElement('li');
            back.innerHTML =  language_back;
            $(back).addClass('back');
            $(back).click(function() {
                hasfocus = 1;
                rebuilding = 1;
                buildDropdown(0);
            }).mouseover(function(event) {
                hasfocus = 1;
                if (opt.debug) console.log('over on : '+this.id);
                jQuery(event.target, $container).addClass(opt.hoverClass);
            }).mouseout(function(event) {
                hasfocus = -1;
                if (opt.debug) console.log('out on : '+this.id);
                jQuery(event.target, $container).removeClass(opt.hoverClass);
            });
            ul.appendChild(back);
        }
        for (id in arr) {
            var li = document.createElement('li');
            li.setAttribute('id', parentid + '_' + id);
            li.setAttribute('id_val', id);
            li.innerHTML = arr[id].Name;
            li.setAttribute('sub', '1');
            if (id == selected_id || id == current_index) {
                $(li).addClass('selected');
            }

            if (arr[id].Sub != null) {
                $(li).addClass('more');
                source = arr[id].Sub;
                $(li).click(function() {
                    hasfocus = 1;
                    buildDropdown(this.getAttribute('id_val'), 0);
                });
            }
            else {
                $(li).click(function() {
                  var fl = $('li.'+opt.hoverClass, $container).get(0);
                    if (opt.debug) console.log('click on :'+id);
                    $('li.'+opt.currentClass).removeClass(opt.currentClass);
                    $(this).addClass(opt.currentClass);
                    setCurrent();
                    hideMe();
                });
            }
            $(li).mouseover(function(event) {
                hasfocus = 1;
                if (opt.debug) console.log('over on : '+this.id);
                jQuery(event.target, $container).addClass(opt.hoverClass);
            })
            .mouseout(function(event) {
                hasfocus = -1;
                if (opt.debug) console.log('out on : '+this.id);
                jQuery(event.target, $container).removeClass(opt.hoverClass);
            });
            ul.appendChild(li);
        }

        return ul;
    }

	function getSelectOptions(parentid) {
		var select_options = new Array();
		var ul = document.createElement('ul');
		$select.children('option').each(function() {
			var li = document.createElement('li');
			li.setAttribute('id', parentid + '_' + $(this).val());
            li.setAttribute('id_val', $(this).val());
			li.innerHTML = $(this).html();
			if ($(this).is(':selected')) {
				$input.val($(this).html());
				$(li).addClass(opt.currentClass);
			}
			ul.appendChild(li);
			$(li)
			.mouseover(function(event) {
				hasfocus = 1;
				if (opt.debug) console.log('over on : '+this.id);
				jQuery(event.target, $container).addClass(opt.hoverClass);
			})
			.mouseout(function(event) {
				hasfocus = -1;
				if (opt.debug) console.log('out on : '+this.id);
				jQuery(event.target, $container).removeClass(opt.hoverClass);
			})
			.click(function(event) {
			  var fl = $('li.'+opt.hoverClass, $container).get(0);
				if (opt.debug) console.log('click on :'+this.id);
				$('li.'+opt.currentClass).removeClass(opt.currentClass);
				$(this).addClass(opt.currentClass);
				setCurrent();
				hideMe();
			});
		});
		return ul;
	}
	$(document).click(function(){
		if(hasfocus<0)
			hideMe();
	});
    $('iframe').load(function(){
        $(this.contentDocument).click(function(){
            if(hasfocus<0)
                hideMe();
        });
    });

};