var g_rpt_master_id; var g_cw_id; var gInitSerialize; var gPHPSESSID = "?PHPSESSID=" + 'ln5avvr9ntmkcjsvkr6tkrh7e3'; //var gtzoffsetnodst = ""; // Not used? remove? var gbanners_on = ""; var gCalendar; var gLoggedIn; var gCanAdd; var gIsAdmin; var gIsManager; var gData; var cw_jsonStatus; var ajaxActive = false; var monthEvents; var gCameFromMonth = true; var gCameFromDetail = false; var gDestinationScreen; var jPleaseWait; var jEmailBodyDIV; var jRemindBodyDIV; var gNoPublicCats = false; var setpassword = false; var last_saved_location_id = 0; var btnclicked = 'none'; // Used to detect button mousedown event when blur event preceeds click var fieldsToPopulate = {"edittype":"input", "approved":"input", "rpt_last_flag":"input", "reminder_id":"input", "repeat_id":"input", "event_id":"input", "calendar_id":"input", "actiontype":"input", "imported":"input", "create_user_id":"input", "edit_user_id":"input", "editfrom":"input", "draft":"input", "old_draft":"input", "occ_changed":"input", "old_occ_changed":"input", "createtimestamp":"input", "title":"input", "allday":"checkbox", "noend":"checkbox", "rpt_sun":"checkbox", "rpt_mon":"checkbox", "rpt_tue":"checkbox", "rpt_wed":"checkbox", "rpt_thu":"checkbox", "rpt_fri":"checkbox", "rpt_sat":"checkbox", "rpt_noenddate":"checkbox", "description":"textarea", "login_email":"span", "category_id":"select", "location_id":"select", "location_name":"input", "location_street":"input", "location_city":"input", "location_stateprovince":"input", "location_zippostal":"input", "location_country":"input", "emonth":"select", "eday":"select", "eyear":"select", "starthour":"select", "startminute":"select", "startampm":"select", "endhour":"select", "endminute":"select", "endampm":"select", "priortime":"select", "rpt_type":"select", "rpt_days":"select", "rpt_weeks":"select", "rpt_month_place":"select", "rpt_end_month":"select", "rpt_end_day":"select", "rpt_end_year":"select"}; var cal; var touchCapable = false; //##################################### Initialization ################################################ function init(){ if(window.location.href.match(/crd=([^&#]+)/i)){ gCalendar = RegExp.$1; } if ('ontouchstart' in document.documentElement){ touchCapable = true; } if(touchCapable){ $("body").touchwipe({ wipeLeft: function() { swipeHandler("next"); }, wipeRight: function() { swipeHandler("prev"); }, preventDefaultEvents: false }); $("#edit").touchwipe({ wipeUp: function() { formfocus(); }, wipeDown: function() { formfocus(); }, preventDefaultEvents: false }); } $("#nextday").bind("click", navDay); $("#prevday").bind("click", navDay); $("#eventstemplate").bind("click", displayEvent); $("#loginlink").bind("click", logInOut); $("#logoutlink").bind("click", logInOut); $(".todaylink").bind("click", goToToday); $("a.addlink").bind("click", addEvent); $("#editlink").bind("click", editEvent); $("#rpt_type").change(docontrols); $("#openNewEmail").click(openNewEmail); $("#getReminder").click(getReminder); $("#downloadEvent").click(downloadEvent); jDetailBodyDIV = $("#event"); // **************************************************************** // Try logging in with cookies // **************************************************************** // Get possible user cookies var usernameold = readCookie("cwUsername"); // Legacy cookie var usernamenew = readCookie("cw_user"); // Transitional single calendar cookie var calendar_specific_cookie_name = "cw_auth_" + $("#calendar_id").val(); var usernamemulticalcookie = readCookie(calendar_specific_cookie_name); // New multi-calendar cookie if ((usernameold) || (usernamenew) || (usernamemulticalcookie)) { // For new cookies loginCookies(initMonthlyDisplay); } else { initMonthlyDisplay(); } jPleaseWait = $("#pleasewait"); gTimeoutHandle = window.setTimeout(refresh, timeoutMilliseconds); jEmailBodyDIV = createEmailDIV(); $("body").append(jEmailBodyDIV.hide()); jRemindBodyDIV = createRemindDIV(); $("body").append(jRemindBodyDIV.hide()); //alert(navigator.userAgent); // Conditional setup of html editor if (usehtmled) { if (typeof tinyMCE == 'undefined') { // Send event to Google Anaytics for tracking that tinymce did not load // This may be that cdn failed or blocked by firewall //_gaq.push(['_trackEvent', 'editor_mobile_tinymce_notloaded', gCalendar]); } else { // Description editor - NOTE: EITHER SETUP OR ONINIT CAN GO AWAY tinyMCE.init({ selector: "#description", theme: "modern", width: "100%", height: 175, relative_urls : false, remove_script_host : false, forced_root_block: false, browser_spellcheck : true, menubar: "", toolbar: "bold italic | alignleft aligncenter alignright | bullist numlist", autofocus: false }); } } // Click on title sets focus on title $('#title').bind('click', function(event) { if (event.target.id == 'title') { //alert('titlefocus'); $("#edit").focus(); $("#title").focus(); } return true; }); /* KEEP THIS CODE FOR POSSIBLE FUTURE USE // Custom code for crd = wawi to prevent adds and edits. // Should be removed when mobile supports conflict prevention // Also see other usage of global addeditdisable line 343 if (gCalendar == 'wawi') { $(".addlink").remove(); $(".editlink").remove(); addeditdisable = 1; } else { addeditdisable = 0; } */ // Related to above commented out code. Keeping here for possible future developments addeditdisable = 0; // ---------------------------- // HIDE / SHOW LOCATION DETAILS // ---------------------------- // Initial state of elements //$("#hide_show_text").text("Show location details"); $("#hide_show_arrow").removeClass("fa fa-arrow-up").addClass("fa fa-arrow-down"); // So they don't have to keep opening more details each time when // adding multiple users at a time. if ($.cookie("locationdetails") == "visible") { //$("#hide_show_text").text("Hide location details"); //$("#hide_show_arrow").removeClass("fa fa-arrow-down").addClass("fa fa-arrow-up"); //$("#locdetail_down_arrow").hide(); //$("#locdetail_up_arrow").show(); $("#locationdetails").show(); $("#location_details_show").hide(); $("#location_details_hide").css("display","inline-block"); } // Event handler for showing/hiding additional user options $("#location_details_control").on("click", function(event) { if ($("#locationdetails").is(':visible')) { $("#locationdetails").hide(); //$("#location_details_hide").hide(); //$("#location_details_show").show(); $("#location_details_hide").hide(); $("#location_details_show").css("display","inline-block"); $.cookie("locationdetails", "hidden"); //alert('hide'); } else { $("#locationdetails").show(); $("#location_details_show").hide(); $("#location_details_hide").css("display","inline-block"); $.cookie("locationdetails", "visible"); //alert("show"); } event.stopPropagation(); }); // Event handler for location fild focus $(".locationfield").on("focus", function(event) { btnclicked = 'none'; }); // Event handler for location fild change $(".locationfield").on("change", function(event) { locchange(); }); // ---------------------------- // HIDE / SHOW END DATE // ---------------------------- // Initial state of elements $("#hide_show_arrow").removeClass("fa fa-arrow-up").addClass("fa fa-arrow-down"); // So they don't have to keep opening more details each time when // adding multiple users at a time. if ($.cookie("end_date_div") == "visible") { $("#end_date_div").show(); $("#end_date_show").hide(); $("#end_date_hide").css("display","inline-block"); } // Event handler for showing/hiding end date $("#end_date_control").on("click", function(event) { if ($("#end_date_div").is(':visible')) { $("#end_date_div").hide(); $("#end_date_hide").hide(); $("#end_date_show").css("display","inline-block"); $.cookie("end_date_div", "hidden"); } else { $("#end_date_div").show(); $("#end_date_show").hide(); $("#end_date_hide").css("display","inline-block"); $.cookie("end_date_div", "visible"); } event.stopPropagation(); }); } function swipeHandler(direction){ if($("#calendar").is(":visible")){ cal.navMonth(direction); } else if($("#day").is(":visible")){ navDay(direction); } } //########################## Month Display ##################################### function initMonthlyDisplay(data, result){ if(data){ commonAjaxCallback(data, result); } cal = new cwCal($("#calendar")[0], disabledDates, selectedDate, clearCache, "pleasewait"); cal.render(); } function getMonthEvents(calendar, pDate){ //alert(pDate); var date = new Date(pDate); clearCache(); ajaxActive = true; date.setDate(1); date.setDate(1 - date.getDay()); var month = (date.getMonth() + 1); var year = date.getFullYear(); var day = date.getDate(); date.setDate(date.getDate() + 42); var emonth = (date.getMonth() + 1); var eyear = date.getFullYear(); var eday = date.getDate(); // Categories filter if (typeof cidarray != "undefined") { var catlist = ''; for (var i = 0; i < cidarray.length; i++) { catlist += '&cid[]=' + cidarray[i]; } } else { var catlist = ''; } // Locations filter if (typeof lidarray != "undefined") { var loclist = ''; for (var i = 0; i < lidarray.length; i++) { loclist += '&lid[]=' + lidarray[i]; } } else { var loclist = ''; } $.getJSON("/cwapi.php" + gPHPSESSID + catlist + loclist, {fmt:"json", view:"n", bd:day, bm:month, by:year, ed:eday, em:emonth, ey:eyear, crd:calendar}, monthCallback, "json") .done(function() { //console.log( "getMonthEvents success" ); }) .fail(function() { //console.log( "getMonthEvents error" ); }); } function monthCallback(data, result){ if(!commonAjaxCallback(data, result)){ return; } monthEvents = new Object(); if(data.status.code == 200){ //here we need to load the dates into the monthEvents object for(var i = 0; i < data.dateswithevents.length; i++){ var cw_event = data.dateswithevents[i] if(cw_event.month.length == 1){ cw_event.month = "0" + cw_event.month; } if(cw_event.day.length == 1){ cw_event.day = "0" + cw_event.day; } monthEvents[parseInt(cw_event.year + cw_event.month + cw_event.day)] = cw_event; } }else{ if(data.status.code == 999){ alert(data.status.msg); return; } if(data.status.code != 204){ document.write(data.status.msg + "\n" + data.status.code); return; } } cal.render(cal.date, true); } function clearCache(){ monthEvents = undefined; } //################################## Day Display ################################## function getDayEvents(calendar, date){ gCameFromDetail = false; ajaxActive = true; cal.date = date; gCameFromMonth = false; var month = (date.getMonth() + 1); var year = date.getFullYear(); var day = date.getDate(); $("#navTodayAddLogInOut").hide(); // Categories filter if (typeof cidarray != "undefined") { var catlist = ''; for (var i = 0; i < cidarray.length; i++) { catlist += '&cid[]=' + cidarray[i]; } } else { var catlist = ''; } // Locations filter if (typeof lidarray != "undefined") { var loclist = ''; for (var i = 0; i < lidarray.length; i++) { loclist += '&lid[]=' + lidarray[i]; } } else { var loclist = ''; } $.getJSON("/cwapi.php" + gPHPSESSID + catlist + loclist, {fmt:"json", view:"s", bd:day, bm:month, by:year, ed:day, em:month, ey:year, crd:calendar}, dayCallback, "json") .done(function() { //console.log( "getDayEvents success" ); }) .fail(function() { //console.log( "getDayEvents error" ); }); } function dayCallback(data, result){ $("#eventdetailsarrow").show(); commonAjaxCallback(data, result); if(data.status.code == 200 || data.status.code == 204){ $(".dayeventsA, .dayeventsB").remove(); //emptying out the event list jPleaseWait.hide(); // Do not show add button if show busy set and not logged in if ((nolognavbar) || ((calshowbusy) && (!gLoggedIn))) { $("#day #a1").css({"display":"none"}); } else { $("#day #a1").css({"display":"inline"}); } $("#day").show(); $(".date").text(cal.date.format("ddd, mmm d, yyyy")); if(data.status.code == 204){ // Nothing to drill into so hide the arrow $("#eventdetailsarrow").hide(); var jEventDiv = $("#eventstemplate").clone(true).insertAfter("#eventstemplate").eq(0); jEventDiv.find(".title").text("No events for this day.") .css("text-align","center") .css("font-size","1.5em") .css("color","#aaa") .css("margin","100px 0"); jEventDiv.attr("class", "dayeventsA"); jEventDiv.show(); } else{ for(var i = data.eventsummaries.length - 1; i >= 0; i--){ var cw_event = data.eventsummaries[i]; jEventDiv = $("#eventstemplate").clone(true).insertAfter("#eventstemplate").eq(0); // Note: Test on addeditdisable added to shut off add/edit, see custom code for crd=wawi line 185 if ((cw_event.canedit) && (!addeditdisable)) { jEventDiv.find("#eventdetails").css("margin", "15px 15px 15px 70px "); var editLink = jEventDiv.find("#editlink"); if(cw_event.draft){ editLink.text("Edit Draft"); jEventDiv.find("#eventdetails").css("margin", "15px 15px 15px 100px "); } editLink.show(); } jEventDiv.attr("cw_id", cw_event.event_id); //alternating lighter and darker rows if(i % 2){ var dayClassName = "dayeventsB"; } else{ dayClassName = "dayeventsA"; } jEventDiv.attr("class", dayClassName); jEventDiv.attr("repeat_id", cw_event.repeat_id); jEventDiv.show(); jEventDiv.find(".title").text(cw_event.title); jEventDiv.find(".category_name").text(cw_event.category_name); if(cw_event.location_name){ jEventDiv.find(".location").text(data.settings.location_prefix + " " + cw_event.location_name); } else{ jEventDiv.find(".location").text(""); } // Event date(s) if (cw_event["isbanner"]) { cal.banner_beg_date = new Date(parseInt(cw_event["event_year"]), parseInt(cw_event["event_month"])-1, parseInt(cw_event["event_day"])); // end date obj cal.banner_end_date = new Date(parseInt(cw_event["end_event_year"]), parseInt(cw_event["end_event_month"])-1, parseInt(cw_event["end_event_day"])); // end date obj if (cal.date.getFullYear() == cal.banner_beg_date.getFullYear()) { var bandatetimestr = cal.banner_beg_date.format("ddd, mmm d"); } else { var bandatetimestr = cal.banner_beg_date.format("ddd, mmm d, yyyy"); } if (data.settings.military == '1') { var timeformatstr = "UTC:HH:MM"; } else { var timeformatstr = "UTC:h:MMtt"; } if (!cw_event["allday"]) { bandatetimestr += " | " + dateFormat(tsToDate(cw_event, "start_timestamp_gmt", "start_tzoffset"), timeformatstr); } if (cal.date.getFullYear() == cal.banner_end_date.getFullYear()) { bandatetimestr += ' - ' + cal.banner_end_date.format("ddd, mmm d"); } else { bandatetimestr += ' - ' + cal.banner_end_date.format("ddd, mmm d, yyyy"); } if ((!cw_event["noend"]) && (!cw_event["allday"])) { bandatetimestr += " | " + dateFormat(tsToDate(cw_event, "end_timestamp_gmt", "end_tzoffset"), timeformatstr); } else if (!cw_event["allday"]) { //bandatetimestr += " no end time "; } else { //bandatetimestr += " all day "; } jEventDiv.find(".startendtime").text(bandatetimestr); } else { displayStartEndTime(jEventDiv, cw_event, data.settings); } } } } else { if(data.status.code == 999){ alert(data.status.msg); return; } document.write(data.status.msg + "\n" + data.status.code); cal.render(cal.date); jPleaseWait.hide(); $(cal.grid).show(); } } function navDay(e){ jPleaseWait.show(); if(typeof(e) == "string") { var direction = e; } else { direction = e.target.id; } if(direction.match(/next/i)){ cal.date.setDate(cal.date.getDate() + 1); } else { cal.date.setDate(cal.date.getDate() - 1) } getDayEvents(gCalendar, cal.date); } function dayDone(){ $("#day").hide(); // Do not show add button if show busy set and not logged in if ((calshowbusy) && (!gLoggedIn)) { $("#navTodayAddLogInOut #a1").css({"display":"none"}); } else { $("#navTodayAddLogInOut #a1").css({"display":"inline"}); } if (!nolognavbar) { $("#navTodayAddLogInOut").show(); } cal.render(cal.date); $(cal.grid).show(); } //######################### Event Display ############################### function displayEvent(e){ gCameFromDetail = true; if(typeof(e) == "string"){ $("#edit").hide(); } else { //need to check to make sure that an event was clicked on var cw_id = $(e.target).closest("[cw_id]").attr("cw_id"); if(cw_id){ g_cw_id = cw_id; } else { return; } g_rpt_master_id = $(e.target).closest("[repeat_id]").attr("repeat_id"); $("#day").hide(); } jPleaseWait.show(); getEvent(gCalendar, g_cw_id, g_rpt_master_id, eventCallback, ""); } //######################## common Event Display and Edit Code ################################### function getEvent(calendar, id, repeat_id, callback, edittype){ ajaxActive = true; if(callback == editEventCallback){ var op = "u"; //under new cwapi this has the same meaning of update } else{ op = "d"; //for a single event detail is now "d" } $.getJSON("/cwapi.php" + gPHPSESSID, {fmt:"json", view:op, "eid[]":id, edittype:edittype, "repeat_id":repeat_id, crd:calendar}, callback, "json") .done(function() { //console.log( "getEvent success" ); }) .fail(function() { //console.log( "getEvent error" ); }); } // Populate and display event detail function eventCallback(data, result){ commonAjaxCallback(data, result); if(data.status.code == 200){ jPleaseWait.hide(); var jEventDiv = $("#event"); // Do not show email or download buttons if show busy set and not logged in if ((calshowbusy) && (!gLoggedIn)) { $("#openNewEmail").css({"display":"none"}); $("#downloadEvent").css({"display":"none"}); } else { $("#openNewEmail").css({"display":"inline"}); $("#downloadEvent").css({"display":"inline"}); } // Do not show remind button if show busy set and not logged in and event not is past if (((calshowbusy) && (!gLoggedIn)) || (data.eventdetails[0].inpast)) { $("#getReminder").css({"display":"none"}); } else { $("#getReminder").css({"display":"inline"}); } jEventDiv.show(); var cw_event = data.eventdetails[0]; // Event date(s) if (cw_event["isbanner"]) { cal.banner_beg_date = new Date(parseInt(cw_event["event_year"]), parseInt(cw_event["event_month"])-1, parseInt(cw_event["event_day"])); // end date obj cal.banner_end_date = new Date(parseInt(cw_event["end_event_year"]), parseInt(cw_event["end_event_month"])-1, parseInt(cw_event["end_event_day"])); // end date obj var bandatetimestr = cal.banner_beg_date.format("ddd, mmm d, yyyy"); if (data.settings.military == '1') { var timeformatstr = "UTC:HH:MM"; } else { var timeformatstr = "UTC:h:MMtt"; } if (!cw_event["allday"]) { bandatetimestr += " | " + dateFormat(tsToDate(cw_event, "start_timestamp_gmt", "start_tzoffset"), timeformatstr); } bandatetimestr += ' - ' + cal.banner_end_date.format("ddd, mmm d, yyyy"); if ((!cw_event["noend"]) && (!cw_event["allday"])) { bandatetimestr += " | " + dateFormat(tsToDate(cw_event, "end_timestamp_gmt", "end_tzoffset"), timeformatstr); } else if (!cw_event["allday"]) { //bandatetimestr += " no end time "; } else { //bandatetimestr += " all day "; } $(".detaildate").text(bandatetimestr); } else { cal.event_beg_date = new Date(parseInt(cw_event["event_year"]), parseInt(cw_event["event_month"])-1, parseInt(cw_event["event_day"])); // end date obj $(".detaildate").text(dateFormat(cal.event_beg_date, "ddd, mmm d, yyyy")); } jEventDiv.attr("repeat_id", cw_event.repeat_id); jEventDiv.attr("cw_id", cw_event.event_id); //the data goes into an element that has the className matching it's JSON property name var location_nameCounter = 0; // Loop thru and populate available event data (field labels and content) for(var p in cw_event){ // Check if description only html editor comment if ((p == "description") && (cw_event[p] == "")){ cw_event[p] = ''; } //we need to find the label var jCell = jEventDiv.find("."+p); if(jCell.length == 0){ continue; } //either it's just to the left of where we put the data var jLabel = jCell.prev(".label"); if(jLabel.length == 0){ //or it's somewhere above jLabel = jCell.closest(".label"); } //we're going to hide the label if there is no corresponding data if(cw_event[p] != "" && cw_event[p] != null){ jLabel.show(); } else{ jLabel.hide(); jCell.hide(); continue; } // If show busy set and not logged in then don't show category /* if ((calshowbusy) && (!gLoggedIn) && (p == "category_name")) { jLabel.hide(); jCell.hide(); continue; } */ if(p == "location_name"){ jCell.show(); var location = cw_event[p]; if(location && (location_nameCounter == 0)){ jCell.slice(1).html(location); if(cw_event.location_id != 0){ if (((cw_event.location_map_url) && (cw_event.location_map_show)) || ((cw_event.location_weather_url) && (cw_event.location_weather_show))) { w = screen.availWidth - 100; h = screen.availHeight - 225; var features = "width="+w+",height="+h+",left=50,top=50"; features += ",screenX=50,screenY=50"; features += ",scrollbars=1,resizable=1,location=1"; features += ",menubar=1,toolbar=1,status=1"; if((cw_event.location_map_url) && (cw_event.location_map_show)){ location += " (map)"; } if((cw_event.location_weather_url) && (cw_event.location_weather_show)){ location += " (weather)"; } } } location_nameCounter++; jCell.eq(0).html(location); } }else if(p == "phone"){ var phone = cw_event[p]; if (phone != '') { jCell.html('' + phone + ''); jCell.show(); } }else if(p == "location_phone"){ var location_phone = cw_event[p]; if (location_phone != '') { jCell.html('' + location_phone + ''); jCell.show(); } }else if(p == "url"){ var url = cw_event[p]; if(url){ if(!url.match(/^https?/)){ url = "http://" + url; } jCell.html('' + cw_event[p] + ''); jCell.show(); }else{ jCell.text(""); } }else if(p == "email"){ var email = cw_event[p]; if(email){ if(email.match(/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i)){ //if(checkemailaddress(email)){ jCell.html('' + email + ''); }else{ jCell.text(cw_event[p]); } jCell.show(); }else{ jCell.text(""); } }else if (p == "description"){ if (p.search("") != -1) { jCell.html(cw_event[p].replace(/\n/g, "
")); } else { jCell.html(cw_event[p]); } jCell.show(); }else if (p == "privatenote"){ if (p.search("") != -1) { jCell.html(cw_event[p].replace(/\n/g, "
")); } else { jCell.html(cw_event[p]); } jCell.show(); }else if (p == "location_directions" || p == "location_guidelines"){ jCell.html(cw_event[p].replace(/\n/g, "
")); jCell.show(); }else { jCell.text(cw_event[p]); jCell.show(); } } if (!cw_event["isbanner"]) { displayStartEndTime(jEventDiv, cw_event, data.settings); $("#detail_startendtime").show(); } else { $("#detail_startendtime").hide(); } } else { if(data.status.code == 999){ alert(data.status.msg); return; } cal.render(); } } function eventDone(){ $("#event").hide(); $("#edit").hide(); // Do not show add button if show busy set and not logged in if ((calshowbusy) && (!gLoggedIn)) { $("#navTodayAddLogInOut #a1").css({"display":"none"}); } else { $("#navTodayAddLogInOut #a1").css({"display":"inline"}); } if (!nolognavbar) { $("#navTodayAddLogInOut").show(); } $("#pleasewait").show(); if(gCameFromMonth){ cal.render(cal.date); } else{ getDayEvents(gCalendar, cal.date); } } //######################### Add New Event ############################### function checkCalendarStatus() { // Check calendar type status var alertstr = ''; if (calendar_type == "Expired") { alertstr = "Sorry, your calendar trial has expired. \n\nAs a courtesy, your calendar is available for viewing. \nYou may restore the ability to add and edit events by purchasing a subscription."; } else if (calendar_type == "Billing-C") { alertstr = "Sorry, our records show a problem billing for your account. \n\nAs a courtesy, your calendar is available for viewing. \nYou may restore the ability to add and edit events by updating your billing information."; } else if (calendar_type == "Renewal-C") { alertstr = "Sorry, our records show your subscription renewal is past due. \n\nAs a courtesy, your calendar is available for viewing. \nYou may restore the ability to add and edit events by renewing your subscription"; } if (alertstr != '') { alertstr += "\n\nFor details, login to your calendar using a desktop or tablet and go to Account Details. \n\nOr, contact support@calendarwiz.com" alert(alertstr); return false; } else { return true; } } function addEvent(e, skipCategories){ if (!checkCalendarStatus()) { return false; } endDateIsDirty = false; // For date picker control if(skipCategories == undefined){ //we need to populate the category drop down editEventEvent = undefined; getEditLocations(gCalendar, populateLocationDropDown); getEditCategories(gCalendar, populateCategoryDropDown); return; } // Need to check here to see if we're logged in with // permission to add an event if(gLoggedIn){ if (gCanAdd) { $(cal.grid).hide(); $("#navTodayAddLogInOut").hide(); $("#day").hide(); jPleaseWait.show(); getNewEvent(gCalendar, cal.date); } else { if(gCameFromMonth){ cal.render(cal.date); }else{ getDayEvents(gCalendar, cal.date); } cal.render(cal.date, false); alert('Sorry, this login not allowed to add events'); } }else{ if($("#loginform").is(":visible")) return; if(confirm("Login required to add an event.\nDo you want to login?")){ gDestinationScreen = "#edit"; $(cal.grid).hide(); $("#navTodayAddLogInOut").hide(); $("#day").hide(); logincancelviz(); $("#loginform").show(); $("#navTodayAddLogInOut").hide(); $("#username")[0].focus(); } } } function getNewEvent(calendar, date){ ajaxActive = true; var month = (date.getMonth() + 1); var year = date.getFullYear(); var day = date.getDate(); //"a" code is all the defaults $.getJSON("/cwapi.php" + gPHPSESSID, {fmt:"json", view:"a", aday:day, amonth:month, ayear:year, crd:calendar}, editEventCallback, "json") .done(function() { //console.log( "getDayEvents success" ); }) .fail(function() { //console.log( "getDayEvents error" ); }); } //############################ Display Event for Adding or Editing ############################### var editEventEvent; function editEvent(e, skipCategories){ if (!checkCalendarStatus()) { return false; } if(skipCategories == undefined){ //we need to populate the category drop down editEventEvent = e; getEditLocations(gCalendar, populateLocationDropDown); getEditCategories(gCalendar, populateCategoryDropDown); return false; } $("#allorsingle").hide(); $("#day").hide(); $("#event").hide(); var edittype = ""; if(typeof(e) == "string"){ edittype = e; //send in the repeat_id in here jPleaseWait.show(); getEvent(gCalendar, g_cw_id, g_rpt_master_id, editEventCallback, edittype); return false; } else{ g_cw_id = $(e.target).closest("[cw_id]").attr("cw_id"); g_rpt_master_id = $(e.target).closest("[repeat_id]").attr("repeat_id"); } if(g_rpt_master_id > 0){ //we need to pop up a dialog to ask the user whether they want to do an //edit on a single event or all occurences of a repeating event //$("#radioEditSingle")[0].checked = false; //$("#radioEditAll")[0].checked = false; //$(":input[name='btneditthis']").attr("disabled", true); //$(":input[name='btneditall']").attr("disabled", true); $("#allorsingle").show(); return false; } else{ jPleaseWait.show(); getEvent(gCalendar, g_cw_id, g_rpt_master_id, editEventCallback, edittype); return false; } } function editEventCallback(data, result){ commonAjaxCallback(data, result); if(data.status.code == 200){ jPleaseWait.hide(); var jEventDiv = $("#edit"); jEventDiv.show(); if(cal.date == undefined){ cal.date = new Date(); } $(".date").text(cal.date.format("dddd, mmmm d, yyyy")); if(data.status.view == "a"){ var cw_event = data.eventdefaults; } else if(data.status.view == "u"){ var cw_event = data.eventupdatedetails[0]; } else{ cw_event = data.eventdetails[0]; } //need to extract the day, month, year from the seconds //need to heed if this is military time var mil = data.settings.military == '1'; var startDate = tsToDate(cw_event, "start_timestamp_gmt", "start_tzoffset"); cw_event.emonth = dateFormat(startDate, "UTC:m"); cw_event.eyear = dateFormat(startDate, "UTC:yyyy"); cw_event.eday = dateFormat(startDate, "UTC:d"); var endDate = tsToDate(cw_event, "end_timestamp_gmt", "end_tzoffset"); var rptendDate = tsToDate(cw_event, "rpt_end_timestamp_gmt", "rpt_end_tzoffset"); // For banner events if(mil){ $("#startampm").hide(); $("#endampm").hide(); $("#startampmlabel").hide(); $("#endampmlabel").hide(); cw_event.starthour = dateFormat(startDate, "UTC:H"); cw_event.endhour = dateFormat(endDate, "UTC:H"); } else{ $("#startampm").show(); $("#endampm").show(); $("#startampmlabel").show(); $("#endampmlabel").show(); //alert(dateFormat(startDate, "UTC:H") ) ; cw_event.starthour = dateFormat(startDate, "UTC:h"); cw_event.endhour = dateFormat(endDate, "UTC:h"); } setHoursDropDown($("#starthour")[0], mil); setHoursDropDown($("#endhour")[0], mil); cw_event.startminute = dateFormat(startDate, "UTC:MM"); if(cw_event.startminute.match(/^[1-5][0,5]$/)){ cw_event.startminute = "+" + cw_event.startminute; } cw_event.startampm = dateFormat(startDate, "UTC:tt"); cw_event.endminute = dateFormat(endDate, "UTC:MM"); if(cw_event.endminute.match(/^[1-5][0,5]$/)){ cw_event.endminute = "+" + cw_event.endminute; } cw_event.endampm = dateFormat(endDate, "UTC:tt"); cw_event.draft = "0"; if(cw_event.login_email == ""){ $("#remindme").hide(); } else{ $("#remindme").show(); } //apparently when a single event comes through here there are no rpt fields //so the rpt fields default to the last state they were in //so we need to come up with something to initialize their state //what we can do is just insert default values into cw_event right here cw_event.rpt_end_day = dateFormat(rptendDate, "UTC:d"); cw_event.rpt_end_month = dateFormat(rptendDate, "UTC:m"); cw_event.rpt_end_year = dateFormat(rptendDate, "UTC:yyyy"); if(cw_event.rpt_type == undefined){ cw_event.rpt_sun = false; cw_event.rpt_mon = false; cw_event.rpt_tue = false; cw_event.rpt_wed = false; cw_event.rpt_thu = false; cw_event.rpt_fri = false; cw_event.rpt_sat = false; cw_event.rpt_type = "none"; cw_event.rpt_weeks = "1"; cw_event.rpt_days = "2"; cw_event.rpt_month_place = "first"; cw_event.rpt_noenddate= false; } initControls(); //only for whether they are enabled or disabled. for(var p in fieldsToPopulate){ var thisInputControl = $("#"+p); if(fieldsToPopulate[p].match(/span/)){ thisInputControl.text(cw_event[p]); } else if(fieldsToPopulate[p].match(/checkbox/)){ if(cw_event[p]){ thisInputControl.attr("checked", true); } else { thisInputControl.attr("checked", false); } } else { thisInputControl.val(cw_event[p]); //console.log(p); } if(cw_event.edittype == "single") { //in single event of a repeating series mode if(p.match(/^rpt_/) && !p.match(/^rpt_last_flag/)){ thisInputControl.attr("disabled", true); } } else { thisInputControl.attr("disabled", false); } } // Store location_id in global DOM variable from location select list last_saved_location_id = $("#location_id").val(); // Set Saved Location zero option text if editing event already has Saved Location if (last_saved_location_id != 0) { $("#location_id option[value='0']").text('De-Select Saved Location'); } // If using html editor (i.e. tinymce) update the tinymce editor so has // content of the description text area and not left over from previous edit if ((usehtmled) && (typeof tinyMCE != 'undefined')) { // Get editor object var editor = tinyMCE.get('description'); // Get content of description text area var descriptionval = $("#description").val(); descriptionval = descriptionval.replace(//g, ""); editor.execCommand('mceSetContent', false, descriptionval); editor.startContent = tinymce.trim(editor.getContent({ format: 'raw' })); editor.isNotDirty = true; editor.nodeChanged(); } setNumDays('e'); setNumDays('rpt_end_'); timeOptions(); docontrols(); gInitSerialize = $("[name=eventform]").serialize(); // COMMENTED OUT UNTIL aftertinyinit IS WORKING // THIS IS WORKING SO TINYMCE IS NOT IN FOCUS WHEN OPENING // EDITOR AND RELEASES FOCUS ON TITLE SO KEYBOARD DOES NOT // OPEN ON FORM ENTRY? CHECK THIS ON IPHONE $("#title")[0].focus(); $("#title")[0].blur(); } else { if(data.status.code == 999){ alert(data.status.msg); return; } jPleaseWait.hide(); $(cal.grid).show(); setTimeout(window.alert, 0, data.status.msg); } } //################################ Saving an Event ####################################### function SaveEvent(mode){ // Added 9/7/12 because "dirty" check below was allowing the form to be // saved without an Event Title if (mode != 'delete') { var valid = validate(); if(!valid){ return false; } } // If using html editor (i.e. tinymce), need to get description into actual textarea for posting if ((usehtmled) && (typeof tinyMCE != 'undefined')) { var tinymce_description = tinymce.get('description').getContent(); if (tinymce_description != '') { $("#description").val('' + tinymce_description); // Only if description not blank } else { $("#description").val(''); } } else { // Remove html editor comment tag in case was edited by html editor and then html editor turned off in options // Note that other html tags are not removed at this time $("#description").val($("#description").val().replace(//g, "")); } var serialize = $("[name=eventform]").serialize(); var edittype = $("#edittype").val(); if(mode == "delete"){ if(!confirm("Are you sure you want to DELETE this event? This operation cannot be undone.")){ return; } serialize += "&btndelete=Delete"; $("#edit").hide(); jPleaseWait.show(); $.post("/calendars/editevent_savemobile.php" + gPHPSESSID + "&crd=" + gCalendar + "&view=u", serialize, eventSaveCallback, "json") .done(function() { //console.log( "SaveEvent success" ); }) .fail(function() { //console.log( "SaveEvent error" ); }); return; } if(mode == "draft"){ serialize = serialize.replace(/draft=0/, "draft=1"); } if(edittype == "single" || edittype == ""){ serialize = serialize.replace(/occ_changed=0/, "occ_changed=1"); } var dirty = gInitSerialize != serialize; if(dirty){ if(!validate()){ return; } if($("#old_occ_changed").val() == "1" && (edittype == 'repeats')){ if(!confirm("CAUTION: You are editing all occurrences of this repeating event. Saving will overwrite changes previously made to individual occurrences of this event.")){ return; } } } // input name="occ_changed" type=hidden value="0" // CLIENT: Flag set when editing occurrence of a repeating series if any data was changed. This needs to be set by client and in POST serialize = serialize.replace(/minute=%2B/g, "minute="); jPleaseWait.show(); jPleaseWait.css("top","1122px"); // Get primary category name and put into serialize variable var selcatoption = $("#category_id option:selected"); var cat_name = selcatoption.text(); serialize += "&cat_name=" + cat_name; // Get category noconflict property value for the selected category var catnoconflicts = selcatoption.prop("noconflicts"); // If saved location selected, Get selected location noconflict property if ($("#location_id").val() != 0) { var sellocoption = $("#location_id option:selected"); var loc_name = sellocoption.text(); var locnoconflicts = sellocoption.prop("noconflicts"); } else { var locnoconflicts = '0'; var loc_name = ''; } if ((mode == "save") || (mode == 'draft')) { if ((mode != 'draft') && ((catnoconflicts == "1") || (locnoconflicts == "1"))) { // Check for category conflicts $.post("/calendars/editevent_conflictcheck.php"+gPHPSESSID+"&crd="+gCalendar+"&catnoconflicts="+catnoconflicts+"&locnoconflicts="+locnoconflicts, serialize, function(data) { if (data.status.code == 700) { var catconcount = parseInt(data.conflicts.catconcount); if (catconcount == 1) { var catcontxt = ""; } else { var catcontxt = "s"; } var locconcount = parseInt(data.conflicts.locconcount); if (locconcount <= 1) { var loccontxt = ""; } else { var loccontxt = "s"; } var numconflicts = parseInt(data.conflicts.eventconcount); if (numconflicts == 1) { var numcontxt = ""; } else { var numcontxt = "s"; } var conflictmsg = 'Sorry, this event conflicts with ' + numconflicts + ' event' + numcontxt + ' in the calendar. ' + "\n\n"; if (catconcount > 0) { conflictmsg += ' - ' + catconcount +' conflict' + catcontxt + ' in category ' + cat_name + "\n"; } if (locconcount > 0) { conflictmsg += ' - ' + locconcount +' conflict' + loccontxt + ' at location ' + loc_name + "\n"; } conflictmsg += "\n"; conflictmsg += 'Please Choose different time'; if (catconcount > 0) { if (locconcount > 0) { conflictmsg += ', category or location.'; } else { conflictmsg += ' or category.'; } } else { conflictmsg += ' or location.'; } conflictmsg += "\n\n"; jPleaseWait.css("top","170px"); jPleaseWait.hide(); alert(conflictmsg); return false; } else { // No conflicts found so save postSave(serialize); } }, "json"); } else { // No conflict check, just save postSave(serialize); } } } function postSave(serialize) { // Go ahead and save event (NOTE VIEW=A DOES NOT AFFECT EDITEVENT_SAVEMOBILE.PHP IT ADDS OR UPDATES BASED ON EVENT_ID PRESENT) $("#edit").hide(); $.post("/calendars/editevent_savemobile.php" + gPHPSESSID + "&crd=" + gCalendar + "&view=a", serialize, eventSaveCallback, "json"); } function eventSaveCallback(data, result){ commonAjaxCallback(data, result); if(data.status.code == 200){ if(gCameFromDetail){ displayEvent(" "); } else{ //here we agreed not to change the setting for the day we came from //based on the saved day if we're changing the entire series of repeating events //so how do we tell if this is a repeating series? if(g_rpt_master_id == 0 || g_rpt_master_id == undefined){ cal.date.setFullYear(parseInt($("#eyear").val())); cal.date.setMonth(parseInt($("#emonth").val()) - 1, parseInt($("#eday").val())); } //need to show the day view here getDayEvents(gCalendar, cal.date); } }else{ if(data.status.code == '855'){ getMonthEvents(gCalendar, cal.date); $("#navTodayAddLogInOut").show(); alert('Sorry, you have exceeded allowed daily events. Contact support@calendarwiz.com'); return; } else { debug(data.status.msg); } } } //##################################### Email Functions ################################# var introNoteMaxLength = 800; function createEmailDIV(){ var jEmailBodyDIV = $("
"); var tHTML = '
Back
'; tHTML += '
'; //tHTML += '
Email Event
'; tHTML += ''; tHTML += ''; tHTML += ''; tHTML += ''; tHTML += ''; tHTML += ''; tHTML += ''; //tHTML += '
'; tHTML += '
'; tHTML += ''; tHTML += ''; tHTML += ''; tHTML += '
'; tHTML += '
'; //tHTML += ' '; //tHTML += ''; jEmailBodyDIV.append(tHTML); var jIntroNote = jEmailBodyDIV.find("[cwui=intronote]"); var jCharLeft = jEmailBodyDIV.find("[cwui=charleft]"); //jEmailBodyDIV.find("[cwui=nointro]") //.bind("click", function(){jEmailBodyDIV.find("[cwui=intronote]").val("").trigger("keyup")}) //.css({"font-size":"65%"}) //.hover(function(){ // jEmailBodyDIV.find("[cwui=nointro]").css({"text-decoration":"none", cursor:"pointer"}) // }, // function(){ // jEmailBodyDIV.find("[cwui=nointro]").css({"text-decoration":"none", cursor:"default"}) // } // ); jEmailBodyDIV.find("[cwui=emailbtnback]").bind("click", function(){ $(".bottom_drop").show(); jDetailBodyDIV.show(); jEmailBodyDIV.hide();}).css({"margin-top":"10px"}); jEmailBodyDIV.find("[cwui=sendemail]").bind("click", sendEmail).css({"margin-top":"10px"}); jIntroNote.bind("keyup", function(){ var len = jIntroNote.val().length; if(len > introNoteMaxLength){ jIntroNote.val(jIntroNote.val().substr(0,introNoteMaxLength)); return false; } jCharLeft.text("Max " + introNoteMaxLength + " characters, " +(introNoteMaxLength - len) + " remaining"); return true; }); // Email for styles //jEmailBodyDIV.find("[cwui=emailfrom]").css({"width":"90%", "margin-top":"10px", "margin-left":"10px"}); //jEmailBodyDIV.find("[cwui=emailto]").css({width:"90%", "margin-top":"10px", "margin-left":"10px"}); //jEmailBodyDIV.find("[cwui=subject]").css({width:"90%", "margin-top":"10px", "margin-left":"10px"}); //jIntroNote.css({width:"90%", "margin-top":"10px", "margin-left":"10px"}); //jEmailBodyDIV.find("[cwui=emailheader]").css({"padding-top":"20px"}); //jEmailBodyDIV.find("[cwui=sendfromemail]").css({"padding-top":"10px", "padding-left":"10px"}); //jEmailBodyDIV.find("[cwui=sendtoemail]").css({"padding-top":"10px", "padding-left":"10px"}); //jEmailBodyDIV.find("[cwui=emailsubject]").css({"padding-top":"10px", "padding-left":"10px"}); //jEmailBodyDIV.find("[cwui=emailmsg]").css({"padding-top":"10px", "padding-left":"10px"}); return jEmailBodyDIV; } function openNewEmail(e){ var jDetailDIV = $(e.target).closest("[cwui='detaildiv']"); jDetailBodyDIV.hide(); jEmailBodyDIV.show(); jEmailBodyDIV.find("[cwui=emailfrom]").val(gData.status.email); /* // Get best default email, with display name if possible var prefillemailaddress = gData.status.email; // Just email address, no display name if((gData.status.firstname != '') || (gData.status.lastname != '')){ prefillemailaddress = '<' + prefillemailaddress + '>'; } if(gData.status.lastname != ''){ prefillemailaddress = gData.status.lastname + ' ' + prefillemailaddress; } if(gData.status.firstname != ''){ prefillemailaddress = gData.status.firstname + ' ' + prefillemailaddress; } jEmailBodyDIV.find("[cwui=emailfrom]").val(prefillemailaddress); jEmailBodyDIV.find("[cwui=emailto]").val(prefillemailaddress); */ jEmailBodyDIV.find("[cwui=subject]").val("Calendar Note: " + jDetailDIV.find(".title").text()); jEmailBodyDIV.find("[cwui=intronote]").val("I thought you might be interested in this event.\n\nThank you").trigger('keyup'); $(".bottom_drop").hide(); return false; } function sendEmail(e){ ajaxActive = true; var jDetailDIV = $(e.target).closest("div"); var emailto = jEmailBodyDIV.find("[cwui=emailto]").val(); var emailfrom = jEmailBodyDIV.find("[cwui=emailfrom]").val(); if(!emailto.match(/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i)){ //if(!checkemailaddress(emailto)){ jEmailBodyDIV.find("[cwui=emailto]").focus(); alert("Please enter a valid to email address"); jDetailDIV.scrollTop(0); return; } if(!emailfrom.match(/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i)){ //if(!checkemailaddress(emailfrom)){ jEmailBodyDIV.find("[cwui=emailfrom]").focus(); alert("Please enter a valid from email address"); jDetailDIV.scrollTop(0); return; } var subject = jEmailBodyDIV.find("[cwui=subject]").val(); var note = jEmailBodyDIV.find("[cwui=intronote]").val(); if(subject == ""){ jEmailBodyDIV.find("[cwui=subject]").focus(); alert("Please enter a subject"); jDetailDIV.scrollTop(0); return; } if(note.length > introNoteMaxLength){ jEmailBodyDIV.find("[cwui=intronote]").focus(); alert("Please shorten your introduction to " + introNoteMaxLength + " characters."); jDetailDIV.scrollTop(0); return; } $.post("/cwapi.php" + gPHPSESSID + "&callback=?", {subject:subject, intronote:note, fromemail:emailfrom, toemail:emailto, event_id:g_cw_id, repeat_id:g_rpt_master_id, fmt:"json", view:"sendevent", crd:gCalendar}, emailCallback, "json") .done(function() { //console.log( "sendEmail success" ); }) .fail(function() { //console.log( "sendEmail error" ); }); $(".bottom_drop").show(); } function emailCallback(data, result){ commonAjaxCallback(data, result); if(data.status.code == "200"){ //here we show the status msg alert(data.status.msg); jDetailBodyDIV.show();jEmailBodyDIV.hide(); }else{ if(data.status.code == 999){ alert(data.status.msg); return; } document.write(data.status.msg); } } //##################################### Remind Functions ################################# function createRemindDIV(){ jRemindBodyDIV = $(""); //var tHTML = '
Set Email Reminder
'; var tHTML = ''; tHTML += '
'; tHTML += ''; tHTML += ' before this event. '; tHTML += ''; tHTML += '


