sum field values based on condition in another field in javascript - javascript

I am attempting to sum a number of field values but only if a condition associated with those filed values is met. For example:
I have a form with several number value fields. Each of those number fields is accompanied by a choice in status. I simply want to add all of the number fields of the same status, or possibly some with a couple different status. Here is the code I tried, that does not work:
// field names
var cTotal1 = "Day1Pd1Total";
var cTotal2 = "Day1Pd2Total";
var cTotal3 = "Day1Pd3Total";
var cTotal4 = "Day1Pd4Total";
var cTotal5 = "Day1Pd5Total";
var cTotal6 = "Day1Pd6Total";
var cStatus1 = "Day1Pd1Status";
var cStatus2 = "Day1Pd2Status";
var cStatus3 = "Day1Pd3Status";
var cStatus4 = "Day1Pd4Status";
var cStatus5 = "Day1Pd5Status";
var cStatus6 = "Day1Pd6Status";
// get conditonal field values
var vStatus1 = this.getField(cStatus1).value;
var vStatus2 = this.getField(cStatus2).value;
var vStatus3 = this.getField(cStatus3).value;
var vStatus4 = this.getField(cStatus4).value;
var vStatus5 = this.getField(cStatus5).value;
var vStatus6 = this.getField(cStatus6).value;
// get field values base on condition
if(vStatus1 = "1"){
var vTotal1 = this.getField(cTotal1).value;
}else{
var vTotal1 = "0";
}
if(vStatus2 = "1"){
var vTotal2 = this.getField(cTotal2).value;
}else{
var vTotal2 = "0";
}
if(vStatus3 = "1"){
var vTotal3 = this.getField(cTotal3).value;
}else{
var vTotal3 = "0";
}
if(vStatus4 = "1"){
var vTotal4 = this.getField(cTotal4).value;
}else{
vTotal4 = "0";
}
if(vStatus5 = "1"){
var vTotal5 = this.getField(cTotal5).value;
}else{
vTotal5 = "0";
}
if(vStatus6 = "1"){
var vTotal6 = this.getField(cTotal6).value;
}else{
vTotal6 = "0";
}
// clear result value
event.value = "";
// add values
var FLPTotal = vTotal1+ vTotal2 + vTotal3 + vTotal4 + vTotal5 + vTotal6;
event.value = FLPTotal;
I have also tried something like this:
var FLPTotal = vTotal1(vStatus1 == "1") + vTotal2(vStatus2 == "1") +vTotal3(vStatus3 == "1") +vTotal4(vStatus4 == "1") +vTotal5(vStatus5 == "1") +vTotal6(vStatus6 == "1")
My knowledge of JavaScript is fairly poor, I admit. Any help would be genuinely appreciated. Thank you!

After working on this some more, I noticed it was riddled with syntax errors. After fixing them, I got this to work:
// field names
var cTotal1 = "Day1Pd1Total";
var cTotal2 = "Day1Pd2Total";
var cTotal3 = "Day1Pd3Total";
var cTotal4 = "Day1Pd4Total";
var cTotal5 = "Day1Pd5Total";
var cTotal6 = "Day1Pd6Total";
var cStatus1 = "Day1Pd1Status";
var cStatus2 = "Day1Pd2Status";
var cStatus3 = "Day1Pd3Status";
var cStatus4 = "Day1Pd4Status";
var cStatus5 = "Day1Pd5Status";
var cStatus6 = "Day1Pd6Status";
// get conditonal field values
var vStatus1 = this.getField(cStatus1).value;
var vStatus2 = this.getField(cStatus2).value;
var vStatus3 = this.getField(cStatus3).value;
var vStatus4 = this.getField(cStatus4).value;
var vStatus5 = this.getField(cStatus5).value;
var vStatus6 = this.getField(cStatus6).value;
// get field values base on condition
if(vStatus1 == "1"){
var vTotal1 = this.getField(cTotal1).value;
}else{
var vTotal1 = "";
}
if(vStatus2 == "1"){
var vTotal2 = this.getField(cTotal2).value;
}else{
var vTotal2 = "";
}
if(vStatus3 == "1"){
var vTotal3 = this.getField(cTotal3).value;
}else{
var vTotal3 = "";
}
if(vStatus4 == "1"){
var vTotal4 = this.getField(cTotal4).value;
}else{
var vTotal4 = "";
}
if(vStatus5 == "1"){
var vTotal5 = this.getField(cTotal5).value;
}else{
var vTotal5 = "";
}
if(vStatus6 == "1"){
var vTotal6 = this.getField(cTotal6).value;
}else{
var vTotal6 = "";
}
// clear result value
event.value = "";
// add values
var FLPTotal = vTotal1 + vTotal2 + vTotal3 + vTotal4 + vTotal5 + vTotal6;
event.value = FLPTotal;
I am not sure it is as streamlined as it could be, but it is doing what I need.

