// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

// jQuery and respond_to: http://ozmm.org/posts/jquery_and_respond_to.html
jQuery.ajaxSetup({ 
  'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")} 
})

// This function gets called when the end-user clicks on some date.
function selected(cal, date) {
	cal.sel.value = date; // just update the date in the input field.
	
	if (jQuery("#maspore_date_of_event_censor").length > 0 && jQuery("#maspore_date_of_diagnosis").length > 0) {
		if (jQuery("#maspore_date_of_event_censor").val() != "" && jQuery("#maspore_date_of_diagnosis").val() != "") {
			var startDay = jQuery("#maspore_date_of_event_censor").val();
			var endDay = jQuery("#maspore_date_of_diagnosis").val();
			
			jQuery("#maspore_event_free_survial").val(Math.round(Utils.minus2Dates(startDay, endDay) / 365.4 * 10000) / 10000);
		}//end if
	}//end if
	
	if (jQuery("#maspore_date_of_diagnosis").length > 0) {
		if ( jQuery("#maspore_date_of_diagnosis").val() != "") {
			var startDay = "00-00-0001";
			var endDay = jQuery("#maspore_date_of_diagnosis").val();
			
			jQuery("#maspore_leukemial_free_survial").val(Math.round(Utils.minus2Dates(startDay, endDay) / 365.4 * 10000) / 10000);
		}//end if
	}//end if
	
	if( jQuery("#maspore_date_of_diagnosis").length > 0 && jQuery("#relapse_1_date_of_relapse").length > 0) {
		if (jQuery("#maspore_date_of_diagnosis").val() != "" && jQuery("#relapse_1_date_of_relapse").val() != "") {
			var startDay = jQuery("#relapse_1_date_of_relapse").val();
			var endDay = jQuery("#maspore_date_of_diagnosis").val();
			
			jQuery("#maspore_relapse_free_survival").val(Math.round(Utils.minus2Dates(startDay, endDay) / 365.4 * 10000) / 10000);
		}//end if	
	}//end if
	
	if( jQuery("#maspore_date_of_diagnosis").length > 0 && jQuery("#maspore_date_of_death").length > 0) {
		if (jQuery("#maspore_date_of_diagnosis").val() != "" && jQuery("#maspore_date_of_death").val() != "") {
			var startDay = jQuery("#maspore_date_of_death").val();
			var endDay = jQuery("#maspore_date_of_diagnosis").val();
			
			jQuery("#maspore_overall_survial").val(Math.round(Utils.minus2Dates(startDay, endDay) / 365.4 * 10000) / 10000);
		}//end if	
	}//end if
	
	if( jQuery("#diagnosis_date_of_bma").length > 0 && jQuery("#diagnosis_date_of_diagnosis_new").length > 0) {
		if( jQuery("#diagnosis_date_of_bma").val() != "" && jQuery("#diagnosis_date_of_diagnosis_new").val() != "") {
			var startDay = jQuery("#diagnosis_date_of_diagnosis_new").val();
			var endDay = jQuery("#diagnosis_date_of_bma").val();
			
			var numberOfDay = Math.round(Utils.minus2Dates(startDay, endDay) * 10000) / 10000;
			var year = Math.floor(numberOfDay / 365);
			var month = Math.floor((numberOfDay - year * 365)/30);
			var day = Math.floor((numberOfDay - year * 365 - month * 30));
			var str = "";
			if( year != 0) {
				str += year + " Year(s) ";
			}//end if
			
			if(month != 0) {
				str += month + " Month(s) ";
			}//end if
			str += day + " Day(s)";
			if( str.charAt(0) == '-') {
				str = str.substring(1);
			}//end if
			jQuery("#predicted_time_point").html("<b>" + str + "</b>");
		}//end if
		else {
			jQuery("#predicted_time_point").html("");
		}//end else
	}//end if
	
  	//if (cal.dateClicked && (cal.sel.id == "sel1" || cal.sel.id == "sel3"))
	if (cal.dateClicked)
    // if we add this call we close the calendar on single-click.
    // just to exemplify both cases, we are using this only for the 1st
    // and the 3rd field, while 2nd and 4th will still require double-click.
    cal.callCloseHandler();
}

// And this gets called when the end-user clicks on the _selected_ date,
// or clicks on the "Close" button.  It just hides the calendar without
// destroying it.
function closeHandler(cal) {
  cal.hide();                        // hide the calendar
	cal.destroy();
  _dynarch_popupCalendar = null;
}

