/* jQuery timeslider
 * Shows a slider for selecting a time
 *
 * Copyright (c) 2009 Alex Barrett (spleenboy.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) 
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * Usage:
 * $('input.time').timeslider({ hide: true|false, step: 30 });
 * @hide indicates whether the slider is hidden when it is initialized
 * @step indicates the number of minutes between steps in the slider
 */

/**
 * Enhanced .offset()
 * Abstracts offset().right and offset().bottom into a built-in getter, and adds .offset(top, left) as a setter.
 *
 * @version 1.0
 * @example $('#tester').offset().bottom
 * @example $('#tester').offset().right
 * @example $('#tester').offset(10, 20);
 * @example $('#tester').offset(10, 20, 'fast');
 * @example $('#tester').offset('+=10', '+=20');
 * @example $('#tester').offset('+=5', '-=30');
 * @author Brian Schweitzer (BrianFreud)
 * @author Charles Phillips, first half of the return conditional ( http://groups.google.com/group/jquery-dev/browse_thread/thread/10fa400d3f9d9521/ )
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */
(function($) {
    var offsetMethod = $.fn.offset;
    $.fn.offset = function () {
        var offset = offsetMethod.call(this),
            bottom = offset.top + this.outerHeight(),
            right = offset.left + this.outerWidth(),
            a = arguments;
        return (a.length) ? this.animate({
                                         top  : a[0].top  || a[0],
                                         left : a[0].left || a[1]
                                         }, (a[0].top ? a[1] : a[2]) || 1)
                          : $.extend(offset, {
                                             bottom: bottom,
                                             right: right
                                             });
    };
})(jQuery);

(function($) {
    var positionMethod = $.fn.position;
    $.fn.position = function () {
        var position = positionMethod.call(this),
            bottom = position.top + this.outerHeight(),
            right = position.left + this.outerWidth(),
            a = arguments;
        return (a.length) ? this.animate({
                                         top  : a[0].top  || a[0],
                                         left : a[0].left || a[1]
                                         }, (a[0].top ? a[1] : a[2]) || 1)
                          : $.extend(position, {
                                             bottom: bottom,
                                             right: right
                                             });
    };
})(jQuery);


jQuery.fn.timeslider = function(options) {
    var o = $.extend({
		className: '',
        hide: true,
        step: 15 // minutes
    }, options);
    var max = 24 * 60;

    // Gets the number of minutes from 0 - 1440 based on the time from midnight
    var getMinutesFromTime = function(time) {
        try {
            var date = new Date('1/1/2000 ' + time);
            return (date.getHours() * 60) + date.getMinutes();
        } catch (e) {
            return 0;
        }
    };

    // Gets the time from the number of minutes
    var getTimeFromMinutes = function(minutes) {
        var hours = Math.floor(minutes / 60);
        var minutes = minutes % 60;
        var ampm = hours > 11 ? " pm" : " am";
        if (minutes < 10) minutes = "0" + minutes;
        if (hours == 0 || hours == 24) {
            ampm = " am";
            hours = 12;
        } else if (hours > 12) {
            hours = hours - 12;
        }
        return hours + ":" + minutes + ampm;
    };

    var round = function(i) {
        return Math.round(i / o.step) * o.step;
    };

    return this.each(function() {
        var textbox = $(this);
        var current = round(getMinutesFromTime(textbox.val()));
        textbox.val(getTimeFromMinutes(current));

        var sliding = function(e, ui) {
            var time = getTimeFromMinutes(ui.value);
            textbox.val(time);
        };

        var slider = $('<div class="timeslider" />').slider({
            step: o.step,
            max: 24 * 60,
            value: current,
            animate: true,
            slide: sliding
        });
		
		if (o.className != null && o.className.length > 0) {
			slider.addClass(o.className);
		}

        slider.insertAfter(textbox);
        if (o.hide) {
            slider.hide();
            textbox.focus(function() { slider.show(); });
            $(document).mousedown(function(event) {
                var target = $(event.target);
                if (slider.is(':visible') && target.parents('.timeslider').length == 0) {
                    slider.hide();
                }
            });
        }
    });
};


/** 
 * ImageSelect jQuery plugin
 * 
 * @author Stefan Zollinger
 * 
 * options:
 *   containerClass: 'image-select-container'
 *   imageClass: 'image-select'
 *   thumbnailWidth: '60'
 *   imageSrc: 'text' or 'value'
 * 
 */

