Special Javascript function in Asp.net? - asp.net

///<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();?

Related

How to draw a Curved line between two Points using Here Maps?

Need suggestions on how to add Curved Polyline using Here Maps Javascript API ?
There is no any straight way, but you can use following formula:
var D2R = Math.PI / 180;
var R2D = 180 / Math.PI;
var Coord = function(lon, lat) {
this.lon = lon;
this.lat = lat;
this.x = D2R * lon;
this.y = D2R * lat;
};
Coord.prototype.view = function() {
return String(this.lon).slice(0, 4) + ',' + String(this.lat).slice(0, 4);
};
Coord.prototype.antipode = function() {
var anti_lat = -1 * this.lat;
var anti_lon = (this.lon < 0) ? 180 + this.lon : (180 - this.lon) * -1;
return new Coord(anti_lon, anti_lat);
};
var LineString = function() {
this.coords = [];
this.length = 0;
};
LineString.prototype.move_to = function(coord) {
this.length++;
this.coords.push(coord);
};
var Arc = function(properties) {
this.properties = properties || {};
this.geometries = [];
};
Arc.prototype.json = function() {
if (this.geometries.length <= 0) {
return { 'geometry': { 'type': 'LineString', 'coordinates': null }, 'type': 'Feature', 'properties': this.properties };
} else if (this.geometries.length == 1) {
return { 'geometry': { 'type': 'LineString', 'coordinates': this.geometries[0].coords }, 'type': 'Feature', 'properties': this.properties };
} else {
var multiline = [];
for (var i = 0; i < this.geometries.length; i++) {
multiline.push(this.geometries[i].coords);
}
return { 'geometry': { 'type': 'MultiLineString', 'coordinates': multiline }, 'type': 'Feature', 'properties': this.properties };
}
};
Arc.prototype.strip = function() {
var s = H.geo.Strip ? new H.geo.Strip() : new H.geo.LineString();
for (var i = 0; i < this.geometries.length; i++) {
if (this.geometries[i].coords.lenght !== 0) {
var coords = this.geometries[i].coords;
for (var j = 0; j < coords.length; j++) {
var p = new H.geo.Point(coords[j][1], coords[j][0]);
s.pushPoint(p);
}
}
}
return s;
}
For detailed example, I have created a sample, please check - https://demo.support.here.com/examples/v3.1/geodesic_polyline

How to Autolink the url in Trix Editor

When we paste the content in trix-editor the href not getting paste as simple text. How can we make it as a link.
var TrixAutoLinker,
bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
addEventListener("trix-initialize", function(event) {
return new TrixAutoLinker(event.target);
});
TrixAutoLinker = (function() {
var INPUT, PATTERN, isValidURL;
function TrixAutoLinker(element) {
this.element = element;
this.autoLink = bind(this.autoLink, this);
this.editor = this.element.editor;
this.element.addEventListener("trix-render", this.autoLink);
this.autoLink();
}
TrixAutoLinker.prototype.autoLink = function() {
var currentRange, i, len, range, ref, ref1, results1, url;
ref = this.getURLsWithRanges();
results1 = [];
for (i = 0, len = ref.length; i < len; i++) {
ref1 = ref[i], url = ref1.url, range = ref1.range;
if (this.getHrefAtRange(range) !== url) {
currentRange = this.editor.getSelectedRange();
this.editor.setSelectedRange(range);
if (this.editor.canActivateAttribute("href")) {
this.editor.activateAttribute("href", url);
}
results1.push(this.editor.setSelectedRange(currentRange));
} else {
results1.push(void 0);
}
}
return results1;
};
TrixAutoLinker.prototype.getDocument = function() {
return this.editor.getDocument();
};
TrixAutoLinker.prototype.getDocumentString = function() {
return this.getDocument().toString();
};
TrixAutoLinker.prototype.getHrefAtRange = function(range) {
return this.getDocument().getCommonAttributesAtRange(range).href;
};
PATTERN = /(https?:\/\/\S+\.\S+)\s/ig;
TrixAutoLinker.prototype.getURLsWithRanges = function() {
var match, position, range, results, string, url;
results = [];
string = this.getDocumentString();
while (match = PATTERN.exec(string)) {
url = match[1];
if (isValidURL(url)) {
position = match.index;
range = [position, position + url.length];
results.push({
url: url,
range: range
});
}
}
return results;
};
INPUT = document.createElement("input");
INPUT.type = "url";
INPUT.required = true;
isValidURL = function(value) {
INPUT.value = value;
return INPUT.checkValidity();
};
return TrixAutoLinker;
})();
// ---
// generated by coffee-script 1.9.2

