var jpform_before = function(data, form, opts) {
	var job = $('select[name=job]', form);
	var comp = $('#id_company', form);

	// either a job is specified, or company name is not dirty
	$('.company-error').toggle(!job.val() && comp.hasClass('searching'));
	return (job.val() || !comp.hasClass('searching'));
}

var run_calendar = function(randkey, dynamic, cid, full_calendar_options) {
	var jobkind = 0;
	var jobtype = '';
	var scope = $('.sel-page-randkey:contains(' + randkey + ')').parent();
	var jpform = $('#jpform-' + randkey);

	function prepJobForm(button, clicked, calCell) {
 		//console.log($(calCell));
 		//console.log($(calCell).attr('date'));
		if (calCell) {
			var mydate = $(calCell).attr('date');
			var date_input = $("input[name=date]", jpform);
			mydate = $.datepicker.parseDate('m-d-yy', mydate);
			mydate = $.datepicker.formatDate(date_input.attr('format'), mydate);
			date_input.val(mydate);
		}

 		// If this is an option, allow setting the option number
 		$('p.optnumber', jpform).toggle(jobtype == 'option')
	    $("select#id_option_number option[value='1']", jpform).attr('selected', 'selected');

   		$('input[name=kind]', jpform).val(jobkind);
    	$('input[name=model]', jpform).val($.selectedModel);
 		$('input[name=name]', jpform).val('');
		$('input[name=company]', jpform).parents('p').toggle(jobtype != 'out');
		$('#id_name_optional', jpform).toggle(jobtype != 'out');
 		$('input[name=company]', jpform).val('');
 		$('input#id_company', jpform).val('start typing slowly..');
 		$('input#id_company', jpform).removeClass('searching');
 		$('.errorlist:not(.company-error)', jpform).remove();
 		$('.company-error', jpform).hide();
    	jpform.dialog('open');
	}

	function installCalendar (source) {
		if (!source && installCalendar.last_source)
			source = installCalendar.last_source;
		installCalendar.last_source = source;

		var dropfn = function(event, ui) {
            var elem = ui.draggable;
            if (!elem.hasClass('phasebutton'))
                return;
			prepJobForm(elem, false, this);
		}

	    var myFcnOpts = {
	        aspectRatio: 1,
			events: source,
			header: {
				left: 'prev,next today',
				center: 'title',
				right: cid ? 'month,agendaWeek,agendaDay' : 'month,basicWeek,agendaDay'
			},
	        eventRender: function(event, element) {
	            element.attr('title', event.description);
	            element.css('background-color', '#'+event.color);
                var timeoutId;
                var tipsyOpts = {
                    gravity: 'n',
                    html: true,
                    title: function () {
                        var src = '/job/jobphase_tooltip/' + event.phaseid + '/';
                        var target = devlib.tmpElem();
                        target.show();

                        timeoutId = setTimeout(function () {
                            $.get(src, function (data) {
                                $(target).html(data);
                            })
                        }, 250);
                        console.log(this);
                        return target;
                    }
                }

                tipsyOpts.onHoverOut = function () {
                    console.log('clearing timeout');
                    clearTimeout(timeoutId);
                }


                $(element).find('a').tipsy(tipsyOpts);
	        },
			viewDisplay: function (view) {
	            $.selectedModel = cid;
				$('td[class^=fc][date]').droppable({drop: dropfn});			
			},
		firstDay: 1
		};

                $.extend(myFcnOpts, full_calendar_options);

		if ($('#calendar', scope).data('fullCalendar'))
			$('#calendar', scope).fullCalendar('destroy');
		$('#calendar', scope).fullCalendar(myFcnOpts);
		$('#calendar', scope).fullCalendar('render');
	}

	$(".phasebutton", scope).mousedown(function(){
		jobkind = $(this).attr('pid');
		if($(this).hasClass('event-option')) jobtype = 'option';
		else if($(this).hasClass('event-out')) jobtype = 'out';
		else jobtype = '';
		jpform.dialog('option', 'title', 'New ' + $(this).text());
	});

	$(".phaselink", scope).click(function(event){
		event.preventDefault();
		prepJobForm(0, true, 0);
	});

	$('.phasebutton', scope).draggable({
		helper: 'clone'
	});

	$('.col .click-edit', scope).after("<br />");

    var toggle_fields = function() {
    	var show = !$('select[name="job"]', jpform).val();
    	$('#new-job-fields', jpform).toggle(show);
	};
	$('#id_job option[value=""]', jpform).text('New job...');
	$('#id_job', jpform).click(toggle_fields);
	$('#id_job', jpform).keyup(toggle_fields);
	toggle_fields()

    $('#id_company', jpform)
    	.autocomplete('/contact/contact_autocomplete/company/', {
		}).result(function(event, item) {
			$(this).removeClass('searching');
			$('input[name=company]', jpform).val(item[1]);
    	}).bind('empty', function(event) {
			$(this).removeClass('searching');
			$('input[name=company]', jpform).val('');
    	}).bind('dirty', function(event) {
			$(this).addClass('searching');
			$('input[name=company]', jpform).val('');
		});

	if (cid) {
    	installCalendar('/job/calendar_source/' + cid + '/');
		$.selectedModel = cid;
	} else {
    	installCalendar('/job/calendar_source/');
	}

	if (dynamic) {
		devlib.runLib(jpform);
	}

	jpform.dialog({autoOpen: false, title: 'New job phase' });
};