(function($) {
	var $selectbox;
	
	$.fn.imageSelect = function(options){
		var opts = $.extend({}, $.fn.imageSelect.defaults, options);
		
		return this.each(function() {
			var $this = $(this);
			$selectbox = $this;
			if(this.tagName == 'SELECT'){
				
				$this.wrap('<div class="' + opts.containerClass + '">' );
				var html = '';				
				$this.children('option').each(function(){
					
					if(this.selected == true){
						selectClass = 'selected';
					}else{
						selectClass = '';
					}
					var src;
					if(opts.imageSrc == 'text'){
						src = $(this).text(); 
					}else{
						src = this.value;
					}
					
					if (this.value == '' || this.value == undefined) {
						html += '<a class="' +
											selectClass +
											' ' +
											opts.imageClass +
											'" href="#select_' +
											this.value +
											'"><div style="background-color: #ccc; width: ' +
											opts.thumbnailWidth + 'px; height: ' + opts.thumbnailWidth +
											'px" >'+opts.emptyText+'</div></a>';
					} else {
						html += '<a class="' +
											selectClass +
											' ' +
											opts.imageClass +
											'" href="#select_' +
											this.value +
											'"><img  src="' +
											src +
											'" style="width: ' +
											opts.thumbnailWidth +
											'px" /></a>';
					}
				});
				
				$(this).after(html);
				
				$('a.image-select').click($.fn.imageSelect.selectImage);
				$('a.image-select').hover($.fn.imageSelect.hoverImage,$.fn.imageSelect.unhoverImage);
				
				$this.css('display', 'none');
			}
			
  		});
	}
	
	$.fn.imageSelect.hoverImage = function(e){
		var pos = $('img',this).offset();
		var src = $('img',this).attr('src');
		
		$('<div/>').attr({
			'id':'previewSelect'
		}).css({
			'background':'url(http://beagleproductions.com/loading.gif)',
			'z-index':'100',
			'border':'1px #333 solid',	
			'width':32,
			'height':32,		
			'position':'absolute',
			'top':pos.bottom+2,
			'left':(pos.left - 16 + ( $.fn.imageSelect.defaults.thumbnailWidth / 2 ) )
		}).appendTo('body');
		
		$('<img/>').attr({
			'src':src
		}).css({
			'display':'none'
		}).appendTo('#previewSelect');
		
		$('#previewSelect img').each(function(){
			$(this).parent().css({		
				'width':$('#previewSelect img').outerWidth(),
				'height':$('#previewSelect img').outerHeight(),				
				'position':'absolute',
				'display':'block',
				'top':pos.bottom+2,
				'left':(pos.left - ( $('#previewSelect img').outerWidth() / 2 ) + ( $.fn.imageSelect.defaults.thumbnailWidth / 2 ) )
			});
			$(this).show();
		});
		
	}
	$.fn.imageSelect.unhoverImage = function(e){
		$(this).css('outline','0px #f00 solid');
		$('#previewSelect').remove();
	}
	
	$.fn.imageSelect.selectImage = function(e){
		var $selectBox = $(this).prevAll('select:first');
		
		if($selectBox.attr('multiple') == true){
			var $option = $selectBox.children('option[value='+this.href.split('_')[1]+']');
			
			if($option.attr('selected') == true){
				$option.attr('selected', false);
				$(this).removeClass('selected');
			}else{
				$option.attr('selected', true);
				$(this).addClass('selected');
			}
			
		}else{
			$selectBox.val(this.href.split('_')[1]);
			$(this).parent().children('a').removeClass('selected');
			$(this).addClass('selected');
			// SELECT MOD //
				$selectbox.find('option:contains("'+$(this).find('img').attr('src')+'")').attr('selected','selected');
		}
				
		return false;
	}
	
	$.fn.imageSelect.defaults = {
		containerClass: 'image-select-container',
		imageClass: 'image-select',
		imageSrc: 'text',
		thumbnailWidth: '60',
		emptyText: 'No image'
	};
  
	function debug(msg) {
		if (window.console && window.console.log) 
			window.console.log('imageselect: ' + msg);
	};
  

})(jQuery)


function getImageWidth(myImage) {
	var x, obj;
	if (document.layers) {
		var img = getImage(myImage);
		return img.width;
	} else {
		return getElementWidth(myImage);
	}
	return -1;
}

function getImageHeight(myImage) {
	var y, obj;
	if (document.layers) {
		var img = getImage(myImage);
		return img.height;
	} else {
		return getElementHeight(myImage);
	}
	return -1;
}


$.fn.insertAtCaret = function (myValue) {
        return this.each(function(){
                //IE support
                if (document.selection) {
                        this.focus();
                        sel = document.selection.createRange();
                        sel.text = myValue;
                        this.focus();
                }
                //MOZILLA/NETSCAPE support
                else if (this.selectionStart || this.selectionStart == '0') {
                        var startPos = this.selectionStart;
                        var endPos = this.selectionEnd;
                        var scrollTop = this.scrollTop;
                        this.value = this.value.substring(0, startPos)
                                      + myValue
                              + this.value.substring(endPos,
this.value.length);
                        this.focus();
                        this.selectionStart = startPos + myValue.length;
                        this.selectionEnd = startPos + myValue.length;
                        this.scrollTop = scrollTop;
                } else {
                        this.value += myValue;
                        this.focus();
                }
        });

};