how to show monthly repeated events in full calender plugin

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);
},
});

Fullcalendar recurring events limits (using dow)

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;
};

Changing Marker Icons while using MarkerClusterer (Works in IE9 and Chrome, Doesn't Work in Firefox or earlier IE versions)

I have a public-facing site using GoogleMaps API v3 and the MarkerClusterer library. The page that is having a problem can be found here (http://www.mihomes.com/Find-Your-New-Home/San-Antonio-Homes). If you view this page in IE9 or Chrome, the correct pin icon images are shown, while in previous IE versions and Firefox different (and incorrect) pin icons.
IE9
Firefox 3.6.8
Here is the JavaScript code that generates the pins/clustering:
$(function() {
var dl_grid = new DLGrid(".GMapGrid");
dl_grid.init();
var dl_map = new DLMap("#map");
dl_map.init();
var markers = dl_grid.CollectMarkerData();
dl_map.LoadMarkers(markers);
});
var DLIcons = new function() {
var me = this;
me.NormalIcon = "/images/GoogleMapsIcons/mi_icon_n.png";
me.HoverIcon = "/images/GoogleMapsIcons/new_mi_icon_r.png";
me.ClusterIcon = "/images/GoogleMapsIcons/mi_icon_n.png";
me.ClusterHoverIcon = "/images/GoogleMapsIcons/new_mi_icon_r.png";
me.SalesCenterIcon = "/images/GoogleMapsIcons/new_mi_icon_n2.gif";
me.DesignCenterIcon = "/images/GoogleMapsIcons/mi_dc_n.png";
me.DesignCenterHoverIcon = "/images/GoogleMapsIcons/mi_dc_r.png";
};
//Used for all functions relating to the table below the map
var DLGrid = function(grid_selector) {
//Initialize variables
var me = this;
me.grid = $(grid_selector);
//Initialize
me.init = function() {
setupTableSorting();
setupHoverEvents();
setupZoomButtons();
};
//Setup the table sorting
var setupTableSorting = function() {
//Init tablesorter plugin
var sort_options = { headers: { 0: { sorter: false }, 4: { sorter: false} } };
if (MI_DIVISION_LANDING_TABLE_SORT_OPTIONS != undefined) {
sort_options = MI_DIVISION_LANDING_TABLE_SORT_OPTIONS;
}
me.grid.tablesorter(sort_options);
//As soon as the user sorts, remove all Community Groups
me.grid.bind("sortEnd", function() {
me.grid.find("tr.communityGroup").remove();
$("tr.groupedCommunity").removeClass("groupedCommunity").addClass("ungroupedCommunity");
//$("tr.ungroupedCommunity").removeClass("ungroupedCommunity");
me.grid.trigger("update");
});
};
var highlightRow = function(marker) {
var markerId = (typeof (marker) == "string") ? marker : marker.jsonData.MarkerID;
$(me.grid).find("#" + markerId).addClass("highlightedRow");
};
// Bind to mouseover/mouseout events and highlight the proper row in the table
// Trigger mouseover/mouseout events when you hover over a row in the table
var setupHoverEvents = function() {
$(document).bind("MARKER_MOUSEOVER", function(e, marker) {
$(me.grid).find("tbody tr.highlightedRow").removeClass("highlightedRow");
if (typeof (marker) != "string" && marker.length != undefined) {
for (var i = 0; i < marker.length; i++) {
highlightRow(marker[i]);
}
}
else {
highlightRow(marker);
}
});
// $(document).bind("MULTIPLE_MARKER_MOUSEOVER", function(e, markers) {
// $(me.grid).find("tbody tr.highlightedRow").removeClass("highlightedRow");
// for (var i = 0; i < markers.length; i++) {
// var markerId = (typeof (markers[i]) == "string") ? markers[i] : markers[i].jsonData.MarkerID;
// $(me.grid).find("#" + markerId).addClass("highlightedRow");
// }
// });
$(me.grid).find("tbody tr").mouseover(function() {
$(document).trigger("MARKER_MOUSEOVER", [$(this).attr("id")]);
});
};
// The zoom buttons next to each row should zoom to a marker and show it's info window
var setupZoomButtons = function() {
$(me.grid).find("tbody tr .zoom_link img").click(function() {
$(document).trigger("MAP_SHOW_MARKER_POPUP_AND_ZOOM", [$(this).parent().parent().attr("id")]);
});
};
// Collect and parse the JSON data from the hidden 'data' column in the table
me.CollectMarkerData = function() {
var markers = [];
$.each(me.grid.find("tbody tr:not(.communityGroup)"), function(i, row) {
var dataCell = $(row).children("td.data");
var rawContent = $(dataCell).text();
var json_data = {};
if (rawContent.length > 0) {
json_data = JSON.parse(rawContent);
}
json_data["MarkerID"] = $(row).attr("id");
markers.push(json_data);
});
return markers;
};
};
//Used for all functions relating to map
var DLMap = function(map_div_selector) {
//Initialize variables
var me = this;
me.mapDivSelector = map_div_selector;
me.mapObj;
me.init = function() {
setupMap();
bindHoverEvents();
setupPopupEvents();
setupDesignCenter();
};
//Basic setup of map
var setupMap = function() {
me.mapObj = new DLGoogleMap(me.mapDivSelector);
me.mapObj.init(onMarkerMouseOver, showMarkerPopup);
};
// Add an array of markers (from json data) to the map
me.LoadMarkers = function(markers) {
$.each(markers, function(i, json_marker) {
me.mapObj.addMarker(json_marker);
});
me.mapObj.fitMapToMarkers();
};
var showMarkerPopup = function(markerJson, zoomToLocation) {
var source = $("#MapMarkerInfoWindow").html();
var template = Handlebars.compile(source);
var content = template(markerJson);
var triggerKey = (zoomToLocation == true) ? "MAP_SHOW_POPUP_AND_ZOOM" : "MAP_SHOW_POPUP";
$(document).trigger(triggerKey, [content, markerJson.Lat, markerJson.Lng]);
};
var onMarkerMouseOver = function(markerJson) {
$(document).trigger("MARKER_MOUSEOVER", markerJson);
}
// Highlight (or unhighlight) a marker when a mouseover/mouseout event is triggered
var bindHoverEvents = function() {
$(document).bind("MARKER_MOUSEOVER", function(e, marker) {
if (typeof (marker) != "string" && marker.length != undefined) {
marker = marker[0];
}
me.mapObj.resetMarkerHighlighting();
me.mapObj.highlightMarker(marker);
});
// $(document).bind("MULTIPLE_MARKER_MOUSEOVER", function(e, markers) {
// me.mapObj.resetMarkerHighlighting();
// if (markers[0].cluster != null) {
// me.mapObj.highlightCluster(markers[0]
// }
// });
};
var setupPopupEvents = function() {
$(document).bind("MAP_SHOW_POPUP", function(e, content, lat, lng) {
me.mapObj.showPopup(content, lat, lng);
});
$(document).bind("MAP_SHOW_POPUP_AND_ZOOM", function(e, content, lat, lng) {
me.mapObj.showPopup(content, lat, lng, true);
});
$(document).bind("MAP_SHOW_MARKER_POPUP", function(e, marker) {
if (typeof (marker) == "string") {
marker = me.mapObj.findMarkerByID(marker);
}
showMarkerPopup(marker.jsonData);
});
$(document).bind("MAP_SHOW_MARKER_POPUP_AND_ZOOM", function(e, marker) {
if (typeof (marker) == "string") {
marker = me.mapObj.findMarkerByID(marker);
}
showMarkerPopup(marker.jsonData, true);
});
};
var setupDesignCenter = function() {
var jsonText = $.trim($("#DesignCenterData").text());
if (jsonText.length > 5) {
var dcJson = JSON.parse(jsonText);
me.mapObj.addDesignCenterMarker(dcJson);
}
};
};
var DLGoogleMap = function(map_div_selector) {
//Initialize variables
var me = this;
me.mapDiv = $(map_div_selector);
me.gmap;
me.markers = [];
me.markerClusterer;
me.infoWindow;
me.onMouseOver;
me.onClick;
me.ZOOM_TO_LEVEL = 14;
me.highlightedMarkers = [];
me.designCenterMarker = null;
//Extend Google Map Classes
google.maps.Marker.prototype.jsonData = null;
google.maps.Marker.prototype.iconImg = null;
google.maps.Marker.prototype.iconHoverImg = null;
me.init = function(onMouseOver, onClick) {
me.onMouseOver = onMouseOver;
me.onClick = onClick;
setupMap();
setupClustering();
setupDrivingDirectionLinks();
};
var setupMap = function() {
//var latlng = new google.maps.LatLng(40.05, -82.95);
var myOptions = {
zoom: 14,
scrollwheel: false,
mapTypeId: google.maps.MapTypeId.TERRAIN
};
me.gmap = new google.maps.Map(document.getElementById("map"), myOptions);
me.infoWindow = new google.maps.InfoWindow();
};
var setupDrivingDirectionLinks = function() {
$("a.gDirectionsLink").live("click", function(e) {
e.preventDefault();
$(".gPopupInfo").hide();
$(".gDrivingDirections").show();
});
$("a.gCloseDrivingDirections").live("click", function(e) {
e.preventDefault();
$(".gDrivingDirections").hide();
$(".gPopupInfo").show();
});
};
//Add a single json marker to the map
me.addMarker = function(jsonMarker) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(jsonMarker.Lat, jsonMarker.Lng),
title: jsonMarker.Name
});
marker.jsonData = jsonMarker;
if (jsonMarker.HasSalesCenter == "True") {
marker.iconImg = DLIcons.SalesCenterIcon;
}
else {
marker.iconImg = DLIcons.NormalIcon;
}
marker.iconHoverImg = DLIcons.HoverIcon;
marker.icon = marker.iconImg;
google.maps.event.addListener(marker, 'click', function() {
me.onClick(marker.jsonData);
});
google.maps.event.addListener(marker, 'mouseover', function() { me.onMouseOver(marker) });
me.markerClusterer.addMarker(marker);
me.markers.push(marker);
};
//Add an arbitrary marker
me.addDesignCenterMarker = function(dcJson) {
me.designCenterMarker = new google.maps.Marker({
position: new google.maps.LatLng(dcJson.Lat, dcJson.Lng),
title: "Design Center",
map: me.gmap
});
me.designCenterMarker.jsonData = dcJson;
me.designCenterMarker.iconImg = DLIcons.DesignCenterIcon;
me.designCenterMarker.iconHoverImg = DLIcons.DesignCenterHoverIcon;
me.designCenterMarker.icon = me.designCenterMarker.iconImg;
google.maps.event.addListener(me.designCenterMarker, 'mouseover', function() {
me.highlightMarker(me.designCenterMarker);
});
google.maps.event.addListener(me.designCenterMarker, 'mouseout', function() {
me.unHighlightMarker(me.designCenterMarker);
});
google.maps.event.addListener(me.designCenterMarker, 'click', function() {
me.infoWindow.close();
var source = $("#DesignCenterInfoWindow").html();
var template = Handlebars.compile(source);
var content = template(me.designCenterMarker.jsonData);
me.showPopup(content, me.designCenterMarker.jsonData.Lat, me.designCenterMarker.jsonData.Lng);
});
};
me.resetMarkerHighlighting = function() {
for (var i = 0; i < me.highlightedMarkers.length; i++) {
me.unHighlightMarker(me.highlightedMarkers[i]);
}
me.highlightedMarkers = [];
}
me.highlightMarker = function(m) {
var marker = (typeof (m) == "string") ? me.findMarkerByID(m) : m;
if (marker != null) {
if (marker.cluster == null || (marker.cluster.hasMultipleMarkers() == false)) {
marker.setIcon(marker.iconHoverImg);
}
else {
highlightCluster(marker.cluster);
}
me.highlightedMarkers.push(marker);
}
};
me.unHighlightMarker = function(m) {
var marker = (typeof (m) == "string") ? me.findMarkerByID(m) : m;
if (marker != null) {
if (marker.cluster == null || (marker.cluster.hasMultipleMarkers() == false)) {
marker.setIcon(marker.iconImg);
}
else {
unHighlightCluster(marker.cluster);
}
}
};
me.zoomAndShowPopup = function(content, lat, lng) {
};
me.showPopup = function(content, lat, lng, zoomToLocation) {
if (zoomToLocation == true) {
var adjustedLat = lat - (me.gmap.getZoom() * 0.01);
me.zoomToLocation(adjustedLat, lng);
}
me.infoWindow.setContent(content);
me.infoWindow.setPosition(new google.maps.LatLng(lat, lng));
me.infoWindow.open(me.gmap);
};
me.zoomToLocation = function(lat, lng) {
me.gmap.setZoom(me.ZOOM_TO_LEVEL)
me.gmap.setCenter(new google.maps.LatLng(lat, lng));
};
me.fitMapToMarkers = function() {
me.markerClusterer.fitMapToMarkers();
};
//Setup the map 'clustering', so that nearby markers will cluster together to form 1 icon
var setupClustering = function() {
Cluster.prototype.iconImg = DLIcons.ClusterIcon;
Cluster.prototype.iconHoverImg = DLIcons.ClusterHoverIcon;
var mc_options = {
gridSize: 15,
maxZoom: 15,
zoomOnClick: false,
styles: [{ url: DLIcons.ClusterIcon, height: 30, width: 20, textColor: "#fff", textSize: 10}],
showMarkerCount: false,
onClusterAdded: onClusterAdded
};
me.markerClusterer = new MarkerClusterer(me.gmap, [], mc_options);
//Setup Cluster Info Windows with a list of marker links
google.maps.event.addListener(me.markerClusterer, 'clusterclick', function(cluster) {
me.infoWindow.close();
var source = $("#MapClusterInfoWindow").html();
var template = Handlebars.compile(source);
var markers = getClusterJsonMarkers(cluster);
var data = {
markers: markers
};
var content = template(data);
$(document).trigger("MAP_SHOW_POPUP", [content, cluster.getCenter().lat(), cluster.getCenter().lng()]);
});
//Setup Cluster marker highlighting
google.maps.event.addListener(me.markerClusterer, 'clustermouseover', function(cluster) {
me.resetMarkerHighlighting();
highlightCluster(cluster);
var cmarkers = cluster.getMarkers();
$(document).trigger("MARKER_MOUSEOVER", [cmarkers]);
});
$(".openMarkerPopup").live("click", function(e) {
e.preventDefault();
$(document).trigger("MAP_SHOW_MARKER_POPUP", [$(this).attr("rel")]);
});
};
var onClusterAdded = function(cluster) {
if (clusterHasSalesCenter(cluster)) {
cluster.iconImg = DLIcons.SalesCenterIcon;
cluster.updateIconUrl(cluster.iconImg);
}
else {
cluster.iconImg = DLIcons.ClusterIcon;
}
};
var clusterHasSalesCenter = function(cluster) {
if ((cluster == undefined) || (cluster.markers_ == undefined)) {
return false;
}
for (var i = 0; i < cluster.markers_.length; i++) {
if (cluster.markers_[i].jsonData.HasSalesCenter == "True") {
return true;
}
}
return false;
};
var highlightCluster = function(cluster) {
//me.highlightedMarkers = [];
// for (var i = 0; i < cluster.markers_.length; i++) {
// me.highlightedMarkers.push(cluster.markers_[i]);
// }
cluster.updateIconUrl(cluster.iconHoverImg);
};
var unHighlightCluster = function(cluster) {
cluster.updateIconUrl(cluster.iconImg);
};
var getClusterJsonMarkers = function(cluster) {
var jsonMarkers = [];
var gmarkers = cluster.getMarkers();
for (var i = 0; i < gmarkers.length; i++) {
jsonMarkers.push(gmarkers[i].jsonData);
}
return jsonMarkers;
};
// Get a marker on the map given it's MarkerID
me.findMarkerByID = function(markerId) {
for (var i = 0; i < me.markers.length; i++) {
if (me.markers[i].jsonData.MarkerID == markerId) {
return me.markers[i];
break;
}
}
return null;
};
};
This website is built using .NET Framework 3.5 and ASP.NET WebForms.
Thanks for the assistance.

Resources