// This function shows the calendar under the element having the given id.
// It takes care of catching "mousedown" signals on document and hiding the
// calendar if the click was outside.
function showCalendar(id, format, default_date, showsTime, showsOtherMonths) {
  var el = document.getElementById(id);
  if (_dynarch_popupCalendar != null) {
    // we already have some calendar created
    _dynarch_popupCalendar.hide();                 // so we hide it first.
  } else {
    // first-time call, create the calendar.
    var cal = new Calendar(1, null, selected, closeHandler);
	
	
    // uncomment the following line to hide the week numbers
    // cal.weekNumbers = false;
    if (typeof showsTime == "string") {
      cal.showsTime = true;
      cal.time24 = (showsTime == "24");
    }
    if (showsOtherMonths) {
      cal.showsOtherMonths = true;
    }
    _dynarch_popupCalendar = cal;                  // remember it in the global var
    cal.setRange(1900, 2070);        // min/max year allowed.
    cal.create();
  }
  
  _dynarch_popupCalendar.setDateFormat(format);    // set the specified date format
  _dynarch_popupCalendar.parseDate(el.value);      // try to parse the text in field

  if( jQuery("input[@id*='" + id + "']").val() == "" && typeof(default_date) != "undefined") {	
  	_dynarch_popupCalendar.parseDate(default_date);	
  }//end if
  
  _dynarch_popupCalendar.sel = el;                 // inform it what input field we use

  // the reference element that we pass to showAtElement is the button that
  // triggers the calendar.  In this example we align the calendar bottom-right
  // to the button.
  _dynarch_popupCalendar.showAtElement(el, "Br");        // show the calendar

  return false;
}

var MINUTE = 60 * 1000;
var HOUR = 60 * MINUTE;
var DAY = 24 * HOUR;
var WEEK = 7 * DAY;


jQuery(document).ready(function() {
	jQuery("div.sidebar").mouseover(function() {
		var ul = jQuery(this).children(":first");
		var sibling = jQuery(this).children(":last");
		sibling.css("display", "block");
	});
	
	jQuery("div.sidebar").mouseout(function() {
		var sibling = jQuery(this).children(":last");
		sibling.css("display", "none");
	});
	
	jQuery("li.function-name-div").click(function() {
		var link = jQuery(this).children(":first").attr("href");
		document.location = link;
		return false;
	});
	
	/*
		jQuery("div.sidebar").find("li").mouseover( function() {
			jQuery(this).css("background-color", "#9fbbe0");
		}).mouseout(function() {
			jQuery(this).css("background-color", "#c9daef");
		});
	*/
	
	jQuery("table.tablesorter").find("tr").mouseover(function() {
		jQuery(this).find("td").css("background-color", "#FFFABF");
	}).mouseout(function() {
		if (jQuery(this).attr("class") == "odd") {
			jQuery(this).find("td").css("background-color", "#F9F9F9");
		}//end if
		else {
			jQuery(this).find("td").css("background-color", "#fff");
		}//end else
	});
	
	jQuery("table.tablesorter").find("td").click(function() {
		jQuery(this).css({"background-color": "#CFDCFF"});
	});
	
});

function addMoreLocation( link_dom ) {
	var html = jQuery(link_dom).parent().parent().parent().html();
	var super_parent = jQuery(link_dom).parent().parent().parent().parent();
	super_parent.find("input[@name*=_location]").each(function() {
		var name = jQuery(this).attr("name");
		var stt = name.split("@")[0];
		var tail = name.split("@")[1];
	});
	super_parent.append("<div class = 'location-form'>" + html + "</div>");
	return false;
}//end addMoreLocation

function removeLocation( link_dom ) {
	if (jQuery(link_dom).parent().parent().parent().parent().find("div.location-form").length > 1) {
		jQuery(link_dom).parent().parent().parent().remove();
	}//end if
	return false;
}//end addMoreLocation

function updateVialsLeft() {
	jQuery("input[@name*='vials_taken_out']").blur(function() {
		var name = jQuery(this).attr("name").split("[")[0];
		var initial = parseInt(jQuery("#" + name + "_initial").html());
		var vialsLeftField = jQuery("#" + name + "_left");
		var leftValue = parseInt(vialsLeftField.html());
		if (!Utils.isNumeric(jQuery(this).val())) {
			alert("Please key in a numeric value");
			jQuery(this)[0].select();
			return false;
		}//end if
		var takenOutValue = parseInt(jQuery(this).val());
		if (takenOutValue > initial) {
			alert("You cannot take more " + initial);
			jQuery(this)[0].focus();
			return false;
		} else {
			if (initial == takenOutValue) {
				vialsLeftField.html("0");
			}
			else {
				vialsLeftField.html(initial - takenOutValue);
			}//end else
		}//end else
		
	});
}//end updateVialsLeft

