position absolute doesn't work - php

position absolute doesn't work in mozilla. For jquery calender I used position:absolute for a div it seems to work all except mozilla in windows. When I remove the position:absolute it will work in windows firefox but only showing alternate months in all other browsers
jquery is
var CalendarEightysix = new Class({
Implements: Options,
options: {
'slideDuration': 500,
'fadeDuration': 200,
'toggleDuration': 200,
'fadeTransition': Fx.Transitions.linear,
'slideTransition': Fx.Transitions.Quart.easeOut,
'prefill': true,
'defaultDate': null,
'linkWithInput': true,
'theme': 'default',
'defaultView': 'month',
'startMonday': false,
'alwaysShow': false,
'injectInsideTarget': false,
'format': '%n/%d/%Y',
'alignX': 'right',
'alignY': 'ceiling',
'offsetX': 0,
'offsetY': 0,
'draggable': false,
'pickable': true,
'toggler': null,
'pickFunction': $empty,
'disallowUserInput': false,
'minDate': null,
'maxDate': null,
'excludedWeekdays': null,
'excludedDates': null,
'createHiddenInput': false,
'hiddenInputName': 'date',
'hiddenInputFormat': '%t'
},
initialize: function(target, options) {
this.setOptions(options);
this.target = $(target);
this.transitioning = false;
//Extend Date with unix timestamp parser
Date.defineParser({
re: /^[0-9]{10}$/,
handler: function(bits) { return new Date.parse('Jan 01 1970').set('seconds', bits[0]); }
});
//Selected date
if($defined(this.options.defaultDate)) this.selectedDate = new Date().parse(this.options.defaultDate).clearTime();
else if(this.options.linkWithInput && $chk(this.target.get('value'))) this.selectedDate = new Date().parse(this.target.get('value')).clearTime();
if(!$defined(this.selectedDate) || !this.selectedDate.isValid()) this.selectedDate = new Date();
this.viewDate = this.selectedDate.clone().set('date', 1).clearTime();
//Base
var innerHtml = '<div class="wrapper"><div class="header"><div class="arrow-left"></div><div class="arrow-right"></div><div class="label clickable"></div></div>'+
'<div class="body"><div class="inner"><div class="container a"></div><div class="container b"></div></div></div><div class="footer"></div></div>';
this.element = new Element('div', { 'class': 'calendar-eightysix', 'html': innerHtml, 'style': 'display: '+ (this.options.alwaysShow ? 'block' : 'none') }).addClass(this.options.theme);
if(this.options.injectInsideTarget) this.element.injectBottom(this.target);
else {
this.element.injectBottom($(document.body));
this.position();
window.addEvent('resize', this.position.bind(this));
}
this.currentContainer = this.element.getElement('.container.a').setStyle('z-index', 999);
this.tempContainer = this.element.getElement('.container.b').setStyle('z-index', 998);
//Header
this.header = this.element.getElement('.header');
this.label = this.header.getElement('.label');
this.arrowLeft = this.header.getElement('.arrow-left');
this.arrowRight = this.header.getElement('.arrow-right');
this.label.addEvent('click', this.levelUp.bind(this));
this.arrowLeft.addEvent('click', this.slideLeft.bind(this));
this.arrowRight.addEvent('click', this.slideRight.bind(this));
//Date range
if($defined(this.options.minDate)) {
this.options.minDate = Date.parse(this.options.minDate).clearTime();
if(!this.options.minDate.isValid()) this.options.minDate = null;
}
if($defined(this.options.maxDate)) {
this.options.maxDate = Date.parse(this.options.maxDate).clearTime();
if(!this.options.maxDate.isValid()) this.options.maxDate = null;
}
//Excluded dates
if($defined(this.options.excludedDates)) {
var excludedDates = [];
this.options.excludedDates.each(function(date) {
excludedDates.include(this.format(new Date().parse(date).clearTime(), '%t'));
}.bind(this));
this.options.excludedDates = excludedDates;
}
//Dragger
if(this.options.draggable && !this.options.injectInsideTarget) {
this.header.addClass('dragger');
new Drag(this.element, { 'handle': this.header });
}
//Hidden input
if(this.options.createHiddenInput) {
this.hiddenInput = new Element('input', { 'type': 'hidden', 'name': this.options.hiddenInputName }).injectAfter(this.target);
}
//Prefill date
if(this.options.prefill) this.pick();
//Link with input
if(!this.options.disallowUserInput && this.options.linkWithInput && this.target.get('tag') == 'input') {
this.target.addEvent('keyup', function() {
this.setDate(this.target.get('value'), false);
}.bind(this));
}
//Disallow input
if(this.options.disallowUserInput && this.target.get('tag') == 'input')
this.target.addEvents({ 'keydown': ($lambda(false)), 'contextmenu': ($lambda(false)) });
//Toggler
if($defined(this.options.toggler)) this.options.toggler = $(this.options.toggler);
//Show / hide events
($defined(this.options.toggler) ? this.options.toggler : this.target).addEvents({
'focus': this.show.bind(this), 'click': this.show.bind(this)
});
if(!this.options.alwaysShow) document.addEvent('mousedown', this.outsideClick.bind(this));
MooTools.lang.addEvent('langChange', function() { this.render(); this.pick(); }.bind(this));
//View
this.view = this.options.defaultView;
this.render();
},
render: function() {
this.currentContainer.empty();
switch(this.view) {
case 'decade': this.renderDecade(); break;
case 'year': this.renderYear(); break;
default: this.renderMonth();
}
},
renderMonth: function() {
this.view = 'month';
this.currentContainer.empty().addClass('month');
if(this.options.pickable) this.currentContainer.addClass('pickable');
var lang = MooTools.lang.get('Date'), weekdaysCount = this.viewDate.format('%w') - (this.options.startMonday ? 1 : 0);
if(weekdaysCount == -1) weekdaysCount = 6;
var today = new Date();
//Label
this.label.set('html', lang.months[this.viewDate.get('month')] +' '+ this.viewDate.format('%Y'));
//Day label row
var row = new Element('div', { 'class': 'row' }).injectBottom(this.currentContainer);
for(var i = (this.options.startMonday ? 1 : 0); i < (this.options.startMonday ? 8 : 7); i++) {
var day = new Element('div', { 'html': lang.days[this.options.startMonday && i == 7 ? 0 : i] }).injectBottom(row);
day.set('html', day.get('html').substr(0, 2));
}
//Add days for the beginning non-month days
row = new Element('div', { 'class': 'row' }).injectBottom(this.currentContainer);
y = this.viewDate.clone().decrement('month').getLastDayOfMonth();
for(var i = 0; i < weekdaysCount; i++) {
this.injectDay(row, this.viewDate.clone().decrement('month').set('date', y - (weekdaysCount - i) + 1), true);
}
//Add month days
for(var i = 1; i <= this.viewDate.getLastDayOfMonth(); i++) {
this.injectDay(row, this.viewDate.clone().set('date', i));
if(row.getChildren().length == 7) {
row = new Element('div', { 'class': 'row' }).injectBottom(this.currentContainer);
}
}
//Add outside days
var y = 8 - row.getChildren().length, startDate = this.viewDate.clone().increment('month').set('date', 1);
for(var i = 1; i < y; i++) {
this.injectDay(row, startDate.clone().set('date', i), true);
}
//Always have six rows
for(var y = this.currentContainer.getElements('.row').length; y < 7; y++) {
row = new Element('div', { 'class': 'row' }).injectBottom(this.currentContainer);
for(var z = 0; z < 7; z++) {
this.injectDay(row, startDate.clone().set('date', i), true);
i++;
}
}
this.renderAfter();
},
//Used by renderMonth
injectDay: function(row, date, outside) {
today = new Date();
var day = new Element('div', { 'html': date.get('date') }).injectBottom(row);
day.date = date;
if(outside) day.addClass('outside');
if(($defined(this.options.minDate) && this.format(this.options.minDate, '%t') > this.format(date, '%t')) ||
($defined(this.options.maxDate) && this.format(this.options.maxDate, '%t') < this.format(date, '%t')) ||
($defined(this.options.excludedWeekdays) && this.options.excludedWeekdays.contains(date.format('%w').toInt())) ||
($defined(this.options.excludedDates) && this.options.excludedDates.contains(this.format(date, '%t'))))
day.addClass('non-selectable');
else if(this.options.pickable) day.addEvent('click', this.pick.bind(this));
if(date.format('%x') == today.format('%x')) day.addClass('today');
if(date.format('%x') == this.selectedDate.format('%x')) day.addClass('selected');
},
renderYear: function() {
this.view = 'year';
this.currentContainer.addClass('year-decade');
var today = new Date(), lang = MooTools.lang.get('Date').months;
//Label
this.label.set('html', this.viewDate.format('%Y'));
var row = new Element('div', { 'class': 'row' }).injectBottom(this.currentContainer);
for(var i = 1; i < 13; i++) {
var month = new Element('div', { 'html': lang[i - 1] }).injectBottom(row);
month.set('html', month.get('html').substr(0, 3)); //Setting and getting the innerHTML takes care of html entity problems (e.g. [M&a]uml;r => [Mär]z)
var iMonth = this.viewDate.clone().set('month', i - 1);
month.date = iMonth;
if(($defined(this.options.minDate) && this.format(this.options.minDate.clone().set('date', 1), '%t') > this.format(iMonth, '%t')) ||
($defined(this.options.maxDate) && this.format(this.options.maxDate.clone().set('date', 1), '%t') < this.format(iMonth, '%t')))
month.addClass('non-selectable');
else month.addEvent('click', this.levelDown.bind(this));
if(i - 1 == today.get('month') && this.viewDate.get('year') == today.get('year')) month.addClass('today');
if(i - 1 == this.selectedDate.get('month') && this.viewDate.get('year') == this.selectedDate.get('year')) month.addClass('selected');
if(!(i % 4) && i != 12) row = new Element('div', { 'class': 'row' }).injectBottom(this.currentContainer);
}
this.renderAfter();
},
renderDecade: function() {
this.label.removeClass('clickable');
this.view = 'decade';
this.currentContainer.addClass('year-decade');
var today = new Date();
var viewYear, startYear;
viewYear = startYear = this.viewDate.format('%Y').toInt();
while(startYear % 12) startYear--;
//Label
this.label.set('html', startYear +' – '+ (startYear + 11));
var row = new Element('div', { 'class': 'row' }).injectBottom(this.currentContainer);
for(var i = startYear; i < startYear + 12; i++) {
var year = new Element('div', { 'html': i }).injectBottom(row);
var iYear = this.viewDate.clone().set('year', i);
year.date = iYear;
if(($defined(this.options.minDate) && this.options.minDate.get('year') > i) ||
($defined(this.options.maxDate) && this.options.maxDate.get('year') < i)) year.addClass('non-selectable');
else year.addEvent('click', this.levelDown.bind(this));
if(i == today.get('year')) year.addClass('today');
if(i == this.selectedDate.get('year')) year.addClass('selected');
if(!((i + 1) % 4) && i != startYear + 11) row = new Element('div', { 'class': 'row' }).injectBottom(this.currentContainer);
}
this.renderAfter();
},
renderAfter: function() {
//Iterate rows and add classes and remove navigation if nessesary
var rows = this.currentContainer.getElements('.row');
for(var i = 0; i < rows.length; i++) {
rows[i].set('class', 'row '+ ['a', 'b', 'c', 'd', 'e', 'f', 'g'][i] +' '+ (i % 2 ? 'even' : 'odd')).getFirst().addClass('first');
rows[i].getLast().addClass('last');
if(i == (this.view == 'month' ? 1 : 0) && $defined(this.options.minDate) && this.format(this.options.minDate, '%t') >= this.format(rows[i].getFirst().date, '%t'))
this.arrowLeft.setStyle('visibility', 'hidden');
if(i == rows.length - 1 && $defined(this.options.maxDate)) {
if((this.view == 'month' && this.format(this.options.maxDate, '%t') <= this.format(rows[i].getLast().date, '%t')) ||
(this.view == 'year' && this.format(this.options.maxDate, '%t') <= this.format(rows[i].getLast().date.clone().increment('month'), '%t')) ||
(this.view == 'decade' && this.format(this.options.maxDate, '%t') <= this.format(rows[i].getLast().date.clone().increment('year'), '%t')))
this.arrowRight.setStyle('visibility', 'hidden');
}
};
},
slideLeft: function() {
this.switchContainers();
//Render new view
switch(this.view) {
case 'month': this.viewDate.decrement('month'); break;
case 'year': this.viewDate.decrement('year'); break;
case 'decade': this.viewDate.set('year', this.viewDate.get('year') - 12); break;
}
this.render();
//Tween the new view in and old view out
this.currentContainer.set('tween', { 'duration': this.options.slideDuration, 'transition': this.options.slideTransition }).tween('left', [-this.currentContainer.getWidth(), 0]);
this.tempContainer.set('tween', { 'duration': this.options.slideDuration, 'transition': this.options.slideTransition }).tween('left', [0, this.tempContainer.getWidth()]);
},
slideRight: function() {
this.switchContainers();
//Render new view
switch(this.view) {
case 'month': this.viewDate.increment('month'); break;
case 'year': this.viewDate.increment('year'); break;
case 'decade': this.viewDate.set('year', this.viewDate.get('year') + 12); break;
}
this.render();
//Tween the new view in and old view out
this.currentContainer.set('tween', { 'duration': this.options.slideDuration, 'transition': this.options.slideTransition }).tween('left', [this.currentContainer.getWidth(), 0]);
this.tempContainer.set('tween', { 'duration': this.options.slideDuration, 'transition': this.options.slideTransition }).tween('left', [0, -this.currentContainer.getWidth()]);
},
levelDown: function(e) {
if(this.transitioning) return;
this.switchContainers();
this.viewDate = e.target.date;
//Render new view
switch(this.view) {
case 'year': this.renderMonth(); break;
case 'decade': this.renderYear(); break;
}
//Tween the new view in and old view out
this.transitioning = true;
this.currentContainer.set('tween', { 'duration': this.options.fadeDuration, 'transition': this.options.fadeTransition,
'onComplete': function() { this.transitioning = false }.bind(this) }).setStyles({'opacity': 0, 'left': 0}).fade('in');
this.tempContainer.set('tween', { 'duration': this.options.fadeDuration, 'transition': this.options.fadeTransition }).fade('out');
},
levelUp: function() {
if(this.view == 'decade' || this.transitioning) return;
this.switchContainers();
//Set viewdates and render
switch(this.view) {
case 'month': this.renderYear(); break;
case 'year': this.renderDecade(); break;
}
//Tween the new view in and old view out
this.transitioning = true;
this.currentContainer.set('tween', { 'duration': this.options.fadeDuration, 'transition': this.options.fadeTransition,
'onComplete': function() { this.transitioning = false }.bind(this) }).setStyles({'opacity': 0, 'left': 0}).fade('in');
this.tempContainer.set('tween', { 'duration': this.options.fadeDuration, 'transition': this.options.fadeTransition }).fade('out');
},
switchContainers: function() {
this.currentContainer = this.currentContainer.hasClass('a') ? this.element.getElement('.container.b') : this.element.getElement('.container.a');
this.tempContainer = this.tempContainer.hasClass('a') ? this.element.getElement('.container.b') : this.element.getElement('.container.a');
this.currentContainer.empty().removeClass('month').removeClass('year-decade').setStyles({ 'opacity': 1, 'display': 'block', 'z-index': 999 });
this.tempContainer.setStyle('z-index', 998);
this.label.addClass('clickable');
this.arrowLeft.setStyle('visibility', 'visible');
this.arrowRight.setStyle('visibility', 'visible');
},
pick: function(e) {
if($defined(e)) {
this.selectedDate = e.target.date;
this.element.getElements('.selected').removeClass('selected');
e.target.addClass('selected');
}
var value = this.format(this.selectedDate);
if(!this.options.injectInsideTarget) {
switch(this.target.get('tag')) {
case 'input': this.target.set('value', value); break;
default: this.target.set('html', value);
}
(this.hide.bind(this)).delay(150);
}
if($defined(this.hiddenInput)) this.hiddenInput.set('value', this.format(this.selectedDate, this.options.hiddenInputFormat));
this.options.pickFunction(this.selectedDate);
},
position: function() {
var top, left;
var coordinates = this.target.getCoordinates();
switch(this.options.alignX) {
case 'left':
left = coordinates.left;
break;
case 'middle':
left = coordinates.left + (coordinates.width / 2) - (this.element.getWidth() / 2);
break;
case 'right': default:
left = coordinates.left + coordinates.width;
}
switch(this.options.alignY) {
case 'bottom':
top = coordinates.top + coordinates.height;
break;
case 'top':
top = coordinates.top - this.element.getHeight();
break;
case 'ceiling': default:
top = coordinates.top;
}
left += this.options.offsetX.toInt();
top += this.options.offsetY.toInt();
this.element.setStyles({ 'top': top, 'left': left });
},
show: function() {
if(!this.visible & !this.options.alwaysShow) {
this.visible = true;
if(!Browser.Engine.trident) {
this.element.setStyles({ 'opacity': 0, 'display': 'block' });
if(!this.options.injectInsideTarget) this.position();
this.element.set('tween', { 'duration': this.options.toggleDuration, 'transition': this.options.fadeTransition }).fade('in');
} else {
this.element.setStyles({ 'opacity': 1, 'display': 'block' });
if(!this.options.injectInsideTarget) this.position();
}
}
},
hide: function() {
if(this.visible & !this.options.alwaysShow) {
this.visible = false;
if(!Browser.Engine.trident) {
this.element.set('tween', { 'duration': this.options.toggleDuration, 'transition': this.options.fadeTransition,
'onComplete': function() { this.element.setStyle('display', 'none') }.bind(this) }).fade('out');
} else this.element.setStyle('display', 'none');
}
},
toggle: function() {
if(this.visible) this.hide();
else this.show();
},
format: function(date, format) {
if(!$defined(format)) format = this.options.format;
if(!$defined(date)) return;
format = format.replace(/%([a-z%])/gi,
function($1, $2) {
switch($2) {
case 'D': return date.get('date');
case 'n': return date.get('mo') + 1;
case 't': return (date.getTime() / 1000).toInt();
}
return '%'+ $2;
}
);
return date.format(format);
},
outsideClick: function(e) {
if(this.visible) {
var elementCoords = this.element.getCoordinates();
var targetCoords = this.target.getCoordinates();
if(((e.page.x < elementCoords.left || e.page.x > (elementCoords.left + elementCoords.width)) ||
(e.page.y < elementCoords.top || e.page.y > (elementCoords.top + elementCoords.height))) &&
((e.page.x < targetCoords.left || e.page.x > (targetCoords.left + targetCoords.width)) ||
(e.page.y < targetCoords.top || e.page.y > (targetCoords.top + targetCoords.height))) ) this.hide();
}
},
//Version 1.0.1 addition, can easily be called from outside
setDate: function(value, pick) {
if(!$defined(pick)) pick = true;
if($type(value) == 'date') {
var date = value.clearTime();
} else {
var date = $chk(value) ? new Date().parse(this.target.get('value')).clearTime() : new Date().clearTime();
}
if(date.isValid()) {
this.selectedDate = date.clone();
this.viewDate = this.selectedDate.clone().set('date', 1);
this.render();
if(pick) this.pick();
}
}
});
Style.css is
.calendar-eightysix .body {
position: relative;
}
.calendar-eightysix .body .inner .container {
position: absolute;
left: 0;
}