Related

Showing errors, the data validation rule has more items than the limit of 500. Use the list from a range criteria instead

The following codes showing errors due to limit of 500. I tried to solve it and reviewed many docs but failed. Is there any way to solve it?
var spreadsheet = SpreadsheetApp.getActive();
var dashboard = spreadsheet.getSheetByName("Dashboard");
var wsOptions = spreadsheet.getSheetByName("Master");
var options = wsOptions.getRange(2, 1, wsOptions.getLastRow()-1,6).getDisplayValues();
function onEdit(e){
var as = e.source.getActiveSheet();
var val = e.range.getValue();
var val_not = e.range.getA1Notation();
if (val_not =='F5' && as.getName() == "Dashboard"){
if(val === "All"){
dashboard.getRange('G5').setValue(new Date()).setNumberFormat("yyyy-mm-dd");
dashboard.getRange('G5').clearDataValidations();
}
else{
var filteredOptions = options.filter(function(o){return o[5] === val});
var listToApply = filteredOptions.map(function(o){return o[0]}).sort().reverse();
var cell = dashboard.getRange('G5');
var rule = SpreadsheetApp.newDataValidation().requireValueInList(listToApply).setAllowInvalid(false).build();
cell.clearContent();
cell.clearDataValidations();
cell.setDataValidation(rule);
}
}
}
Explanation:
As the error suggests:
The data validation rule has more items than the limit of 500. Use the
‘List from a range’ criteria instead.
you should use requireValueInRange().
In order to use the latter, you need to define a range of data validation items. In the following approach, I create a range of these items opt_range and I use that as an argument for the requireValueInRange() function.
Solution 1:
function onEdit(e){
var as = e.source.getActiveSheet();
var val = e.range.getValue();
var val_not = e.range.getA1Notation();
var spreadsheet = SpreadsheetApp.getActive();
var dashboard = spreadsheet.getSheetByName("Dashboard");
var wsOptions = spreadsheet.getSheetByName("Master");
var options = wsOptions.getRange(2, 1, wsOptions.getLastRow()-1,6).getDisplayValues();
if (val_not =='F5' && as.getName() == "Dashboard"){
if(val === "All"){
dashboard.getRange('G5').setValue(new Date()).setNumberFormat("yyyy-mm-dd");
dashboard.getRange('G5').clearDataValidations();
}
else{
var filteredOptions = options.filter(function(o){return o[5] === val});
var listToApply = filteredOptions.map(function(o){return o[0]}).sort().reverse();
var listToApply2D = listToApply.map(ta=>[ta]);
var jSize = wsOptions.getRange('J:J').getValues().filter(String).length;
if (jSize>0){ wsOptions.getRange(1,10,jSize,1).clearContent()};
wsOptions.getRange(1,10,listToApply2D.length,listToApply2D[0].length).setValues(listToApply2D);
var opt_range = wsOptions.getRange(1,10,listToApply2D.length,listToApply2D[0].length);
var cell = dashboard.getRange('G5');
var rule = SpreadsheetApp.newDataValidation().requireValueInRange(opt_range).build();
cell.clearContent();
cell.clearDataValidations();
cell.setDataValidation(rule);
}
}
}
Solution 2 (recommended):
Assuming you don't have 500 unique items in the list, you can still use the code you posted, but take the unique list of the items:
function onEdit(e){
var spreadsheet = SpreadsheetApp.getActive();
var dashboard = spreadsheet.getSheetByName("Dashboard");
var wsOptions = spreadsheet.getSheetByName("Master");
var options = wsOptions.getRange(2, 1, wsOptions.getLastRow()-1,6).getDisplayValues();
var as = e.source.getActiveSheet();
var val = e.range.getValue();
var val_not = e.range.getA1Notation();
if (val_not =='F5' && as.getName() == "Dashboard"){
if(val === "All"){
dashboard.getRange('G5').setValue(new Date()).setNumberFormat("yyyy-mm-dd");
dashboard.getRange('G5').clearDataValidations();
}
else{
var filteredOptions = options.filter(function(o){return o[5] === val});
var listToApply = filteredOptions.map(function(o){return o[0]}).sort().reverse();
var uniqueList = listToApply.filter((v, i, a) => a.indexOf(v) === i); // <= New code
var cell = dashboard.getRange('G5');
var rule = SpreadsheetApp.newDataValidation().requireValueInList(uniqueList).setAllowInvalid(false).build();
cell.clearContent();
cell.clearDataValidations();
cell.setDataValidation(rule);
}
}
}
Instead of using requireValueInList use requireValueInRange. This implies that you should add the values in the list to a range.
Resources
https://developers.google.com/apps-script/reference/spreadsheet/data-validation-builder#requireValueInRange(Range)
https://developers.google.com/apps-script/reference/spreadsheet/data-validation-builder#requirevalueinrangerange,-showdropdown

