With this code i able to show daily and weekly event, but i am unable to show monthly event.I am using full calendar plugin in one of my laravel project.by using dow parameter i show daily event and with ranges show event form starting date.
$('#calendar').fullCalendar({
defaultDate: moment(),
editable: false,
eventLimit: true, // allow "more" link when too many events
events:function(start, end, timezone, callback){
$.ajax({url: baseUrl +"/calenderevents",
type:'post',
success: function(data)
{
var events = [];
var range = [];
$.each(data, function(index, element) {
events.push({
title : element.title,
start : element.start,
end : element.end,
id : element.id,
dow : element.dow,
ranges : range
});
range.push({
start: moment(element.ranges)
});
});
callback(events);
}
});
},
dayClick: function() {
$('#event-message').text("Add Activity");
$('#calender-error').html('');
if($("#user_role_id").data("user-role") == 1){
return false;
}
$("#delete-event").hide();
$('.dimensions').attr('readonly', 'readonly');
$('#clear-form').click();
$('.calender-event').attr({
'id':'calender_event_form',
'action':baseUrl+'/assisted',
});
$.fancybox({
content: $('#add_calender_event'),
padding : 10,
fitToView:false,
autoSize: false,
width:485,
height:600,
openEffect : 'elastic',
closeEffect : 'elastic',
});
},
eventRender: function (event, element) {
// element.addClass('href', 'javascript:void(0);');
element.addClass('event');
element.attr('id', event.id);
if("ranges" in event)
{
return (event.ranges.filter(function(range){ // test event against all the ranges
return (event.start.isAfter(range.start));
}).length)>0;
}
}
});
var matchingDaysBetween = function (start, end, test) {
var days = [];
for (var day = moment(start); day.isBefore(end); day.add(30, 'd')) {
if (test(day)) {
days.push(moment(day));
// push a copy of day
}
}
return days;
}
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
var defaultEvents = [
<c:forEach var='periodicTask' items='${periodicTaskTemplates}'>
<c:choose>
<c:when test='${fn:containsIgnoreCase(periodicTask.frequency, "Weekly")}'>
{ id: '${periodicTask.id}', title: '${periodicTask.task}',
start: '10:00', // a start time (10am in this example)
end: '14:00', // an end time (6pm in this example)
ranges: [{ //repeating events are only displayed if they are within one of the following ranges.
start: moment(new Date('${periodicTask.startDate}')).startOf('year'), //next two weeks
end: moment(new Date('${periodicTask.endDate}')).add(7,'d'),
}]
,type:'${periodicTask.description}',location:'${periodicTask.location.name}',endDate:new Date('${periodicTask.endDate}'),area: '${periodicTask.area.name}',frequency:'${periodicTask.frequency}', startDate: new Date('${periodicTask.startDate}'),repeat: 0,color: "#"+ Math.random().toString(16).slice(2, 8) ,dow: [${periodicTask.day}]},
</c:when>
<c:otherwise>
{ id: '${periodicTask.id}', title: '${periodicTask.task}',start: new Date(y, m, '${periodicTask.startDay}'), end: new Date(y, m, '${periodicTask.endDay}', 24, 0, 0, 0) ,type:'${periodicTask.description}',area: '${periodicTask.area.name}',startDate: new Date('${periodicTask.startDate}'),frequency:'${periodicTask.frequency}',location:'${periodicTask.location.name}', repeat: 1,endDate:new Date('${periodicTask.endDate}'), color: "#"+ Math.random().toString(16).slice(2, 8) },
</c:otherwise>
</c:choose>
</c:forEach>
];
// Any value represanting monthly repeat flag
var REPEAT_MONTHLY = 1;
// Any value represanting yearly repeat flag
var REPEAT_YEARLY = 2;
function Unix_timestamp(t)
{
var dt = new Date(t*1000);
var hr = dt.getHours();
var m = "0" + dt.getMinutes();
var s = "0" + dt.getSeconds();
return dt;
}
$('#calendar').fullCalendar({
header: {
left: 'prev,next',
center: 'title',
right: 'month,basicWeek,basicDay'
},
displayEventTime: false,
eventLimit: true,
editable: true,
eventMouseover: function (data, event, view) {
// $('#'+data.id).tooltip('show')
tooltip = '<div class="tooltip tooltip-top" style="display:none;position:absolute;border:1px solid #333;background-color:#161616;border-radius:5px;padding:10px; color:#fff;font-size:12px Arial;;height:auto;position:absolute;z-index:10001;line-height: 150%;">' + 'title ' + ':- ' + data.title + '</br>' + 'description ' + ':- ' + data.type + '</br>' + 'location ' + ':- ' + data.location + '</br>' + 'Frequency ' + ':- ' + data.frequency + '</br>' + 'Area ' + ':- ' + data.area+'';
if(data.frequency =='Weekly'){
var weekday = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
tooltip += '</br>'+'Day' + ':- ' + weekday[data.dow] + '</br></div>';
}else{
tooltip += '</br>'+'Start Date ' + ':- ' + data.startDate + '</br>End Date ' + ':- ' + data.endDate + '</br></div>';
}
$("body").append(tooltip);
$(this).mouseover(function (e) {
$(this).css('z-index', 10000);
$('.tooltip ').fadeIn('500');
$('.tooltip ').fadeTo('10', 1.9);
}).mousemove(function (e) {
$('.tooltip ').css('top', e.pageY + 10);
$('.tooltip ').css('left', e.pageX + 20);
});
},
eventDrop: function(event, delta, revertFunc) {
swal({
title: "Are you sure?",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, Re-Shedule it!"
},
function (isConfirm) {
if (isConfirm)
{
window.location = "${pageContext.request.contextPath}/task/periodic-task-shedule-update/"+event.id+"/"+event.start.format()+"/"+new Date(event.start).getDay() ;
}
else{
revertFunc()
}
});
},
eventMouseout: function (data, event, view) {
$(this).css('z-index', 8);
$('.tooltip ').remove();
},
events: function(start, end, timezone, callback) {
/* $.ajax({
type: "POST",
url: "${pageContext.request.contextPath}/task/calendar-periodic-task-view",
dataType: 'json',
data: {
start: event.start,
end: event.end
},
success: function(doc) {
var events = [];
$(doc).find('event').each(function() {
events.push({
start: $('#start').val(''),
end: $('#end').val('')
});
});
callback(events);
}
}); */
var current_month = new Date($('#calendar').fullCalendar('getDate').format()).getMonth()+1;
var current_fullYear = new Date($('#calendar').fullCalendar('getDate').format()).getFullYear();
var events = [];
$.each(defaultEvents, function(key, event) {
if (Date.parse(new Date(event.endDate)) >= Date.parse(new Date($('#calendar').fullCalendar('getDate').format()))) {
if(event.repeat ===0 ){
var objevent={
start: "14:00",
color:event.color,
id:event.id,
location:event.location,
repeat:event.repeat,
title:event.title,
dow:event.dow,
area:event.area,
frequency:event.frequency,
type:event.type,
endDate:event.endDate,
startDate: event.startDate
}
events.push(objevent);
}else if(event.repeat === 1 && ( current_month > (new Date(event.start).getMonth()+1)) || current_fullYear > new Date(event.start).getFullYear() ){
var new_start_date = new Date(current_fullYear+'-'+current_month+'-'+new Date(event.start).getDate());
var new_end_date = new Date(current_fullYear+'-'+current_month+'-'+new Date(event.end).getDate());
var objevent={
color:event.color,
start:new_start_date,
id:event.id,
location:event.location,
repeat:event.repeat,
area:event.area,
frequency:event.frequency,
end:new_end_date,
title:event.title,
type:event.type,
endDate:event.endDate,
startDate: event.startDate
}
events.push(objevent);
}
events.push(objevent);
}
});
callback(events);
},
});
Related
Default icons not showing for MarkerCluster plugin after using IconCreateFunction.
I want to use the default icons for the plugin but when using attached code I loose all the icons functions, I only get the numbers with no icons and if I activate the "childCount" I get one type of circle with the numbers offcenter within the icon. The markers has already been clustered and I want to add this value to the markercluster that is why I'm using the IconCreateFuncton so the numbers on the map shows correctly but I have lost all the icons and its beautiful functions... what is missing?
Result below using "var childCount"
$.getJSON("../test/test.geojson", function(json) {
geoLayer = L.geoJson(json, {
pointToLayer: function(feature, latlng) {
var log_p = feature.properties.log_p;
var marker;
if (log_p > 0){
marker = new L.shapeMarker(latlng, {radius: log_p*25, fillColor: '#2b83ba', fillOpacity: 0.5, color: '#000000', weight: 1, shape: 'circle'});
}
else {
marker = null
}
return marker;
},
onEachFeature: function(feature, layer) {
var popupText = "Amount per day: " + '<b>' + feature.properties.total + '</b>';
layer.bindPopup(popupText, {
closeButton: true,
offset: L.point(0, -20)
});
layer.on('click', function() {
layer.openPopup();
});
},
});
var markers = new L.MarkerClusterGroup({
iconCreateFunction: function(cluster) {
var children = cluster.getAllChildMarkers();
var sum = 0;
for (var i = 0; i < children.length; i++) {
sum += children[i].feature.properties.total;
}
/*
var childCount = cluster.getAllChildMarkers();
var c = ' marker-cluster-';
if (childCount < 10) {
c += 'small';
} else if (childCount < 500) {
c += 'medium';
} else {
c += 'large';
}
*/
return new L.DivIcon({ html: '<b>' + sum + '</b>', className: 'marker-cluster'/* + c */, iconSize: new L.Point(40, 40) });
}
});
markers.addLayer(geoLayer)
map.addLayer(markers);
});
Markercluster icons, styles and functions are lost
I manage to solve the problem, a few lines of code was missing. I added them to the original JavaScript code as follows.
$.getJSON("../test/test.geojson", function(json) {
geoLayer = L.geoJson(json, {
pointToLayer: function(feature, latlng) {
var log_p = feature.properties.log_p;
var marker;
if (log_p > 0) {
marker = new L.shapeMarker(latlng, {
radius: log_p * 25,
fillColor: '#2b83ba',
fillOpacity: 0.5,
color: '#000000',
weight: 1,
shape: 'circle'
});
} else {
marker = null
}
return marker;
},
onEachFeature: function(feature, layer) {
var popupText = "Amount per day: " + '<b>' + feature.properties.total + '</b>';
layer.bindPopup(popupText, {
closeButton: true,
offset: L.point(0, -20)
});
layer.on('click', function() {
layer.openPopup();
});
},
});
var clusters = new L.MarkerClusterGroup({
maxClusterRadius: 125,
iconCreateFunction: function(cluster) {
var children = cluster.getAllChildMarkers();
var sum = 0;
for (var i = 0; i < children.length; i++) {
sum += children[i].feature.properties.total;
}
var childCount = cluster.getChildCount()
var c = ' marker-cluster-';
if (childCount + sum <= 50) {
c += 'small';
} else if (childCount + sum <= 250) {
c += 'medium';
} else {
c += 'large';
}
return new L.DivIcon({
html: '<div><span>' + sum + '</span></div>',
className: 'marker-cluster marker-cluster-' + c,
iconSize: new L.Point(40, 40)
});
},
});
clusters.addLayer(geoLayer)
map.addLayer(clusters);
});
I can't get the correct visualization on fullcalendar v4. I'm using this format 'DD-MM-YYYY HH:mm:ss' for dates and calendar events or select ranges with '00:00:00' time are shown with one day less.
I tried with nextDayThreshold: "00:00:00" but it seems to be excluding and doesn't works with '00:00:00'.
One option is to modify all end dates from '00:00:00' to '23:59:59', but isn't a good solution.
here there is my calendar definition:
calendar = new FullCalendar.Calendar(calendarEl, {
plugins: ['interaction', 'dayGrid', 'timeGrid', 'list'],
locale: 'es',
selectable: true,
editable: true,
eventLimit: true,
displayEventTime : false,
nextDayThreshold: "00:00:00",
views: {
list: {
displayEventTime : true,
}
},
header: {
left: 'prevYear,prev,next,nextYear,today',
center: 'title',
right: 'dayGridMonth,timeGridWeek,timeGridDay,listMonth'
},
events: [{
daysOfWeek: [0,6],
rendering:"background",
color: "#ff9f89",
overLap: false,
allDay: true
}],
events: function(fetchInfo, successCallback, failureCallback) {
jQuery.ajax({
type: 'POST',
url: '/calendar/getCalendarEvents',
data: {
token: localStorage.token,
userFilter: userFilter
},
success: function(events) {
successCallback(events);
}
});
},
select: function (info) {
startDateSelected = moment(info.startStr).format("DD-MM-YYYY HH:mm:ss");
endDateSelected = moment(info.endStr).format("DD-MM-YYYY HH:mm:ss");
console.log('de ' + startDateSelected + ' a ' + endDateSelected);
},
eventClick: function(info) {
evTittleSelected = info.event.title;
startDateSelected = moment(info.event.start).format("DD-MM-YYYY HH:mm:ss");
endDateSelected = moment(info.event.end).format("DD-MM-YYYY HH:mm:ss");
console.log('de ' + startDateSelected + ' a ' + endDateSelected);
},
eventResize: function(info) {
evTittleSelected = info.event.title;
startDateSelected = moment(info.event.start).format("DD-MM-YYYY HH:mm:ss");
endDateSelected = moment(info.event.end).format("DD-MM-YYYY HH:mm:ss");
console.log('de ' + startDateSelected + ' a ' + endDateSelected);
},
eventDrop: function(info) {
evTittleSelected = info.event.title;
startDateSelected = moment(info.event.start).format("DD-MM-YYYY HH:mm:ss");
endDateSelected = moment(info.event.end).format("DD-MM-YYYY HH:mm:ss");
console.log('de ' + startDateSelected + ' a ' + endDateSelected);
}
});
any idea?
I am trying to plot a mutibar column chart with legend. This is my code. The code is seems to be working but its not adding legend in an appropriate format. I'm adding screenshots of my data table and the output coming from my code. The legend should be showing Different types of priorities but its showing "Legend Text" everywhere.
Output
Datatable
//Plotting Matrix Chart
chartMatrix.Visible = true;
LoadChartData(dtHourvsPriorityMatrix);
chartMatrix.Series["Priority"].ChartType = SeriesChartType.Column;
chartMatrix.Series["Priority"]["DrawingStyle"] = "Emboss";
//chartMatrix.ChartAreas["ChartArea1"].Area3DStyle.Enable3D = true;
chartMatrix.Series["Priority"].IsValueShownAsLabel = true;
// Create a new legend called "Legend".
chartMatrix.Legends.Add(new Legend("Legend"));
// Set Docking of the Legend chart to the Default Chart Area.
chartMatrix.Legends["Legend"].DockedToChartArea = "ChartAreaF";
// Assign the legend to Series=Priority.
chartMatrix.Series["Priority"].Legend = "Legend";
chartMatrix.Series["Priority"].IsVisibleInLegend = true;
LegendCellColumn lcc = new LegendCellColumn("Priority", LegendCellColumnType.Text, "LEGENDTEXT");
lcc.HeaderFont = new System.Drawing.Font("Trebuchet MS", 12F, System.Drawing.FontStyle.Bold);
chartMatrix.Legends["Legend"].CellColumns.Add(lcc);
private void LoadChartData(DataTable initialDataSource)
{
for (int i = 1; i < initialDataSource.Columns.Count; i++)
{
Series series = new Series();
foreach (DataRow dr in initialDataSource.Rows)
{
int y = (int)dr[i];
series.Points.AddXY(dr["Hour"].ToString(), y);
}
chartMatrix.Series.Add(series);
}
}
Try to use canvasjs chart.
Use web service for binding data
<script type="text/javascript">
$(document).ready(function () {
var district = $('#ContentPlaceHolder1_hiddistrict').val();
var assembly = $('#ContentPlaceHolder1_hidassembly').val();
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "../WebMyVoterService.asmx/GenderWise",
data: '{"districtid":"' + district + '","assembly" :"' + assembly + '" }',
processData: false,
success: OnSuccess,
failure: function (response) {
alert(response);
},
error: function (response) {
alert(response);
}
});
function OnSuccess(response) {
var dpmale = [];
var dpfemale = [];
for (var i = 0; i < response.d.length; i++) {
var obj = response.d[i];
var datamale =
{
y: parseInt(obj.male),
label: obj.boothno,
};
var datafemale =
{
y: parseInt(obj.female),
label: obj.boothno,
};
dpmale.push(datamale);
dpfemale.push(datafemale);
}
var chart = new CanvasJS.Chart("chartContainerbar", {
animationEnabled: true,
axisX: {
interval: 1,
labelFontSize: 10,
lineThickness: 0,
},
axisY2: {
valueFormatString: "0",
lineThickness: 0,
labelFontSize: 10,
},
toolTip: {
shared: true
},
legend: {
verticalAlign: "top",
horizontalAlign: "center",
fontSize: 10,
},
data: [{
type: "stackedBar",
showInLegend: true,
name: "Male",
axisYType: "secondary",
color: "#f8d347",
dataPoints: dpmale
},
{
type: "stackedBar",
showInLegend: true,
name: "Female",
axisYType: "secondary",
color: "#6ccac9",
dataPoints: dpfemale
}
]
});
chart.render();
}
});
</script>
URL : http://canvasjs.com/
I have been trying to make recurring events in fullcalendar, I really find dow feature helpful, but I really want to add date ranges to it.
In other words, dow : [1] will repeat a task for every single Monday, the problems is, I want to make it visible only in a date range I set.
You can not set ranges by using dow, you have to perform some custom functionality.
Lets suppose that you have fetched events data from your database which contains multiple event objects. each event object has start date end date property and also to and from properties which contains date range , isRecurring is a Boolean property which we will add true in case of recurring events otherwise it will be false.
Remember the recurring events take start and end time without date, you only need to give them time slots, like start = "16:00" and end = "20:00" You can extract time by using moment js like i did while initializing my event object
{
title:'Recurring Event',
start: moment.utc(event.start).format('HH:mm'),
end: moment.utc(event.end).format('HH:mm'),
isRecurrring: event.isRecurring,
ranges: [{
start: moment(event.from),
end: moment(event.to),
}],
}
I have used moment.utc() to ignore the timezone.
Now override the eventRender function while initializing your fullCalendar. Your eventRender function will be
eventRender: function(event, element, view){
if (event.isRecurrring) {
return (event.ranges.filter(function(range){
return (moment(event.start).isBefore(range.end) &&
moment(event.end).isAfter(range.start));
}).length) > 0;
}
}
You coulded set ranges as this example:
repeatingEvents.push({
title: "From: " + inputDateStart + " To: " + inputDateFinish,
start: vm.timeStart,
end: vm.timeFinish,
dow: listDay,
ranges: [{
start: dateStart,
end: dateFinish
}]
})
$("#calendar").fullCalendar("refetchEvents");
So you can use both "dow" and "ranges". Hope help for you!
function createCalendar() {
vm.uiConfig = timeProfileFactory.getCalendarConfig();
vm.uiConfig.calendar.eventClick = eventClick;
vm.uiConfig.calendar.eventDrop = alertOnDrop;
vm.uiConfig.calendar.eventResize = alertOnResize;
vm.uiConfig.calendar.eventRender = eventRender;
vm.uiConfig.calendar.select = selectSlot;
vm.uiConfig.calendar.header.center = "title";
vm.events = function(start, end, timezone, callback) {
callback(repeatingEvents);
}
vm.eventSources = [vm.events];
};
function selectSlot(start, end, jsEvent, view) {
var allDay = !start.hasTime() && !end.hasTime();
var offset = ((new Date()).getTimezoneOffset())/60;
var dateStart = (new Date(start)).setHours(0, 0, 0, 0);
dateStart = new Date(dateStart);
dateStart.setHours(dateStart.getHours() - offset);
dateStart = dateStart.toISOString();
var timeStart = (new Date(start)).toISOString();
var timeEnd = (new Date(end)).toISOString();
timeStart = timeStart.split('T')[0];
timeEnd = timeEnd.split('T')[0];
var length = repeatingEvents.length;
if(positionEvent == -1 || repeatingEvents.length == 0) {
positionEvent = 0;
} else {
positionEvent = repeatingEvents[length - 1].position + 1;
}
repeatingEvents.push({
title: "From: " + start.format("DD/MM/YYYY"),
start: start.format("HH:mm"),
end: end.format("HH:mm"),
dow: [new Date(start).getDay()],
ranges: [{
start: dateStart,
end: null
}],
position: positionEvent,
allDay: false
});
length++;
if(repeatingEvents[length - 1].end == "00:00") {
repeatingEvents[length - 1].end = "24:00";
}
if(allDay) {
repeatingEvents[length - 1].allDay = true;
repeatingEvents[length - 1].start = null;
repeatingEvents[length - 1].end = null;
}
$("#calendar").fullCalendar("refetchEvents");
};
function eventClick(event, date, jsEvent, view) {
isOpenDialog = true;
for(var i = 0; i < repeatingEvents.length; i++) {
if(repeatingEvents[i].position == event.position && isOpenDialog) {
selectIndex = i;
vm.timeStart = repeatingEvents[i].start;
vm.timeFinish = repeatingEvents[i].end;
vm.dateStart = repeatingEvents[i].title.split(' ')[1];
if(repeatingEvents[i].ranges[0].end == null) {
vm.dateFinish = "";
vm.radioValue = "never";
} else {
vm.dateFinish = repeatingEvents[i].title.split(' ')[3];
vm.radioValue = "on";
}
angular.forEach(vm.checkDays, function(item) {
item.checked = false;
});
angular.forEach(event.dow, function(index) {
vm.checkDays[index].checked = true;
})
openDialog();
break;
}
}
};
function alertOnResize(event, delta, revertFunc, jsEvent, ui, view) {
for(var i in repeatingEvents) {
if(repeatingEvents[i].position == event.position) {
var timeFinish = event.end.format("HH:mm");
if(timeFinish == "00:00") {
timeFinish = "24:00";
}
repeatingEvents[i].end = timeFinish;
break;
}
}
$("#calendar").fullCalendar("refetchEvents");
};
function alertOnDrop(event, delta, revertFunc, jsEvent, ui, view) {
for(var i in repeatingEvents) {
if(repeatingEvents[i].position == event.position) {
if(repeatingEvents[i].allDay || event.allDay) {
revertFunc();
} else {
var timeStart = event.start.format("HH:mm");
var timeFinish = event.end.format("HH:mm");
var dateStart = repeatingEvents[i].ranges[0].start;
var dateFinish = repeatingEvents[i].ranges[0].end;
var oldTimeStart = repeatingEvents[i].start.split(':')[0]*3600 + repeatingEvents[i].start.split(':')[1]*60;
var newTimeStart = timeStart.split(':')[0]*3600 + timeStart.split(':')[1]*60;
var deltaHour = newTimeStart - oldTimeStart;
var deltaDay = (delta/1000 - deltaHour)/86400;
dateStart = new Date(dateStart);
dateStart.setDate(dateStart.getDate() + deltaDay);
dateStart = dateStart.toISOString();
var title;
if(dateFinish != null) {
dateFinish = new Date(dateFinish);
dateFinish.setDate(dateFinish.getDate() + deltaDay);
dateFinish = dateFinish.toISOString();
title = "From: " + moment(dateStart).format("DD/MM/YYYY") + " To: " + moment(dateFinish).format("DD/MM/YYYY");
} else {
title = "From: " + moment(dateStart).format("DD/MM/YYYY");
}
for(var j in event.dow) {
repeatingEvents[i].dow[j] = parseInt(repeatingEvents[i].dow[j]) + deltaDay;
if(repeatingEvents[i].dow[j] > 6) {
repeatingEvents[i].dow.splice(j, 1);
}
}
repeatingEvents[i].start = timeStart;
repeatingEvents[i].end = timeFinish;
repeatingEvents[i].ranges[0].start = dateStart;
repeatingEvents[i].ranges[0].end = dateFinish;
repeatingEvents[i].title = title;
if(timeFinish == "00:00") {
repeatingEvents[i].end = "24:00";
}
$("#calendar").fullCalendar("refetchEvents");
}
break;
}
}
};
function eventRender(event, element, view) {
var removeEvent = $("<i class='removeEvent icons8-delete pull-right'></i>");
removeEvent.on("click", function() {
isOpenDialog = false;
vm.removeEvent(event);
});
element.find(".fc-content").prepend(removeEvent);
var result;
if(event.ranges[0].end == null) {
result = (event.ranges.filter(function(range) {
var startConvert = (new Date(event.start)).toISOString();
return (event.start.isAfter(range.start) || startConvert == range.start);
}).length) > 0;
} else {
result = (event.ranges.filter(function(range) {
return (event.start.isBefore(range.end) && event.end.isAfter(range.start));
}).length) > 0;
}
return result;
};
///<reference name="MicrosoftAjax.js"/>
Type.registerNamespace("AmpUI.Form");
AmpUI.Form.FBuilder = function (element) {
AmpUI.Form.FBuilder.initializeBase(this, [element]);
this._questions = null;
this._formID = null;
this._submitted = null;
this._facID = null;
this._formType = null;
this._autoSaveID = null;
this._typeName = null;
this._enableAutoSave = true;
this._autoSaveInterval = 30000;
this._template = null;
this._btnsave = null;
this._btnsubmit = null;
this._btnsavebottom = null;
this._btnsubmitbottom = null;
this._saveDelegate = null;
this._submitDelegate = null;
this._isautosave = null;
this._saveCallback = null;
this._submitCallback = null;
};
//define proto
AmpUI.Form.FBuilder.prototype = {
initialize: function () {
AmpUI.Form.FBuilder.callBaseMethod(this, "initialize");
//wire up save/submit events
if (this._submitted) {
this.GetResponses(this);
}
else {
//register the dependencies
Array.forEach(this.get_qrefs(), function (e, i, a) {
e.registerDepedency(a);
});
//start autosave
if (this._enableAutoSave && !this._submitted) {
this._autoSaveID = setInterval("$find('" + this._element.id + "').SaveForm(true);", this._autoSaveInterval);
}
if (this._saveDelegate === null) {
this._saveDelegate = Function.createDelegate(this, this.Save);
}
Sys.UI.DomEvent.addHandler($get(this._btnsave), 'click', this._saveDelegate);
Sys.UI.DomEvent.addHandler($get(this._btnsavebottom), 'click', this._saveDelegate);
if (this._submitDelegate === null) {
this._submitDelegate = Function.createDelegate(this, this.SubmitForm);
}
Sys.UI.DomEvent.addHandler($get(this._btnsubmit), 'click', this._submitDelegate);
Sys.UI.DomEvent.addHandler($get(this._btnsubmitbottom), 'click', this._submitDelegate);
}
this._template = "<div class='form_question'><span>{2}</span><div class='form_answer'>{3}</div></div>";
},
dispose: function () {
//init
AmpUI.Form.FBuilder.callBaseMethod(this, "dispose");
},
SaveForm: function (is_auto) {
this._isautosave = is_auto;
var questions = this.get_json();
var sa = new ampWeb.FormService();
sa.SaveFormQuestions(Sys.Serialization.JavaScriptSerializer.serialize(this.get_json()), false, this._typeName, this.onSuccess, this.onFail, this);
},
Save: function () {
this.SaveForm(false);
},
SubmitForm: function () {
var useValidation = true;
var valid = false;
try {
valid = Page_ClientValidate();
}
catch (e) {
useValidation = false;
}
if (valid || !useValidation) {
//stop autosave
clearInterval(this._autoSaveID);
autosaveEnabled = false;
var sa = new ampWeb.FormService();
sa.SaveFormQuestions(Sys.Serialization.JavaScriptSerializer.serialize(this.get_json()), true, this._typeName, this.onSubmitComplete, this.onFail, this);
} else {
$('#' + me._element.id + ' .fbuilder-result').html('Invalid responses were found. Please make all required corrections before submitting.');
}
},
onSuccess: function (s, me) {
$('#' + me._element.id + ' .fbuilder-result').fadeOut();
if (me._isautosave) {
var now = new Date();
$('#' + me._element.id + ' .fbuilder-result').html('Last autosave:' + now.format('hh:mm tt'));
} else {
$('#' + me._element.id + ' .fbuilder-result').html('Form has been saved.');
me._save();
if (me._saveCallback)
me._saveCallback.call(me);
}
$('#' + me._element.id + ' .fbuilder-result').fadeIn();
},
onFail: function (r, me) {
$('#' + me._element.id + ' .fbuilder-result').html(r.get_message());
//var s = new ampWeb.FormService();
//s.ReportAjaxError(r.get_message());
},
onSubmitComplete: function (r, me) {
$('#' + me._element.id + ' .fbuilder-result').html('Your responses have been submitted.');
$('#' + me._element.id).fadeOut('fast', function () {
$('#' + me._element.id).html('<h1>Thank you for submitting.</h1>');
clearInterval(me._autoSaveID);
me._submitted = true;
me.GetResponses(me);
if (me._submitCallback)
me._submitCallback.call(me);
});
},
GetResponses: function (me) {
var sa = new ampWeb.FormService();
sa.GetFormResponses(me._formID, me.WriteToForm, me.onFail, me);
},
WriteToForm: function (answers, me) {
var ar = Sys.Serialization.JavaScriptSerializer.deserialize(answers);
//recreate if missing
if ($('#' + me._element.id + ' #submitted').length == 0) { $('#' + me._element.id).append("<div id='submitted'/>"); }
Array.forEach(ar, function (a) {
$('#' + me._element.id + ' #submitted').append(String.format(me._template, null, null, a.question, a.response));
});
$('#' + me._element.id).fadeIn('fast');
me._submit();
},
resetInterval: function () {
if (this._enableAutoSave) {
clearInterval(this._autoSaveID);
this._autoSaveID = this._autoSaveID = setInterval("$find('" + this._element.id + "').SaveForm(true);", 30000);
}
},
get_questions: function () {
return Sys.Serialization.JavaScriptSerializer.serialize(this._questions);
},
set_questions: function (q) {
this._questions = Sys.Serialization.JavaScriptSerializer.deserialize(q);
},
get_qrefs: function () {
var a = new Array();
Array.forEach(this._questions, function (i) {
a.push($find(i));
});
return a;
},
get_json: function () {
var a = new Array();
Array.forEach(this._questions, function (i) {
a.push($find(i));
});
var b = new Array();
Array.forEach(a, function (i) {
b.push(i.get_json());
});
return b;
},
get_formID: function () {
return this._formID;
},
set_formID: function (value) {
this._formID = value;
},
get_submitted: function () {
return this._submitted;
},
set_submitted: function (value) {
this._submitted = value;
},
set_facID: function (value) {
this._facID = value;
},
get_facID: function () {
return this._facID;
},
set_formType: function (value) {
this._formType = value;
},
get_formType: function () {
return this._formType;
},
set_typeName: function (value) {
this._typeName = value;
},
get_typeName: function () {
return this._typeName;
},
set_enableAutoSave: function (value) {
this._enableAutoSave = value;
},
get_enableAutoSave: function () {
return this._enableAutoSave;
},
set_autoSaveInterval: function (value) {
if (!isNaN(value))
this._autoSaveInterval = value;
},
get_autoSaveInterval: function () {
return this._autoSaveInterval;
},
set_template: function (value) {
this._template = value;
},
get_template: function () {
return this._template;
},
set_btnsave: function (v) {
this._btnsave = v;
},
get_btnsave: function () {
return this._btnsave;
},
get_btnsubmit: function () {
return this._btnsubmit;
},
set_btnsubmit: function (v) {
this._btnsubmit = v;
},
set_btnsave: function (v) {
this._btnsave = v;
},
get_btnsavebottom: function () {
return this._btnsavebottom;
},
get_btnsubmitbottom: function () {
return this._btnsubmitbottom;
},
set_btnsubmitbottom: function (v) {
this._btnsubmitbottom = v;
},
set_btnsavebottom: function (v) {
this._btnsavebottom = v;
},
get_saveCallback: function () {
return this._saveCallback;
},
set_saveCallback: function (f) {
var fn = window[f];
if (fn && typeof (fn) === 'function')
this._saveCallback = fn;
},
get_submitCallback: function (f) {
return this._submitCallback;
},
set_submitCallback: function (f) {
var fn = window[f];
if (fn && typeof (fn) === 'function')
this._submitCallback = fn;
},
add_save: function (handler) {
this.get_events().addHandler("save", handler);
},
remove_save: function (handler) {
this.get_events().removeHandler("save", handler);
},
_save: function () {
var handler = this.get_events().getHandler("save");
if (handler) handler(this, Sys.EventArgs.Empty);
},
add_submit: function (handler) {
this.get_events().addHandler("submit", handler);
},
remove_submit: function (handler) {
this.get_events().removeHandler("submit", handler);
},
_submit: function () {
var handler = this.get_events().getHandler("submit");
if (handler) handler(this, Sys.EventArgs.Empty);
}
}
//register in the namespace
AmpUI.Form.FBuilder.registerClass("AmpUI.Form.FBuilder", Sys.UI.Control);
if (typeof (Sys) !== "undefined") Sys.Application.notifyScriptLoaded();
Is it special? for example, i never understand the addHandlder and removeHandler in the Javascript function and also WHAT IS registerNamespace AND WHAT IS Sys.Application.notifyScriptLoaded();?
Is it special? for example, i never understand the addHandlder and removeHandler in the Javascript function and also WHAT IS registerNamespace AND WHAT IS Sys.Application.notifyScriptLoaded();?