In jquery replace the switchContainers: function() with
switchContainers: function() {
this.currentContainer = this.currentContainer.hasClass('a') ? this.element.getElement('.container.b') : this.element.getElement('.container.a');
this.tempContainer = this.tempContainer.hasClass('a') ? this.element.getElement('.container.b') : this.element.getElement('.container.a');
this.currentContainer.empty().removeClass('month').removeClass('year-decade').setStyles({ 'opacity': 1, 'display': 'block', 'z-index': 999 });
this.tempContainer.setStyles({ 'display': 'none', 'z-index': 998 });
this.currentContainer.hasClass('a') ? this.currentContainer.setStyles({ 'opacity': 1, 'display': 'block', 'z-index': 999 }) : '';
this.label.addClass('clickable');
this.arrowLeft.setStyle('visibility', 'visible');
this.arrowRight.setStyle('visibility', 'visible');
},
In style.css
Replace the .calendar-eightysix .body .inner .container with
.calendar-eightysix .body .inner .container {
left: 0;
}

Related

Why the coordinates of a polygon in Google Map returns false Lat, Lng values?

Here is my code that i am using for fetching data from Google Maps also fetching coordinates of polygon and polylines from Drawer.
**
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta charset="UTF-8" />
<title>Muhammad</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&libraries=drawing"></script>
<style type="text/css">
#map,
html,
body {
padding: 0;
margin: 0;
width: 95%;
height: 700px;
float: right;
}
#panel {
width: 200px;
font-family: Arial, sans-serif;
font-size: 13px;
float: right;
margin: 10px;
}
#color-palette {
clear: both;
}
.color-button {
width: 14px;
height: 14px;
font-size: 0;
margin: 2px;
float: left;
cursor: pointer;
}
#delete-button {
margin-top: 5px;
}
</style>
<script type="text/javascript">
var drawingManager;
var selectedShape;
var colors = ["#1E90FF", "#FF1493", "#32CD32", "#FF8C00", "#4B0082"];
var selectedColor;
var colorButtons = {};
function clearSelection() {
if (selectedShape) {
selectedShape.setEditable(false);
selectedShape = null;
}
}
function setSelection(shape) {
clearSelection();
// getting shape coordinates
var v = shape.getPath();
var coords = [];
for (var i = 0; i < v.getLength(); i++) {
var xy = v.getAt(i);
console.log(`Cordinate lat ${i}: ` + xy.lat() + `and long ${i}: ` + xy.lng());
var x = document.createElement('INPUT');
x.setAttribute('type', 'text');
x.setAttribute('value', xy);
document.body.appendChild(x);
coords.push([xy.lat()], [xy.lng()]);
}
console.log(coords + 'Muhammad');
document.getElementById('coords_value').value = coords;
selectedShape = shape;
shape.setEditable(true);
selectColor(shape.get("fillColor") || shape.get("strokeColor"));
}
function saveButton(shape) {
}
function deleteSelectedShape() {
if (selectedShape) {
selectedShape.setMap(null);
}
}
function selectColor(color) {
selectedColor = color;
for (var i = 0; i < colors.length; ++i) {
var currColor = colors[i];
colorButtons[currColor].style.border = currColor == color ? "2px solid #789" : "2px solid #fff";
}
// Retrieves the current options from the drawing manager and replaces the
// stroke or fill color as appropriate.
var polylineOptions = drawingManager.get("polylineOptions");
polylineOptions.strokeColor = color;
drawingManager.set("polylineOptions", polylineOptions);
var rectangleOptions = drawingManager.get("rectangleOptions");
rectangleOptions.fillColor = color;
drawingManager.set("rectangleOptions", rectangleOptions);
var circleOptions = drawingManager.get("circleOptions");
circleOptions.fillColor = color;
drawingManager.set("circleOptions", circleOptions);
var polygonOptions = drawingManager.get("polygonOptions");
polygonOptions.fillColor = color;
drawingManager.set("polygonOptions", polygonOptions);
}
function setSelectedShapeColor(color) {
console.log("fn setSelectedShapeColor()");
console.log(selectedShape);
if (selectedShape) {
if (selectedShape.type == google.maps.drawing.OverlayType.POLYLINE) {
selectedShape.set("strokeColor", color);
} else {
selectedShape.set("fillColor", color);
}
}
}
function makeColorButton(color) {
var button = document.createElement("span");
button.className = "color-button";
button.style.backgroundColor = color;
google.maps.event.addDomListener(button, "click", function() {
selectColor(color);
setSelectedShapeColor(color);
});
return button;
}
function buildColorPalette() {
var colorPalette = document.getElementById("color-palette");
for (var i = 0; i < colors.length; ++i) {
var currColor = colors[i];
var colorButton = makeColorButton(currColor);
colorPalette.appendChild(colorButton);
colorButtons[currColor] = colorButton;
}
selectColor(colors[0]);
}
function initialize() {
var pakistan = new google.maps.LatLng(30.3753, 69.3451);
var map = new google.maps.Map(document.getElementById("map"), {
zoom: 3,
center: pakistan,
disableDefaultUI: true,
zoomControl: true
});
var marker = new google.maps.Marker({
position: pakistan,
map: map
});
var polyOptions = {
strokeWeight: 0,
fillOpacity: 0.45,
editable: true,
draggable: true
};
// Creates a drawing manager attached to the map that allows the user to draw
// markers, lines, and shapes.
drawingManager = new google.maps.drawing.DrawingManager({
drawingMode: google.maps.drawing.OverlayType.POLYGON,
markerOptions: {
draggable: true
},
polylineOptions: {
editable: true,
draggable: true
},
rectangleOptions: polyOptions,
circleOptions: polyOptions,
polygonOptions: polyOptions,
map: map
});
google.maps.event.addListener(drawingManager, "overlaycomplete", function(e) {
if (e.type !== google.maps.drawing.OverlayType.MARKER) {
// Switch back to non-drawing mode after drawing a shape.
drawingManager.setDrawingMode(null);
// Add an event listener that selects the newly-drawn shape when the user
// mouses down on it.
var newShape = e.overlay;
newShape.type = e.type;
google.maps.event.addListener(newShape, "click", function(e) {
if (e.vertex !== undefined) {
if (newShape.type === google.maps.drawing.OverlayType.POLYGON) {
var path = newShape.getPaths().getAt(e.path);
path.removeAt(e.vertex);
if (path.length < 3) {
newShape.setMap(null);
}
}
if (newShape.type === google.maps.drawing.OverlayType.POLYLINE) {
var path = newShape.getPath();
path.removeAt(e.vertex);
if (path.length < 2) {
newShape.setMap(null);
}
}
}
setSelection(newShape);
saveButton(newShape);
});
setSelection(newShape);
saveButton(newShape);
}
});
// Clear the current selection when the drawing mode is changed, or when the
// map is clicked.
google.maps.event.addListener(drawingManager, "drawingmode_changed", clearSelection);
google.maps.event.addListener(map, "click", clearSelection);
google.maps.event.addDomListener(document.getElementById("delete-button"), "click", deleteSelectedShape);
buildColorPalette();
}
google.maps.event.addDomListener(window, "load", initialize);
var IO = {
//returns array with storable google.maps.Overlay-definitions
IN: function(
arr, //array with google.maps.Overlays
encoded //boolean indicating if pathes should be stored encoded
) {
var shapes = [],
goo = google.maps,
shape,
tmp;
for (var i = 0; i < arr.length; i++) {
shape = arr[i];
tmp = {
type: this.t_(shape.type),
id: shape.id || null
};
switch (tmp.type) {
case "CIRCLE":
tmp.radius = shape.getRadius();
tmp.geometry = this.p_(shape.getCenter());
break;
case "MARKER":
tmp.geometry = this.p_(shape.getPosition());
break;
case "RECTANGLE":
tmp.geometry = this.b_(shape.getBounds());
break;
case "POLYLINE":
tmp.geometry = this.l_(shape.getPath(), encoded);
break;
case "POLYGON":
tmp.geometry = this.m_(shape.getPaths(), encoded);
break;
}
shapes.push(tmp);
}
return shapes;
},
//returns array with google.maps.Overlays
OUT: function(
arr, //array containg the stored shape-definitions
map //map where to draw the shapes
) {
var shapes = [],
goo = google.maps,
map = map || null,
shape,
tmp;
for (var i = 0; i < arr.length; i++) {
shape = arr[i];
switch (shape.type) {
case "CIRCLE":
tmp = new goo.Circle({
radius: Number(shape.radius),
center: this.pp_.apply(this, shape.geometry)
});
break;
case "MARKER":
tmp = new goo.Marker({
position: this.pp_.apply(this, shape.geometry)
});
break;
case "RECTANGLE":
tmp = new goo.Rectangle({
bounds: this.bb_.apply(this, shape.geometry)
});
break;
case "POLYLINE":
tmp = new goo.Polyline({
path: this.ll_(shape.geometry)
});
break;
case "POLYGON":
tmp = new goo.Polygon({
paths: this.mm_(shape.geometry)
});
break;
}
tmp.setValues({
map: map,
id: shape.id
});
shapes.push(tmp);
}
return shapes;
},
l_: function(path, e) {
path = path.getArray ? path.getArray() : path;
if (e) {
return google.maps.geometry.encoding.encodePath(path);
} else {
var r = [];
for (var i = 0; i < path.length; ++i) {
r.push(this.p_(path[i]));
}
return r;
}
},
ll_: function(path) {
if (typeof path === "string") {
return google.maps.geometry.encoding.decodePath(path);
} else {
var r = [];
for (var i = 0; i < path.length; ++i) {
r.push(this.pp_.apply(this, path[i]));
}
return r;
}
},
m_: function(paths, e) {
var r = [];
paths = paths.getArray ? paths.getArray() : paths;
for (var i = 0; i < paths.length; ++i) {
r.push(this.l_(paths[i], e));
}
return r;
},
mm_: function(paths) {
var r = [];
for (var i = 0; i < paths.length; ++i) {
r.push(this.ll_.call(this, paths[i]));
}
return r;
},
p_: function(latLng) {
return [latLng.lat(), latLng.lng()];
},
pp_: function(lat, lng) {
return new google.maps.LatLng(lat, lng);
},
b_: function(bounds) {
return [this.p_(bounds.getSouthWest()), this.p_(bounds.getNorthEast())];
},
bb_: function(sw, ne) {
return new google.maps.LatLngBounds(this.pp_.apply(this, sw), this.pp_.apply(this, ne));
},
t_: function(s) {
var t = ["CIRCLE", "MARKER", "RECTANGLE", "POLYLINE", "POLYGON"];
for (var i = 0; i < t.length; ++i) {
if (s === google.maps.drawing.OverlayType[t[i]]) {
return t[i];
}
}
}
};
</script>
</head>
<body>
<div id="panel">
<div id="color-palette"></div>
<form method="POST" action="submit.php">
<input type="text" id="coords_value" name="coords" value="Muhammad">
<button onclick="saveButton()">Muhammad</button>
</form>
<div><button id="delete-button">Delete Selected Shape</button></div>
</div>
<div id="map"></div>
</body>
</html>
**
and my submit.php file
**
<?php $servername = "localhost";
$username = "root";
$password = "";
$db = "users";
$mysqli = new mysqli($servername, $username, $password, $db);
// SET #g = 'POLYGON($_POST[coords])';
$coords = $_POST['coords'];
//$stmt = "INSERT INTO polygon_data (polygon_values) VALUES (GeomFromText('POLYGON((30 10, 40 40, 20 40, 10 20, 30 10))'))";
$stmt = "INSERT INTO polygon_data (polygon_values) VALUES (PolygonFromText('POLYGON((40.95269385429521, -74.14416921914062,40.959175907354734, -74.11670339882812,40.9419322410085, -74.13009298623047))'))";
if ($mysqli->query($stmt) === TRUE) {
echo "feedback sucessfully submitted";
} else {
echo "Error: " . $stmt . "<br>" . $mysqli->error;
}
$mysqli->close();
?>
**
For example if i draw a pollygon and then i gets the following points that are not correct, this is because in a polygon the first and last point's coordinates would be same but in mine case it seems to be somehow different as below.
(61.81599137659937,102.17362172851564,62.956500953314375,117.64237172851564,56.80241721826492,111.84159047851564)
and this difference is a huge difference.And i did not getting my expecting result?
Thanks