dynamically added input text field and get values to php and send to mysql

I have created like attachment and I have some problem to develop. The text boxes in bottom are dynamically created when add Article button pressed and now I want to update that "Added Article Details" section insert into mysql database some times have 5 rows sometime 2 rows and 1 row also wants to add. I named text box 1,2,3,4,5,6....... how to solve
My Javascript
function added_artic() {
if (added_art) {
document.getElementById('added_article').style.cssText = "display:block;";
var art_name = document.getElementsByName('article_name')[0].value;
var app = document.getElementsByName('appearance')[0].value;
var weight = document.getElementsByName('weight')[0].value;
var netWeight = document.getElementsByName('net_weight')[0].value;
var qty = document.getElementsByName('qty')[0].value;
var test = document.getElementsByName('test')[0].selectedOptions[0].text;
var added = document.getElementById("added");
var i_artname = document.createElement('input');
i_artname.value = art_name;
i_artname.name = "art_name" + art_name_id++;
i_artname.id = "txt_added";
i_artname.disabled = true;
added.appendChild(i_artname);
var i_app = document.createElement('input');
i_app.value = app;
i_app.name = "app" + app_id++;
i_app.id = "txt_added";
i_app.disabled = true;
added.appendChild(i_app);
var i_weight = document.createElement('input');
i_weight.value = weight;
i_weight.name = "weight" + weight_id++;
i_weight.id = "txt_added";
i_weight.className = "cal_weight";
i_weight.disabled = true;
added.appendChild(i_weight);
var i_netweight = document.createElement('input');
i_netweight.value = netWeight;
i_netweight.name = "netWeight" + netWeight_id++;
i_netweight.id = "txt_added";
i_netweight.className = "cal_netWeight";
i_netweight.disabled = true;
added.appendChild(i_netweight);
var i_qty = document.createElement('input');
i_qty.value = qty;
i_qty.name = "qty" + qty_id++;
i_qty.id = "txt_added";
i_qty.className = "cal_qty";
i_qty.disabled = true;
added.appendChild(i_qty);
var i_test = document.createElement('input');
i_test.value = test;
i_test.name = "test" + test_id++;
i_test.id = "txt_added";
i_test.className = "cal_test";
i_test.disabled = true;
added.appendChild(i_test);
var remove_btn = document.createElement('input');
remove_btn.type = "button";
remove_btn.value = "";
remove_btn.id = "remove_btn";
remove_btn.onclick = function ()
{
i_artname.parentElement.removeChild(i_artname);
i_app.parentElement.removeChild(i_app);
i_weight.parentElement.removeChild(i_weight);
i_netweight.parentElement.removeChild(i_netweight);
i_qty.parentElement.removeChild(i_qty);
i_test.parentElement.removeChild(i_test);
edit_btn.parentElement.removeChild(edit_btn);
this.parentElement.removeChild(this);
get_total();
if (!document.getElementsByName("test1")[0] && !document.getElementsByName("test2")[0] && !document.getElementsByName("test3")[0] && !document.getElementsByName("test4")[0] && !document.getElementsByName("test5")[0] && !document.getElementsByName("test6")[0] && !document.getElementsByName("test7")[0] && !document.getElementsByName("test8")[0] && !document.getElementsByName("test9")[0] && !document.getElementsByName("test10")[0])
{
document.getElementById('added_article').style.cssText = "display:none;";
}
}
added.appendChild(remove_btn);
var edit_btn = document.createElement('input');
edit_btn.type = "button";
edit_btn.value = "";
edit_btn.id = "edit_btn";
var a = 'weight' + (weight_id - 1);
var b = 'netWeight' + (netWeight_id - 1);
var c = 'qty' + (qty_id - 1);
edit_btn.onclick = function ()
{
document.getElementsByName(a)[0].disabled = false;
document.getElementsByName(b)[0].disabled = false;
document.getElementsByName(c)[0].disabled = false;
edit_btn.style.cssText = "background-image: url('images/update.png');";
edit_btn.onclick = function ()
{
document.getElementsByName(a)[0].disabled = true;
document.getElementsByName(b)[0].disabled = true;
document.getElementsByName(c)[0].disabled = true;
edit_btn.style.cssText = "background-image: url('images/edit.png');";
get_total();
};
};
added.appendChild(edit_btn);
document.getElementsByName('article_name')[0].value = "Article Name";
document.getElementsByName('appearance')[0].value = "Appearance";
document.getElementsByName('weight')[0].value = "";
document.getElementsByName('net_weight')[0].value = "";
document.getElementsByName('qty')[0].value = "";
document.getElementsByName('test')[0].value = "Select You Tested Karatage type";
}
}
my Project screen shot -

