Within two years, I became the largest contributor to JELD-WEN.com with 100,000 lines of code and 50,000 deletions. I developed and maintained numerous components integrating with internal web services, implemented security measures, and managed web development operations within the company.
if ($('#com_jw_egresscalc').length > 0 ) {
var egresscalc = new Com_jw_egresscalc();
egresscalc.init();
}
function Com_jw_egresscalc () {
var self = this;
self.allOptions;
self.inputForm = $('#com_jw_egresscalc form');
self.inputMaterial = $('#com_jw_egresscalc form select[name="material"]');
self.inputProduct = $('#com_jw_egresscalc form select[name="product"]');
self.inputStyle = $('#com_jw_egresscalc form select[name="style"]');
self.inputSizes = $('#com_jw_egresscalc form #egresscalc-size-input');
self.inputSizesType = $('#com_jw_egresscalc form input[name="input-size-type"]');
self.inputFrameWidth = $('#com_jw_egresscalc form input[name="frameWidth"]');
self.inputFrameWidthFraction = $('#com_jw_egresscalc form select[name="frameWidth_fraction"]');
self.inputFrameHeight = $('#com_jw_egresscalc form input[name="frameHeight"]');
self.inputFrameHeightFraction = $('#com_jw_egresscalc form select[name="frameHeight_fraction"]');
self.inputLegHeight = $('#com_jw_egresscalc form input[name="legHeight"]');
self.inputLegHeightFraction = $('#com_jw_egresscalc form select[name="legHeight_fraction"]');
self.selectedInputSizesType = 'fraction';
self.formulas = [];
self.results = [];
self.errors = {};
self.egressChecks = {
first: {
cow: '>= 20',
coh: '>= 24',
cos: '>= 5.0',
vas: '>= 0',
dos: '>= 0'
},
second: {
cow: '>= 20',
coh: '>= 24',
cos: '>= 5.7',
vas: '>= 0',
dos: '>= 0'
}
}
/*
self.egressChecks = {
cow: '>= 20',
coh: '>= 24',
cos: {
first: '>= 5.0',
second: '>= 5.7'
}
vas: '>= 0',
dos: '>= 0'
}
*/
self.init = function() {
self.inputMaterial.attr("disabled", true);
self.inputProduct.attr("disabled", true);
self.inputStyle.attr("disabled", true);
self.getOptions().done(function(data) {
self.allOptions = JSON.parse(data);
self.fillMaterials();
self.inputMaterial.bind('change', self.fillProducts);
self.inputProduct.bind('change', self.fillStyles);
self.inputStyle.bind('change', self.showHideSizing);
self.inputSizesType.bind('change', self.switchSizesType);
self.inputForm.bind('submit', function(e){
e.preventDefault();
self.processForm();
});
self.inputSizes.find('input').bind('keyup', function(){
$('#egresscalc-results').hide();
});
self.inputSizes.find('select').bind('change', function(){
$('#egresscalc-results').hide();
});
});
}
self.serviceDown = function(error) {
$('#egresscalc-service-down').show();
if (typeof error != 'undefined') {
console.log(error);
}
}
self.getOptions = function() {
return $.ajax({
url: 'index.php/?option=com_jw_egresscalc&task=egresscalc.getOptions&format=raw',
error: function(xhr, status, error){
self.serviceDown(xhr.status + ": " + error);
}
});
}
self.fillMaterials = function() {
$.each(self.allOptions, function(index, material) {
self.inputMaterial.append($('<option>', {value: index}).text(material.title));
});
self.inputMaterial.attr("disabled", false);
self.inputProduct.attr("disabled", false);
self.inputStyle.attr("disabled", false);
}
self.fillProducts = function() {
var materialId = self.inputMaterial.val();
self.clearInput('product');
self.clearInput('style');
self.showHideSizing();
if (!materialId) {
return;
}
$.each(self.allOptions[materialId].products, function(index, product) {
self.inputProduct.append($('<option>', {value: index}).text(product.title));
});
}
self.fillStyles = function() {
var materialId = self.inputMaterial.val();
var productId = self.inputProduct.val();
self.clearInput('style');
self.showHideSizing();
if (!productId) {
return;
}
$.each(self.allOptions[materialId].products[productId].styles, function(index, style) {
self.inputStyle.append($('<option>', {value: style.id}).text(style.title));
});
}
self.clearInput = function(inputField) {
inputField = inputField.charAt(0).toUpperCase() + inputField.slice(1);
eval('self.input' + inputField).find('option:not(.placeholder)').remove();
}
self.showHideSizing = function() {
var styleId = self.inputStyle.val();
var frameWidth = self.inputFrameWidth.val();
var frameHeight = self.inputFrameHeight.val();
if (!styleId) {
self.inputSizes.find('input[type="text"], select').val('');
self.inputSizes.hide();
$('#egresscalc-results').hide();
} else {
self.getFormula(styleId, frameWidth, frameHeight).done(function(data) {
self.formulas = JSON.parse(data);
$('#egresscalc-size-input>h3').html(self.inputStyle.find('option:selected').text());
self.inputSizes.show();
if(self.formulas.has_leg == 1) {
$('#egresscalc-input-legheight').show();
} else {
$('#egresscalc-input-legheight').hide();
}
self.errors = {};
self.inputForm.find('input.error').removeClass('error').prev('.error').text('');
});
}
}
self.switchSizesType = function() {
self.selectedInputSizesType = $('input[name="input-size-type"]:checked').val();
self.inputForm.find('input.error').removeClass('error').prev('.error').text('');
$('#egresscalc-results').hide();
if(self.selectedInputSizesType === 'decimal') {
self.inputSizes.find('select.fraction-dropdown').hide();
self.inputSizes.find('select.fraction-dropdown').val('');
} else {
self.inputSizes.find('select.fraction-dropdown').show();
}
}
self.processForm = function() {
var styleId = self.inputStyle.val();
var frameWidth = self.inputFrameWidth.val();
var frameWidthFraction = self.inputFrameWidthFraction.val();
var frameHeight = self.inputFrameHeight.val();
var frameHeightFraction = self.inputFrameHeightFraction.val();
var legHeight = self.inputLegHeight.val();
var legHeightFraction = self.inputLegHeightFraction.val();
var formulas = self.formulas;
self.errors = {};
self.validateField(self.inputFrameWidth);
self.validateField(self.inputFrameHeight);
if(self.formulas.has_leg == true){
self.validateField(self.inputLegHeight);
}
if($.isEmptyObject(self.errors)) {
if(self.selectedInputSizesType === 'fraction') {
if(frameWidthFraction != ''){
frameWidth = self.addFraction(frameWidth, frameWidthFraction);
}
if(frameHeightFraction != ''){
frameHeight = self.addFraction(frameHeight, frameHeightFraction);
}
if(legHeightFraction != ''){
legHeight = self.addFraction(legHeight, legHeightFraction);
}
}
self.postForm(styleId, frameWidth, frameHeight, legHeight, formulas).done(function(data) {
self.results = JSON.parse(data);
self.fillResults();
self.checkResults();
});
} else {
$('#egresscalc-results').hide();
}
}
self.validateField = function(field) {
field.removeClass('error');
field.prev('.error').text('');
var messages = {
blank: 'This field can not be left blank.',
numeric: 'This field must be a numeric value.',
decimal: 'Please switch input type to decimals.',
comma: 'This field may not contain commas.',
fraction: 'Please switch input type to fractions.'
}
// Number
if(isNaN(field.val())) {
self.errors[field.attr('name')] = messages.numeric;
field.prev('.error').text(messages.numeric);
field.addClass('error');
}
// Fraction
if(self.selectedInputSizesType === 'decimal') {
if(field.val().indexOf('/') != -1)
{
self.errors[field.attr('name')] = messages.fraction;
field.prev('.error').text(messages.fraction);
field.addClass('error');
}
}
// Decimal
if(self.selectedInputSizesType === 'fraction') {
if(field.val().indexOf('.') != -1)
{
self.errors[field.attr('name')] = messages.decimal;
field.prev('.error').text(messages.decimal);
field.addClass('error');
}
}
// Comma
if(self.selectedInputSizesType === 'fraction') {
if(field.val().indexOf(',') != -1)
{
self.errors[field.attr('name')] = messages.comma;
field.prev('.error').text(messages.comma);
field.addClass('error');
}
}
// Blank
if(field.val() === '') {
self.errors[field.attr('name')] = messages.blank;
field.prev('.error').text(messages.blank);
field.addClass('error');
}
}
self.postForm = function(styleId, frameWidth, frameHeight, legHeight, formulas) {
return $.ajax({
url: 'index.php/?option=com_jw_egresscalc&task=egresscalc.postForm&format=raw',
data: { styleId: styleId, frameWidth: frameWidth, frameHeight: frameHeight, legHeight: legHeight, formulas: formulas },
error: function(xhr, status, error){
self.serviceDown(xhr.status + ": " + error);
}
});
}
self.getFormula = function(styleId, framewidth, frameheight) {
return $.ajax({
url: 'index.php/?option=com_jw_egresscalc&task=egresscalc.getFormula&format=raw',
data: { styleId: styleId },
error: function(xhr, status, error){
self.serviceDown(xhr.status + ": " + error);
}
});
}
self.fillResults = function() {
$('#egresscalc-results').show();
$('#egresscalc-results tbody tr').hide();
$.each(self.results, function(index, value) {
$('#com_jw_egresscalc #egresscalc-results tr[data-result="' + index + '"]').show();
$('#com_jw_egresscalc #egresscalc-results tr[data-result="' + index + '"] td.result').html(value);
});
}
self.checkResults = function() {
var hasError = false;
var errors = {
second: {},
first: {}
};
var errorMessages = {
second: "Meets IRC egress requirements for 1st floor only.",
first: "Does NOT meet IRC Egress Requirements."
};
$('#egresscalc-results td').removeClass('error');
$.each(self.results, function(key) {
$.each(self.egressChecks, function(floor) {
if(!self.resultPasses(key, floor)) {
hasError = true;
errors[floor][key] = true;
$('#com_jw_egresscalc #egresscalc-results tr[data-result="' + key + '"] td.' + floor).addClass('error');
}
});
});
if(hasError === true) {
$.each(errors, function(floor, value) {
if(!$.isEmptyObject(value)){
$('#com_jw_egresscalc .result-message').html('<span class="warning">' + errorMessages[floor] + '</span>');
}
});
} else {
$('#com_jw_egresscalc .result-message').html('<span class="success">Meets IRC Egress Requirements.</span>');
}
}
self.resultPasses = function(key, floor) {
return eval(self.results[key] + self.egressChecks[floor][key]);
}
self.addFraction = function(number, fraction) {
var splitFraction = fraction.split('/');
fraction = splitFraction[0] / splitFraction[1];
return parseFloat(number) + fraction;
}
}
<?php
/**
* @version 1.0.0
* @package com_jw_egresscalc
* @copyright JELD-WEN © Copyright 2012. All Rights Reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
* @author Alex Crawford <alexc@jeld-wen.com> - JELD-WEN http://jeld-wen.com
*/
header('Content-Type: application/json');
defined('_JEXEC') or die;
require_once JPATH_COMPONENT.'/controller.php';
class Jw_egresscalcControllerEgresscalc extends Jw_egresscalcController
{
public function getOptions(){
$allOptions = array();
$materialModel = $this->getModel('material');
$productModel = $this->getModel('product');
$styleModel = $this->getModel('style');
$materials = $materialModel->getMaterials();
foreach($materials as $material) {
$materialProducts = array();
$products = $productModel->getProductsByMaterialId($material->id);
foreach($products as $product) {
$styles = $styleModel->getStylesByProductId($product->id);
$productStyles = array();
foreach($styles as $style) {
$productStyles[] = array(
'id' => $style->id,
'title' => $style->title
);
}
$materialProducts[] = array(
'id' => $product->id,
'title' => $product->title,
'styles' => $productStyles
);
}
$allOptions[] = array(
'id' => $material->id,
'title' => $material->title,
'products' => $materialProducts
);
}
echo json_encode($allOptions);
}
public function postForm(){
$styleId = (empty($_GET['styleId']) ? null : $_GET['styleId']);
$formulas = (empty($_GET['formulas']) ? null : $_GET['formulas']);
$frameWidth = (empty($_GET['frameWidth']) ? null : $_GET['frameWidth']);
$frameHeight = (empty($_GET['frameHeight']) ? null : $_GET['frameHeight']);
$legHeight = (empty($_GET['legHeight']) ? null : $_GET['legHeight']);
$calcFormulas = array();
$formulaAbbreviations = array('cow', 'coh', 'cos', 'vas', 'dos');
foreach($formulaAbbreviations as $abbrv) {
$jsonFormulas = json_decode($formulas[$abbrv]);
if (!empty($jsonFormulas)) {
$calcFormulas[$abbrv] = $jsonFormulas;
}
}
$results = array();
$variables = array('FrameWidth', 'FrameHeight');
$values = array($frameWidth, $frameHeight);
if($legHeight != null){
array_push($variables, 'LegHeight');
array_push($values, $legHeight);
}
foreach($calcFormulas as $abbrv => $formulaConditions){
foreach($formulaConditions as $formulaCondition){
$condition = str_replace($variables, $values, $formulaCondition->condition);
$condition = (empty($condition) ? true : $condition);
if($this->calc_string($condition)) {
$formula = str_replace($variables, $values, $formulaCondition->formula);
$result = $this->calc_string($formula);
$results[$abbrv] = $result;
array_push($variables, strtoupper($abbrv));
array_push($values, $result);
break;
}
}
}
echo json_encode($results);
}
public function getFormula(){
$styleId = (empty($_GET['styleId']) ? null : $_GET['styleId']);
$formulaModel = $this->getModel('formula');
$formulas = $formulaModel->getFormulaByStyleId($styleId);
echo json_encode($formulas);
}
function calc_string($mathString)
{
$cf_DoCalc = create_function("", "return (".$mathString.");");
$rounded = round($cf_DoCalc(), 3);
return $rounded;
}
}
var findstore;
var findstore.results;
var findstore.map;
var findstore.bounds;
var findstore.infoWindow;
var findstore.markers = [];
var findstore.mappings = [];
var findstore.dirMap;
var findstore.dirBounds;
var findstore.dirDisplay;
var findstore.dirService;
var findstore.dirMarkers = [];
var findstore.uriVars = {};
$(document).ready(function() {
// limit loading findstore map
if ($('#findstore-map').length != 0) {
findstore.bounds = new google.maps.LatLngBounds();
findstore.infoWindow = new google.maps.InfoWindow();
findstore.map = new google.maps.Map(document.getElementById("findstore-map"), {
center: new google.maps.LatLng(0, 0),
zoom: 2,
mapTypeId: 'roadmap',
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU}
});
// get URI parameters
var uriSegments = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
findstore.uriVars[key] = value;
});
if (typeof(findstore.uriVars["uri"]) !== 'undefined'){
initCheckbox(findstore.uriVars["uri"]);
}
}
// limit loading directions map
if ($('#directions-map').length != 0) {
findstore.dirBounds = new google.maps.LatLngBounds();
findstore.dirService = new google.maps.DirectionsService();
findstore.dirDisplay = new google.maps.DirectionsRenderer();
findstore.dirMap = new google.maps.Map(document.getElementById("directions-map"), {
center: new google.maps.LatLng(0, 0),
zoom: 2,
mapTypeId: 'roadmap',
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU}
});
findstore.dirDisplay.setMap(findstore.dirMap);
initDirections(dirAddress, dirPosition);
}
// IE indexOf workaround
// https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/indexOf
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
"use strict";
if (this == null) {
throw new TypeError();
}
var t = Object(this);
var len = t.length >>> 0;
if (len === 0) {
return -1;
}
var n = 0;
if (arguments.length > 1) {
n = Number(arguments[1]);
if (n != n) { // shortcut for verifying if it's NaN
n = 0;
} else if (n != 0 && n != Infinity && n != -Infinity) {
n = (n > 0 || -1) * Math.floor(Math.abs(n));
}
}
if (n >= len) {
return -1;
}
var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
for (; k < len; k++) {
if (k in t && t[k] === searchElement) {
return k;
}
}
return -1;
}
}
});
/* Click Events */
// Submit form
$('#findstore-submit').click(function() {
$('#findstore-search').submit();
});
$('#findstore-search').submit(function(e) {
e.preventDefault();
$('#findstore-right-middle .message').remove();
var form = this;
validate(form).done(function(data) {
findstore.results = data;
initMappings();
}).fail(function() {
clearMap();
clearResults();
});
});
// Loading icon for any AJAX
$(".findstore-loading").bind("ajaxStart", function(){
$(this).show();
}).bind("ajaxComplete", function(){
$(this).hide();
});
// Show more results click event
$('#findstore-results .more-results').live("click", function(e) {
var order = $(this).closest('tr').attr('data-order');
var group = $(this).closest('tr').attr('data-group');
findstore.mappings[order].open = true;
showMore(order, group);
});
// Hide more results click event
$('#findstore-results .hide-results').live("click", function(e) {
var order = $(this).closest('tr').attr('data-order');
var group = $(this).closest('tr').attr('data-group');
findstore.mappings[order].open = false;
hideMore($(this).closest('tr').attr('data-order'), $(this).closest('tr').attr('data-group'));
});
$('#findstore-type-filters :input').live("click", function(e) {
initMappings();
});
$('form[name="getDirections"] #btnGetDirections').live("click", function(e) {
e.preventDefault();
var start = $('form[name="getDirections"] input[name="fromAddress"]').val();
var end = $('form[name="getDirections"] input[name="toAddress"]').val();
calcRoute(start, end);
});
/* Functions */
// retreive the data
function validate(form){
var valid = true;
findstore.results = null;
var response = $.Deferred();
if (valid === true) {
var selZip = $('#findstore-zip').val();
var selRadius = $('#findstore-radius').val();
var selFilters = new Array();
$('input[name=findstore-filters]:checked').each(function(key,val){
selFilters.push($(val).val());
});
var selModel = findstore.uriVars['model'];
$.ajax({
url: 'findastore?task=findstore.search&format=raw',
data: { selZip: selZip, selFilters: selFilters, selRadius: selRadius, selModel: selModel }
}).done(function(data) {
if ( data.length > 0 ) {
response.resolve(data);
} else {
response.reject();
}
}).fail(function() {
response.reject();
});
} else {
response.reject();
}
return response.promise();
}
// preselect checkboxes
function initCheckbox(uri) {
var segments = uri.split("/");
$.each(window.filters, function(f, filter){
$.each(filter.mappings, function(m, mapping){
if ($.isEmptyObject(mapping.uris)) {
var matchAll = false;
} else {
var matchAll = true;
var uris = $.parseJSON(mapping.uris);
$.each(uris, function(u, uriString){
var uriArray = uriString.split(',');
$.each(uriArray, function(u, uri){
uriTrimmed = uri.replace(/\s/g, '');
if (segments.indexOf(uriTrimmed) != -1) {
} else {
matchAll = false;
}
});
});
}
if(matchAll){
$('#findstore-filter-' + mapping.id).attr('checked', 'checked');
}
});
});
}
// prepare the directions iframe view
function initDirections(address, position){
$('#findstore-direction-steps').empty();
$('form[name="getDirections"] input[name="toAddress"]').val(address);
for (i = 0; i < findstore.dirMarkers.length; i++) {
findstore.dirMarkers[i].setMap(null);
}
findstore.dirMarkers.length = 0;
findstore.dirDisplay.setMap(null);
findstore.dirBounds = new google.maps.LatLngBounds();
position = position.replace(/[()]/g,'');
position = position.split(',');
var marker = new google.maps.Marker({
position: new google.maps.LatLng(position[0], position[1]),
map: findstore.dirMap,
icon: 'http://maps.google.com/mapfiles/ms/micons/green-dot.png'
});
findstore.dirMarkers.push(marker);
findstore.dirBounds.extend(marker.position);
findstore.dirMap.fitBounds(findstore.dirBounds);
findstore.dirMap.setZoom(14);
}
function calcRoute(start, end) {
var request = {
origin:start,
destination:end,
travelMode: google.maps.TravelMode.DRIVING
};
findstore.dirService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
findstore.dirDisplay.setDirections(response);
findstore.dirDisplay.setMap(findstore.dirMap);
showSteps(response);
}
});
}
function showSteps(directionResult) {
$('#findstore-direction-steps').empty();
for (i = 0; i < findstore.dirMarkers.length; i++) {
findstore.dirMarkers[i].setMap(null);
}
findstore.dirMarkers.length = 0;
var route = directionResult.routes[0].legs[0];
$('#findstore-direction-steps').append(
'<h5>' + route.start_address + '</h5>'
);
for (var i = 0; i < route.steps.length; i++) {
$('#findstore-direction-steps').append(
'<li class="step"><span>' + (i + 1) + '.</span><div class="detail">' + route.steps[i].instructions + '</div></li>'
);
}
$('#findstore-direction-steps').append(
'<h5>' + route.end_address + '</h5>'
);
}
function initMappings(){
findstore.mappings.length = 0;
$.each(findstore.results, function(i, result) {
var latlng = new google.maps.LatLng(
result[0].lat,
result[0].lon
);
var marker = new google.maps.Marker({
position: latlng
})
var mapping = {
details: result[0],
marker: marker,
group: i,
open: false
}
if($(result).length > 1) {
mapping.children = true;
}
findstore.mappings.push(mapping);
});
filterTypes();
updateResults();
}
function showMore(order, group){
$.each(findstore.results[group], function(s, store) {
if (s > 0) {
var latlng = new google.maps.LatLng(
store.lat,
store.lon
);
var marker = new google.maps.Marker({
position: latlng
});
var mapping = {
details: store,
marker: marker,
group: group,
child: true
}
findstore.mappings.splice(Number(order) + Number(s), 0, mapping);
}
});
updateResults();
var storeCount = findstore.results[group].length - 1;
$('#findstore-results-body tr[data-order="' + order + '"] .more-results').replaceWith(
'<div class="hide-results">- Hide more stores (' + storeCount + ')</div>'
);
}
function hideMore(order, group){
index = (Number(order) + 1);
amount = $('#findstore-results-body tr[data-group="' + group + '"]').length - 1;
findstore.mappings.splice(index, amount);
updateResults();
var storeCount = findstore.results[group].length - 1;
$('#findstore-results-body tr[data-order="' + order + '"] .hide-results').replaceWith(
'<div class="more-results">+ Show more stores (' + storeCount + ')</div>'
);
}
function filterTypes(){
var filterTypes = [];
if ($("input[name='type-filter[]']:checked").length < 1) {
filterTypes = ['Home Center', 'Window and Door Store', 'Lumber Yard']
} else {
$.each($("input[name='type-filter[]']:checked"), function() {;
filterTypes.push($(this).val());
});
}
var spliceMappings = [];
$.each(findstore.mappings, function(i, mapping) {
store = mapping.details;
match = filterTypes.indexOf(store.type);
if (match === -1) {
spliceMappings.push(i);
}
});
$.each(spliceMappings.reverse(), function(i, index) {
findstore.mappings.splice(index, 1);
});
}
function updateResults(){
$('#findstore-right-bottom').show();
$('#findstore-right-middle .message').remove();
$('#findstore-results-body tr').not('.first').remove();
$.each(findstore.mappings, function(i, mapping) {
var store = mapping.details;
if (i%2 == 0) { var oddeven = 'even' } else { var oddeven = 'odd' }
var clone = $('#findstore-results-body tr.first').clone();
clone.show();
clone.removeClass('first').addClass(oddeven).attr('data-order', i).attr('data-group', mapping.group);
clone.find('.marker img').attr('src', 'http://chart.apis.google.com/chart?chst=d_map_spin&chld=.75|0|CAD7FC|16|b|' + (i + 1));
clone.find('.details h5').html(store.name);
clone.find('.details h6').html(store.type);
clone.find('.details p').html(store.address + '<br>' + store.city + ', ' + store.state + ' ' + store.zip + '<br>' + store.phone);
clone.find('.details span').html(store.distance + ' mi');
clone.find('.directions a').attr('href', 'index.php?option=com_jw_findstore&layout=directions&address=' + store.address + ' ' + store.city + ', ' + store.state + ' ' + store.zip + '&position=' + mapping.marker.position + '&tmpl=hopup');
clone.appendTo($('#findstore-results-body'));
$.each(store.products, function(p, product) {
clone.find('td[data-category='+product.category+']').append('<li data-match="'+product.match+'">' + product.name + '</li>');
});
if (mapping.children) {
var storeCount = findstore.results[mapping.group].length -1;
if (mapping.open){
clone.find('td.store-info').append('<div class="hide-results">- Hide more stores (' + storeCount + ')</div>');
} else {
clone.find('td.store-info').append('<div class="more-results">+ Show more results (' + storeCount + ')</div>');
}
}
if (mapping.child) {
clone.addClass('child');
}
});
if (findstore.mappings.length > 0){
updateMap();
} else {
clearMap();
clearResults();
}
$(".iframe").colorbox({iframe:true, width:"840px", height:"600px", scrolling: false});
}
function updateMap(){
clearMap();
findstore.bounds = new google.maps.LatLngBounds();
$.each(findstore.mappings, function(i, mapping) {
var store = mapping.details;
var overlay =
'<div class="details">' +
'<h4>' + store.name + '</h4>' +
'<h6>' + store.type + '</h6>' +
'<p>' + store.address + '</p>' +
'<p>' + store.city + ', ' + store.state + ' ' + store.zip + '</p>' +
'<p>' + store.phone + '</p>' +
'<span>' + store.distance + ' mi</span>' +
'</div>';
mapping.marker.setIcon('http://chart.apis.google.com/chart?chst=d_map_spin&chld=.75|0|CAD7FC|16|b|' + ( i + 1 ));
mapping.marker.setMap(map);
google.maps.event.addListener(mapping.marker, 'click', function() {
findstore.infoWindow.close();
infoWindow.setContent(overlay);
map.setZoom(10);
map.panTo(mapping.marker.getPosition());
findstore.infoWindow.open(map, mapping.marker);
});
findstore.bounds.extend(mapping.marker.position);
findstore.markers.push(mapping.marker);
});
map.fitBounds(findstore.bounds);
}
function clearResults(){
$('#findstore-results-body tr').not('.first').remove();
$('#findstore-right-bottom').hide();
$('#findstore-right-middle .message').remove();
$('#findstore-right-middle').append('<span class="message">There are no locations that match your criteria. Please try a different search.</span>');
}
function clearMap(){
for (var i = 0; i < findstore.markers.length; i++) {
findstore.markers[i].setMap(null);
}
findstore.markers.length = 0;
}
<?php
/**
* @version 1.0.0
* @package com_jw_findstore
* @copyright JELD-WEN © Copyright 2012. All Rights Reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
* @author Alex Crawford <alexc@jeld-wen.com> - JELD-WEN http://jeld-wen.com
*/
header('Content-Type: application/json');
defined('_JEXEC') or die;
require_once JPATH_COMPONENT.'/controller.php';
class Jw_findstoreControllerFindstore extends Jw_findstoreController
{
public function search() {
$mappings = $this->getModel()->getMappings();
$collections = $this->getModel()->getCollections();
$selZip = (empty($_GET['selZip']) ? null : $_GET['selZip']);
$selFilters = (empty($_GET['selFilters']) ? array() : $_GET['selFilters']);
$selRadius = (empty($_GET['selRadius']) ? 40 : $_GET['selRadius']);
$selModel = (empty($_GET['selModel']) ? null : $_GET['selModel']);
$url = 'GetDealersTest?zip='. $selZip .'&distance='. $selRadius .'&collectionId='. implode(',', $selFilters);
$debug = false;
if ($debug == true) {
$url = 'tests/findstore.xml';
$xml = simplexml_load_file($url);
} else {
$ch = curl_init($url);
$options = array(
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSLCERT => JPATH_BASE.'...',
CURLOPT_SSLCERTPASSWD => '...',
CURLOPT_SSLKEY => JPATH_BASE.'...',
);
curl_setopt_array($ch, $options);
$response = curl_exec($ch);
$xml = new SimpleXMLElement($response);
}
$storeId = 0;
$dealerGroups = array();
foreach ($xml->DealerGroup as $dealerGroup) {
// HOTFIX: Remove Madison from Home Depot / Lowe's
if($selModel == 'madison') {
$accum = (isset($dealerGroup->attributes()->accum) ? $dealerGroup->attributes()->accum : null);
if ($accum == '509' || $accum == '612'){
continue;
}
}
$dealers = array();
foreach ($dealerGroup->Dealer as $dealer) {
// HOTFIX: Remove Madison from Home Depot / Lowe's
if($selModel == 'madison') {
$name = (isset($dealer->attributes()->name) ? $dealer->attributes()->name : null);
if (strpos($name, "LOWE'S") !== false || strpos($name, "HOME DEPOT") !== false){
continue;
}
}
$products = array();
$matchAny = false;
$categories = array();
foreach ($dealer->Product as $product) {
$productMatch = false;
foreach($collections as $key => $val) {
if ( $val->col_id == $product->attributes()->number ) {
// prepare the first two segments for comparison
$productSegments = explode(".", $product->attributes()->number);
if ( count($productSegments) > 1 ) {
$productCategory = $productSegments[0].".".$productSegments[1];
}
// prepare the product for highlighting
if (in_array($productCategory, $selFilters)) {
$productMatch = true;
}
// re-set the productCategory to integer so we can easily put it in the right column
foreach ( $mappings as $mapping ) {
// if no mapping has been set up in the back-end, the product will not be added
if ($productCategory == $mapping->collections ) {
$productName = $val->title;
$productNumber = $val->col_id;
$productCategory = $mapping->category;
$products[] = array(
'name' => $productName,
'number' => $productNumber,
'category' => $productCategory,
'match' => $productMatch,
);
$categories[] = $mapping->collections;
}
}
}
}
}
// Make sure the dealer has a match
foreach ($selFilters as $selFilter) {
if (in_array($selFilter, $categories)) {
$matchAny = true;
}
}
// only return dealers with at least one match, unless search is empty
if ($matchAny == true || empty($_GET['selFilters'])) {
// if a dealer has no products, do not return the dealer
if ( count($products) > 0 ) {
$dealers[] = array(
'id' => $storeId,
'name' => (string)$dealer->attributes()->name,
'type' => (string)$dealer->attributes()->storeType,
'address' => (string)$dealer->attributes()->addrline1,
'city' => (string)$dealer->attributes()->city,
'state' => (string)$dealer->attributes()->state,
'zip' => (string)$dealer->attributes()->zip,
'phone' => (string)$dealer->attributes()->phone,
'distance' => (string)$dealer->attributes()->distance,
'lat' => (string)$dealer->attributes()->lat,
'lon' => (string)$dealer->attributes()->lon,
'products' => $products,
);
$storeId = $storeId + 1;
}
}
}
if (!empty($dealers)) {
$dealerGroups[] = $dealers;
}
if (count($dealerGroups) === 15) {
break;
}
}
$dealerGroups = json_encode($dealerGroups);
die($dealerGroups);
}
public function debug() {
$timeBench03start = microtime(true);
//$_GET['selZip'] = '97601';
//$_GET['selFilters'] = array('1.1', '1.3');
//$_GET['selRadius'] = '40';
if (empty($_GET['selFilters'])) {
$_GET['selFilters'] = array();
}
if (empty($_GET['selZip'])) {
$_GET['selZip'] = null;
}
if (empty($_GET['selRadius'])) {
$_GET['selRadius'] = '40';
}
$selZip = $_GET['selZip'];
$selFilters = $_GET['selFilters'];
$selRadius = $_GET['selRadius'];
$url = '.../GetDealersTest?zip='. $selZip .'&distance='. $selRadius .'&collectionId='. $selFilters;
//$url = 'webappstest1.local/atlas/GetDealers/report.xml?zip='. $selZip .'&distance=40&collectionId='. $selFilters;
$timeBench01start = microtime(true);
$ch = curl_init($url);
$options = array(
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSLCERT => JPATH_BASE.'...',
CURLOPT_SSLCERTPASSWD => '...',
CURLOPT_SSLKEY => JPATH_BASE.'...',
);
curl_setopt_array($ch, $options);
$response = curl_exec($ch);
$xml = new SimpleXMLElement($response);
$timeBench01end = microtime(true);
$timeBench01 = ($timeBench01end - $timeBench01start);
$timeBench02start = microtime(true);
$mappings = $this->getModel()->getMappings();
$collections = $this->getModel()->getCollections();
$storeId = 0;
$dealerGroups = array();
foreach ($xml->DealerGroup as $dealerGroup) {
$dealers = array();
// any product with a mapping and collection in our component's back end will be returned in the result
foreach ($dealerGroup->Dealer as $dealer) {
$products = array();
$matchAny = false;
$categories = array();
foreach ($dealer->Product as $product) {
$productMatch = false;
foreach($collections as $key => $val) {
if ( $val->col_id == $product->attributes()->number ) {
// prepare the first two segments for comparison
$productSegments = explode(".", $product->attributes()->number);
if ( count($productSegments) > 1 ) {
$productCategory = $productSegments[0].".".$productSegments[1];
}
// prepare the product for highlighting
if (in_array($productCategory, $selFilters)) {
$productMatch = true;
}
// re-set the productCategory to integer so we can easily put it in the right column
foreach ( $mappings as $mapping ) {
// if no mapping has been set up in the back-end, the product will not be added
if ($productCategory == $mapping->collections ) {
$productName = $val->title;
$productNumber = $val->col_id;
$productCategory = $mapping->category;
$products[] = array(
'name' => $productName,
'number' => $productNumber,
'category' => $productCategory,
'match' => $productMatch,
);
$categories[] = $mapping->collections;
}
}
}
}
}
// Make sure the dealer has a match
foreach ($selFilters as $selFilter) {
if (in_array($selFilter, $categories)) {
$matchAny = true;
}
}
// only return dealers with at least one match, unless search is empty
if ($matchAny == true || empty($_GET['selFilters'])) {
// if a dealer has no products, do not return the dealer
if ( count($products) > 0 ) {
$dealers[] = array(
'id' => $storeId,
'name' => (string)$dealer->attributes()->name,
'type' => (string)$dealer->attributes()->storeType,
'address' => (string)$dealer->attributes()->addrline1,
'city' => (string)$dealer->attributes()->city,
'state' => (string)$dealer->attributes()->state,
'zip' => (string)$dealer->attributes()->zip,
'phone' => (string)$dealer->attributes()->phone,
'distance' => (string)$dealer->attributes()->distance,
'lat' => (string)$dealer->attributes()->lat,
'lon' => (string)$dealer->attributes()->lon,
'products' => $products,
);
$storeId = $storeId + 1;
}
}
}
if (!empty($dealers)) {
$dealerGroups[] = $dealers;
}
}
$dealerGroups = json_encode($dealerGroups);
$timeBench02end = microtime(true);
$timeBench02 = ($timeBench02end - $timeBench02start);
$timeBench03end = microtime(true);
$timeBench03 = ($timeBench03end - $timeBench03start);
if (empty($_GET['bench'])) {
var_dump($url);
var_dump($xml);
} else if ($_GET['bench'] == '1'){
var_dump('TIME: ' . $timeBench01 . ' seconds to return XML from service');
var_dump($url);
var_dump($xml);
} else if ($_GET['bench'] == '2'){
var_dump('TIME: ' . $timeBench02 . ' seconds to parse XML into JSON array');
var_dump($dealerGroups);
} else if ($_GET['bench'] == 'all'){
var_dump('TIME: ' . $timeBench03 . ' seconds for script to execute');
var_dump($dealerGroups);
}
die;
}
}
<?php
defined('_JEXEC') or die('Restricted access');
jimport('joomla.application.component.modelitem');
class Jw_findstoreModelJw_findstore extends JModelItem
{
protected $filters;
protected $collections;
public function getFilters()
{
$db = JFactory::getDBO();
$query = $db->getQuery(true);
$query->select('id,title,image,ordering');
$query->from('#__jw_findstore_categories');
$query->where('state = 1');
$query->order('ordering ASC');
$db->setQuery((string)$query);
$categories = $db->loadObjectList();
foreach ($categories as $category){
$db = JFactory::getDBO();
$query = $db->getQuery(true);
$query->select('id,title,collections,category,uris,ordering');
$query->from('#__jw_findstore_mappings');
$query->where('state = 1');
$query->where('category = '.$category->id);
$query->order('ordering ASC');
$db->setQuery((string)$query);
$mappings = $db->loadObjectList();
$filters[] = array($category->id => $category->title, "image" => $category->image, "mappings" => $mappings);
}
return $filters;
}
public function getCollections()
{
$db = JFactory::getDBO();
$query = $db->getQuery(true);
$query->select('id,title,col_id,ordering');
$query->from('#__jw_findstore_collections');
$query->where('state = 1');
$query->order('ordering ASC');
$db->setQuery((string)$query);
$collections = $db->loadObjectList();
//$collections = json_encode($collections);
return $collections;
}
public function getMappings()
{
$db = JFactory::getDBO();
$query = $db->getQuery(true);
$query->select('id,collections,category, uris');
$query->from('#__jw_findstore_mappings');
$query->where('state = 1');
$db->setQuery((string)$query);
$mappings = $db->loadObjectList();
return $mappings;
}
public function getUris()
{
$db = JFactory::getDBO();
$query = $db->getQuery(true);
$query->select('id,collections,category,uris');
$query->from('#__jw_findstore_mappings');
$query->where('state = 1');
$db->setQuery((string)$query);
$mappings = $db->loadObjectList();
foreach ($mappings as $mapping){
$db = JFactory::getDBO();
$query = $db->getQuery(true);
$query->select('id,title,collections,category,ordering');
$query->from('#__jw_findstore_mappings');
$query->where('state = 1');
$query->where('category = '.$category->id);
$query->order('ordering ASC');
$db->setQuery((string)$query);
$mappings = $db->loadObjectList();
$filters[] = array($category->id => $category->title, "image" => $category->image, "mappings" => $mappings);
}
return $filters;
}
}
if ($('#com_jw_lookup').length > 0 ){
var com_jw_lookup = new Com_jw_lookup();
com_jw_lookup.init();
}
function Com_jw_lookup(){
var self = this;
self.order = {};
self.ordertype;
self.inputmask = {};
self.inputmask['store'] = '1234-123456';
self.inputmask['online'] = 'W123456789';
self.inputlength = {};
self.inputlength['store'] = 11;
self.inputlength['online'] = 10;
self.phones = {};
self.phones['store'] = '1-800-HOME-DEPOT (1-800-466-3337)';
self.phones['online'] = '1-800-430-3376';
self.init = function(){
// Next
$('input.next').click(function(){
var valid = self.validateStep(1);
if(!valid) return false;
self.ordertype = $('input[name="ordertype"]:checked').val();
$('.typeinfo').hide();
$('.typeinfo[data-type=' + self.ordertype + ']').show();
if(self.ordertype === 'online'){
$('#lookup-contact h6 b').html(self.phones[self.ordertype]);
}
var ordernumInput = $('input[name="ordernum"]');
$(ordernumInput).attr("placeholder", self.inputmask[self.ordertype]);
$(ordernumInput).attr("maxlength", self.inputlength[self.ordertype]);
$('.lookup-step[data-step=1]').hide();
$('.lookup-step[data-step=2]').show();
$('#errormsg').html('').hide();
});
// Prev
$('input.prev').click(function(){
$('input[name="ordernum"]').val('');
$('input[name="lastname"]').val('');
$('.lookup-step[data-step=2]').hide();
$('.lookup-step[data-step=1]').show();
$('#errormsg').html('').hide();
$('#lookup-contact h6 b').html('1-800-HOME-DEPOT <br> (1-800-466-3337)');
});
// Submit
$('#lookup-form').submit(function(e){
e.preventDefault();
var valid = self.validateStep(2);
if(!valid) return false;
var form = this;
var url = form.action;
var input = $('#lookup-form').serialize();
$.post(url, input)
.done(function(response){
if(response.result == 'success'){
self.showResult(response);
} else if(response.result == 'fail'){
self.showFail();
} else {
self.showNoResult();
}
}).fail(function(xhr) {
self.showFail();
console.log(xhr);
}
);
});
// New Lookup
$('input.newlookup').click(function(){
$('#lookup-result li').removeClass();
$('#lookup-result li .check').hide();
$('#lookup-result .ordernum').html('');
$('#lookup-result #recdate').html('');
$('#lookup-result #estdate').html('Not Yet Available');
$('input[name="ordertype"]').prop('checked', false);
$('input[name="ordernum"]').val('');
$('input[name="lastname"]').val('');
$('.lookup-step[data-step=3]').hide();
$('.lookup-step[data-step=1]').show();
$('#lookup-contact h6 b').html('1-800-HOME-DEPOT <br> (1-800-466-3337)');
});
// Loading icon
$("#ajax-loader").bind("ajaxStart", function(){
$(this).show();
}).bind("ajaxComplete", function(){
$(this).hide();
});
// Invoice Modal
$('a#popup-store').click(function(e){
console.log($(this).data('path'));
var path = $(this).data('path') + 'components/com_jw_lookup/assets/img/invoices/' + self.ordertype + '.png';
modal.open({
content: '<img src="' + path + '" width="100%">',
width: 700,
height: 400
});
e.preventDefault();
});
$('a#popup-online').click(function(e){
console.log($(this).data('path'));
var path = $(this).data('path') + 'components/com_jw_lookup/assets/img/invoices/' + self.ordertype + '.png';
modal.open({
content: '<img src="' + path + '" width="100%">',
width: 700,
height: 400
});
e.preventDefault();
});
// Input mask
$('input[name="ordernum"]').keyup(function() {
$('input[name="ordernum"]').removeClass('error');
var start = this.selectionStart,
end = this.selectionEnd;
if (event.keyCode == 8 || event.keyCode == 46 || event.keyCode == 37 || event.keyCode == 39) return false;
if(self.ordertype === 'store') {
var value = $(this).val();
if (value.length > 4) {
value = value.replace('-', '');
$(this).val(value.substring(0,4) + '-' + value.slice(4));
}
if(start === 5){
start++;
end++;
}
}
this.setSelectionRange(start, end);
});
}
self.showResult = function(result){
$('.lookup-step[data-step=2]').hide();
$('.lookup-step[data-step=3]').show();
$('#lookup-result .ordernum').html(result.ordernum);
$('#lookup-result #recdate').html(result.recdate);
$('#lookup-result #estdate').html(result.estdate);
$('#lookup-result #lastupdate').html(result.lastupdate);
for(i = 0; i < (result.step); i++) {
var item = $('#lookup-result li:nth-child('+ i +')');
item.addClass('success');
item.children('.check').css('display', 'inline-block');
}
$('#lookup-result li:nth-child('+ result.step +')').addClass('current');
if(result.step > 5){
$('#lookup-result li:nth-child(5) h5').html('Shipped Order');
} else {
$('#lookup-result li:nth-child(5) h5').html('Shipping Order');
}
switch(result.extra) {
case 'partial':
$('#lookup-extra').html('<p>* One or more of your items have shipped. Please contact customer service for information about the remaining items in your order: ' + self.phones[self.ordertype] + '</p>');
break;
case 'split':
case 'cancel':
$('#lookup-extra').html('<p>* Please contact customer service regarding your order.<br> We apologize for any inconvenience. <br><b>Please Contact: ' + self.phones[self.ordertype] + '</b></p>');
break;
default:
$('#lookup-extra').html('');
}
}
self.showNoResult = function(){
$('#errormsg').html('Your order could not be found. Please re-enter the order number as it appears on the receipt or in the confirmation email.').show();
}
self.showFail = function(){
$('#errormsg').html('Please contact customer service regarding your order.<br> We apologize for any inconvenience. <br><b>Please Contact: ' + self.phones[self.ordertype] + '</b>').show();
}
self.validateStep = function(step){
var isValid = true;
switch(step){
case 1:
if(!$('input[name="ordertype"]').is(':checked')){
$('#errormsg').html('Please choose an order type.').show();
isValid = false;
}
break;
case 2:
var value = $('input[name="ordernum"]').val().replace('-', '');
if(value == ''){
$('#errormsg').html('Please input your order number.').show();
$('input[name="ordernum"]').addClass('error');
isValid = false;
} else if(self.ordertype == 'store') {
//var trim = value.replace('-', '');
if(isNaN(value)){
$('#errormsg').html('Your order number should only contain numbers.').show();
$('input[name="ordernum"]').addClass('error');
isValid = false;
} else if(value.length <= 4){
$('#errormsg').html('Please verify your order number length.').show();
$('input[name="ordernum"]').addClass('error');
isValid = false;
}
} else if(self.ordertype == 'online') {
var first = value.charAt(0).toUpperCase();
if(first != 'W' && first != 'C'){
$('#errormsg').html('Your order number should begin with a C or W.').show();
$('input[name="ordernum"]').addClass('error');
isValid = false;
} else if(value.length != 10){
$('#errormsg').html('Your order number should be 10 characters long.').show();
$('input[name="ordernum"]').addClass('error');
isValid = false;
}
}
if(isValid) {
$('input[name="ordernum"]').removeClass('error');
}
break;
}
if(isValid) $('#errormsg').html('').hide();
return isValid;
}
}
var modal = (function(){
var
method = {},
$overlay,
$modal,
$content,
$close;
// Center the modal in the viewport
method.center = function () {
var top, left;
top = Math.max($(window).height() - $modal.outerHeight(), 0) / 2;
left = Math.max($(window).width() - $modal.outerWidth(), 0) / 2;
$modal.css({
top:top + $(window).scrollTop(),
left:left + $(window).scrollLeft()
});
};
// Open the modal
method.open = function (settings) {
$content.empty().append(settings.content);
$modal.css({
width: settings.width || 'auto',
height: settings.height || 'auto'
});
method.center();
$(window).bind('resize.modal', method.center);
$modal.show();
$overlay.show();
};
// Close the modal
method.close = function () {
$modal.hide();
$overlay.hide();
$content.empty();
$(window).unbind('resize.modal');
};
// Generate the HTML and add it to the document
$overlay = $('<div class="com_jw_lookup hopup overlay"></div>');
$modal = $('<div class="com_jw_lookup hopup main"></div>');
$content = $('<div class="com_jw_lookup hopup content"></div>');
$close = $('<a class="com_jw_lookup hopup close" href="#">close</a>');
$modal.hide();
$overlay.hide();
$modal.append($content, $close);
$(document).ready(function(){
$('body').append($overlay, $modal);
});
$close.click(function(e){
e.preventDefault();
method.close();
});
return method;
}());
<?php
ini_set('soap.wsdl_cache_enabled', '0');
ini_set('soap.wsdl_cache_ttl', '0');
defined('_JEXEC') or die;
require_once JPATH_COMPONENT.'/controller.php';
class Jw_lookupControllerStatus extends Jw_lookupController
{
public function lookupOrder()
{
$debug = (isset($_GET["debug"]) && $_GET['debug'] == 'true' ) ? true : false;
if ($debug) {
ini_set("display_errors", 1);
$input = $_GET;
echo '<pre>';
} else {
header('Content-Type: application/json');
$input = $_POST;
}
$ordernum = $input['ordernum'];
$url = ".../Jw_Thd_Wsi_GetOrderStatusWS?wsdl";
$local_cert = "...";
$passphrase = "...";
$options = array(
'local_cert' => $local_cert,
'passphrase' => $passphrase,
'trace' => 1,
'cache_wsdl' => WSDL_CACHE_NONE
);
$parameters = array(
"OrderNumber" => $input['ordernum']
);
$output = array();
try {
$client = new SoapClient($url, $options);
$client->__setLocation('.../Jw_Thd_Wsi_GetOrderStatusWS?wsdl');
$response = $client->getOrderStatus($parameters);
if($debug){
$reqXML = $client->__getLastRequest();
$respXML = $client->__getLastResponse();
echo '<h1>Request</h1>';
echo $reqXML;
echo '<h1>Response</h1>';
echo $respXML;
echo '<h1>Output</h1>';
var_dump($response);
}
$output['ordernum'] = $ordernum;
if($response->Result == "SUCCESS") {
$output['result'] = 'success';
$dt = new DateTime($response->OrderCreateDate);
$output['recdate'] = $dt->format('m/d/Y');
$startdate = $response->EstimatedDeliveryDateStart->_;
$enddate = $response->EstimatedDeliveryDateEnd->_;
if($startdate != 'NULL' && $enddate != 'NULL'){
$startDt = new DateTime($response->EstimatedDeliveryDateStart->_);
$endDt = new DateTime($response->EstimatedDeliveryDateEnd->_);
if($startDt == $endDt){
$output['estdate'] = $endDt->format('m/d/Y');
} else {
$output['estdate'] = $startDt->format('m/d/Y') . ' - ' . $endDt->format('m/d/Y');
}
} else {
$output['estdate'] = '<b class="error">Contact Customer Service</b>';
$output['extra'] = 'split';
}
$lastupdate = $response->LastUpdatedDateTime->_;
if($lastupdate != 'NULL'){
$lastupDt = new DateTime($response->LastUpdatedDateTime->_);
$output['lastupdate'] = $lastupDt->format('m/d/Y');
} else {
$output['lastupdate'] = '<b>N/A.</b>';
}
$output['step'] = $this->getOrderStep($response);
if ($response->OrderCanceled == true){
$output['extra'] = 'cancel';
} elseif ($response->PartialOrder){
$output['extra'] = 'partial';
} elseif ($response->SplitOrder){
$output['extra'] = 'split';
}
} else {
$output['result'] = 'error';
}
} catch(Exception $e) {
if($debug){
echo '<h1>Error</h1>';
var_dump($e);
}
$output['result'] = 'fail';
}
if($debug){
echo '<h1>JSON</h1>';
die(json_encode($output));
} else {
die(json_encode($output));
}
}
public function lookupCustomer()
{
die();
}
public function getOrderStep($response) {
if ($response->PreparingOrder == '300'){
return '1';
} elseif ($response->PreparingOrder == '200'){
return '2';
} elseif ($response->BuildingOrder == '200'){
return '3';
} elseif ($response->PackagingOrder == '200'){
return '4';
} elseif ($response->ShippedOrder == '100'){
$endDt = new DateTime($response->EstimatedDeliveryDateEnd->_);
$endDate = $endDt->format('m/d/Y');
$nowDate = date('m/d/Y');
if ($endDate >= $nowDate) {
return '5';
} else {
return '6';
}
} else {
return '0';
}
}
}