Dynamic Web Twain - PHP - Adding Additional HTML Fields

I've got a Laravel project but I think I have an idea of how to incorporate the Dynamic Web Twain (https://www.dynamsoft.com/Products/WebTWAIN_Overview.aspx) into it.
The only problem is I'm not quite sure how I would go about adding additional fields to the scanner UI (like what you see here: https://demo.dynamsoft.com/dwt/online_demo_scan.aspx).
At the moment my Laravel site has a working upload portion to a model where I can submit attachments, however, with the attachment form are fields that include "visibility", "type", "upload location" etc. etc. But I can't seem to figure out how I would add fields like what I already use.
From what I've tested, this is an incredibly useful tool and would work well if I could integrate it into all aspects of my site.
The closest thing I can find is here: https://developer.dynamsoft.com/dwt/api-reference/uploading-downloading/sethttpformfield
Which references what is done in this demo: https://demo.dynamsoft.com/Samples/dwt/Scan-Documents-and-Upload-Them/DWT_Scan_Upload_Demo.html
As you can see, you can add a field name and field value, using the "+" button, but I want to add some fields in the form that are available immediately. The other issue that I might need to work around is if I use this demo and add a value and name, this is how everything is posted and I'm not sure how to translate to something my project can understand.
-----------------------------23491353817351
Content-Disposition: form-data; name="This is a field"
Wow
-----------------------------23491353817351
Content-Disposition: form-data; name="RemoteFile"; filename="507-0.jpg"
Content-Type: application/octet-stream
ÿØÿà
This aspect is a necessary part of my project, so unfortunately there's no real way around this besides moving forward.
This is the current script in the online demo:
Dynamsoft.WebTwainEnv.RegisterEvent('OnWebTwainReady', Dynamsoft_OnReady); // Register OnWebTwainReady event. This event fires as soon as Dynamic Web TWAIN is initialized and ready to be used
var DWObject, blankField = "", extrFieldsCount = 0, upload_returnSth = true;
var CurrentPathName = unescape(location.pathname);
var CurrentPath = CurrentPathName.substring(0, CurrentPathName.lastIndexOf("/") + 1);
var strHTTPServer = location.hostname;
var strActionPage;
var scriptLanguages = [
{ desc: "PHP", val: "php" },
{ desc: "PHP-MySQL", val: "phpMySQL" },
{ desc: "CSharp", val: "csharp" },
{ desc: "CSharp-MSSQL", val: "csMSSQL" },
{ desc: "VB.NET", val: "vbnet" },
{ desc: "VBNET-MSSQL", val: "vbnetMSSQL" },
{ desc: "JSP", val: "jsp" },
{ desc: "JSP-Oracle", val: "jspOracle" },
{ desc: "ASP", val: "asp" },
{ desc: "ASP-MSSQL", val: "aspMSSQL" },
{ desc: "ColdFusion", val: "cfm" },
{ desc: "CS-Azure", val: "csAzure" }
];
function languageSelected() {
if (document.getElementById("ddlLanguages").selectedIndex > 7)
upload_returnSth = false;
else
upload_returnSth = true;
if ([0, 2, 4, 6].indexOf(document.getElementById("ddlLanguages").selectedIndex) == -1) {
document.getElementById("extra-fields-div-id").style.display = 'none';
document.getElementById('div-extra-fields').style.display = 'none';
}
else {
document.getElementById("extra-fields-div-id").style.display = '';
if (document.getElementById('div-extra-fields').children.length > 1 ||
document.getElementById('div-extra-fields').children[0].children[0].value != '') {
document.getElementById('div-extra-fields').style.display = '';
}
}
}
function addAField() {
extrFieldsCount++;
if (extrFieldsCount == 3) {
document.getElementById('div-extra-fields').style.overflowY = 'scroll';
}
if (document.getElementById('div-extra-fields').style.display == "none")
document.getElementById('div-extra-fields').style.display = '';
else {
document.getElementById('div-extra-fields').appendChild(blankField);
blankField = document.getElementsByClassName('div-fields-item')[extrFieldsCount - 1].cloneNode(true);
}
}
function downloadPDFR() {
DCP_DWT_OnClickCloseInstall();
DWObject.Addon.PDF.Download(
CurrentPath + '/Resources/addon/Pdf.zip',
function () {/*console.log('PDF dll is installed');*/
},
function (errorCode, errorString) {
console.log(errorString);
}
);
}
function Dynamsoft_OnReady() {
blankField = document.getElementsByClassName('div-fields-item')[0].cloneNode(true);
DWObject = Dynamsoft.WebTwainEnv.GetWebTwain('dwtcontrolContainer'); // Get the Dynamic Web TWAIN object that is embeded in the div with id 'dwtcontrolContainer'
if (DWObject) {
DWObject.Width = 505;
DWObject.Height = 600;
for (var i = 0; i < scriptLanguages.length; i++)
document.getElementById("ddlLanguages").options.add(new Option(scriptLanguages[i].desc, i));
document.getElementById("ddlLanguages").options.selectedIndex = 2;
/*
* Make sure the PDF Rasterizer and OCR add-on are already installedsample
*/
if (!Dynamsoft.Lib.env.bMac) {
var localPDFRVersion = '';
if(Dynamsoft.Lib.product.bChromeEdition){
localPDFRVersion = DWObject._innerFun('GetAddOnVersion', '["pdf"]');
}
else {
localPDFRVersion = DWObject.getSWebTwain().GetAddonVersion("pdf");
}
if (localPDFRVersion != Dynamsoft.PdfVersion) {
var ObjString = [];
ObjString.push('<div class="p15" id="pdfr-install-dlg">');
ObjString.push('The <strong>PDF Rasterizer</strong> is not installed on this PC<br />Please click the button below to get it installed');
ObjString.push('<p class="tc mt15 mb15"><input type="button" value="Install PDF Rasterizer" onclick="downloadPDFR();" class="btn lgBtn bgBlue" /><hr></p>');
ObjString.push('<i><strong>The installation is a one-time process</strong> <br />It might take some time depending on your network.</i>');
ObjString.push('</div>');
Dynamsoft.WebTwainEnv.ShowDialog(400, 310, ObjString.join(''));
}
else {
/**/
}
}
}
}
function AcquireImage() {
if (DWObject) {
var bSelected = DWObject.SelectSource();
if (bSelected) {
var OnAcquireImageSuccess, OnAcquireImageFailure;
OnAcquireImageSuccess = OnAcquireImageFailure = function () {
DWObject.CloseSource();
};
DWObject.OpenSource();
DWObject.IfDisableSourceAfterAcquire = true; //Scanner source will be disabled/closed automatically after the scan.
DWObject.AcquireImage(OnAcquireImageSuccess, OnAcquireImageFailure);
}
}
}
function LoadImages() {
if (DWObject) {
DWObject.Addon.PDF.SetResolution(300);
DWObject.Addon.PDF.SetConvertMode(EnumDWT_ConverMode.CM_RENDERALL);
DWObject.LoadImageEx('', 5,
function () {
},
function (errorCode, errorString) {
alert('Load Image:' + errorString);
}
);
}
}
function OnHttpUploadSuccess() {
console.log('successful');
}
function OnHttpServerReturnedSomething(errorCode, errorString, sHttpResponse) {
//console.log(errorString);
var textFromServer = sHttpResponse;
_printUploadedFiles(textFromServer);
}
function _printUploadedFiles(info) {
//console.log(info);
if (info.indexOf('DWTUploadFileName') != -1) {
var url, _strPort;
DWObject.IfSSL = Dynamsoft.Lib.detect.ssl;
_strPort = location.port == "" ? 80 : location.port
url = 'http://' + location.hostname + ':' + location.port
if (Dynamsoft.Lib.detect.ssl == true) {
_strPort = location.port == "" ? 443 : location.port;
url = 'https://' + location.hostname + ':' + location.port
}
var savedIntoToDB = false, imgIndexInDB = "-1";
if (info.indexOf("DWTUploadFileIndex:") != -1) {
savedIntoToDB = true;
imgIndexInDB = info.substring(info.indexOf('DWTUploadFileIndex') + 19, info.indexOf('DWTUploadFileName'));
//console.log(imgIndexInDB);
}
var fileName = info.substring(info.indexOf('DWTUploadFileName') + 18, info.indexOf('UploadedFileSize'));
var fileSize = info.substr(info.indexOf('UploadedFileSize') + 17);
if (savedIntoToDB) {
if (info.indexOf('CSHARP') != -1) {
url += CurrentPath + 'action/csharp-db.aspx?imgID=' + imgIndexInDB;
}
else if (info.indexOf('VBNET') != -1) {
url += CurrentPath + 'action/vbnet-db.aspx?imgID=' + imgIndexInDB;
}
else if (info.indexOf('PHP') != -1) {
url += CurrentPath + 'action/php-mysql.php?imgID=' + imgIndexInDB;
}
else if (info.indexOf('JSP') != -1) {
url += CurrentPath + 'action/jsp-oracle.jsp?imgID=' + imgIndexInDB;
}
}
else {
url += CurrentPath + 'action/UploadedImages/' + encodeURI(fileName);
}
var newTR = document.createElement('tr');
_str = "<td class='tc'><a class='bluelink'" + ' href="' + url + '" target="_blank">' + fileName + "</a></td>"
+ "<td class='tc'>" + fileSize + '</td>';
if (info.indexOf("FieldsTrue:") != -1)
_str += "<td class='tc'><a class='bluelink'" + '" href="' + url.substring(0, url.length - 4) + '_1.txt' + '" target="_blank">Fields</td>';
else {
_str += "<td class='tc'>No Fields</td>";
}
newTR.innerHTML = _str;
document.getElementById('div-uploadedFile').appendChild(newTR);
}
}
function upload_preparation(_name) {
DWObject.IfShowCancelDialogWhenImageTransfer = !document.getElementById('quietScan').checked;
strActionPage = CurrentPath + 'action/';
switch (document.getElementById("ddlLanguages").options.selectedIndex) {
case 0: strActionPage += "php.php"; break;
case 2: strActionPage += "csharp.aspx"; break;
case 6: strActionPage += "jsp.jsp"; break;
case 4: strActionPage += "vbnet.aspx"; break;
case 8: strActionPage += "asp.asp"; break;
case 10: strActionPage += "cfm.cfm"; break;
case 1: strActionPage += "php-mysql.php?imgID=new"; break;
case 7: strActionPage += "jsp-oracle.jsp?imgID=new"; break;
case 3: strActionPage += "csharp-db.aspx?imgID=new"; break;
case 5: strActionPage += "vbnet-db.aspx?imgID=new"; break;
case 9: strActionPage += "asp-db.asp"; break;
case 11: preparetoUploadtoAzure(_name); break;
default: break;
}
DWObject.IfSSL = Dynamsoft.Lib.detect.ssl;
var _strPort = location.port == "" ? 80 : location.port;
if (Dynamsoft.Lib.detect.ssl == true)
_strPort = location.port == "" ? 443 : location.port;
DWObject.HTTPPort = _strPort;
if ([0, 2, 4, 6].indexOf(document.getElementById("ddlLanguages").selectedIndex) != -1) {
/* Add Fields to the Post */
var fields = document.getElementsByClassName('div-fields-item');
DWObject.ClearAllHTTPFormField();
for (var n = 0; n < fields.length; n++) {
var o = fields[n];
if (o.children[0].value != '')
DWObject.SetHTTPFormField(o.children[0].value, o.children[1].value);
}
}
}
function UploadImage_inner() {
if (DWObject.HowManyImagesInBuffer == 0)
return;
var Digital = new Date();
var uploadfilename = Digital.getMilliseconds(); // Uses milliseconds according to local time as the file name
upload_preparation(uploadfilename);
// Upload the image(s) to the server asynchronously
if (document.getElementById("ddlLanguages").options.selectedIndex == 11 /*Azure*/) return;
if (document.getElementsByName('ImageType')[0].checked) {
var uploadIndexes = [];
for (var i = DWObject.HowManyImagesInBuffer - 1; i > -1 ; i--) {
uploadIndexes.push(i);
}
var uploadJPGsOneByOne = function (errorCode, errorString, sHttpResponse) {
if (upload_returnSth)
_printUploadedFiles(sHttpResponse);
if (uploadIndexes.length > 0) {
var _index = uploadIndexes.pop();
if (upload_returnSth)
DWObject.HTTPUploadThroughPost(strHTTPServer, _index, strActionPage, uploadfilename + "-" + _index.toString() + ".jpg", OnHttpUploadSuccess, uploadJPGsOneByOne);
else
DWObject.HTTPUploadThroughPost(strHTTPServer, _index, strActionPage, uploadfilename + "-" + _index.toString() + ".jpg", uploadJPGsOneByOne, OnHttpServerReturnedSomething);
}
}
var _index = uploadIndexes.pop();
if (upload_returnSth)
DWObject.HTTPUploadThroughPost(strHTTPServer, _index, strActionPage, uploadfilename + "-" + _index.toString() + ".jpg", OnHttpUploadSuccess, uploadJPGsOneByOne);
else
DWObject.HTTPUploadThroughPost(strHTTPServer, _index, strActionPage, uploadfilename + "-" + _index.toString() + ".jpg", uploadJPGsOneByOne, OnHttpServerReturnedSomething);
}
else if (document.getElementsByName('ImageType')[1].checked) {
DWObject.HTTPUploadAllThroughPostAsMultiPageTIFF(strHTTPServer, strActionPage, uploadfilename + ".tif", OnHttpUploadSuccess, OnHttpServerReturnedSomething);
}
else if (document.getElementsByName('ImageType')[2].checked) {
DWObject.HTTPUploadAllThroughPostAsPDF(strHTTPServer, strActionPage, uploadfilename + ".pdf", OnHttpUploadSuccess, OnHttpServerReturnedSomething);
}
}
function UploadImage() {
if (DWObject) {
var nCount = 0, nCountUpLoaded = 0, aryFilePaths = [];
if (document.getElementById('uploadDirectly').checked) {
DWObject.IfShowCancelDialogWhenImageTransfer = false;
function ds_load_file_to_upload_directly(bSave, filesCount, index, path, filename) {
nCount = filesCount;
var filePath = path + "\\" + filename;
aryFilePaths.push(filePath);
if (aryFilePaths.length == nCount) {
upload_preparation();
var i = 0;
function uploadFileOneByOne() {
DWObject.HTTPUploadThroughPostDirectly(strHTTPServer, filePath, strActionPage, filename,
function () {
console.log('Upload Image:' + aryFilePaths[i] + ' -- successful');
i++;
if (i != nCount)
uploadFileOneByOne();
else
DWObject.UnregisterEvent('OnGetFilePath', ds_load_file_to_upload_directly);
},
OnHttpServerReturnedSomething
);
}
uploadFileOneByOne();
}
}
DWObject.RegisterEvent('OnGetFilePath', ds_load_file_to_upload_directly);
DWObject.ShowFileDialog(false, "Any File | *.*", 0, "", "", true, true, 0);
}
else {
UploadImage_inner();
}
}
}
/*******************/
/* Upload to Azure */
var Base64Binary = {
_keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
decode: function (input, arrayBuffer) {
//get last chars to see if are valid
var lkey1 = this._keyStr.indexOf(input.charAt(input.length - 1));
var lkey2 = this._keyStr.indexOf(input.charAt(input.length - 2));
var bytes = (input.length / 4) * 3;
if (lkey1 == 64) bytes--; //padding chars, so skip
if (lkey2 == 64) bytes--; //padding chars, so skip
var uarray;
var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4;
var i = 0;
var j = 0;
if (arrayBuffer)
uarray = new Uint8Array(arrayBuffer);
else
uarray = new Uint8Array(bytes);
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
for (i = 0; i < bytes; i += 3) {
//get the 3 octects in 4 ascii chars
enc1 = this._keyStr.indexOf(input.charAt(j++));
enc2 = this._keyStr.indexOf(input.charAt(j++));
enc3 = this._keyStr.indexOf(input.charAt(j++));
enc4 = this._keyStr.indexOf(input.charAt(j++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
uarray[i] = chr1;
if (enc3 != 64) uarray[i + 1] = chr2;
if (enc4 != 64) uarray[i + 2] = chr3;
}
return uarray;
}
}
function uploadImageInner_azure(blobSasUrl, fileDataAsArrayBuffer) {
var ajaxRequest = new XMLHttpRequest();
try {
ajaxRequest.open('PUT', blobSasUrl, true);
ajaxRequest.setRequestHeader('x-ms-blob-type', 'BlockBlob');
ajaxRequest.send(fileDataAsArrayBuffer);
ajaxRequest.onreadystatechange = function () {
if (ajaxRequest.readyState == 4) {
console.log('Upload image to azure server successfully.');
}
}
}
catch (e) {
console.log("can't upload the image to server.\n" + e.toString());
}
}
function preparetoUploadtoAzure(__name) {
var uploadfilename = '';
//For JPEG, upload the current image
if (document.getElementsByName('ImageType')[0].checked) {
DWObject.SelectedImagesCount = 1;
DWObject.SetSelectedImageIndex(0, DWObject.CurrentImageIndexInBuffer);
DWObject.GetSelectedImagesSize(EnumDWT_ImageType.IT_JPG);
uploadfilename = __name + '.jpg';
}
else { //For TIFF, PDF, upload all images
var count = DWObject.HowManyImagesInBuffer;
DWObject.SelectedImagesCount = count;
for (var i = 0; i < count; i++) {
DWObject.SetSelectedImageIndex(i, i);
}
if (document.getElementsByName('ImageType')[1].checked) {
DWObject.GetSelectedImagesSize(EnumDWT_ImageType.IT_TIF);
uploadfilename = __name + '.tif';
}
else {
DWObject.GetSelectedImagesSize(EnumDWT_ImageType.IT_PDF);
uploadfilename = __name + '.pdf';
}
}
var strImg, aryImg, _uint8_STR, _bin_ARR, _blobImg;
strImg = DWObject.SaveSelectedImagesToBase64Binary();
// convert base64 to Uint8Array
var bytes = (strImg.length / 4) * 3;
var _temp = new ArrayBuffer(bytes);
_uint8_STR = Base64Binary.decode(strImg, _temp);
// convert Uint8Array to blob
_blobImg = new Blob([_uint8_STR]);
// upload to Azure server
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
uploadImageInner_azure(xhr.responseText, _blobImg);
}
}
var actionPageFullPath = CurrentPath + 'action/' + 'azure.aspx?imageName=' + uploadfilename;
xhr.open('GET', actionPageFullPath, true);
xhr.send();
}
/*******************/