JavaScript error with splitting string into array

I am running into an issue with splitting a string into an array. To help myself troubleshoot the problem, I included two alert() functions, but only one gets called. Therefore, I know that there is an issue splitting a string into an array (for a basic username/password check). Here is my JS code:
function check() {
var user = document.loginform.usr.value;
var pass = document.loginform.psw.value;
var valid = false;
var txt = new XMLHttpRequest();
var alltext = "";
var allLines = [];
var usrn = [];
var pswd = [];
txt.open("GET", "/c.txt", true);
alltext = txt.responseText;
allLines = alltext.split(/\r\n|\n/);
usrn = allLines[0].split(',');
alert("usrn split");
pswd = allLines[1].split(',');
alert("pswd split");
for (var i=0; i <usrn.length; i++) {
if ((user == usrn[i]) && (pass == pswd[i])) {
valid = true;
break;
}
}
if(valid) {
window.location = "test.html";
return false;
}else{
var div = document.getElementById("login");
div.innerHTML = '<font color="red" size=2><i>Invalid Username/Password!</i></font><br>' + div.innerHTML;
}
}
The file that contains the login credentials (c.txt) is as follows:
User1,User2
pass,password
When User1 enters his/her name into the form, the password should be "pass". However, the script gets stopped at "pswd = allLines[1].split(',');". Am I misunderstanding the lines array?
Any help is appreciated - thanks!
You need to either use a synchronous call by changing the line to
txt.open("GET", "/c.txt", false);
Or use the "onreadystatechange" event to get the response when the server returns it
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
alltext = txt.responseText;
allLines = alltext.split(/\r\n|\n/);
usrn = allLines[0].split(',');
alert("usrn split");
pswd = allLines[1].split(',');
alert("pswd split");
for (var i=0; i <usrn.length; i++) {
if ((user == usrn[i]) && (pass == pswd[i])) {
valid = true;
break;
}
}
if(valid) {
window.location = "test.html";
return false;
}else{
var div = document.getElementById("login");
div.innerHTML = '<font color="red" size=2><i>Invalid Username/Password!</i></font><br>' + div.innerHTML;
}
}
}
You need to call txt.send(). Also it is async so txt.responseText will most likely be null.
You can use onreadystatechanged like so to ensure that txt.responseText has a value:
txt.onreadystatechange = function() {
if (txt.readyState == 4) { // 4 = DONE
alert(txt.responseText);
}
}
Okay - after fiddling with the code and doing some more research, I got a working script. This script takes data from a form and checks it against a file (c.txt). If the form entries match a username/password combination in c.txt, it takes you to another webpage.
function check() {
var user = document.loginform.usr.value;
var pass = document.loginform.psw.value;
var valid = false;
var txt;
if(window.XMLHttpRequest){
txt = new XMLHttpRequest();
}else{
txt = new ActiveXObject("Microsoft.XMLHTTP");
}
var allLines = [];
var usrn = [];
var pswd = [];
txt.onreadystatechange=function() {
if(txt.readyState==4 && txt.status==200){
var alltext = txt.responseText;
allLines = alltext.split(/\r\n|\n/);
usrn = allLines[0].split(',');
pswd = allLines[1].split(',');
for (var i=0; i <usrn.length; i++) {
if ((user == usrn[i]) && (pass == pswd[i])) {
valid = true;
break;
}
}
if(valid) {
window.location = "test.html";
return false;
}else{
var div = document.getElementById("login");
div.innerHTML = '<font color="red" size=2><i>Invalid Username/Password!</i></font><br>' + div.innerHTML;
}
}
}
txt.open("GET", "c.txt", false);
txt.send();
}