'; tHTML += ''; tHTML += ''; tHTML += ''; //tHTML += '
'; tHTML += ''; tHTML += '
'; jRemindBodyDIV.append(tHTML); jRemindBodyDIV.find("[cwui=btnback]").bind("click", function(){ $(".bottom_drop").show(); jDetailBodyDIV.show(); jRemindBodyDIV.hide(); }); jRemindBodyDIV.find("[cwui=setremind]").bind("click", setReminder); jRemindBodyDIV.find("[cwui=delete]").bind("click", deleteReminder); //jRemindBodyDIV.find("[cwui=email]").css({width:"90%", "margin-top":"10px"}); //jRemindBodyDIV.find("[cwui=remindheader]").css({"padding-top":"20px"}); //jRemindBodyDIV.find("[cwui=sendreminder]").css({"padding-top":"10px", "padding-left":"10px"}); return jRemindBodyDIV; } function getReminder(e){ $(".bottom_drop").hide(); ajaxActive = true; var jDetailDIV = $(e.target).closest("div"); $.getJSON("/cwapi.php" + gPHPSESSID + "&callback=?", {event_id:g_cw_id, repeat_id:g_rpt_master_id, fmt:"json", view:"getremind", crd:gCalendar}, reminderCallback) .done(function() { //console.log( "getReminder success" ); }) .fail(function() { //console.log( "getReminder error" ); }); return false; } function setReminder(e){ ajaxActive = true; var jDetailDIV = $(e.target).closest("div"); var priortime = jRemindBodyDIV.find("[cwui=priortime]").val(); var email = jRemindBodyDIV.find("[cwui=email]").val(); if(!jRemindBodyDIV.reminder_id){ jRemindBodyDIV.reminder_id = 0; } if(email.match(/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i)){ //if(checkemailaddress(email)){ if (g_rpt_master_id > 0) { g_repeat_mode = 'all'; } else { g_repeat_mode = 'single'; } $.getJSON("/cwapi.php" + gPHPSESSID + "&callback=?", {reminder_id:jRemindBodyDIV.reminder_id, email:email, priortime:priortime, repeat_mode:g_repeat_mode, event_id:g_cw_id, repeat_id:g_rpt_master_id, fmt:"json", view:"setremind", crd:gCalendar}, reminderCallback) .done(function() { //console.log( "setReminder success" ); }) .fail(function() { //console.log( "setReminder error" ); }); }else{ alert("Please enter a valid email address"); } $(".bottom_drop").show(); } function deleteReminder(e){ ajaxActive = true; var jDetailDIV = $(e.target).closest("div"); if (g_rpt_master_id > 0) { g_repeat_mode = 'all'; } else { g_repeat_mode = 'single'; } $.getJSON("/cwapi.php" + gPHPSESSID + "&callback=?", {reminder_id:jRemindBodyDIV.reminder_id, repeat_mode:g_repeat_mode, event_id:g_cw_id, repeat_id:g_rpt_master_id, fmt:"json", view:"delremind", crd:gCalendar}, reminderCallback) .done(function() { //console.log( "deleteReminder success" ); }) .fail(function() { //console.log( "deleteReminder error" ); }); $(".bottom_drop").show(); } function reminderCallback(data, result){ commonAjaxCallback(data, result); if(data.status.code == 200 || data.status.code == 201){ if(data.status.view == "getremind"){ //here we need to display the reminder form and hide the event display jDetailBodyDIV.hide(); jRemindBodyDIV.show(); jRemindBodyDIV.find("[cwui=priortime]").val(data.remindersettings.priortime); jRemindBodyDIV.find("[cwui=email]").val(data.remindersettings.email); /* if(data.status.code == 200){ jRemindBodyDIV.find("[cwui=email]").val(data.remindersettings.email); }else{ // Get best default email, with display name if possible var prefillemailaddress = gData.status.email; // Just email address, no display name if((gData.status.firstname != '') || (gData.status.lastname != '')){ prefillemailaddress = '<' + prefillemailaddress + '>'; } if(gData.status.lastname != ''){ prefillemailaddress = gData.status.lastname + ' ' + prefillemailaddress; } if(gData.status.firstname != ''){ prefillemailaddress = gData.status.firstname + ' ' + prefillemailaddress; } jRemindBodyDIV.find("[cwui=email]").val(prefillemailaddress); } */ jRemindBodyDIV.reminder_id = data.remindersettings.reminder_id; if(data.remindersettings.reminder_id){ jRemindBodyDIV.find("[cwui=delete]").show(); jRemindBodyDIV.find("[cwui=setremind]").val("Update Reminder"); }else{ jRemindBodyDIV.find("[cwui=setremind]").val("Set Reminder"); jRemindBodyDIV.find("[cwui=delete]").hide(); } }else{ //here we show the error status msg alert(data.status.msg); jDetailBodyDIV.show();jRemindBodyDIV.hide(); } }else{ if(data.status.code == 999){ alert(data.status.msg); return; } //debug(data.status.msg); } } function downloadEvent(e){ $(".bottom_drop").hide(); location.href = "/calendars/popcal.php" + gPHPSESSID + "&eid=" + g_cw_id; return false; } //##################################### Form Functions ################################# function setNumDays(prefix){ //we need to make the eday dropdown have the right number of days in it. //also have to change the selected day if it is greater than the number of days in the month var feb = 28; if((parseInt($("#"+prefix+"year").val()) % 4) == 0){ feb = 29; } var days = dateFormat.daysInMonth[parseInt($("#"+prefix+"month").val())]; if(days == 28){ days = feb; } var dayDD = $("#"+prefix+"day")[0]; var len = dayDD.options.length; if(len == days)return; if(len < days){ for(var i = len; i < days; i++){ dayDD[i] = new Option(i + 1, i + 1); } } else{ var selectedIndex = dayDD.selectedIndex; dayDD.options.length = days; if(selectedIndex > (days - 1)){ dayDD.selectedIndex = days - 1; } } } function setHoursDropDown(dd, military){ if(military){ if(dd.options.length == 24){ return; } else { dd.options.length = 0; for(var i = 0; i < 24; i++){ dd.options[i] = new Option(pad(i), i); } } } else{ // Handles scenario where if(dd.options.length == 12){ return; } else { dd.options.length = 0; for(var i = 0; i < 12; i++){ dd.options[i] = new Option(pad(i + 1), pad(i + 1)); } } } } function timeOptions(type){ var allday = $("#allday")[0].checked; var noend = $("#noend")[0].checked; if(type == "allday" && allday){ $("#noend")[0].checked = false; noend = false; } else if(type == "noend" && noend){ $("#allday")[0].checked = false; allday = false; } if(!allday && !noend){ $("#starthour").removeAttr("disabled"); $("#startminute").removeAttr("disabled"); $("#startampm").removeAttr("disabled"); $("#starttime").show(); $("#endhour").removeAttr("disabled"); $("#endminute").removeAttr("disabled"); $("#endampm").removeAttr("disabled"); $("#endtime").show(); } else if(noend){ $("#starthour").removeAttr("disabled"); $("#startminute").removeAttr("disabled"); $("#startampm").removeAttr("disabled"); $("#starttime").show(); $("#endhour").attr("disabled", true); $("#endminute").attr("disabled", true); $("#endampm").attr("disabled", true); $("#endtime").hide(); } else{ $("#starthour").attr("disabled", true); $("#startminute").attr("disabled", true); $("#startampm").attr("disabled", true); $("#starttime").hide(); $("#endhour").attr("disabled", true); $("#endminute").attr("disabled", true); $("#endampm").attr("disabled", true); $("#endtime").hide(); } } // Following function is not currently used, it returns all categories // that arer viewable by this visitor or logged in user. Since mobile // only gets categories for add and edit it is no longer used. This // change was done to plug security hole where all users who could edit // could add / edit any category, not just those they manage or if // category is set to allow users to add / edit own events. function getCategories(calendar, callback){ $.getJSON("/cwapi.php" + gPHPSESSID, {fmt:"json", view:"c", crd:calendar}, callback, "json") .done(function() { //console.log( "getCategories success" ); }) .fail(function() { //console.log( "getCategories error" ); }); } // Following function now used to get list of categories for add / edit // Note the subview parameter to be used in the get category list api // function to flag filtering of only categories allowed to edit for this // logged in user - introduced 120406 by Dennis Mulryan function getEditCategories(calendar, callback){ $.getJSON("/cwapi.php" + gPHPSESSID, {fmt:"json", view:"c", subview:"addedit", crd:calendar}, callback, "json") .done(function() { //console.log( "getEditCategories success" ); }) .fail(function() { //console.log( "getEditCategories error" ); }); } // Get locations for add / edit form function getEditLocations(calendar, callback){ $.getJSON("/cwapi.php" + gPHPSESSID, {fmt:"json", view:"l", subview:"addedit", crd:calendar}, callback, "json") .done(function() { //console.log( "getEditCategories success" ); }) .fail(function() { //console.log( "getEditCategories error" ); }); } // Loads categories into select function populateCategoryDropDown(data, result){ if (data.categories != undefined) { var categories = data.categories; var jEventDiv = $("#edit"); var catDD = jEventDiv.find(":input[name='category_id']")[0]; catDD.options.length = 0; for(var i = 0; i < categories.length; i++){ // This put in because API sends any category name with special characters as null // Need to fix this in API since affects all category name from API (e.g. search widgets) if(!categories[i].category_name) { categories[i].category_name = 'unknown'; } if(categories[i].category_name.length > 45){ categories[i].category_name = categories[i].category_name.substr(0, 45) + "..."; } catDD.options[catDD.options.length] = new Option(categories[i].category_name, categories[i].category_id); // Add noconflicts attribute to this category option, note need to use length-1 // because we just created option so length changed and need to backup one index catDD.options[catDD.options.length-1].noconflicts = categories[i].noconflicts; } } if(editEventEvent == undefined){ addEvent(editEventEvent, true); } else{ editEvent(editEventEvent, true); } } // Loads locations into select function populateLocationDropDown(data, result){ if (data.locations != undefined) { // Clear any remnants of prior add or edit last_saved_location_id = 0; $("#locmsg, #locmsgbottom").hide(); // Put location data into var var locations = data.locations; var jEventDiv = $("#edit"); var locDD = jEventDiv.find(":input[name='location_id']")[0]; locDD.options.length = 0; if (data.locations.length > 0) { // First option is no saved location locDD.options[0] = new Option("Choose Saved Location", "0"); for(var i = 0; i < locations.length; i++){ // This put in because API sends any location name with special characters as null // Need to fix this in API since affects all location name from API (e.g. search widgets) if(!locations[i].location_name) { locations[i].location_name = 'unknown'; } if(locations[i].location_name.length > 45){ locations[i].location_name = locations[i].location_name.substr(0, 45) + "..."; } locDD.options[locDD.options.length] = new Option(locations[i].location_name, locations[i].location_id); // Add noconflicts attribute to this category option, note need to use length-1 // because we just created option so length changed and need to backup one index locDD.options[locDD.options.length-1].noconflicts = locations[i].location_no_conflicts; } } else { // No current saved locations locDD.options[0] = new Option("No Saved Locations Yet", "0"); } } // if(editEventEvent == undefined){ // addEvent(editEventEvent, true); // } // else{ // editEvent(editEventEvent, true); // } } //######################### Refresh ############################### var gTimeoutHandle; var timeoutMilliseconds = 60000 * 115; //115 minutes function refresh(){ //based on the screen we're on we'll want to call something different //first we have to clear any existing timeout if(gTimeoutHandle){ window.clearTimeout(gTimeoutHandle); gTimeoutHandle = undefined; gTimeoutHandle = window.setTimeout(refresh, timeoutMilliseconds); } //now which screen are we on? if($("#calendar").is(":visible")){ cal.render(cal.date, false); } else if($("#day").is(":visible")){ getDayEvents(gCalendar, cal.date); } else if($("#event").is(":visible")){ getEvent(gCalendar, g_cw_id, g_rpt_master_id, eventCallback, ""); } $.post("/cwapi.php" + gPHPSESSID, {view:"refresh", fmt:"json", crd:gCalendar}, refreshCallback, "json") .done(function() { //console.log( "refresh success" ); }) .fail(function() { //console.log( "refresh error" ); }); } function refreshCallback(data, result){ commonAjaxCallback(data, result, true); } //######################### Authorization ############################### function createCookie(name,value,days) { if (days) { var date = new Date(); date.setTime(date.getTime()+(days*24*60*60*1000)); var expires = "; expires="+date.toGMTString(); } else var expires = ""; document.cookie = name+"="+value+expires+"; path=/"; } function readCookie(name) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for(var i=0;i < ca.length;i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); } return null; } function eraseCookie(name) { createCookie(name,"",-1); } function logout(){ $("#loginform").hide(); $("#loginlink").show(); $("#logoutlink").hide(); // Do not show add button if show busy set and not logged in if ((calshowbusy) && (!gLoggedIn)) { $("#navTodayAddLogInOut #a1").css({"display":"none"}); } else { $("#navTodayAddLogInOut #a1").css({"display":"inline"}); } if (!nolognavbar) { $("#navTodayAddLogInOut").show(); } if(cw_jsonStatus.code == 401){ //here we want to go back in history if there is history if(window.history.length){ window.history.back(); }else{ alert("This calendar has no public events.\nYou must login to view the calendar."); scrollTo(0, 0); } }else{ $(cal.grid).show(); } } function login(username, password, callback){ // Hide wrong case message $("#passwordmsg").hide(); var rememberme = $("#rememberme:checked").val(); var parameters = {scr:username, psw:password, crd:gCalendar, remlogin:rememberme}; $.post("/cwapi.php" + gPHPSESSID + "&auth=login&fmt=json", parameters, callback, "json") .done(function(data) { // Successful login }) .fail(function() { return false; }); } function loginFromForm(){ var username = $.trim($("#username").val()); if(username == ""){ //$("#username")[0].focus(); alert("Please enter Username or Email."); return; } var password = $.trim($("#password").val()); if(password == ""){ //$("#password")[0].focus(); alert("Please enter a Password."); return; } var parameters = {login:username, password:password, setpassword:setpassword}; $.post("/calendars/ajax/check_password_case.php" + gPHPSESSID + "&crd=" + gCalendar, parameters) .done(function(data) { data = $.parseJSON(data); if (data.passcheck == "wrong password") { // Wrong password so show alert and return false // Reset to initial value so will check case again setpassword = false; // Alert wrong password alert('Invalid username or password.'); return false; } else if ((data.passcheck == "wrong case") && (!setpassword) && (data.verify_counter <= 5)) { // Wrong case and has not yet confirmed use as entered // Most likely this is first check of password case // Get returned user id user_id = data.user_id; // Set flag so next time will reset password case and login setpassword = true; // Show wrong case message $("#passwordmsg").show(); // Google event ga('send', 'event', 'CaseVerifyMForm', 'show', gCalendar); return false; } else if ((data.passcheck == "wrong case") && (setpassword)) { // If wrong pasword and verified to use as entered OR verify counter shows // user has seen message above maximum then do password case reset and login // Google event ga('send', 'event', 'CaseVerifyMForm', 'reset', gCalendar); user_id = data.user_id; // Reset password case var parameters = {password:password, user_id:user_id}; $.post("/calendars/ajax/set_password_case.php" + gPHPSESSID + "&crd=" + gCalendar, parameters) .done(function(data) { // Go login login(username, password, loginCallback); }) .fail(function() { return false; }); } else { // Password case matches so just login login(username, password, loginCallback); } }) .fail(function() { return false; }); } function loginCookies(callback){ var rememberme = true; $.post("/cwapi.php" + gPHPSESSID + "&auth=cookies&fmt=json", {fmt:"json", crd:gCalendar, rememberme:true}, callback, "json") .done(function(data) { // Successful login }) .fail(function() { return false; }); } function showLoginScreen(){ var username = readCookie("cw_user"); if(username){ $("#username").val(unescape(username)); $("#password").val(""); $("#rememberme").attr("checked", true); } else{ $("#username").val(""); $("#password").val(""); $("#rememberme").attr("checked", false); } $("#navTodayAddLogInOut").hide(); $(cal.grid).hide(); logincancelviz(); $("#loginform").show(); if(username){ $("#password")[0].focus(); } else{ $("#username")[0].focus(); } //$("#username")[0].focus(); } function logincancelviz() { //alert('logincancelviz ' + gNoPublicCats); if (gNoPublicCats) { $("#logincancel").hide(); } else { $("#logincancel").show(); } } function logInOut(e){ if(e.target.id == "loginlink"){ showLoginScreen(); gDestinationScreen = undefined; } else{ //here we need to call the cwapi.php script to cancel the php session. $.post("/cwapi.php" + gPHPSESSID + "&auth=logout&fmt=json", {crd:gCalendar}, logoutCallback, "json") .done(function() { //console.log( "logInOut success" ); }) .fail(function() { //console.log( "logInOut error" ); }); } } function logoutCallback(data, result){ commonAjaxCallback(data, result); if(data.status["code"] == 200){ cal.render(cal.date); } } function loginCallback(data, result){ commonAjaxCallback(data, result); if(data.status.code == 200){ $("#loginform").hide(); // Do not show add button if show busy set and not logged in if ((calshowbusy) && (!gLoggedIn)) { $("#navTodayAddLogInOut #a1").css({"display":"none"}); } else { $("#navTodayAddLogInOut #a1").css({"display":"inline"}); } if (!nolognavbar) { $("#navTodayAddLogInOut").show(); } gCanAdd = data.status.canadd; // Can this use add events true or false gIsAdmin = data.status.isadmin; // Is this user an admin gIsManager = data.status.ismanager; // Is this user a manager if(gDestinationScreen == "#edit"){ addEvent(); return; } cal.render(cal.date); $(cal.grid).show(); // Reset to initial value so will check case again setpassword = false; }else{ if(data.status.code == 999){ alert(data.status.msg); return; } $("#navTodayAddLogInOut").hide(); logincancelviz(); $("#loginform").show(); alert("Please try again.\n" + data.status.msg); } } function setCalendar(){ var calendar = $("#cal_id").val(); if(calendar == ""){ $("#cal_id")[0].focus(); alert("Please enter a calendar."); return; } window.location.href = "/mobile.html?crd=" + calendar; return; } //#################################### Format Functions ############################## function displayStartEndTime(jEventDiv, cw_event, settings){ if(cw_event.allday){ jEventDiv.find(".startendtime").text("All Day"); } else{ var mil = settings.military == '1'; if(mil){ var endText = ""; if(!cw_event.noend){ endText = " - " + dateFormat(tsToDate(cw_event, "end_timestamp_gmt", "end_tzoffset"), "UTC:HH:MM"); } var startText = dateFormat(tsToDate(cw_event, "start_timestamp_gmt", "start_tzoffset"), "UTC:HH:MM"); jEventDiv.find(".startendtime").text(startText + " " + endText); } else{ endText = ""; if(!cw_event.noend){ endText = " - " + dateFormat(tsToDate(cw_event, "end_timestamp_gmt", "end_tzoffset"), "UTC:h:MMtt"); } startText = dateFormat(tsToDate(cw_event, "start_timestamp_gmt", "start_tzoffset"), "UTC:h:MMtt"); jEventDiv.find(".startendtime").text(startText + " " + endText); } } } function tsToDate(cw_event, tsPropertyName, timeZoneOffsetPropertyName){ return new Date((parseInt(cw_event[tsPropertyName]) + 3600*parseFloat(cw_event[timeZoneOffsetPropertyName])) * 1000) } //################################################## Navigation Functions ########################################## function goBackToDay(){ $("#allorsingle").hide(); $("#day").show(); } function goToToday(){ jPleaseWait.show(); cal.render(); } //############################################## AJAX Functions ######################################################## function commonAjaxCallback(data, result, noscroll){ if(data.status.code == 999){ alert(data.status.msg); return; } ajaxActive = false; if(data == undefined){ return false; } if(data.status.PHPSESSID){ gPHPSESSID = "?PHPSESSID=" + data.status.PHPSESSID; gData = data; } cw_jsonStatus = data.status; gNoPublicCats = data.status.nopubliccats; if(data.status.code == 404){ $("#cal_id").val(gCalendar); jPleaseWait.hide(); if(cal){ $(cal.grid).hide(); } $("#promptCalendar").show(); $("#navTodayAddLogInOut").hide(); return false; }else if(data.status.code == 401){ $("#cal_id").val(gCalendar); jPleaseWait.hide(); if(cal){ $(cal.grid).hide(); } $("#day").hide(); $("#navTodayAddLogInOut").hide(); logincancelviz(); $("#loginform").show(); $("#username")[0].focus(); gDestinationScreen = undefined; return false; } if(data.status.PHPSESSID){ gPHPSESSID = "?PHPSESSID=" + data.status.PHPSESSID; } gLoggedIn = data.status.loggedin; gCanAdd = data.status.canadd; gIsAdmin = data.status.isadmin; gIsManager = data.status.ismanager; if(gLoggedIn){ $("#loginlink").hide(); $("#logoutlink").show(); } else{ $("#loginlink").show(); $("#logoutlink").hide(); } // Do not show add button if show busy set and not logged in // HERE: MAYBE PUT IN (gCanAdd) IN CONDITIONAL TO NOT SHOW // ADD BUTTON IF CANNOT ADD - BEST WOULD BE TO CONSOLIDATE // INTO FUNCTION SINCE THIS CODE IS DUPLICATED IN SCRIPT //if ((calshowbusy) && (!gLoggedIn) && (!gCanAdd)) { if ((calshowbusy) && (!gLoggedIn)) { $("#navTodayAddLogInOut #a1").css({"display":"none"}); } else { $("#navTodayAddLogInOut #a1").css({"display":"inline"}); } if(noscroll == undefined){ setTimeout(scrollTo, 0, 0, 1); } return true; } $.ajaxSetup({ "error":function(XMLHttpRequest, textStatus, errorThrown) { document.write(textStatus + " " + errorThrown); document.write("response: " + XMLHttpRequest.response + "
"); document.write("responseType: " + XMLHttpRequest.responseType + "
"); document.write("responseText: " + XMLHttpRequest.responseText + "
"); document.write("status: " + XMLHttpRequest.status + "
"); document.write("statusText: " + XMLHttpRequest.statusText + "
"); document.write("Sorry, Please try closing and reopening your calendar"); ajaxActive = false;} }); // ---------------------------------------------------------------------------------------------- // Function to get and set selected location // ---------------------------------------------------------------------------------------------- function getlocation() { // Hide any Validation Engine prompts //$('#eventform').validationEngine('hideAll'); var selectedValue = $("#location_id").val(); // DOM Global, remember last selected saved location id last_saved_location_id = selectedValue; if (selectedValue == 0) { $("#location_name").val(''); $("#location_city").val(''); $("#location_country").val(''); $("#location_stateprovince").val(''); $("#location_street").val(''); $("#location_zippostal").val(''); $("#location_no_conflicts").val(0); // Change text in Saved Locations zero option to un-select $("#location_id option[value='0']").text('Choose Saved Location'); } else { // Ajax call to get existing saved location details var parameters = {crd:gCalendar}; var theurl = "/calendars/editevent_getlocation.php" + gPHPSESSID + "&location_id=" + selectedValue; //$.post(theurl, parameters) $.getJSON(theurl, parameters,"json") .done(function(data) { statusObj = data.status; $("#location_name").val(data.location.location_name); $("#location_city").val(data.location.location_city); $("#location_country").val(data.location.location_country); $("#location_stateprovince").val(data.location.location_stateprovince); $("#location_street").val(data.location.location_street); $("#location_zippostal").val(data.location.location_zippostal); // Clear location message span just in case warning was present from previous // change to saved event information //cellid = $("#locmsg"); //cellid.hide(); $("#locmsg, #locmsgbottom").hide(); // Hide the add location link since don't want to add location that is already a // saved location, this will be made visible if any changes are made to location //$("#addlocationspan").hide(); // Note: Only setting flag for location not allowing conflicts, this is single location // at this time but future needs to support multiple locations so if any location does // not allow conflicts then flag is set. $("#location_no_conflicts").val(data.location.location_no_conflicts); // Change text in Saved Locations zero option to un-select $("#location_id option[value='0']").text('De-Select Saved Location'); }); } } // If location text changes then set id to zero so no longer saved location function locchange(event) { var locmsgdivid = 'locmsg'; // Default, location change message will show below location details // See change event was triggered by click on button. // The value of btnclicked is set onmousedown for each button // because the onchange event will trigger before the click event // on a button and we want to know which button is clicked here so // we can adjust the behavior of the save location message depending // on the button that was clicked. For example the cancel button just // closes the editor, the save button just shows the Save Location // message and does not save until touch Save again if (btnclicked == 'cancelbtn') { eventDone(); return true; } else if (btnclicked == 'deletebtn') { SaveEvent('delete'); return true; } else if ((btnclicked == 'savebtn') || (btnclicked == 'savedraftbtn')) { locmsgdivid = 'locmsgbottom'; // Location change message will show above Save button } // Reset btnclicked = 'none'; var btntxt_add = ''; btntxt_add_1 = btntxt_add + 'Add as new Saved Location'; btntxt_add_2 = btntxt_add + 'Add ' + $("#location_name").val() + ' as new Saved Location'; var celltxt = ''; if (last_saved_location_id != 0) { var btntxt_update = ''; btntxt_update += 'Update this Saved Location'; // This is a saved location that has been changed $("#location_id").val(0); // Set location id to zeror, no longer saved location $("#location_no_conflicts").val(0); // Only saved locations can have no conflicts set celltxt = "Changes to saved location, " + $("#location_id option[value='" + last_saved_location_id + "']").text() + ", will only apply to this event."; if ((gIsAdmin == '1') || (locations_only_admins == 0)) { // Aways allow admins to add / update locations or any who edit if only admins option not set celltxt += ' You may:
' + btntxt_add_1 + '
' + btntxt_update; // append add and/or update links to saved locations message // Show location message and save as new location button $("#"+locmsgdivid).css("display","block").html(celltxt); return; } else { // Just show location message with no save as new location button //$("#"+locmsgdivid).css("display","inline-block").html(celltxt); $("#"+locmsgdivid).css({"display":"block","background-color":"#fcf8e3","color":"#c09853"}).html(celltxt); } } else { // Not a saved location changed, just location entered for event // Show suggestion to add to Saved Locations if ((gIsAdmin == '1') || ((locations_only_admins == 0))) { // If allowed to manage locations // This is new location not derived from Saved Location celltxt = "Suggestion: "; celltxt += btntxt_add_2; // append add link to saved locations message // Show location message and save as new location button $("#"+locmsgdivid).css("display","inline-block").html(celltxt); } } } // Add location via ajax function addlocation(update_location_id) { var current_locations = $("#location_id option").length; if (current_locations >= allowed_locations) { var alertstr = "You have exceeded your subscripiton limit of " + allowed_locations + " locations. "; alertstr += 'Email support@calendarwiz.com for more locations.'; alert(alertstr); return false; } var location_name = escape($("#location_name").val()); if (location_name == '') { alert("Please enter a Location Name."); return false; } var location_street = escape($("#location_street").val()); var location_city = escape($("#location_city").val()); var location_stateprovince = escape($("#location_stateprovince").val()); var location_zippostal = escape($("#location_zippostal").val()); var location_country = escape($("#location_country").val()); var theurl = "calendars/ajax/save_location_from_editor.php?crd=" + gCalendar; theurl += "&location_id=" + update_location_id; theurl += "&location_name=" + location_name; theurl += "&location_street=" + location_street; theurl += "&location_city=" + location_city; theurl += "&location_stateprovince=" + location_stateprovince; theurl += "&location_zippostal=" + location_zippostal; theurl += "&location_country=" + location_country; theurl += "&PHPSESSID=" + gPHPSESSID; //$("#locmsg, #locmsgbottom").hide(); $("#pleasewait").show(); // ASYNC FALSE NOT WORKING IN FIREFOX, CAUSING ADDLOCATION TO FAIL // MAY HAVE SOMETHING TO DO WITH XHOOK? //$.ajaxSetup({async: false}); // Do post to save the location $.getJSON(theurl, function(data){ //$.ajaxSetup({async: true}); if (data.status.code == 200) { $("#pleasewait").hide(); // Get info for new location var location_id = data.locationdetails.location_id; var location_name = unescape(data.locationdetails.location_name); if (update_location_id != 0) { // ---------------------------------------- // UPDATED: Update location name in select // ---------------------------------------- $('#location_id').find('option[value="' + location_id + '"]').text(location_name); $('#location_id').val(location_id); } else { // ----------------------------------------------- // ADDED: Insert new location into location select // ----------------------------------------------- // Insert new location into locations select options in alpha order // Note value != 0 is for first 'Select From...' dummy option var numsavedlocoptions = $('#location_id option').length; if (numsavedlocoptions == 1) { // This is first saved location so just append $('#location_id').append(''); $('#location_id').val(location_id); } else { // Already one or more saved locations so insert in alphabetic order or to end var locoptioncount = 0; $('#location_id option').each(function() { locoptioncount++; if (locoptioncount == numsavedlocoptions){ // Just append to end $('#location_id').append(''); $('#location_id').val(location_id); return false; } else if ((this.text.toLowerCase() > location_name.toLowerCase()) && (this.value != 0)) { // Insert in alpha order $(this).before(''); $('#location_id').val(location_id); return false; } }); } } // Show brief success message - this div is defined in header.inc.php if (data.locationdetails.result == 'added') { // Added saved location if($("#locmsg").is(":visible")){ $("#locmsg").html('Location Added Successfully').show().delay(4000).fadeOut(); } else { $("#locmsgbottom").html('Location Added Successfully.
You May Now Proceed.
').show().delay(4000).fadeOut(); } } else { // Updated saved location if($("#locmsg").is(":visible")){ $("#locmsg").html('Location Updated Successfully').show().delay(4000).fadeOut(); } else { $("#locmsgbottom").html('Location Updated Successfully.
You May Now Proceed.
').show().delay(4000).fadeOut(); } } numsavedlocoptions++; //----------------------------- // Update mirror locations list //----------------------------- /* // Build item html var mirrorlochtml = '
'; mirrorlochtml += ' ' + location_name + '
'; // Insert item into mirror locations list var nummirrorlocoptions = $('#mirrorloc_dialog .mirrorlocitem').length; if (nummirrorlocoptions == 1) { // This is first saved location so just append $('#mirrorloc_dialog').append(mirrorlochtml); } else { // Already one or more saved locations so insert in alphabetic order or to end var mirrorlocoptioncount = 0; $('#mirrorloc_dialog .mirrorlocitem').each(function() { mirrorlocoptioncount++; if (mirrorlocoptioncount == nummirrorlocoptions){ // Just append to end $('#mirrorloc_dialog').append(mirrorlochtml); return false; } else if ($(this).find(".mirrorlocname").text().toLowerCase().trim() > location_name.toLowerCase()) { // Insert in alpha order $(this).before(mirrorlochtml); return false; } }); } $("#mlocid_" + location_id).uniform(); $.uniform.update("#mlocid_" + location_id); hidemirrorloc(); // Show mirror locations select button if more than two saved locations if (numsavedlocoptions > 2) { $("#mirrorlocdiv").show(); $("#mirrorloctoofew").hide(); } */ } else { // Something went wrong alert(data.status.msg); } }); } //####################### Monthly Calendar ################################## function disabledDates(date){ //here we need to see if the date is already here. If not we need to get it if(ajaxActive) return cwCal.FETCHING; if(monthEvents == undefined ){ //we need to get events from calendarwiz //alert(cal.date); getMonthEvents(gCalendar, cal.date); return cwCal.FETCHING; } else{ if(monthEvents[cal.dateToInt(date)] == undefined){ return cwCal.DISABLED; } else{ return cwCal.ENABLED; } } } function selectedDate(e){ var jCell = $(e.target); if (typeof(jCell[0].date) == 'undefined') { var jCell = $(e.currentTarget); if (typeof(jCell[0].date) == 'undefined') { var jCell = $(e.target).closest("td"); if (typeof(jCell[0].date) == 'undefined') { return false; } } } $(cal.grid).hide(); jPleaseWait.show(); getDayEvents(gCalendar, jCell[0].date); } var cwCal = function(grid, disabledDates, selectedDate, clearCache, pleaseWait){ this.grid = grid; this.date = null; this.disabledDates = disabledDates; this.selectedDate = selectedDate; this.clearCache = clearCache; this.pleasewait = $("#" + pleaseWait)[0]; var that = this; this.navMonth = function(e){ $(that.pleasewait).show(); if(typeof(e) == "string"){ var direction = e; }else{ direction = e.target.id } if(direction.match(/next/i)){ //alert(that.date.getMonth()); //alert(that.date); // Bug, next line will jump from Jan to Mar when current date is greater than 28th or 29th of Jan // depending on if Feb has 28 or 29 days - may affect other months where following month has fewer days than current day //that.date.setMonth(that.date.getMonth() + 1); // This is fix for above problem var middate = new Date(that.date.getFullYear(),that.date.getMonth(),15,0,0,0,0); middate.setMonth(middate.getMonth() + 1); that.date = middate; that.render(that.date); } else{ that.date.setMonth(that.date.getMonth() - 1); that.render(that.date); } } $(".nav").bind("click", this.navMonth); this.dateToInt = function(date){ var month = date.getMonth() + 1; if(month < 10){ month = "0" + month; } else{ month = month.toString(); } var day = date.getDate(); if(day < 10){ day = "0" + day; } else{ day = day.toString(); } return parseInt(date.getFullYear().toString() + month + day); } }; cwCal.months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; cwCal.days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; cwCal.ENABLED = 1; cwCal.DISABLED = 0; cwCal.FETCHING = -1; cwCal.prototype.render = function(date, preserveCache){ gCameFromMonth = true; if(!preserveCache){ clearCache(); } if(date == undefined){ this.date = new Date(); } else{ this.date = date; } var today = new Date(); var todaydom = today.getDate(); var todaymonth = today.getMonth(); var todayyear = today.getFullYear(); var initmonth = this.date.getMonth(); $("#month").text(dateFormat.i18n.monthNames[initmonth + 12] + " " + this.date.getFullYear()); var start = new Date(this.date); var startmonth = start.getMonth(); start.setDate(1); var dow = start.getDay(); start.setDate(start.getDate() - dow); for(var i = 2; i < 8; i++){ for(var j = 0; j < 7; j++){ var dom = start.getDate(); var moy = start.getMonth(); var cell = this.grid.rows[i].cells[j]; var jCell = $(cell); // Unbind click event, otherwise multiple bind occur // on the jCell causing mutiple request to the server jCell.unbind("click"); cell.innerHTML = dom; cell.className = ""; if((dom == todaydom) && (todaymonth == moy) && (todayyear == start.getFullYear())){ cell.className = "today "; } else if(moy != startmonth){ cell.className = "offmonth "; } if(j == 0 || j == 6){ cell.className += "weekend "; } var dateStatus = this.disabledDates(start); cell.date = new Date(start); jCell.bind("click", this.selectedDate); if(dateStatus == cwCal.DISABLED){ cell.className += "disabled"; cell.innerHTML += "
 
