I am using this version of the store locator https://github.com/googlemaps/js-store-locator
I would like to display the distance to each location once the user has submitted their search input (Enter a location). https://googlemaps.github.io/js-store-locator/examples/panel.html
I tried creating a duplicate of storeLocator.Store.prototype.distanceTo on line 441 of http://pastebin.com/ZGrWN6ib
storeLocator.Store.prototype.distanceTo = function(a) {
var b = this.getLocation(),
c = storeLocator.toRad_(b.lat()),
d = storeLocator.toRad_(b.lng()),
b = storeLocator.toRad_(a.lat()),
e = storeLocator.toRad_(a.lng());
a = b - c;
d = e - d;
c = Math.sin(a / 2) * Math.sin(a / 2) + Math.cos(c) * Math.cos(b) * Math.sin(d / 2) * Math.sin(d / 2);
return 12742 * Math.atan2(Math.sqrt(c), Math.sqrt(1 - c))
};
I am able to pass the first parameter but the second parameter var b = this.getLocation() keeps coming up as undefined
Can I check to see to see if the user location is set, and if so run the function? or do i need to hook into one of the listeners?
if(!this.getLocation()){
return 0;
}
else {
var b = this.getLocation(),
c = storeLocator.toRad_(b.lat()),
d = storeLocator.toRad_(b.lng()),
b = storeLocator.toRad_(a.lat()),
e = storeLocator.toRad_(a.lng());
a = b - c;
d = e - d;
c = Math.sin(a / 2) * Math.sin(a / 2) + Math.cos(c) * Math.cos(b) * Math.sin(d / 2) * Math.sin(d / 2);
return 12742 * Math.atan2(Math.sqrt(c), Math.sqrt(1 - c));
}
You are using this.getLocation(), that means your file has to be a storeLocator.Store.prototype.
The getLocation() method probably belongs to the store-locator.min.js, which should be included in your html file, maybe thats why you can not find the getLocation() method.
In the Google Maps GitHub example page, the store-locator.min.js is included in the panel.html file.
From this example folder, you can see the structure of files.
Got it! So if you want to display the distance in the store list view here's what you can do:
First beautify the store-locator.min.js file for easier reading with something like http://jsbeautifier.org/
Then modify this portion of function storeLocator.Panel.prototype.init_
if (b.geometry) {
this.directionsFrom_ = b.geometry.location;
a.directionsVisible_ && a.renderDirections_();
var c = a.get("view");
c.highlight(null);
var d = c.getMap();
b.geometry.viewport ? d.fitBounds(b.geometry.viewport) : (d.setCenter(b.geometry.location), d.setZoom(12));
c.refreshView();
a.listenForStoresUpdate_();
// New Addition
// You will need to create helper functions to set the cookie, i will include below
storeLocator.setCookie("searchAddy",b.geometry.location,1);
// End New Addition
} else a.searchPosition(b.name)
Then add this function right above storeLocator.Panel.prototype.stores_changed
storeLocator.Panel.prototype.ifDistanceFrom = function(b) {
var str = storeLocator.getCookie('searchAddy');
var regex = /\((-?[0-9]+\.[0-9]+), (-?[0-9]+\.[0-9]+)\)/g;
var latlonArray = [];
var match = regex.exec(str);
while (match) {
latlonArray.push({
"lat" : match[1],
"lon" : match[2]
});
match = regex.exec(str);
};
var a = new google.maps.LatLng(latlonArray[0].lat,latlonArray[0].lon),
b = b.getLocation(),
c = storeLocator.toRad_(b.lat()),
d = storeLocator.toRad_(b.lng()),
b = storeLocator.toRad_(a.lat()),
e = storeLocator.toRad_(a.lng());
a = b - c;
d = e - d;
c = Math.sin(a / 2) * Math.sin(a / 2) + Math.cos(c) * Math.cos(b) * Math.sin(d / 2) * Math.sin(d / 2);
return 12742 * Math.atan2(Math.sqrt(c), Math.sqrt(1 - c));
};
Now modify this portion of function storeLocator.Panel.prototype.stores_changed
for (var b = function() {
a.highlight(this.store, !0)
}, e = 0, f = Math.min(10, c.length); e < f; e++) {
var g = c[e].getInfoPanelItem();
g.store = c[e];
// New Addition
if(storeLocator.checkCookie() != null) {
var distance = this.ifDistanceFrom(g.store);
$(g).find('input').val(distance.toFixed(1));
}
else {
$(g).find('.dist-span').hide();
}
// End New Addition
d && c[e].getId() == d.getId() && $(g).addClass("highlighted");
g.clickHandler_ || (g.clickHandler_ = google.maps.event.addDomListener(g, "click", b));
this.storeList_.append(g)
}
Lastly modify your Data Feed file DataSource.prototype.parse_ function
DataSource.prototype.parse_ = function(csv) {
var stores = [];
var rows = csv.split('\n');
var headings = this.parseRow_(rows[0]);
for (var i = 1, row; row = rows[i]; i++) {
row = this.toObject_(headings, this.parseRow_(row));
var features = new storeLocator.FeatureSet;
// If you have features
features.add(this.FEATURES_.getById('featureName1-' + featureName1));
// New Addition
var distInput = "<span class='dist-span'>Distance: <input class='dist-input' value='' size='2' type='text' /> mi.</span>"
// End New Addition
var position = new google.maps.LatLng(row.Ycoord, row.Xcoord);
var shop = this.join_([row.Street_add], ', ');
var locality = row.Locality+', '+row.State+' '+row.Postcode;
var store = new storeLocator.Store(row.Fcilty_typ, position, features, {
title: row.Fcilty_nam,
// New Addition
address: this.join_([shop, locality, distInput], '<br>'),
// End New Addition
hours: row.Hrs_of_bus
});
stores.push(store);
}
return stores;
};
Below are the helper functions you will need to add to store-locator.min.js for setting the cookie.
storeLocator.setCookie = function(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires;
// alert('Cookie set: '+ cvalue);
};
storeLocator.getCookie = function (cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
};
return "";
};
storeLocator.checkCookie = function () {
var a = storeLocator.getCookie("searchAddy");
if (a != "") {
return 1;
}
else {
return null;
}
};
Inside the DataSource.prototype.parse_ function I added a new div element within the misc parameter, and used the store id as a unique div class.
var id = row.name.toLowerCase().replace(/[\. ,:-]+/g, '-');
var position = new google.maps.LatLng(row.latitude, row.longitude);
var locality = this.join_([row.state, row.postal_code], ', ');
var store = new storeLocator.Store(id, position, features, {
title: row.name,
address: this.join_([row.street, locality], '<br>'),
phone: row.phone_number,
misc: '<div class="distance '+id+'"></div>',
});
And then inside the DataSource.prototype.toObject_ I just added some jQuery for updating the text when a location is searched.
var panelDiv = document.getElementById('panel');
var panel = new storeLocator.Panel(panelDiv, {
view: view
});
google.maps.event.addListener(panel, 'geocode', function(result) {
panel.stores.forEach(function(store){
var distance = Math.round(store.distanceTo(result.geometry.location));
jQuery('.distance').each(function(){
if (jQuery(this).hasClass(store.getId())) {
jQuery(this).text(distance);
}
});
});
});
There's probably a better way, but this worked in my case.
Related
Im trying to make an online Role Playing Game, but my code is not working. It asks the user what they want their character to be named, and what race they want to be. It would then randomly choose some stats for them, and -- depending upon their race -- add and subtract from their stats.
var nameAndRaceFunction = function(){
var namePrompt = prompt("What shall you name your character?");
var racePrompt = prompt("What race shall your character be? Please spell it correctly, with no capitals.");
var race = racePrompt.toLowerCase();
var totalSentence = namePrompt + " the " + race;
document.getElementById("nameAndRace").innerHTML = totalSentence;
}
var str = Math.floor((Math.random() * 10) + 1);
var int = Math.floor((Math.random() * 10) + 1);
var hlth = Math.floor((Math.random() * 10) + 1);
var dext = Math.floor((Math.random() * 10) + 1);
var getStatFunction = function(){
if(racePrompt === "elf"){
elfStats();
}else if(racePrompt === "dwarf"){
dwarfStats();
}else if(racePrompt === "man"){
manStats();
}else{
}
}
var elfStats = function(){
var elfStr = str;
var elfInt = int + 1;
var elfHlth = (hlth - 1)*10;
var elfDext = dext + 1;
document.getElementById("strength").innerHTML = elfStr;
document.getElementById("intelligence").innerHTML = elfInt;
document.getElementById("health").innerHTML = elfHlth;
document.getElementById("dexterity").innerHTML = elfDext;
}
var manStats = function(){
var manStr = str + 2;
var manInt = int;
var manHlth = (hlth - 1) * 10;
var manDext = dext;
document.getElementById("strength").innerHTML = manStr;
document.getElementById("intelligence").innerHTML = manInt;
document.getElementById("health").innerHTML = manHlth;
document.getElementById("dexterity").innerHTML = manDext;
}
var dwarfStats = function(){
var dwarfStr = str + 1;
var dwarfInt = int;
var dwarfHlth = (hlth + 1) * 10;
var dwarfDext = dext - 1;
document.getElementById("strength").innerHTML = dwarfStr;
document.getElementById("intelligence").innerHTML = dwarfInt;
document.getElementById("health").innerHTML = dwarfHlth;
document.getElementById("dexterity").innerHTML = dwarfDext;
}
racePrompt is defined inside the nameAndRaceFunction() function scope. It is not accessible outside of it. Further: you lower case it, so later I will check only for race not racePrompt.
One solution would be to make race global like str, int, hlth, dext
var nameAndRaceFunction = function() {
namePrompt = prompt("What shall you name your character?");
var racePrompt = prompt("What race shall your character be? Please spell it correctly, with no capitals.");
race = racePrompt.toLowerCase();
var totalSentence = namePrompt + " the " + race;
document.getElementById("nameAndRace").innerHTML = totalSentence;
getStatFunction()
}
var namePrompt, race;
var str = Math.floor((Math.random() * 10) + 1);
var int = Math.floor((Math.random() * 10) + 1);
var hlth = Math.floor((Math.random() * 10) + 1);
var dext = Math.floor((Math.random() * 10) + 1);
var getStatFunction = function() {
if (race === "elf") {
elfStats();
} else if (race === "dwarf") {
dwarfStats();
} else if (race === "man") {
manStats();
} else {
}
}
getStatFunction should be called with the race as argument or you should define the variable racePrompt outsite the function
Also, if you mean to make a player, a good idea should be have it as an object and use the nameAndRaceFunction like a constructor
Im getting an NaN error in the total grade. Can someone help me to find the cause of this error? Or give me some ideas how to fix this? Im just new to javascript and web development. Sorry for the logic of my code..
here's my code.
function Calculate(){
var term = $("#term").val();
var fac_code = $("#faculty_code").val();
$.ajax({
type: 'POST',
url: 'getrecords.php',
data: {
"done": 1,
"term": term,
"fac_code": fac_code
},
dataType: 'json',
success: function(data)
{
var major = data[3];
var quizzes = data[4];
var homework = data[5];
var attendance = data[6];
var laboratory = data[7];
var activity = data[8];
var recitation = data[9];
var q = +(document.getElementById('quiz').textContent);
var a = +(document.getElementById('atten').textContent);
var h = +(document.getElementById('home').textContent);
var r = +(document.getElementById('reci').textContent);
var m = +(document.getElementById('me').textContent);
var ac = +(document.getElementById('activityy').textContent);
var l = +(document.getElementById('laboratory').textContent);
var ma = $('.me');
var qui = $('.quize');
var homesea = $('.hos');
var re = $('.recits');
var laborat = $('.labo');
var activit = $('.activity');
var attenda = $('.atte');
var MisVisible = ma.is(':visible');
var QisVisible = qui.is(':visible');
var HisVisible = homesea.is(':visible');
var RisVisible = re.is(':visible');
var LisVisible = laborat.is(':visible');
var AisVisible = activit.is(':visible');
var ATisVisible = attenda.is(':visible');
var mt;
var qt;
var ht;
var rt;
var act;
var lt;
var att;
if (MisVisible === true) {
mt = m / 100 * 50 + 50;
}
if (QisVisible === true){
qt = q / 100 * 50 + 50;
}
if(HisVisible === true){
ht = h / 100 * 50 + 50;
}
if(RisVisible === true){
rt = r / 100 * 50 + 50;
}
if(LisVisible === true){
lt = l / 100 * 50 + 50;
}
if(AisVisible === true){
act = ac / 100 * 50 + 50;
}
if(ATisVisible === true){
att = a / 100 * 50 + 50;
}
mtt = mt * (major * 0.01);
qtt = qt * (quizzes * 0.01);
attt = att * (attendance * 0.01);
htt = ht * (homework * 0.01);
rtt = rt * (recitation * 0.01);
actt = act * (activity * 0.01);
ltt = lt * (laboratory * 0.01);
var grade = mtt + qtt + attt + htt + rtt + actt + ltt;
document.getElementById('td_grade').innerHTML = grade;
}
});
}
The best answer would be to know how to use the Dev Tools source pane. Put breakpoints in your code, and start stepping through the code to see the values.
If I were to take a wild guess, one of these is undefined or missing.
var major = data[3];
var quizzes = data[4];
var homework = data[5];
var attendance = data[6];
var laboratory = data[7];
var activity = data[8];
var recitation = data[9];
Or one of these can't be parsed correctly by the unary + as a number
var q = +(document.getElementById('quiz').textContent);
var a = +(document.getElementById('atten').textContent);
var h = +(document.getElementById('home').textContent);
var r = +(document.getElementById('reci').textContent);
var m = +(document.getElementById('me').textContent);
var ac = +(document.getElementById('activityy').textContent);
var l = +(document.getElementById('laboratory').textContent);
Use Chrome's Dev tool by pressing F12 and go to console tab, to check for any variable you can use:
console.log(variable_name);
Additionally, your HTML value maybe not in a form of int so you should not use unary plus to get the value, use this instead to check whether your value is good:
if (!isNaN(parseFloat("10000")){
//do something
}
I have a function called save with this code, it's meant to save data from a timer.
The class with the Model is this:
var Schema = mongoose.Schema;
var Timer = new Schema({
Time: {type: Number},
Desc: {type: String},
Doc: {type: String}
});
Timer.statics.findByDesc = function(value, callback){
this.find({ Desc: {"$regex": value, "$options": "i"}}, callback);
}
Timer.statics.findByDoc = function(value, callback) {
this.find({ Doc: { "$regex": value, "$options": "i" }}, callback);
}
Timer.statics.findAll = function(callback){
this.find({}, callback);
}
module.exports = mongoose.model('Timer', Timer);
the model is defined by this code which is imported with:
var Timer = require('./../../models/timer');
but I'm testing it with constants in a function which is called by clicking button, this is the code inside the function:
var newTimer = new Timer({
Time: 6000, Desc: "My first timertest!", Doc: "Test's Dossier"
});
newTimer.save();
however with trial and error I have figured out that it never calls newTimer.save(), it seems to get stuck somewhere without ever leaving the var newTimer = new Timer() function.
I have tried my Timer Model code in other files with code like:
/**
* Created by kevin on 08/03/2016.
*/
var Timer = require('../models/timer'),
mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/legalapp');
mongoose.connection.on('open', function() {
console.log('Mongoose connected.');
});
var newTimer = new Timer({
Time: 5000, Desc: "My first timertest!", Doc: "Test's Dossier"
});
console.log(newTimer.Time);
console.log(newTimer.Desc);
console.log(newTimer.Doc);
newTimer.save();
mongoose.connection.close();
and this did work, so after 3 hours of trying, I'm going crazy, so I came here.
I am using javascript, nodeJS, jquery and mongoose in my project.
Here is the entire file:
var timers = [], Timer = require('./../../models/timer');
function timer(id){
this.id = id;
this.running = false;
this.start = new Date();
this.current = new Date();
this.paused = new Date();
this.timed = 0;
this.desc = "";
this.pauseTime = 0;
this.pauseTimeBuffer = 0;
this.prevTimed = 0;
this.first = true;
this.h = Math.floor(this.timed / 1000 / 60 / 60);
this.timed -= this.h * 1000 * 60 * 60;
this.h = checkTime(this.h);
this.m = Math.floor(this.timed / 1000 / 60);
this.timed -= this.m * 1000 * 60;
this.m = checkTime(this.m);
this.s = Math.floor(this.timed / 1000);
this.timed -= this.s * 1000;
this.s = checkTime(this.s);
}
function startTime(timer){
if(!timer.running) {
if (timer.first) {
timer.start = new Date();
timer.first = false;
}
timer.running = true;
time(timer);
}
}
function stopTime(timer){
if(timer.running) {
if (timer.pauseTime === 0) {
timer.paused = new Date();
} else {
timer.paused = new Date();
timer.pauseTimeBuffer = timer.pauseTime;
}
timer.running = false;
time(timer);
}
}
function save(timer){
//stopTime(timer);
/*var desc = prompt("Enter the description of this task", timer.desc);
var dossier = prompt("What dossier does this timer belong to?");
var current = new Date();
var timed = timer.current - timer.start;
timed -= timer.pauseTime;
*/
var newTimer = new Timer();
newTimer.Time = 6000;
newTimer.Desc = "My first timertest!";
newTimer.Doc = "Test's Dossier";
newTimer.save();
alert("yay");
}
function time(timer) {
if(timer.running) {
var name = '#timer' + timer.id;
var $time = $('' + name);
timer.current = new Date();
timer.timed = timer.current - timer.start;
timer.timed -= timer.pauseTime;
timer.h = Math.floor(timer.timed / 1000 / 60 / 60);
timer.timed -= timer.h * 1000 * 60 * 60;
timer.h = checkTime(timer.h);
timer.m = Math.floor(timer.timed / 1000 / 60);
timer.m = checkTime(timer.m);
timer.timed -= timer.m * 1000 * 60;
timer.s = Math.floor(timer.timed / 1000);
timer.timed -= timer.s * 1000;
timer.s = checkTime(timer.s);
$time.html("" + timer.h + ":" + timer.m + ":" + timer.s);
//var t = setTimeout(time(timer), 10);
}else{
timer.current = new Date();
timer.pauseTime = timer.current - timer.paused;
timer.pauseTime += timer.pauseTimeBuffer;
//var t = setTimeout(time(timer), 10);
}
}
function checkTime(i) {
if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
function init(timer){
var name = "#timer" + timer.id;
var $time = $('' + name)
$time.html("" + timer.h + ":" + timer.m + ":" + timer.s);
run();
}
function run(){
for(i = 0; i < timers.length;i++){
var timer = timers[i];
setTimeout(time(timer), 10);
}
setTimeout(run, 10);
}
function action(id, action){
if(action === "start"){
var t = timers[id - 1];
startTime(t);
}else if(action === "stop"){
var t = timers[id - 1];
stopTime(t);
}else if(action === "save"){
var t = timers[id - 1];
save(t);
}
}
function stopAll(){
for(i = 0; i < timers.length; i++){
var t = timers[i];
stopTime(t);
}
}
function add(){
stopAll();
var number = timers.length + 1;
var starttext = '"start"';
var savetext = '"save"';
var stoptext = '"stop"';
var newTimer = new timer(number);
timers.push(newTimer);
$('#timers').append("<br/>" +
"<h1>Timer " + number + "</h1>" +
"<div id=" + 'timer' + number + ">Test</div>" +
"<button onclick='action(" + number + ", " + starttext + ")" + "'>Start</button>" +
"<button onclick='action(" + number + ", " + stoptext + ")" + "'>Stop</button>" +
"<button onclick='add()'>Add</button>" +
"<button onclick='action(" + number + ", " + savetext + ")" + "'>Save</button>" +
"<p class='description' id='" + 'desc' + number + "'>Click here to enter a description</p>");
$(".description").click(function(){
var text = prompt("Please enter your description here");
if(text === ""||text === null) {
$(this).html("Click here to enter a description");
}else{
$(this).html(text);
timers[number - 1].desc = text;
}
});
init(newTimer);
setTimeout(startTime(newTimer));
}
Save is the function that I have problems with.
You cannot make client side Javascript and server side Javascript coexist at the same file. Jquery/HTML code runs inside a browser and nodejs/express runs inside a server.
Reference to Client-Server concept
https://softwareengineering.stackexchange.com/questions/171203/what-are-the-differences-between-server-side-and-client-side-programming
Some good reference to work with NodeJS
calling a server side function from client side(html button onclick) in node.js
Sample app
https://github.com/jmhdez/Nodejs-Sample
I have this file on my server: (Index.html)
<script src="script.js"></script>
Then Script.js:
function generateUUID() {
var d = new Date().getTime();
var uuid = 'xxx-xxx-4xx-yxxx-xxxxyyyyxxxx'.replace(/[xy]/g, function(c) {
var r = (d + Math.random()*16)%16 | 0;
d = Math.floor(d/16);
return (c=='x' ? r : (r&0x3|0x8)).toString(16);
});
return uuid;
};
window.onload=doit;
function doit() {
var uuidme;
uuidme = generateUUID();
window.location.href = "/test?uuid=" + uuidme;
}
And the get varible goes crazy, it never stops changing the code which is NOT even close to what I would like.
before redirecting, check the url to see if you're already at the right spot with a uuid set. You can do this by scanning the url for the variable uuid using indexOf window.location.href.indexOf('uuid=') == -1:
function generateUUID() {
var d = new Date().getTime();
var uuid = 'xxx-xxx-4xx-yxxx-xxxxyyyyxxxx'.replace(/[xy]/g, function(c) {
var r = (d + Math.random()*16)%16 | 0;
d = Math.floor(d/16);
return (c=='x' ? r : (r&0x3|0x8)).toString(16);
});
return uuid;
};
window.onload=doit;
function doit() {
// make sure we dont find uuid set in the url already
if(window.location.href.indexOf('uuid=') == -1) {
var uuidme;
uuidme = generateUUID();
window.location.href = "/test?uuid=" + uuidme;
}
}
I posted a similar question at the Drupal Forum, but I haven't had much luck.
I'm upgrading a site from D6 to D7. So far it's gone well, but I'm getting a Javascript error that I just can't pin down a solution for.
This is a cut down version of the whole script:
(function($) {
function sign(secret, message) {
var messageBytes = str2binb(message);
var secretBytes = str2binb(secret);
if (secretBytes.length > 16) {
secretBytes = core_sha256(secretBytes, secret.length * chrsz);
}
var ipad = Array(16), opad = Array(16);
for (var i = 0; i < 16; i++) {
ipad[i] = secretBytes[i] ^ 0x36363636;
opad[i] = secretBytes[i] ^ 0x5C5C5C5C;
}
var imsg = ipad.concat(messageBytes);
var ihash = core_sha256(imsg, 512 + message.length * chrsz);
var omsg = opad.concat(ihash);
var ohash = core_sha256(omsg, 512 + 256);
var b64hash = binb2b64(ohash);
var urlhash = encodeURIComponent(b64hash);
return urlhash;
}
function addZero(n) {
return ( n < 0 || n > 9 ? "" : "0" ) + n;
}
Date.prototype.toISODate =
new Function("with (this)\nreturn " +
"getFullYear()+'-'+addZero(getMonth()+1)+'-'" +
"+addZero(getDate())+'T'+addZero(getHours())+':'" +
"+addZero(getMinutes())+':'+addZero(getSeconds())+'.000Z'");
function getNowTimeStamp() {
var time = new Date();
var gmtTime = new Date(time.getTime() + (time.getTimezoneOffset() * 60000));
return gmtTime.toISODate() ;
}
}(jQuery));
The part that keeps throwing an error I'm seeing in Firebug is at:
Date.prototype.toISODate =
new Function("with (this)\n return " +
"getFullYear()+'-'+addZero(getMonth()+1)+'-'" +
"+addZero(getDate())+'T'+addZero(getHours())+':'" +
"+addZero(getMinutes())+':'+addZero(getSeconds())+'.000Z'");
Firebug keeps stopping at "addZero is not defined". JS has never been my strong point, and I know some changes have been made in D7. I've already wrapped the entire script in "(function($) { }(jQuery));", but I must be missing something else. The same script works perfectly on the D6 site.
Here is the "fixed" version of the whole code with #Pointy suggestion added. All I left out is the part of the script for making the hash that goes to Amazon, and some of my declared variables.
(function($) {
var typedText;
var strSearch = /asin:/;
var srchASIN;
$(document).ready(function() {
$("#edit-field-game-title-und-0-asin").change(function() {
typedText = $("#edit-field-game-title-und-0-asin").val();
$.ajax({
type: 'POST',
data: {typedText: typedText},
dataType: 'text',
url: '/asin/autocomplete/',
success:function(){
document.getElementById('asin-lookup').style.display='none';
x = typedText.search(strSearch);
y = (x+5);
srchASIN = typedText.substr(y,10)
amazonSearch();
}
});
});
$("#search_asin").click(function() {
$("#edit-field-game-title-und-0-asin").val('');
document.getElementById('name-lookup').style.display='none';
$("#edit-field-game-title-und-0-asin").val('');
$("#edit-title").val('');
$("#edit-field-subtitle-und-0-value").val('');
$("#edit-field-game-edition-und-0-value").val('');
$("#edit-field-release-date-und-0-value-date").val('');
$("#edit-field-asin-und-0-asin").val('');
$("#edit-field-ean-und-0-value").val('');
$("#edit-field-amazon-results-und-0-value").val('');
$("#edit-body").val('');
srchASIN = $("#field-asin-enter").val();
amazonSearch();
});
$("#clear_search").click(function() {
$("#field-asin-enter").val('');
$("#edit-field-game-title-und-0-asin").val('');
$("#edit-title").val('');
$("#edit-field-subtitle-und-0-value").val('');
$("#edit-field-game-edition-und-0-value").val('');
$("#edit-field-release-date-und-0-value-date").val('');
$("#edit-field-release-dt2-und-0-value-date").val('');
$("#edit-field-asin-und-0-asin").val('');
$("#edit-field-ean-und-0-value").val('');
$("#edit-field-amazon-results-und-0-value").val('');
$("#field-amazon-platform").val('');
$("#field-amazon-esrb").val('');
$("#edit-body-und-0-value").val('');
document.getElementById('asin-lookup').style.display='';
document.getElementById('name-lookup').style.display='';
});
function amazonSearch(){
var ASIN = srchASIN;
var azScr = cel("script");
azScr.setAttribute("type", "text/javascript");
var requestUrl = invokeRequest(ASIN);
azScr.setAttribute("src", requestUrl);
document.getElementsByTagName("head").item(0).appendChild(azScr);
}
});
var amzJSONCallback = function(tmpData){
if(tmpData.Item){
var tmpItem = tmpData.Item;
}
$("#edit-title").val(tmpItem.title);
$("#edit-field-game-edition-und-0-value").val(tmpItem.edition);
$("#edit-field-release-date-und-0-value-date").val(tmpItem.relesdate);
$("#edit-field-release-dt2-und-0-value-date").val(tmpItem.relesdate);
$("#edit-field-asin-und-0-asin").val(tmpItem.asin);
$("#edit-field-ean-und-0-value").val(tmpItem.ean);
$("#field-amazon-platform").val(tmpItem.platform);
$("#field-amazon-publisher").val(tmpItem.publisher);
$("#field-amazon-esrb").val(tmpItem.esrb);
};
function ctn(x){ return document.createTextNode(x); }
function cel(x){ return document.createElement(x); }
function addEvent(obj,type,fn){
if (obj.addEventListener){obj.addEventListener(type,fn,false);}
else if (obj.attachEvent){obj["e"+type+fn]=fn; obj.attachEvent("on"+type,function(){obj["e"+type+fn]();});}
}
var styleXSL = "http://www.tlthost.net/sites/vglAmazonAsin.xsl";
function invokeRequest(ASIN) {
cleanASIN = ASIN.replace(/[-' ']/g,'');
var unsignedUrl = "http://xml-us.amznxslt.com/onca/xml?Service=AWSECommerceService&AssociateTag=theliterarytimes&IdType=ASIN&ItemId="+cleanASIN+"&Operation=ItemLookup&ResponseGroup=Medium,ItemAttributes,OfferFull&Style="+styleXSL+"&ContentType=text/javascript&CallBack=amzJSONCallback";
var lines = unsignedUrl.split("\n");
unsignedUrl = "";
for (var i in lines) { unsignedUrl += lines[i]; }
// find host and query portions
var urlregex = new RegExp("^http:\\/\\/(.*)\\/onca\\/xml\\?(.*)$");
var matches = urlregex.exec(unsignedUrl);
var host = matches[1].toLowerCase();
var query = matches[2];
// split the query into its constituent parts
var pairs = query.split("&");
// remove signature if already there
// remove access key id if already present
// and replace with the one user provided above
// add timestamp if not already present
pairs = cleanupRequest(pairs);
// encode the name and value in each pair
pairs = encodeNameValuePairs(pairs);
// sort them and put them back together to get the canonical query string
pairs.sort();
var canonicalQuery = pairs.join("&");
var stringToSign = "GET\n" + host + "\n/onca/xml\n" + canonicalQuery;
// calculate the signature
//var secret = getSecretAccessKey();
var signature = sign(secret, stringToSign);
// assemble the signed url
var signedUrl = "http://" + host + "/onca/xml?" + canonicalQuery + "&Signature=" + signature;
//document.write ("<html><body><pre>REQUEST: "+signedUrl+"</pre></body></html>");
return signedUrl;
}
function encodeNameValuePairs(pairs) {
for (var i = 0; i < pairs.length; i++) {
var name = "";
var value = "";
var pair = pairs[i];
var index = pair.indexOf("=");
// take care of special cases like "&foo&", "&foo=&" and "&=foo&"
if (index == -1) {
name = pair;
} else if (index == 0) {
value = pair;
} else {
name = pair.substring(0, index);
if (index < pair.length - 1) {
value = pair.substring(index + 1);
}
}
// decode and encode to make sure we undo any incorrect encoding
name = encodeURIComponent(decodeURIComponent(name));
value = value.replace(/\+/g, "%20");
value = encodeURIComponent(decodeURIComponent(value));
pairs[i] = name + "=" + value;
}
return pairs;
}
function cleanupRequest(pairs) {
var haveTimestamp = false;
var haveAwsId = false;
var nPairs = pairs.length;
var i = 0;
while (i < nPairs) {
var p = pairs[i];
if (p.search(/^Timestamp=/) != -1) {
haveTimestamp = true;
} else if (p.search(/^(AWSAccessKeyId|SubscriptionId)=/) != -1) {
pairs.splice(i, 1, "AWSAccessKeyId=" + accessKeyId);
haveAwsId = true;
} else if (p.search(/^Signature=/) != -1) {
pairs.splice(i, 1);
i--;
nPairs--;
}
i++;
}
if (!haveTimestamp) {
pairs.push("Timestamp=" + getNowTimeStamp());
}
if (!haveAwsId) {
pairs.push("AWSAccessKeyId=" + accessKeyId);
}
return pairs;
}
function sign(secret, message) {
var messageBytes = str2binb(message);
var secretBytes = str2binb(secret);
if (secretBytes.length > 16) {
secretBytes = core_sha256(secretBytes, secret.length * chrsz);
}
var ipad = Array(16), opad = Array(16);
for (var i = 0; i < 16; i++) {
ipad[i] = secretBytes[i] ^ 0x36363636;
opad[i] = secretBytes[i] ^ 0x5C5C5C5C;
}
var imsg = ipad.concat(messageBytes);
var ihash = core_sha256(imsg, 512 + message.length * chrsz);
var omsg = opad.concat(ihash);
var ohash = core_sha256(omsg, 512 + 256);
var b64hash = binb2b64(ohash);
var urlhash = encodeURIComponent(b64hash);
return urlhash;
}
Date.prototype.toISODate = function() {
function addZero(n) {
return ( n < 0 || n > 9 ? "" : "0" ) + n;
}
var d = this;
return d.getFullYear() + '-' +
addZero(d.getMonth() + 1) + '-' +
addZero(d.getDate()) + 'T' +
addZero(d.getHours()) + ':' +
addZero(d.getMinutes()) + ':' +
addZero(d.getSeconds()) + '.000Z';
};
function getNowTimeStamp() {
var time = new Date();
var gmtTime = new Date(time.getTime() + (time.getTimezoneOffset() * 60000));
return gmtTime.toISODate() ;
}
}(jQuery));
Here's a better version of your code:
Date.prototype.toISODate = function() {
function addZero(n) {
return ( n < 0 || n > 9 ? "" : "0" ) + n;
}
var d = this;
return d.getFullYear() + '-' +
addZero(d.getMonth() + 1) + '-' +
addZero(d.getDate()) + 'T' +
addZero(d.getHours()) + ':' +
addZero(d.getMinutes()) + ':' +
addZero(d.getSeconds()) + '.000Z';
};
That moves "addDate" inside the extension function, and it avoids the horrid with statement.