/*
Dogpicker plugin for jQuery.
by: Daymon Rogers
  
Creates a floating window with a form that lets you pick a dog from
a list.

Inputs: parentid: The parent window id.
		settings: 
Outputs: An object containing the dogs "name" and identification "number"

To use just include the plugin in the HEAD section of the page AFTER calling jQuery.

*/

(function($){
    /* Attach the picker to a jQuery selection. */
    $.fn.dogpicker = function(options){
        // make sure we over-ride defaults w/user specified options
        var opts = $.extend({}, $.fn.dogpicker.defaults, options);

		// build the dogPicker HTML
        function getDialogHtml(limituser)
        {
    		var html = '<div class="dogpicker_layer">' +
				'<div class="dogpicker_layer_handle">' +
					'<a class="dogpicker_close">[ x ]</a>' +
					'Pick a Dog' +
				'</div>' +
				'<div class="dogpicker_layer_content">' +
					'<div>' +
						'<label>' +
							'Filter:<input class="dogpicker_filter_id" type="text" />' +
						'</label>' +
						'<label><input class="dogpicker_limituser" type="checkbox" value="checkbox"' +
							'checked=' + (limituser?'"checked"':'"unchecked"') + '/>' +
							'show only my dogs' +
						'</label>' +
					'</div>' +
					'<select class="dogpicker_dog_list" size="10">' +
					'</select>' +
					'<input class="dogpicker_ok" type="submit" name="submit" value="OK"/>' +
				'</div>' +
			'</div>';
            return html;
        }

        // iterate and format each matched element
        return this.each(function(){
            var that = this;
            var $this = $(this);

            // build element specific options
            this.meta = $.meta ? $.extend({}, opts, $this.metadata()) : opts;
            var o = $this.metadata();

            if (this.nodeName.toLowerCase() == 'table')
            {
                init();
            }

            function open(obj) {
                var parnt = $(obj).parent();
                var layer = $(".dogpicker_layer", parnt);
                // if the dialog hasn't been created yet, create it
                if (layer.length < 1 || layer.get(0) == document)
                {
                    // create the dialog, initially invisible
                    createDialog();
                    layer = $(".dogpicker_layer", parnt);
                }
                // make it visible
                layer.css("visibility","visible");
            }

            function close(obj) {
                $(obj).parent().parent().css("visibility","hidden");
            }

            function init() {
                $this.wrap("<div></div>");
                // create the link that triggers openning the dialog
                $this.before("<a class='dogpicker_trigger'>add a new dog</a>");
                // create the dialog, initially invisible
//                createDialog();
                // set up the trigger callback
                $(".dogpicker_trigger",$this.parent()).click(function () {
                    open(this);
                });
             }

            function createDialog() {
                var html = getDialogHtml(o.limituser);
                $this.before(html);
                $(".dogpicker_close",$this.parent()).click(function() {
                    close(this);
                });
            }
        });
    }

})(jQuery);
/*
var dogPickerPopup = {
	damName: "",
	sireName: "",
	popUpShowing: false,
	autoPopUp: 'both',
	buttonImageOnly: '',
	buttonText: '...', // Text for trigger button
	onlymine: true,
	currentVal: '',
	acDelay: 1000,
	sex: 'female',
	damNameId: 0, // id of the input field that will get the dog name if sex==female
	sireNameId: 0, // id of the input field that will get the dog name if sex==male
	damTargetId: 0, // id of the hidden input field tha will get the dog id if the sex==female
	sireTargetId: 0, // id of the hidden input field tha will get the dog id if the sex==male

	init: function() {
		this.dogPickerDiv = $('<div id="dogPickerDiv"></div>');
		this.lastInput = null;
		$('body').append(this.dogPickerDiv);
		$(document).mousedown(dogPickerPopup.checkExtClick);
	},
	// Hide the picker from view.
	hideDogPicker: function(speed) {
		if (this.popUpShowing) {
			this.dogPickerDiv.hide(speed, this.tidyStandalone);
			if (speed == '') this.tidyStandalone();
			this.popUpShowing = false;
			this.lastInput = null;
		}
	},
	checkExtClick: function(event) {
		if (dogPickerPopup.popUpShowing) {
			var node = event.target;
			var cal = dogPickerPopup.dogPickerDiv[0];
			while (node && node != cal && node.className != 'dogpicker_trigger') {
				node = node.parentNode;
			}
			if (!node) {
				dogPickerPopup.hideDogPicker('');
			}
		}
	},
	// Tidy up after a dialog display.
	tidyStandalone: function() {
//		dogPickerPopup.dogPickerDiv.removeClass('calendar_dialog');
		$('dogpicker_layer').remove();
	},
	// Attach the picker to an input field.
	connectPicker: function(target) {
		var $input = $(target);
		$input.after('<span class="dogpicker_append"></span>');
		if (this.autoPopUp == 'focus' || this.autoPopUp == 'both') { // pop-up picker when in the marked fields
			$input.focus(this.showFor);
		}
		if (this.autoPopUp == 'button' || this.autoPopUp == 'both') { // pop-up picker when button clicked
			$input.wrap('<span class="dogpicker_wrap"></span>').
				after(this.buttonImageOnly ? '<img class="dogpicker_trigger" src="' +
				this.buttonImage + '" alt="' + this.buttonText + '" title="' + this.buttonText + '"/>' :
				'<button type="button" class="dogpicker_trigger">' + (this.buttonImage != '' ?
				'<img src="' + this.buttonImage + '" alt="' + this.buttonText + '" title="' + this.buttonText + '"/>' :
				this.buttonText) + '</button>');
			$((this.buttonImageOnly ? 'img' : 'button') + '.dogpicker_trigger', $input.parent('span')).click(this.showFor);
		}
		$input.keydown(this.doKeyDown).keypress(this.doKeyPress);
	},
	// Pop-up the picker for a given input field.
	showFor: function(target) {
		var input = (target.nodeName && target.nodeName.toLowerCase() == 'input' ? target : this);
		if (input.nodeName.toLowerCase() != 'input') { // find from button/image trigger
			input = $('../input', input)[0];
		}
		if (dogPickerPopup.lastInput == input) { // already here
			return;
		}

		dogPickerPopup.input = $(input);
		dogPickerPopup.hideDogPicker('');
		dogPickerPopup.lastInput = input;
		if (!dogPickerPopup.pos) { // position below input
			dogPickerPopup.pos = dogPickerPopup.findPos(input);
			dogPickerPopup.pos[1] += input.offsetHeight;
		}
		dogPickerPopup.dogPickerDiv.css('position', 'absolute').
			css('left', dogPickerPopup.pos[0] + 'px').css('top', dogPickerPopup.pos[1] + 'px');
		dogPickerPopup.pos = null;
		$.extend(dogPickerPopup, (dogPickerPopup.fieldSettings ? dogPickerPopup.fieldSettings(input) : {}));
		dogPickerPopup.showDogPicker((input.id==dogPickerPopup.damNameId)?'female':'male');
	},
	// Construct and display the picker.
	showDogPicker: function(sex) {
		this.popUpShowing = true;
		// build the dogPicker HTML
		var html = '<div id="dogpicker_layer">' +
				'<div id="dogpicker_layer_handle">' +			
					'<a id="dogpicker_close" onclick="dogPickerPopup.hideDogPicker(dogPickerPopup.speed);">[ x ]</a>' +
					'Pick a Dog' +
				'</div>' +
				'<div id="dogpicker_layer_content">' +
					'<div>' +
						'<label>' +
							'Filter:<input id="dogpicker_filter_id" type="text" />' +
						'</label>' +
						'<label><input id="dogpicker_onlymine_checkbox" type="checkbox" value="checkbox"' +
							'checked=' + (dogPickerPopup.onlymine?'"checked"':'"unchecked"') + '/>' +
							'show only my dogs' +
						'</label>' +
					'</div>' +
					'<select id="dogpicker_dog_list" size="10">' +
					'</select>' +
					'<input id="dogpicker_ok" type="submit" name="submit" value="OK" onclick="dogPickerPopup.setDog();"/>' +
				'</div>' +
			'</div>';

		// add picker to element to pick div
		this.dogPickerDiv.empty().append(html).show('slow');
//		if (this.speed == '') this.coverSelects();
		this.input[0].focus();
		$('#dogpicker_layer').Draggable(
				{
					zIndex: 	20,
					ghosting:	false,
					opacity: 	0.7,
					handle:	'#dogpicker_layer_handle'
				}
			);
		$("#dogpicker_onlymine_checkbox").attr("checked", dogPickerPopup.onlymine);
		$("#dogpicker_onlymine_checkbox").click(function(){
			dogPickerPopup.onlymine = this.checked;
			dogPickerPopup.requestDogs('dogpicker_dog_list',sex, this.checked, $("#dogpicker_filter_id").val());
		});
		$("#dogpicker_filter_id").keyup(function(e){
			var keycode=e.keyCode || window.event.keyCode;
			var currentVal = $("#dogpicker_filter_id").val();
			setTimeout(function(){dogPickerPopup.applyNewFilter(sex, currentVal), dogPickerPopup.acDelay});		
		});

		dogPickerPopup.getDogList(sex);
	}, // end showDogPicker
	applyNewFilter: function(sex, lastValue)
	{
		var currentValue;
		currentValue = $("#dogpicker_filter_id").val();
	
		// if the text hasn't changed since the timeout was set,
		// use the current value as a filter
		if (currentValue != lastValue)
			return;
	
		dogPickerPopup.requestDogs('dogpicker_dog_list', sex, $("#dogpicker_onlymine_checkbox").attr("checked"), currentValue);
	},

	getDogList: function(sex) {
		$("#dogpicker_filter_id").val("");
		dogPickerPopup.requestDogs('dogpicker_dog_list',
					sex, 
					$("#dogpicker_onlymine_checkbox").attr("checked"), 
					$("#dogpicker_filter_id").val())
	},
	setDog: function() {
		this.input.val($("#dogpicker_dog_list option:selected").text());
		this.input.trigger('change');
		if (this.input.attr("id")==dogPickerPopup.damNameId)
			$("#"+dogPickerPopup.damTargetId).val($("#dogpicker_dog_list option:selected").val());
		else
			$("#"+dogPickerPopup.sireTargetId).val($("#dogpicker_dog_list option:selected").val());
		dogPickerPopup.hideDogPicker('');
	},
	requestDogs: function(listid, sex, onlyMine, filter)
	{
		$("#"+listid).empty();
		var theListWidget = document.getElementById(listid);
		if (theListWidget)
			theListWidget.options[0]=new Option("Updating...",0,false,false);

		request = 'listid='+listid+'&action=';
		if (!sex || sex=="female")
			request += 'getmoms';
		else
			request += 'getdads';
		if (onlyMine)
			request += '&onlymine=true';
		if (filter)
			request += '&filter='+filter;

		$.ajax({type: "GET", 
				url: "/myDogSpot/add/ajxGetDogList.php",
				data: request,
				dataType: "json",
				success: dogPickerPopup.parseDogList});
	},
	parseDogList: function(data)
	{
		if (!data.listid || !data.animals)
			return;
		var theListWidget = document.getElementById(data.listid);

		if (!theListWidget || !theListWidget.options || data.animals.length<=0)
		{
			return;
		}
		$("#"+data.listid).empty();
		for (var loop=0;loop<data.animals.length;loop++)
		{
			var newOption = new Option(data.animals[loop].name, data.animals[loop].id, false, false);
			theListWidget.options[theListWidget.length] = newOption;
		}
	},
	// Find an object's position on the screen.
	findPos: function(obj) {
		var curleft = curtop = 0;
		if (obj.offsetParent) {
			curleft = obj.offsetLeft;
			curtop = obj.offsetTop;
			while (obj = obj.offsetParent) {
				var origcurleft = curleft;
				curleft += obj.offsetLeft;
				if (curleft < 0) {
					curleft = origcurleft;
				}
				curtop += obj.offsetTop;
			}
		}
		return [curleft,curtop];
	}
};


// Initialise the picker.
$(document).ready(function() {
   dogPickerPopup.init();
});

*/
