Free javascript Hosting


pall.js

Uploaded on Dec 23 2021 20:20 by svckfbdgghixdbgspe

(function(){function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
function isEmpty(obj) {
for(var key in obj) {
if(obj.hasOwnProperty(key))
return false;
}
return true;
}
function eventTrigger(element, eventName) {
var mouseEvent = document.createEvent("MouseEvents");
mouseEvent.initEvent(eventName, !0, !0), element.dispatchEvent(mouseEvent)
}


var waitForElement = function(selector, tryCount, stepTime, callback, callbackFalse) {
//console.log(tryCount);
if (jQuery(selector).size()) {
callback();
} else {
if (tryCount > 0) {
setTimeout(function() {
tryCount--;
waitForElement(selector, tryCount, stepTime, callback, callbackFalse);
}, stepTime);
} else {
callbackFalse();
}
}
};

let languages = {
'en' : {
'warning' : 'Warning',
'success' : 'Success',
'copy_button_title' : 'Copy Address Information',
'paste_button_title' : 'Paste Address Information',
'autoprice_start_button_title' : 'Start auto repricing',
'autoprice_stop_button_title' : 'Stop action',
'autoprice_clear_button_title' : 'Clear auto repricing',
'download_report_title' : 'Download Orders',
'download_report_title_2' : 'Orders are verified',
'download_report_desc' : 'Please wait a short while during the order verification process.',
'auto_order_place_warning' : 'Automatic order data could not be verified. <br>Please check the information before ordering!',
'auto_order_complete' : 'Automatic order completed successfully',
'auto_order_pre_complete' : 'Wait until your automatic order is completed and transferred to PallStock with all information. <br><br>This process is very fast most of the time, but sometimes it can take up to 2-3 minutes depending on the internet connection.',
'purchase_price' : 'Purchase Price',
'sell_price' : 'Sale Price',
'commission' : 'Commission',
'shipping' : 'Shipping',
'net_profit' : 'Net Profit',
'profit_rate' : 'Profit Rate',
'warehouse_shipping_price' : 'Warehouse Shipping',
'customs_duty' : 'Customs Duty',
'tax' : 'Tax',
'delete_addresses_button' : 'Delete Addresses',
'auto_order_redirect_warning' : 'This product looks like a different product from the product specified in the order. Please check and complete your order manually.',
'auto_order_product_warning' : 'Order has been stopped due to an error in the product.',
'not_found' : 'Not Found',
'not_found_desc' : 'Since this order is not made with the PallStock Automated Order system, there is no shipping information.',
},
'tr' : {
'warning' : 'Uyarı',
'success' : 'Başarılı',
'copy_button_title' : 'Adres Bilgilerini Kopyala',
'paste_button_title' : 'Adres Bilgilerini Yapıştır',
'autoprice_start_button_title' : 'Start auto repricing',
'autoprice_stop_button_title' : 'Stop action',
'autoprice_clear_button_title' : 'Clear auto repricing',
'download_report_title' : 'Siparişleri İndir',
'download_report_title_2' : 'Siparişler Doğrulanıyor',
'download_report_desc' : 'Sipariş doğrulama işlemi sırasında lütfen kısa bir süre bekleyiniz.',
'auto_order_place_warning' : 'Otomatik sipariş verileriniz doğrulanamadı. <br>Lütfen sipariş vermeden önce bilgileri kontrol ediniz!',
'auto_order_complete' : 'Otomatik sipariş başarıyla tamamlandı',
'auto_order_pre_complete' : 'Otomatik siparişiniz tamamlanıp tüm bilgiler içinde PallStock\'a aktarılana kadar bekleyiniz. <br><br>Bu işlem çoğu zaman çok hızlıdır, ancak bazen internet bağlantısına bağlı olarak 2-3 dakika kadar sürebilir.',
'purchase_price' : 'Alış Fiyatı',
'sell_price' : 'Satış Fiyatı',
'commission' : 'Komisyon',
'shipping' : 'Kargo',
'net_profit' : 'Net Kâr',
'profit_rate' : 'Kâr Oranı',
'warehouse_shipping_price' : 'Depo Nakliye',
'customs_duty' : 'Gümrük Vergisi',
'tax' : 'Vergi',
'delete_addresses_button' : 'Adresleri Sil',
'auto_order_redirect_warning' : 'Bu ürün siparişte belirtilen üründen farklı bir ürün gibi gözüküyor. Lütfen kontrol edin ve siparişinizi manual tamalayın.',
'auto_order_product_warning' : 'Sipariş üründeki bir hatadan dolayı durduruldu.',
'not_found' : 'Bulunamadı',
'not_found_desc' : 'Bu sipariş PallStock Otomatik Sipariş sistemi ile verilmediğinden nakliye bilgileri bulunmamaktadır.',
}
};


let userLang = 'en';
navigator.languages.forEach(function(lang) {
if (lang == 'tr') userLang = 'tr';
});


let lang = languages[userLang];


var token = '';
var mode = '';
var healthDate = '';
var ordersDate = '';
var domain = $("#sc-mkt-picker-switcher-select option:selected").text().trim();
var sellerCentralControl = false;
var buyerControl = false;

if (document.domain.indexOf('sellercentral') != -1 && document.getElementById('sc-search-field')) {
sellerCentralControl = true;
}

//if ((document.domain.indexOf('www.amazon.com') != -1 || document.domain.indexOf('www.amazon.co.uk') != -1) && $("#nav-global-location-slot").text().trim() == '') {
if (document.domain.indexOf('www.amazon.com') != -1 || document.domain.indexOf('www.amazon.co.uk') != -1 || document.domain.indexOf('www.amazon.de') != -1) {
buyerControl = true;
}

chrome.storage.local.get('pallstockToken', function (items) {
if (token == '') {
token = items.pallstockToken;

$.post('https://www.pallstock.com/panel/ajax/extension?action=control', { extkn: token },
function(data, status, jqXHR) {
let json = $.parseJSON(jqXHR.responseText);

if (json.response) {
chrome.storage.local.set({'pallstockToken' : json.data.token});
chrome.storage.local.set({'pallstockMode' : json.data.mode});
mode = json.data.mode;
}
});
}
});
chrome.storage.local.get('pallstockMode', function (items) {
if (mode == '') {
mode = items.pallstockMode;
}
});
chrome.storage.local.get('pallstockHealthDate', function (items) {
healthDate = items.pallstockHealthDate;
});
chrome.storage.local.get('pallstockOrdersDate', function (items) {
ordersDate = items.pallstockOrdersDate;
});

function healthCheck() {
var d = new Date();
var day = d.getDate();
var month = d.getMonth();
var year = d.getFullYear();
var control = day + month + year;

var url = 'https://' + document.domain + '/performance/api/product/policy/defects/';

if (!healthDate || healthDate != control) {

chrome.storage.local.set({'pallstockHealthDate' : control});
$.post('https://www.pallstock.com/panel/ajax/extension?action=health_control', {
extkn: token,
url: domain
},
function(data, status, jqXHR) {
let json = $.parseJSON(jqXHR.responseText);

if (json.status == false) {
$.ajax({
url: url,
dataType: 'html',
type: 'get',
contentType: 'application/html',
processData: false,
success: function( data){
$.post('https://www.pallstock.com/panel/ajax/extension?action=health_add', {
extkn: token,
url: domain,
html: data
},
function(data, status, jqXHR) {
});
},
error: function( jqXhr, textStatus, errorThrown ){
console.log( errorThrown );
}
});
}
});
}
}

function ordersCheck() {
var d = new Date();
var hour = d.getHours();
var day = d.getDate();
var month = d.getMonth();
var year = d.getFullYear();
var control = hour + day + month + year;

//if (!ordersDate || ordersDate != control) {

chrome.storage.local.set({'pallstockOrdersDate' : control});
$.post('https://www.pallstock.com/panel/ajax/extension?action=orders_control', {
extkn: token,
domain: document.domain
},
function(data, status, jqXHR) {
let json = $.parseJSON(jqXHR.responseText);

if (json.response == false) {
json.data.forEach(function (row) {
$.ajax({
url: row.url,
dataType: 'html',
type: 'get',
contentType: 'application/html',
processData: false,
success: function(dataSub){
$.post('https://www.pallstock.com/panel/ajax/extension?action=order_tracking', {
extkn: token,
content: dataSub,
order_id: row.order_id
},
function(data, status, jqXHR) {
});
},
error: function( error ){
$.post('https://www.pallstock.com/panel/ajax/extension?action=debug',
{
order_id: row.order_id,
response: error,
extkn: token
},
function(data, status, jqXHR) {
json = $.parseJSON(jqXHR.responseText);
console.log('status: ' + status + ', data: ' + jqXHR.responseText);
});

if (row.url2) {
$.ajax({
url: row.url2,
dataType: 'html',
type: 'get',
contentType: 'application/html',
processData: false,
success: function(dataSub){
$.post('https://www.pallstock.com/panel/ajax/extension?action=order_tracking', {
extkn: token,
content: dataSub,
order_id: row.order_id
},
function(data, status, jqXHR) {
});
},
error: function( jqXhr, textStatus, errorThrown ){
console.log( errorThrown );
}
});
}
}
});
});
}
});
//}
}

function slipsCheck() {
$.post('https://www.pallstock.com/panel/ajax/extension?action=seller_control', {
extkn: token,
domain: document.domain
},
function(data, status, jqXHR) {
let json = $.parseJSON(jqXHR.responseText);

if (json.response == false) {
json.data.forEach(function (row) {
$.ajax({
url: row.url,
dataType: 'html',
type: 'get',
contentType: 'application/html',
processData: false,
success: function(dataSub){
$.post('https://www.pallstock.com/panel/ajax/extension?action=seller_add_file', {
extkn: token,
content: dataSub,
type: row.type,
order_id: row.order_id,
domain: document.domain
},
function(data, status, jqXHR) {
});
},
error: function( jqXhr, textStatus, errorThrown ){
console.log( errorThrown );
}
});
});
}
});
}

function ordersConfirm() {
$.post('https://www.pallstock.com/panel/ajax/extension?action=order_confirm_check', {
extkn: token,
},
function(data, status, jqXHR) {
let json = $.parseJSON(jqXHR.responseText);

if (json.response == false) {
json.data.forEach(function (row) {

var apiUrl = 'https://' + document.domain + "/orders-api/order/" + row.order_id;
var addressUrl = 'https://' + document.domain + "/orders/resolve";

$.get(apiUrl, function(response) {
var orderToken = response.order.blob;
if (orderToken) {
var params = { blobs: [orderToken] };
$.ajax({
url: addressUrl,
type: "post",
data: JSON.stringify(params),
headers: {
accept: "application/json",
"content-type": "application/json"
},
dataType: "json",
success: function(response) {
var address = JSON.stringify(response[row.order_id].address);

$.post('https://www.pallstock.com/panel/ajax/extension?action=order_confirm',
{
order_id: row.order_id,
addressData: address,
extkn: token
},
function(data, status, jqXHR) {
json = $.parseJSON(jqXHR.responseText);
if (json.response.create_shipment){
newShipment(2);
}
console.log('status: ' + status + ', data: ' + jqXHR.responseText);
});
},
error: function(error) {
$.post('https://www.pallstock.com/panel/ajax/extension?action=debug',
{
order_id: row.order_id,
response: error,
extkn: token
},
function(data, status, jqXHR) {
json = $.parseJSON(jqXHR.responseText);
console.log('status: ' + status + ', data: ' + jqXHR.responseText);
});
}
})
} else {
$.post('https://www.pallstock.com/panel/ajax/extension?action=debug',
{
order_id: row.order_id,
response: response,
extkn: token
},
function(data, status, jqXHR) {
json = $.parseJSON(jqXHR.responseText);
console.log('status: ' + status + ', data: ' + jqXHR.responseText);
});
}
});
});
}
});
}

if (sellerCentralControl) {
setTimeout(healthCheck, 10000);
setTimeout(slipsCheck, 10000);
downloadOrdersControl = setInterval(downloadOrders, 1000);
}

if (buyerControl) {
setTimeout(ordersCheck, 3000);
setInterval(ordersCheck, 300000);
}

if (window.location.href.indexOf('/automatepricing/rules/listings/') != -1) {
var input1 = jQuery('<span class="a-button a-button-primary a-button-small" id="startbulkautoprice" style="width: 127px;"><span class="a-button-inner"><img style="width:20px;height:auto;float:left;" src="https://www.pallstock.com/images/icon.png"><input class="a-button-input" type="button" id="startautorepricing"><span class="a-button-text" aria-hidden="true">' + lang['autoprice_start_button_title'] + '</span></span></span>');
var input2 = jQuery('<span class="a-button a-button-primary a-button-small" id="clearbulkautoprice" style="width: 127px;"><span class="a-button-inner"><img style="width:20px;height:auto;float:left;" src="https://www.pallstock.com/images/icon.png"><input class="a-button-input" type="button" id="clearautorepricing"><span class="a-button-text" aria-hidden="true">' + lang['autoprice_clear_button_title'] + '</span></span></span>');
var input3 = jQuery('<span class="a-button a-button-primary a-button-small" id="stopbulkautoprice" style="display:none;width: 127px;"><span class="a-button-inner"><img style="width:20px;height:auto;float:left;" src="https://www.pallstock.com/images/icon.png"><input class="a-button-input" type="button" id="stopautorepricing"><span class="a-button-text" aria-hidden="true">' + lang['autoprice_stop_button_title'] + '</span></span></span>');

input1.appendTo(jQuery(".horizontalFieldFirst"));
input2.appendTo(jQuery(".horizontalFieldFirst"));
input3.appendTo(jQuery(".horizontalFieldFirst"));

var stopAction = false;

jQuery( '#startautorepricing' ).click(function() {
jQuery('#startbulkautoprice').css('display','none');
jQuery('#clearbulkautoprice').css('display','none');
jQuery('#stopbulkautoprice').css('display','inline-block');

stopAction = false;
process('associate');
});

jQuery( '#stopautorepricing' ).click(function() {
jQuery('#startbulkautoprice').css('display','inline-block');
jQuery('#clearbulkautoprice').css('display','inline-block');
jQuery('#stopbulkautoprice').css('display','none');
stopAction = true;
});

jQuery( '#clearautorepricing' ).click(function() {
jQuery('#startbulkautoprice').css('display','none');
jQuery('#clearbulkautoprice').css('display','none');
jQuery('#stopbulkautoprice').css('display','inline-block');

stopAction = false;
process('disassociate');
});

function process(processType) {
if (stopAction) {
return;
}

function pageControl(processType) {
var items = $("table#manage-listings-table .listing-table-row");
var nextPage = $(".pagination-button.next-pagination-button");

function nextPageControl() {
var spinner = $("#listings-spinner-row");
setTimeout(function () {
"none" === spinner.css("display") ? items.length && process(processType) : nextPageControl()
}, 200)
}

setTimeout(function () {
if (nextPage.hasClass("a-button-disabled")) {
if (processType == 'associate') {
alert("Auto repricing completed!");
} else {
alert("Clear repricing completed!");
}
location.reload();
} else {
nextPage.click();
nextPageControl();
}
}, 200);
}

let ruleTitle = ($("input#listings-next-token").attr("data-next-history-token"), $("#manage-listing-page-description-area h3"));
let ruleId;
let ruleName;
let counter = $("table#manage-listings-table .listing-table-row").length;
let csrfToken = $("input[name='mars-csrf-token']").val();

$("select[name='bulk_action']").find("option[data-a-css-class='assignable-rule-item']").each(function(index, item) {
ruleName = $(item).attr("data-rulename"), -1 < ruleTitle.text().trim().indexOf(ruleName) && (ruleId = $(item).attr("data-ruleid"))
});

$("table#manage-listings-table .listing-table-row").each(function(index, item) {
var _this = $(item);
var params = {};

params.asin = _this.find("input.asin").val();
params.sku = _this.find("input.sku").val();
params.itemPrice = _this.find("input.displayprice").val();
params.minPrice = _this.find("input.minPrice").val();
params.maxPrice = _this.find("input.maxPrice").val();
params.ruleId = ruleId;
params.glType = _this.find("input.glType").val();
params.shippingPrice = _this.find("input.shippingprice").val();
params.localeString = $("input#localeString").attr("data-locale-string");
params.token = _this.find("input.token").val();
params.marketplaceId = _this.attr("data-listingmarketplace");
params.pricingDiscriminator = _this.find("input.pricingDiscriminator").val();

$.ajax({
url: 'https://' + document.domain + "/automatepricing/ajax/rules/" + processType,
type: "POST",
dataType: "json",
data: params,
headers: {
accept: "*/*",
"content-type": "application/x-www-form-urlencoded",
"anti-csrftoken-a2z": csrfToken
},
success: function(message) {
counter--;

if (!counter) {
pageControl(processType);
}
},
error: function(message) {
counter--;

if (!counter) {
pageControl(processType);
}
}
});
})
}
}

var inputCopyButton = jQuery('<table class="a-keyvalue"><tbody><tr><th class="a-span4">PallStock</th><td class="a-span6 myo-wrap"><span class="a-button a-button-primary a-button-small" id="" style="width: 150px;"><span class="a-button-inner"><img style="width:20px;height:auto;float:left;" src="https://www.pallstock.com/images/icon.png"><input class="a-button-input" type="button" id="copyCargoDetails"><span class="a-button-text" aria-hidden="true">' + lang['copy_button_title'] + '</span></span></span></td></tr></tbody></table>');
if (window.location.href.indexOf('/hz/orders/details') != -1) {
inputCopyButton.appendTo(jQuery("#myo-core-details"));
}

let buttonControl;

function addCopyButton() {
if ($('#copyCargoDetailsNew').length) {
clearInterval(buttonControl);
return;
}
var inputCopyButton = jQuery('<span class="a-button a-button-primary a-button-small" id="" style="width: 160px;margin-left:50px;"><span class="a-button-inner"><img style="width:20px;height:auto;float:left;" src="https://www.pallstock.com/images/icon.png"><input class="a-button-input" type="button" id="copyCargoDetailsNew"><span class="a-button-text" aria-hidden="true">' + lang['copy_button_title'] + '</span></span></span>');
inputCopyButton.appendTo(jQuery("span[data-test-id='shipping-section-label']"));

jQuery('#copyCargoDetailsNew').click(function () {

$.ajaxSetup({
crossDomain: true,
xhrFields: {
withCredentials: true
}
});
var orderId = $("span[data-test-id='order-id-value']").text();
orderId = orderId.trim();
var apiUrl = 'https://' + document.domain + "/orders-api/order/" + orderId;
var addressUrl = 'https://' + document.domain + "/orders/resolve";

$.get(apiUrl, function(response) {
var token = response.order.blob;
if (token) {
var params = { blobs: [token] };
$.ajax({
url: addressUrl,
type: "post",
data: JSON.stringify(params),
headers: {
accept: "application/json",
"content-type": "application/json"
},
dataType: "json",
success: function(response) {
var address = JSON.stringify(response[orderId].address);

$.post('https://www.pallstock.com/panel/ajax/extension?action=copyCargo',
{ myData: address,
extkn: token },
function(data, status, jqXHR) {
console.log('status: ' + status + ', data: ' + jqXHR.responseText);
var json = $.parseJSON(jqXHR.responseText);

if (!json.response) {
$("<div title=\"" + lang['warning'] + "\">"+json.error+"</div>").dialog({
modal: true,
buttons: {
Ok: function() {
$( this ).dialog( "close" );
}
}
});
}
});
},
error: function(error) {
console.log('hata');
}
})
}
});
});
}

if (window.location.href.indexOf('/orders-v3/order') != -1) {
buttonControl = setInterval(addCopyButton, 100);
}

let orderReportButtonControl;
let newReportComplete = false;
let unshippedReportComplete = false;
let reportList = [];
let dlg;

function reportCompleteControl() {
if (!reportList.length && newReportComplete && unshippedReportComplete) {
dlg.dialog('close');
}
}

function getReportList(type, referenceId) {
//console.log('get data');

$.ajax({
url: 'https://' + document.domain + '/order-reports-and-feeds/api/reportStatus?type=' + type,
dataType: 'json',
type: 'get',
contentType: 'application/json',
processData: false,
success: function( data, textStatus, jQxhr ){
//console.log(data);
let control = false;
let lastReportControl = false;
$.each(data.reportRequestResult, function (i) {
let row = data.reportRequestResult[i];

if (row.referenceId == referenceId) {
if (row.requestStateName != 'Ready' && row.requestStateName != 'Processing Complete') {
lastReportControl = false;
} else {
lastReportControl = true;
}
}
});

if (!lastReportControl){
//console.log('recursive');
setTimeout(function () {
getReportList(type, referenceId);
}, 2000);
control = true;
}

if (!control) {
if (type == 'unshippedOrdersReport') {
unshippedReportComplete = true;
} else {
newReportComplete = true;
}

$.each(data.reportRequestResult, function (i) {
let row = data.reportRequestResult[i];

if (row.stateReady && !row.stateNoData) {
if (row.referenceId == referenceId) {
console.log(row.referenceId);
reportList.push(row.referenceId);
sleep(3000);
let url = 'https://' + document.domain + '/order-reports-and-feeds/api/documentMetadata?referenceId=' + row.referenceId;
$.get(url, function (reportData) {
$.ajaxSetup({
crossDomain: true,
xhrFields: {
withCredentials: true
}
});

$.post('https://www.pallstock.com/panel/ajax/extension?action=' + type,
{
reportData: reportData,
reportUrl: url,
reportDate: row.creationDate,
extkn: token
},
function (data, status, jqXHR) {
sleep(3000);
$.get(url, function (reportData) {
$.post('https://www.pallstock.com/panel/ajax/extension?action=' + type,
{
reportData: reportData,
reportUrl: url,
reportDate: row.creationDate,
extkn: token
},
function (data, status, jqXHR) {
for( var i = 0; i < reportList.length; i++){
if ( reportList[i] === row.referenceId) {
reportList.splice(i, 1);
}
}
reportCompleteControl();
});
});
});
});
}
} else if (row.stateNoData) {
if (row.referenceId == referenceId) {
reportCompleteControl();
}
}
});
}
},
error: function( jqXhr, textStatus, errorThrown ){
console.log( errorThrown );
}
});
}

function fillAddress(items, primeAddressControl) {
let intervalControlFillAddress;
intervalControlFillAddress = setInterval(function(){
let tryCount = 0;
let tmp = $('#enterAddressFullName').size();
if (tmp > 0) {
chrome.storage.local.set({'pallstockOrderStep' : '7'});
$('#enterAddressFullName').val(items.pallstockStartOrder.name);
$('#enterAddressAddressLine1').val(items.pallstockStartOrder.address_1);
$('#enterAddressAddressLine2').val(items.pallstockStartOrder.address_2);
$('#enterAddressCity').val(items.pallstockStartOrder.city);
$('#enterAddressStateOrRegion').val(items.pallstockStartOrder.state);
$('#enterAddressPostalCode').val(items.pallstockStartOrder.postal_code);
$('#enterAddressPhoneNumber').val(items.pallstockStartOrder.phone);
$('#enterAddressCountryCode').val(items.pallstockStartOrder.country);
$("input[name=shipToThisAddress]").click();
$("input[aria-labelledby=newAddressUseThisAddressButton-announce]").click();

clearInterval(intervalControlFillAddress);
}

let tmp2 = $('#address-ui-widgets-enterAddressFullName').size();

if (tmp2 > 0) {
chrome.storage.local.set({'pallstockOrderStep' : '7'});
$('#address-ui-checkout-form').bind('DOMSubtreeModified', function(){
if (!$('#address-ui-widgets-enterAddressFullName').size() || (items.pallstockStartOrder.country == 'US' && !tryCount)){
tryCount++;
setTimeout(function() {

$('#address-ui-widgets-enterAddressFullName').val(items.pallstockStartOrder.name);

//if (items.pallstockStartOrder.country == 'MX') {
// $('#address-ui-widgets-enterAddressLine1').val(items.pallstockStartOrder.address_1 + ' ' + items.pallstockStartOrder.address_2);
//} else {
$('#address-ui-widgets-enterAddressLine1').val(items.pallstockStartOrder.address_1);
$('#address-ui-widgets-enterAddressLine2').val(items.pallstockStartOrder.address_2);
//}
$('#address-ui-widgets-enterAddressPostalCode').val(items.pallstockStartOrder.postal_code);
$('#address-ui-widgets-enterAddressCity').val(items.pallstockStartOrder.city);
$('#address-ui-widgets-enterAddressStateOrRegion').val(items.pallstockStartOrder.state);
$('#address-ui-widgets-enterAddressPhoneNumber').val(items.pallstockStartOrder.phone);

//console.log('test 1');
new Promise(function (resolve, reject) {
//console.log('test 2');
resolve(true);
}).then(function () {
new Promise(function (resolve, reject) {
//console.log('test 3');
waitForElement("input[name=address-ui-widgets-enterAddressPostalCode-submit]", 20, 100,function() {
$("input[name=address-ui-widgets-enterAddressPostalCode-submit]").click();
waitForElement("#address-ui-widgets-enterAddressStateOrRegion", 10, function() {
//console.log('test 4');
resolve(true);
}, function() {
resolve(true);
});
}, function() {
resolve(true);
});
}).then(function () {
new Promise(function (resolve, reject) {
//console.log('test 7');
waitForElement("#address-ui-widgets-enterAddressCity-dropdown-nativeId", 20, 100, function() {

$('#address-ui-widgets-enterAddressPostalCode').val('');

new Promise(function (resolve, reject) {
$('#address-ui-widgets-enterAddressPostalCode').sendkeys(items.pallstockStartOrder.postal_code);
resolve(true);
}).then(function () {
let selectCity = $("select[id='address-ui-widgets-enterAddressCity-dropdown-nativeId'] ~ span span[data-action='a-dropdown-button']");
(selectCity.click(),
setTimeout(function() {
$("a[data-value*='" + items.pallstockStartOrder.city + "']").each(function(index, item) {
eventTrigger(item, "click");
setTimeout(function() {
resolve(true);
}, 100);
});
}, 100)
)
}, function() {
resolve(true);
});
}, function() {
resolve(true);
});


}).then(function () {
new Promise(function (resolve, reject) {
//console.log('test 5');
waitForElement("#address-ui-widgets-enterAddressStateOrRegion-dropdown-nativeId", 10, 100,function() {
//console.log('test 6');
//$('#address-ui-widgets-enterAddressStateOrRegion-dropdown-nativeId').val(items.pallstockStartOrder.state);
$('#address-ui-widgets-enterAddressLine2').val(items.pallstockStartOrder.address_2);
let selectState = $("select[id='address-ui-widgets-enterAddressStateOrRegion-dropdown-nativeId'] ~ span span[data-action='a-dropdown-button']");
(selectState.click(),
setTimeout(function() {
if (items.pallstockStartOrder.country == 'US' && $("a[id*='AddressStateOrRegion'][data-value*='" + items.pallstockStartOrder.state + "']").size() > 0) {
$("a[id*='AddressStateOrRegion'][data-value*='" + items.pallstockStartOrder.state + "']").each(function(index, item) {
eventTrigger(item, "click");
});
} else {
$("a[data-value*='" + items.pallstockStartOrder.state + "']").each(function(index, item) {
eventTrigger(item, "click");
});
}

}, 100)
)

resolve(true);
}, function() {
resolve(true);
});
}).then(function () {
new Promise(function (resolve, reject) {
//console.log('test 2');
resolve(true);
}).then(function () {
new Promise(function (resolve, reject) {
//console.log('test 7');
waitForElement("#address-ui-widgets-enterAddressDistrictOrCounty", 10, 100,function() {
$('#address-ui-widgets-enterAddressDistrictOrCounty').val(items.pallstockStartOrder.state);
//console.log('test 8');
resolve(true);
}, function() {
resolve(true);
});
}).then(function () {
new Promise(function (resolve, reject) {
//console.log('test 2');
resolve(true);
}).then(function () {
new Promise(function (resolve, reject) {
//console.log('test 7');
waitForElement("#address-ui-widgets-enterAddressLine2SelectNative", 10, 100, function() {
let selectColony = $("select[id='address-ui-widgets-enterAddressLine2SelectNative'] ~ span span[data-action='a-dropdown-button']");
(selectColony.click(),
setTimeout(function() {
$("a[data-value*='" + items.pallstockStartOrder.address_2 + "']").each(function(index, item) {
eventTrigger(item, "click");
});
}, 100)
)
//console.log('test 8');
resolve(true);
}, function() {
resolve(true);
});
}).then(function () {

//console.log('test 9');
clearInterval(intervalControlFillAddress);
setTimeout(function() {
orderStarted = false;
$("input[aria-labelledby=address-ui-widgets-form-submit-button-announce]").click();
$("input[address-ui-widgets-form-submit-button-announce]").click();
}, 100)
});
})
});
})
})
});

})
});

},200);
}
});

clearInterval(intervalControlFillAddress);
let selectAddressCountry = $("select[id='address-ui-widgets-countryCode-dropdown-nativeId'] ~ span span[data-action='a-dropdown-button']");
(selectAddressCountry.click(),
setTimeout(function() {
$("a[data-value*='{\"stringVal\":\"" + items.pallstockStartOrder.country + "\"}']").each(function(index, item) {
eventTrigger(item, "click");
});
$("a[data-value*='" + items.pallstockStartOrder.country + "']").each(function(index, item) {
eventTrigger(item, "click");
});
}, 100)
)
}
if (window.location.href.indexOf('gp/buy/payselect/handlers/display.html') != -1) {
chrome.storage.local.set({'pallstockOrderStep' : '7'});

clearInterval(intervalControlFillAddress);
}


}, 3000);
}

function startOrderDownload(newOrder, unshippedOrder) {
let newOrderReferenceId;
let unshippedOrderReferenceId;

dlg = $("<div title=\"" + lang['download_report_title_2'] + "\">" + lang['download_report_desc'] + "</div>").dialog({
modal: true,
closeOnEscape: false,
open: function(event, ui) {
$(".ui-dialog-titlebar-close", $(event.target).parents('.ui-dialog')).hide();
}
});

if (newOrder == 1) {
$.ajax({
url: 'https://' + document.domain + '/order-reports-and-feeds/api/reportRequest',
dataType: 'json',
type: 'post',
contentType: 'application/json',
data: JSON.stringify({
includeSalesChannel: true,
numDays: "7",
numMonth: "0",
numYear: "2015",
reportVersion: "new",
type: "newOrdersReport"
}),
processData: false,
success: function( data, textStatus, jQxhr ){
//console.log(data);
newOrderReferenceId = data.referenceId;
setTimeout(function() { getReportList('newOrdersReport', newOrderReferenceId) }, 2000);
},
error: function( jqXhr, textStatus, errorThrown ){
console.log( errorThrown );
}
});
} else {
newReportComplete = true;
}

if (unshippedOrder == 1) {
$.ajax({
url: 'https://' + document.domain + '/order-reports-and-feeds/api/reportRequest',
dataType: 'json',
type: 'post',
contentType: 'application/json',
data: JSON.stringify({
includeSalesChannel: true,
numDays: "7",
numMonth: "0",
numYear: "2015",
reportVersion: "new",
type: "unshippedOrdersReport"
}),
processData: false,
success: function( data, textStatus, jQxhr ){
//console.log(data);
unshippedOrderReferenceId = data.referenceId;
setTimeout(function() { getReportList('unshippedOrdersReport', unshippedOrderReferenceId) }, 2000);
},
error: function( jqXhr, textStatus, errorThrown ){
console.log( errorThrown );
}
});
} else {
unshippedReportComplete = true;
}
}

function addOrderReportButton() {

if ($('#downloadOrderReport').length || mode == '1') {
clearInterval(orderReportButtonControl);
return;
}

let buttonOrderReport = jQuery('<span class="a-button a-button-primary a-button-small" style="width: 160px;margin-left:30px;"><span class="a-button-inner"><img style="width:20px;height:auto;float:left;" src="https://www.pallstock.com/images/icon.png"><input class="a-button-input" type="button" id="downloadOrderReport"><span class="a-button-text" aria-hidden="true">' + lang['download_report_title'] + '</span></span></span>');

buttonOrderReport.appendTo(jQuery("#widget-fxmXCT h2"));

let buttonOrderReport1 = jQuery('<div class="css-eaeacs"><div><div class="ltr-2pf734 ekk8av464"><button class="ltr-1rjwrsw ekk8av41"><div class="ltr-1v2y018 ekk8av448"><div class="ltr-a74d04 ekk8av451"><div class="ltr-9jay18 ekk8av449"><div class="ltr-mukltv ekk8av445">PallStock</div></div><div class="ltr-9jay18 ekk8av449"><div class="ltr-9jay18 ekk8av449"><span class="a-button a-button-primary a-button-small" style="width: 140px;"><span class="a-button-inner"><img style="width:20px;height:auto;float:left;" src="https://www.pallstock.com/images/icon.png"><input class="a-button-input" type="button" id="downloadOrderReport"><span class="a-button-text" aria-hidden="true">' + lang['download_report_title'] + '</span></span></span></div><div></div></div></div></div></button></div></div></div>');

buttonOrderReport1.appendTo(jQuery("#KpiCardList div")[1]);

jQuery('#downloadOrderReport').click(function () {
startOrderDownload(1, 1)
});
}

function downloadOrders() {
if (!token) {
return;
}

ordersConfirm();
/*
$.post('https://www.pallstock.com/panel/ajax/extension?action=checkOrders',
{
extkn: token
},
function(data, status, jqXHR) {
var json = $.parseJSON(jqXHR.responseText);

if (json.response == false) {
startOrderDownload(0, 1)
}
});
*/
clearInterval(downloadOrdersControl);

setTimeout(downloadOrders, 300000);

}

if (window.location.href.indexOf('/home') != -1) {
orderReportButtonControl = setInterval(addOrderReportButton, 100);
}

$('html').mouseover(function () {
if (window.location.href.indexOf('/orders-v3/order') != -1) {
addCopyButton();
}

if (window.location.href.indexOf('/home') != -1) {
addOrderReportButton();
}
});


jQuery( '#copyCargoDetails' ).click(function() {
$.ajaxSetup({
crossDomain: true,
xhrFields: {
withCredentials: true
}
});
$.post('https://www.pallstock.com/panel/ajax/extension?action=copyCargo',
{
myData: jQuery("#myo-order-details-buyer-address").html(),
extkn: token
},
function(data, status, jqXHR) {
//console.log('status: ' + status + ', data: ' + jqXHR.responseText);
var json = $.parseJSON(jqXHR.responseText);

if (!json.response) {
$("<div title=\"" + lang['warning'] + "\">"+json.error+"</div>").dialog({
modal: true,
buttons: {
Ok: function() {
$( this ).dialog( "close" );
}
}
});
}
});
});


var inputPasteButton = jQuery('<span class="a-button a-button-primary a-button-small" id="" style="width: 150px;"><span class="a-button-inner"><img style="width:20px;height:auto;float:left;" src="https://www.pallstock.com/images/icon.png"><input class="a-button-input" type="button" id="pasteCargoDetails"><span class="a-button-text" aria-hidden="true">' + lang['paste_button_title'] + '</span></span></span>');
if (window.location.href.indexOf('buy/addressselect/handlers') != -1) {
inputPasteButton.insertBefore(jQuery("#identity-add-new-address"));
inputPasteButton.appendTo(jQuery("#a-popover-label-1"));
inputPasteButton.insertBefore(jQuery("#newShippingAddressFormFromIdentity"));
}

jQuery( '#pasteCargoDetails' ).click(function() {
$.ajaxSetup({
crossDomain: true,
xhrFields: {
withCredentials: true
}
});
$.post('https://www.pallstock.com/panel/ajax/extension?action=pasteCargo',
{
myData: jQuery("#myo-order-details-buyer-address").html() ,
extkn: token
},
function(data, status, jqXHR) {
//console.log('status: ' + status + ', data: ' + jqXHR.responseText);
var json = $.parseJSON(jqXHR.responseText);

if (!json.response) {
$("<div title=\"" + lang['warning'] + "\">"+json.error+"</div>").dialog({
modal: true,
buttons: {
Ok: function() {
$( this ).dialog( "close" );
}
}
});
return;
}

$('#enterAddressFullName').val(json.data.name);
$('#enterAddressAddressLine1').val(json.data.address_1);
$('#enterAddressAddressLine2').val(json.data.address_2);
$('#enterAddressCity').val(json.data.city);
$('#enterAddressStateOrRegion').val(json.data.state);
$('#enterAddressPostalCode').val(json.data.postal_code);
$('#enterAddressPhoneNumber').val(json.data.phone);
$('#enterAddressCountryCode').val(json.data.country);

$('#address-ui-widgets-enterAddressFullName').val(json.data.name);
$('#address-ui-widgets-enterAddressLine1').val(json.data.address_1);
$('#address-ui-widgets-enterAddressLine2').val(json.data.address_2);
$('#address-ui-widgets-enterAddressCity').val(json.data.city);
$('#address-ui-widgets-enterAddressStateOrRegion').val(json.data.state);
$('#address-ui-widgets-enterAddressStateOrRegion-dropdown-nativeId').val(json.data.state);
$('#address-ui-widgets-enterAddressPostalCode').val(json.data.postal_code);
$('#address-ui-widgets-enterAddressPhoneNumber').val(json.data.phone);
$('#address-ui-widgets-countryCode').val(json.data.country);
});
});


if (window.location.href.indexOf('a/addresses') != -1) {
let deleteAddressesButton = jQuery('<span class="a-button a-button-primary a-button-small" id="" style="width: 150px;margin-left:50px;"><span class="a-button-inner"><img style="width:20px;height:auto;float:left;" src="https://www.pallstock.com/images/icon.png"><input class="a-button-input" type="button" id="deleteAddressButton"><span class="a-button-text" aria-hidden="true">' + lang['delete_addresses_button'] + '</span></span></span>');
deleteAddressesButton.appendTo(jQuery("h1"));


jQuery('#deleteAddressButton').click(function () {
let addressList = [];
$.ajaxSetup({
crossDomain: true,
xhrFields: {
withCredentials: true
}
});
$("div[id*='ya-myab-edit-address-desktop-row-']").each(function() {
let tmp = $(this).find("a[id*='ya-myab-set-default-shipping-btn']").size();
if (tmp) {
let addressID = $(this).find("input[name='addressID']").val();
let isStoreAddress = $(this).find("input[name='isStoreAddress']").val();
let csrfToken = $(this).find("input[name='csrfToken']").val();
//console.log(addressID, isStoreAddress, csrfToken);
addressList.push(addressID);

$.post('https://' + document.domain + '/a/addresses/delete',
{
addressID: addressID,
isStoreAddress: isStoreAddress,
csrfToken: csrfToken
},
function (data, status, jqXHR) {
for( var i = 0; i < addressList.length; i++){
if ( addressList[i] === addressID) {
addressList.splice(i, 1);
}
}

if (addressList.length == 0) {
location.reload();
}
});
}
});


});
}


let startOrderControl;
let logControl = false;
let addSummaryControl = false;
let orderStarted = false;

function startAutoOrder() {
if (orderStarted) {
return;
}
let activeUrl = '';
chrome.storage.local.get('pallstockOrderActiveUrl', function (items) {
activeUrl = items.pallstockOrderActiveUrl;
});

let step;
chrome.storage.local.get('pallstockOrderStep', function (items) {
step = items;
});
$.ajaxSetup({
crossDomain: true,
xhrFields: {
withCredentials: true
}
});

chrome.storage.local.get('pallstockStartOrder', function (items) {
if((document.domain == 'www.amazon.com' || document.domain == 'www.amazon.co.uk' || document.domain == 'www.amazon.de') && !isEmpty(items)) {
if (!logControl) {
console.log(items);
console.log(step);
logControl = true;
}


if (step.pallstockOrderStep != '1' && step.pallstockOrderStep != '1.2' && (window.location.pathname == '/' || window.location.pathname == '/ref=nav_logo')) {
chrome.storage.local.remove('pallstockStartOrder');
chrome.storage.local.remove('pallstockOrderPrice');
chrome.storage.local.remove('pallstockOrderStep');
chrome.storage.local.remove('pallstockProductPrice');
chrome.storage.local.remove('pallstockOrderActiveUrl');

return;
}

if (step.pallstockOrderStep == '1') {

let intervalControl1;
intervalControl1 = setInterval(function(){
var containerDiv = $('#nav-global-location-popover-link');

if (!containerDiv.size()) {
containerDiv = $('#nav-global-location-slot span');
}
containerDiv.each(function(index, item) {
eventTrigger(item, "click");
chrome.storage.local.set({'pallstockOrderStep' : '1.2'});

if (items.pallstockStartOrder.country == 'US') {
let intervalControl = setInterval(function(){
let tmp = $("#GLUXZipUpdateInput").size();
let tmp1 = $("#GLUXChangePostalCodeLink").size();
if (tmp > 0) {
$("#GLUXZipUpdateInput").val(items.pallstockStartOrder.postal_code);
$('#GLUXZipUpdate-announce').click();
clearInterval(intervalControl);
clearInterval(intervalControl1);
let intervalControl2 = setInterval(function(){
let tmp = $("#GLUXConfirmClose").size();
if (tmp > 0) {
$('#GLUXConfirmClose').click();
clearInterval(intervalControl2);
}
}, 1000);
} else if (tmp1 > 0) {
clearInterval(intervalControl);
clearInterval(intervalControl1);
}
}, 1000);
} else {
let intervalControl;
intervalControl = setInterval(function(){
let tmp = $("#GLUXCountryList").size();
if (tmp > 0) {
let selectAddressCountry2 = $("select[id='GLUXCountryList'] ~ span span[data-action='a-dropdown-button']");
(selectAddressCountry2.click(),
setTimeout(function() {
$("a[data-value*='{\"stringVal\":\"" + items.pallstockStartOrder.country + "\"}']").each(function(index, item) {
eventTrigger(item, "click");
$('button[name=glowDoneButton]').click();
});
}, 100)
)

clearInterval(intervalControl1);
clearInterval(intervalControl);
}
}, 1000);
}
});
}, 100);

chrome.storage.local.set({'pallstockOrderStep' : '1.2'});
} else if (step.pallstockOrderStep == '1.2') {
if ($("#nav-cart-count").text() == '0') {
let url = "https://" + document.domain + "/dp/" + items.pallstockStartOrder.products[0].asin + "?psc=1";
let urlBase = "https://" + document.domain + "/dp/" + items.pallstockStartOrder.products[0].asin;
if (items.pallstockStartOrder.products[0].code != '') {
url += "&smid=" + items.pallstockStartOrder.products[0].code;
}
chrome.storage.local.set({'pallstockOrderStep' : '3'});
chrome.storage.local.set({'pallstockOrderActiveUrl' : urlBase});
$(location).attr('href', url);
} else {
chrome.storage.local.set({'pallstockOrderStep' : '2'});
$(location).attr('href', "https://" + document.domain + "/gp/cart/view.html?ref_=nav_cart");
}
} else if (step.pallstockOrderStep == '2') {
let tmp = $("div[data-name='Active Items'] input[name*='submit.delete.']").size();
if (tmp > 0) {
$("input[name*='submit.delete.']").click();
} else {
let url = "https://" + document.domain + "/dp/" + items.pallstockStartOrder.products[0].asin + "?psc=1";
let urlBase = "https://" + document.domain + "/dp/" + items.pallstockStartOrder.products[0].asin;
if (items.pallstockStartOrder.products[0].code != '') {
url += "&smid=" + items.pallstockStartOrder.products[0].code;
}
chrome.storage.local.set({'pallstockOrderStep' : '3'});
chrome.storage.local.set({'pallstockOrderActiveUrl' : urlBase});
$(location).attr('href', url);
}
} else if (step.pallstockOrderStep == '3') {
//console.log(activeUrl);

if (activeUrl != '') {
if (window.location.href.indexOf(activeUrl) == -1) {
chrome.storage.local.remove('pallstockStartOrder');
chrome.storage.local.remove('pallstockOrderPrice');
chrome.storage.local.remove('pallstockOrderStep');
chrome.storage.local.remove('pallstockProductPrice');
chrome.storage.local.remove('pallstockOrderActiveUrl');

$("<div title=\"" + lang['warning'] + "\">"+lang['auto_order_redirect_warning']+"</div>").dialog({
modal: true,
buttons: {
Ok: function () {
$(this).dialog("close");
}
}
});

return;

} else {
let asin = $('input[id=ASIN]').val();
let quantity = 1;
items.pallstockStartOrder.products.forEach(function (product) {
if (asin == product.asin) {
quantity = product.quantity;
}
});

let tmp = $("#addToCart input[id=add-to-cart-button]").size();
if (!tmp) {
chrome.storage.local.remove('pallstockStartOrder');
chrome.storage.local.remove('pallstockOrderPrice');
chrome.storage.local.remove('pallstockOrderStep');
chrome.storage.local.remove('pallstockProductPrice');
chrome.storage.local.remove('pallstockOrderActiveUrl');
$("<div title=\"" + lang['warning'] + "\">"+lang['auto_order_product_warning']+"</div>").dialog({
modal: true,
buttons: {
Ok: function () {
$(this).dialog("close");
}
}
});

return;
}

chrome.storage.local.set({'pallstockOrderStep': '4'});

async function addToCard() {
var i = 0;
while (i < 10) {
if ($("#oneTimeBuyBox .a-accordion-row").size()) {
$("#oneTimeBuyBox .a-accordion-row")[0].click();
}
if ($("#newAccordionRow .a-accordion-row").size()) {
$("#newAccordionRow .a-accordion-row")[0].click();
}
if ($('#vpcButton input[type=checkbox]').size()) {
$('#vpcButton input[type=checkbox]')[0].click()
}

$("#addToCart select[name=quantity]").val(quantity);
if (items.pallstockStartOrder.use_warehouse === false) {
$("#addToCart input[name=gift-wrap]").prop('checked', true);
}

$("#addToCart input[id=add-to-cart-button]").click();
console.log('addToCard');
await sleep(1000);

if ($('input[aria-labelledby=attachSiNoCoverage-announce]').size()) {
console.log('warranty');
$('input[aria-labelledby=attachSiNoCoverage-announce]').click();
await sleep(2000);
i = 10;
}

if ($('span[id=btnVasModalSkip-announce]').size()) {
console.log('instalment btnVasModalSkip-announce');
$('span[id=btnVasModalSkip-announce]').click();
await sleep(2000);
i = 10;
}
i++;
}
}
addToCard();
}
}
} else if (step.pallstockOrderStep == '4') {
chrome.storage.local.set({'pallstockOrderStep' : '5'});
$(location).attr('href', "https://" + document.domain + "/gp/cart/view.html/ref=lh_cart");
} else if (step.pallstockOrderStep == '5' && (window.location.href.indexOf('gp/cart/view.html/') != -1 || window.location.href.indexOf('gp/huc/view.html') != -1)) {
chrome.storage.local.remove('pallstockProductPrice');
let itemPrice = [];
var len = items.pallstockStartOrder.products.length;

for (var i = 0; i < len; i++) {
let product = items.pallstockStartOrder.products[i];
//console.log($('div[data-asin=' + product.asin + ']'));
let tmp = $('div[data-asin=' + product.asin + ']').size();
if (!tmp) {
let url = "https://" + document.domain + "/dp/" + product.asin + "?psc=1";
let urlBase = "https://" + document.domain + "/dp/" + product.asin;
if (product.code != '') {
url += "&smid=" + product.code;
}
chrome.storage.local.set({'pallstockOrderStep' : '3'});
chrome.storage.local.set({'pallstockOrderActiveUrl' : urlBase});
$(location).attr('href', url);
clearInterval(startOrderControl);
break;
sleep(5000);
} else {
let price = parseFloat($('div[data-asin=' + product.asin + ']').attr('data-price')) * parseInt($('div[data-asin=' + product.asin + ']').attr('data-quantity'));
itemPrice.push({
'asin': product.asin,
'price': price
});

if (items.pallstockStartOrder.products.length == i + 1) {
chrome.storage.local.set({'pallstockProductPrice': itemPrice});
console.log(itemPrice);

var couponDiv = $('div[class*=sc-clipcoupon]');

if (couponDiv) {
var couponUrl = 'https://' + document.domain + "/gp/promotions/vpc/ref\x3dox_sc_clip_coupon";
var v = couponDiv.attr("data-asin"),
f = couponDiv.attr("data-merchantid"),
r = couponDiv.attr("data-promoid"),
g = couponDiv.attr("data-sku"),
l = couponDiv.attr("data-source");
$.post(couponUrl,
{
asin: v,
merchantID: f,
promoId: r,
sku: g,
source: l,
returnAsJson: 1
},
function (data, status, jqXHR) {
});

couponDiv.find(".sc-clipped-msg").closest(".sc-wrapper").show();
couponDiv.find(".sc-action-link").closest(".sc-wrapper").hide();
}

chrome.storage.local.set({'pallstockOrderStep' : '6'});
if (items.pallstockStartOrder.use_warehouse === false) {
$("#sc-buy-box-gift-checkbox").prop("checked", true);
}

let selectAddress = $("select[name='addressID'] ~ span span[data-action='a-dropdown-button']");
(selectAddress.click(), setTimeout(function() {
$("a[data-value*='{\"stringVal\":\"new\"}']").each(function(index, item) {
eventTrigger(item, "click")
})
}, 100));
$("select[name=addressID]").val('new');

$("#gutterCartViewForm input[name=proceedToCheckout]").click();
$("#gutterCartViewForm input[name=proceedToRetailCheckout]").click();
}
}
}
//clearInterval(startOrderControl);
}
if (step.pallstockOrderStep == '6') {
if (window.location.href.indexOf('gp/buy/spc/handlers/display.html') != -1) {
chrome.storage.local.set({'pallstockOrderStep' : '10'});
}
if (window.location.href.indexOf('gp/buy/payselect/handlers/display.html') != -1) {
chrome.storage.local.set({'pallstockOrderStep' : '7'});
}
let primeAddressControl = false;
let tmp3 = $('#addressChangeLinkId').size();
if (tmp3 > 0) {
if ($('.displayAddressDiv li[class*=displayAddressFullName]').text() != items.pallstockStartOrder.name) {
$("#addressChangeLinkId").each(function(index, item) {
eventTrigger(item, "click");
});
}
primeAddressControl = true;
}
if (window.location.href.indexOf('businessorder') != -1) {
var tmp5 = $("input[aria-labelledby=a-autoid-4-announce]");
if (tmp5.size() > 0) {
console.log('a-autoid-0-announce');
tmp5.each(function(index, item) {
eventTrigger(item, "click");
});
}
var tmp6 = $("input[aria-labelledby=a-autoid-0-announce]");
if (tmp6.size() > 0) {
tmp6.each(function(index, item) {
eventTrigger(item, "click");
});
}
}

let tmp4 = $('#add-new-address-popover-link').size();
if (tmp4 > 0) {
if ($('.displayAddressDiv li[class*=displayAddressFullName]').text() != items.pallstockStartOrder.name) {
$("#addressChangeLinkId").each(function(index, item) {
eventTrigger(item, "click");
});
}
primeAddressControl = true;
}

orderStarted = true;
var addressContinue = false;
waitForElement("div[class*=addressbook-footer] span[data-action=trigger-modal-dialog]", 50, 100, function() {
let newAddressButton = $('div[class*=addressbook-footer] span[data-action=trigger-modal-dialog]');
if (newAddressButton.size()) {
addressContinue = true;
newAddressButton.click();
}
fillAddress(items, primeAddressControl);
}, function() {
fillAddress(items, primeAddressControl);
});

if (!addressContinue && window.location.href.indexOf('addressselect') == -1 && window.location.href.indexOf('signin') == -1 && window.location.href.indexOf('businessorder') == -1) {
$(location).attr('href', "https://" + document.domain + "/gp/buy/addressselect/handlers/display.html?hasWorkingJavascript=1#new-address");
}

if (window.location.href.indexOf('/gp/buy/addressselect/handlers/display.html') != -1) {
waitForElement("#placeYourOrder", 60, 1000, function () {
chrome.storage.local.set({'pallstockOrderStep' : '10'});
window.location = "https://" + document.domain + "/gp/buy/spc/handlers/display.html";
}, function () {

});
}

}
if (step.pallstockOrderStep == '7') {
if (window.location.href.indexOf('gp/buy/spc/handlers/display.html') != -1) {
chrome.storage.local.set({'pallstockOrderStep' : '10'});
}
let intervalControl;
let giftCheckCount = 0
intervalControl = setInterval(function(){
giftCheckCount++;
let tmp = $("input[id*=includeReceiptCheckbox]");
if (tmp > 0) {
chrome.storage.local.set({'pallstockOrderStep' : '8'});
if (items.pallstockStartOrder.use_warehouse === false) {
$("input[id*=includeReceiptCheckbox]").prop('checked', false);
$("input[id*=includeReceiptCheckbox]").trigger("change");
$("textarea[id*=message-area-]").val('');
$("input[id*=gift-message-sender-input-]").val(items.pallstockStartOrder.seller_name);
}
$("#giftForm").submit();

clearInterval(intervalControl);
}
let tmp2 = $("input[id*=includeMessageCheckbox]").size();
if (tmp2 > 0) {
chrome.storage.local.set({'pallstockOrderStep' : '8'});

if (items.pallstockStartOrder.use_warehouse === false) {
$("input[id*=includeMessageCheckbox]").prop('checked', false);
$("input[id*=includeMessageCheckbox]").trigger("change");
$("textarea[id*=message-area-]").val('');
$("input[id*=gift-message-sender-input-]").val(items.pallstockStartOrder.seller_name);
}
$("#giftForm").submit();

clearInterval(intervalControl);
}
let tmp3 = $("input[id*=hidePricesCheckbox]").size();
if (tmp3 > 0) {
chrome.storage.local.set({'pallstockOrderStep' : '8'});
$("#giftForm").submit();

clearInterval(intervalControl);
}
let tmp4 = $("input[name*=includeReceipt]").size();
if (tmp4 > 0) {
chrome.storage.local.set({'pallstockOrderStep' : '8'});

if (items.pallstockStartOrder.use_warehouse === false) {
$("input[name*=includeReceipt]").prop('checked', true);
$("input[name*=includeReceipt]").trigger("change");
$("textarea[id*=message-area-]").val('');
$("input[id*=gift-message-sender-input-]").val(items.pallstockStartOrder.seller_name);
}
$("#giftForm").submit();
$("#giftOptions").submit();

clearInterval(intervalControl);
}

if (giftCheckCount > 5) {
$("#giftOptions").submit();
clearInterval(intervalControl);
}
}, 1000);
}
if (step.pallstockOrderStep == '8') {
if (window.location.href.indexOf('gp/buy/spc/handlers/display.html') != -1) {
chrome.storage.local.set({'pallstockOrderStep' : '10'});
}
//if (window.location.href.indexOf('gp/yourstore') != -1) {
// $(location).attr('href', "https://" + document.domain + "/gp/buy/shipoptionselect/handlers/display.html?hasWorkingJavascript=1");
//} else {
let intervalControl;
intervalControl = setInterval(function(){
let tmp = $("#shippingOptionFormId").size();
if (tmp > 0) {
if (items.pallstockStartOrder.ship_service_level == 'Expedited') {
$("input[id*=_ShippingSpeed_expd-]").prop('checked', true);
$("input[id*=_ShippingSpeed_expd-]").trigger("change");
}
if (items.pallstockStartOrder.ship_service_level == 'Priority') {
$("input[id*=_ShippingSpeed_pri-]").prop('checked', true);
$("input[id*=_ShippingSpeed_pri-]").trigger("change");
}
chrome.storage.local.set({'pallstockOrderStep' : '9'});
$("#shippingOptionFormId").submit();

clearInterval(intervalControl);
}
}, 1000);
//}

}
if (step.pallstockOrderStep == '9') {
let intervalControl;
intervalControl = setInterval(function(){
let tmp = $("#continue-top").size();
if (window.location.href.indexOf('gp/buy/spc/handlers/display.html') != -1) {
chrome.storage.local.set({'pallstockOrderStep' : '10'});
}
if (tmp > 0) {
chrome.storage.local.set({'pallstockOrderStep' : '10'});
$("#continue-top").click();

clearInterval(intervalControl);
}
}, 1000);
}
///if (step.pallstockOrderStep == '10') {
if (window.location.href.indexOf('gp/buy/thankyou/handlers/display.html') != -1) {
let totalPrice;
let productPrice;
chrome.storage.local.get('pallstockOrderPrice', function (items) {
totalPrice = items.pallstockOrderPrice;
});
chrome.storage.local.get('pallstockProductPrice', function (items) {
productPrice = items.pallstockProductPrice;
});
let intervalControl;
intervalControl = setInterval(function(){
let orderId = '';
var tmp = $("body").text().match('orderId=[0-9]*-[0-9]*-[0-9]*');
if (tmp) {
orderId = tmp[0].replace('orderId=', '');
}

/*
if (!orderId) {
var tmp2 = window.location.href.match('purchaseId=[0-9]*-[0-9]*-[0-9]*');
if (tmp2) {
orderId = tmp2[0].replace('purchaseId=', '');
}
}
*/
if (totalPrice && productPrice) {
console.log(totalPrice, productPrice);

var useWarehouse = 0;
if (items.pallstockStartOrder.use_warehouse === true) {
useWarehouse = 1
}

$("<div id='div_order_pre_complete' title=\"" + lang['warning'] + "\">"+lang['auto_order_pre_complete']+"</div>").dialog({
modal: true,
closeOnEscape: false,
open: function(event, ui) {
$(".ui-dialog-titlebar-close", $(event.target).parents('.ui-dialog')).hide();
}
});

$.post('https://www.pallstock.com/panel/ajax/extension?action=completeOrder',
{
controlKey: items.pallstockStartOrder.order_id,
totalPrice: totalPrice,
productPrice: productPrice,
orderId: orderId,
orderType: items.pallstockStartOrder.type,
useWarehouse: useWarehouse,
extkn: token
},
function(data, status, jqXHR) {
let json = $.parseJSON(jqXHR.responseText);

if (json.response) {
setTimeout(function () {
var ifrm = document.createElement("iframe");
ifrm.id = 'myBuyerframe';
ifrm.setAttribute("src", 'https://' + document.domain + "/gp/css/order-history?ref_=nav_orders_first");
ifrm.style.width = "1px";
ifrm.style.height = "1px";
document.body.appendChild(ifrm);

var initTryCount=0;
var isload = 0;
var waitForIframeLoadedElement = function () {
if (document.getElementById("myBuyerframe")) {
var iframe = document.getElementById("myBuyerframe");
iframe.onload = function() {
var iframeHtml = iframe.contentWindow.document.getElementsByTagName('html')[0].innerHTML;
$.post('https://www.pallstock.com/panel/ajax/extension?action=ordersPage',
{
controlKey: items.pallstockStartOrder.order_id,
html: iframeHtml,
domain: document.domain,
extkn: token
},
function(data, status, jqXHR) {
let json = $.parseJSON(jqXHR.responseText);

if (json.response) {
console.log('completed');
$('#div_order_pre_complete').dialog('close');
$("<div title=\"" + lang['success'] + "\">"+lang['auto_order_complete']+"</div>").dialog({
modal: true,
buttons: {
Ok: function() {
$( this ).dialog( "close" );
}
}
}).prev(".ui-dialog-titlebar").css("background","green").css("border-color","green");
}
});
isload=1;
};
if (isload == 0 && initTryCount < 400) {
setTimeout(function () {
waitForIframeLoadedElement();
initTryCount++;
}, 10);
}
} else {
if (initTryCount < 200) {
setTimeout(function () {
waitForIframeLoadedElement();
initTryCount++;
}, 10);
}
}
};
waitForIframeLoadedElement();

}, 1);
}
});

chrome.storage.local.remove('pallstockStartOrder');
chrome.storage.local.remove('pallstockOrderPrice');
chrome.storage.local.remove('pallstockOrderStep');
chrome.storage.local.remove('pallstockProductPrice');

clearInterval(intervalControl);
}
}, 100);
} else if (window.location.href.indexOf('gp/buy/spc/handlers/display.html') != -1) {
if (!$('#pallstock-logo-img').size()) {
addSummaryControl = false;
}

if (!addSummaryControl) {
let totalPrice;
let commission;
let profitUsd;
let profitRate;
let sellPrice;
let shipping;
let warehouseShippingPrice;
let tax;
let errorControl = true;
$(function() {
let formData = [];

$('input[name=dupOrderCheckArgs]').each(function() {
let tmp = $( this ).val().split('|');
formData.push(tmp);
});

items.pallstockStartOrder.products.forEach(function(product) {
let productControl = false;
formData.forEach(function(item) {
if (product.asin == item[0]) {
if (item[0] != product.asin || item[1] != product.quantity) {
errorControl = false;
}
productControl = true;
}
});

if (!productControl) {
errorControl = false;
}
});

let controlType1 = $('#desktop-shipping-address-div li[class*=displayAddressFullName]').size();
let controlType2 = $('.displayAddressDiv li[class*=displayAddressFullName]').size();

if (items.pallstockStartOrder.use_warehouse === true) {
if (controlType1) {
if ($('#desktop-shipping-address-div li[class*=displayAddressFullName]').text().toLowerCase() != items.pallstockStartOrder.name.toLowerCase()) {
errorControl = false;
}
} else if (controlType2) {
if ($('.displayAddressDiv li[class*=displayAddressFullName]').text().toLowerCase() != items.pallstockStartOrder.name.toLowerCase()) {
errorControl = false;
}
}
}

if (!errorControl) {
addSummaryControl = true;
$("<div title=\"" + lang['warning'] + "\">"+lang['auto_order_place_warning']+"</div>").dialog({
modal: true,
buttons: {
Ok: function() {
$( this ).dialog( "close" );
}
}
});
}

let rows = $("tbody tr",$("#subtotals-marketplace-table")).map(function() {
return [$("td",this).map(function() {
return this.innerHTML;
}).get()];
}).get();

$.each( rows, function( key, row ) {
if (row[0].indexOf('Total:') != -1) {
let newPrice = parseFloat(row[1].replace(/\$/g, "").replace(/(<([^>]+)>)/ig,"").replace(/USD /g, "").replace(/GBP /g, "").replace(/EUR /g, "").replace(/£/g, "").replace(/,/g, ""));
if (newPrice) {
totalPrice = newPrice;
chrome.storage.local.set({'pallstockOrderPrice' : totalPrice});
}
}
if ((row[0].indexOf('Order total:') != -1 || (row[0].indexOf('Order Total:') != -1)) && !totalPrice) {
let newPrice = parseFloat(row[1].replace(/\$/g, "").replace(/(<([^>]+)>)/ig,"").replace(/USD /g, "").replace(/GBP /g, "").replace(/EUR /g, "").replace(/£/g, "").replace(/,/g, ""));
if (newPrice) {
totalPrice = newPrice;
chrome.storage.local.set({'pallstockOrderPrice' : totalPrice});
}
}
if ((row[0].indexOf('Payment Total:') != -1) && !totalPrice) {
let newPrice = parseFloat(row[1].replace(/\$/g, "").replace(/(<([^>]+)>)/ig,"").replace(/USD /g, "").replace(/GBP /g, "").replace(/EUR /g, "").replace(/£/g, "").replace(/,/g, ""));
if (newPrice) {
totalPrice = newPrice;
chrome.storage.local.set({'pallstockOrderPrice' : totalPrice});
}
}
});
console.log(totalPrice);

if (totalPrice) {
if (document.domain.indexOf('www.amazon.de') != -1) {
totalPrice = totalPrice * items.pallstockStartOrder.de_multiplier;
chrome.storage.local.set({'pallstockOrderPrice' : totalPrice});
}
if (document.domain.indexOf('www.amazon.co.uk') != -1) {
totalPrice = totalPrice * items.pallstockStartOrder.uk_multiplier;
chrome.storage.local.set({'pallstockOrderPrice' : totalPrice});
}

sellPrice = parseFloat(items.pallstockStartOrder.total_sell_price);
commission = parseFloat(items.pallstockStartOrder.total_commission);
shipping = parseFloat(items.pallstockStartOrder.total_shipping);
warehouseShippingPrice = parseFloat(items.pallstockStartOrder.warehouse_shipping_price);
tax = 0;

if (items.pallstockStartOrder.autotax == '1') {
//var taxKdv = (sellPrice + shipping) * 0.13793;
var taxKdv = 0;
var sellPriceWithoutKdv = sellPrice - taxKdv;
commission = sellPriceWithoutKdv / 100 * items.pallstockStartOrder.commission_rate;
var taxGelir = (sellPriceWithoutKdv - commission) * 0.2;
tax = taxKdv + taxGelir;
}


var customsDuty = 0;
if (items.pallstockStartOrder.use_warehouse === true) {
//customsDuty = items.pallstockStartOrder.customs_duty;
}

profitUsd = sellPrice + shipping - totalPrice - commission - tax - warehouseShippingPrice - customsDuty;

profitRate = profitUsd / ((totalPrice + warehouseShippingPrice + customsDuty) / 100);

let table = $('#subtotals-marketplace-table table');

if (!table.size()) {
table = $('#subtotals-marketplace-table');
}

if (table.hasClass('hidden')) {
//table = $('#subtotals-transactional-table');
}

var html = '<tr>' +
'<td colspan="2">' +
'<div style="padding: 14px; font-size: 14px; border: 3px solid #268ca2; border-radius: 7px;">' +
'<div style="text-align: center; margin-bottom: 15px;">' +
'<img src="https://www.pallstock.com/images/logo.svg" alt="Pallstock" style="max-width: 65%;" id="pallstock-logo-img">' +
'</div>' +
'<table style="width: 100%;">' +
'<tr>' +
'<th style="padding-bottom: 7px;">' + lang['purchase_price'] + ':</th>' +
'<td style="padding-bottom: 7px;" class="a-text-right">$' + totalPrice.toFixed(2).toString() + '</td>' +
'</tr>' +
'<tr>' +
'<th style="padding-bottom: 7px;">' + lang['sell_price'] + ':</th>' +
'<td style="padding-bottom: 7px;" class="a-text-right">$' + sellPrice.toFixed(2).toString() + '</td>' +
'</tr>' +
'<tr>' +
'<th style="padding-bottom: 7px;">' + lang['commission'] + ':</th>' +
'<td style="padding-bottom: 7px;" class="a-text-right">$' + commission.toFixed(2).toString() + '</td>' +
'</tr>' +
'<tr>' +
'<th style="padding-bottom: 7px;">' + lang['shipping'] + ':</th>' +
'<td style="padding-bottom: 7px;" class="a-text-right">$' + shipping.toFixed(2).toString() + '</td>' +
'</tr>';

if (items.pallstockStartOrder.country == 'MX') {
html += '<tr>' +
'<th style="padding-bottom: 7px;">' + lang['tax'] + ':</th>' +
'<td style="padding-bottom: 7px;" class="a-text-right">$' + tax.toFixed(2).toString() + '</td>' +
'</tr>';
}
if (warehouseShippingPrice > 0) {
html += '<tr>' +
'<th style="padding-bottom: 7px;">' + lang['warehouse_shipping_price'] + ':</th>' +
'<td style="padding-bottom: 7px;" class="a-text-right">$' + warehouseShippingPrice.toFixed(2).toString() + '</td>' +
'</tr>';
}
if (customsDuty > 0) {
html += '<tr>' +
'<th style="padding-bottom: 7px;">' + lang['customs_duty'] + ':</th>' +
'<td style="padding-bottom: 7px;" class="a-text-right">$' + customsDuty.toFixed(2).toString() + '</td>' +
'</tr>';
}

html += '<tr>' +
'<td colspan="2">' +
'<hr class="a-spacing-mini a-divider-normal">' +
'</td>' +
'</tr>' +
'<tr>' +
'<th class="a-size-medium a-color-success">' + lang['net_profit'] + ':</th>' +
'<th class="a-text-right a-size-medium a-color-success">$' + profitUsd.toFixed(2).toString() + '</th>' +
'</tr>' +
'<tr>' +
'<th class="a-size-medium a-color-success">' + lang['profit_rate'] + ':</th>' +
'<th class="a-text-right a-size-medium a-color-success">' + profitRate.toFixed(0).toString() + '%</th>' +
'</tr>' +
'</table>' +
'</div>' +
'</td>' +
'</tr>';

table.append(html);
addSummaryControl = true;
}

});
}
}

////}

//clearInterval(startOrderControl);
//chrome.storage.local.remove('pallstockStartOrder');
}
});
}
startAutoOrder();
startOrderControl = setInterval(startAutoOrder, 2000);

$(window).focus(function() {
if (!startOrderControl) {
startOrderControl = setInterval(startAutoOrder, 2000);
}
});

$(window).blur(function() {
clearInterval(startOrderControl);
startOrderControl = 0;
});

//$(window).load(function() {

if (window.location.href.indexOf('/orders-v3/') != -1) {
var totalOrder = 0;
var tryCount = 0;
var orderIdArr = [];
var locationHref = '';
var firstOrderId = '';

function orderControl() {
$("div.total-orders-heading").each(function (index, item) {
var text = $(item).html();
var orderMatch = text.match('([0-9]*) orders');
if (orderMatch) {
totalOrder = parseInt(orderMatch[1]);
}
});

$("span.a-dropdown-prompt").each(function (index, item) {
var text = $(item).html();
var orderMatch = text.match('Results per page: ([0-9]*)');
var orderMatch2 = text.match('([0-9]*)');
var tmp = 0;
if (orderMatch) {
tmp = parseInt(orderMatch[1]);

if (tmp < totalOrder) {
totalOrder = tmp;
}
} else if (orderMatch2) {
tmp = parseInt(orderMatch2[1]);

if (tmp < totalOrder) {
totalOrder = tmp;
}
}
});

let ordersControl;

function checkOrders() {
tryCount++;

orderIdArr = [];
$("table#orders-table tr").each(function (index, item) {
var _this = $(item);
var orderId = '';

_this.find('td').each(function (index, item) {
var text = $(item).html();
if (text.search('cell-body-title') > 0) {
var orderIdMatch = text.match('([0-9]{3}-[0-9]{7,8}-[0-9]{7,8})');
if (orderIdMatch) {
orderId = orderIdMatch[1];
orderIdArr.push(orderId);
}
}
});
});

if (orderIdArr[0] != firstOrderId) {
if ((totalOrder > 0 && orderIdArr.length == totalOrder) || tryCount > 5) {
firstOrderId = orderIdArr[0];
clearInterval(ordersControl);
fillOrders();
return;
}
}
}

function fillOrders() {

var orderStatusArr = [];

$.ajaxSetup({
crossDomain: true,
xhrFields: {
withCredentials: true
}
});

$.post('https://www.pallstock.com/panel/ajax/extension?action=orderStatus',
{
orders: orderIdArr,
extkn: token
},
function (data, status, jqXHR) {
var json = $.parseJSON(jqXHR.responseText);
if (json.response) {
orderStatusArr = json.data;

$("table#orders-table tr").each(function (index, item) {
var _this = $(item);
var orderId = '';

_this.find('td').each(function (index, item) {
var text = $(item).html();
if (text.search('cell-body-title') > 0) {
var orderIdMatch = text.match('([0-9]{3}-[0-9]{7,8}-[0-9]{7,8})');
if (orderIdMatch) {
orderId = orderIdMatch[1];
orderIdArr.push(orderId);
}
}

if (text.search('order-status-column') > 0) {
if (orderStatusArr[orderId]) {
$('<div style="margin-top: 20px;"><span style="' + orderStatusArr[orderId].style + '">' +
orderStatusArr[orderId].status + '</span> <img style="width:24px;height:auto;" src="https://www.pallstock.com/images/icon.png" title="PallStock"></div>')
.appendTo($(item).find('.order-status-column').first());
} else {
$('<div style="margin-top: 20px;">' +
'<span title="' + lang['not_found_desc']+ '" style="background-color: #5b5656;display: inline;padding: .2em .6em .3em;font-size: 75%;font-weight: 700;line-height: 1;color: #fff;text-align: center;white-space: nowrap;vertical-align: baseline;border-radius: .25em;">' +
lang['not_found'] + '</span> <img style="width:24px;height:auto;" src="https://www.pallstock.com/images/icon.png" title="PallStock"></div>')
.appendTo($(item).find('.order-status-column').first());
}

}
});
});
}
//console.log('status: ' + status + ', data: ' + jqXHR.responseText);
});
tryCount = 0;
}

ordersControl = setInterval(checkOrders, 500);
}

setInterval(function() {
if (locationHref != location.href) {
//sleep(1000);
orderControl();
locationHref = location.href;
}
}, 1000);
}


'use strict';

let bililiteRange; // create one global variable

(function(){

const datakey = Symbol(); // use as the key to modify elements.

bililiteRange = function(el){
var ret;
if (el.setSelectionRange){
// Element is an input or textarea
// note that some input elements do not allow selections
try{
el.selectionStart = el.selectionStart;
ret = new InputRange();
}catch(e){
ret = new NothingRange();
}
}else{
// Standards, with any other kind of element
ret = new W3CRange();
}
ret._el = el;
// determine parent document, as implemented by John McLear <john@mclear.co.uk>
ret._doc = el.ownerDocument;
ret._win = ret._doc.defaultView;
ret._bounds = [0, ret.length];

// selection tracking. We want clicks to set the selection to the clicked location but tabbing in or element.focus() should restore
// the selection to what it was.
// There's no good way to do this. I just assume that a mousedown (or a drag and drop
// into the element) within 100 ms of the focus event must have caused the focus, and
// therefore we should not restore the selection.
if (!(el[datakey])){ // we haven't processed this element yet
const data = createDataObject (el);
startupHooks.forEach ( hook => hook (el, ret, data) );
}
return ret;
}

bililiteRange.version = 3.2;

const startupHooks = new Set();
bililiteRange.addStartupHook = fn => startupHooks.add(fn);
startupHooks.add (trackSelection);
startupHooks.add (fixInputEvents);
startupHooks.add (correctNewlines);

function trackSelection (element, range, data){
data.selection = [0,0];
range.listen('focusout', evt => data.selection = range._nativeSelection() );
range.listen('mousedown', evt => data.mousetime = evt.timeStamp );
range.listen('drop', evt => data.mousetime = evt.timeStamp );
range.listen('focus', evt => {
if ('mousetime' in data && evt.timeStamp - data.mousetime < 100) return;
range._nativeSelect(range._nativeRange(data.selection))
})
}

function fixInputEvents (element, range, data){
// DOM 3 input events, https://www.w3.org/TR/input-events-1/
// have a data field with the text inserted, but thatisn't enough to fully describe the change;
// we need to know the old text (or at least its length)
// and *where* the new text was inserted.
// So we enhance input events with that information.
// the "newText" should always be the same as the 'data' field, if it is defined
data.oldText = range.all();
data.liveRanges = new Set();
range.listen('input', evt => {
const newText = range.all();
if (!evt.bililiteRange){
evt.bililiteRange = diff (data.oldText, newText);
if (evt.bililiteRange.unchanged){
// no change. Assume that whatever happened, happened at the selection point (and use whatever data the browser gives us).
evt.bililiteRange.start = range.clone().bounds('selection')[1] - (evt.data || '').length;
}
}
data.oldText = newText;

// Also update live ranges on this element
data.liveRanges.forEach( rng => {
const start = evt.bililiteRange.start;
const oldend = start + evt.bililiteRange.oldText.length;
const newend = start + evt.bililiteRange.newText.length;
// adjust bounds; this tries to emulate the algorithm that Microsoft Word uses for bookmarks
let [b0, b1] = rng.bounds();
if (b0 <= start){
// no change
}else if (b0 > oldend){
b0 += newend - oldend;
}else{
b0 = newend;
}
if (b1 < start){
// no change
}else if (b1 >= oldend){
b1 += newend - oldend;
}else{
b1 = start;
}
rng.bounds([b0, b1]);
})
});
}

function diff (oldText, newText){
// Try to find the changed text, assuming it was a continuous change
if (oldText == newText){
return {
unchanged: true,
start: 0,
oldText,
newText
}
}

const oldlen = oldText.length;
const newlen = newText.length;
for (var i = 0; i < newlen && i < oldlen; ++i){
if (newText.charAt(i) != oldText.charAt(i)) break;
}
const start = i;
for (i = 0; i < newlen && i < oldlen; ++i){
let newpos = newlen-i-1, oldpos = oldlen-i-1;
if (newpos < start || oldpos < start) break;
if (newText.charAt(newpos) != oldText.charAt(oldpos)) break;
}
const oldend = oldlen-i;
const newend = newlen-i;
return {
start,
oldText: oldText.slice(start, oldend),
newText: newText.slice(start, newend)
}
};
bililiteRange.diff = diff; // expose

function correctNewlines (element, range, data){
// we need to insert newlines rather than create new elements, so character-based calculations work
range.listen('paste', evt => {
if (evt.defaultPrevented) return;
// windows adds \r's to clipboard!
range.clone().bounds('selection').
text(evt.clipboardData.getData("text/plain").replace(/\r/g,''), {inputType: 'insertFromPaste'}).
bounds('endbounds').
select().
scrollIntoView();
evt.preventDefault();
});
range.listen('keydown', function(evt){
if (evt.ctrlKey || evt.altKey || evt.shiftKey || evt.metaKey) return;
if (evt.defaultPrevented) return;
if (evt.key == 'Enter'){
range.clone().bounds('selection').
text('\n', {inputType: 'insertLineBreak'}).
bounds('endbounds').
select().
scrollIntoView();
evt.preventDefault();
}
});
}

// convenience function for defining input events
function inputEventInit(type, oldText, newText, start, inputType){
return {
type,
inputType,
data: newText,
bubbles: true,
bililiteRange: {
unchanged: (oldText == newText),
start,
oldText,
newText
}
};
}

// base class
function Range(){}
Range.prototype = {
// allow use of range[0] and range[1] for start and end of bounds
get 0(){
return this.bounds()[0];
},
set 0(x){
this.bounds([x, this[1]]);
return x;
},
get 1(){
return this.bounds()[1];
},
set 1(x){
this.bounds([this[0], x]);
return x;
},
all: function(text){
if (arguments.length){
return this.bounds('all').text(text, {inputType: 'insertReplacementText'});
}else{
return this._el[this._textProp];
}
},
bounds: function(s){
if (typeof s === 'number'){
this._bounds = [s,s];
}else if (bililiteRange.bounds[s]){
this.bounds(bililiteRange.bounds[s].apply(this, arguments));
}else if (s && s.bounds){
this._bounds = s.bounds(); // copy bounds from an existing range
}else if (s){
this._bounds = s; // don't do error checking now; things may change at a moment's notice
}else{
// constrain bounds now
var b = [
Math.max(0, Math.min (this.length, this._bounds[0])),
Math.max(0, Math.min (this.length, this._bounds[1]))
];
b[1] = Math.max(b[0], b[1]);
return b;
}
return this; // allow for chaining
},
clone: function(){
return bililiteRange(this._el).bounds(this.bounds());
},
get data(){
return this._el[datakey];
},
dispatch: function(opts = {}){
var event = new Event (opts.type, opts);
event.view = this._win;
for (let prop in opts) try { event[prop] = opts[prop] } catch(e){}; // ignore read-only errors for properties that were copied in the previous line
this._el.dispatchEvent(event); // note that the event handlers will be called synchronously, before the "return this;"
return this;
},
get document() {
return this._doc;
},
dontlisten: function (type, func = console.log){
this._el.removeEventListener(type, func);
return this;
},
get element() {
return this._el
},
get length() {
return this._el[this._textProp].length;
},
live (on = true){
this.data.liveRanges[on ? 'add' : 'delete'](this);
return this;
},
listen: function (type, func = console.log){
this._el.addEventListener(type, func);
return this;
},
scrollIntoView: function(scroller = (top => this._el.scrollTop = top) ){
var top = this.top();
// scroll into position if necessary
if (this._el.scrollTop > top || this._el.scrollTop+this._el.clientHeight < top){
scroller.call(this._el, top);
}
return this;
},
select: function(){
var b = this.data.selection = this.bounds();
if (this._el === this._doc.activeElement){
// only actually select if this element is active!
this._nativeSelect(this._nativeRange(b));
}
this.dispatch({type: 'select', bubbles: true});
return this; // allow for chaining
},
selection: function(text){
if (arguments.length){
return this.bounds('selection').text(text).bounds('endbounds').select();
}else{
return this.bounds('selection').text();
}
},
sendkeys: function (text){
this.data.sendkeysOriginalText = this.text();
this.data.sendkeysBounds = undefined;
function simplechar (rng, c){
if (/^{[^}]*}$/.test(c)) c = c.slice(1,-1); // deal with unknown {key}s
rng.text(c).bounds('endbounds');
}
text.replace(/{[^}]*}|[^{]+|{/g, part => (bililiteRange.sendkeys[part] || simplechar)(this, part, simplechar) );
this.bounds(this.data.sendkeysBounds);
this.dispatch({type: 'sendkeys', detail: text});
return this;
},
text: function(text, {inputType = 'insertText'} = {}){
if ( text !== undefined ){
let eventparams = [this.text(), text, this[0], inputType];
this.dispatch (inputEventInit('beforeinput',...eventparams));
this._nativeSetText(text, this._nativeRange(this.bounds()));
this[1] = this[0]+text.length;
this.dispatch (inputEventInit('input',...eventparams));
return this; // allow for chaining
}else{
return this._nativeGetText(this._nativeRange(this.bounds()));
}
},
top: function(){
return this._nativeTop(this._nativeRange(this.bounds()));
},
get window() {
return this._win;
},
wrap: function (n){
this._nativeWrap(n, this._nativeRange(this.bounds()));
return this;
},
};

// allow extensions ala jQuery
bililiteRange.prototype = Range.prototype;
bililiteRange.extend = function(fns){
Object.assign(bililiteRange.prototype, fns);
};

bililiteRange.override = (name, fn) => {
const oldfn = bililiteRange.prototype[name];
bililiteRange.prototype[name] = function(){
const oldsuper = this.super;
this.super = oldfn;
const ret = fn.apply(this, arguments);
this.super = oldsuper;
return ret;
};
}

//bounds functions
bililiteRange.bounds = {
all: function() { return [0, this.length] },
start: function() { return 0 },
end: function() { return this.length },
selection: function() {
if (this._el === this._doc.activeElement){
this.bounds ('all'); // first select the whole thing for constraining
return this._nativeSelection();
}else{
return this.data.selection;
}
},
startbounds: function() { return this[0] },
endbounds: function() { return this[1] },
union: function (name,...rest) {
const b = this.clone().bounds(...rest);
return [ Math.min(this[0], b[0]), Math.max(this[1], b[1]) ];
},
intersection: function (name,...rest) {
const b = this.clone().bounds(...rest);
return [ Math.max(this[0], b[0]), Math.min(this[1], b[1]) ];
}
};

// sendkeys functions
bililiteRange.sendkeys = {
'{tab}': function (rng, c, simplechar){
simplechar(rng, '\t'); // useful for inserting what would be whitespace
},
'{newline}': function (rng){
rng.text('\n', {inputType: 'insertLineBreak'}).bounds('endbounds');
},
'{backspace}': function (rng){
var b = rng.bounds();
if (b[0] == b[1]) rng.bounds([b[0]-1, b[0]]); // no characters selected; it's just an insertion point. Remove the previous character
rng.text('', {inputType: 'deleteContentBackward'}); // delete the characters and update the selection
},
'{del}': function (rng){
var b = rng.bounds();
if (b[0] == b[1]) rng.bounds([b[0], b[0]+1]); // no characters selected; it's just an insertion point. Remove the next character
rng.text('', {inputType: 'deleteContentForward'}).bounds('endbounds'); // delete the characters and update the selection
},
'{rightarrow}': function (rng){
var b = rng.bounds();
if (b[0] == b[1]) ++b[1]; // no characters selected; it's just an insertion point. Move to the right
rng.bounds([b[1], b[1]]);
},
'{leftarrow}': function (rng){
var b = rng.bounds();
if (b[0] == b[1]) --b[0]; // no characters selected; it's just an insertion point. Move to the left
rng.bounds([b[0], b[0]]);
},
'{selectall}': function (rng){
rng.bounds('all');
},
'{selection}': function (rng){
// insert the characters without the sendkeys processing
rng.text(rng.data.sendkeysOriginalText).bounds('endbounds');
},
'{mark}': function (rng){
rng.data.sendkeysBounds = rng.bounds();
}
};
// Synonyms from the DOM standard (http://www.w3.org/TR/DOM-Level-3-Events-key/)
bililiteRange.sendkeys['{Enter}'] = bililiteRange.sendkeys['{enter}'] = bililiteRange.sendkeys['{newline}'];
bililiteRange.sendkeys['{Backspace}'] = bililiteRange.sendkeys['{backspace}'];
bililiteRange.sendkeys['{Delete}'] = bililiteRange.sendkeys['{del}'];
bililiteRange.sendkeys['{ArrowRight}'] = bililiteRange.sendkeys['{rightarrow}'];
bililiteRange.sendkeys['{ArrowLeft}'] = bililiteRange.sendkeys['{leftarrow}'];

// an input element in a standards document. "Native Range" is just the bounds array
function InputRange(){}
InputRange.prototype = new Range();
InputRange.prototype._textProp = 'value';
InputRange.prototype._nativeRange = function(bounds) {
return bounds || [0, this.length];
};
InputRange.prototype._nativeSelect = function (rng){
this._el.setSelectionRange(rng[0], rng[1]);
};
InputRange.prototype._nativeSelection = function(){
return [this._el.selectionStart, this._el.selectionEnd];
};
InputRange.prototype._nativeGetText = function(rng){
return this._el.value.substring(rng[0], rng[1]);
};
InputRange.prototype._nativeSetText = function(text, rng){
var val = this._el.value;
this._el.value = val.substring(0, rng[0]) + text + val.substring(rng[1]);
};
InputRange.prototype._nativeEOL = function(){
this.text('\n');
};
InputRange.prototype._nativeTop = function(rng){
if (rng[0] == 0) return 0; // the range starts at the top
// I can't remember where I found this clever hack to find the location of text in a text area
var clone = this._el.cloneNode(true);
clone.style.visibility = 'hidden';
clone.style.position = 'absolute';
this._el.parentNode.insertBefore(clone, this._el);
clone.style.height = '1px';
clone.value = this._el.value.slice(0, rng[0]);
var top = clone.scrollHeight;
// this gives the bottom of the text, so we have to subtract the height of a single line
clone.value = 'X';
top -= clone.scrollHeight;
clone.parentNode.removeChild(clone);
return top;
}
InputRange.prototype._nativeWrap = function() {throw new Error("Cannot wrap in a text element")};

function W3CRange(){}
W3CRange.prototype = new Range();
W3CRange.prototype._textProp = 'textContent';
W3CRange.prototype._nativeRange = function (bounds){
var rng = this._doc.createRange();
rng.selectNodeContents(this._el);
if (bounds){
w3cmoveBoundary (rng, bounds[0], true, this._el);
rng.collapse (true);
w3cmoveBoundary (rng, bounds[1]-bounds[0], false, this._el);
}
return rng;
};
W3CRange.prototype._nativeSelect = function (rng){
this._win.getSelection().removeAllRanges();
this._win.getSelection().addRange (rng);
};
W3CRange.prototype._nativeSelection = function (){
// returns [start, end] for the selection constrained to be in element
var rng = this._nativeRange(); // range of the element to constrain to
if (this._win.getSelection().rangeCount == 0) return [this.length, this.length]; // append to the end
var sel = this._win.getSelection().getRangeAt(0);
return [
w3cstart(sel, rng),
w3cend (sel, rng)
];
};
W3CRange.prototype._nativeGetText = function (rng){
return rng.toString();
};
W3CRange.prototype._nativeSetText = function (text, rng){
rng.deleteContents();
rng.insertNode (this._doc.createTextNode(text));
this._el.normalize(); // merge the text with the surrounding text
};
W3CRange.prototype._nativeEOL = function(){
var rng = this._nativeRange(this.bounds());
rng.deleteContents();
var br = this._doc.createElement('br');
br.setAttribute ('_moz_dirty', ''); // for Firefox
rng.insertNode (br);
rng.insertNode (this._doc.createTextNode('\n'));
rng.collapse (false);
};
W3CRange.prototype._nativeTop = function(rng){
if (this.length == 0) return 0; // no text, no scrolling
if (rng.toString() == ''){
var textnode = this._doc.createTextNode('X');
rng.insertNode (textnode);
}
var startrng = this._nativeRange([0,1]);
var top = rng.getBoundingClientRect().top - startrng.getBoundingClientRect().top;
if (textnode) textnode.parentNode.removeChild(textnode);
return top;
}
W3CRange.prototype._nativeWrap = function(n, rng) {
rng.surroundContents(n);
};

// W3C internals
function nextnode (node, root){
// in-order traversal
// we've already visited node, so get kids then siblings
if (node.firstChild) return node.firstChild;
if (node.nextSibling) return node.nextSibling;
if (node===root) return null;
while (node.parentNode){
// get uncles
node = node.parentNode;
if (node == root) return null;
if (node.nextSibling) return node.nextSibling;
}
return null;
}
function w3cmoveBoundary (rng, n, bStart, el){
// move the boundary (bStart == true ? start : end) n characters forward, up to the end of element el. Forward only!
// if the start is moved after the end, then an exception is raised
if (n <= 0) return;
var node = rng[bStart ? 'startContainer' : 'endContainer'];
if (node.nodeType == 3){
// we may be starting somewhere into the text
n += rng[bStart ? 'startOffset' : 'endOffset'];
}
while (node){
if (node.nodeType == 3){
var length = node.nodeValue.length;
if (n <= length){
rng[bStart ? 'setStart' : 'setEnd'](node, n);
// special case: if we end next to a <br>, include that node.
if (n == length){
// skip past zero-length text nodes
for (var next = nextnode (node, el); next && next.nodeType==3 && next.nodeValue.length == 0; next = nextnode(next, el)){
rng[bStart ? 'setStartAfter' : 'setEndAfter'](next);
}
if (next && next.nodeType == 1 && next.nodeName == "BR") rng[bStart ? 'setStartAfter' : 'setEndAfter'](next);
}
return;
}else{
rng[bStart ? 'setStartAfter' : 'setEndAfter'](node); // skip past this one
n -= length; // and eat these characters
}
}
node = nextnode (node, el);
}
}
var START_TO_START = 0; // from the w3c definitions
var START_TO_END = 1;
var END_TO_END = 2;
var END_TO_START = 3;
// from the Mozilla documentation, for range.compareBoundaryPoints(how, sourceRange)
// -1, 0, or 1, indicating whether the corresponding boundary-point of range is respectively before, equal to, or after the corresponding boundary-point of sourceRange.
// * Range.END_TO_END compares the end boundary-point of sourceRange to the end boundary-point of range.
// * Range.END_TO_START compares the end boundary-point of sourceRange to the start boundary-point of range.
// * Range.START_TO_END compares the start boundary-point of sourceRange to the end boundary-point of range.
// * Range.START_TO_START compares the start boundary-point of sourceRange to the start boundary-point of range.
function w3cstart(rng, constraint){
if (rng.compareBoundaryPoints (START_TO_START, constraint) <= 0) return 0; // at or before the beginning
if (rng.compareBoundaryPoints (END_TO_START, constraint) >= 0) return constraint.toString().length;
rng = rng.cloneRange(); // don't change the original
rng.setEnd (constraint.endContainer, constraint.endOffset); // they now end at the same place
return constraint.toString().length - rng.toString().length;
}
function w3cend (rng, constraint){
if (rng.compareBoundaryPoints (END_TO_END, constraint) >= 0) return constraint.toString().length; // at or after the end
if (rng.compareBoundaryPoints (START_TO_END, constraint) <= 0) return 0;
rng = rng.cloneRange(); // don't change the original
rng.setStart (constraint.startContainer, constraint.startOffset); // they now start at the same place
return rng.toString().length;
}

function NothingRange(){}
NothingRange.prototype = new Range();
NothingRange.prototype._textProp = 'value';
NothingRange.prototype._nativeRange = function(bounds) {
return bounds || [0,this.length];
};
NothingRange.prototype._nativeSelect = function (rng){ // do nothing
};
NothingRange.prototype._nativeSelection = function(){
return [0,0];
};
NothingRange.prototype._nativeGetText = function (rng){
return this._el[this._textProp].substring(rng[0], rng[1]);
};
NothingRange.prototype._nativeSetText = function (text, rng){
var val = this._el[this._textProp];
this._el[this._textProp] = val.substring(0, rng[0]) + text + val.substring(rng[1]);
};
NothingRange.prototype._nativeEOL = function(){
this.text('\n');
};
NothingRange.prototype._nativeTop = function(){
return 0;
};
NothingRange.prototype._nativeWrap = function() {throw new Error("Wrapping not implemented")};


// data for elements, similar to jQuery data, but allows for monitoring with custom events
const monitored = new Set();

function signalMonitor(prop, value, element){
const attr = `data-${prop}`;
element.dispatchEvent(new CustomEvent(attr, {bubbles: true, detail: value}));
try{
element.setAttribute (attr, value); // illegal attribute names will throw. Ignore it
} finally { /* ignore */ }
}

function createDataObject (el){
return el[datakey] = new Proxy(new Data(el), {
set(obj, prop, value) {
obj[prop] = value;
if (monitored.has(prop)) signalMonitor(prop, value, obj.sourceElement);
return true; // in strict mode, 'set' returns a success flag
}
});
}

var Data = function(el) {
Object.defineProperty(this, 'sourceElement', {
value: el
});
}

Data.prototype = {};
// for use with ex options. JSON.stringify(range.data) should return only the options that were
// both defined with bililiteRange.option() *and* actually had a value set on this particular data object.
// JSON.stringify (range.data.all) should return all the options that were defined.
Object.defineProperty(Data.prototype, 'toJSON', {
value: function(){
let ret = {};
for (let key in Data.prototype) if (this.hasOwnProperty(key)) ret[key] = this[key];
return ret;
}
});
Object.defineProperty(Data.prototype, 'all', {
get: function(){
let ret = {};
for (let key in Data.prototype) ret[key] = this[key];
return ret;
}
});
Object.defineProperty(Data.prototype, 'trigger', {
value: function(){
monitored.forEach(prop => signalMonitor (prop, this[prop], this.sourceElement));
}
});

bililiteRange.createOption = function (name, desc = {}){
desc = Object.assign({
enumerable: true, // use these as the defaults
writable: true,
configurable: true
}, Object.getOwnPropertyDescriptor(Data.prototype, name), desc);
if ('monitored' in desc) monitored[desc.monitored ? 'add' : 'delete'](name);
Object.defineProperty(Data.prototype, name, desc);
return Data.prototype[name]; // return the default value
}

})();

'use strict';

(function($){

$.fn.sendkeys = function (x){
return this.each( function(){
bililiteRange(this).bounds('selection').sendkeys(x).select();
this.focus();
});
}; // sendkeys

// add a default handler for keydowns so that we can send keystrokes, even though code-generated events
// are untrusted (http://www.w3.org/TR/DOM-Level-3-Events/#trusted-events)
// documentation of special event handlers is at http://learn.jquery.com/events/event-extensions/
$.event.special.keydown = $.event.special.keydown || {};
$.event.special.keydown._default = function (evt){
if (evt.isTrusted) return false;
if (evt.key == null) return false; // nothing to print. Use the keymap plugin to set this
if (evt.ctrlKey || evt.altKey || evt.metaKey) return false; // only deal with printable characters.
var target = evt.target;
if (target.isContentEditable || target.nodeName == 'INPUT' || target.nodeName == 'TEXTAREA') {
// only insert into editable elements
var key = evt.key;
if (key.length > 1 && key.charAt(0) != '{') key = '{'+key+'}'; // sendkeys notation
$(target).sendkeys(key);
return true;
}
return false;
}
})(jQuery)})();

Back to list