Highcharts data from MySQL / PHP

I am trying to build the data for my Highcharts chart but I'm having trouble when a certain day has no rows.
I.e. I want a chart to show enquiries per day for the current week. If no enquiries were received on Wednesday, then that day is missing from my chart or the data from Thursday falls into Wednesday which is wrong, depending on what I do.
SQL I have:
$W = date('W');
$Y = date('Y');
$SQL = "SELECT DATE_FORMAT(enquiries.dateCreated, '%a') AS name, COUNT(*) AS y
FROM enquiries
WHERE WEEK(enquiries.dateCreated, 1) = $W
AND YEAR(enquiries.dateCreated) = $Y
GROUP BY DAY(enquiries.dateCreated)";
$result = $this->db->prepare($SQL);
$result->execute();
return $result->fetchAll(PDO::FETCH_ASSOC);
And my current attempt to put it into an array which doesn't work:
$enquiries = $this->model->enquiriesTime();
$dayData = array();
for ($i = 0; $i != 5; $i++) {
if ($enquiries[$i]['name'] == 'Mon' || $enquiries[$i]['name'] == 'Tue' || $enquiries[$i]['name'] == 'Wed' || $enquiries[$i]['name'] == 'Thu' || $enquiries[$i]['name'] == 'Fri') {
$dayData[$i] = $enquiries[$i]['y'];
} else {
$dayData[$i] = '0';
}
}
When a day doesn't exist the 0 gets added to the end of the array and not index 2 (Wednesday) like it should, so Wednesday's results are actually Thursdays.
How can I get this to work properly?
Here is the JS:
function createActivityChart() {
$.ajax({
url: ROOT + 'Ajax',
data: {
call: 'lists->enquiriesTime'
},
dataType: 'json',
type: 'POST',
async: true,
success: function(returned) {
$('#enquiriesChart').highcharts({
chart: {
type: 'column'
},
title: {
text: 'Weekly activity chart'
},
xAxis: {
categories: [
'Mon',
'Tue',
'Wed',
'Thu',
'Fri'
]
},
yAxis: {
min: 0,
title: null,
stackLabels: {
enabled: true,
style: {
fontWeight: 'bold',
color: (Highcharts.theme && Highcharts.theme.textColor) || 'gray'
}
}
},
tooltip: {
headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
'<td style="padding:0"><b>{point.y:.0f}</b></td></tr>',
footerFormat: '</table>',
shared: true,
useHTML: true
},
plotOptions: {
column: {
stacking: 'normal',
dataLabels: {
enabled: false,
color: (Highcharts.theme && Highcharts.theme.dataLabelsColor) || 'white',
style: {
textShadow: '0 0 3px black, 0 0 3px black'
}
}
}
},
series: returned
});
}
})
}
And the HTML container:
<div class="row-fluid">
<div class="span12">
<div class="gridData">
<div id="activityChart" style="min-width: 200px; height: 200px; margin: 0 auto"></div>
</div>
</div>
</div>
What I use to do to avoid your problem is create the highchart array with all 0 values, and then overwrite them. This way you make sure no data is left behind.
I appear to have done it using this horrendous logic ladder:
for ($i = 0; $i != 5; $i++) {
if ($i == 0) {
if ($enquiries[$i]['name'] == 'Mon') {
$dayData[$i] = $enquiries[$i]['y'];
} else {
$enquiriesI = array(array('name' => 'Mon', 'y' => 0));
array_splice($enquiries, 0, 0, $enquiriesI);
$dayData[$i] = 0;
}
}
if ($i == 1) {
if ($enquiries[$i]['name'] == 'Tue') {
$dayData[$i] = $enquiries[$i]['y'];
} else {
$enquiriesI = array(array('name' => 'Tue', 'y' => 0));
array_splice($enquiries, 1, 0, $enquiriesI);
$dayData[$i] = 0;
}
}
if ($i == 2) {
if ($enquiries[$i]['name'] == 'Wed') {
$dayData[$i] = $enquiries[$i]['y'];
} else {
$enquiriesI = array(array('name' => 'Wed', 'y' => 0));
array_splice($enquiries, 2, 0, $enquiriesI);
$dayData[$i] = 0;
}
}
if ($i == 3) {
if ($enquiries[$i]['name'] == 'Thu') {
$dayData[$i] = $enquiries[$i]['y'];
} else {
$enquiriesI = array(array('name' => 'Thu', 'y' => 0));
array_splice($enquiries, 3, 0, $enquiriesI);
$dayData[$i] = 0;
}
}
if ($i == 4) {
if ($enquiries[$i]['name'] == 'Fri') {
$dayData[$i] = $enquiries[$i]['y'];
} else {
$enquiriesI = array(array('name' => 'Fri', 'y' => 0));
array_splice($enquiries, 4, 0, $enquiriesI);
$dayData[$i] = 0;
}
}
}
There must be a better way?
I have found that the above method works well for week days and the following method for days of the month:
public function parseMonthlyGraph($SQLResults) { // For days
$dayData = array();
$startDate = date('Y-m').'-01';
$lastDay = date("t", strtotime($startDate));
for ($i = 0; $i != 31; $i++) {
if($i == $lastDay)
{
break;
}
$dayName = date('jS', strtotime($startDate . ' + '.$i.' days'));
if ($SQLResults[$i]['name'] == $dayName) {
$dayData[$i] = $SQLResults[$i]['y'];
if (empty($SQLResults[$i + 1])) {
$SQLResults[$i + 1]['name'] = date('jS', strtotime($startDate . ' + ' . $i+1 . +' days'));
$SQLResults[$i + 1]['y'] = 0;
}
} else {
$enquiriesI = array(array('name' => $dayName, 'y' => 0));
array_splice($SQLResults, $i, 0, $enquiriesI);
$dayData[$i] = 0;
}
}
return $dayData;
}