Update/Replace output text onClick - replaceNodes - Javascript

I have a form that takes information and outputs it in a div if its complete. If the form is not complete, output is error messages relating to the specific field which needs correcting. The error messages/output update as information is changed and the button is clicked.
Currently valid output will update as it changes, but going between valid output and error messages, the two sets of text both appear on the page, and then remain there until I refresh the page. Here's the code:
/*
Project 1 - AJAX 2015
2/14/15
Mitch Gundrum
*/
/*
Function to create input and HTML elements,
Create output nodes; output div
*/
function init() {
//Output Div
var div = document.createElement("div");
div.id = "output";
//Name
var name = document.getElementById("name").value;
name.type = "text";
//Address
var address = document.getElementById("address").value;
address.type = "text";
var city = document.getElementById("city").value;
city.type = "text";
var state = document.getElementById("state");
state.type = "text";
var index = state.selectedIndex;
var fullState = state.options[index];
var zip = document.getElementById("zip").value;
zip.type = "text";
//Email
var email = document.getElementById("email").value;
email.type = "text";
//Phone Number
var areaCode = document.getElementById("areaCode").value;
areaCode.type = "text";
var prefix = document.getElementById("prefix").value;
prefix.type = "text";
var suffix = document.getElementById("suffix").value;
suffix.type = "text";
//Gender
var gender = document.getElementsByName("gender");
var genderChoice = "";
for (var i = 0; i < gender.length; i++) {
if (gender[i].checked) {
genderChoice += gender[i].value;
}
}
//Previous Courses
var courses = document.getElementsByName("courses");
var courseChoice = "";
for (var e = 0; e < courses.length; e++) {
if (courses[e].checked) {
courseChoice += courses[e].value + ", ";
}
}
//Call Validate form method; pass all elements
validateForm(div, name, address, city, fullState, zip,
email, areaCode, prefix, suffix, genderChoice,
courseChoice);
}
//Check all elements for null
function validateForm(div, name, address, city, fullState, zip,
email, areaCode, prefix, suffix, genderChoice,
courseChoice) {
var RUN_OUTPUT = 1;
function br() {
return document.createElement('br');
}
if (name == null || name == "") {
var nameError = "Name is not valid";
var printNameError = document.createTextNode(nameError);
var nameLabel = document.getElementById("nameError");
nameLabel.appendChild(printNameError);
RUN_OUTPUT = 0;
}
if (email == null || email == "") {
var emailError = "Email is not valid";
var printEmailError = document.createTextNode(emailError);
var emailLabel = document.getElementById("emailError");
emailLabel.appendChild(printEmailError);
RUN_OUTPUT = 0;
}
if (areaCode == null || areaCode == "" || prefix == null || prefix == "" || suffix == null || suffix == "") {
var phoneError = "Area Code is not valid";
var printPhoneError = document.createTextNode(phoneError);
var phoneLabel = document.getElementById("phoneError");
phoneLabel.appendChild(printPhoneError);
RUN_OUTPUT = 0;
}
if (address == null || address == "") {
var addressError = "Address is not valid";
var printAddressError = document.createTextNode(addressError);
var addressLabel = document.getElementById("addressError");
addressLabel.appendChild(printAddressError);
RUN_OUTPUT = 0;
}
if (city == null || city == "") {
var cityError = "City is not valid";
var printCityError = document.createTextNode(cityError);
var cityLabel = document.getElementById("cityError");
cityLabel.appendChild(printCityError);
RUN_OUTPUT = 0;
}
if (fullState == null || fullState == "") {
var stateError = "State is not valid";
var printStateError = document.createTextNode(stateError);
var stateLabel = document.getElementById("stateError");
stateLabel.appendChild(printStateError);
RUN_OUTPUT = 0;
}
if (zip == null || zip == "") {
var zipError = "Zip is not valid";
var printZipError = document.createTextNode(zipError);
var zipLabel = document.getElementById("zipError");
zipLabel.appendChild(printZipError);
RUN_OUTPUT = 0;
}
if (genderChoice == null || genderChoice == "") {
var genderError = "Gender is not valid";
var printGenderError = document.createTextNode(genderError);
var genderLabel = document.getElementById("genderError");
genderLabel.appendChild(printGenderError);
RUN_OUTPUT = 0;
}
if (courseChoice == null || courseChoice == "") {
var courseError = "No Courses!";
var printCourseError = document.createTextNode(courseError);
var courseLabel = document.getElementById("courseError");
courseLabel.appendChild(printCourseError);
RUN_OUTPUT = 0;
}
if (Boolean(RUN_OUTPUT) != false) {
document.getElementsByClassName("errorField").textContent = "";
runOutputForm(div, name, address, city, fullState, zip,
email, areaCode, prefix, suffix, genderChoice,
courseChoice);
}
}
function runOutputForm(div, name, address, city, fullState, zip,
email, areaCode, prefix, suffix, genderChoice,
courseChoice) {
function br() {
return document.createElement('br');
}
var printName = document.createTextNode("Name: " + name + " ");
var printEmail = document.createTextNode("Email: " + email + " ");
var printPhone = document.createTextNode("Phone: " + areaCode + "-" + prefix + "-" + suffix);
var printAddress = document.createTextNode("Address: " + address + " " + city + ", " + fullState.text + " " + zip);
var printGender = document.createTextNode("Gender: " + genderChoice);
var printCourses = document.createTextNode("Courses Taken: " + courseChoice + " ");
div.appendChild(br());
div.appendChild(printName);
div.appendChild(br());
div.appendChild(printEmail);
div.appendChild(br());
div.appendChild(printPhone);
div.appendChild(br());
div.appendChild(printAddress);
div.appendChild(br());
div.appendChild(printGender);
div.appendChild(br());
div.appendChild(printCourses);
div.appendChild(br());
var output = document.getElementById("output");
if (output) {
output.parentNode.replaceChild(div, output);
} else {
document.body.appendChild(div);
}
}
I would like for only the current accurate messages to appear, either errors or valid output, not both. My element-replacing logic seems to be off. I am not using jQuery or innerHTML for this project. Please advise.
jsFiddle

