
// Open Slimbox with the specified parameters
(function($) {
	
	// Global variables, accessible to Slimbox only
	var win = $(window), options, compatibleOverlay, ie6 = !window.XMLHttpRequest,
		operaFix = window.opera && (document.compatMode == "CSS1Compat") && ($.browser.version >= 9.3), documentElement = document.documentElement,
		// DOM elements
		overlayModal, center, middle, centerInner, centerWidth, centerHeight;
	
	/*
	Initialization
	*/
	$(function() {
		// Append the ModalWindow HTML code at the bottom of the document
		$("body").append(
			$([
				overlayModal = $('<div id="overlayModal" class="modal-overlay" />')[0],
				center = $('<div id="modal-window" />')[0]				
			]).css("display", "none")
		);
		
		closeWindow = $('<div class="close-window" />').appendTo(center).append(
			$('<a class="closelink" id="modal-closelink" />').add(overlayModal).click(close)[0]							
		)[0];
		
		centerInner = $('<div id="modal-window-inner" />').appendTo(center);
		
		
	});
	
	$.modalWindow = function(_options){
		options = $.extend({
		parent: "body",
		windowId: "myModal",
		innerContent: null,
		width: 529,		
		height: 466,
		initialWidth: 150,			// Initial width of the box (in pixels)
		initialHeight: 150,			// Initial height of the box (in pixels)
		overlayOpacity: 0.7,
		overlayFadeDuration: 400,
		resizeDuration: 400,			// Duration of each of the box resize animations (in milliseconds)
		resizeEasing: "swing"			// "swing" is jQuery's default easing
		}, _options);
		
		middle = win.scrollTop() + ((operaFix ? documentElement.clientHeight : win.height()) / 2);
		centerWidth = options.initialWidth;
		centerHeight = options.initialHeight;
		
		
		$(center).css({top: Math.max(0, middle - (centerHeight / 2)), width: centerWidth, height: centerHeight, marginLeft: -centerWidth/2}).show();
		
		compatibleOverlay = ie6 || (overlayModal.currentStyle && (overlayModal.currentStyle.position != "fixed"));
		if (compatibleOverlay) overlayModal.style.position = "absolute";
		$(overlayModal).css("opacity", options.overlayOpacity).fadeIn(options.overlayFadeDuration);
		position();
		
		animateBox();
	};
	
	function close(){
		$(center).hide();
		stop();		
		$(overlayModal).stop().fadeOut(options.overlayFadeDuration);
	};
	
	function animateBox() {
		centerWidth = options.width;
		centerHeight = options.height;
		var top = Math.max(0, middle - (centerHeight / 2));
		if (center.offsetHeight != centerHeight) {
			$(center).animate({height: centerHeight, top: top}, options.resizeDuration, options.resizeEasing);
		}
		if (center.offsetWidth != centerWidth) {
			$(center).animate({width: centerWidth, marginLeft: -centerWidth/2}, options.resizeDuration, options.resizeEasing);
		}
		$(center).queue(function() {
			$(centerInner).append(options.innerContent);
			$('#myModal').load(function() 
    		{
        		$(document).trigger('ready');
    		});
						
		});
	};
	
	function position() {
		var l = win.scrollLeft(), w = operaFix ? documentElement.clientWidth : win.width();
		$([center]).css("left", l + (w / 2));
		if (compatibleOverlay) $(overlayModal).css({left: l, top: win.scrollTop(), width: w, height: win.height()});
	};
	
	function stop() {
		$(centerInner).empty();				
		$([center]).stop(true);		
	};
	

	
})(jQuery);


var openMyModal = function(source) {
	// due to a stupid browser cache problem especially in safari, we have to generate a random number for the name attribute. Many thanks to http://codylindley.com/thickboxforum/comments.php?DiscussionID=682&page=1 
	var a = ""+Math.random();
	var b = a.substring(2,8);
	content = '<iframe id="myModal" name="myModal' + b + '" width="529" height="466" frameborder="0" allowtransparency="false" scrolling="yes" src="' + source + '"></iframe>';
	
	$.modalWindow({
		innerContent: content, overlayOpacity: 0.2
	});
};


/*
 * jQuery selectbox plugin
 *
 * Copyright (c) 2007 Sadri Sahraoui (brainfault.com)
 * Licensed under the GPL license:
 *   http://www.gnu.org/licenses/gpl.html
 *
 * The code is inspired from Autocomplete plugin (http://www.dyve.net/jquery/?autocomplete)
 *
 * Revision: $Id$
 * Version: 0.3
 */
jQuery.fn.extend({
	selectbox: function(options) {
		return this.each(function() {
			new jQuery.SelectBox(this, options);
		});
	}
});

jQuery.SelectBox = function(selectobj, options) {
	
	var opt = options || {};
	opt.inputClass = opt.inputClass || "selectbox";
	opt.containerClass = opt.containerClass || "selectbox-wrapper";
	opt.hoverClass = opt.hoverClass || "selected";
	opt.debug = opt.debug || false;
	
	var elm_id = selectobj.id;
	var active = -1;
	var inFocus = false;
	var hasfocus = 0;
	//jquery object for select element
	var $select = $(selectobj);
	// jquery container object
	var $container = setupContainer(opt);
	//jquery input object 
	var $input = setupInput(opt);
	// hide select and append newly created elements
	$select.hide().before($input).before($container);
	
	init();
	
	$input
	.click(function(){
        if (!inFocus) {
		  $container.toggle();
		}
	})
	.focus(function(){
	   if ($container.not(':visible')) {
	       inFocus = true;
	       $container.show();
	   }
	})
	.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 !
				setCurrent();
				hideMe();
				break;
		}
	})
	.blur(function() {
		if ($container.is(':visible') && hasfocus > 0 ) {
			if(opt.debug) console.log('container visible and has focus')
		} else {
			hideMe();	
		}
	});


	function hideMe() { 
		hasfocus = 0;
		$container.hide(); 
	}
	
	function init() {
		$container.append(getSelectOptions()).hide();
		var width = $input.width()
		$container.width(width);
    }
	
	function setupContainer(options) {
		var container = document.createElement("div");
		$container = $(container);
		$container.attr('id', elm_id+'_container');
		$container.addClass(options.containerClass);
		
		return $container;
	}
	
	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.hoverClass, $container).get(0);
		var el = li.id
		$select.val(el);
		$input.val($(li).html());
		return true;
	}
	
	// select value
	function getCurrentSelected() {
		return $select.val();
	}
	
	// input value
	function getCurrentValue() {
		return $input.val();
	}
	
	function getSelectOptions() {
		var select_options = new Array();
		var ul = document.createElement('ul');
		$select.children('option').each(function() {
			var li = document.createElement('li');
			li.setAttribute('id', $(this).val());
			li.innerHTML = $(this).html();
			if ($(this).is(':selected')) {
				$input.val($(this).html());
				$(li).addClass(opt.hoverClass);
			}
			ul.appendChild(li);
			$(li)
			.mouseover(function(event) {
				hasfocus = 1;
				if (opt.debug) console.log('out 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) {
				if (opt.debug) console.log('click on :'+this.id);
				$(this).addClass(opt.hoverClass);
				setCurrent();
				hideMe();
			});
		});
		return ul;
	}
	
};