Redirect to homepage from splash page magento

I am trying to redirect to my homepage from a splash (age verification) page, and it just keeps popping up the same age verification page.
I have the ageVerify.php script in the root folder and I have the other script at the top of my template file page. I just need to find the correct file structure format to redirect too after someone hits "yes i'm 18"
The code below doesn't work when added to the top of my column1.phtml file - it just keeps going back and recalling the verify.php script. Any ideas would be very helpful!
<?php
function verified()
{
$redirect_url='http://www.johnsoncreeksmokejuice.com.vhost.zerolag.com/verify.php';
$expires=-1;
session_start();
$validated=false;
if (!empty($_COOKIE["verified"])) {
$validated=true;
}
if (!$validated && isset($_SESSION['verified'])) {
$validated=true;
}
if (is_numeric($expires) && $expires==-1 && !isset($_SESSION['verified'])) {
$validated=false;
}
if ($validated) {
return;
}
else {
$redirect_url=$redirect_url."?return=index.php&x=".$expires;
Header('Location: '.$redirect_url);
exit(0);
}
}
verified();
?>
If $_SESSION is not set always will evaluate this
if (is_numeric($expires) && $expires==-1 && !isset($_SESSION['verified'])) {
$validated=false;
}
Just fix it and should work.
Assuming that everything else is fine, I would replace
if (!empty($_COOKIE["verified"])) {
$validated=true;
}
if (!$validated && isset($_SESSION['verified'])) {
$validated=true;
}
if (is_numeric($expires) && $expires==-1 && !isset($_SESSION['verified'])) {
$validated=false;
}
By:
if ( (isset($_COOKIE["verified"] && !empty($_COOKIE["verified"])) OR isset($_SESSION['verified']) ) {
$validated=true;
}
So, if user has a non-empty "verified" cookie or a "verified" session set, it assumes he is validated.
Chose to use a javascript alternative. Worked out much easier for me:
function writeCookie(key,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = key+"="+value+expires+"; path=/";
}
function readCookie(key) {
var nameEQ = key + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function ageGate() {
var monthDays = {
1: 31,
2: 29,
3: 31,
4: 30,
5: 31,
6: 30,
7: 31,
8: 31,
9: 30,
10: 31,
11: 30,
12: 31
};
var months = {
1: 'January',
2: 'February',
3: 'March',
4: 'April',
5: 'May',
6: 'June',
7: 'July',
8: 'August',
9: 'September',
10: 'October',
11: 'November',
12: 'December'
};
var monthOptions = [];
var dayOptions = {};
var yearOptions = [];
for (var month in monthDays) {
var days = monthDays[month];
monthOptions.push('<option value="' + month + '">' + months[month] + '</option>');
dayOptions[month] = [];
for (var i=1; i <= days; i++) {
var day = i;
dayOptions[month].push('<option value="' + day + '">' + day + '</option>');
}
}
var currentYear = new Date();
currentYear = currentYear.getFullYear();
var startYear = currentYear - 120;
for (var y=currentYear; y > startYear; y--) {
yearOptions.push('<option value="' + y + '">' + y + '</option>');
}
$s(document).ready(function(){
var monthHtml = '';
for (var j=0; j < monthOptions.length; j++) {
var html = monthOptions[j];
monthHtml += html;
}
$s('#ageMonth').html(monthHtml);
var yearHtml = '';
for (var i=0; i < yearOptions.length; i++) {
yearHtml += yearOptions[i];
}
$s('#ageYear').html(yearHtml);
$s('#ageMonth').bind('change', function(){
var dayHtml = '';
var month = $s(this).val();
for (var i=0; i < dayOptions[month].length; i++) {
dayHtml += dayOptions[month][i];
}
$s('#ageDay').html(dayHtml);
});
$s('#ageEnterSite').click(function(e){
e.preventDefault();
var date = new Date();
date.setMonth($s('#ageMonth').val() - 1);
date.setDate($s('#ageDay').val());
date.setYear($s('#ageYear').val());
var maxDate = new Date();
// alert(maxDate.getFullYear());
maxDate.setYear(maxDate.getFullYear() - 18);
if (date <= maxDate) {
writeCookie('jcsj_age_verified', '1', 30);
$s('#age-gate').fadeOut(function(){
$s(this).remove();
$s('body').removeClass('age-gate-visible');
});
}
else {
window.location.href = 'http://google.com';
}
});
$s('#ageMonth').change(); // load default month
// $s('#ageDay').prop('disabled', true);
setTimeout(function(){
$s('body').addClass('age-gate-visible');
$s('#age-gate').fadeIn();
}, 200);
});
}
if (readCookie('jcsj_age_verified')) {
} else {
ageGate();
}
</script>

Actionscript Serialization Class

I have an actionscript class that serializes and unserializes data compatible with php's serialization functions. I expanded it to support binary data but now the unserialization does not seem to work.
For example, this data is not unserialized correctly:
a:2:{i:0;s:1:"õ";i:1;a:2:{i:0;s:32:"mÎiyl·T=doÁ°ýNd_¤ÁÝ`:AåÁˆ#";i:1;s:32:"ÿ^ò`d^|“T¶&JÐÞG[±iÏ*Ÿ!–Ü’IÍ";}}
Here is the class:
package pack
{
import flash.utils.ByteArray;
import flash.utils.Dictionary;
import mx.collections.ArrayCollection;
import mx.controls.Alert;
import mx.core.*;
use namespace mx_internal;
public class Serializer extends Object
{
public static const version:String = "3.0.0";
mx_internal static var c:uint;
mx_internal static var pattern:RegExp = /[A-Z][a-z]{2}, \d{2} [A-Z][a-z]{2} \d{4} \d{2}:\d{2}:\d{2} \+|\-\d{4}/g
public static function serialize(data:*):ByteArray
{
var bas:ByteArray = new ByteArray();
var tmp:ByteArray = new ByteArray();
var i:int = 0;
var key:String;
if(data is Boolean){
bas.writeUTFBytes('b:');
bas.writeUnsignedInt(data);
bas.writeUTFBytes(';');
} else if(data is int){
bas.writeUTFBytes('i:');
bas.writeUTFBytes(data);
bas.writeUTFBytes(';');
} else if(data is Number){
bas.writeUTFBytes('d:');
bas.writeUTFBytes(data);
bas.writeUTFBytes(';');
} else if(data is ByteArray){
bas.writeUTFBytes('s:');
bas.writeUTFBytes(data.length.toString());
bas.writeUTFBytes(':"');
bas.writeBytes(data);
bas.writeUTFBytes('";');
} else if(data is String){
bas.writeUTFBytes('s:');
bas.writeUTFBytes(data.length.toString());
bas.writeUTFBytes(':"');
bas.writeUTFBytes(data);
bas.writeUTFBytes('";');
} else if(data is Date){
bas.writeUTFBytes('s:');
bas.writeUTFBytes(data.toString().length.toString());
bas.writeUTFBytes(':"');
bas.writeUTFBytes(data);
bas.writeUTFBytes('";');
} else if(data is ArrayCollection){
for(key in data){
tmp.writeBytes(Serializer.serialize(i));
tmp.writeBytes(Serializer.serialize(data[key]));
i += 1;
}
bas.writeUTFBytes('a:');
bas.writeUTFBytes(i.toString());
bas.writeUTFBytes(':{');
bas.writeBytes(tmp);
bas.writeUTFBytes('}');
} else if(data is Array){
for(key in data){
tmp.writeBytes(Serializer.serialize(i));
tmp.writeBytes(Serializer.serialize(data[key]));
i += 1;
}
bas.writeUTFBytes('a:');
bas.writeUTFBytes(i.toString());
bas.writeUTFBytes(':{');
bas.writeBytes(tmp);
bas.writeUTFBytes('}');
} else if(data is Object){
for(key in data){
tmp.writeBytes(Serializer.serialize(key));
tmp.writeBytes(Serializer.serialize(data[key]));
i += 1;
}
bas.writeUTFBytes('O:8:"stdClass":');
bas.writeUTFBytes(i.toString());
bas.writeUTFBytes(':{');
bas.writeBytes(tmp);
bas.writeUTFBytes('}');
} else if(data == null || data == undefined){
bas.writeUTFBytes('N;');
} else {
bas.writeUTFBytes('i:0;');
}
return bas;
}
public static function unserialize(data:ByteArray):*
{
Serializer.c = 0;
return Serializer.unserialize_internal(data);
}
mx_internal static function unserialize_internal(data:ByteArray):*
{
var result:*;
var tmpvar:*;
var tmp:Array = new Array();
var type:String = Serializer.charAt(data, Serializer.c);
var pos:uint = 0;
var islist:Boolean = true;
var i:uint;
switch(type){
case "N":
Serializer.c += 2;
break;
case "b":
result = Serializer.substr(data, Serializer.c+2, 1).toString() == '1'
//result = data.substr(Serializer.c+2, 1) == "1"
Serializer.c += 4
break;
case "i":
tmp.push(Serializer.indexOf(data, ';', Serializer.c));
//tmp.push(data.indexOf(";", Serializer.c))
pos = Serializer.c+2
Serializer.c = tmp[0]+1
result = int(Serializer.substring(data, pos, tmp[0]));
//result = int(data.substring(pos,tmp[0]))
break;
case "d":
tmp.push(Serializer.indexOf(data, ';', Serializer.c));
//tmp.push(data.indexOf(";", Serializer.c))
pos = Serializer.c + 2
Serializer.c = tmp[0]+1
result = Number(Serializer.substring(data, pos, tmp[0]));
//result = Number(data.substring(pos,tmp[0]))
break;
case "s":
tmp.push(int(Serializer.indexOf(data, ':', Serializer.c+2)));
//tmp.push(int(data.indexOf(":", Serializer.c+2)))
tmp.push(tmp[0]+2)
pos = Serializer.c+2
tmp.push(0)
tmp.push(int(Serializer.substring(data, pos, tmp[0])));
//tmp.push(int(data.substring(pos, tmp[0])));
if(tmp[3] == 0)
{
result = "";
Serializer.c = pos+5
} else {
var lenc:uint = Serializer.stringBCLenght(data, Serializer.c, tmp[3]);
if(lenc != tmp[3])
{
result = Serializer.substr(data, tmp[0]+2, lenc);
//result = data.substr(tmp[0]+2, lenc);
Serializer.c = tmp[0]+4+lenc;
} else {
result = Serializer.substr(data, tmp[0]+2, tmp[3]);
//result = data.substr(tmp[0]+2, tmp[3]);
Serializer.c = tmp[0]+4+tmp[3];
}
}
if(Serializer.pattern.test(result))
{
result = new Date(result)
}
break;
case "a":
//result:ByteArray;
pos = Serializer.c+2
tmp.push(int(Serializer.indexOf(data, ":", pos)))
tmp.push(int(Serializer.substring(data, pos, tmp[0])))
//tmp.push(int(data.indexOf(":", pos)))
//tmp.push(int(data.substring(pos, tmp[0])))
Serializer.c = tmp[0]+2
result = []
for(i = 0; i < tmp[1]; i++){
tmpvar = Serializer.unserialize_internal(data)
result[tmpvar] = Serializer.unserialize_internal(data)
if(!(tmpvar is int) || tmpvar < 0){
islist = false
}
}
if(islist){
tmp.push([])
for(var key:uint = 0; key < result.length; key++){
pos = tmp[2].length
while(key > pos){
tmp[2].push(null)
pos +=1
}
tmp[2].push(result[key])
}
result = tmp[2]
}
Serializer.c += 1
break;
case "O":
pos = Serializer.indexOf(data, "\"", Serializer.c)+1;
Serializer.c = Serializer.indexOf(data, "\"", pos);
tmp.push(Serializer.substring(data, pos, Serializer.c))
//pos = data.indexOf("\"", Serializer.c)+1;
//Serializer.c = data.indexOf("\"", pos);
//tmp.push(data.substring(pos, Serializer.c))
Serializer.c += 2
i = Serializer.c
Serializer.c = Serializer.indexOf(data, ":", i)
i = int(Serializer.substring(data, i, Serializer.c))
//Serializer.c = data.indexOf(":", i)
//i = int(data.substring(i, Serializer.c))
Serializer.c +=2;
result = {};
var tmps:*;
while(i > 0){
tmps = Serializer.unserialize_internal(data)
result[tmps] = Serializer.unserialize_internal(data)
i -= 1
}
break;
}
return result;
}
mx_internal static function stringCLenght(data:String, from:uint = 0, len:uint = 0):int
{
var i:uint;
var j:uint = len;
var startIndex:uint = from + 4 + len.toString().length;
for (i = 0; i < j; i++){
if (data.charCodeAt(i+startIndex) > 128)
{
j = j - 1
}
}
return j;
}
mx_internal static function stringBCLenght(data:ByteArray, from:uint = 0, len:uint = 0):int
{
var i:uint;
var j:uint = len;
var startIndex:uint = from + 4 + len.toString().length;
for (i = 0; i < j; i++){
if (Serializer.charCodeAt(data, i+startIndex) > 128)
{
j = j - 1
}
}
return j;
}
mx_internal static function stringLength(data:String):uint
{
var code:int = 0
var result:int = 0
var slen:int = data.length;
while(slen){
slen = slen - 1
try
{
code = data.charCodeAt(slen)
} catch(e:Error){
code = 65536
}
if(code < 128){
result = result + 1
} else if(code < 2048){
result = result + 2
} else if(code < 65536){
result = result + 3
} else {
result = result + 4
}
}
return result
}
public static function charAt(bytes:ByteArray, index:int):String {
if (bytes.length <= index) return null;
return String.fromCharCode(bytes[index]);
}
public static function charCodeAt(bytes:ByteArray, index:int):int {
if (bytes.length <= index) return -1;
return bytes[index];
}
public static function substr(bytes:ByteArray, start:int, length:int=0):ByteArray {
var res:ByteArray = new ByteArray();
bytes.position = start;
bytes.readBytes(res, 0, length);
return res;
}
public static function substring(bytes:ByteArray, start:int, end:int=0):ByteArray {
return substr(bytes, start, end-start);
}
public static function indexOf(bytes:ByteArray, str:String, startIndex:int):int {
var num:int = 0;
for (var i:int=0; i<bytes.length; i++) {
var strPos:int = 0;
while (bytes[i+strPos] == str.charCodeAt(strPos)) {
strPos++;
if (strPos == str.length) {
num++;
if(num == startIndex) {
return i;
}
}
}
}
return -1;
}
}
}
I resolved the issue, no need for answers.

Categories