"; }else if(dateStatus == cwCal.ENABLED){ cell.className += "enabled"; cell.innerHTML +="
 
"; } else{ break; } start.setDate(dom + 1); } if(dateStatus == cwCal.FETCHING)break; } for(j = 0; j < 7; j++){ this.grid.rows[1].cells[j].innerHTML = cwCal.days[j]; } if(preserveCache){ $(this.pleasewait).hide(); $(this.grid).show(); } } // ------------------------------------ // CONTROLS CONTEXT FUNCTIONS // ------------------------------------ // Master function to set controls states depending on repeat // type selected on page load or user selection function initControls(){ enablerptchoices(); enableweekdays(); enablerptdate(); enablerptfields(); if(cw_jsonStatus.view == "a"){ $("#deleteButton").hide(); $("#deleteButtonTop").hide(); } else{ $("#deleteButton").show(); $("#deleteButtonTop").show(); } } function docontrols() { // Single occurrence of repeating event if (document.eventform.edittype.value == "single") { disablerptchoices(); disablerptdate(); disablerptfields(); disableweekdays(); donoenddate(); return; } // No repeating event if (document.eventform.rpt_type.selectedIndex == 0) { // No repeats disablerptdate(); disablerptfields(); disableweekdays(); clearweekdays(); donoenddate(); disablerptdate(); } // Repeat options below if (document.eventform.rpt_type.selectedIndex == 1) { // Daily disablerptfields(); disableweekdays(); clearweekdays(); donoenddate(); } if (document.eventform.rpt_type.selectedIndex == 2){ // Once Every # Days disableweekdays(); clearweekdays(); disablerptfields(); document.eventform.rpt_days.disabled = false; $("#rpt_days").show(); donoenddate(); $(document.eventform.rpt_type.options[2]).text("Every..."); } else{ $(document.eventform.rpt_type.options[2]).text("Every # days"); } if (document.eventform.rpt_type.selectedIndex == 3){ // Every # weeks by day disablerptfields(); enableweekdays(); document.eventform.rpt_weeks.disabled = false; $("#rpt_weeks").show(); donoenddate(); $(document.eventform.rpt_type.options[3]).text("Every..."); } else{ $(document.eventform.rpt_type.options[3]).text("Every # weeks"); } if (document.eventform.rpt_type.selectedIndex == 4) { // Monthly by day disablerptfields(); enableweekdays(); document.eventform.rpt_month_place.disabled = false; $("#rpt_month_place").show(); donoenddate(); } if (document.eventform.rpt_type.selectedIndex == 5) { // Monthly by date disablerptfields(); disableweekdays(); clearweekdays(); donoenddate(); } if (document.eventform.rpt_type.selectedIndex == 6) { // Yearly by date disablerptfields(); disableweekdays(); clearweekdays(); donoenddate(); } //weeksDaysUpdate(); return; } // Additional Controls Context Function Called By docontrols // Disable repeat fields function disablerptfields() { document.eventform.rpt_weeks.disabled=true; $("#rpt_weeks").hide(); document.eventform.rpt_days.disabled=true; $("#rpt_days").hide(); document.eventform.rpt_month_place.disabled=true; $("#rpt_month_place").hide(); } // Enable repeat fields - for posting function enablerptfields() { document.eventform.rpt_weeks.disabled=false; $("#rpt_weeks").show(); document.eventform.rpt_days.disabled=false; $("#rpt_days").show(); document.eventform.rpt_month_place.disabled=false; $("#rpt_month_place").show(); } // Disable repeat date function disablerptdate() { document.eventform.rpt_end_day.disabled=true; document.eventform.rpt_end_month.disabled=true; document.eventform.rpt_end_year.disabled=true; $("#enddate").hide(); } // Enable repeat date function enablerptdate() { document.eventform.rpt_end_day.disabled=false; document.eventform.rpt_end_month.disabled=false; document.eventform.rpt_end_year.disabled=false; $("#enddate").show(); } //Disable weekdays function disableweekdays() { // Disable check boxes document.eventform.rpt_sun.disabled=true; document.eventform.rpt_mon.disabled=true; document.eventform.rpt_tue.disabled=true; document.eventform.rpt_wed.disabled=true; document.eventform.rpt_thu.disabled=true; document.eventform.rpt_fri.disabled=true; document.eventform.rpt_sat.disabled=true; $("#selectbydays").hide(); } // Enable weekdays function enableweekdays() { document.eventform.rpt_sun.disabled=false; document.eventform.rpt_mon.disabled=false; document.eventform.rpt_tue.disabled=false; document.eventform.rpt_wed.disabled=false; document.eventform.rpt_thu.disabled=false; document.eventform.rpt_fri.disabled=false; document.eventform.rpt_sat.disabled=false; $("#selectbydays").show(); } // Clear weekdays function clearweekdays () { document.eventform.rpt_sun.checked=false; document.eventform.rpt_mon.checked=false; document.eventform.rpt_tue.checked=false; document.eventform.rpt_wed.checked=false; document.eventform.rpt_thu.checked=false; document.eventform.rpt_fri.checked=false; document.eventform.rpt_sat.checked=false; } // Disable all repeat choices function disablerptchoices() { document.eventform.rpt_type.disabled=true; } // Enable all repeat choices function enablerptchoices() { document.eventform.rpt_type.disabled=false; } // Process click on allday checkbox function doallday() { if (document.eventform.allday.checked) { document.eventform.noend.checked = false; disabletimes(); return; } else if (!document.eventform.noend.checked) { enabletimes(); return; } } // Process click on noend (time) checkbox function donoend() { if (document.eventform.noend.checked) { document.eventform.allday.checked = false; document.eventform.endhour.disabled = true; document.eventform.endminute.disabled = true; if (document.eventform.endampm) { document.eventform.endampm.disabled = true; } document.eventform.starthour.disabled = false; document.eventform.startminute.disabled = false; if (document.eventform.startampm) { document.eventform.startampm.disabled = false; } return; } else if (!document.eventform.allday.checked) { enabletimes(); return; } } // Process change to no end date checkbox function donoenddate() { // If editing single occurrence of repeating event if (document.eventform.edittype.value == "single") { document.eventform.rpt_noenddate.disabled = true; $("#noenddate").hide(); return; } // If yearly repeats not checked then disable if (document.eventform.rpt_type.selectedIndex != 6) { document.eventform.rpt_noenddate.checked = false; document.eventform.rpt_noenddate.disabled = true; $("#noenddate").hide(); } else { //yearly repeats is checked document.eventform.rpt_noenddate.disabled = false; $("#noenddate").show(); } if (document.eventform.rpt_noenddate.checked) { disablerptdate(); } else { enablerptdate(); } } function disabletimes() { document.eventform.starthour.disabled = true; document.eventform.startminute.disabled = true; if (document.eventform.startampm) { document.eventform.startampm.disabled = true; } document.eventform.endhour.disabled = true; document.eventform.endminute.disabled = true; if (document.eventform.endampm) { document.eventform.endampm.disabled = true; } } function enabletimes() { document.eventform.starthour.disabled = false; document.eventform.startminute.disabled = false; if (document.eventform.startampm) { document.eventform.startampm.disabled = false; } document.eventform.endhour.disabled = false; document.eventform.endminute.disabled = false; if (document.eventform.endampm) { document.eventform.endampm.disabled = false; } } // ------------------------------------ // END CONTROLS CONTEXT FUNCTIONS // ------------------------------------ endDateIsDirty = false; // Init, used by doDateSync function // Function to sync start and end dates when banners on function doDateSync(e) { var targetId = e.target.id; // Make sure start date is before End Date (single event or banner end date) var startday = Number(document.eventform.eday.value); var startmonth = Number(document.eventform.emonth.value); var startyear = Number(document.eventform.eyear.value); var starthour = Number(document.eventform.starthour.value); var startminute = Number(document.eventform.startminute.value); var endday = Number(document.eventform.end_eday.value); var endmonth = Number(document.eventform.end_emonth.value); var endyear = Number(document.eventform.end_eyear.value); var endhour = Number(document.eventform.endhour.value); var endminute = Number(document.eventform.endminute.value); var starttimestamp = new Date(startyear,startmonth,startday); var endtimestamp = new Date(endyear,endmonth,endday); if (starttimestamp != endtimestamp) { if ((targetId == 'eday') || (targetId == 'emonth') || (targetId == 'eyear')) { var startDateChanged = true; } else if ((targetId == 'end_eday') || (targetId == 'end_emonth') || (targetId == 'end_eyear')) { var endDateChanged = true; endDateIsDirty = true; } if ((startDateChanged) && (!endDateIsDirty)) { $("#end_eday").val(startday); $("#end_emonth").val(startmonth); $("#end_eyear").val(startyear); // Scratch //$("#end_eday").val(dateFormat(new Date((parseInt(starttimestamp) + 3600*parseFloat(gtzoffsetnodst)) * 1000), "d")); // $("#end_emonth").val(dateFormat(tsToDate(cw_event, "starttimestamp", "start_tzoffset"), "m")); // $("#end_eyear").val(dateFormat(tsToDate(cw_event, "starttimestamp", "start_tzoffset"), "yyyy")); //new Date((parseInt(cw_event[tsPropertyName]) + 3600*parseFloat(cw_event[timeZoneOffsetPropertyName])) * 1000) return; } } } /* function enableall() { document.chooseedit.btneditthis.disabled=true; document.chooseedit.btneditall.disabled=false; } function enablethis() { document.chooseedit.btneditthis.disabled=false; document.chooseedit.btneditall.disabled=true; } */ // Utility function to display validation message function cwscroll (positionselector) { var offset = $(positionselector).offset(); $('html,body').animate({ scrollTop: offset.top - 100 }, { duration: 'slow', easing: 'swing'}); } function validate() { // -------------------------------------------------------- // Dates and Times Validation // -------------------------------------------------------- // Check text fields //var value = document.eventform.title.value; var value = $("#title").val(); if (value == "") { document.eventform.title.focus(); alert("Please enter an event Title"); return false; } // Check that category was selected var value = document.eventform.category_id.value; if (value == "0") { document.eventform.category_id.focus(); alert("Please select a Category."); return false; } var isMilitaryTime = !$("#startampm").is(":visible"); // If startam field visible then NOT military if (gbanners_on == '1') { // ----------- // BANNERS ON // ----------- // Get date and time vars var startday = Number(document.eventform.eday.value); var startmonth = Number(document.eventform.emonth.value); var startyear = Number(document.eventform.eyear.value); var starthour = Number(document.eventform.starthour.value); var startminute = Number(document.eventform.startminute.value); var endday = Number(document.eventform.end_eday.value); var endmonth = Number(document.eventform.end_emonth.value); var endyear = Number(document.eventform.end_eyear.value); var endhour = Number(document.eventform.endhour.value); var endminute = Number(document.eventform.endminute.value); if (!isMilitaryTime) { // If not military or 24 hour format // Need to convert to 24 hour format var startampm = document.eventform.startampm.value; var endampm = document.eventform.endampm.value; // Convert start hour to military time if ((startampm == "am") && (starthour == 12)) { starthour = starthour - 12; } else if ((startampm == "pm") && (starthour != 12)) { starthour = starthour + 12; } // Convert end hour to military time if ((endampm == "am") && (endhour == 12)) { endhour = endhour - 12; } else if ((endampm == "pm") && (endhour != 12)) { endhour = endhour + 12; } } else { var startampm = ""; var endampm = ""; } // Get just date timestamps not times var startdaytimestamp = new Date(startyear,startmonth,startday); var enddaytimestamp = new Date(endyear,endmonth,endday); // If overnight shift then make end on next day if ((starthour >= 12) && (endhour < 12)) { var tendstamp = enddaytimestamp.getTime() + (1 * 24 * 60 * 60 * 1000); enddaytimestamp.setTime(tendstamp); } // Make sure end date not before start date if (enddaytimestamp < startdaytimestamp) { cwscroll ("#eday"); alert("Start Date is after End Date"); return false; } // Get number of days spanned var days_span = ((enddaytimestamp - startdaytimestamp) / 86400000) + 1; // Get days spanned by event //console.log(days_span); if (days_span == 1) { // if not banner event if ((document.eventform.noend.checked == false) && (document.eventform.allday.checked == false)) { // Not banner and not allday or not end so need to check event times // Get start and end timestamps including times var starttimetimestamp = new Date(startyear,startmonth,startday,starthour,startminute); var endtimetimestamp = new Date(endyear,endmonth,endday,endhour,endminute); // Make sure single day / non banner event start time not equal or after end time if (endtimetimestamp <= starttimetimestamp) { cwscroll ("#starthour"); alert("Start Time is equal or after End Time"); return false; } } } else { // If banner event // Is banner event so check not exceeding maximum days span // Check the date range, 86400000 is the number of milliseconds in one day //var ban_days_back = 90; var ban_days_back = ""; if (days_span > ban_days_back) { cwscroll ("#eyear"); alert("Individual events cannot span more than " + ban_days_back + " days."); return false; } } } else { // BANNERS OFF // Check event start time is before end time on a day // Modified to skip pm to am event times to allow // events starting at say 11:00pm and ending at 2:00am // the next day. veday = Number(document.eventform.eday.value); vemonth = Number(document.eventform.emonth.value) - 1; // Months are 0-11 in javascript veyear = Number(document.eventform.eyear.value); vstarthour = Number(document.eventform.starthour.value); vstartminute = Number(document.eventform.startminute.value); vendhour = Number(document.eventform.endhour.value); vendminute = Number(document.eventform.endminute.value); //console.log(isMilitaryTime); if (!isMilitaryTime) { vstartampm = document.eventform.startampm.value; vendampm = document.eventform.endampm.value; //console.log('not military'); // Convert start hour to military time if ((vstartampm == "am") && (vstarthour == 12)) { vstarthour = vstarthour - 12; } else if ((vstartampm == "pm") && (vstarthour != 12)) { vstarthour = vstarthour + 12; } // Convert end hour to military time if ((vendampm == "am") && (vendhour == 12)) { vendhour = vendhour - 12; } else if ((vendampm == "pm") && (vendhour != 12)) { vendhour = vendhour + 12; } } vstartstamp = new Date(veyear,vemonth,veday,vstarthour,vstartminute,0); vendstamp = new Date(veyear,vemonth,veday,vendhour,vendminute,0); //console.log(vstarthour); //console.log(vendhour); // If overnight shift then make end on next day if ((vstarthour >= 12) && (vendhour < 12)) { var tendstamp = vendstamp.getTime(); tendstamp = tendstamp + (1 * 24 * 60 * 60 * 1000); vendstamp.setTime(tendstamp); } //console.log(vstartstamp); //console.log(vendstamp); if ((document.eventform.noend.checked == false) && (document.eventform.allday.checked == false)) { // Skip if no end time or allday if (vstartstamp.getTime() >= vendstamp.getTime()) { //document.eventform.starthour.focus(); alert("Start Time is equal to or after End Time"); return false; } } } // If repeating and not editing single occurrence, check start date is before end date if ((!document.eventform.rpt_type.selectedIndex == 0) && (document.eventform.edittype.value != "single") && (!document.eventform.rpt_noenddate.checked)) { var startday = Number(document.eventform.eday.value); var startmonth = Number(document.eventform.emonth.value) - 1; var startyear = Number(document.eventform.eyear.value); var starthour = Number(document.eventform.starthour.value); var startminute = Number(document.eventform.startminute.value); var rptendday = Number(document.eventform.rpt_end_day.value); var rptendmonth = Number(document.eventform.rpt_end_month.value) - 1; var rptendyear = Number(document.eventform.rpt_end_year.value); var endhour = Number(document.eventform.endhour.value); var endminute = Number(document.eventform.endminute.value); var starttimestamp = new Date(startyear,startmonth,startday); var rptendtimestamp = new Date(rptendyear,rptendmonth,rptendday); if (starttimestamp >= rptendtimestamp) { //document.eventform.rpt_end_month.focus(); alert("Start Date is equal to or later than Repeat End Date"); return false; } } // For applicable options, maker sure day of week(s) are checked if ((document.eventform.rpt_type.selectedIndex == 3) || (document.eventform.rpt_type.selectedIndex == 4)) { var nd = 0; if (document.eventform.rpt_sun.checked) { nd++; } if (document.eventform.rpt_mon.checked) { nd++; } if (document.eventform.rpt_tue.checked) { nd++; } if (document.eventform.rpt_wed.checked) { nd++; } if (document.eventform.rpt_thu.checked) { nd++; } if (document.eventform.rpt_fri.checked) { nd++; } if (document.eventform.rpt_sat.checked) { nd++; } if (nd == 0) { alert("Please select days of week to complete repeating event."); return false; } } return true; } function weeksDaysUpdate(){ var weeks = $("#rpt_weeks").val(); if(weeks == "1"){ weeks = "week"; } else{ weeks = weeks + " weeks"; } $("#rpt_type option:eq(3)").text("Every " + weeks + " on these days"); var days = $("#rpt_days").val(); if(days == "2"){ days = "other day"; } else{ days = days + " days"; } $("#rpt_type option:eq(2)").text("Every " + days); } /* * Date Format 1.2.3 * (c) 2007-2009 Steven Levithan * MIT license * * Includes enhancements by Scott Trenda * and Kris Kowal * * Accepts a date, a mask, or a date and a mask. * Returns a formatted version of the given date. * The date defaults to the current date/time. * The mask defaults to dateFormat.masks.default. */ function pad(val, len) { val = String(val); len = len || 2; while (val.length < len) val = "0" + val; return val; }; var dateFormat = function () { var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g, timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g, timezoneClip = /[^-+\dA-Z]/g; // Regexes and supporting functions are cached through closure return function (date, mask, utc) { var dF = dateFormat; // You can't provide utc if you skip other args (use the "UTC:" mask prefix) if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) { mask = date; date = undefined; } // Passing date through Date applies Date.parse, if necessary date = date ? new Date(date) : new Date; if (isNaN(date)) throw SyntaxError("invalid date"); mask = String(dF.masks[mask] || mask || dF.masks["default"]); // Allow setting the utc argument via the mask if (mask.slice(0, 4) == "UTC:") { mask = mask.slice(4); utc = true; } var _ = utc ? "getUTC" : "get", d = date[_ + "Date"](), D = date[_ + "Day"](), m = date[_ + "Month"](), y = date[_ + "FullYear"](), H = date[_ + "Hours"](), M = date[_ + "Minutes"](), s = date[_ + "Seconds"](), L = date[_ + "Milliseconds"](), o = utc ? 0 : date.getTimezoneOffset(), flags = { d: d, dd: pad(d), ddd: dF.i18n.dayNames[D], dddd: dF.i18n.dayNames[D + 7], m: m + 1, mm: pad(m + 1), mmm: dF.i18n.monthNames[m], mmmm: dF.i18n.monthNames[m + 12], yy: String(y).slice(2), yyyy: y, h: H % 12 || 12, hh: pad(H % 12 || 12), H: H, HH: pad(H), M: M, MM: pad(M), s: s, ss: pad(s), l: pad(L, 3), L: pad(L > 99 ? Math.round(L / 10) : L), t: H < 12 ? "a" : "p", tt: H < 12 ? "am" : "pm", T: H < 12 ? "A" : "P", TT: H < 12 ? "AM" : "PM", Z: utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""), o: (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4), S: ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10] }; return mask.replace(token, function ($0) { return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1); }); }; }(); // Some common format strings dateFormat.masks = { "default": "ddd mmm dd yyyy HH:MM:ss", shortDate: "m/d/yy", mediumDate: "mmm d, yyyy", longDate: "mmmm d, yyyy", fullDate: "dddd, mmmm d, yyyy", shortTime: "h:MM TT", mediumTime: "h:MM:ss TT", longTime: "h:MM:ss TT Z", isoDate: "yyyy-mm-dd", isoTime: "HH:MM:ss", isoDateTime: "yyyy-mm-dd'T'HH:MM:ss", isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'" }; // Internationalization strings dateFormat.i18n = { dayNames: [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ], monthNames: [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ] }; dateFormat.daysInMonth = [0,31,28,31,30,31,30,31,31,30,31,30,31]; // For convenience... Date.prototype.format = function (mask, utc) { return dateFormat(this, mask, utc); }; function debug(txt){ $("#debug").text($("#debug").text() + " " + txt); } /** * jQuery Plugin to obtain touch gestures from iPhone, iPod Touch and iPad, should also work with Android mobile phones (not tested yet!) * Common usage: wipe images (left and right to show the previous or next image) * * @author Andreas Waltl, netCU Internetagentur (http://www.netcu.de) * @version 1.1.1 (9th December 2010) - fix bug (older IE's had problems) * @version 1.1 (1st September 2010) - support wipe up and wipe down * @version 1.0 (15th July 2010) * THIS MODIFIED BY DWM 161031 TO FIX INCORRECT SWIPE RIGHT WHEN DAY VIEW WITH * LONG LIST OF EVENTS WHEN SLIGHT DIAGONAL IN SWIPE DOWN CAUSING SWIPE ON X AXIS */ (function($) { $.fn.touchwipe = function(settings) { var config = { min_move_x: 75, min_move_y: 75, wipeLeft: function() { }, wipeRight: function() { }, wipeUp: function() { }, wipeDown: function() { }, preventDefaultEvents: true }; if (settings) $.extend(config, settings); this.each(function() { var startX; var startY; var isMoving = false; var wasWipe = false; var target; function cancelTouch() { this.removeEventListener('touchmove', onTouchMove); isMoving = false; wasWipe = true; } function wipeX(dx) { wasWipe = true; cancelTouch(); if(dx > 0) { config.wipeLeft(); } else { config.wipeRight(); } } function wipeY(dy) { wasWipe = true; cancelTouch(); if(dy > 0) { config.wipeDown(); } else { config.wipeUp(); } } function onTouchMove(e) { if(config.preventDefaultEvents) { e.preventDefault(); } if(isMoving) { var x = e.touches[0].pageX; //var y = e.touches[0].pageY; //var x = e.touches[0].screenX; //var y = e.touches[0].screenY; //var x = e.touches[0].clientX; var y = e.touches[0].clientY; //var scrx = e.touches[0].screenX; //var scry = e.touches[0].screenY; var dx = startX - x; var dy = startY - y; var dxabs = Math.abs(dx); var dyabs = Math.abs(dy); //alert('dabsx:'+dxabs+' dabsy:'+dyabs); //alert('scrx:'+scrx+' scry:'+scry); //$(".touchdata").html('dabsx:'+dxabs+' dabsy:'+dyabs); if (dxabs >= config.min_move_x) { var dxmax = true; } else { var dxmax = false; } if (dyabs >= config.min_move_y) { var dymax = true; } else { var dymax = false; } if ((dxmax) && (dymax)) { if (dxabs > dyabs) { wipeX(dx); } else { wipeY(dy); } } else if (dxmax) { wipeX(dx); } else if (dymax) { wipeY(dy); } // Original code as of 161031 // if(Math.abs(dx) >= config.min_move_x) { // wasWipe = true; // cancelTouch(); // if(dx > 0) { // config.wipeLeft(); // } // else { // config.wipeRight(); // } // } // else if(config.wipeDown && (Math.abs(dy) >= config.min_move_y)) { // wasWipe = true; // cancelTouch(); // if(dy > 0) { // config.wipeDown(); // } // else { // config.wipeUp(); // } // } } } function onTouchEnd(e){ if(!wasWipe){ config.click({target:target}); } this.removeEventListener('touchend', onTouchEnd); } function onTouchStart(e) { if (e.touches.length == 1) { startX = e.touches[0].pageX; //startY = e.touches[0].pageY; startY = e.touches[0].clientY; target = e.touches[0].target; isMoving = true; wasWipe = false; this.addEventListener('touchmove', onTouchMove, false); if(config.click){ this.addEventListener('touchend', onTouchEnd, false); } } } if ('ontouchstart' in document.documentElement) { this.addEventListener('touchstart', onTouchStart, false); } }); return this; }; })(jQuery); $(init);