var chartOptions = null; var chartData = null; var prodKey = "Dyd7kC4wxLDFz0rQ6W5T28DPgrM6SOBe"; var client_secret = "4b60ff23b1d9d8336a22b3dc9467ca3c"; var client_id = "lacrosse_api_user"; var userSKey = null; var urlLoc = window.location.protocol + "//" + window.location.host; var hashLoc = window.location.hash; var serviceURL = window.location.protocol + "//decent-destiny-704.appspot.com/laxservices/"; //var serviceURL = "https://la-crosse-alerts.uc.r.appspot.com/laxservices/"; var firstRun = 0; var askOnRefresh = false; var myLineChart = {}; var devData = {}; if ( urlLoc.indexOf("localhost") > -1 ) var serviceURL = window.location.protocol + "//" + window.location.host + "/laxservices/"; else if ( urlLoc.indexOf("2.decent-destiny") > -1 ) var serviceURL = window.location.protocol + "//2.decent-destiny-704.appspot.com/laxservices/"; // This is horrible use of a variable. need to figure it out later var tempSensor = null; // Code from other account.js page var myScroll; var state = null; // Need to load this fast and not wait for the 288 values function initDataTable(refresh) { if (refresh == true) { //Go get up to date readings var dataString = "pkey=Dyd7kC4wxLDFz0rQ6W5T28DPgrM6SOBe&ref=" + userSKey + "&action=refreshdeviceinfo"; $.ajax({ type: "GET", url: serviceURL + "user-api.php", data: dataString, success: function(response) { udevicesInitData = response; for (var key in udevicesInitData) { if ( udevicesInitData[key].obs ) { if ( udevicesInitData[key].ispws ) updatePWSPanel( udevicesInitData[key] ); else updateDataPanel( udevicesInitData[key] ); } } }, error: function () { //should add some kind of not up to date warning here }}); } else { // We are not getting new data, just making the page with whatever we already have. for (var key in devicesInitData) { if ( devicesInitData[key].obs ) { if ( devicesInitData[key].ispws ) updatePWSPanel( devicesInitData[key] ); else updateDataPanel( devicesInitData[key] ); } } } } // init all charts at once function initChart( fullRefresh ) { var allDevId = ""; $('div.device-chart').each(function(){ var $this = $(this); var deviceId = $this.data("id"); allDevId = allDevId + deviceId + "-"; var chartContainer = $("#device-" + deviceId + "-charts .charts-container").first(); chartContainer.spin('medium'); }); limit = 288; // Setup Charts - need to figure this out so it doesnt have to grab data on device orientation change getChartData( allDevId.substring(0, allDevId.length - 1), limit ); } //Get remote data from the server, makes a spinner while we wait for data. This will cache data to the sensorData variable. function getChartData(deviceId, limit) { acceptables = [288,2100,10000]; // approx 1 day/week/month(all) worth of 5 minute intervals, faster select statment than calculating date. $("#chartDiv-" + deviceId).css("opacity", ".25"); $("#chartDiv-" + deviceId).spin("medium"); // Do we have the data we need already? if(!devData[deviceId] || //no data ( devData[deviceId] && devData[deviceId]['obs'] && devData[deviceId]['obs'].length < limit && //we have data, but do we have enough acceptables.indexOf(devData[deviceId]['obs'].length) !== -1 //We probably have all the records if its not one of those 3 )) { var queryString = "deviceid=" + deviceId + "&limit=" + limit + "&timezone=" + timezone + "&metric=" + isMetric; $.ajax({ type: "GET", url: serviceURL + "device_info.php?", data:queryString, dataType: "json", cache: true, success: function(msg) { for (var dev in msg) { thisdevid = msg[dev].device_id; devData[thisdevid] = msg[dev]; if (limit = 288) updateTable( msg[dev] ); } processDeviceInfo(msg); } }); } else { var device = {}; device.device0 = devData[deviceId]; processDeviceInfo(device); } }; function processDeviceInfo( msg ) { for (var device in msg) { if( msg[device] && msg[device].success) { msg.device0 = msg[device]; var deviceId = msg.device0.device_id; var pws = false; if (deviceId.charAt(0) == "7") { pws = true; } msg.device0.isMetric = isMetric; //Graph variable setup var timeData = new Array(); var line2 = new Array(); var line1 = new Array(); var line3 = new Array(); var line4 = new Array(); var deviceType = msg.device0.device_type; // The next two variables help UI / UX based on screen sizes // Divisor is how we deal with number of points. // split value is if we need to chop up that date. var divisor = 1; var splitValue = ( msg.device0.obs[0].timestamp ).indexOf(" ") + 1; // used to give appropriate scale to data and k for last point var length = msg.device0.obs.length - 1; if (pws) { deviceType = "pws"; var time = $(".chartnavtimerow-" + deviceId + " .disabled").data("id"); var type = $(".chartnavtyperow-" + deviceId + " .disabled").data("id"); if (!type) type = "t"; var reqData = {}; switch (type) { //What graph are we displaying case "t": reqData.L1 = "IndoorTemp"; reqData.L2 = "OutdoorTemp"; reqData.L3 = "OutdoorHumid"; reqData.L4 = "IndoorHumid"; break case "p": reqData.L1 = "Pressure"; break case "r": reqData.L1 = "Rain1hr"; reqData.L2 = "Rain24hr"; reqData.L3 = "RainWeek"; break; } var seconds = 86400; switch (time){ case "m": seconds = 2764800; $('#timeLabel-' + deviceId).html("
Last Month
"); break; case "w": seconds = 604800; $('#timeLabel-' + deviceId).html("
Last Week
"); break; case "d": $('#timeLabel-' + deviceId).html("
Last 24 hours
"); break; } var timetoget = Math.floor(Date.now() / 1000) - seconds; var gData = new Array(); //We cant actually fit thousands of records on one small chart for ( var i in msg.device0.obs) { if ( msg.device0.obs[length - i].TimeStamp > timetoget ) { gData.push(msg.device0.obs[length - i]); } } length = gData.length - 1; if ( gData.length > 50 ) divisor = gData.length / 50; for (var i in gData) { if ( !( i%divisor >= 1 )|| i == length) { //var myDate = new Date(gData[i].TimeStamp *1000); timeData.push(gData[i].timestamp ); // push based on device - should have a flag set on the first one to indicate it is Not Connected if (reqData.L1) line1.push(gData[i][reqData.L1]); if (reqData.L2) line2.push(gData[i][reqData.L2]); if (reqData.L3) line3.push(gData[i][reqData.L3]); if (reqData.L4) line4.push(gData[i][reqData.L4]); } } // Buttons disable correctly, Calls to this function with data (only calls db if it needs more) } else { var gData = new Array(); pastTime = 86400 if ($(".chartnavtimerow-" + deviceId + " .disabled").data("id") == "w") { pastTime *= 7; $('#timeLabel-' + deviceId).html("
Last Week
"); splitValue = 0; } else { $('#timeLabel-' + deviceId).html("
Last 24 hours
"); } var last24 = Math.floor(Date.now() / 1000) - pastTime; for ( var i in msg.device0.obs) { if ( msg.device0.obs[length - i].u_timestamp > last24 ) { gData.push(msg.device0.obs[length - i]); } } length = gData.length - 1; if ( gData.length > 50 ) divisor = gData.length / 50; for (var i in gData) { if ( !( i%divisor >= 1 )|| i == length) { timeData.push(( gData[i].timestamp ).substr(splitValue) ); // shows only hour:minute if day, else Day as well if week. // push based on device - should have a flag set on the first one to indicate it is Not Connected if ( gData[i].probe_temp === "N/C" ) line1.push(0); else if ( deviceType === "TX60" ) line1.push(gData[i].probe_temp); else if (gData[i].probe_temp === "Dry") line1.push(0); else line1.push(100); // only push these if we don't have a TX71 if ( deviceType !== "TX71" ) { line3.push(gData[i].humidity); line2.push(gData[i].ambient_temp); } } } } //Set up our data and options for the graph chartData = graphData (deviceType, timeData, line1, line2, line3, line4, type ); chartOptions = { legendTemplate : "", scaleLabel: "<%= ' ' + value%>", // Boolean - whether or not the chart should be responsive and resize when the browser does. responsive: false, pointDot: false, pointHitDetectionRadius: 5, showXLabels: 24 // Boolean - whether to maintain the starting aspect ratio or not when responsive, if set to false, will take up entire container //maintainAspectRatio: false }; // setup Charts and Table while we are here setupCharts( deviceId ); $("#chartDiv-" + deviceId).spin(false); $("#chartDiv-" + deviceId).css("opacity", "1"); /* commented out to prevent it from updating when its unnessecary to do so. if ( msg["device0"].ispws ) updatePWSPanel( msg[ "device0" ] ); else updateDataPanel( msg[ "device0" ] ); */ if ( isMetric > 0 ) { $(".ifTempMetric").html("Temperature from -40 to 60 °C"); $(".temperaturelabel").html("(-40 to 60 °C)"); $(".rainlabel1h").html("(0 to 305 Milimeters)"); $(".rainlabel24h").html("(0 to 1830 Milimeters)"); $(".pressurelabel").html("(930 to 1065 hPa)"); $(".windlabel").html("(0 to 45 Meters/Sec)"); } else { $(".ifTempMetric").html("Temperature from -40 to 140 °F"); $(".temperaturelabel").html("(-40 to 140 °F)"); $(".rainlabel1h").html("(0 to 12 Inches)"); $(".rainlabel24h").html("(0 to 72 Inches)"); $(".pressurelabel").html("(27.5 to 31.5 inHg)"); $(".windlabel").html("(0 to 100 MPH)"); } } } } function setupCharts( deviceId) { // Get context with jQuery - using jQuery's .get() method and assigned to line chart var ctx = $("#device-" + deviceId + "-charts [id^='chart-dy-temp']").get(0).getContext("2d"); // get the gosh darn size correct ctx.canvas.height = $("#bodyTag").height() * .65; ctx.canvas.width = $("#bodyTag").width() * .93; if (myLineChart && myLineChart[deviceId]) myLineChart[deviceId].destroy(); // Set up the chart myLineChart[deviceId] = new Chart(ctx).Line( chartData, chartOptions); // Generate legend var legend = myLineChart[deviceId].generateLegend(); document.getElementById("legendDiv-" + deviceId ).innerHTML = legend; } function graphData (sType, timeData, line1, line2, line3, line4, type) { // Create graph data object function gData(label, fColor, sColor,pSColor, pData) { this.label = label; this.fillColor = fColor; this.strokeColor = sColor; this.pointColor = sColor; this.pointStrokeColor = pSColor; this.pointHighlightFill = pSColor; this.pointHighlightStroke = sColor; this.data = pData; } // Probe Temp can have different labels dependent on Type templabel = " (°F)"; pressurelabel = " (inHg)"; rainlabel = " (in)" if (isMetric) { templabel = " (°C)"; pressurelabel = " (hPa)"; rainlabel = " (mm)" } var probeLabel = "Probe Temp" + templabel; if ( sType !== "TX60") { probeLabel = "Wet (100) / Dry (0)" } if ( sType != "pws" ) { // Create our graph variables var secondLine = new gData("Sensor" + templabel,"rgba(236, 173, 161, 0.2)","#FF5A5E","#fff",line2); var thirdLine = new gData("Humidity (%)","rgba(151,187,205,0.25)","rgba(45, 82, 226, 1)","#fff",line3); var firstLine = new gData( probeLabel, "rgba(92, 184, 92, 0.2)", "#4CAE4C", "#fff", line1); } else { label1 = ""; label2 = ""; label3 = ""; label4 = ""; switch (type){ //set label text based on what chart we are looking at (PWS) case "t": label1 = "Indoor Temperature" + templabel; label2 = "Outdoor Temperature" + templabel; label3 = "Outdoor Humidity (%)"; label4 = "Indoor Humidity (%)"; break case "p": label1 = "Pressure" + pressurelabel; break case "r": label1 = "Rain 1hr" + rainlabel; label4 = "Rain 24hr" + rainlabel; //switching order here to display labels in a better order label3 = "Rain Week" + rainlabel; line4 = line2; break; } var firstLine = new gData(label1, "rgba(92, 184, 92, 0.2)", "#00C800", "#fff", line1); var fourthLine = new gData(label2,"rgba(236, 173, 161, 0.2)","#f00","#fff",line2); //switched for order of display var thirdLine = new gData(label3,"rgba(151,187,205,0.25)","#00f","#fff",line3); var secondLine= new gData(label4, "rgba(128, 0, 128, 0.1)", "#707", "#fff", line4); } // Set up dataset to make sure labels only get passed for appropriate datasets var datasets = []; if ( sType !== "TX71" && sType !== "pws") { datasets.push(secondLine, thirdLine); } datasets.push(firstLine); if (sType == "pws") { switch (type) { case "t": datasets.push(fourthLine); case "r": datasets.push(secondLine); datasets.push(thirdLine); case "p": // FirstLine is already pushed break; } } // Create our data object and return it var data = { labels: timeData, datasets: datasets }; return data; } function checkAlert(data, alertType, alertHigh, alertLow) { if ( alertType !== "wet") { data = parseFloat(data); //Needs to be float, else 25.5 is Not greater than 25 if( alertLow !== undefined && data < alertLow && alertLow !== -100 ) return true; if( alertHigh !== undefined && data > alertHigh && alertHigh !== -100 ) return true; return false; } else { if( alertHigh !== undefined && data === "Dry" && alertHigh === 0 ) return true; if( alertHigh !== undefined && data === "Wet" && alertHigh === 1 ) return true; return false; } } function updateThermometer(deviceId, el) { var $thermometer = $("#device-"+deviceId+" .thermometer"); var $activeInput = $("#device-"+deviceId+" .data-panel li.active"); var $sensor = $activeInput.data('sensor'); var $sensorValue = $activeInput.data('sensorvalue' ); var $alertMax = ( $activeInput.attr('data-alertmax' ) != "-100" ) ? $activeInput.attr('data-alertmax' ) : ""; var $alertMin = ( $activeInput.attr('data-alertmin' ) != "-100" ) ? $activeInput.attr('data-alertmin' ) : ""; // Check for alertmax and alert min to be -100 if (el) { $activeInput = el; } var cls = ''; var flat = false; if ( $sensor === 'rh' || $sensor === 'outrh' ) { //Set Thermometer details based on type cls = 'wxn-widget-indicator-thermo-green'; flat = true; $thermometer.wxnindicatorthermo({min:0, max:100}); $thermometer.wxnindicatorthermo({labelingSystem: 'numeric'}); } else if ( $sensor === 'wet' ) { if ( $sensorValue === 'Wet' ) { $sensorValue = 1; } else { $sensorValue = 0; } cls = 'wxn-widget-indicator-thermo-wet'; flat = true; $thermometer.wxnindicatorthermo({min:0, max:1}); $thermometer.wxnindicatorthermo({labelingSystem: 'custom', labels:[[0, 'DRY', true], [1, 'WET', true]]}); } else if ($sensor && $sensor.indexOf('rain') != -1 ) { var $maxVal = $sensor.indexOf('1h') !== -1 ? (isMetric > 0 ? 305 : 12) : (isMetric > 0 ? 1830 : 72); cls = 'wxn-widget-indicator-thermo-wet'; flat = true; $thermometer.wxnindicatorthermo({min:0, max:$maxVal}); $thermometer.wxnindicatorthermo({labelingSystem: 'custom', labels:[[0, '0', true], [$maxVal, $maxVal.toString(), true]]}); } else if ( $sensor === 'pressure') { cls = 'wxn-widget-indicator-thermo-green'; flat = true; var $maxVal = isMetric > 0 ? 1065: 32 ; var $minVal = isMetric > 0 ? 930 : 27 ; $thermometer.wxnindicatorthermo({min:$minVal, max:$maxVal}); if (isMetric > 0) $thermometer.wxnindicatorthermo({labelingSystem: 'numeric'}); else { $thermometer.wxnindicatorthermo({labelingSystem: 'custom', labels:[[$minVal, $minVal.toString(), true], [$maxVal, $maxVal.toString(), true]]}); } } else { cls = ''; flat = false; $thermometer.wxnindicatorthermo({labelingSystem: 'numeric'}); $thermometer.wxnindicatorthermo({min:-20, max:isMetric > 0 ? 60 : 120}); } $thermometer.wxnindicatorthermo({'flat':flat, cls:cls}); $thermometer.wxnindicatorthermo( 'value', $sensorValue ); $thermometer.wxnindicatorthermo({indicatorIntialMove:true}); $thermometer.wxnindicatorthermo('alertHigh', $alertMax ); $thermometer.wxnindicatorthermo('alertLow', $alertMin ); $thermometer.wxnindicatorthermo('units', $activeInput.data('units')); $thermometer.wxnindicatorthermo('refresh'); } function askConfirm() { if (askOnRefresh) { // Put your custom message here EDIT: I dont think this is actually used return "Leaving/refreshing while registering will break the rest of registration."; } } jQuery(document).ready(function($){ window.onbeforeunload = askConfirm; // get session key userSKey = getCookie("uSAbc"); userSKey1 = getCookie("uSAbc1"); var platform=navigator.platform; console.log("platform"+platform); var dataString = "pkey=Dyd7kC4wxLDFz0rQ6W5T28DPgrM6SOBe"+ "&ref=" + userSKey + "&platform="+platform+"&action=updatelog"; console.log("dataString"+dataString); $.ajax({ type: "GET", url: serviceURL + "user-api.php?", data: dataString, success: function(response) { modal.style.display = "block"; }, error: function () { } }); if(userSKey1 !='') { $(".nav-panel").addClass("hidden"); $(".nav-chart").addClass("hidden"); $(".nav-table").addClass("hidden"); $(".nav-settings").addClass("hidden"); $(".charts").addClass("hidden"); $(".panels").addClass("hidden"); $(".p1").addClass("hidden"); $("#panel_header").css('display', 'none'); $('#chart_header').css('display', 'none'); userSKey=userSKey1; } if (userSKey == "" && hashLoc != "#createUser" && hashLoc != "#recoverPassword" && hashLoc != "#privacyPolicy" && hashLoc != "#termsOfUse" ) { window.location.replace(urlLoc + "/v1.2/#userLogin"); } if (jstest){ window.location.replace(urlLoc + "/v1.2/?jstest=true#test"); } // handle csv div if ( !getMobileOS() ) { $(".csvDivs").show(); } $(".cnbd").addClass("disabled"); $(".cnbt").addClass("disabled"); $("tr[class^='chartnavtimerow-0'] .cnbm").hide(); // Handle footer active states on clicks $('[data-role="footer"] a').on('click', function() { var temp = $(this).parent().attr('class').split(" ")[0] + " a"; hashLoc = temp; prepNavPanel(); }); // click on the device list sets up Panel and Thermo $('.device_list').on('click', setPanelPage ); //On clicking the message, show/hide the attatched content $('.dropDown-box').on('click', function() { $(this).siblings().toggle(500); } ); $("input[id^='setCustTimezone']").change(function() { var thisDevId= $(this).parent().parent().data('id'); if($(this).is(":checked")) { $("#customTimezone-" + thisDevId).parent().show(); $("#syncTimeSubmit-" + thisDevId).html("Set Timezone"); } else { $("#customTimezone-" + thisDevId).parent().hide(); $("#syncTimeSubmit-" + thisDevId).html("Sync Timezone"); } }); $("div[id^=chartDiv-]").css("opacity", ".25"); $("div[id^=chartDiv-]").spin("medium"); /* Dynamic Data Panel attachments*/ $('.panel').on('vclick', "[id^='device_input']" , setWidgetAndThermo ); $('.panel').on('vclick', "[id^='device_input'] .alert-indicator" , goToAlertPage ); $("#formSetup").on( 'submit' , preRegGateway ); $("#formSetup-2").on( 'submit' , associateGateway ); $(".gwLinkRegSen").on( 'vclick' , function( event ) { window.location.href = "#sensorSetup-1"; event.preventDefault(); }); //HiddenForPWS-DEVID, but since all PWS DEVID start with 7FFF, one command gets all of them, and only them. $('[class^="HiddenForPWS-7FFF"]').hide(); $("#formSensorSetup").on( 'submit' , findNewSensor ); $("#formSensorSetup-2").on( 'submit' , nameSensor ); $("#formStationSetup").on( 'submit' , findNewStation ); $("#formStationSetup-3").on( 'submit' , nameStation ); $("#formLogin").on( 'submit' , loginAction ); $("#formCreate").on( 'submit' , createAction ); $("form[id^='deleteSensor']").on( 'submit' , deleteAction ); $("#formGatewayDelete").on( 'submit' , deleteGWAction ); $("form[id^='sensorInterval']").on( 'submit' , setIntervalAction ); $("form[id^='sensorTimezoneSync']").on( 'submit' , syncPWSTimezone ); $('a[href="#devicelist"]').on( 'vclick' , homeAction ); $('a[href="#logoutLink"]').click( logoutAction ); $('a[href="#createUser"]').click( startCreateAction ); $('#newUserDiv').click( startCreateAction ); $('#userLogin-recoverpass').click( startPassRecoverAction ); $("#formRecoverPassword").on( 'submit' , recoverPasswordAction ); $("#formPhoneUpdate").on( 'submit' , updatePhoneAction ); $("#formEmailUpdate").on( 'submit' , updateEmailAction ); $("#formUnameUpdate").on( 'submit' , updateUnameAction ); $("#formTZUpdate").on( 'submit' , updateTimezoneAction ); $("#formMetricUpdate").on( 'submit' , updateMetricAction ); $("#formPasswordUpdate").on( 'submit' , updatePasswordAction ); $('#returnToLogin').click( loginReturnAction ); $('a[href="#newDeviceRefresh"]').click( function() { areYouSure("New Sensors can take from 5 to 10 minutes to load. The app should grab it automatically.", "Continue anyways with manual check? "); }); $(".settingsBack").click( prepNavPanel ); $(".deleteCurAlert").click( deleteAlertAction ); $("#weathertonson").click( updateWeatherAction ); $("#pp-content-load").click( getPPContentAction ); $("#tos-content-load").click( getTOSContentAction ); $(" form[id^='setDevName-']").on( 'submit' , setSensorNameAction ); $("form[id^='alert-']").on( 'submit' , AlertActionV2 ); $(".specialAlertNav").on('click', specialAlertNavAction) $("form[id^='special-alert-']").on( 'submit' , specialAlertAction ); $("#formStationSetup-2").on( 'submit' , updatePWSsettingsOnReg ); $("#weathertonson").click( updateWeatherAction ); $(".chartNavButton").click( chartRedraw ); initDataTable(); setTimeout( function() { initChart("iexist"); } , 100); setInterval( function() { initChart("iexist"); } , refreshInt ); setInterval( function() {initDataTable(true);}, 300000); // Refresh datapanel every 10 minutes // only look for new sensors if we are not on the login page if ( hashLoc.search("userLogin") == -1 && hashLoc.search("stationSetup") == -1) { silentFindNewSensor(); } /***Code from other account.js page**/ if($('#upsell-container').length) $('#upsell-container').button(); $(".thermometer, .text-display, #device-display-container, .chart").css('display', 'block').removeAttr( "style" ); if (myScroll) myScroll.destroy(); /***End Code other page**/ $( window ).on( "orientationchange", function( event ) { initChart(); }); //Set up any other values and variables $("#iUpdateTime").val(timezone); $(".expand").click( alternateAction ); // get phone list getProvAction(); if (typeof userGatewaysList !== 'undefined') { userGatewaysList = ":" + userGatewaysList; while (userGatewaysList.indexOf(":") == 0 && userGatewaysList.length > 1) { gw = userGatewaysList.substring(1,9); userGatewaysList = userGatewaysList.substring(9); dataString = "gatewayid=" + gw + "&pkey=" + prodKey + "&action=getGatewayInfo"; $.ajax({ type: "GET", url: "https://decent-destiny-704.appspot.com/laxservices/user-api.php?", data: dataString, dataType: 'json', success: function(response) { response = JSON.stringify(response); gwidIndex = response.indexOf("gwid="); gw = response.substring(gwidIndex+5, response.indexOf("]", gwidIndex) - 1); pad = "00000000"; gw = (pad+gw).slice(-pad.length); if (response.indexOf("lastseen=") > -1) { $userTimezone = $(".gwLS-" + gw).data("timezone"); lastseen = response.substring(response.indexOf("lastseen=")); lastseen = lastseen.substring(9, lastseen.indexOf(",")); var timeConverted; try { timeConverted = new Date(lastseen*1000).toLocaleString('en-US', {timeZone : $userTimezone}); } catch (err) { timeConverted = timeConverted ? timeConverted : new Date(lastseen*1000).toLocaleString(); } $(".gwLS-" + gw).html(timeConverted); } } }); } } if (hashLoc.substring(hashLoc.indexOf("-") + 1, hashLoc.indexOf("-") + 17).length == 16){ vTemp = $("li:jqmData(id=" + hashLoc.substring(hashLoc.indexOf("-") + 1, hashLoc.indexOf("-") + 17) + ")"); vTemp.trigger('click'); } }); $(function(){ // Check the initial Poistion of the Sticky Header var stickyHeaderTop = 40; $(window).scroll(function(){ if( $(window).scrollTop() > stickyHeaderTop ) { $('.LeftSticky').css({position: 'fixed', top: '0px'}); } else { $('.LeftSticky').css({position: 'static', top: '0px'}); } }); }); function chartRedraw() { var newFilter = $(this).data('id'); var thisDevId = $(this).parents('table').data('devid'); var type = $('.chartnavtyperow-' + thisDevId).find('.disabled').data("id"); var time = $('.chartnavtimerow-' + thisDevId).find('.disabled').data("id"); //Enable all buttons $("#chartNavDiv-" + thisDevId).find("button").removeClass("disabled"); //Find buttons to disable if ("trp".indexOf(newFilter) > -1 ) // determines if the user clicked on Type or Time type = newFilter; else time = newFilter; var newLimit = 288 if (time == "w") newLimit = 2100; // minutes in 7 days / 5 minutes rounded up for a more guaranteed coverage else if (time == "m") newLimit = 10000; // if any deice has more than 10k records in a month.... //disable buttons $('#chartNavDiv-' + thisDevId + ' .cnb' + type).addClass('disabled'); $('#chartNavDiv-' + thisDevId + ' .cnb' + time).addClass('disabled'); getChartData(thisDevId, newLimit ); } function alternateAction() { if ($(this).next(".row").css('display') == "none"){ $(this).next(".row").show({}); var smoothe = window.setInterval(function() {window.scrollTo(0,document.body.scrollHeight)}, 40); window.setTimeout(function() {clearInterval(smoothe)}, 500); } else { $(this).next(".row").hide({}); } } function setPanelPage() { if (! $(this).data('device-type')) { var thermoElement = $("#"+ 'device_input_1_null_' + $(this).data('id')) ; } else var thermoElement = $("#"+ 'device_input_1_' + $(this).data('device-type') + "_" + $(this).data('id') ); $("[id^='device_input']").removeClass('active'); $("[id^='device_input_1_']").addClass("active"); prepNavPanel(); updateThermometer( thermoElement.data('deviceId'), thermoElement ); } function prepNavPanel () { // set nav accordingly - since we click these as a setup in teh beginning need to check extensively if ( hashLoc.search("chart") != -1 ) { setNavActive( ".nav-chart a" ); } else if ( hashLoc.search("table") != -1 ) { setNavActive( ".nav-table a" ); } else if ( hashLoc.search("settings") != -1 ) { setNavActive( ".nav-settings a" ); } else { setNavActive( ".nav-panel a"); } } function setWidgetAndThermo() { // Set up vars var $this = $(this); var deviceId = $this.data('device-id'); // Remove all actives and hide all current thermos and then show only selected $("[id^='device_input']").removeClass('active'); $("#device-" + deviceId + " .data-panel li .thermo-connector").addClass("hidden"); $this.addClass('active'); $(".thermo-connector", $this).removeClass("hidden"); //Update thermometer updateThermometer( deviceId, $this); } function goToAlertPage() { var $this = $(this).parent(); var alertType = $this.data('sensor'); var deviceId = $this.data('device-id'); window.location.href = urlLoc + "/v1.2/#device-" + alertType + "-alert-" + deviceId; event.preventDefault(); } function preRegGateway( event ) { // hide any previous errors $("#setup-1-warning").hide(); // get serial number and do initial check var serialNumber = $("#gatewayIdSetup").val(); if (! /^[0-9]{8}$/.test( serialNumber )) { $("#setup-1-warning").text("You did not enter 8 digits. Please verify the serial number and enter again."); $("#setup-1-warning").show(); return false; } // If we are successful set up the string and call the service var dataString = "gatewayid=" + serialNumber + "&phase=1"; $.ajax({ type: "GET", url: serviceURL + "device-api.php", data: dataString, success: function(response) { // Handling the response -- Need to finish out URL's and more here if (response !== null) { switch (response[0]) { case "1": regGateway(); break; case "3": case "2": // 2 -- factory registered but not user-registered // 3 -- factory registered and user-registered (already $("#setup-1-warning").html('You need to factory reset your device. Please click here for easy "how-to" or call customer service at: 608-785-7920'); $("#setup-1-warning").show(); break; default: // 0 -- ERROR // 4 -- INVALID SERIAL NUMBER $("#setup-1-warning").text("Please contact customer service at: 608-785-7920"); $("#setup-1-warning").show(); } } else { // Likely they did not enter 8 digits and somehow got pass JS check above. Could be spammer $("#setup-1-warning").text("Please verify the serial number and try again"); $("#setup-1-warning").show(); } }, error: function () { // only comes up if no connection $("#setup-1-warning").text("Server may be busy or your connection may be poor. Please, check your connection and try again."); $("#setup-1-warning").show(); } }); event.preventDefault(); } function regGateway() { var dataString = "gatewayid=" + $("#gatewayIdSetup").val() + "&phase=2"; // set this to session just in case there is a refresh of some sort sessionStorage.setupGW = $("#gatewayIdSetup").val(); $.ajax({ type: "GET", url: serviceURL + "device-api.php", data: dataString, success: function(response) { $("#setup-1 .container").css("opacity", ".25"); $("#setup-1").spin('medium'); setTimeout(function() { $("#setup-1 .container").css("opacity", "1"); $("#setup-1").spin(false); window.location.href = "#setup-2"; }, 20000); } }); } function associateGateway ( event ) { // set local var and erase session variable as we write it permanently var setupGW = sessionStorage.setupGW; sessionStorage.removeItem("setupGW"); var dataString = "gatewayid=" + setupGW + "&pkey=" + prodKey + "&ref=" + userSKey + "&action=addgateway"; $("#setup-2 .container").css("opacity", ".25"); $("#setup-2").spin('medium'); // Attempt to sync to prod db $.ajax({ type: "GET", url: serviceURL + "user-api.php", data: dataString, success: function(response) { //if called again remove local storage object here }, error: function(response) { // Sync to DB later, Write locally for use now var estGwID = localStorage.estGwId ? localStorage.estGwId : ""; if ( estGwID.search(setupGW) === -1 ) estGwID += "G" + setupGW; localStorage.estGwId = estGwID; } }); setTimeout(function() { $("#setup-2 .container").css("opacity", "1"); $("#setup-2").spin(false); window.location.href = urlLoc + "/v1.2/#setup-3"; }, 2000); event.preventDefault(); } // call on startup to find any new sensors that need to be added function silentFindNewSensor () { var dataString = "pkey=" + prodKey + "&ref=" + userSKey + "&action=getnewsensors"; setTimeout(function(){ $.ajax({ type: "GET", url: serviceURL + "user-api.php?", data: dataString, success: function(response) { }, error: function(response) { } }); }, 3000); } function findNewSensor ( event ) { // hide any previous errors $("#sensorSetup-1-warning").hide(); var dataString = "pkey=" + prodKey + "&ref=" + userSKey + "&action=getnewsensors"; $("#sensorSetup-1 .container").css("opacity", ".25"); $("#sensorSetup-1").spin('medium'); setTimeout(function() { $.ajax({ type: "GET", url: serviceURL + "user-api.php?", data: dataString, success: function(response) { if ( response && response.newSensor != null ){ tempSensor = response.newSensor; $("#tempSensorName").html(response.sName); $("#sensorSetup-1").spin(false); $("#sensorSetup-1 .container").css("opacity", "1"); $("#formSensorSetup-2").show(); window.location.href = urlLoc + "/v1.2/#sensorSetup-2"; } else { spinTakedown( "sensorSetup-1" , 'Please check your connection and try again. Thank you.'); } }, error: function(response) { spinTakedown( "sensorSetup-1" , 'Our servers are experiencing heavy load. Please try again shortly.'); } }); }, 3000); // going to have to add a box here to let them know sensor wasn't found. Please push again. event.preventDefault(); } function findNewStation ( event ) { askOnRefresh = true; // hide any previous errors $("#stationSetup-1-warning").hide(); $('#stationErrorSection').hide() var dataString = "pkey=" + prodKey + "&ref=" + userSKey + "&action=getnewsensors"; $("#stationSetup-1 .container").css("opacity", ".25"); $("#stationSetup-1").spin('medium'); setTimeout(function() { $.ajax({ type: "GET", url: serviceURL + "user-api.php?", data: dataString, success: function(response) { if ( response && response.newSensor != null ){ tempSensor = response.newSensor; $("#tempSensorName").html(response.sName); $("#stationSetup-1").spin(false); $("#stationSetup-1 .container").css("opacity", "1"); $("#formSensorSetup-2").show(); $(".pwsIDStore").html(response.newSensor); window.location.href = urlLoc + "/v1.2/#stationSetup-2"; } else { spinTakedown( "stationSetup-1" , 'No New Devices Were Found.'); $('#stationErrorSection').show() } }, error: function(response) { spinTakedown( "stationSetup-1" , 'Our servers are experiencing heavy load. Please try again shortly.'); } }); }, 3000); // going to have to add a box here to let them know sensor wasn't found. Please push again. event.preventDefault(); } function getCookie(cname) { var name = cname + "="; var ca = document.cookie.split(';'); for(var i=0; i 15) { validInput = false; $("#iCreatePass").parent().addClass("has-error"); $(".newuser-Password-Warning").html("15 charicter max").show(); } if (uPass != uConfPass) { validInput = false; $("#iCreatePass").parent().addClass("has-error"); $("#iConfPass").parent().addClass("has-error"); $(".newuser-Password-Warning").html("Passwords do not match").show(); $(".newuser-ConfPassword-Warning").html("Passwords do not match").show(); } if (uTel.length > 0) { if (uProv < 1) { validInput = false; $("#iCreateProvider").parent().addClass("has-error"); $(".newuser-Provider-Warning").html("Must select one").show(); } } if (uTel.length != 10 && uTel.length > 0) { validInput = false; $("#iCreatePhone").parent().addClass("has-error"); $(".newuser-Phone-Warning").html("Must be 10 numbers").show(); } if (uTime < 1) { validInput = false; $("#iCreateTime").parent().addClass("has-error"); $(".newuser-Time-Warning").html(" Must select one").show(); } if (validInput) { destURL = serviceURL + "user-api.php?pkey=" + prodKey + "&action=createuser"; passform = $("#formCreate"); $("#createUser .container").css("opacity", ".25"); $("#createUser").spin('medium'); rawdata = passform.serialize(); $.post( destURL, rawdata) .done(function( response ) { // Handling the response -- Need to finish out URL's and more here // alert(response); // alert(response.result); if ( response && response.result != "Fail - User already exists" && response.result != "Fail - Password should be at least 8 characters in length and should include at least one upper case letter, one number, and one special character.") { setCookie( "uSAbc" , response.result, 5 , "/"); userSKey = response.result; $("#createUser .container").css("opacity", "1"); $("#createUser").spin(false); window.location.href = urlLoc + "/v1.2/"; } else if ( response && response.result == "Fail - User already exists" ) { spinTakedown( "createUser" , 'Your email is already taken. Please try again or Click Here to recover your password.'); } else if ( response && response.result == "Fail - Password should be at least 8 characters in length and should include at least one upper case letter, one number, and one special character." ) { spinTakedown( "createUser" , 'Password should be at least 8 characters in length and should include at least one upper case letter, one number, and one special character.'); } else { spinTakedown( "createUser" , 'An error happened. Please try again.'); } }) .fail(function(){ spinTakedown( "createUser" , 'Our servers are experiencing heavy load. Please try again shortly.'); }); } event.preventDefault(); } function deleteAlertAction( event ) { var deviceId = $(this).parent().parent().find("form[id^='alert']").data('id'); var validationID = $(this).parent().parent().find("form[id^='alert']").data('validid'); var expired = $(this).parent().parent().find("form[id^='alert']").data('expired'); var formId = $(this).parent().parent().find("form[id^='alert']").attr('id'); var currentAlertLocation = "device-" + validationID + "-alert-" + deviceId; dataString = "action=deletealert&pkey=" + prodKey + "&sensor=" + deviceId + "&type=" + validationID; $("#" + currentAlertLocation + " .container").css("opacity", ".25"); $("#" + currentAlertLocation).spin('medium'); $.ajax({ type: "GET", url: serviceURL + "user-api.php?", data: dataString, success: function(response) { // Handling the response -- Need to finish out URL's and more here // checks if exists typeof pagetype !== 'undefined' if (response !== null && response.result == "success" ) { $("#" + currentAlertLocation).spin(false); $("#" + currentAlertLocation + " .container").css("opacity", "1"); initDataTable(true); hashLoc="#" + deviceId; $("#" + formId).trigger("reset"); window.location.href = urlLoc + "/v1.2/#device-" + deviceId; } else if (response !== null) { switch(response.result) { case "NotFound": case "AccessError": spinTakedown( currentAlertLocation , 'No alert found to delete'); break; case 'fail': spinTakedown( currentAlertLocation , 'Alert was not deleted'); break; case 'DBE': spinTakedown( currentAlertLocation , 'Alert failed to delete properly'); break; default: spinTakedown( currentAlertLocation , 'A specific error occured: ' + response.error); break; } } else { spinTakedown( currentAlertLocation , 'An error happened. Please try again.'); } }, error: function () { spinTakedown( currentAlertLocation , 'Our servers are experiencing heavy load. Please try again shortly.'); } }); } function specialAlertAction (event) { var deviceId = $(this).data('id'); var notSeeSend = $("#textEmailAlert-miss-" + deviceId).val(); var batterySend = $("#textEmailAlert-batt-" + deviceId).val(); var currentAlertLocation = "device-special-alert-" + deviceId; var minTime = $("#alertTimer-miss-" + deviceId).val(); var dataString = "action=updateSpecialAlert&ref=" + userSKey + "&pkey=" + prodKey + "¬seen=" + notSeeSend + "&sensor=" + deviceId + "&battery=" + batterySend + "&timer=" + minTime; console.log(dataString); console.log(serviceURL); $.ajax({ type: "GET", url: serviceURL + "user-api.php?", data: dataString, success: function(response) { //alert(response.result); if (response && response.result && typeof response.result.miss != 'undefined' ) { text = ""; for( var typeKey in response.result ) { if (response.result[typeKey]) if (typeKey == "miss") text += " Not Seen Alert updated. "; else text += " Low Battery Alert Updated. "; } if (text == "") text = "nothing updated"; spinTakedown( currentAlertLocation , text); } else if (response && response.result == 2) { spinTakedown( currentAlertLocation , 'Phone number missing or invalid, please register a phone number to recieve text alerts.'); } else if (response && response.result == 3) { spinTakedown( currentAlertLocation , 'Whoops, your provider for you phone is missing. You need to reregister it.'); } else { spinTakedown( currentAlertLocation , 'An unknown error occured. Please try again.'); } }, error: function () { spinTakedown( currentAlertLocation , 'Our servers are experiencing heavy load. Please try again shortly.'); } }); event.preventDefault(); } function AlertActionV2( event) { //Improved version $( "span[name='alert-warning-message']").html(""); var deviceId = $(this).data('id'); var expired = $(this).data('expired'); var deviceType = $(this).data('type'); var validationID = $(this).data('validid'); var alertName = $(this).data('name').length ? $(this).data('name').toString() : $(this).data('type') ; var currentAlertLocation = "device-" + validationID + "-alert-" + deviceId; var ispws = deviceId.charAt(0) == "7" ? true : false; textEmailAlert = $("#textEmailAlert-" + validationID + "-" + deviceId).val().trim(); compare = true; var input1; var input2; var submitType; var validalert = true; submitType = validationID; var singleCompare = "wetDry"; switch (submitType) { //set limits based on what we are going to check case "temp": case "temp2": case "dewpoint": validmax = isMetric > 0 ? 60 : 140; validmin = -40; break; case "rh": case "outrh": validmax = 100; validmin = ispws ? 3 : 19; break; case "windv": case "gustv": validmax = isMetric > 0 ? 45 : 100; validmin = 0; break; case "rain1h": validmax = isMetric > 0 ? 305 : 12; validmin = 0; break; case "rain24h": validmax = isMetric > 0 ? 1830 : 72; validmin = 0; break; case "pressure": validmax = isMetric > 0 ? 1065 : 31.50; validmin = isMetric > 0 ? 930 : 27.50; break; case "wind": validmax = 360; validmin = 0; singleCompare = "wind"; case "wet": compare = false; break; } if (compare) { //Basically, If its not a WET alert, so its got a lot of constraints which are functionally identical for all alerts //Hide the old errors $("#high" + submitType + "-" + deviceId).parent().removeClass("has-error"); $("#low" + submitType + "-" + deviceId).parent().removeClass("has-error"); //Get the values the user gave us. input1 = $("#high" + submitType + "-" + deviceId).length ? parseFloat($("#high" + submitType + "-" + deviceId ).val().trim()) : null; input2 = $("#low" + submitType + "-" + deviceId).length ? parseFloat($("#low" + submitType + "-" + deviceId ).val().trim()) : null; //Begin checking, but thanks to short circuting, order matters. if (!isNaN(input1) && !isNaN(input2)) { //we have both inputs if (input1 validmax || input1 < validmin) { //and its out of range validalert = false; $("#high" + submitType + "-" + deviceId).focus(); $("#high" + submitType + "-" + deviceId).parent().addClass("has-error"); $(".high" + submitType + "-Warning").html("is not between " + validmin + " and " + validmax); } } else if (!isNaN(input2)) { //Ok, we have input 2 only if (input2 > validmax || input2 < validmin) { //and its out of range validalert = false; $("#low" + submitType + "-" + deviceId).focus(); $("#low" + submitType + "-" + deviceId).parent().addClass("has-error"); $(".low" + submitType + "-Warning").html("is not between " + validmin + " and " + validmax); } } else if (isNaN(input1) && isNaN(input2)) { //gave us nothing validalert = false; $("#high" + submitType + "-" + deviceId).focus(); $("#high" + submitType + "-" + deviceId).parent().addClass("has-error"); $(".high" + submitType + "-Warning").html("Must fill in at least one"); $("#low" + submitType + "-" + deviceId).parent().addClass("has-error"); $(".low" + submitType + "-Warning").html("Must fill in at least one"); } if (validalert) { //ensures invalid/not connected readings are consistent input1 = input1 > -50 ? input1 : -100; input2 = input2 > -50 ? input2 : -100; } } else { $("#" + singleCompare + "-" + deviceId).parent().removeClass("has-error"); var textEmailAlert = $("#textEmailAlert-" + submitType + "-" + deviceId).length ? $("#textEmailAlert-" + submitType + "-" + deviceId).val().trim() : null; var selValue = $("#" + singleCompare + "-" + deviceId).length ? $("#" + singleCompare + "-" + deviceId).val().trim() : null; if (selValue/22.5 > 16 || selValue < 0 || selValue == null) { validalert = false; $("#" + singleCompare + "-" + deviceId).focus(); $("#" + singleCompare + "-" + deviceId).parent().addClass("has-error"); $("." + singleCompare + "-Warning").html("No Value Selected"); } input1 = selValue; } if(validalert) { $("#" + currentAlertLocation + " .container").css("opacity", ".25"); $("#" + currentAlertLocation).spin('medium'); var dataString = "action=createAlertV2&ref=" + userSKey + "&pkey=" + prodKey + "&how=" + textEmailAlert + "&sensor=" + deviceId + "&alType=" + submitType + "&input1=" + input1 + "&input2=" + input2 + "&metric="+ isMetric; $.ajax({ type: "GET", url: serviceURL + "user-api.php?", data: dataString, success: function(response) { if (response && response.result && response.result == "success") { $("#" + currentAlertLocation).spin(false); $("#" + currentAlertLocation + " .container").css("opacity", "1"); initDataTable(true); hashLoc="#" + deviceId; window.location.href = urlLoc + "/v1.2/#device-" + deviceId; } else if (response.result !== null && response.result == "fail") { spinTakedown(currentAlertLocation, response.error); } else { spinTakedown( currentAlertLocation , 'An unknown error occured. Please try again.'); } }, error: function () { spinTakedown( currentAlertLocation , 'Our servers are experiencing heavy load. Please try again shortly.'); } }); } event.preventDefault(); } function deleteAction( event ) { var $this = $(this); var uId = $this.data("id"); $("#deleteSensor-warning-" + uId).hide(); // If we are start the spinner, and call the service var dataString = "pkey=" + prodKey + "&ref=" + userSKey + "&sensor=" + uId + "&action=deletesensor"; $.ajax({ type: "GET", url: serviceURL + "user-api.php?", data: dataString, success: function(response) { // Handling the response -- Need to finish out URL's and more here if ( response.result && response.result === "success") { window.location.href = urlLoc + "/v1.2/"; //window.location.reload(); } else { $("#deleteSensor-warning-" + uId).html( "You either are a guest viewing this sensor, or there was an error. Please try again." ); $("#deleteSensor-warning-" + uId).show(); } }, error: function () { $("#deleteSensor-warning-" + uId).html( "There was a network error. Please try again." ); $("#deleteSensor-warning-" + uId).show(); } }); event.preventDefault(); } function deleteGWAction( event ) { $(':radio:not(:checked)').attr('disabled', true); var $this = $(this); var uId = $('input[name=delGW]:checked', '#formGatewayDelete').val(); $("#deleteGateway-warning").hide(); $("#gatewayDeleteBtn").prop("disabled",true); // If we are start the spinner, and call the service var dataString = "pkey=" + prodKey + "&ref=" + userSKey + "&gateway=" + uId + "&action=deletegateway"; $.ajax({ type: "GET", url: serviceURL + "user-api.php?", data: dataString, success: function(response) { $("#gatewayDeleteBtn").prop("disabled",false); // Handling the response -- Need to finish out URL's and more here if ( response.result && response.result === "success") { $('input[name=delGW]:checked', '#formGatewayDelete').parent().parent().hide(); window.location.href = urlLoc + "/v1.2/#profile"; } else if (response.result && response.result === "fail sensors"){ //Problem, both {"result":"fail sensors"} (has sensors) and {"result":"fail"} (Usually successfully deleted already) fall here. Double click causes "fail" on the second call $("#deleteGateway-warning").html( "There are still sensors associated with this gateway. Please delete them first by clicking on the 'Sensor' from the home screen then clicking on 'Settings' and then 'Delete Sensor' " ); $("#deleteGateway-warning").show(); } else { $("#deleteGateway-warning").html( "The gateway failed to delete." ); $("#deleteGateway-warning").show(); } }, error: function () { $("#gatewayDeleteBtn").prop("disabled",false); $("#deleteGateway-warning-").html( "There was a network error. Please try again." ); $("#deleteGateway-warning-").show(); } }); $(':radio:not(:checked)').attr('disabled', false); event.preventDefault(); } function getAlertsByAlertId( event ) { // If we are successful set up the string, start the spinner, and call the service var dataString = "client_secret=" + client_secret + "&client_id=" + client_id; $.ajax({ type: "GET", url: "http://www.lacrossealerts.com/v1/alerts/" + alertId + "?", headers: { "Accept":"application/json" }, data: dataString, success: function(response) { // Handling the response -- Need to finish out URL's and more here console.log(response); }, error: function () { spinTakedown( "createUser" , 'Our servers are experiencing heavy load. Please try again shortly.'); } }); event.preventDefault(); } function deleteAlertWD( event ) { // If we are successful set up the string, start the spinner, and call the service var urlString = "client_secret=" + client_secret + "&client_id=" + client_id; var postURL = "http://www.lacrossealerts.com/v1/alerts/" + alertID + "?" + urlString; // "deviceSerial": "00015F5CD0C79BA9", //1224 ---> 1213 is other one var dataString = { }; $.ajax({ type: "DELETE", url: postURL, headers: { "Accept":"application/json" }, contentType: "application/json", data: JSON.stringify( dataString ), dataType: "json", success: function(response) { // Handling the response -- Need to finish out URL's and more here console.log(response); }, error: function () { spinTakedown( "createUser" , 'Our servers are experiencing heavy load. Please try again shortly.'); } }); event.preventDefault(); } function editAlertWD( event ) { // If we are successful set up the string, start the spinner, and call the service var urlString = "client_secret=" + client_secret + "&client_id=" + client_id; var postURL = "http://www.lacrossealerts.com/v1/alerts/103007?" + urlString; // "deviceSerial": "00015F5CD0C79BA9", //1224 ---> 1213 is other one var dataString = { "field": "temp2", "type":"range", "max": 10, "min": 0 }; $.ajax({ type: "PUT", url: postURL, headers: { "Accept":"application/json" }, contentType: "application/json", data: JSON.stringify( dataString ), dataType: "json", success: function(response) { // Handling the response -- Need to finish out URL's and more here console.log(response); }, error: function () { spinTakedown( "createUser" , 'Our servers are experiencing heavy load. Please try again shortly.'); } }); event.preventDefault(); } function setSensorNameAction() { var deviceId = $(this).data('id'); var newName = $("#newDevName-" + deviceId).val(); dataString = "action=updatesensorname&pkey=" + prodKey + "&sensor=" + deviceId + "&ref=" + userSKey + "&name=" + newName; currentLoc = "device-" + deviceId + "-settings" $("#" + currentLoc + " .container").css("opacity", ".25"); $("#" + currentLoc).spin('medium'); $.ajax({ type: "GET", url: serviceURL + "user-api.php?", data: dataString, success: function(response) { // Handling the response if ( response && response.result && response.result === "success") { $("#" + currentLoc + " .container").css("opacity", "1"); $("#" + currentLoc).spin(false); $("#setDevName-warning-" + deviceId).html("Success").show(); setTimeout( function(){ location.reload(); },2000 ) } else { $("#" + currentLoc + " .container").css("opacity", "1"); $("#" + currentLoc).spin(false); $("#setDevName-warning-" + deviceId).html("An error occured").show(); } }, error: function () { $("#" + currentLoc + " .container").css("opacity", "1"); $("#" + currentLoc).spin(false); $("#setDevName-warning-" + deviceId).html("a network Error occured, please try again shortly").show(); } }); event.preventDefault(); } function spinTakedown( temp , message ) { $("#" + temp).spin(false); $("#" + temp + " .container").css("opacity", "1"); $("#" + temp + "-warning").html( message ); $("#" + temp + "-warning").show(); } function areYouSure(text1, text2) { $("#sure .sure-1").text(text1); $("#sure .sure-2").text(text2); $.mobile.changePage("#sure"); } function updateDataPanel( deviceInfo ) { selected = null; isSelected = $("#dataPanel_" + deviceInfo.device_id + " .active").length; if (isSelected == 1) selected = $("#dataPanel_" + deviceInfo.device_id + " .active"); var alerts = deviceInfo.alerts; var dataObs = deviceInfo.obs[0]; var dUnits = deviceInfo.unit; var firstDone = false; var inputCount = 0; var text1 = '
  • ' + '
    Readings
    ' + '
    Alerts
    ' + '
  • '; var typeKey = "batt" for (i = 0; i < 2; i++) { specialval = 0; if (alerts && alerts[typeKey]) { if (alerts[typeKey].phone != "") specialval += 2; if (alerts[typeKey].email != "") specialval += 1; $("#textEmailAlert-" + typeKey + "-" + deviceInfo["device_id"]).val(specialval); } if (alerts && alerts[typeKey] && typeKey == "miss") { $("#alertTimer-miss-" + deviceInfo["device_id"]).val(alerts["miss"]["min"]); } typeKey = "miss"; } for( var typeKey in dUnits ) { if ( !dUnits.hasOwnProperty(typeKey) ) { return false; } // set some values var displayUnit = ( dUnits[typeKey] ? dUnits[typeKey] : ""); var inputAlert = null; var alertMin = ( ( alerts && alerts[typeKey] ) ? alerts[typeKey].min : null ); var alertMax = ( ( alerts && alerts[typeKey] ) ? alerts[typeKey].max : null ); var alertWet = ( ( alerts && alerts[typeKey] ) ? alerts[typeKey].wet : null ); var alertIcon = ( ( alerts && alerts[typeKey] ) ? 'fa-check text-success' : 'fa-plus' ); var hasAlert = (( alerts && alerts[typeKey] != null) ? true : false); var alertMethod = null; var disabled = false; var readingKey = null; var typeLabel = null; var alertTrig = false; var alertIDType = null; valMax = ( (alertMax != "-100" && alertMin != null) ? ((isMetric > 0 && (typeKey == "temp" || typeKey == "temp2")) ? (Math.round((alertMax - 32) * 5/9)) : alertMax) : null); valMin = ( (alertMin != "-100" && alertMin != null) ? ((isMetric > 0 && (typeKey == "temp" || typeKey == "temp2")) ? (Math.round((alertMin - 32) * 5/9)) : alertMin) : null); alertMax = valMax; alertMin = valMin; // account for wet alert if ( alerts && alerts[typeKey] && typeKey === "wet" ) alertMax = alerts[typeKey].wet; //update inputCount inputCount++; // Get the type label switch (typeKey) { case "temp": readingKey = "ambient_temp"; typeLabel = "Sensor"; break; case "temp2": readingKey = "probe_temp"; typeLabel = "Probe"; break; case "rh": readingKey = "humidity"; typeLabel = "Humidity"; break; case "wet": readingKey = "probe_temp"; typeLabel = "Wet / Dry"; break; } // set the alert Method if ( hasAlert ) { if ( alerts[typeKey].email != "" && alerts[typeKey].phone != "" ) alertMethod = "both" else if ( alerts[typeKey].phone != "" ) alertMethod = "text" else if ( alerts[typeKey].email != "" ) alertMethod = "email" } // see if alert is triggered if ( hasAlert ) alertTrig = checkAlert( dataObs[readingKey], typeKey, parseFloat(alertMax), parseFloat(alertMin) ); text1 += '
  • '; text1 += ( alertTrig ? '
    ' : '
    '); text1 += '
    ' + '
    ' + dataObs[readingKey] + '' + displayUnit + '' + '
    ' + '
    ' + typeLabel + '
    ' + '
    ' + '
    ' + '
    '; text1 += ''; if(hasAlert) { if (!disabled && !alertTrig) { if ( typeKey !== "wet" ) text1 += 'Alert range ' + ((alertMin && alertMin != "-100") ? "Min: " + alertMin + "  " : '') + ( (alertMax && alertMax != "-100") ? "Max: " + alertMax : ''); else text1 += 'Alert type: ' + ( (alertMax && alertMax == "1" ) ? "Wet" : "Dry"); } else if ( alertTrig ) { text1 += "Alert Triggered"; } else text1 += 'Alert Value: (Alert is disabled)'; } else text1 += 'No alerts set'; text1 += ''; if ( hasAlert ) { $("#del-" + typeKey + "-alert-" + deviceInfo["device_id"]).show(); $("#ca-" + typeKey + "-" + deviceInfo["device_id"]).text("Update Alert"); switch (typeKey) { case "temp": case "temp2": case "rh": $("#alert-" + typeKey + "-" + deviceInfo["device_id"] + " #high" + typeKey + "-" + deviceInfo["device_id"]).val(valMax); $("#alert-" + typeKey + "-" + deviceInfo["device_id"] + " #low" + typeKey + "-" + deviceInfo["device_id"]).val(valMin); $("#textEmailAlert-" + typeKey + "-" + deviceInfo["device_id"]).val(alertMethod); break; case "wet": readingKey = "probe_temp"; typeLabel = "Wet / Dry"; $("#textEmailAlert-wet-" + deviceInfo["device_id"]).val(alertMethod); $("#wetDry-" + deviceInfo["device_id"]).val(alertWet); break; } } else { $("#del-" + typeKey + "-alert-" + deviceInfo["device_id"]).hide(); $("#ca-" + typeKey + "-" + deviceInfo["device_id"]).text("Create Alert"); } // the above and this below are hacks needed to give alerts an id and then generate a page for them off of it and link to it. hasAlert = false; text1 += '
    ' + '
    ' + '
    ' + '
    ' + '
    ' + "
  • \n"; firstDone = true; } // update dataPanel $("#dataPanel_" + deviceInfo.device_id ).html(text1); // update Last seen lowbatdesc = "Good"; if (parseInt(dataObs["lowbattery"])) { lowbatdesc = "Replace"; $( "#device-" + deviceInfo.device_id + " .notiBattery" ).parent().addClass("red-danger"); } else { $( "#device-" + deviceInfo.device_id + " .notiBattery" ).parent().removeClass("red-danger"); } lowbatdesc = ( parseInt(dataObs["lowbattery"]) ? "Replace" : "Good"); $( "#device-" + deviceInfo.device_id + " .notiTime" ).html( dataObs["timestamp"] ); $( "#device-" + deviceInfo.device_id + " .notiLink" ).html( dataObs["linkquality"] + "%" ); $( "#device-" + deviceInfo.device_id + " .notiBattery" ).html( lowbatdesc ); // Last seen out of date if(new Date().getTime()/1000 - dataObs["utctime"] > 10800) { //3 hours at 3600 seconds per hour $( "#device-" + deviceInfo.device_id + " .notiTime" ).parent().addClass("red-danger"); } else { $( "#device-" + deviceInfo.device_id + " .notiTime" ).parent().removeClass("red-danger"); } // if device is expired switch this out if ( deviceInfo.expired == "1" ) { $(".notExpiredDiv-" + deviceInfo.device_id).hide(); $(".renewAlertDiv-" + deviceInfo.device_id).hide(); $(".isExpiredDiv-" + deviceInfo.device_id).show(); } else if ( deviceInfo.alerts && ( ( deviceInfo.alerts.temp && deviceInfo.alerts.temp.alert_id == "0" ) || ( deviceInfo.alerts.temp2 && deviceInfo.alerts.temp2.alert_id == "0" ) || ( deviceInfo.alerts.rh && deviceInfo.alerts.rh.alert_id == "0" ) || ( deviceInfo.alerts.wet && deviceInfo.alerts.wet.alert_id == "0" ) ) && deviceInfo.expired == "0" ) { $(".isExpiredDiv-" + deviceInfo.device_id).hide(); $(".notExpiredDiv-" + deviceInfo.device_id).show(); $(".renewAlertDiv-" + deviceInfo.device_id).show(); } else{ $(".renewAlertDiv-" + deviceInfo.device_id).hide(); $(".isExpiredDiv-" + deviceInfo.device_id).hide(); $(".notExpiredDiv-" + deviceInfo.device_id).show(); } } function updateTable( deviceInfo ) { var text1 = null; if (deviceInfo.ispws) { updatePWSTable( deviceInfo); } else { var dataObs = deviceInfo.obs; for( var key in dataObs ) { if ( dataObs.hasOwnProperty(key) ) { var temp = dataObs[key]; text1 += "" + temp.timestamp + ""; if ( deviceInfo.device_type === "TX71" ) text1 += "" + temp.probe_temp + ""; else if ( deviceInfo.device_type === "TX70" ){ text1 += "" + parseFloat( temp.ambient_temp ).toFixed(1) + deviceInfo["unit"]["temp"] + ""; text1 += "" + temp.probe_temp + ""; text1 += "" + parseFloat( temp.humidity ).toFixed(1) + deviceInfo["unit"]["rh"] + ""; } else { text1 += "" + parseFloat( temp.ambient_temp ).toFixed(1) + deviceInfo["unit"]["temp"] + ""; text1 += "" + parseFloat( temp.probe_temp ).toFixed(1) + deviceInfo["unit"]["temp2"] + ""; text1 += "" + parseFloat( temp.humidity ).toFixed(1) + deviceInfo["unit"]["rh"] + ""; } text1 += ""; } } $("#dTable_" + deviceInfo.device_id ).html(text1); } } function updatePWSTable( deviceInfo ) { var text1 = "
    "; text1 += "
    Time"; text1 += "
    Indoor Temp"; text1 += "
    Indoor Humidity"; text1 += "
    Outdoor Temp"; text1 += "
    Outdoor Humidity"; text1 += "
    Dew Point"; text1 += "
    Wind"; text1 += "
    Gusts"; text1 += "
    Pressure"; text1 += "
    1h Precip."; text1 += "
    24h Precip."; text1 += "
    Week Precip."; text1 += "
    Month Precip."; text1 += "
    Total Precip."; text1 += "
    " var dataObs = deviceInfo.obs; var odds = false; for( var key in dataObs ) { if ( dataObs.hasOwnProperty(key) ) { var temp = dataObs[key]; text1 += "
    " : ">"; text1 += "
    " + temp.timestamp + "
    "; text1 += "
    " + parseFloat( temp.IndoorTemp ).toFixed(1) + deviceInfo["unit"]["temp"] + "
    "; text1 += "
    " + parseFloat( temp.IndoorHumid ).toFixed(1) + deviceInfo["unit"]["rh"] + "
    "; text1 += "
    " + parseFloat( temp.OutdoorTemp ).toFixed(1) + deviceInfo["unit"]["temp2"] + "
    "; text1 += "
    " + parseFloat( temp.OutdoorHumid ).toFixed(1) + deviceInfo["unit"]["rh"] + "
    "; text1 += "
    " + parseFloat( temp.DewPoint ).toFixed(1) + deviceInfo["unit"]["dewpoint"] + "
    "; text1 += "
    " + temp.WindDir + "
    " + parseFloat( temp.WindVelocity ).toFixed(1) + deviceInfo["unit"]["windv"] + "
    "; text1 += "
    " + parseFloat( temp.GustVelocity ).toFixed(1) + deviceInfo["unit"]["gustv"] + "
    "; text1 += "
    " + parseFloat( temp.Pressure ).toFixed(2) + deviceInfo["unit"]["pressure"] + "
    "; text1 += "
    " + parseFloat( temp.Rain1hr ).toFixed(2) + deviceInfo["unit"]["rain1h"] + "
    "; text1 += "
    " + parseFloat( temp.Rain24hr ).toFixed(2) + deviceInfo["unit"]["rain1h"] + "
    "; text1 += "
    " + parseFloat( temp.RainWeek ).toFixed(2) + deviceInfo["unit"]["rain1h"] + "
    "; text1 += "
    " + parseFloat( temp.RainMonth ).toFixed(2) + deviceInfo["unit"]["rain1h"] + "
    "; text1 += "
    " + parseFloat( temp.RainTotal ).toFixed(2) + deviceInfo["unit"]["rain1h"] + "
    "; text1 += "
    "; odds = odds ? false : true; } } $("#table-condensed-div_" + deviceInfo.device_id ).html(text1); } function updatePWSPanel( deviceInfo ) { var alerts = deviceInfo.alerts; var dataObs = deviceInfo.obs[0]; var dUnits = deviceInfo.unit; var firstDone = false; var inputCount = 0; var text1 = '
  • ' + '
    Readings
    ' + '
    Alerts
    ' + '
  • '; var pws = false; if (deviceInfo.device_id.charAt(0) == "7") { pws = true; var pos = dataObs["Icon"] * 100; $(".pwsicon-"+ deviceInfo.device_id).css('backgroundPosition', "0 -" + pos + "px"); } var typeKey = "batt" for (i = 0; i < 2; i++) { specialval = 0; if (alerts && alerts[typeKey]) { if (alerts[typeKey].phone != "") specialval += 2; if (alerts[typeKey].email != "") specialval += 1; $("#textEmailAlert-" + typeKey + "-" + deviceInfo["device_id"]).val(specialval); } if (alerts && alerts[typeKey] && typeKey == "miss") { $("#alertTimer-miss-" + deviceInfo["device_id"]).val(alerts["miss"]["min"]); } typeKey = "miss"; } for( var typeKey in dUnits ) { if ( !dUnits.hasOwnProperty(typeKey) ) { return false; } // set some values var displayUnit = ( dUnits[typeKey] ? dUnits[typeKey] : ""); var inputAlert = null; var alertMin = ( ( alerts && alerts[typeKey] ) ? alerts[typeKey].min : null ); var alertMax = ( ( alerts && alerts[typeKey] ) ? alerts[typeKey].max : null ); var alertWet = ( ( alerts && alerts[typeKey] ) ? alerts[typeKey].wet : null ); var alertIcon = ( ( alerts && alerts[typeKey] ) ? 'fa-check text-success' : 'fa-plus' ); var hasAlert = (( alerts && alerts[typeKey] != null) ? true : false); var alertMethod = null; var disabled = false; var readingKey = null; var typeLabel = null; var alertTrig = false; var alertIDType = null; var convertType = "temp"; var alertable = true; var pws = (deviceInfo.device_type == null ? true : false); valMax = ( (alertMax != "-100" && alertMin != null) ? ((isMetric > 0 && (typeKey == "temp" || typeKey == "temp2" || typeKey == "dewpoint")) ? (Math.round((alertMax - 32) * 5/9)) : alertMax) : null); valMin = ( (alertMin != "-100" && alertMin != null) ? ((isMetric > 0 && (typeKey == "temp" || typeKey == "temp2" || typeKey == "dewpoint")) ? (Math.round((alertMin - 32) * 5/9)) : alertMin) : null); alertMax = valMax; alertMin = valMin; // account for wet alert if ( alerts && alerts[typeKey] && typeKey === "wet" ) alertMax = alerts[typeKey].wet; //update inputCount inputCount++; // Get the type label and setup variables switch (typeKey) { case "temp": readingKey = "IndoorTemp"; typeLabel = "Indoor Temp"; break; case "temp2": readingKey = "OutdoorTemp"; typeLabel = "Outdoor Temp"; break; case "rh": readingKey = "IndoorHumid"; typeLabel = "Indoor Humidity"; break; case "wet": readingKey = "probe_temp"; typeLabel = "Wet / Dry"; convertType = "no"; break; case "FeelsLike": readingKey = "FeelsLike"; typeLabel = "Feels Like"; convertType = "no"; alertable = false; break; case "outrh": readingKey = "OutdoorHumid"; typeLabel = "Outdoor Humidity"; convertType = "no"; break; case "dewpoint": readingKey = "DewPoint"; typeLabel = "DewPoint"; break; case "wind": readingKey = "WindDir"; typeLabel = "Wind Direction"; convertType = "no"; break; case "windv": readingKey = "WindVelocity"; typeLabel = "Wind Velocity"; convertType = "wind"; break; case "gustv": readingKey = "GustVelocity"; typeLabel = "Gust Velocity"; convertType = "wind"; break; case "rain1h": readingKey = "Rain1hr"; typeLabel = "Rain (1hr)"; convertType = "rain"; break; case "rain24h": readingKey = "Rain24hr"; typeLabel = "Rain (24hr)"; convertType = "rain"; break; case "rainW": readingKey = "RainWeek"; typeLabel = "Rain (Week)"; alertable = false; break; case "rainM": readingKey = "RainMonth"; typeLabel = "Rain (Month)"; alertable = false; break; case "rainT": readingKey = "RainTotal"; typeLabel = "Rain (Total)"; alertable = false; break; case "pressure": readingKey = "Pressure"; typeLabel = "Pressure"; convertType = "pressure"; break; } if (convertType != "no" && isMetric > 0 ) { if (convertType == 'pressure') { alertMax = valMax == null ? null : (valMax * 33.863886666718315).toFixed(0); alertMin = valMin == null ? null : (valMin * 33.863886666718315).toFixed(0); } else if (convertType == 'rain') { alertMax = valMax == null ? null : (valMax * 25.4).toFixed(0); alertMin = valMin == null ? null : (valMin * 25.4).toFixed(0); } else if (convertType == 'wind') { alertMax = valMax == null ? null : (valMax * 0.44704).toFixed(0); alertMin = valMin == null ? null : (valMin * 0.44704).toFixed(0); } else { //temp, and already converted above alertMax = valMax; alertMin = valMin; } valMax = alertMax; valMin = alertMin; } // set the alert Method if ( hasAlert ) { if ( alerts[typeKey].email != "" && alerts[typeKey].phone != "" ) alertMethod = "both" else if ( alerts[typeKey].phone != "" ) alertMethod = "text" else if ( alerts[typeKey].email != "" ) alertMethod = "email" } // see if alert is triggered if ( hasAlert ) alertTrig = checkAlert( dataObs[readingKey], typeKey, parseFloat(alertMax), parseFloat(alertMin) ); text1 += '
  • ' : '>
    '); text1 += '
    ' + '
    ' + dataObs[readingKey] + '' + displayUnit + '' + '
    ' + '
    ' + typeLabel + '
    ' + '
    ' + '
    ' + '
    '; text1 += ''; if(hasAlert) { if (!disabled && !alertTrig) { if ( typeKey !== "wet" ) text1 += 'Alert range ' + ((alertMin && alertMin != "-100") ? "Min: " + alertMin + "  " : '') + ( (alertMax && alertMax != "-100") ? "Max: " + alertMax : ''); else text1 += 'Alert type: ' + ( (alertMax && alertMax == "1" ) ? "Wet" : "Dry"); } else if ( alertTrig ) { text1 += "Alert Triggered"; } else text1 += 'Alert Value: (Alert is disabled)'; } else if (alertable) text1 += 'No alerts set'; text1 += ''; if ( hasAlert ) { $("#del-" + typeKey + "-alert-" + deviceInfo["device_id"]).show(); $("#ca-" + typeKey + "-" + deviceInfo["device_id"]).text("Update Alert"); $("#alert-" + typeKey + "-" + deviceInfo["device_id"] + " #high" + typeKey + "-" + deviceInfo["device_id"]).val(valMax); $("#alert-" + typeKey + "-" + deviceInfo["device_id"] + " #low" + typeKey + "-" + deviceInfo["device_id"]).val(valMin); $("#textEmailAlert-" + typeKey + "-" + deviceInfo["device_id"]).val(alertMethod); } else { $("#del-" + typeKey + "-alert-" + deviceInfo["device_id"]).hide(); $("#ca-" + typeKey + "-" + deviceInfo["device_id"]).text("Create Alert"); } // the above and this below are hacks needed to give alerts an id and then generate a page for them off of it and link to it. hasAlert = false; if (alertable) { text1 += '
    ' + '
    ' + '
    ' + '
    ' + '
    ' + "
  • \n"; } else { text1 += '\n'; } firstDone = true; } // update dataPanel $("#dataPanel_" + deviceInfo.device_id ).html(text1); // update Last seen $( "#device-" + deviceInfo.device_id + " .notiTime" ).html( dataObs["timestamp"] ); $( "#device-" + deviceInfo.device_id + " .notiLink" ).html( dataObs["linkquality"] + "%" ); $( "#device-" + deviceInfo.device_id + " .notiBattery" ).html( ( dataObs["lowbattery"] ? "Good" : "Replace") ); // Last seen out of date if(new Date().getTime()/1000 - dataObs["utctime"] > 10800) { //3 hours at 3600 seconds per hour $( "#device-" + deviceInfo.device_id + " .notiTime" ).parent().addClass("red-danger"); } else { $( "#device-" + deviceInfo.device_id + " .notiTime" ).parent().removeClass("red-danger"); } // if device is expired switch this out if ( deviceInfo.expired == "1" ) { $(".notExpiredDiv-" + deviceInfo.device_id).hide(); $(".renewAlertDiv-" + deviceInfo.device_id).hide(); $(".isExpiredDiv-" + deviceInfo.device_id).show(); } else if ( deviceInfo.alerts && ( ( deviceInfo.alerts.temp && deviceInfo.alerts.temp.alert_id == "0" ) || ( deviceInfo.alerts.temp2 && deviceInfo.alerts.temp2.alert_id == "0" ) || ( deviceInfo.alerts.rh && deviceInfo.alerts.rh.alert_id == "0" ) || ( deviceInfo.alerts.wet && deviceInfo.alerts.wet.alert_id == "0" ) ) && deviceInfo.expired == "0" ) { $(".isExpiredDiv-" + deviceInfo.device_id).hide(); $(".notExpiredDiv-" + deviceInfo.device_id).show(); $(".renewAlertDiv-" + deviceInfo.device_id).show(); } else{ $(".renewAlertDiv-" + deviceInfo.device_id).hide(); $(".isExpiredDiv-" + deviceInfo.device_id).hide(); $(".notExpiredDiv-" + deviceInfo.device_id).show(); } } /**** * Class name is the footer element to set active. * Remove is used if we want to clear other elements * @param className */ function setNavActive( element ) { $('.mobile-nav .ui-btn').removeClass( "ui-btn-active" ); $( element ).addClass( "ui-btn-active" ); } /** * Determine the mobile operating system. * This function either returns 'iOS', 'Android' or 'unknown' * * @returns {String} */ function getMobileOS() { var userAgent = navigator.userAgent || navigator.vendor || window.opera; if( userAgent.match( /iPad/i ) || userAgent.match( /iPhone/i ) || userAgent.match( /iPod/i ) ) return 'iOS'; else if( userAgent.match( /Android/i ) ) return 'Android'; else return false; } function setIntervalAction ( event ) { var $this = $(this); var uId = $this.data("id"); var sInt = $("#sIntValue_" + uId).val(); $("#changeInterval-warning-" + uId).hide(); // If we are start the spinner, and call the service var dataString = "pkey=" + prodKey + "&ref=" + userSKey + "&sensor=" + uId + "&action=setsensorinterval" + "&interval=" + sInt; console.log(dataString); $.ajax({ type: "GET", url: serviceURL + "user-api.php?", data: dataString, success: function(response) { // Handling the response -- Need to finish out URL's and more here if ( response && response.result && response.result === "success") { $("#changeInterval-warning-" + uId).html( response.result ); $("#changeInterval-warning-" + uId).show(); $("#sensorIntervalSpan_" + uId).html("Current Interval: " + sInt + " mins"); $("#sIntValue_" + uId).val(sInt); //feels redundent and unessecary. } else if ( response && response.result ) { $("#changeInterval-warning-" + uId).html( response.result ); $("#changeInterval-warning-" + uId).show(); } else { $("#changeInterval-warning-" + uId).html( "There was a network error. Please try again." ); $("#changeInterval-warning-" + uId).show(); } }, error: function () { $("#changeInterval-warning-" + uId).html( "There was a network error. Please try again." ); $("#changeInterval-warning-" + uId).show(); } }); event.preventDefault(); } function syncPWSTimezone ( event ) { var $this = $(this); var uId = $this.data("id"); var custTimezone = $("#customTimezone-" + uId).val(); var set = 0; if ($("#setCustTimezone-" + uId).is(':checked')) { set = 1; } $("#timezoneSync-warning-" + uId).hide(); // If we are start the spinner, and call the service var dataString = "pkey=" + prodKey + "&ref=" + userSKey + "&sensor=" + uId + "&timezone=" + custTimezone + "&set=" + set + "&action=syncStationTimezone"; if (set == 0 || (set == 1 && custTimezone != 0)) { $.ajax({ type: "GET", url: serviceURL + "user-api.php?", data: dataString, success: function(response) { // Handling the response -- Need to finish out URL's and more here if ( response && response.result && response.result === true) { $("#timezoneSync-warning-" + uId).html( "success" ); $("#timezoneSync-warning-" + uId).show(); } else { $("#timezoneSync-warning-" + uId).html( "There was a network error. Please try again." ); $("#timezoneSync-warning-" + uId).show(); } }, error: function () { $("#timezoneSync-warning-" + uId).html( "There was a network error. Please try again." ); $("#timezoneSync-warning-" + uId).show(); } }); } event.preventDefault(); } function updateTimezoneAction( event ) { // hide any previous errors $("#changeTimeZone-warning").hide(); var time = $("#iUpdateTime").val(); var syncdevs = 1; if($("#accountTimezonePWSLimiter").is(":checked")) { syncdevs = 0; } timezone = time; $("#changeTimeZone.container").css("opacity", ".25"); $("#changeTimeZone").spin('medium'); var dataString = "pkey=" + prodKey + "&time=" + time + "&ref=" + userSKey + "&syncdevs=" + syncdevs + "&action=updatetimezone"; $.ajax({ type: "GET", url: serviceURL + "user-api.php?", data: dataString, success: function(response) { // Handling the response -- Need to finish out URL's and more here if ( response && response.result && response.result == "success" ) { initChart(); $("#changeTimeZone").spin(false); $("#iProfileTime").html($("#iUpdateTime option[value='" + time + "']").text()); hashLoc="#profile"; $("#timezoneUpdateSuccess").show(); setTimeout( function(){ $("#timezoneUpdateSuccess").hide(); },15000 ); window.location.href = urlLoc + "/v1.2/#profile"; } else if ( response && response.result && response.result == "invalid time" ) spinTakedown( "changeTimeZone" , 'Invalid time entered. Please Try Again'); else spinTakedown( "changeTimeZone" , 'An error happened. Please try again.'); }, error: function () { spinTakedown( "changeTimeZone" , 'Our servers are experiencing heavy load. Please try again shortly.'); } }); event.preventDefault(); } function updateMetricAction( event ) { // hide any previous errors $("#changeMetric-warning").hide(); var metric = $("#iUpdateMetric").val(); $("#changeMetric.container").css("opacity", ".25"); $("#changeMetric").spin('medium'); var dataString = "pkey=" + prodKey + "&metric=" + metric + "&ref=" + userSKey + "&action=updatemetric"; $.ajax({ type: "GET", url: serviceURL + "user-api.php?", data: dataString, success: function(response) { // Handling the response -- Need to finish out URL's and more here if ( response && response.result && response.result == "success" ) { isMetric = metric; initDataTable(true); initChart(); $("#changeMetric").spin(false); $("#iProfileMetric").html($("#iUpdateMetric option[value='" + metric + "']").text()); hashLoc="#profile"; $("#metricUpdateSuccess").show(); setTimeout( function(){ $("#metricUpdateSuccess").hide(); },15000 ); window.location.href = urlLoc + "/v1.2/#profile"; } else if ( response && response.result && response.result == "invalid time" ) spinTakedown( "changeMetric" , 'Invalid time entered. Please Try Again'); else spinTakedown( "changeMetric" , 'An error happened. Please try again.'); }, error: function () { spinTakedown( "changeMetric" , 'Our servers are experiencing heavy load. Please try again shortly.'); } }); event.preventDefault(); } function updatePasswordAction( event ) { // hide any previous errors $("#changePassword-warning").hide(); var updateValue = $("#iUpdatePass").val(); var updateConfVal = $("#iConfUpdatePass").val(); $("#changePassword.container").css("opacity", ".25"); $("#changePassword").spin('medium'); if (updateValue != updateConfVal) { spinTakedown( "changePassword" , 'The entered passwords do not match'); } else { subURL = serviceURL + "user-api.php?pkey=" + prodKey + "&ref=" + userSKey + "&action=updatepassword"; passform = $("#formPasswordUpdate"); //subURL = "http" + subURL.substring(4); rawdata = passform.serialize(); $.post(subURL, rawdata) .done(function(response){ if ( response && response.result && response.result == "success" ) { $("#changePassword").spin(false); $("#passUpdateSuccess").show(); setTimeout( function(){ $("#passUpdateSuccess").hide(); },15000 ); hashLoc="#profile"; $("#iUpdatePass").val(""); window.location.href = urlLoc + "/v1.2/#profile"; } else if ( response && response.result) spinTakedown( "changePassword" , response.result); else spinTakedown( "changePassword" , 'An error happened. Please try again.'); }) .fail(function(){ spinTakedown( "changePassword" , 'Our servers are experiencing heavy load. Please try again shortly.'); }); } event.preventDefault(); } function updateWeatherAction( event ) { var dataString = "q=La%20crosse,wi&callback=test&units=imperial&APPID=d65beeb9214a28a0760faf4d0f2beaed"; var url = "http://api.openweathermap.org/data/2.5/weather?"; $.ajax({ type: "GET", url: url, data: dataString, jsonpCallback: 'test', contentType: "application/json", dataType: 'jsonp', success: function(response) { $("#humidity").text(response.main.pressure + " hpa"); $("#currLocaleTemp").html( ' ' + response.main.temp + " °F"); $("#pressure").text(response.main.humidity + "%"); $("#cloudiness").text(response.weather[0].description); $("#windInfo").html( Math.ceil(response.wind.speed) + " MPH from " + Math.ceil(response.wind.deg) + "°"); }, error: function ( response ) { } }); event.preventDefault(); } function getProvAction( ) { //Ajax command to get phone providers, with 2 optional values limitlevel and selectid, limitlevel=1 required here. //limitlevel=1 means only select id and name, any other limit level assumes one provider only, limitlevel=2&selectid=4 var dataString = "pkey=" + prodKey + "&action=getproviders&limitlevel=1"; $.ajax({ type: "GET", url: serviceURL + "user-api.php?", data: dataString, success: function(response) { for(var i = 0; i < response.length; i++) { var val = response[i].id; var opt = response[i].name; var el = document.createElement("option"); el.text = opt; el.value = val; $(".phone-provider-list").append(el); } if(userProviderID){ $(".phone-provider-list").val(userProviderID); } else { $(".phone-provider-list").val(0); } }, error: function(response) { alert('Our servers are experiencing heavy load. Some things may not have loaded properly.'); } }); } function getPPContentAction() { var dataString = "pkey=" + prodKey + "&action=getPrivacyPolicy"; console.log('rube'); $.ajax({ type: "GET", url: serviceURL + "user-api.php?", data: dataString, success: function(response) { $("#pp-content-ajax").html(response['content']); }, error: function(response) { alert('Our servers are experiencing heavy load. Some things may not have loaded properly.'); } }); } function getTOSContentAction() { var dataString = "pkey=" + prodKey + "&action=getTOS"; console.log('rube'); $.ajax({ type: "GET", url: serviceURL + "user-api.php?", data: dataString, success: function(response) { $("#tos-content-ajax").html(response['content']); }, error: function(response) { alert('Our servers are experiencing heavy load. Some things may not have loaded properly.'); } }); }