Keep Weather info even when offline

So I'm creating a widget for the iPhone lockscreen using CSS/HTML. I can't figure out how to keep the weather info from disappearing when the phone screen turns off after a minute or when the phone is offline. Any tips? Here's the code:
<script type="text/javascript">
var iconExtWall = '.png'
var iconExtLock = '.png'
var locale = 'Beirut, Lebanon'
var iconSetWall = 'stardock'
var iconSetLock = 'stardock'
var enableWallpaper = true
var isCelsius = true
var useRealFeel = false
var enableLockScreen = true
var source = 'appleAccuweatherStolen'
var stylesheetWall = 'mini'
var stylesheetLock = 'Under_StatusBar'
var updateInterval = 15
var postal;
var demoMode = false;
var enabled;
if (location.href.indexOf("Wallpaper") > 0){
stylesheet = stylesheetLock;
iconSet = iconSetLock;
iconExt = iconExtLock;
enabled = enableLockScreen;
}else{
stylesheet = stylesheetWall;
iconSet = iconSetWall;
iconExt = iconExtWall;
enabled = enableWallpaper;
}
if(enabled == true){
if(iconSet == null || iconSet == 'null' || iconSet == ""){
var iconSet = stylesheet;
}
var headID = document.getElementsByTagName("head")[0];
var styleNode = document.createElement('link');
styleNode.type = 'text/css';
styleNode.rel = 'stylesheet';
styleNode.href = 'Stylesheets/'+stylesheet+'.css';
headID.appendChild(styleNode);
var scriptNode = document.createElement('script');
scriptNode.type = 'text/javascript';
scriptNode.src = 'Sources/'+source+'.js';
headID.appendChild(scriptNode);
}
function onLoad(){
if (enabled == true){
if (demoMode == true){
document.getElementById("weatherIcon").src="IconSets/"+iconSet+"/"+"cloudy1"+iconExt;
document.getElementById("city").innerText="Somewhere";
document.getElementById("desc").innerText="Partly Cloudy";
document.getElementById("temp").innerText="100�";
document.getElementById("forecast").innerText="Sun";
}else{
document.getElementById("weatherIcon").src="IconSets/"+iconSet+"/"+"dunno"+iconExt;
validateWeatherLocation(escape(locale).replace(/^%u/g, "%"), setPostal)
}
}else{
document.getElementsByTagName("body")[0].innerText='';
}
}
function convertTemp(num)
{
if (isCelsius == true)
return Math.round ((num - 32) * 5 / 9);
else
return num;
}
function setPostal(obj){
if (obj.error == false){
if(obj.cities.length > 0){
postal = escape(obj.cities[0].zip).replace(/^%u/g, "%")
document.getElementById("WeatherContainer").className = "";
weatherRefresherTemp();
}else{
document.getElementById("city").innerText="Not Found";
document.getElementById("WeatherContainer").className = "errorLocaleNotFound";
}
}else{
document.getElementById("city").innerText=obj.errorString;
document.getElementById("WeatherContainer").className = "errorLocaleValidate";
setTimeout('validateWeatherLocation(escape(locale).replace(/^%u/g, "%"), setPostal)', Math.round(1000*60*5));
}
}
function dealWithWeather(obj){
var translatedesc="description";
if (obj.error == false){
document.getElementById("city").innerText=obj.city;
document.getElementById("city2").innerText=obj.city;
document.getElementById("desc").innerText=obj.description.toLowerCase();
if(useRealFeel == true){
tempValue = convertTemp(obj.realFeel);
}else{
tempValue = convertTemp(obj.temp)
}
document.getElementById("temp").innerText=tempValue+"º";
document.getElementById("weatherIcon").src="IconSets/"+iconSet+"/"+MiniIcons[obj.icon]+iconExt;
/*ProductRed*/
lastResults = new Array;
lastResults[0] = {daycode:obj.daycode, icon:obj.icon, hi:obj.hi, lo:obj.lo, now:obj.temp};
var c = obj.forecast.length;
var titi = new Array("Sun","Mon","Tue","Wed","Thu","Fri","Sat");
var toto =new Date();
var tutu = toto.getDay();
var tata;
if (c > 6) c = 6; // just to be safe
for (var i=0; i<c; ++i)
{
var forecast = obj.forecast[i];
tata = tutu + i;
if(tata > 6) {tata = tata - 7;}
document.getElementById('day'+i).innerText = titi[tata];
document.getElementById('hi'+i).innerHTML = convertTemp(forecast.hi)+'&#176 ';
document.getElementById('low'+i).innerHTML= convertTemp(forecast.lo)+'&#176 ';
document.getElementById('wIcon'+i).src="IconSets/"+iconSet+"/"+MiniIcons[forecast.icon]+iconExt;
lastResults[i+1] = {daycode:forecast.daycode, icon:forecast.icon, hi:forecast.hi, lo:forecast.lo};
}
/*ProductRed*/
document.getElementById("WeatherContainer").className = "";
}else{
//Could be down to any number of things, which is unhelpful...
document.getElementById("WeatherContainer").className = "errorWeatherDataFetch";
}
var this_date_timestamp = new Date()
var this_weekday = this_date_timestamp.getDay()
var this_date = this_date_timestamp.getDate()
var this_month = this_date_timestamp.getMonth()
var this_year = this_date_timestamp.getYear()
if (this_year < 1000)
this_year+= 1900;
if (this_year==101)
this_year=2001;
}
function weatherRefresherTemp(){ //I'm a bastard ugly hack. Hate me.
fetchWeatherData(dealWithWeather,postal);
setTimeout(weatherRefresherTemp, 60*1000*updateInterval);
}
Thanks!

Categories

Resources