function addDNAUnit( dom ) {
	var numberOfUnit = jQuery(dom).val();
	var dna_unit_location = jQuery(dom).parent().parent().parent().find("div[@name='dna-unit']");
	
	var dna_entry = jQuery(dom).parent().parent().parent().find("div[@class='dna_entry_name']");
	var dna_entry_name = dna_entry.attr("name");
	dna_unit_location.html("");
	var each_entry_name = dna_entry.find("input")[0].name;
	var original_name = each_entry_name.split("[")[0];
	for( var i = 0; i < numberOfUnit; i++) {
		var postfix = i == 0 ? "" : i + "";
		var initialHtml = dna_entry.html();
		dna_entry.find("td[@name=t-label]").each(function() {
			var currentHTML = jQuery(this).html();
			currentHTML = "T" + postfix + " " + currentHTML.split("T ")[1];
			jQuery(this).html(currentHTML);	
		});
		
		dna_entry.find("input").each(function() {
			var currentName =  jQuery(this).attr("name");
			currentName = currentName.split("[")[0] + "_unit" + i + "[" + currentName.split("[")[1];
			jQuery(this).attr("name", currentName);
			jQuery(this).addClass("{conditions:['not-blank']}");
		});
		dna_unit_location.append(dna_entry.html());
		dna_entry.html(initialHtml);
	}//end for
}//end addDNAUnit

function addEnrolmentForm( dom ) {
	var parent = jQuery(dom).parent();
	var html = parent.html();
	var formPath = jQuery(dom).attr("formpath");
	var patientId = jQuery(dom).attr("patientid");
	var enrolmentFormId = jQuery(dom).attr("enrolmentformid");
	
	parent.html("<img src = '/images/loading.gif'></img>");
	
	jQuery.post("/forms/associate_enrolment_form", {fpath: formPath, pid: patientId, enrolmentformid : enrolmentFormId}, function() {
		parent.html("<a href = '" + formPath + "'>View</a> | <a href = '#' enrolmentformid = '" + enrolmentFormId + "'formpath = '" + formPath + "' patientid = '" + patientId + "' onclick = 'javascript:removeEnrolmentForm(this)'>Remove</a>")
	});
	return false;
	
}//end removeEnrolmentForm

function removeEnrolmentForm( dom ) {
	var parent = jQuery(dom).parent();
	var html = parent.html();
	var formPath = jQuery(dom).attr("formpath");
	var patientId = jQuery(dom).attr("patientid");
	var enrolmentFormId = jQuery(dom).attr("enrolmentformid");
	parent.html("<img src = '/images/loading.gif'></img>");
	
	jQuery.post("/forms/remove_associate_enrolment_form", {pid: patientId}, function() {
		parent.html("<a href = '#' enrolmentformid = '" + enrolmentFormId + "' onclick = 'javascript:return addEnrolmentForm(this);' formpath = '" + formPath + "' patientid = '" + patientId + "'>Add</a>")
	});
	return false;
	
}//end removeEnrolmentForm

function setActionForUploadForm( domId, button_id ) {	
	
	if (false) {
		jQuery("#" + domId).change(function(){
			jQuery("#uploading-form-div").css("display", "none");
			jQuery("#loading-div-for-uploading-form").css("display", "block");
			jQuery("#" + button_id).click();
			return false;
		});//end onchange
	}//end if
}//end setActionForUploadImage

function updateUploadForm( filePath, publicFileName, formId ) {
	jQuery("#loading-div-for-uploading-form").css("display", "none");
	jQuery("#loading-div-for-uploading-after-upload").css("display", "block");
	jQuery("#loading-div-for-uploading-after-upload").html("<a href = '" + publicFileName + "'>" + filePath + "</a>");
	jQuery("#submit-form-id").val(formId)
}//end updateUploadForm


jQuery.fn.submitWithAjax = function(targetdiv) {			// submits a form via ajax and load the returned results into "targetdiv" layer
	this.submit(function() {
		$(targetdiv).load($(this).attr("action"),$(this).serializeArray());
		// $(this)[0].reset();			// this resets the form
		return false;		
	})
};	

function display_ae(aeid,targetdiv) {
	if (aeid=="") {
		jQuery(targetdiv).hide();
	}
	else {			
		jQuery(targetdiv).load('/antiemetics/show_dd_details/'+ aeid);
		jQuery(targetdiv).show();
	}
};



