
initDB();

var version = "3.3.1.2";

$(function() {
    Parse.$ = jQuery;	
});
var Promise = window.Promise;
if (!Promise) {
    Promise = JSZip.external.Promise;
}
$.mobile.pageContainer.pagecontainer({ defaults: true });
var _validFileExtensions = [".png",".jpg", ".jpeg"];
var CurrentUser = Parse.User.current();
var userX = Parse.Object.extend("User");
var SelectedUser = new userX();
	SelectedUser = CurrentUser;
var SelectedManager = new userX();
var SelectedLeadRecipient = new userX();
var ReportTargetUser = new userX();
var ListingAuthor = new userX();
var Users = new userX();

var Lead = Parse.Object.extend("Lead");
var LeadNote = Parse.Object.extend("LeadNote");
var UserNote = Parse.Object.extend("UserNote");
var SelectedLead = Parse.Object.extend("Lead");
var SaleNote = Parse.Object.extend("SaleNote");
var SaleNotesArray = [];
var ReportItemArray =[];
var QueryStartDateString ="";
var AssetListing = Parse.Object.extend("AssetListing");
var SelectedAssetListing = Parse.Object.extend("AssetListing");
var SelectedLeadListing = Parse.Object.extend("AssetListing");
var Customer = Parse.Object.extend("Customer");
var Buyer = Parse.Object.extend("Customer");
var Seller = Parse.Object.extend("Customer");
var SelectedCustomerObject = {};
var imgObjects = [];
var imgArray = [];
var viewingUserTable = false;
var stringyIMGs = "";
var listingID ="";
var listingStatus ="";
var vinSearchResultArray = [];
var vinSearchResultObj = {};
var customerArray = [];
var auctionResultsArray = [];
var selectedCompany = {};
var allPendingListings = [];
var selectedAuctionSearchType = "";
var selectedAuctionSearchCategory = "";
var selectedAuctionSearchMake = "";
var selectedSearchType = "*x*";
var newListingIsTitled;
var serialSearchAttempts = 0;
var galleryImageIndex = 0;
var galleryImageCount = 0;
var totalInvValue = 0;
var totalInvCost = 0;

function filterCustomersInDialog(){
    var input, filter, ul, li, a, p, i;
    input = document.getElementById('customer-dialog-filter');
    filter = input.value.toUpperCase();
    ul = document.getElementById("selectcustomer-menu");
    li = ul.getElementsByTagName('li');
    // Loop through all list items, and hide those who don't match the search query
    for (i = 0; i < li.length; i++) {
        a = li[i].getElementsByTagName("a")[0];
        if (a.innerHTML.toUpperCase().indexOf(filter) > -1) {
            li[i].style.display = "";
        } else {
            li[i].style.display = "none";
        }
    }
}
function filterNewListingMakes() {
    var input, filter, ul, li, a, p, i;
    input = document.getElementById('new-listing-make-filter');
    filter = input.value.toUpperCase();
    ul = document.getElementById("new-listing-make-select-dialog-menu");
    li = ul.getElementsByTagName('li');
    // Loop through all list items, and hide those who don't match the search query
    for (i = 0; i < li.length; i++) {
        a = li[i].getElementsByTagName("a")[0];
        if (a.innerHTML.toUpperCase().indexOf(filter) > -1) {
            li[i].style.display = "";
        } else {
            li[i].style.display = "none";
        }
    }
}
function filterNewListingCategories() {
    var input, filter, ul, li, a, p, i;
    input = document.getElementById('new-listing-category-filter');
    filter = input.value.toUpperCase();
    ul = document.getElementById("new-listing-category-select-dialog-menu");
    li = ul.getElementsByTagName('li');
    // Loop through all list items, and hide those who don't match the search query
    for (i = 0; i < li.length; i++) {
        a = li[i].getElementsByTagName("a")[0];
        if (a.innerHTML.toUpperCase().indexOf(filter) > -1) {
            li[i].style.display = "";
        } else {
            li[i].style.display = "none";
        }
    }
}
function filterNewListingYears() {
    var input, filter, ul, li, a, p, i;
    input = document.getElementById('new-listing-year-filter');
    filter = input.value.toUpperCase();
    ul = document.getElementById("new-listing-year-select-dialog-menu");
    li = ul.getElementsByTagName('li');
    // Loop through all list items, and hide those who don't match the search query
    for (i = 0; i < li.length; i++) {
        a = li[i].getElementsByTagName("a")[0];
        if (a.innerHTML.toUpperCase().indexOf(filter) > -1) {
            li[i].style.display = "";
        } else {
            li[i].style.display = "none";
        }
    }
}
function filterAuctionModelYears() {
    var input, filter, ul, li, a, p, i;
    input = document.getElementById('auction-model-year-filter');
    filter = input.value.toUpperCase();
    ul = document.getElementById("auction-model-year-select-dialog-menu");
    li = ul.getElementsByTagName('li');
    // Loop through all list items, and hide those who don't match the search query
    for (i = 0; i < li.length; i++) {
        a = li[i].getElementsByTagName("a")[0];
        if (a.innerHTML.toUpperCase().indexOf(filter) > -1) {
            li[i].style.display = "";
        } else {
            li[i].style.display = "none";
        }
    }
}
/*
$('#auction-comp-base-type-select').change(function() {
	$("#auction-category-select-button").hide();
	$("#auction-make-select-button").hide();
    selectedAuctionSearchType = $(this).find("option:selected").attr('data-equipType');
    //$('#auction-category-select-menu').empty();
	if	(selectedAuctionSearchType == "E"){
		$('#auction-category-select-button span').text('Select a category');
		createUlEleFromArrayOfObjs(auctionEquipCategories,"auction-category-select", function (cats){
			$("#auction-category-select-dialog-menu").replaceWith(cats);
			$("#auction-category-select-button").show();
		});
	}
	if	(selectedAuctionSearchType == "R"){
		$('#auction-category-select-button span').text("Select a category");
		createUlEleFromArrayOfObjs(auctionTrailerCategories,"auction-category-select", function (cats){
			$("#auction-category-select-dialog-menu").replaceWith(cats);
			$("#auction-category-select-button").show();
		});
	}
	if	(selectedAuctionSearchType == "T"){
			$("#auction-category-select-button span").text("Select a category");
		createUlEleFromArrayOfObjs(auctionTruckCategories,"auction-category-select", function (cats){
			$("#auction-category-select-dialog-menu").replaceWith(cats);
			$("#auction-category-select-button").show();
		});
	}
});
*/

$(document).on('tap', "#to-new-listing-serial-btn", function(){
	$("#new-listing-vin-area").show();
});
$(document).on('tap', "#go-to-new-listing-details-btn", function(){
	//$("#go-to-new-listing-details-btn").hide();
	//$(document).find("#new-listing-comp-results-table").hide();
	//$(document).find("#new-listing-auction-comp-results-container").empty();
	//getCompsWithDialogType("new-listing-comp-search");
	var year = $(document).find('#new-listing-year-select-button span').text();
	var equipVIN = $('input[name=equipVIN]').val();
	checkModelYearByVIN(year,equipVIN);
	$("#new-listing-details-area").show();
	$("#new-listing-image-upload-area").show();
});
$(document).on('tap', "#new-listing-date-select-dialog-menu li", function(event){
	event.preventDefault();
	$('#new-listing-year-select-button span').text($(this).text());
	$('#new-listing-year-select-dialog').dialog('close');
	$('#new-listing-category-select-button').show();
});
$(document).on('tap', "#skip-add-new-customer-btn", function(){
	$("#new-listing-primary-data-area").show();
});
/*
$(document).on('tap', "#new-listing-base-type-select-dialog-menu li", function(event){
	event.preventDefault();
	console.log("base clicked");
	$("#new-listing-category-select-button").hide();
	$("#new-listing-make-select-button").hide();
	selectedAuctionSearchType = $(this).attr("data-equipType");
	if	(selectedAuctionSearchType == "E"){
		$('#new-listing-category-select-button span').text('Select a category');
		createUlEleFromArrayOfObjs(auctionV3Categories,"new-listing-category-select", function (cats){
			$("#new-listing-category-select-dialog-menu").replaceWith(cats);
			$("#new-listing-category-select-button").show();
		});
	}
	if	(selectedAuctionSearchType == "R"){
		$('#new-listing-category-select-button span').text("Select a category");
		createUlEleFromArrayOfObjs(auctionV3Categories,"new-listing-category-select", function (cats){
			$("#new-listing-category-select-dialog-menu").replaceWith(cats);
			$("#new-listing-category-select-button").show();
		});
	}
	if	(selectedAuctionSearchType == "T"){
		$("#new-listing-category-select-button span").text("Select a category");
		createUlEleFromArrayOfObjs(auctionV3Categories,"new-listing-category-select", function (cats){
			$("#new-listing-category-select-dialog-menu").replaceWith(cats);
			$("#new-listing-category-select-button").show();
		});
	}
	$('#new-listing-base-type-select-button span').text($(this).text());
	$('#new-listing-base-type-select-dialog').dialog('close');
});
*/
$(document).on('tap', "#new-listing-category-select-dialog-menu li", function(event){
	event.preventDefault();
	selectedAuctionSearchCategory = $(this).text();	
	if (selectedAuctionSearchCategory == "OTHER"){
		$('#new-listing-category-select-button span').text("Select category");
		$("#new-listing-category-input").show();
		$("#new-listing-make-input").show();
		$("#new-listing-model-fieldset").show();
	}else{
		$("#new-listing-category-input").hide();
		$("#new-listing-make-input").hide();
		$("#new-listing-model-fieldset").hide();
		$('#new-listing-category-select-button span').text($(this).text());
		$("#new-listing-make-select-button").show();
	}
	$('#new-listing-category-select-dialog').dialog('close');
});
$(document).on('tap', "#new-listing-category-select-button", function(){
	$("#new-listing-make-select-button").hide();
});

$(document).on('tap', "#new-listing-make-select-dialog-menu li", function(event){
	event.preventDefault();
	selectedAuctionSearchMake = $(this).text();
	if (selectedAuctionSearchMake == "OTHER"){
		$("#new-listing-make-input").show();
		$("#new-listing-model-fieldset").show();
		$('#new-listing-make-select-button span').text("Select make");
		$("#new-listing-model-select-button").hide();
	}else{
		$("#new-listing-make-input").hide();
		$("#new-listing-model-fieldset").hide();
		$('#new-listing-make-select-button span').text($(this).text());
		crawlForAuctionModels("newListing",selectedAuctionSearchCategory,selectedAuctionSearchMake);
		$('#new-listing-model-select-button span').text("Select model");
	}
    $('#new-listing-make-select-dialog').dialog('close');
    
});
$(document).on('tap', "#new-listing-model-select-dialog-menu li", function(event){
	event.preventDefault();
	selectedAuctionSearchModel = $(this).text();
	if (selectedAuctionSearchModel == "OTHER"){
		$("#new-listing-model-fieldset").show();
		$('#new-listing-model-select-button span').text("Select model");
		$('#new-listing-model-select-dialog').dialog('close');
	}else{
		$('#new-listing-model-select-button span').text($(this).text());
		$('#new-listing-model-select-dialog').dialog('close');
		$('#new-listing-vin-area').show();
		runV3Comps("newListing");
	}
});
$(document).on('tap', "#new-listing-make-select-button", function(){
	console.log("open make select");
});
$(document).on('tap', "#user-options-btn", function(){
	updateUserSelectDropdown();
	$.mobile.changePage("#user-display-select-dialog", {transition: 'pop', role: 'dialog'});
});
$(document).on('tap', '#user-display-select-dialog-menu li', function(event){
	event.preventDefault();
	var attributeID = $(this).data("id");
    var userQuery;
		userQuery = new Parse.Query(Users);
		userQuery.equalTo("objectId", attributeID);
		userQuery.include("user");
		userQuery.first({
			useMasterKey:true,
			success: function(rep){
				SelectedUser = rep;
				var first = rep.get("firstName");
				var last = rep.get("lastName");
				loadUserProfile();
				$("#user-listings").empty();
				$("#list-title").text("");
				$('#user-options-btn').text(first+" "+last);
				$('#user-display-select-button').text(first+" "+last);
				$('#user-item-display-select-button').text("Select items to display");
				$('#user-display-select-dialog').dialog('close');
				$("#user-options-dialog").dialog('close');
			}, error: function(error){
				console.log("Query error:"+error.message);	
			}
		});
});
$(document).on('tap', '#new-user-manager-select-dialog-menu li', function(event){
	event.preventDefault();
	var attributeID = $(this).data("id");
    var userQuery;
		userQuery = new Parse.Query(Users);
		userQuery.equalTo("objectId", attributeID);
		userQuery.include("user");
		userQuery.first({
		success: function(rep){
			SelectedManager = rep;
			var first = rep.get("firstName");
			var last = rep.get("lastName");
			$('#new-user-manager-select-button').text("Manager:"+first+" "+last);
			$('#new-user-manager-select-dialog').dialog('close');
		}, error: function(error){
			console.log("Query error:"+error.message);	
		}
	});
});

$(document).on('tap', "#confirm-send-user-contract-confirmed-btn", function(event){
	event.preventDefault();
	$(".dialog-view-area").LoadingOverlay("show");
	sendRepContract(SelectedUser);
});
$(document).on('tap', "#confirm-send-user-contract-cancel-btn", function(event){
	$('#confirm-send-user-contract-dialog').dialog('close');
});

$(document).on('tap', '#edit-user-manager-select-dialog-menu li', function(event){
	event.preventDefault();
	var attributeID = $(this).data("id");
    var userQuery;
		userQuery = new Parse.Query(Users);
		userQuery.equalTo("objectId", attributeID);
		userQuery.include("user");
		userQuery.first({
		success: function(manager){
			console.log("manager changed");
			sessionStorage.setItem('changingManager',"true");
			SelectedManager = manager;
			var first = manager.get("firstName");
			var last = manager.get("lastName");
			console.log("you selected "+first+" "+last);
			$('#edit-user-manager-select-button span').text("Manager:"+first+" "+last);
			$('#edit-user-manager-select-dialog').dialog('close');
		}, error: function(error){
			console.log("Query error:"+error.message);	
		}
	});
});
$(document).on('tap', "#go-to-you-btn", function(event){
	event.preventDefault();
	$("#go-to-you-btn").hide();
	$("#user-options-btn-area").hide();
	$("#user-settings-button").show();
	$("#new-listing-btn").show();
	SelectedUser = CurrentUser;
	loadUserProfile();
});
$(document).on('tap', "#user-item-display-select-button", function(event){
	event.preventDefault();
	updateDisplaySelectDropdown()
	$.mobile.changePage("#user-item-display-select-dialog", {transition: 'pop', role: 'dialog'});
});

$(document).on('tap', '#user-item-display-select-dialog-menu li', function(event){
	event.preventDefault();
	var t = $(this).text();
	var i = $(this).attr("data-option-index");
	$("#user-listings").empty();
	$("#list-title").text("");
	$('#user-item-display-select-button').text(t);
	if (i=="0"){
		console.log("nothing selected");
	}
	if (i=="1"){
		getLeadsForUser(SelectedUser);
	}
	if (i=="2"){
		getListingsForUserWithStatus(SelectedUser,"Active");
	}
	if (i=="3"){
		getListingsForUserWithStatus(SelectedUser,"Pending");
	}
	if (i=="4"){
		getListingsForUserWithStatus(SelectedUser,"Rejected");
	}
	if (i=="5"){
		getListingsForUserWithStatus(SelectedUser,"Removed");
	}
	if (i=="6"){
		getListingsForUserWithStatus(SelectedUser,"Sale-Pending");
	}
	if (i=="7"){
		getListingsForUserWithStatus(SelectedUser,"Sold");
	}
	if (i=="8"){
		getCustomersForUser(SelectedUser);
	}
	if (i=="9"){
		getTeamByManager(SelectedUser);
	}
	if (i=="10"){
		getTeamLeadsForManager();
	}
	if (i=="11"){
		getTeamListingsForManagerByStatus("Active");
	}
	if (i=="12"){
		getTeamListingsForManagerByStatus("Pending");
	}
	if (i=="13"){
		getTeamListingsForManagerByStatus("Rejected");
	}
	if (i=="14"){
		getTeamListingsForManagerByStatus("Sale-Pending");
	}
	if (i=="15"){
		getTeamListingsForManagerByStatus("Sold");
	}
	if (i=="16"){
		getAllPendingListings();
	}
	if (i=="17"){
		getAllRejectedListings();
	}
	if (i=="18"){
		getAllRemovedListings();
	}
	if (i=="19"){
		getAllPendingSaleListings();
	}
	if (i=="20"){
		getAllSoldUnits();
	}
	if (i=="21"){
		viewAllLeads();
	}
	if (i=="22"){
		viewAllCustomers();
	}
	if (i=="23"){
		viewAllPendingReps();
	}
	if (i=="24"){
		viewAllSuspendedReps();
	}
	$('#user-item-display-select-dialog').dialog('close');

});

const _MapAbbrFullName = {"AZ":"Arizona","AL":"Alabama","AK":"Alaska","AR":"Arkansas","CA":"California","CO":"Colorado","CT":"Connecticut","DC":"District of Columbia","DE":"Delaware","FL":"Florida","GA":"Georgia","HI":"Hawaii","ID":"Idaho","IL":"Illinois","IN":"Indiana","IA":"Iowa","KS":"Kansas","KY":"Kentucky","LA":"Louisiana","ME":"Maine","MD":"Maryland","MA":"Massachusetts","MI":"Michigan","MN":"Minnesota","MS":"Mississippi","MO":"Missouri","MT":"Montana","NE":"Nebraska","NV":"Nevada","NH":"New Hampshire","NJ":"New Jersey","NM":"New Mexico","NY":"New York","NC":"North Carolina","ND":"North Dakota","OH":"Ohio","OK":"Oklahoma","OR":"Oregon","PA":"Pennsylvania","RI":"Rhode Island","SC":"South Carolina","SD":"South Dakota","TN":"Tennessee","TX":"Texas","UT":"Utah","VT":"Vermont","VA":"Virginia","WA":"Washington","WV":"West Virginia","WI":"Wisconsin","WY":"Wyoming","AB":"Alberta","BC":"British Columbia","MB":"Manitoba","NB":"New Brunswick","NF":"Newfoundland","NT":"Northwest Territory","NS":"Nova Scotia","NU":"Nunavut","ON":"Ontario","PE":"Prince Edward Island","QC":"Quebec","SK":"Saskatchewan","YT":"Yukon"};

const _MapFullNameAbbr = {"arizona":"AZ","alabama":"AL","alaska":"AK","arkansas":"AR","california":"CA","colorado":"CO","connecticut":"CT","districtofcolumbia":"DC","delaware":"DE","florida":"FL","georgia":"GA","hawaii":"HI","idaho":"ID","illinois":"IL","indiana":"IN","iowa":"IA","kansas":"KS","kentucky":"KY","louisiana":"LA","maine":"ME","maryland":"MD","massachusetts":"MA","michigan":"MI","minnesota":"MN","mississippi":"MS","missouri":"MO","montana":"MT","nebraska":"NE","nevada":"NV","newhampshire":"NH","newjersey":"NJ","newmexico":"NM","newyork":"NY","northcarolina":"NC","northdakota":"ND","ohio":"OH","oklahoma":"OK","oregon":"OR","pennsylvania":"PA","rhodeisland":"RI","southcarolina":"SC","southdakota":"SD","tennessee":"TN","texas":"TX","utah":"UT","vermont":"VT","virginia":"VA","washington":"WA","westvirginia":"WV","wisconsin":"WI","wyoming":"WY","alberta":"AB","britishcolumbia":"BC","manitoba":"MB","newbrunswick":"NB","newfoundland":"NF","northwestterritory":"NT","novascotia":"NS","nunavut":"NU","ontario":"ON","princeedwardisland":"PE","quebec":"QC","saskatchewan":"SK","yukon":"YT"}

function convertStateToAbbr(input) {
	if(input === undefined) return input;
	var strInput = input.trim();
	if(strInput.length === 2) {
		// already abbr, check if it's valid
		var upStrInput = strInput.toUpperCase();
		return _MapAbbrFullName[upStrInput]?upStrInput :undefined;
	}
	var strStateToFind = strInput.toLowerCase().replace(/\ /g, '');
	var foundAbbr = _MapFullNameAbbr[strStateToFind];
	return foundAbbr;
}

function convertStateToFullName(input) {
  if(input === undefined) return input;
  var strInput = input.trim();
  if(strInput.length !== 2) {
    // already full name, return formatted fullname
    return _MapAbbrFullName[convertStateToAbbr(strInput)];
  }
  var strStateToFind = strInput.toLowerCase().replace(/\ /g, '');
  var foundFullName = _MapAbbrFullName[strStateToFind];
  return foundFullName ;
}
function updateUserSelectDropdown(){
	console.log("update user dropdown");
	var output = "";
	var xOutput = "";
	var ut = "";
	var stringy = (JSON.stringify(CurrentUser.attributes));
	var u = JSON.parse(stringy);
	$("#user-item-display-select-button").text("Select items to display");
	if (u.userType == "Admin" || u.userType == "Super-Admin" || u.userType == "Developer"){
		getAllUsers(function(members){
			output += "<div class=\"ui-select\">";
			output += "<select name=\"user-display-select\" id=\"user-display-select\" data-native-menu=\"false\" tabindex=\"-1\">";
			output += "<option value=\"0\">Select another user</option>";
			xOutput += "<li data-option-index=\"0\" data-icon=\"false\" data-id=\"none\" class role=\"option\" aria-selected=\"false\">";
			xOutput += "<a href=\"#\" tabindex=\"-1\" class=\"ui-btn\">Select another user</a></li>";
			for (var i = 0; i < members.length; i++) {
				var stringy = JSON.stringify(members[i]);
				var memberObj = JSON.parse(stringy);
				var manager = memberObj.assignedManager;
				var start = members[i].get("signOnDate");
				if (start){
					start = formatDateNoTime(start);
				}
				if(!manager){
					output += "<option value=\"1\">"+memberObj.firstName+" "+memberObj.lastName+"</option>";
					xOutput += "<li data-option-index=\""+i+"\" data-icon=\"false\" data-id="+memberObj.objectId+" objType=\"user\" class role=\"option\" aria-selected=\"false\">";
					xOutput += "<a href=\"#\" tabindex=\"-1\" class=\"ui-btn\">"+memberObj.firstName+" "+memberObj.lastName+" </br><small>"+memberObj.city+", "+memberObj.state+"</small>";
					if (start){
						xOutput += "</br><small>Start Date:"+start+"</small></a></li>";
					}else{
						xOutput += "</a></li>";
					}					
				}else{
					output += "<option value=\"1\">"+memberObj.firstName+" "+memberObj.lastName+"</option>";
					xOutput += "<li data-option-index=\""+i+"\" data-icon=\"false\" data-id="+memberObj.objectId+" objType=\"user\" class role=\"option\" aria-selected=\"false\">";
					xOutput += "<a href=\"#\" tabindex=\"-1\" class=\"ui-btn\">"+memberObj.firstName+" "+memberObj.lastName+" </br><small>"+memberObj.city+", "+memberObj.state+"</small></br><small>Manager:"+manager.firstName+" "+manager.lastName+"</small>";
					if (start){
						xOutput += "</br><small>Start Date:"+start+"</small></a></li>";
					}else{
						xOutput += "</a></li>";
					}
				}
			}	
			output += "</select>";
			output += "<div style=\"display:none;\" id=\"user-display-select-listbox-placeholder\"><!---Placeholder---></div>";
			output += "</div>";
			$("#user-display-select").html(output);
			$("#user-display-select-area").show();	
			$("#user-display-select-dialog-menu").html(xOutput);		
		});
	}
	if (u.userType == "Manager"){
		getTeamByManager(SelectedUser, function(members){
			output += "<div class=\"ui-select\">";
			output += "<select name=\"user-display-select\" id=\"user-display-select\" data-native-menu=\"false\" tabindex=\"-1\">";
			output += "<option value=\"0\">Select another user</option>";
			xOutput += "<li data-option-index=\"0\" data-icon=\"false\" data-id=\"none\" class role=\"option\" aria-selected=\"false\">";
			xOutput += "<a href=\"#\" tabindex=\"-1\" class=\"ui-btn\">Select another user</a></li>";

			for (var i = 0; i < members.length; i++) {
				var stringy = JSON.stringify(members[i]);
				var memberObj = JSON.parse(stringy);
				var start = members[i].get("signOnDate");
				if (start){
					start = formatDateNoTime(start);
				}
				output += "<option value=\"1\">"+memberObj.firstName+" "+memberObj.lastName+"</option>";
				xOutput += "<li data-option-index=\""+i+"\" data-icon=\"false\" data-id="+memberObj.objectId+" objType=\"user\" class role=\"option\" aria-selected=\"false\">";
				xOutput += "<a href=\"#\" tabindex=\"-1\" class=\"ui-btn\">"+memberObj.firstName+" "+memberObj.lastName+"</small>";
				if (start){
					xOutput += "</br><small>Start Date:"+start+"</small></a></li>";
				}else{
					xOutput += "</a></li>";
				}
			}			
			output += "</select>";
			output += "<div style=\"display:none;\" id=\"user-display-select-listbox-placeholder\"><!---Placeholder---></div>";
			output += "</div>";
			$("#user-display-select").html(output);
			$("#user-display-select-area").show();	
			$("#user-display-select-dialog-menu").html(xOutput);
		});
	}					
}
function updateDisplaySelectDropdown(){
	var output = "";
	var xOutput = "";
	$("#user-item-display-select").empty();
	$("#user-item-display-select-dialog-menu").empty();
	var stringy = (JSON.stringify(CurrentUser.attributes));
	var cu = JSON.parse(stringy);
	var str = (JSON.stringify(SelectedUser.attributes));
	var su = JSON.parse(str);
	var first = su.firstName;
	var lastChar = first[first.length -1].toUpperCase();
	if (lastChar =="S"){
		first += "'";
	}else{
		first += "'s";
	}
	
	if (SelectedUser.toJSON().objectId == CurrentUser.toJSON().objectId){
		first = "Your";
	}
	output += "<div class=\"ui-select\">";
	output += "<select name=\"user-item-display-select\" id=\"user-item-display-select\" data-native-menu=\"false\" tabindex=\"-1\">";
	//output += "<option value=\"0\">Select items to display</option>";
	////REP OPTIONS////
	output += "<option value=\"1\">"+first+" leads</option>";
	output += "<option value=\"2\">"+first+" active listings</option>";
	output += "<option value=\"3\">"+first+" pending listings</option>";
	output += "<option value=\"4\">"+first+" rejected listings</option>";
	output += "<option value=\"5\">"+first+" removed listings</option>";
	output += "<option value=\"6\">"+first+" pending sales</option>";
	output += "<option value=\"7\">"+first+" sold units</option>";
	output += "<option value=\"8\">"+first+" customers</option>";

	xOutput += "<li data-option-index=\"1\" data-icon=\"false\" data-id=\"none\" objType=\"lead\" status=\"Active\" class role=\"option\" aria-selected=\"false\">";
	xOutput += "<a href=\"#\" tabindex=\"-1\" class=\"ui-btn\">"+first+" leads</a></li>";
	xOutput += "<li data-option-index=\"2\" data-icon=\"false\" data-id=\"none\" objType=\"listing\" status=\"Active\" class role=\"option\" aria-selected=\"false\">";
	xOutput += "<a href=\"#\" tabindex=\"-1\" class=\"ui-btn\">"+first+" active listings</a></li>";
	xOutput += "<li data-option-index=\"3\" data-icon=\"false\" data-id=\"none\" objType=\"listing\" status=\"Pending\" class role=\"option\" aria-selected=\"false\">";
	xOutput += "<a href=\"#\" tabindex=\"-1\" class=\"ui-btn\">"+first+" pending listings</a></li>";
	xOutput += "<li data-option-index=\"4\" data-icon=\"false\" data-id=\"none\" objType=\"listing\" status=\"Rejected\" class role=\"option\" aria-selected=\"false\">";
	xOutput += "<a href=\"#\" tabindex=\"-1\" class=\"ui-btn\">"+first+" rejected listings</a></li>";
	xOutput += "<li data-option-index=\"5\" data-icon=\"false\" data-id=\"none\" objType=\"listing\" status=\"Removed\" class role=\"option\" aria-selected=\"false\">";
	xOutput += "<a href=\"#\" tabindex=\"-1\" class=\"ui-btn\">"+first+" removed listings</a></li>";
	xOutput += "<li data-option-index=\"6\" data-icon=\"false\" data-id=\"none\" objType=\"listing\" status=\"Sale-Pending\" class role=\"option\" aria-selected=\"false\">";
	xOutput += "<a href=\"#\" tabindex=\"-1\" class=\"ui-btn\">"+first+" pending sales</a></li>";
	xOutput += "<li data-option-index=\"7\" data-icon=\"false\" data-id=\"none\" objType=\"listing\" status=\"Sold\" class role=\"option\" aria-selected=\"false\">";
	xOutput += "<a href=\"#\" tabindex=\"-1\" class=\"ui-btn\">"+first+" sold units</a></li>";
	xOutput += "<li data-option-index=\"8\" data-icon=\"false\" data-id=\"none\" objType=\"customer\" status=\"none\" class role=\"option\" aria-selected=\"false\">";
	xOutput += "<a href=\"#\" tabindex=\"-1\" class=\"ui-btn\">"+first+" customers</a></li>";

	////MANAGER OPTIONS////
	if (su.userType == "Manager" || su.userType == "Admin" || su.userType == "Super-Admin" || su.userType == "Developer"){
		output += "<option value=\"9\">"+first+" team</option>";
		output += "<option value=\"10\">"+first+" team's leads</option>";
		output += "<option value=\"11\">"+first+" team's active listings</option>";
		output += "<option value=\"12\">"+first+" team's pending listings</option>";
		output += "<option value=\"13\">"+first+" team's rejected listings</option>";
		output += "<option value=\"14\">"+first+" team's pending sales</option>";
		output += "<option value=\"15\">"+first+" team's completed sales</option>";

		xOutput += "<li data-option-index=\"9\" data-icon=\"false\" data-id=\"none\" objType=\"user\" status=\"none\" class role=\"option\" aria-selected=\"false\">";
		xOutput += "<a href=\"#\" tabindex=\"-1\" class=\"ui-btn\" style=\"background-color:#2FFC2F;\">"+first+" team</a></li>";
		xOutput += "<li data-option-index=\"10\" data-icon=\"false\" data-id=\"none\" objType=\"lead\" status=\"none\" class role=\"option\" aria-selected=\"false\">";
		xOutput += "<a href=\"#\" tabindex=\"-1\" class=\"ui-btn\" style=\"background-color:#2FFC2F;\">"+first+" team's leads</a></li>";
		xOutput += "<li data-option-index=\"11\" data-icon=\"false\" data-id=\"none\" objType=\"listing\" status=\"Active\"  class role=\"option\" aria-selected=\"false\">";
		xOutput += "<a href=\"#\" tabindex=\"-1\" class=\"ui-btn\" style=\"background-color:#2FFC2F;\">"+first+" team's active listings</a></li>";
		xOutput += "<li data-option-index=\"12\" data-icon=\"false\" data-id=\"none\" objType=\"listing\" status=\"Pending\"  class role=\"option\" aria-selected=\"false\">";
		xOutput += "<a href=\"#\" tabindex=\"-1\" class=\"ui-btn\" style=\"background-color:#2FFC2F;\">"+first+" team's pending listings</a></li>";
		xOutput += "<li data-option-index=\"13\" data-icon=\"false\" data-id=\"none\" objType=\"listing\" status=\"Rejected\" class role=\"option\" aria-selected=\"false\">";
		xOutput += "<a href=\"#\" tabindex=\"-1\" class=\"ui-btn\" style=\"background-color:#2FFC2F;\">"+first+" team's rejected listings</a></li>";
		xOutput += "<li data-option-index=\"14\" data-icon=\"false\" data-id=\"none\" objType=\"listing\" status=\"Pending\" class role=\"option\" aria-selected=\"false\">";
		xOutput += "<a href=\"#\" tabindex=\"-1\" class=\"ui-btn\" style=\"background-color:#2FFC2F;\">"+first+" team's pending sales</a></li>";
		xOutput += "<li data-option-index=\"15\" data-icon=\"false\" data-id=\"none\" objType=\"listing\" status=\"Sold\" class role=\"option\" aria-selected=\"false\">";
		xOutput += "<a href=\"#\" tabindex=\"-1\" class=\"ui-btn\" style=\"background-color:#2FFC2F;\">"+first+" team's completed sales</a></li>";
	}
	////ADMIN OPTIONS////
	if (cu.userType == "Admin" || cu.userType == "Super-Admin" || cu.userType == "Developer"){
		output += "<option value=\"16\">All pending listings</option>";
		output += "<option value=\"17\">All rejected listings</option>";
		output += "<option value=\"18\">All removed listings</option>";
		output += "<option value=\"19\">All pending sales</option>";
		output += "<option value=\"20\">All sold units</option>";
		output += "<option value=\"21\">All leads</option>";
		output += "<option value=\"22\">All customers</option>";
		output += "<option value=\"23\">All pending reps</option>";
		output += "<option value=\"23\">All suspended reps</option>";

		xOutput += "<li data-option-index=\"16\" data-icon=\"false\" data-id=\"none\" objType=\"listing\" status=\"Pending\" class role=\"option\" aria-selected=\"false\">";
		xOutput += "<a href=\"#\" tabindex=\"-1\" class=\"ui-btn\" style=\"background-color:#F35755;\">All pending listings</a></li>";
		xOutput += "<li data-option-index=\"17\" data-icon=\"false\" data-id=\"none\" objType=\"listing\" status=\"Rejected\" class role=\"option\" aria-selected=\"false\">";
		xOutput += "<a href=\"#\" tabindex=\"-1\" class=\"ui-btn\" style=\"background-color:#F35755;\">All rejected listings</a></li>";
		xOutput += "<li data-option-index=\"18\" data-icon=\"false\" data-id=\"none\" objType=\"listing\" status=\"Removed\" class role=\"option\" aria-selected=\"false\">";
		xOutput += "<a href=\"#\" tabindex=\"-1\" class=\"ui-btn\" style=\"background-color:#F35755;\">All removed listings</a></li>";		
		xOutput += "<li data-option-index=\"19\" data-icon=\"false\" data-id=\"none\" objType=\"listing\" status=\"Removed\" class role=\"option\" aria-selected=\"false\">";
		xOutput += "<a href=\"#\" tabindex=\"-1\" class=\"ui-btn\" style=\"background-color:#F35755;\">All pending sales</a></li>";
		xOutput += "<li data-option-index=\"20\" data-icon=\"false\" data-id=\"none\" objType=\"listing\" status=\"Removed\" class role=\"option\" aria-selected=\"false\">";
		xOutput += "<a href=\"#\" tabindex=\"-1\" class=\"ui-btn\" style=\"background-color:#F35755;\">All sold units</a></li>";
		xOutput += "<li data-option-index=\"21\" data-icon=\"false\" data-id=\"none\" objType=\"lead\" status=\"none\" class role=\"option\" aria-selected=\"false\">";
		xOutput += "<a href=\"#\" tabindex=\"-1\" class=\"ui-btn\" style=\"background-color:#F35755;\">All leads</a></li>";
		xOutput += "<li data-option-index=\"22\" data-icon=\"false\" data-id=\"none\" objType=\"customer\" status=\"none\" class role=\"option\" aria-selected=\"false\">";
		xOutput += "<a href=\"#\" tabindex=\"-1\" class=\"ui-btn\" style=\"background-color:#F35755;\">All customers</a></li>";
		xOutput += "<li data-option-index=\"23\" data-icon=\"false\" data-id=\"none\" objType=\"user\" status=\"none\" class role=\"option\" aria-selected=\"false\">";
		xOutput += "<a href=\"#\" tabindex=\"-1\" class=\"ui-btn\" style=\"background-color:#F35755;\">All pending reps</a></li>";
		xOutput += "<li data-option-index=\"24\" data-icon=\"false\" data-id=\"none\" objType=\"user\" status=\"none\" class role=\"option\" aria-selected=\"false\">";
		xOutput += "<a href=\"#\" tabindex=\"-1\" class=\"ui-btn\" style=\"background-color:#F35755;\">All suspended reps</a></li>";
	}
	
	output += "</select>";
	output += "<div style=\"display:none;\" id=\"user-item-display-select-listbox-placeholder\"><!---Placeholder---></div>";
	output += "</div>";
	$("#user-item-display-select").html(output);	
	$("#user-item-display-select-dialog-menu").html(xOutput);
}
function addEmailAddress(firstname,lastname,email){
	var u = JSON.stringify(SelectedUser.attributes);
		u = JSON.parse(u);
	var crawlerRequest = new XMLHttpRequest();
		crawlerRequest.open('POST', 'https://api.apify.com/v2/acts/luke~proxy-email-creator/runs?token=BY4CBwXwXxgPc5YmQcrWjJbwS');
		crawlerRequest.setRequestHeader('Content-Type', 'application/json');
		crawlerRequest.onreadystatechange = function () {
		if (this.readyState === 4) {
			alert("Email set up successfully.");
			sendEmailNotification("Your proxyequipment.com Email", u.personalEmail, "Dear "+firstname+",\nYour new email account has been created. Please use the following info to login.\nLogin: "+u.username+"\nPassword: "+firstname+"2020\n***THIS INFO IS CASE SENSITIVE.***\nYour email can be reached from the backend of our site or directly at webmail.proxyequipment.com.\nHave a great day!", function(){
				alert("Email instructions sent!");
			});
		}
	}
	var body = {
  		"userFirstName": firstname,
		"userLastName": lastname,
	  	"userEmail": email
	};
	crawlerRequest.send(JSON.stringify(body));        
}

function returnVersion(){
	var output = "";
		output += "<p class=\"centered-version-label\">V"+version+"";
	var titleOutput = "Proxy Control Panel V"+version;
	$("#main-js").attr("src", "main.js?v="+version);
	$("#proxy-comps-js").attr("src", "/WebApp/js/proxy-comps.js?v="+version);
	$("#proxy-comps-v2-js").attr("src", "/WebApp/js/proxy-compsv2.js?v="+version);
	$("#proxy-charts-js").attr("src", "/WebApp/js/proxy-charts.js?v="+version);
	$("#proxy-serial-search-v2-js").attr("src", "/WebApp/js/proxy-serial-search-v2.js?v="+version);
	$("#proxy-docs-js").attr("src", "/WebApp/js/proxy-docs.js?v="+version);
	$("#jujudates-js").attr("src", "/WebApp/js/jujudates.js?v="+version);
	$(".centered-version-label").html(output);
	$("#page-title").text(titleOutput);
}

function isArray (value) {
	return value && typeof value === 'object' && value.constructor === Array;
}

const arrayToObject = (array) =>
   array.reduce((obj, item) => {
     obj[item.id] = item
     return obj
   }, {})
   
function alpha_numeric_filter(string){
  const alpha_numeric = Array.from('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' + ' ')
  const json_string = JSON.stringify(string)
  let filterd_string = ''
  for (let i = 0; i < json_string.length; i++) {
    let char = json_string[i]
    let index = alpha_numeric.indexOf(char)
    if (index > -1) {
      filterd_string += alpha_numeric[index]
    }
  }
  return filterd_string
}

function compareObjects(a, b) {
    // Create arrays of property names
    console.log("a = "+JSON.stringify(a));
    console.log("b = "+JSON.stringify(b));
    if (JSON.stringify(a)===JSON.stringify(b)){
    	return true;
    }else{
    	return false;
    }
}
function addDashesToPhoneNumber(f){
    f_val = f.value.replace(/\D[^\.]/g, "");
    f.value = f_val.slice(0,3)+"-"+f_val.slice(3,6)+"-"+f_val.slice(6);
    return f;
}
function createImage(src, name) {
  	var img   = new Image();
 	img.src   = src;
  	img.alt   = name;
  	img.title = name;
  	return img; 
}
function addImageToArray(url) {
	alert(JSON.stringify(url));
	imgArray.push(JSON.stringify(url));
}
function getImageName() {
	var fullPath = document.getElementById('upload-file').value;
		if (fullPath) {
    	var startIndex = (fullPath.indexOf('\\') >= 0 ? fullPath.lastIndexOf('\\') : fullPath.lastIndexOf('/'));
    	var filename = fullPath.substring(startIndex);
    	if (filename.indexOf('\\') === 0 || filename.indexOf('/') === 0) {
        filename = filename.substring(1);
    	}
    return (filename);
	}
}
function getBase64Image(img) {
 	var canvas = document.createElement("canvas");
		canvas.width = img.width;
		canvas.height = img.height;
		var ctx = canvas.getContext("2d");
		ctx.drawImage(img, 0, 0);
 	var dataURL = canvas.toDataURL("image/png");
		return dataURL.replace(/^data:image\/(png|jpeg|jpg);base64,/, "");
}
function getBase64ImageNewWay(imgUrl, callback) {
    var img = new Image();
    // onload fires when the image is fully loadded, and has width and height
    img.onload = function(){
      var canvas = document.createElement("canvas");
      canvas.width = img.width;
      canvas.height = img.height;
      var ctx = canvas.getContext("2d");
      ctx.drawImage(img, 0, 0);
      var dataURL = canvas.toDataURL("image/png"),
          dataURL = dataURL.replace(/^data:image\/(png|jpeg|jpg);base64,/, "");
      callback(dataURL); // the base64 string
    };
    // set attributes and src 
    img.setAttribute('crossOrigin', 'anonymous'); //
    img.src = imgUrl;
}
Base64 = {
     _keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
    encodeBinary: function (input) {
        var output = "";
        var bytebuffer;
        var encodedCharIndexes = new Array(4);
        var inx = 0;
        var paddingBytes = 0;
        while (inx < input.length) {
            // Fill byte buffer array
            bytebuffer = new Array(3);
            for (jnx = 0; jnx < bytebuffer.length; jnx++)
                if (inx < input.length)
                    bytebuffer[jnx] = input.charCodeAt(inx++) & 0xff; // throw away high-order byte, as documented at: https://developer.mozilla.org/En/Using_XMLHttpRequest#Handling_binary_data
                else
                    bytebuffer[jnx] = 0;
            // Get each encoded character, 6 bits at a time
            // index 1: first 6 bits
            encodedCharIndexes[0] = bytebuffer[0] >> 2;
            // index 2: second 6 bits (2 least significant bits from input byte 1 + 4 most significant bits from byte 2)
            encodedCharIndexes[1] = ((bytebuffer[0] & 0x3) << 4) | (bytebuffer[1] >> 4);
            // index 3: third 6 bits (4 least significant bits from input byte 2 + 2 most significant bits from byte 3)
            encodedCharIndexes[2] = ((bytebuffer[1] & 0x0f) << 2) | (bytebuffer[2] >> 6);
            // index 3: forth 6 bits (6 least significant bits from input byte 3)
            encodedCharIndexes[3] = bytebuffer[2] & 0x3f;

            // Determine whether padding happened, and adjust accordingly
            paddingBytes = inx - (input.length - 1);
            switch (paddingBytes) {
                case 2:
                    // Set last 2 characters to padding char
                    encodedCharIndexes[3] = 64;
                    encodedCharIndexes[2] = 64;
                    break;
                case 1:
                    // Set last character to padding char
                    encodedCharIndexes[3] = 64;
                    break;
                default:
                    break; // No padding - proceed
            }
            // Now we will grab each appropriate character out of our keystring
            // based on our index array and append it to the output string
            for (jnx = 0; jnx < encodedCharIndexes.length; jnx++)
                output += this._keyStr.charAt(encodedCharIndexes[jnx]);
        }
        return output;
    }
}
function downloadAllImages(dirName, imgs, limit, ext) {
    resetMessage();
    var zip = new JSZip();
	var imgDir = zip.folder(dirName);
	var stringy = JSON.stringify(SelectedAssetListing.attributes);
	var listing = JSON.parse(stringy);
	var author = (JSON.stringify(ListingAuthor.attributes));
		author= JSON.parse(author);
	var type = listing.equipType;
	var year = listing.equipYear;
	var make = listing.equipMake;
	var model = listing.equipModel;
	var description = listing.equipDescription;
	var hours = listing.equipHours;
	var mileage = listing.equipMileage;
	var vin = listing.equipVIN;
	var serial = listing.equipSerial;
	var location = listing.equipLocation;
	var price = listing.equipPrice;
		price = numberToDollars(price);
	var ownerStockNumber = listing.assetOwnerStockNumber;
	var salesmanFirstName = author.firstName;				 		
	var salesmanLstName = author.lastName;
	var salesmanPhone = author.phone;
	var salesmanEmail = author.username;
	var assetOutput = "";
	assetOutput += "Asset type: "+type+'\r\n';
	assetOutput += "Asset year: "+year+'\r\n';
	assetOutput += "Asset make: "+make+'\r\n';
	assetOutput += "Asset model: "+model+'\r\n';
	assetOutput += "Asset hours: "+hours+'\r\n';
	assetOutput += "Asset mileage: "+mileage+'\r\n';
	assetOutput += "Asset serial: "+serial+'\r\n';
	assetOutput += "Asset VIN: "+vin+'\r\n';
	assetOutput += "Asset location: "+location+'\r\n';
	assetOutput += "Asset price: "+price+'\r\n';
	assetOutput += "Asset stock number: "+ownerStockNumber+'\r\n';
	assetOutput += "Asset description: "+description+'\r\n';
	assetOutput += "Sales Rep: "+salesmanFirstName+" "+salesmanLstName+'\r\n';
	assetOutput += "Phone: "+salesmanPhone+'\r\n';
	imgDir.file("Listing-Details.txt", assetOutput);
    //If specified, filter images by extension 
	if (ext) {
        ext = "." + ext;
        imgs = [].slice.call(imgs).filter(function(img) {
            var src = img.src;
            return (src && (src.indexOf(ext, src.length - ext.length) !== -1));
        });
    }
	/* Determine the number of images to download */
    limit = (limit && (0 <= limit) && (limit <= imgs.length))
            ? limit : imgs.length;
	console.log("Number of images to download = "+limit);
	var baseArray = [];
	const getIt = async (callback) => {	
    	/* (Try to) download the images */
	   	for (var i = 0; i < limit; i++) {
	    	var filename = "image_"+i+".jpg";
			console.log("filename = "+filename);
	        var img = imgs[i];
			var myImage = new Image();
				myImage.src = img.src;
			if (!myImage.src.includes("proxyequipment.com")){
				console.log("not new");
				const proxyurl = "https://cors-anywhere.herokuapp.com/";
				const url = img.src; // site that doesn’t send Access-Control-*
				const request = new Request(proxyurl + url, { headers: new Headers({'Mime-Type': 'text\/plain; charset=x-user-defined'})})
				const response = await fetch(request); 
				const contents = await response.text();
				getBase64ImageNewWay(request.url, function (base64){
					var file = imgDir.file(filename,base64,{base64: true});
					if (file && i == limit){
						zip.generateAsync({type:"blob"})
					    .then(function (content) {
					        saveAs(content, dirName+".zip");
							console.log("FINISHED!!!");
					    }, function (e) {
							console.log("ERROR!!!");
					    });
					}
				});
			}else{
				console.log("is new");
				const url = img.src;// our images
				const request = new Request(url, { headers: new Headers({'Mime-Type': 'text\/plain; charset=x-user-defined'})})
				const response = await fetch(request);
				const contents = await response.text();
				getBase64ImageNewWay(request.url, function (base64){
					var file = imgDir.file(filename,base64,{base64: true});
					baseArray.push(file);
					console.log("i = "+i+" limit = "+limit+" base64.length = "+base64.length);
					if (baseArray.length == limit){
					console.log("GO!!!");
						zip.generateAsync({type:"blob"})
					    .then(function (content) {
					        saveAs(content, dirName+".zip");
							console.log("FINISHED!!!");
					    }, function (e) {
							console.log("ERROR!!!");
					    });
					}
				});
			}
		}
		callback = console.log("done");
	}		
	getIt();
} 

$(document).on("tap", '#export-imgs-tab', function(event){
	event.preventDefault();
	var stk = $(this).data("stknum");
	downloadAllImages(stk,imgObjects, imgObjects.length);
});
/* Reset the message.*/
function resetMessage () {
    $("#result")
    .removeClass()
    .text("");
}
/*** show a successful message.* @param {String} text the text to show.*/
function showMessage(text) {
    resetMessage();
    $("#result")
    .addClass("alert alert-success")
    .text(text);
}
/** * show an error message. * @param {String} text the text to show.*/
function showError(text) {
    resetMessage();
    $("#result")
    .addClass("alert alert-danger")
    .text(text);
}
/*** Update the progress bar.* @param {Integer} percent the current percent*/
function updatePercent(percent) {
    $("#progress_bar").removeClass("hide")
    .find(".progress-bar")
    .attr("aria-valuenow", percent)
    .css({
        width : percent + "%"
    });
}
Array.min = function( array ){
    return Math.min.apply( Math, array );
};
Array.max = function( array ){
    return Math.max.apply( Math, array );
}
function getUrlVars() {
    var vars = {};
    var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
        vars[key] = value;
    });
    return vars;
};
function getUrlParam(parameter, defaultvalue){
    var urlparameter = defaultvalue;
    if(window.location.href.indexOf(parameter) > -1){
        urlparameter = getUrlVars()[parameter];
        }
    return urlparameter;
}
function getElementByXpathForDoc(path, doc) {
  return doc.evaluate(path, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
}
function updateCreateLeadHeader() {
	var listing = (JSON.stringify(SelectedAssetListing.attributes));
		listing= JSON.parse(listing);
	var year = listing.equipYear;
	var make = listing.equipMake;
	var model = listing.equipModel;
	var author = (JSON.stringify(ListingAuthor.attributes));
		author= JSON.parse(author);
	var salesmanFirstName = author.firstName;				 		
	var salesmanLstName = author.lastName;
	var salesmanPhone = author.phone;
	var salesmanEmail = author.username;
	$('input[name=lead-name-field]').val("");
	$('input[name=lead-email-field]').val("");
	$('input[name=lead-phone-field]').val("");
	$('textarea[name=lead-comment-textarea]').val("");
	var itemInfo = "";
		itemInfo +="<p>Create lead for "+salesmanFirstName+" "+salesmanLstName+"<br/>";
		itemInfo +="For asset: "+year+" "+make+" "+model+"</p>";
	$('#lead-item-info').html(itemInfo);
}
function fixedEncodeURI(str) {
    return encodeURI(str).replace(/%25/g, '%').replace(/%5B/g, '[').replace(/%5D/g, ']');
}
/*
function searchInventory() {
    var input, filter, ul, li, a, p, i;
    input = document.getElementById('myInput');
    filter = input.value.toUpperCase();
    ul = document.getElementById("list-posts");
    li = ul.getElementsByTagName('li');
    // Loop through all list items, and hide those who don't match the search query
    for (i = 0; i < li.length; i++) {
        a = li[i].getElementsByTagName("p")[0];
        if (a.innerHTML.toUpperCase().indexOf(filter) > -1) {
            li[i].style.display = "";
        } else {
            li[i].style.display = "none";
        }
    }
}
function searchAdminTable() {
    // Declare variables
    var input, filter, ul, li, a, p, i;
    input = document.getElementById('user-listings-filter');
    filter = input.value.toUpperCase();
    ul = document.getElementById("admin-list-posts");
    li = ul.getElementsByTagName('li');
    // Loop through all list items, and hide those who don't match the search query
    for (i = 0; i < li.length; i++) {
		if (viewingUserTable){
        a = li[i].getElementsByTagName("p")[0];
		}else{
        a = li[i].getElementsByTagName("a")[0];
		}
        if (a.innerHTML.toUpperCase().indexOf(filter) > -1) {
            li[i].style.display = "";
        } else {
            li[i].style.display = "none";
        }
    }
}
function searchMyInventory() {
    // Declare variables
    var input, filter, ul, li, a, p, i;
    input = document.getElementById('invSearch');
    filter = input.value.toUpperCase();
    ul = document.getElementById("inv-man-list-posts");
    li = ul.getElementsByTagName('li');
    // Loop through all list items, and hide those who don't match the search query
    for (i = 0; i < li.length; i++) {
        a = li[i].getElementsByTagName("p")[0];
        s = li[i].getElementsByTagName("p")[1];
        r = li[i].getElementsByTagName("p")[2];
        if (a.innerHTML.toUpperCase().indexOf(filter) > -1 || s.innerHTML.toUpperCase().indexOf(filter) > -1 || r.innerHTML.toUpperCase().indexOf(filter) > -1) {
            li[i].style.display = "";
        } else {
            li[i].style.display = "none";
        }
    }
}
*/

function searchUsers() {
    // Declare variables
    var input, filter, ul, li, a, p, i,q,r,s;
    input = document.getElementById('user-filter');
    filter = input.value.toUpperCase();
    ul = document.getElementById("user-display-select-dialog-menu");
    li = ul.getElementsByTagName('li');
    // Loop through all list items, and hide those who don't match the search query
    for (i = 0; i < li.length; i++) {
		if (viewingUserTable){
        a = li[i].getElementsByTagName("p")[0];
		}else{
        a = li[i].getElementsByTagName("a")[0];
		}
        if (a.innerHTML.toUpperCase().indexOf(filter) > -1) {
            li[i].style.display = "";
        } else {
            li[i].style.display = "none";
        }
    }
}

function getCustomersForUser(user){
	$("#list-title").html("<h3>Loading, please stand by...</h3>");
	var query = new Parse.Query(Customer);
	query.include("user");
	query.limit(1000);
	//query.equalTo('user', { "__type": "Pointer", "className": "_User", "objectId": userId });
	query.equalTo('user', user);
	query.find({
		success: function(results){
			var outputTitle = "";
			if (results.length>0){
				$('#user-listings-filter').show();
				outputTitle += "<h3>"+results.length+" customers.</h3>";
			}else{
				$('#user-listings-filter').hide();
				outputTitle += "<h3>No active listing results...</h3>";
			}
			results = results.reverse();
			customerArray = results;
			$("#customer-list").empty();
			var output = "";
			for (var i = 0; i < results.length; i++){
				var stringy = JSON.stringify(results[i]);
				 	stringy = JSON.parse(stringy);
				var companyName = stringy.companyName;
				var contactFirstName = stringy.contactFirstName;
				var contactLastName = stringy.contactLastName;
				var contactPhone = stringy.companyPhone;
				var companyEmail = stringy.companyEmail;
				var address = stringy.companyAddress;
				var zip = stringy.companyZip;
				var city = stringy.companyCity;
				var state = stringy.companyState;
				var custId = stringy.companyID;
				var id = results[i].id;
				output += "<li is=\"listview-li\" itemtype = \"customer\" id ="+id+" coName=\""+companyName+"\" coAddress=\""+address+"\" coCity=\""+city+"\" coState=\""+state+"\" coZip=\""+zip+"\" contFirst=\""+contactFirstName+"\" contLast=\""+contactLastName+"\" contPhone=\""+contactPhone+"\" contEmail=\""+companyEmail+"\" coID=\""+custId+"\">";
				output += "<a class=\"ui-btn-a ui-btn ui-btn-icon-right ui-icon-carat-r\" data-form=\"ui-btn-up-a\" data-swatch=\"a\" data-theme=\"a\">";
				output += "<span style=\"font-size: 16pt;\">"+companyName+"</span></br>";
				output += "<span style=\"font-size: 14pt;\">"+address+"</span></br>";
				output += "<span style=\"font-size: 14pt;\">"+city+", "+state+"</span></br>";
				output += "<span style=\"font-size: 14pt;\">"+zip+"</span></br>";
				output += "<span style=\"font-size: 12pt;\">"+custId+"</span></br>";
				output += "</li>";
			}
			$("#user-listings-title").html(outputTitle);	
			$("#user-listings").html(output);
			$("#list-title").html(outputTitle);	
		}, error: function(error){
			console.log("Query error:"+error.message);	
		}				
	});
}
$(document).on('tap', '#get-all-customer-items', function(){
	var custType = $(this).attr("cust-type");
	var status = $(this).attr("listing-status");
	var custId = SelectedCustomerObject.objID;;
	var query = new Parse.Query(AssetListing);
	query.equalTo("status", status);
	query.include("buyer");
	query.include("seller");
	query.limit(1000);
	query.equalTo(custType, { "__type": "Pointer", "className": "Customer", "objectId": custId });
	query.find({
		success: function(results){
			$("#thumbnail-image").empty();
			results = results.reverse();
			var count = results.length;
			var output = "";
			var outputTitle = "";
			var xxx = "";
			if (custType == "buyer" && status == "Sold"){
				xxx	= "purchased";
			}else
			if (custType == "seller" && status == "Sold"){
				xxx	= "sold";
			}else
			if (custType == "seller" && status == "Active"){
				xxx	= "active";
			}
			outputTitle += "<h3>"+count+" "+xxx+" items.</h3>";
			for (var i in results){
		 		var year = results[i].get("equipYear");
		 		var make = results[i].get("equipMake");
		 		var model = results[i].get("equipModel");
		 		var price = results[i].get("equipPrice");
				price = numberToDollars(price);
		 		var description = results[i].get("equipDescription");
		 		var stockNum = results[i].get("assetOwnerStockNumber");
				var id = results[i].id;
				var imageURLs = results[i].get("equipImgs");
				var imgURL = imageURLs[0];
				imgURL = fixedEncodeURI(imgURL);
				output += "<li is=\"listview-li\" id ="+id+" itemtype = \"listing\">";
				output += "<a class=\"ui-btn-a ui-btn ui-btn-icon-right ui-icon-carat-r\" data-form=\"ui-btn-up-a\" data-swatch=\"a\" data-theme=\"a\">";
				output += "<p><img id=\"thumbnail-image\" class=\"ui-li-icon thumb-wrap\" style=\"float:left;width:80px;height:80px; vertical-align: middle;\" src= "+imgURL+" is=\"image\">";
				output += "<span style=\"font-size: 16pt;\">"+year+" "+make+" " +model+"</span></br>";
				output += "<span style=\"font-size: 14pt;\">"+description+"</span></br>";
				output += "<span style=\"font-size: 14pt;\">"+price+"</span><br/><span style=\"font-size: 10pt;\">Stock #:"+stockNum+"</span></p>";
				output += "</li>";
			}
		$("#customer-item-list").html(output);
		$("#customer-item-list-title").html(outputTitle);	
		}, error: function(error){
			console.log("Query error:"+error.message);	
		}				
	});
});
$(document).on('tap', '#complete-lead-btn', function(){
	$(".dialog-view-area").LoadingOverlay("show");
	var stringy = JSON.stringify(SelectedAssetListing.attributes);
	var listing = JSON.parse(stringy);
	var year = listing.equipYear;
	var make = listing.equipMake;
	var model = listing.equipModel;
	var equipType = listing.equipType;
	var stkNum = listing.assetOwnerStockNumber;
	var author = (JSON.stringify(ListingAuthor.attributes));
		author= JSON.parse(author);
	var manager = author.assignedManager;
	var callerName = $('input[name=lead-name-field]').val();
	var callerPhone = $('input[name=lead-phone-field]').val();
	var callerEmail = $('input[name=lead-email-field]').val();
	var messageDetails = $('textarea[name=lead-comment-textarea]').val();
	if (callerName == ""){
		alert("You must enter a contact name");
		return false;
	}
	if (callerPhone == "" && callerEmail == ""){
		alert("You must enter a phone number or email.");
		return false;
	}
	if (messageDetails == ""){
		alert("You must enter a message.");
		return false;
	} 
	var subject = year+" "+make+" "+model;
	var newLead = new Lead();
		newLead.set("assetListing", SelectedAssetListing);
		newLead.set("user", ListingAuthor);
		newLead.set("contactName", callerName);
		newLead.set("contactPhone", callerPhone);
		newLead.set("contactEmail", callerEmail);
		newLead.set("custComment", messageDetails);
		newLead.set("requestedItem", subject);
		newLead.set("subject", subject);
		newLead.set("category", equipType);
		newLead.set("stockNumber", stkNum);
		newLead.save({
			success: function(lead){
				alert("Lead created! Composing email and sms, please stand by.");
				var selLead = JSON.stringify(lead);
					selLead = JSON.parse(selLead);
 				var	leadId = selLead.objectId;
				if (author.isSuspended != true){
					sendEmailNotification("You have a lead!", author.username, "Stock number: "+listing.assetOwnerStockNumber+"\n"+subject+" has a lead!\n Message: "+messageDetails+"\n More info available at https://proxyequipment.com/WebApp/index.html#lead-details?id="+leadId, function (){
						sendTextMessage("+1"+author.phone, "New lead! "+subject+" "+callerName+" "+messageDetails+". Click this link to view more details https://proxyequipment.com/WebApp/index.html#lead-details?id="+leadId, function(){
							alert("Lead sent!");
						});
					});
				}
				if (author.leadForwarding == true){
					forwardLead(manager,author,listing.assetOwnerStockNumber,callerName,subject,messageDetails,leadId);
				}else
					$(".dialog-view-area").LoadingOverlay("hide");
					$('#create-lead-dialog').dialog('close');
			}, error: function(newLead, error){
				console.log("File Save ERROR!:"+error.message);
			}	
		});
});
function forwardLead(manager,author,stkNum,prospectName,subject,message,leadId){
	var authorFullName = ""+author.firstName+" "+author.lastName+"";
	var managerFullName = ""+manager.firstName+" "+manager.lastName+"";
	alert("Forwarding lead to "+managerFullName+" @ "+manager.phone+" & "+manager.username);
	sendEmailNotification("FWD: "+authorFullName+" has a lead!", manager.username, "Stock number: "+stkNum+"\n"+subject+" has a lead!\n Message: "+message+"\n More info available at https://proxyequipment.com/WebApp/index.html#lead-details?id="+leadId, function (){
		sendTextMessage("+1"+manager.phone, "New lead for "+authorFullName+"! "+subject+" "+prospectName+" "+message+". Click this link to view more details https://proxyequipment.com/WebApp/index.html#lead-details?id="+leadId, function (){
			$(".dialog-view-area").LoadingOverlay("hide");
			$('#create-lead-dialog').dialog('close');
		});
	});
}


function getLeadsForUser(user){
	$("#list-title").html("<h3>Loading, please stand by...</h3>");
	var userId = user.toJSON().objectId;
	var query = new Parse.Query(Lead);
	query.include("user");
	query.ascending('createdAt');
	query.limit(1500);
	query.equalTo('user', { "__type": "Pointer", "className": "_User", "objectId": userId });
	query.find({
		success: function(results){
			var outputTitle = "";
			if (results.length>0){
				$('#user-listings-filter').show();
				outputTitle += "<h3>"+results.length+" leads.</h3>";
			}else{
				$('#user-listings-filter').hide();
				outputTitle += "<h3>No active listing results...</h3>";
			}
			results = results.reverse();
			$("#user-listings").empty();
			var output = "";
			for (var i = 0; i < results.length; i++){
				var lead = JSON.stringify(results[i]);
				 	lead = JSON.parse(lead);
				var subject = lead.subject;
				var contactName = lead.contactName;
				var contactPhone = lead.contactPhone;
				var contactEmail = lead.contactEmail;
				var custComment = lead.custComment;
				var isNew = lead.isNew;
				var status = "";
				if(isNew || isNew == null){
					status+="NEW! ";
				}else{
					status+="";
				}
				var saleDate = new Date(results[i].createdAt);
					saleDate = saleDate.toString();
				var id = results[i].id;
				output += "<li is=\"listview-li\" id ="+id+" itemtype = \"lead\">";
				output += "<a class=\"ui-btn-a ui-btn ui-btn-icon-right ui-icon-carat-r\" data-form=\"ui-btn-up-a\" data-swatch=\"a\" data-theme=\"a\">";
				output += "<p><span style=\"font-size: 16pt;\"><span style=\"font-size: 15pt; color:#65f23a; text-shadow: 1px 1px #000000;\">"+status+"</span>"+subject+"</span></br>";
				output += "<span style=\"font-size: 14pt;\">"+custComment+"</span></br>";
				output += "<span style=\"font-size: 14pt;\">"+contactName+"</span></br>";
				output += "<span style=\"font-size: 14pt;\">"+contactPhone+"</span></br>";
				output += "<span style=\"font-size: 14pt;\">"+contactEmail+"</span></br>";
				output += "<span style=\"font-size: 12pt;\">"+saleDate+"</span></p>";
				output += "</li>";
			}
			$("#user-listings-title").html(outputTitle);	
			$("#user-listings").html(output);
			$("#list-title").html(outputTitle);	
		}, error: function(error){
			console.log("Query error:"+error.message);	
		}				
	});
}
$(document).on('tap', "#view-listing-btn", function(){
	var id = $(this).data("id");
	var leadListingObj = JSON.stringify(SelectedLeadListing);
		leadListingObj = JSON.parse(leadListingObj);
		ListingAuthor = SelectedLeadRecipient;
	    Seller = SelectedLeadListing.get("seller");
		var sts = leadListingObj.status;
		if (sts == "Sale-Pending" || sts == "Sold"){
			Buyer = SelectedLeadListing.get("buyer");
		}
	SelectedAssetListing = SelectedLeadListing;
	$( ":mobile-pagecontainer" ).pagecontainer( "change", "#listing-details", { foo: id, status: leadListingObj.status } );
});
$(document).on('tap', "#create-customer-from-lead-btn", function(){
	var name = $(this).attr("data-name");
	const arr = name.split(/ (.*)/);
	var firstName = arr[0];
	var lastName = arr[1];
	var phone = $(this).attr("data-phone");
	var email = $(this).attr("data-email");
	$('input[name=new-customer-firstname]').val(firstName);
	if (lastName){
		$('input[name=new-customer-lastname]').val(lastName);
	}
	if (phone){
		$('input[name=new-customer-phone]').val(phone);
	}
	if (email){
		$('input[name=new-customer-email]').val(email);
	}
	$.mobile.changePage("#add-customer-dialog", {transition: 'pop', role: 'dialog'});
});
$('#selectequiptype-search').change(function() {
    var $option = $(this).find('option:selected');
    var value = $option.val(); //returns the value of the selected option.
    var text = $option.text(); //returns the text of the selected option.
    selectedAuctionSearchType = $("#selectequiptype-search option:selected").attr('data-equipType');
});
$(document).on('tap', '#selectcustomer-menu li', function(){
    var index = $(this).index();
	var selObj = customerArray[index-1];
		selObj = JSON.stringify(selObj);
		selObj = JSON.parse(selObj);
		selectedCompany = selObj;
	var customerCity =  selectedCompany.companyCity;
	var customerState =  selectedCompany.companyState;
	$('input[name=equipLocation]').val(customerCity+", "+customerState);
	$('#selectcustomer-button span').text(selectedCompany.companyName);
	$('#selectcustomer-dialog').dialog('close');
	$(document).find("#new-listing-primary-data-area").show();
});

$(document).on('tap', '#selectcustomer-button', function(){
	updateCustomerListDropdown();
});
function updateCustomerListDropdown(){
	var query = new Parse.Query(Customer);
	query.include("user");
	query.equalTo('user', CurrentUser);
	query.limit(1000);
	query.find({
		success: function(results){
			results = results.reverse();
			customerArray = results;
			$("#customer-select").empty();
			$("#selectcustomer-menu").empty();
			var output = "";
			var xOutput = "";
			output += "<div class=\"ui-select ui-mini\">";
			output += "<a href=\"#selectcustomer-dialog\" role=\"button\" id=\"selectcustomer-button\" class=\"ui-btn ui-icon-carat-d ui-btn-icon-right ui-corner-all ui-shadow \" data-rel=\"dialog\"><span>Select customer</span></a>";
			output += "<select name=\"selectcustomer\" id=\"selectcustomer\" data-native-menu=\"false\" tabindex=\"-1\">";
			output += "<option value=\"None\">Select customer</option>";
			xOutput += "<li data-option-index=\"0\" data-icon=\"false\" class=\"ui-first-child\" role=\"option\" aria-selected=\"false\">";
			xOutput += "<a href=\"#\" tabindex=\"-1\" class=\"ui-btn\">Select customer</a></li>";
			var zz=0;
			for (var i in results){
				zz++;
				var stringy = JSON.stringify(results[i]);
				 	stringy = JSON.parse(stringy);
				var companyName = stringy.companyName;
				output += "<option value=\""+companyName+"\">"+companyName+"</option>";
				xOutput += "<li data-option-index=\""+zz+"\" data-icon=\"false\" class role=\"option\" aria-selected=\"false\">";
				xOutput += "<a href=\"#\" tabindex=\"-1\" class=\"ui-btn\">"+companyName+"</a></li>";
			}
		output += "</select>";
		output += "<div style=\"display:none;\" id=\"selectcustomer-listbox-placeholder\"><!---Placeholder---></div>";
		output += "</div>";
		$("#customer-select").html(output);	
		$("#selectcustomer-menu").html(xOutput);	
		}, error: function(error){
			console.log("Query error:"+error.message);	
		}				
	});
}
function numberToDollars(number) {
	var offer = "Make an offer!";
	number = number.replace(',', '');
	number = number.replace('$', '');
	var formatter = new Intl.NumberFormat('en-US', {
	        style: 'currency',
            currency: 'USD',
            minimumFractionDigits: 2,
         });
		if (isNaN(number)|| number<=0){
			return offer;
		}else{
         	return formatter.format(number);
		}
}
function Validate(oForm) {
    var arrInputs = oForm.getElementsByTagName("input");
    for (var i = 0; i < arrInputs.length; i++) {
        var oInput = arrInputs[i];
        if (oInput.type == "file") {
            var sFileName = oInput.value;
            if (sFileName.length > 0) {
                var blnValid = false;
                for (var j = 0; j < _validFileExtensions.length; j++) {
                    var sCurExtension = _validFileExtensions[j];
                    if (sFileName.substr(sFileName.length - sCurExtension.length, sCurExtension.length).toLowerCase() == sCurExtension.toLowerCase()) {
                        blnValid = true;
                        break;
                    }
                }
                if (!blnValid) {
                    alert("Sorry, " + sFileName + " is invalid, allowed extensions are: " + _validFileExtensions.join(", "));
                    return false;
                }
            }
        }
    }  
    return true;
}
function selectThumbnailByIndex(index){
    $("#main-image").empty();
	var URLs = sessionStorage.getItem('imageArray');
	URLs = JSON.parse(URLs);
	var mainImgURL = URLs[index];
	mainImgURL = fixedEncodeURI(mainImgURL);
 	var output = "<img id=\"main-image\" style=\"width:100%;\" src= "+mainImgURL+" is=\"image\">";
	$(document).find("#main-image").append(output);
}
$('#previous-img-btn').on('tap', function(e){
	if (galleryImageIndex!=0){
		galleryImageIndex--;
		$("#main-image").empty();
		var URLs = sessionStorage.getItem('imageArray');
		URLs = JSON.parse(URLs);
		var mainImgURL = URLs[galleryImageIndex];
		mainImgURL = fixedEncodeURI(mainImgURL);
	 	var output = "<img id=\"main-image\" style=\"width:100%;\" src= "+mainImgURL+" is=\"image\">";
		$(document).find("#main-image").append(output);
	}else{
		console.log("first image");
	}
});
$('#next-img-btn').on('tap', function(e){
	if (galleryImageIndex<galleryImageCount-1){
		galleryImageIndex++;
		$("#main-image").empty();
		var URLs = sessionStorage.getItem('imageArray');
		URLs = JSON.parse(URLs);
		var mainImgURL = URLs[galleryImageIndex];
		mainImgURL = fixedEncodeURI(mainImgURL);
	 	var output = "<img id=\"main-image\" style=\"width:100%;\" src= "+mainImgURL+" is=\"image\">";
		$(document).find("#main-image").append(output);
	}else{
		console.log("last image");
	}
});
$('#submit-reset').on('tap', function(e){
	$( ":mobile-pagecontainer" ).pagecontainer( "change", "#passwordreset" );
});
function doesCustIdExist(newID){
	console.log("check for customer id: "+newID);
	var custArray = [];
	var query = new Parse.Query(Customer);
	query.include("user");
	query.equalTo('user', CurrentUser);
	query.find({
		success: function(results){
			results = results.reverse();
			for (var i = 0; i < results.length; i++){
				var cust = JSON.stringify(results[i].attributes);
					cust = JSON.parse(cust);
				var id = cust.companyID;
					custArray.push(id);
			}
			var containsID = (custArray.indexOf(""+newID+"") > -1);
			if (containsID){
				console.log("Exists? === >>> "+containsID);
				tryAnotherCustId(newID);
			}else{
				console.log("Created with id: "+newID);
				//var companyID = $('input[name=id]').val();
				var newCustomer = new Customer();
				var contactFirstName = $('input[name=new-customer-firstname]').val();
				var contactLastName = $('input[name=new-customer-lastname]').val();
				var companyName = $('input[name=new-customer-companyname]').val();
				var companyAddress = $('input[name=new-customer-companyaddress]').val();
				var companyCity = $('input[name=new-customer-companycity]').val();
				var companyZip = $('input[name=new-customer-companyzip]').val();
				var companyState = $('select[name=new-customer-companystate] option:selected').text();
				var companyEmail = $('input[name=new-customer-email]').val();
				var companyPhone = $('input[name=new-customer-phone]').val();
				if (companyName  === '') {
			        alert('Company Name is empty.');
			        return false;
			    }else
				if (companyAddress  === '') {
			        alert('Company Address is empty.');
			        return false;
			    }else
				if (companyCity  === '') {
			        alert('Company City is empty.');
			        return false;
			    }else
				if (companyZip  === '') {
			        alert('Company Zip is empty.');
			        return false;
			    }else
				if ($('select[name=new-customer-companystate] option:selected').val()  === 'None') {
			        alert('Please select a state.');
			        return false;
			    }else
				if (contactFirstName  === '') {
			        alert('Contact First Name is empty.');
			        return false;
			    }else
			    if (contactLastName  === '') {
			        alert('Contact Last Name is empty.');
			        return false;
			    }else
				if (companyEmail  === '') {
			        alert('Company Email is empty.');
			        return false;
			    }else
				if (companyPhone  === '') {
			        alert('Company Phone is empty.');
			        return false;
			    }else
				newCustomer.set("companyName", companyName);
				newCustomer.set("contactFirstName", contactFirstName);
				newCustomer.set("contactLastName", contactLastName);
				newCustomer.set("companyAddress", companyAddress);
				newCustomer.set("companyCity", companyCity);
				newCustomer.set("companyZip", companyZip);
				newCustomer.set("companyState", companyState);
				newCustomer.set("companyEmail", companyEmail);
				newCustomer.set("companyPhone", companyPhone);
				newCustomer.set("companyID", newID);
				newCustomer.set("user", CurrentUser);
				newCustomer.save({
					success: function(){
							alert("Congratulations! Your customer has been added.");
							$('#add-customer-dialog').dialog('close');
					}, error: function(newPost, error){
							console.log("File Save ERROR!:"+error.message);
							$('#add-customer-dialog').dialog('close');
					}	
				});
			}
		}, error: function(error){
			console.log("Query error:"+error.message);	
		}				
	});
}
function tryAnotherCustId(newID){
	console.log("...trying again with id: "+newID);
	var letter = newID.charAt(0);
	var numbers = newID.substring(1);
	var num = parseInt(numbers, 10);
		num++;
	var numStr = num.toString();
		letter += numStr;
	var id = letter;
	doesCustIdExist(id);
}
$(document).on('tap','#submit-customer', function(e){
	var startNum = "0";
	var coID = "";
	 	coID = $('input[name=new-customer-companyname]').val().charAt(0);
		coID = coID.toUpperCase();
		coID += startNum;
		doesCustIdExist(coID)
});

function doesUserIdExist(newID){
	console.log("Check if proxy ID exists");
	var idArray = [];
	var query = new Parse.Query(Users);
	query.find({
		success: function(results){
			results = results.reverse();
			for (var i = 0; i < results.length; i++){
				var u = JSON.stringify(results[i].attributes);
					u = JSON.parse(u);
				var id = u.proxyID;
					idArray.push(id);
			}
			var containsID = (idArray.indexOf(""+newID+"") > -1);
			if (containsID){
				console.log("Exists? === >>> "+containsID);
				tryAnotherUserId(newID);
			}else{
				console.log("Creating with id: "+newID);
				var username = $('input[name=usernamesetup]').val();
				var phone = $('input[name=phonesetup]').val();
				var first = $('input[name=firstnamesetup]').val();
				var nickname = $('input[name=nicknamesetup]').val();
				var last = $('input[name=lastnamesetup]').val();
				var street = $('input[name=streetsetup]').val();
				var city = $('input[name=citynamesetup]').val();
				var zip = $('input[name=zipsetup]').val();
				var password = first+"2020";
				var personalEmail = $('input[name=personalemailsetup]').val();
				var state = $('select[name=brokerstate] option:selected').text();
				var manager = $("#new-user-manager-select-button span").text();			
				if (first  === '') {
        			alert('First name is empty.');
			        return false;
			    }else if (manager === "Assign manager") {
					alert('Please select a manager.');
			        return false;
			    }else if (last  === '') {
			        alert('Last name is empty.');
			        return false;
			    }else if (username  === '') {
			    	alert('Email is empty.');
			    	return false;
				}else if (personalEmail  === '') {
			    	alert('Personal email is empty.');
			    	return false;
				}else if (phone  === '') {
					alert('Phone is empty or contains invalid characters');
				    return false;
				}else if (street  === '') {
					alert('Street address is empty.');
				    return false;
			    }else if (city  === '') {
					alert('City is empty.');
				    return false;
			    }else if (zip  === '') {
					alert('Zip is empty.');
				    return false;
			    }else if ($('select[name=brokerstate] option:selected').val()  === 'None') {
			        alert('Please select a state.');
			        return false;
				}else
				var assMan = JSON.stringify(SelectedManager.attributes);
					assMan = JSON.parse(assMan);
				var user = new Parse.User();
				user.set("assignedManager", SelectedManager);
				user.set("username", username);
				user.set("email", username);
				user.set("password", password);
				user.set("firstName", first);
				user.set("nickname", nickname);
				user.set("lastName", last);
				user.set("personalEmail", personalEmail);
				user.set("phone", phone);
				user.set("streetAddress", street);
				user.set("city", city);
				user.set("zipCode", zip);
				user.set("state", state);
				user.set("proxyID", newID);
				user.set("leadForwarding", true);
				user.set("contractStatus", "Pending");
				user.signUp(null, {
			 		success: function(newUser) {
						 alert("New rep set up successfully.")
						$( ":mobile-pagecontainer" ).pagecontainer( "change", "#index" );
						location.reload(true);
						SelectedUser = newUser;
			 		},
					 error: function(user, error) {
			        	alert("Error: " + error.code + " " + error.message);
			  		}
				});
			}
		}, error: function(error){
			console.log("Query error:"+error.message);	
		}				
	});
}

function tryAnotherUserId(newID){
	console.log("...trying again");
	var letters = newID.charAt(0,2);
	console.log(letters)
	var numbers = newID.substring(3);
	var num = parseInt(numbers, 10); 
		num++;
	var numStr = num.toString();
		letters += numStr;
	var id = letters;
	console.log("...trying with id : "+id);
	doesUserIdExist(id);
}
function getAllManagers(callback){
	var query = new Parse.Query(Users);
		query.equalTo("userType","Manager");
		query.notEqualTo("isSuspended",true);
		//query.notEqualTo("objectId", CurrentUser.toJSON().objectId);
		query.ascending('lastName');
		query.find({			
	});
	var adminQuery = new Parse.Query(Users);
		adminQuery.equalTo("userType","Admin");
		adminQuery.notEqualTo("isSuspended",true);
		//query.notEqualTo("objectId", CurrentUser.toJSON().objectId);
		adminQuery.ascending('lastName');
		adminQuery.find({
	});
	var superAdminQuery = new Parse.Query(Users);
		superAdminQuery.equalTo("userType","Super-Admin");
		superAdminQuery.notEqualTo("isSuspended",true);
		//query.notEqualTo("objectId", CurrentUser.toJSON().objectId);
		superAdminQuery.ascending('lastName');
		superAdminQuery.find({
	});
	var developerQuery = new Parse.Query(Users);
		developerQuery.equalTo("userType","Developer");
		developerQuery.notEqualTo("isSuspended",true);
		//query.notEqualTo("objectId", CurrentUser.toJSON().objectId);
		developerQuery.ascending('lastName');
		developerQuery.find({
	});
	var mainQuery = Parse.Query.or(query, adminQuery, superAdminQuery, developerQuery);
		mainQuery.find()
  			.then(function(results) {
				callback(results);
  			})
  		.catch(function(error) {
			  console.log("Some shit went wrong "+error);
    		// There was an error.
  	});	
}

$('#submit-signup').on('tap', function(e){
    e.preventDefault();
	var startNum = "0";
	var proxyID = "";
	var fInitial = $('input[name=firstnamesetup]').val().substring(0,1).toUpperCase();
	var lInitial = $('input[name=lastnamesetup]').val().substring(0,1).toUpperCase();
	var today = new Date();
	var dateX = formatDateWithTimeNoSpace(today);
		dateX = returnYearAsLetter(dateX);
		proxyID += fInitial+lInitial+dateX+startNum;
	 	doesUserIdExist(proxyID);
});
$(document).on("tap", '#edit-listing-tab', function(event){
	event.preventDefault();
	alert("WARNING! If you save changes to an active listing it will be reset to a \"pending\" status and will require approval by an admin.");
  	$( ":mobile-pagecontainer" ).pagecontainer( "change", "#edit-listing", { objid: listingID} );	
});
$(document).on("tap", '#edit-listing-warning-btn', function(event){
	$('#edit-listing-warning-dialog').dialog('open');
});
$('#submit-forgot').on('tap', function(e){				
	var email = $('input[name=resetemail]').val();
	Parse.User.requestPasswordReset(email , {
        success: function () { 
			alert("Please check your email to reset password.");
        }, error: function (error) {
            console.log(".reset-form .error"+error.message);
        }
    });
	$( ":mobile-pagecontainer" ).pagecontainer( "change", "#signin" );
});

function CSVtoArray(text) {
    var re_valid = /^\s*(?:'[^'\\]*(?:\\[\S\s][^'\\]*)*'|"[^"\\]*(?:\\[\S\s][^"\\]*)*"|[^,'"\s\\]*(?:\s+[^,'"\s\\]+)*)\s*(?:,\s*(?:'[^'\\]*(?:\\[\S\s][^'\\]*)*'|"[^"\\]*(?:\\[\S\s][^"\\]*)*"|[^,'"\s\\]*(?:\s+[^,'"\s\\]+)*)\s*)*$/;
    var re_value = /(?!\s*$)\s*(?:'([^'\\]*(?:\\[\S\s][^'\\]*)*)'|"([^"\\]*(?:\\[\S\s][^"\\]*)*)"|([^,'"\s\\]*(?:\s+[^,'"\s\\]+)*))\s*(?:,|$)/g;
    // Return NULL if input string is not well formed CSV string.
    if (!re_valid.test(text)) return null;
    var a = [];                     // Initialize array to receive values.
    text.replace(re_value, // "Walk" the string using replace with callback.
        function(m0, m1, m2, m3) {
            // Remove backslash from \' in single quoted values.
            if      (m1 !== undefined) a.push(m1.replace(/\\'/g, "'"));
            // Remove backslash from \" in double quoted values.
            else if (m2 !== undefined) a.push(m2.replace(/\\"/g, '"'));
            else if (m3 !== undefined) a.push(m3);
            return ''; // Return empty string.
        });
    // Handle special case of empty last value.
    if (/,\s*$/.test(text)) a.push('');
    return a;
}

$(document).on('tap','#submit-listing-btn', function(e){
	var newPost = new AssetListing();
	var URLs = sessionStorage.getItem('imageArray');
	var images = JSON.parse(URLs);
	var admin = (JSON.stringify(CurrentUser.attributes));
		admin = JSON.parse(admin);
		adminID = admin.proxyID;

	var auctionCategory = $("#new-listing-category-select span").text();
	if (auctionCategory === "Select a category"){
		auctionCategory = $('input[id=new-listing-category-input]').val();
	}

	var equipMake = $("#new-listing-make-select-button span").text();
	if (equipMake === "Select make"){
		equipMake = $('input[id=new-listing-make-input]').val();
	}
	var equipModel = $("#new-listing-model-select-button span").text();
	if (equipModel === "Select model"){
		equipModel = $('input[id=new-listing-model-input]').val();
	}
	
	var equipYear = $("#new-listing-year-select-button span").text();
	var equipType = $("#selectequiptype option:selected").text();
	
	var equipHours = $('input[name=equipHours]').val();
	var equipMileage = $('input[name=equipMileage]').val();
	var equipSerial = $('input[name=equipSerial]').val();
	var equipVIN = $('input[name=equipVIN]').val();
	var equipLocation = $('input[name=equipLocation]').val();
	var equipPrice = $('input[name=equipPrice]').val();
	var equipCost = $('input[name=equipCost]').val();
	var equipDescription = $('textarea[name=equipDescription]').val();
	var adminComment = "New listing!";
	var custID = selectedCompany.companyID;
	var today = new Date();
	var dateX = formatDateWithTimeNoSpace(today);
		dateX = returnDateAsStkNum(dateX);
	var ownerStockNumber = ""+adminID+custID+dateX+"";
	//if (equipType  === 'Select equipment type') {
        //alert('Please select a equipment type from the dropdown menu.');
        //return false;
    //}else
    if (selectedCompany.contactFirstName  == null) {
        alert('Please select a customer (Asset owner).');
        return false;
    }else
    if (equipMake  === '') {
        alert('Make-field is empty.');
        return false;
    }else
    if (equipModel  === '' || equipModel == "Select model") {
        alert('Model-field is empty.');
        return false;
    }else
    if (equipYear  === 'Year') {
        alert('Please select a year.');
        return false;
    }else
	if (equipLocation  === '') {
        alert('Location-field is empty.');
        return false;
    }else
	if (equipPrice  === '') {
        alert('Price-field is empty.');
        return false;
    }else
	if (equipCost  === '') {
        alert('Cost-field is empty.');
        return false;
    }else
	if (equipDescription  === '') {
        alert('Description-field is empty.');
        return false;
    }else
	
	if (images.size  === 0) {
        alert('Upload at least 1 image.');
        return false;
    }else
		var query = new Parse.Query(Customer);
		query.include("user");
		query.equalTo("objectId", selectedCompany.objectId);
		query.first({
			success: function(result){
				newPost.set("seller", result);
				newPost.set("status", "Pending");
				newPost.set("user", CurrentUser);
				newPost.set("assetOwnerStockNumber",ownerStockNumber);
				newPost.set("tbCategory",auctionCategory); 		
				newPost.set("equipType", equipType);
				newPost.set("equipMake", equipMake);
				newPost.set("equipModel", equipModel);
				newPost.set("equipYear", equipYear);
				newPost.set("equipHours", equipHours);
				newPost.set("equipMileage", equipMileage);
				newPost.set("equipSerial", equipSerial);
				newPost.set("equipVIN", equipVIN);
				newPost.set("equipLocation", equipLocation);
				newPost.set("equipPrice", equipPrice);
				newPost.set("equipCost", equipCost);
				newPost.set("equipDescription", equipDescription);
				newPost.set("equipImgs", images);
				newPost.set("adminComment", adminComment);
				newPost.save({
					success: function(){
						alert("Congratulations! Your listing has been submitted.");
						sessionStorage.clear();
						location.reload();
					}, error: function(newPost, error){
						console.log("File Save ERROR!:"+error.message);
					}	
				});
			},error: function(error){
				console.log("Query error:"+error.message);	
			}
		});
});
$(document).on('tap', '#reject-listing-btn', function(){
	var query = new Parse.Query(AssetListing);
	var adminComment = document.getElementById('reject-listing-admin-comment').value;
	var today = new Date();
	// Check if empty of not
    if (adminComment  === '') {
        alert('Comment is empty.');
        return false;
    }else
	query.get(listingID, { // we get the object
		success: function (instance) {
			var stringy = JSON.stringify(SelectedAssetListing.attributes);
			var listing = JSON.parse(stringy);
			var year = listing.equipYear;
			var make = listing.equipMake;
			var model = listing.equipModel;
		
			var author = (JSON.stringify(ListingAuthor.attributes));
				author= JSON.parse(author);
			var authorEmail = author.username;
			instance.set("status", "Rejected"); // We update the returned object
			instance.set("adminComment", adminComment);
			instance.set("dateRemoved", today);
			instance.set("lastEditDate", today);
			instance.set("lastEditor", CurrentUser);
			instance.save({
				success: function(){
					alert("Listing rejected!");
					sendEmailNotification("Listing rejected!", authorEmail, "Stock number: "+listing.assetOwnerStockNumber+" "+year+" "+make+" "+model+" has been rejected. Reason for rejection: "+adminComment+"", function (){
						$.mobile.back();
					});
					}, error: function(newPost, error){
						console.log("File Save ERROR!:"+error.message);
					}	
			}); // save it
		}
	});	
});
$(document).on('tap', "#cancel-reject-listing-btn", function(e){
    e.preventDefault();
	$('#reject-listing-warning-dialog').dialog('close');
});

$(document).on('tap','#remove-listing-btn', function(e){
    e.preventDefault();
    $('#remove-listing-warning-dialog').dialog('close');
	var stringy = JSON.stringify(SelectedAssetListing.attributes);
	var listing = JSON.parse(stringy);
var year = listing.equipYear;
	var make = listing.equipMake;
	var model = listing.equipModel;
	var adminComment = document.getElementById('remove-listing-admin-comment').value;
	var today = new Date();
    if (adminComment  === '') {
        alert('Comment is empty.');
        return false;
    }else
	var query = new Parse.Query(AssetListing);
	query.include("user");
	query.equalTo("objectId", listingID);
	query.first({
		success: function(results){
			console.log("Found: "+listingID);	
			results.set("status", "Removed");		
			results.set("adminComment", adminComment);
			results.set("dateRemoved", today);
			results.set("lastEditDate", today);
			results.set("lastEditor", CurrentUser);
			results.save({
				success: function(){
						alert("Congratulations! Your listing has been removed.");
						sendEmailNotification("Listing removed!", "admin@proxyequipment.com", "Stock number: "+listing.assetOwnerStockNumber+" "+year+" "+make+" "+model+" has been removed. Reason for removal: "+adminComment+" Please remove from advertising outlets.", function (){
							sessionStorage.clear();
							window.history.back();
						});
				}, error: function(results, error){
						console.log("File Save ERROR!:"+error.message);
				}	
			});
		},error: function(error){
			console.log("Query error:"+error.message);	
		}
	});	
});

$(document).on('tap','#cancel-remove-listing-btn', function(e){
    e.preventDefault();
    $('#remove-listing-warning-dialog').dialog('close');	
});

$(document).on('tap','#save-edited-listing-btn', function(e){
    $('#edit-listing-warning-dialog').dialog('close');
	var URLs = sessionStorage.getItem('imageArray');
	var images = JSON.parse(URLs);
	var stringy = JSON.stringify(SelectedAssetListing.attributes);
	var listing = JSON.parse(stringy);

	var equipType = document.getElementById('editEquipType').value;
	var equipMake = document.getElementById('editEquipMake').value;
	var equipModel = document.getElementById('editEquipModel').value;
	var equipYear = document.getElementById('editEquipYear').value;
	var equipHours = document.getElementById('editEquipHours').value;
	var equipMileage = document.getElementById('editEquipMileage').value;
	var equipSerial = document.getElementById('editEquipSerial').value;
	var equipVIN = document.getElementById('editEquipVIN').value;
	var equipLocation = document.getElementById('editEquipLocation').value;
	var equipPrice = document.getElementById('editEquipPrice').value;
	var equipCost = document.getElementById('editEquipCost').value;
	var equipDescription = document.getElementById('editEquipDescription').value;
	var adminComment = document.getElementById('edit-listing-admin-comment').value;
	var today = new Date();
	// Check if empty of not
    if (equipMake  === '') {
        alert('Make-field is empty.');
        return false;
    }else if (equipModel  === '') {
        alert('Model-field is empty.');
        return false;
    }else if (equipYear  === '') {
        alert('Year-field is empty.');
        return false;
    }else if (equipLocation  === '') {
        alert('Location-field is empty.');
        return false;
    }else if (equipPrice  === '') {
        alert('Price-field is empty.');
        return false;
    }else if (equipCost  === '') {
        alert('Cost-field is empty.');
        return false;
    }else if (equipDescription  === '') {
        alert('Description-field is empty.');
        return false;
    }else if (adminComment  === '') {
        alert('Comment field is empty.');
        return false;
    }else if (images.size  === 0) {
        alert('Upload at least 1 image.');
        return false;
    }else
	var query = new Parse.Query(AssetListing);
	query.include("user");
	query.equalTo("objectId", listingID);
	query.first({
		success: function(results){
			console.log("Found: "+listingID);	
			results.set("status", "Pending");		
			results.set("equipType", equipType);
			results.set("equipMake", equipMake);
			results.set("equipModel", equipModel);
			results.set("equipYear", equipYear);
			results.set("equipHours", equipHours);
			results.set("equipMileage", equipMileage);
			results.set("equipSerial", equipSerial);
			results.set("equipVIN", equipVIN);
			results.set("equipLocation", equipLocation);
			results.set("equipPrice", equipPrice);
			results.set("equipCost", equipCost);
			results.set("equipDescription", equipDescription);
			results.set("equipImgs", images);
			results.set("adminComment", adminComment);
			results.set("lastEditDate", today);
			results.set("lastEditor", CurrentUser);
			results.save({
				success: function(){
						console.log("Saving: "+listingID);	
						alert("Congratulations! Your listing has been edited.");
						window.history.back();
						sessionStorage.clear();
				}, error: function(results, error){
						console.log("File Save ERROR!:"+error.message);
				}	
			});
		},error: function(error){
			console.log("Query error:"+error.message);	
		}
	});	
});

$(document).on('tap','#save-edited-customer', function(e){
	var companyName = document.getElementById('edit-customer-companyname').value;
	var address = document.getElementById('edit-customer-companyaddress').value;
	var city = document.getElementById('edit-customer-companycity').value;
	var zip = document.getElementById('edit-customer-companyzip').value;
	var firstname = document.getElementById('edit-customer-firstname').value;
	var lastname = document.getElementById('edit-customer-lastname').value;
	var email = document.getElementById('edit-customer-email').value;
	var phone = document.getElementById('edit-customer-phone').value;
	var companyState = $('select[name=edit-customer-companystate] option:selected').text();

	// Check if empty of not
    if (companyName  === '') {
        alert('Company name field is empty.');
        return false;
    }else if ($('select[name=edit-customer-companystate] option:selected').val()  === 'None') {
		alert('Please select a state.');
		return false;
	}else if (address  === '') {
        alert('Address-field is empty.');
        return false;
    }else if (city  === '') {
        alert('City-field is empty.');
        return false;
    }else if (zip  === '') {
        alert('Zip-field is empty.');
        return false;
    }else if (firstname  === '') {
        alert('First name-field is empty.');
        return false;
    }else if (lastname  === '') {
        alert('Last name is empty.');
        return false;
    }else if (email  === '') {
        alert('Email-field is empty.');
        return false;
    }else if (phone  === '') {
        alert('Phone-field is empty.');
        return false;
    }else
	var newCustomer = new Parse.Query(Customer);
	newCustomer.include("user");
	newCustomer.equalTo("objectId", SelectedCustomerObject.objID);
	newCustomer.first({
		success: function(result){
			result.set("companyName", companyName);
			result.set("contactFirstName", firstname);
			result.set("contactLastName", lastname);
			result.set("companyAddress", address);
			result.set("companyCity", city);
			result.set("companyState", companyState);
			result.set("companyZip", zip);
			result.set("companyEmail", email);
			result.set("companyPhone", phone);
			result.set("user", CurrentUser);
			result.save({
				success: function(){
    				$('#editcustomer-dialog').dialog('close');
					alert("Congratulations! Your customer has been updated.");
					window.history.back();
				}, error: function(result, error){
					console.log("File Save ERROR!:"+error.message);
				}	
			});
		},error: function(error){
			console.log("Query error:"+error.message);	
		}
	});	
});
/*
$(document).on('tap','#delete-listing-btn', function(e){
	console.log("DELETE!");
	var sessionArray = sessionStorage.getItem('currentListing');
	var parsedSessionArray = JSON.parse(sessionArray);
	var stringy = JSON.stringify(parsedSessionArray[0]);
	var listing = JSON.parse(stringy);

	const AssetListing = Parse.Object.extend('AssetListing');
	const query = new Parse.Query(AssetListing);
	// here you put the objectId that you want to delete
	query.get(listing.objectId).then((object) => {
	  object.destroy().then((response) => {
	    console.log(response);
	  })
	}, (error) => {
	  console.error(error);
	});
});
*/
function viewEmail() {
	var src = "https://proxyequipmentsales.com:2096/";
	window.location.href = src;
}
$(document).on('tap',"#view-flyer", function(c){
	//c.preventDefault();
	var src = "https://www.proxyequipment.com/WebApp/docs/ProxyTrifold.pdf";
	window.location.href = src;
});

$(document).on('tap',"#view-listing-template", function(c){
	//c.preventDefault();
	var src = "https://www.proxyequipment.com/WebApp/docs/ListingTemplate.pdf";
	window.location.href = src;
});
			   	
$(document).on('tap', "#add-new-user", function(){
	$( ":mobile-pagecontainer" ).pagecontainer( "change", "#signup" );
});

$(document).on('tap', "#sign-out", function(e){
	e.preventDefault();
	// log the user out
	Parse.User.logOut();
	$( ":mobile-pagecontainer" ).pagecontainer( "change", "#signin" );
});
$("#submit-signin").on('tap', function(e){
    e.preventDefault();
	var username = $('input[name=username]').val();
	var password = $('input[name=password]').val();
	Parse.User.logIn(username , password, {
		success: function(u) {
			SelectedUser = CurrentUser;
			$(":mobile-pagecontainer" ).pagecontainer( "change", "#index" );
			location.reload(true);
		},
		error: function(user, error) {
            alert("Error: " + error.code + " " + error.message);
		}
	});
});
$(document).on('tap', "#view-customer-details-page", function(e){
	var type = $(this).attr("data-cust-type");
	if (type == "seller"){
		var seller = (JSON.stringify(Seller.attributes));
		seller = JSON.parse(seller);
		SelectedCustomerObject = {
			coID:seller.companyId,
			coName:seller.companyName,
			coCity:seller.companyCity,
			coState:seller.companyState,
			coAddress:seller.companyAddress,
			coZip:seller.companyZip,
			contFirst:seller.contactFirstName,
			contLast:seller.contactLastName,
			contPhone:seller.companyPhone,
			email:seller.companyEmail,
			objID:Seller.id
		}
	}
	if (type == "buyer"){
		var buyer = (JSON.stringify(Buyer.attributes));
			buyer= JSON.parse(buyer);
		SelectedCustomerObject = {
			coID:buyer.companyId,
			coName:buyer.companyName,
			coCity:buyer.companyCity,
			coState:buyer.companyState,
			coAddress:buyer.companyAddress,
			coZip:buyer.companyZip,
			contFirst:buyer.contactFirstName,
			contLast:buyer.contactLastName,
			contPhone:buyer.companyPhone,
			email:buyer.companyEmail,
			objID:Buyer.id
		}
	}
	$( ":mobile-pagecontainer" ).pagecontainer( "change", "#customer-profile");
});
	
function drag(event){
    event.dataTransfer.setData
    ('target_id',event.target.id);
}
function allowDrop(event){
  event.preventDefault();
}
function drop(event) {
  	event.preventDefault();  
	var drop_target = event.target;
	var drag_target_id = event.dataTransfer.getData('target_id');
	var drag_target = $('#'+drag_target_id)[0];
  	var tmp = document.createElement('span');
  	tmp.className='hide';
  	drop_target.before(tmp);
  	drag_target.before(drop_target);
  	tmp.replaceWith(drag_target);
  	var array = [];
}
function updateListingImgArrayOrder(array){
	var listing = (JSON.stringify(SelectedAssetListing.attributes));
		listing= JSON.parse(listing);
	var query = new Parse.Query(AssetListing);
		query.include("user");
		query.equalTo("assetOwnerStockNumber", listing.assetOwnerStockNumber);
		query.each(function(object){
			object.set("equipImgs",array);
				sessionStorage.clear();
				sessionStorage.setItem('imageArray',JSON.stringify(array));
				return object.save();
			console.log("Saved!")
		}).then(function() {
			console.log("Finished!")
		}, function(err) {
		  console.log(err);
		});
}
$(document).on('tap', "#save-image-order-btn", function(){
	var array = [];
	$('.gallery-thumbnail').each(function () {
  		array.push( $(this).attr("src") );
	});
	updateListingImgArrayOrder(array);
	$('#img-gallery-colapsible').collapsible( "collapse" );
});
$(document).on('tap','#create-pending-sale-btn', function(e){
    var price = $('input[name=purchase-price-field]').val();
    var cost = $('input[name=final-cost-field]').val();
	var comments = $('textarea[name=sale-comments-textarea]').val();
	var today = new Date();
	if(price.length<1){
		price = $('input[name=purchase-price-field]').val();
	}
	if(cost.length<1){
		cost = $('input[name=edit-final-cost-field]').val();
	}
	if(comments.length<1){
		comments = "";
	}else{
		comments = $('textarea[name=sale-comments-textarea]').val();
	}
	if(cost.length==0){
		alert("Please enter a cost for this sale.");
        return false;
	}
	if(price.length==0){
		alert("Please enter a sale price.");
        return false;
	}
	if(Number(price) <= Number(cost)){
		alert("Your price cannot be less than or equal to the cost.");
        return false;
	}
	var query = new Parse.Query(AssetListing);
		query.include("user");
		query.include("buyer");
		query.include("seller");
		query.equalTo("objectId", listingID);
		query.first({
			success: function(listing){
				if (listing){
					var cu = (JSON.stringify(CurrentUser.attributes));
						cu = JSON.parse(cu);
					var stringy = JSON.stringify(SelectedAssetListing.attributes);
					var listingObj = JSON.parse(stringy);
					var author = (JSON.stringify(ListingAuthor.attributes));
						author= JSON.parse(author);
					var manager = author.assignedManager;
					var customerQuery = new Parse.Query(Customer);
					customerQuery.include("user");
					customerQuery.equalTo("objectId", selectedCompany.objectId);
					customerQuery.first({
						success: function(custResult){
							if (!custResult){
								alert("Please select a buyer.");
								return false;
							}
							var buyerObjId = custResult.id;
							var sellerObjId = listingObj.seller.objectId;
							var matches = compareObjects(buyerObjId, sellerObjId);
							if (matches){
								alert("Your buyer and seller can't be the same company.");
								return false;
							}
							listing.set("buyer",custResult);
							listing.set("status","Sale-Pending");
							listing.set("soldForPrice", price);
							listing.set("totalCost", cost);
							listing.set("saleComments", comments);
							listing.set("lastEditDate", today);
							listing.set("saleGenerationDate", today);
							listing.set("lastEditor", CurrentUser);
							listing.save({
							success: function(){
    								$('#sale-pending-dialog').dialog('close');
									alert("Congratulations! Your listing is updated to \"Sale-Pending\".");
									sendEmailNotification("Sale generated!", manager.username, cu.firstName+" "+cu.lastName+" has generated a sale for stock number: "+listingObj.assetOwnerStockNumber, function (){
										//sendTextMessage("+1"+manager.phone, "Sale generated!", manager.username, cu.firstName+" "+cu.lastName+" has generated a sale for stock number: "+listingObj.assetOwnerStockNumber, function(){
											window.history.back();
										//});
									});
							}, error: function(result, error){
									console.log("File Save ERROR!:"+error.message);
							}	
							});
						},error: function(error){
							console.log("Query error:"+error.message);	
						}
					});
				}else{
					console.log("Houston, we have a problem");
				}
			},error: function(error){
				console.log("Query error:"+error.message);	
			}
		});
});
$(document).on('tap', "#view-pending-sale-tab", function(e){
	var stringy = JSON.stringify(SelectedAssetListing.attributes);
	var listing = JSON.parse(stringy);
	var author = (JSON.stringify(ListingAuthor.attributes));
		author= JSON.parse(author);
	var assMan = author.assignedManager; 
	$('input[name=edit-purchase-price-field]').val(listing.soldForPrice);
	$('input[name=edit-final-cost-field]').val(listing.totalCost);
	$('textarea[name=edit-sale-comments-textarea]').val(listing.saleComments);
	$('textarea[name=edit-purchase-comments-textarea]').val(listing.purchaseComments);
	$('textarea[name=edit-sale-admin-comments-textarea]').val();
	var assetOutput = "";
		assetOutput +="<p>Representative: "+author.firstName+" "+author.lastName+"<br/>Manager: "+assMan.firstName+" "+assMan.lastName+"</br>";
		assetOutput +="Asset: "+listing.assetOwnerStockNumber+"<br/>";
		assetOutput +=""+listing.equipYear+" "+listing.equipMake+" "+listing.equipModel+"<br/>";
	if (listing.equipSerial){
		assetOutput +=""+listing.equipSerial+"<br/>";
	}
	if (listing.equipVIN){
		assetOutput +=""+listing.equipVIN+"";
	}
	assetOutput +="</p>";				
	$(document).find("#listing-details-infoBox").empty();
	$(document).find("#listing-details-infoBox").html(assetOutput);
	var noteQuery = new Parse.Query(SaleNote);
	noteQuery.equalTo("listing", SelectedAssetListing);
	noteQuery.include("user");
	noteQuery.include("listing");
	noteQuery.include("message");
	noteQuery.find({
		success: function(results){
			$(document).find("#view-sale-notes-btn").text('View notes ('+results.length+')');
		}, error: function(error){
			console.log(error.message);
		}
	});
    var buyer = (JSON.stringify(Buyer.attributes));
	if	(buyer){
		buyer= JSON.parse(buyer);
		var output = "";
			output +="<p>Buyer: "+buyer.companyName+"<br/>";
			output +=""+buyer.companyAddress+",<br/>";
			output +=""+buyer.companyCity+", "+buyer.companyState+" "+buyer.companyZip+"<br/>";
			output +=""+buyer.contactFirstName+" "+buyer.contactLastName+"<br/>";
			output +=""+buyer.companyPhone+"<br/>";
			output +=""+buyer.companyEmail+"</p>";
		$(document).find("#buyer-details").empty();
		$(document).find("#buyer-details").append(output);
	}
	var seller = (JSON.stringify(Seller.attributes));
	if	(seller){
		seller= JSON.parse(seller);
		var output = "";
			output +="<p>Asset owner: "+seller.companyName+"<br/>";
			output +=""+seller.companyAddress+",<br/>";
			output +=""+seller.companyCity+", "+seller.companyState+" "+seller.companyZip+"<br/>";
			output +=""+seller.contactFirstName+" "+seller.contactLastName+"<br/>";
			output +=""+seller.companyPhone+"<br/>";
			output +=""+seller.companyEmail+"</p>";
		$(document).find("#seller-details").empty();
		$(document).find("#seller-details").append(output);
	}
});
$(document).on('tap', "#copy-buyer-notes-btn", function(e){
	var stringy = JSON.stringify(SelectedAssetListing.attributes);
	var listing = JSON.parse(stringy);
	$('textarea[name=edit-purchase-comments-textarea]').val($('textarea[name=edit-sale-comments-textarea]').val());
});
$(document).on('tap', "#cancel-sale-btn", function(e){
	console.log("cancel sale");
	e.preventDefault();
	$.mobile.changePage("#confirm-cancel-pending-sale-dialog", {transition: 'pop', role: 'dialog'});
});

$(document).on('tap', "#cancel-pending-sale-confirmed-btn", function(e){
	console.log("cancel sale confirmed");
	var cu = (JSON.stringify(CurrentUser.attributes));
		cu = JSON.parse(cu);
	var stringy = JSON.stringify(SelectedAssetListing.attributes);
	var listingObj = JSON.parse(stringy);
	var author = (JSON.stringify(ListingAuthor.attributes));
		author= JSON.parse(author);;
	var manager = author.assignedManager;	
	var today = new Date();
	var query = new Parse.Query(AssetListing);
		query.get(listingID, { // we get the object
		success: function (instance) {
			//$("#cancel-buyer-agreement-btn").trigger('tap');
			//$("#cancel-seller-agreement-btn").trigger('tap');
			instance.set("sellerContractSent", false);
			instance.set("buyerContractSent", false);
			instance.set("wireInfoSent", false);
			instance.set("sellerDocId", "");
			instance.set("buyerDocId", "");
			instance.set("sellerSignatureRequestId", "");
			instance.set("buyerSignatureRequestId", "");
			instance.set("lastEditDate", today);
			instance.set("lastEditor", CurrentUser);
			instance.set("buyer",null);
			instance.set("soldForPrice", "");
			instance.set("totalCost", "");
			instance.set("saleComments", "");
			instance.set("status", "Active");
			instance.save({
				success: function(){
					alert("Sale Cancelled!");
					sendEmailNotification("Sale cancelled!", manager.username, cu.firstName+" "+cu.lastName+" has cancelled the current sale on stock number: "+listingObj.assetOwnerStockNumber, function(){

					});
					$('#confirm-cancel-pending-sale-dialog').dialog('close');
					$('#sale-pending-dialog').dialog('close');
					$('#pending-sale-details-dialog').dialog('close');

				}, error: function(newPost, error){
					console.log("File Save ERROR!:"+error.message);
				}	
			}); // we save it
			},error: function(error){
				console.log("Query error:"+error.message);	
			}
	});	
});

$(document).on('tap', "#cancel-pending-sale-cancel-btn", function(e){
	$('#confirm-cancel-pending-sale-dialog').dialog('close');
});
$(document).on('tap', "#view-contract-status-btn", function(e){
	console.log("View contract status");
	e.preventDefault();
	var listing = (JSON.stringify(SelectedAssetListing.attributes));
	listing= JSON.parse(listing);
	var viewingUser = (JSON.stringify(CurrentUser.attributes));
	viewingUser = JSON.parse(viewingUser);
	var buyerStatusOutput = "";
	var sellerStatusOutput = "";
		if (listing.buyerContractSent == false || listing.buyerContractSent == null){
			buyerStatusOutput = "<h3>Buyer contract status</h3><p>Contract sent: NO</p>";
			$(document).find("#buyer-contract-status-area").html(buyerStatusOutput);
			$(document).find("#send-buyer-agreement-btn").show();
		}
		if (listing.buyerContractSent == true){
			getBuyerContractStatus(listing.buyerSignatureRequestId);			
		}
		if (listing.isTitled == true && !listing.titleUploaded || listing.titleUploaded == false){
			$("#title-upload-dialog-btn").show();
			$("#view-title-btn").hide();
		}
		if (listing.isTitled == false  || listing.isTitled == null){
				$("#title-upload-dialog-btn").hide();
				$("#view-title-btn").hide();
		} 
		///check for title
		if (listing.titleUploaded == true ){
			$("#title-upload-dialog-btn").hide();
			$("#view-title-btn").show();
		}	
		if (listing.sellerContractSent == false || listing.sellerContractSent == null){
			sellerStatusOutput = "<h3>Owner contract status</h3><p>Contract sent: NO</p>";
			$(document).find("#seller-contract-status-area").html(sellerStatusOutput);
			$(document).find("#cancel-seller-agreement-btn").hide();
			if	(viewingUser.userType == "Super-Admin" || viewingUser.userType == "Developer"){
				$(document).find("#send-seller-agreement-btn").show();
			}
			if	(viewingUser.userType == "Admin" || viewingUser.userType == "Manager"){
				if (listing.titleUploaded == true || listing.isTitled == false){
					$(document).find("#send-seller-agreement-btn").show();
				}
			}
		}
		if (listing.sellerContractSent == true){
			$(document).find("#send-seller-agreement-btn").hide();
			getSellerContractStatus(listing.sellerSignatureRequestId);
		}
	$.mobile.changePage("#contract-status-dialog", {transition: 'pop', role: 'dialog'});
});

$(document).on('tap', "#update-buyer-notes-btn", function(e){
	var stringy = JSON.stringify(SelectedAssetListing.attributes);
	var listing = JSON.parse(stringy);
	var cost;
	var price;
	if(listing.buyerContractSent || listing.sellerContractSent != true){
		price = listing.soldForPrice;
		cost = listing.totalCost;
	}else{
		price = $('input[name=edit-purchase-price-field]').val();
		cost = $('input[name=edit-final-cost-field]').val();
	}
    var query = new Parse.Query(AssetListing);
	query.get(listingID, { // we get the object
		success: function (instance) {
		var customerQuery = new Parse.Query(Customer);
			customerQuery.include("user");
			customerQuery.equalTo("objectId", selectedCompany.objectId);
			customerQuery.first({
				success: function(item){
					if(listing.buyerContractSent || listing.sellerContractSent != true){
						instance.set("soldForPrice", price);
						instance.set("totalCost", cost);
					}
					if(listing.buyerContractSent || listing.sellerContractSent == true && $('input[name=edit-purchase-price-field]').val() != price || $('input[name=edit-final-cost-field]').val() != cost){
						alert("Price and cost can't be changed while contracts are active.");
						$('input[name=edit-purchase-price-field]').val(price);
						$('input[name=edit-final-cost-field]').val(cost);
					}
					instance.set("saleComments", $('textarea[name=edit-sale-comments-textarea]').val());
					instance.save({
						success: function(){
							alert("UNIT UPDATED!!!!");
							sendEmailNotification("Sale updated!", "sales@proxyequipment.com", "Stock number: "+listing.assetOwnerStockNumber+" "+listing.equipYear+" "+listing.equipMake+" "+listing.equipModel+" has been updated by "+viewingUser.firstName+" "+viewingUser.lastName+".", function(){
								//$('#pending-sale-details-dialog').dialog('close');
							});
						}, error: function(newPost, error){
							console.log("File Save ERROR!:"+error.message);
						}	
					}); // we save it
				},error: function(error){
					console.log("Query error:"+error.message);	
				}
			});
		}
	});
});
$(document).on('tap', "#update-owner-notes-btn", function(e){
	var stringy = JSON.stringify(SelectedAssetListing.attributes);
	var listing = JSON.parse(stringy);
	var viewingUser = (JSON.stringify(CurrentUser.attributes));
		viewingUser = JSON.parse(viewingUser);
	var cost;
	var price;
	if(listing.buyerContractSent || listing.sellerContractSent != true){
		price = listing.soldForPrice;
		cost = listing.totalCost;
	}else{
		price = $('input[name=edit-purchase-price-field]').val();
		cost = $('input[name=edit-final-cost-field]').val();
	}
    var query = new Parse.Query(AssetListing);
	query.get(listingID, { // we get the object
		success: function (instance) {
		var customerQuery = new Parse.Query(Customer);
			customerQuery.include("user");
			customerQuery.equalTo("objectId", selectedCompany.objectId);
			customerQuery.first({
				success: function(item){
					if(listing.buyerContractSent || listing.sellerContractSent != true){
						instance.set("soldForPrice", price);
						instance.set("totalCost", cost);
					}
					if(listing.buyerContractSent || listing.sellerContractSent == true && $('input[name=edit-purchase-price-field]').val() != price || $('input[name=edit-final-cost-field]').val() != cost){
						alert("Price and cost can't be changed while contracts are active.");
						$('input[name=edit-purchase-price-field]').val(price);
						$('input[name=edit-final-cost-field]').val(cost);
					}
					instance.set("purchaseComments", $('textarea[name=edit-purchase-comments-textarea]').val());
					instance.save({
						success: function(){
							alert("UNIT UPDATED!!!!");
							sendEmailNotification("Sale updated!", "sales@proxyequipment.com", "Stock number: "+listing.assetOwnerStockNumber+" "+listing.equipYear+" "+listing.equipMake+" "+listing.equipModel+" has been updated by "+viewingUser.firstName+" "+viewingUser.lastName+".", function(){
								//$('#pending-sale-details-dialog').dialog('close');
							});						
						}, error: function(newPost, error){
							console.log("File Save ERROR!:"+error.message);
						}	
					}); // we save it
				},error: function(error){
					console.log("Query error:"+error.message);	
				}
			});
		}
	});
});


$(document).on('tap', "#add-sale-note-btn", function(e){
	var comments = $('textarea[name=edit-sale-admin-comments-textarea]').val();
	var newPost = new SaleNote();
		newPost.set("user", CurrentUser);
		newPost.set("listing", SelectedAssetListing);
		newPost.set("message", comments);
		newPost.save({
			success: function(){
				$('textarea[name=edit-sale-admin-comments-textarea]').val("");
				alert("Note saved");
			}, error: function(newPost, error){
				console.log("File Save ERROR!:"+error.message);
			}	
		});
});

$(document).on('tap', "#view-sale-notes-btn", function(e){
	query = new Parse.Query(SaleNote);
	query.equalTo("listing", SelectedAssetListing);
	query.include("user");
	query.include("listing");
	query.include("message");
	query.find({
		success: function(results){
			$.mobile.changePage("#sale-notes-dialog", {transition: 'pop', role: 'dialog', notes: results});
		}, error: function(error){
			console.log(error.message);
		}
	});
});

$(document).on('tap', "#add-lead-note-btn", function(e){
	var comments = $('textarea[name=add-lead-note-textarea]').val();
	var newPost = new LeadNote();
		newPost.set("user", CurrentUser);
		newPost.set("lead", SelectedLead);
		newPost.set("message", comments);
		newPost.save({
			success: function(){
				$('textarea[name=add-lead-note-textarea]').val("");
				alert("Note saved");
			}, error: function(newPost, error){
				console.log("File Save ERROR!:"+error.message);
			}	
		});
});

$(document).on('tap', "#view-lead-notes-btn", function(e){
	query = new Parse.Query(LeadNote);
	query.include("user");
	query.include("lead");
	query.include("message");
	query.equalTo("lead", SelectedLead);
	query.find({
		success: function(results){
			$.mobile.changePage("#lead-notes-dialog", {transition: 'pop', role: 'dialog', notes: results});
		}, error: function(error){
			console.log(error.message);
		}
	});
});
$(document).on('tap', "#cancel-user-note-btn", function(e){
	$('#add-user-notes-dialog').dialog('close');
});
$(document).on('tap', "#save-user-note-btn", function(e){
	var comments = $('textarea[name=add-user-note-textarea]').val();
	var newPost = new UserNote();
		newPost.set("author", CurrentUser);
		newPost.set("user", SelectedUser);
		newPost.set("message", comments);
		newPost.save({
			success: function(){
				$('textarea[name=add-user-note-textarea]').val("");
				alert("Note saved");
				$('#add-user-notes-dialog').dialog('close');
			}, error: function(newPost, error){
				console.log("File Save ERROR!:"+error.message);
			}	
		});
});
$(document).on('tap', "#view-user-notes-btn", function(e){
	query = new Parse.Query(UserNote);
	query.include("user");
	query.include("author");
	query.include("message");
	query.equalTo("user", SelectedUser);
	query.find({
		success: function(results){
			$.mobile.changePage("#user-notes-dialog", {transition: 'pop', role: 'dialog', notes: results});
		}, error: function(error){
			console.log(error.message);
		}
	});
});

$(document).on('tap', "#complete-sale-btn", function(e){
	var today = new Date();
    var query = new Parse.Query(AssetListing);
	query.get(listingID, { // we get the object
		success: function (instance) {
			instance.set("status", "Sold");
			instance.set("dateSold", today);
			instance.save({
				success: function(){
					alert("UNIT SOLD!!!!");
    				$('#pending-sale-details-dialog').dialog('close');
					}, error: function(newPost, error){
						console.log("File Save ERROR!:"+error.message);
						}	
			}); // we save it
		}
	});
});
$(document).on('tap', "#generate-sale-tab", function(e){
	$('input[name=purchase-price-field]').val("");
	$('input[name=final-cost-field]').val("");
	$('textarea[name=sale-comments-textarea]').val("");
});
$(document).on('tap', "#new-titled-vehicle-confirmed-btn", function(e){
	console.log("titled vehicle confirmed");
	newListingIsTitled = true;
	$(":mobile-pagecontainer").pagecontainer( "change", "#new-listing");
	$('#new-titled-vehicle-confirmation-dialog').dialog('close');
});
$(document).on('tap', "#new-titled-vehicle-refused-btn", function(e){
	e.preventDefault();
	newListingIsTitled = true;
	$(":mobile-pagecontainer").pagecontainer( "change", "#new-listing");
	$('#new-titled-vehicle-confirmation-dialog').dialog('close');
});

$(document).on('tap', "#titled-vehicle-confirmed-btn", function(e){
	console.log("titled vehicle confirmed");
	SelectedAssetListing.set("isTitled", true);
	SelectedAssetListing.save({
		success: function(){
			$.mobile.changePage("#financing-confirmation-dialog", {transition: 'pop', role: 'dialog'});
			$('#titled-vehicle-confirmation-dialog').dialog('close');
		}, error: function(result, error){
			alert("File Save ERROR!:"+error.message);
		}	
	});
});
$(document).on('tap', "#titled-vehicle-refused-btn", function(e){
	e.preventDefault();
	SelectedAssetListing.set("isTitled", false);
	SelectedAssetListing.save({
		success: function(){
			$.mobile.changePage("#financing-confirmation-dialog", {transition: 'pop', role: 'dialog'});
			$('#titled-vehicle-confirmation-dialog').dialog('close');
		}, error: function(result, error){
			alert("File Save ERROR!:"+error.message);
		}	
	});
});

$(document).on('tap', "#financing-confirmed-btn", function(e){
	console.log("titled vehicle confirmed");
	SelectedAssetListing.set("proxyFinancing", true);
	SelectedAssetListing.save({
		success: function(){
			$.mobile.changePage("#sale-pending-dialog", {transition: 'pop', role: 'dialog'});
			$('#financing-confirmation-dialog').dialog('close');
		}, error: function(result, error){
			alert("File Save ERROR!:"+error.message);
		}	
	});
});
$(document).on('tap', "#financing-refused-btn", function(e){
	console.log("titled vehicle refused");
	SelectedAssetListing.set("proxyFinancing", false);
	SelectedAssetListing.save({
		success: function(){
			$.mobile.changePage("#sale-pending-dialog", {transition: 'pop', role: 'dialog'});
			$('#financing-confirmation-dialog').dialog('close');
		}, error: function(result, error){
			alert("File Save ERROR!:"+error.message);
		}	
	});
});

$(document).on('tap', "#new-release-btn", function(e){
    $( ":mobile-pagecontainer" ).pagecontainer( "change", "#new-release");
});

$(document).on('tap', '#go-to-admin', function(){
	var stringy = (JSON.stringify(CurrentUser.attributes));
	var u = JSON.parse(stringy);
	if (u.userType == "Admin" || u.userType == "Super-Admin" || u.userType == "Developer" || u.userType == "Manager"){
		$( ":mobile-pagecontainer" ).pagecontainer( "change", "#admin-panel" );
	}else{
		alert("Area restricted.");
	}
});
$(document).on('tap', "#view-my-reps", function(){
	var query = new Parse.Query(Users);
		query.equalTo("assignedManager", SelectedUser);
		query.equalTo(SelectedUser.toJSON().objectId);
		//query.notEqualTo("isSuspended",true);
		query.descending('lastName');
		query.find({
			success: function(results){
				results = results.reverse();
				var output = "";
				var outputTitle = "";
				if (results.length>0){
					outputTitle += "<h3>"+results.length+" Users</h3>";
					$('#user-listings-filter').show();
				}else{
					$('#user-listings-filter').hide();
					outputTitle += "<h3>No reps available</h3>";
				}
				for (var i in results){
			 		var city = results[i].get("city");
			 		var state = results[i].get("state");
			 		var proxyId = results[i].get("proxyID");
			 		var firstName = results[i].get("firstName");
			 		var lastName = results[i].get("lastName");
			 		var nameStatusLine = firstName+" "+lastName;
			 		if	(results[i].get("isSuspended")){
			 			nameStatusLine += " *Suspended*";
			 		}
			 		var phone = results[i].get("phone");
					var id = results[i].id;
					output += "<li is=\"listview-li\" id ="+id+" itemtype = \"user\">";
					output += "<a class=\"ui-btn-a ui-btn ui-btn-icon-right ui-icon-carat-r\" data-form=\"ui-btn-up-a\" data-swatch=\"a\" data-theme=\"a\">";
					output += "<img id=\"thumbnail-image\" class=\"ui-li-icon thumb-wrap\" style=\"float:left;width:80px;height:80px; vertical-align: middle;\" src=\"https://www.proxyequipment.com/images/silhouette.png\" is=\"image\">";
					output += "<span style=\"font-size: 16pt;\">"+nameStatusLine+"</span></br>";
					output += "<span style=\"font-size: 14pt;\">"+city+", "+state+"</span></br>";
					output += "<span style=\"font-size: 12pt;\">"+proxyId+"</span></p>";
					output += "</li>";
				}
			$("#user-listings").html(outputTitle);	
			$("#user-listings").html(output);	
			}, error: function(error){
				console.log("Query error:"+error.message);	
			}				
		});
});
function viewAllLeads(){
	$("#list-title").html("<h3>Loading, please stand by...</h3>");
	QueryStartDateString = "";
	var dateRanges = getDatesFromDaysBack(30);
	for (var z = 0; z < dateRanges.length; z++){
		var s = dateRanges[z].start;
			s = s.split("-").join("/");
		var e = dateRanges[z].end;
			e = e.split("-").join("/");	        
	}
	
	QueryStartDateString = dateRanges[dateRanges.length-1].start;
	var queryStartDate = new Date(QueryStartDateString);

	var query = new Parse.Query(Lead);
		query.include('user');
		query.limit(1000);
		query.greaterThanOrEqualTo("createdAt", queryStartDate);
		query.find({
			success: function(results){
			//results = results.reverse();
				var output = "";
				var outputTitle = "";
				if (results.length>0){
					outputTitle += "<h3>"+results.length+" Leads</h3>";
					$('#user-listings-filter').show();
				}else{
					$('#user-listings-filter').hide();
					outputTitle += "<h3>No leads available</h3>";
				}
			for (var i = 0; i < results.length; i++){
				var lead = JSON.stringify(results[i]);
				 	lead = JSON.parse(lead);
				var recipient = lead.user;	 		
				var subject = lead.subject;
				var contactName = lead.contactName;
				var contactPhone = lead.contactPhone;
				var contactEmail = lead.contactEmail;
				var custComment = lead.custComment;
				var isNew = lead.isNew;
				var status = "";
				if(isNew || isNew == null){
					status+="NEW! ";
				}else{
					status+="";
				}
				var saleDate = new Date(results[i].createdAt);
					saleDate = saleDate.toString();
				var id = results[i].id;
				output += "<li is=\"listview-li\" id ="+id+" itemtype = \"lead\">";
				output += "<a class=\"ui-btn-a ui-btn ui-btn-icon-right ui-icon-carat-r\" data-form=\"ui-btn-up-a\" data-swatch=\"a\" data-theme=\"a\">";
				output += "<span style=\"font-size: 16pt;\"><span style=\"font-size: 15pt; color:#65f23a; text-shadow: 1px 1px #000000;\">"+status+"</span>"+subject+"</span></br>";
				output += "<span>Rep: "+recipient.firstName+" "+recipient.lastName+"</span></br>";
				output += "<span style=\"font-size: 14pt;\">"+custComment+"</span></br>";
				output += "<span style=\"font-size: 14pt;\">"+contactName+"</span></br>";
				output += "<span style=\"font-size: 14pt;\">"+contactPhone+"</span></br>";
				output += "<span style=\"font-size: 14pt;\">"+contactEmail+"</span></br>";
				output += "<span style=\"font-size: 12pt;\">"+saleDate+"</span></br>";
				output += "</li>";
			}
			$("#user-listings-title").html(outputTitle);	
			$("#user-listings").html(output);
			$("#list-title").html(outputTitle);	
		}, error: function(error){
			console.log("Query error:"+error.message);	
		}
	});
}
function viewAllCustomers(){
	var query = new Parse.Query(Customer);
		query.limit(2000);
		query.descending('companyName');
		query.find({
			success: function(results){
				results = results.reverse();
				var output = "";
				var outputTitle = "";
				if (results.length>0){
					outputTitle += "<h3>"+results.length+" Customers</h3>";
					$('#user-listings-filter').show();
				}else{
					$('#user-listings-filter').hide();
					outputTitle += "<h3>No customers available</h3>";
				}
				customerArray = results;
			var output = "";
			for (var i = 0; i < results.length; i++){
				var stringy = JSON.stringify(results[i]);
				 	stringy = JSON.parse(stringy);
				var companyName = stringy.companyName;
				var contactFirstName = stringy.contactFirstName;
				var contactLastName = stringy.contactLastName;
				var contactPhone = stringy.companyPhone;
				var companyEmail = stringy.companyEmail;
				var address = stringy.companyAddress;
				var zip = stringy.companyZip;
				var city = stringy.companyCity;
				var state = stringy.companyState;
				var custId = stringy.companyID;
				var id = results[i].id;
				output += "<li is=\"listview-li\" itemtype = \"customer\" id ="+id+" coName=\""+companyName+"\" coAddress=\""+address+"\" coCity=\""+city+"\" coState=\""+state+"\" coZip=\""+zip+"\" contFirst=\""+contactFirstName+"\" contLast=\""+contactLastName+"\" contPhone=\""+contactPhone+"\" contEmail=\""+companyEmail+"\" coID=\""+custId+"\">";
				output += "<a class=\"ui-btn-a ui-btn ui-btn-icon-right ui-icon-carat-r\" data-form=\"ui-btn-up-a\" data-swatch=\"a\" data-theme=\"a\">";
				output += "<span style=\"font-size: 16pt;\">"+companyName+"</span></br>";
				output += "<span style=\"font-size: 14pt;\">"+address+"</span></br>";
				output += "<span style=\"font-size: 14pt;\">"+city+", "+state+"</span></br>";
				output += "<span style=\"font-size: 14pt;\">"+zip+"</span></br>";
				output += "<span style=\"font-size: 12pt;\">"+custId+"</span></br>";
				output += "</li>";
			}
			$("#list-title").html(outputTitle);
			$("#user-listings").html(output);	
			}, error: function(error){
				console.log("Query error:"+error.message);	
			}				
		});
}
$(document).on('tap', '#approve-listing-tab', function(){
	var query = new Parse.Query(AssetListing);
	query.get(listingID, { // we get the object
		success: function (instance) {
			instance.set("status", "Active"); // We update the returned object
			instance.save({
				success: function(){
					alert("Listing activated!");
					$.mobile.back();
					}, error: function(newPost, error){
						console.log("File Save ERROR!:"+error.message);
					}	
			}); // we save it
		}
	});
});	
$(document).on('tap', '#deactivate-listing-tab', function(){
	var query = new Parse.Query(AssetListing);
	query.get(listingID, { // we get the object
		success: function (instance) {
			instance.set("status", "Pending"); // We update the returned object
			instance.save({
				success: function(){
					alert("Listing de-activated!");
					$.mobile.back();
					}, error: function(newPost, error){
						console.log("File Save ERROR!:"+error.message);
						}	
			}); // we save it
		}
	});	
});
$(document).on('click', '#upload-csv-btn', function(){ 
    var fd = new FormData($("#fileinfo"));
    //fd.append("CustomField", "This is some extra data");
    $.ajax({
    	 url: '/WebApp/csv-upload.php',  
         type: 'POST',
         data: fd,
         success:function(data){
			console.log("Success!!");
              $('#output').html(data);
         },
         cache: false,
         contentType: false,
         processData: false
    });
});
$(document).on('tap', '#downloads-btn', function(e){
	e.preventDefault();
    $( ":mobile-pagecontainer" ).pagecontainer( "change", "#downloads");
});


function getDateFromYear(year){
	var dateString = "01/01/";
		dateString +=year;
		dateString +=" 02:00:00";
	var modelYear = new Date(dateString);
	return modelYear;
}

$("#list-posts").on("click", "li", function(event){
	//event.preventDefault();
	var found = false;
	var attributeID = $(this).attr("id");

	var query;
	query = new Parse.Query(AssetListing);
	query.equalTo("objectId", attributeID);
	query.include("user");
	query.include("buyer");
	query.include("seller");
	query.find({
		success: function(results){
			var id = results[0].id;
			ListingAuthor = results[0].get("user");
			listingID = id;
			Seller = results[0].get("seller");
			var title = results[0].get("equipModel");
			var sts = results[0].get("status");
			if	(sts == "Sale-Pending" || sts== "Sold"){
				Buyer = results[0].get("buyer");
			}
			var ad = results[0];
			SelectedAssetListing = results[0];
			var src = id;
		   	$( ":mobile-pagecontainer" ).pagecontainer( "change", "#listing-details", { foo: src, status: sts} );
		}, error: function(error){
			console.log(error.message);
		}
	});
});
$("#report-item-list").on("click", "li", function(event){
	//event.preventDefault();
	
	var sts = $(this).attr("status");
	var id = $(this).attr("id");
	var type = $(this).attr("type");
	if (type == "Lead" || type == "Team-Lead"){
		//getLeadById(id,function(lead){
			//SelectedLead = lead;
			//SelectedLeadRecipient = lead.get('user');
			$( ":mobile-pagecontainer" ).pagecontainer( "change", "#lead-details", {foo: id});
		//});
	}
	if (type == "Listing" || type == "Team-Listing"){
		getListingById(id,sts,function(){
   			$( ":mobile-pagecontainer" ).pagecontainer( "change", "#listing-details", { foo: id, status: sts} );
		});
	}	
});
function getLeadById(id, callback){
	console.log("Getting lead for id = "+id);
	var leadQuery;
		leadQuery = new Parse.Query(Lead);
		leadQuery.equalTo("objectId", id);
		leadQuery.include("user");
		leadQuery.include("assetListing");
		leadQuery.first({
			success: function(result){
				SelectedLead = result;
				console.log("Found lead = "+result);
				callback(result);
			}, error: function(error){
				console.log(error.message);
			}	
		});
}
function getListingById(id,status,callback){
	var query;
	query = new Parse.Query(AssetListing);
	query.equalTo("objectId", id);
	query.include("user");
	query.include("buyer");
	query.include("seller");
	query.first({
		success: function(result){
			ListingAuthor = result.get("user");
			listingID = id;
			Seller = result.get("seller");
			if (status == "Sale-Pending" || status == "Sold"){
				Buyer = result.get("buyer");
			}
			SelectedAssetListing = result;
			callback(result);
		}, error: function(error){
			console.log(error.message);
		}
	});
}
function getUserById(id,callback){
	var userQuery;
		userQuery = new Parse.Query(Users);
		userQuery.equalTo("objectId", attributeID);
		userQuery.include("user");
		userQuery.first({
			success: function(rep){
				callback(rep);
			}, error: function(error){
				console.log(error.message);
			}
		});
}
$("#customer-item-list").on("click", "li", function(event){
	//event.preventDefault();
	var attributeID = $(this).attr("id");
	var query;
	query = new Parse.Query(AssetListing);
	query.equalTo("objectId", attributeID);
	query.include("user");
	query.include("buyer");
	query.include("seller");
	query.first({
		success: function(listing){
			var id = listing.id;
			ListingAuthor = listing.get("user");
			listingID = id;
			Seller = listing.get("seller");
			Buyer = listing.get("buyer");
			var sts = listing.get("status");
			SelectedAssetListing = listing;
			var src = listingID;
			console.log("src = "+src+" status = "+sts);
		   	$( ":mobile-pagecontainer" ).pagecontainer( "change", "#listing-details", { foo: src, status: sts} );
		}, error: function(error){
			console.log(error.message);
		}
	});
});

$("#user-listings").on("click", "li", function(event){
	//event.preventDefault();
	var attributeID = $(this).attr("id");
	console.log("object id === "+attributeID);
	var coName = $(this).attr("coname");
	var city = $(this).attr("cocity");
	var state = $(this).attr("costate");
	var address = $(this).attr("coaddress");
	var zip = $(this).attr("cozip");
	var contFirst = $(this).attr("contfirst");
	var contLast = $(this).attr("contlast");
	var email = $(this).attr("contemail");
	var contPhone = $(this).attr("contphone");
	var ID = $(this).attr("coid");
	
	const type = $(this).attr("itemtype");
	
	if (type == "listing"){
		console.log("is a listing");
		var query = new Parse.Query(AssetListing);
		query.equalTo("objectId", attributeID);
		query.include("user");
		query.include("buyer");
		query.include("seller");
		query.first({
			success: function(listing){
				listingID = attributeID;
				ListingAuthor = listing.get("user");
				Seller = listing.get("seller");
				var sts = listing.get("status");
				if	(sts == "Sale-Pending" || sts== "Sold"){
					Buyer = listing.get("buyer");
				}
				SelectedAssetListing = listing;
				var src = attributeID;
				$( ":mobile-pagecontainer" ).pagecontainer( "change", "#listing-details", { foo: src, status: sts} );
			}, error:function(error){
				console.log(error.message);
			}
		});
	}
	if (type == "user"){
		console.log("is a user");
		var userQuery;
			userQuery = new Parse.Query(Users);
			userQuery.equalTo("objectId", attributeID);
			userQuery.include("user");
			userQuery.first({
				success: function(rep){
					selectedEqualsCurrentUser = false;
					SelectedUser = rep;
					loadUserProfile();
					//$( ":mobile-pagecontainer" ).pagecontainer( "change", "#index");
				}, error: function(error){
					console.log(error.message);
				}
			});	
	}
	if (type == "lead"){
		console.log("is a lead");
		var leadQuery;
			leadQuery = new Parse.Query(Lead);
			leadQuery.equalTo("objectId", attributeID);
			leadQuery.include("user");
			leadQuery.include("assetListing");
			leadQuery.first({
				success: function(lead){
					SelectedLead = lead;
					SelectedLeadRecipient = lead.get('user');
					SelectedLeadListing = lead.get('assetListing');
					SelectedAssetListing = SelectedLeadListing;
					ListingAuthor = SelectedLeadRecipient;
					var leadListingObj = JSON.stringify(SelectedLeadListing);
					leadListingObj = JSON.parse(leadListingObj);
					$( ":mobile-pagecontainer" ).pagecontainer( "change", "#lead-details", { foo: attributeID} );
				}, error: function(error){
						console.log(error.message);
					}	
				});
	}
	if (type == "customer"){
		console.log("is a customer");
		SelectedCustomerObject = {
		coID:ID,
		coName:coName,
		coCity:city,
		coState:state,
		coAddress:address,
		coZip:zip,
		contFirst:contFirst,
		contLast:contLast,
		contPhone:contPhone,
		email:email,
		objID:attributeID
		}
		$( ":mobile-pagecontainer" ).pagecontainer( "change", "#customer-profile");
	}
});
$("#my-listings").on("click", "li", function(event){
	//event.preventDefault();
	var id = $(this).attr("id");
	var query;
	query = new Parse.Query(AssetListing);
	query.equalTo("objectId", id);
	query.include("user");
	query.find({
		success: function(results){
			var title = results[0].get("equipModel");
			var user = results[0].get("user");
			var id = results[0].id;
			var src = id;
		   	$( ":mobile-pagecontainer" ).pagecontainer( "change", "#listing-details", { foo: src } );
		}, error: function(error){
			console.log(error.message);
		}
	});	
});
$("#inventory-listings").on("click", "li", function(event){
	console.log("item selected");
	//event.preventDefault();
	var attributeID = $(this).attr("id");
	var sts = $(this).attr("status");
	var query = new Parse.Query(AssetListing);
		query.equalTo("objectId", attributeID);
		query.include("user");
		query.include("buyer");
		query.include("seller");
		query.first({
			success: function(listing){
				listingID = attributeID;
				ListingAuthor = listing.get("user");
				Seller = listing.get("seller");
				var sts = listing.get("status");
				if	(sts == "Sale-Pending" || sts== "Sold"){
					Buyer = listing.get("buyer");
				}
				SelectedAssetListing = listing;
				var src = attributeID;
				$( ":mobile-pagecontainer" ).pagecontainer( "change", "#listing-details", { foo: src, status: sts} );
			}, error:function(error){
				console.log(error.message);
			}
		});
});
$("#user-listings").on("click", "li", function(event){
	//event.preventDefault();
	var found = false;
	var attributeID = $(this).attr("id");
	var itemtype = $(this).attr("objType");
	var sts = $(this).attr("status");

	if (itemtype == "user"){
		getUserById(attributeID, function(rep){
			SelectedUser = rep;
			$( ":mobile-pagecontainer" ).pagecontainer( "change", "#index");
		});
	}
	if (itemtype == "listing"){
		getListingById(attributeID,sts,function(){
			$( ":mobile-pagecontainer" ).pagecontainer( "change", "#listing-details", { foo: attributeID, status: sts} );
	 	});
	}
	if (itemtype == "lead"){
		$( ":mobile-pagecontainer" ).pagecontainer( "change", "#lead-details", {foo: attributeID} );
	}
});
/*
$("#list-users").on("click", "li", function(event){
	//event.preventDefault();
	var id = $(this).attr("id");
	var query;
	query = new Parse.Query(Users);
	query.equalTo("objectId", id);
	query.include("user");
	query.first({
		success: function(result){
			if	(result.username == CurrentUser.get("username")){
				selectedEqualsCurrentUser = true;
				SelectedUser = result;
				loadUserProfile();
			}else{
				selectedEqualsCurrentUser = false;
				SelectedUser = result;
				loadUserProfile();
			}
			//sessionStorage.setItem('selectedUser',results);
		   	$( ":mobile-pagecontainer" ).pagecontainer( "change", "#index");
			//updateUsersHeader();
		}, error: function(error){
			console.log(error.message);
		}
	});	
});
*/
$(document).on('tap', "#account-management", function(){
	SelectedUser = CurrentUser;
	loadUserProfile();
	$( ":mobile-pagecontainer" ).pagecontainer( "change", "#index");
});

$("#customer-list").on("click", "li", function(event){
	var coName = $(this).attr("coName");
	var city = $(this).attr("coCity");
	var state = $(this).attr("coState");
	var address = $(this).attr("coAddress");
	var zip = $(this).attr("coZip");

	var contFirst = $(this).attr("contFirst");
	var contLast = $(this).attr("contLast");
	var email = $(this).attr("contEmail");
	var contPhone = $(this).attr("contPhone");
	var ID = $(this).attr("coID");
	var objID = $(this).attr("id");
	SelectedCustomerObject = {
		coID:ID,
		coName:coName,
		coCity:city,
		coState:state,
		coAddress:address,
		coZip:zip,
		contFirst:contFirst,
		contLast:contLast,
		contPhone:contPhone,
		email:email,
		objID:objID
	}
	$( ":mobile-pagecontainer" ).pagecontainer( "change", "#customer-profile");
});

////title upload
function handleFiles(files) {
  	for (let i = 0; i < files.length; i++) {
	    const file = files[i];
	    if (!file.type.startsWith('image/')){ continue }
	    const img = document.createElement("img");
	    	img.classList.add("obj");
		    img.file = file;
		    img.style.cssText = 'width:100%;height:auto;';
		    var preview = document.getElementById("title-preview-area");
		    if (preview.children.length == 0){
		    	preview.appendChild(img);
		    	$("#title-file-select-btn").text("Select back image");
		    }else 
		    	if (preview.children.length == 1){
		    		preview.appendChild(img);
		    		$("#upload-title-btn").show();
		    		$("#reset-title-btn").show();
		    }else 
		    	if (preview.children.length == 2){
		    		alert("Can't have more than 2 sucka!!");
		    }
		const reader = new FileReader();
		    reader.onload = (function(aImg) { return function(e) { aImg.src = e.target.result; }; })(img);
		    reader.readAsDataURL(file);
	}
}

const fileSelect = document.getElementById("title-file-select-btn"),
  	fileElem = document.getElementById("fileElem");
	fileSelect.addEventListener("click", function (e) {
	  if (fileElem) {
	    fileElem.click();
	  }
}, false);
///////////////////

function loadFrontTitle(){
	var titleFrontObj = document.getElementById('title-preview-area').children[0];
	var frontImage = new Image();
		frontImage.src = titleFrontObj.src;
	
	var base64Front = getBase64ImageNewWay(frontImage.src, function (base64String){
		var frontFile = new Parse.File("title-front.jpg", { base64: base64String });
			frontFile.save({
	    	success: function(file) {
		        SelectedAssetListing.set("frontTitleImage", frontFile);
		        SelectedAssetListing.save(null, {
		            success: function() {
		                // Execute any logic that should take place after the object is saved.
		                alert('front image file created');
		                loadBackTitle();
		            },
		            error: function(error) {
		                // Execute any logic that should take place if the save fails.
		                // error is a Parse.Error with an error code and description.
		                alert('Failed to create new object, with error code: ' + error.description);
		            }
		        });
		    },
		    error: function(error) {
		        alert('Failed to save file: ' + error.description);
		    }
		});
	});
}
function loadBackTitle(){
	var titleBackObj = document.getElementById('title-preview-area').children[1];
	var backImage = new Image();
		backImage.src = titleBackObj.src;
		
	var base64Rear = getBase64ImageNewWay(backImage.src, function (base64String){
		var rearFile = new Parse.File("title-back.jpg", { base64: base64String });
			rearFile.save({
	    	success: function(file) {
		        SelectedAssetListing.set("backTitleImage", rearFile);
		        SelectedAssetListing.save(null, {
		            success: function() {
		                // Execute any logic that should take place after the object is saved.
		                alert('Back image file created');
		                setTitleUploadComplete();
		            },
		            error: function(error) {
		                // Execute any logic that should take place if the save fails.
		                // error is a Parse.Error with an error code and description.
		                alert('Failed to create new object, with error code: ' + error.description);
		            }
		        });
		    },
		    error: function(error) {
		        alert('Failed to save file: ' + error.description);
		    }
		});
    });
}
function setTitleUploadComplete(){
	console.log("title complete.");
	SelectedAssetListing.set("titleUploaded", true);
	SelectedAssetListing.save(null, {
        success: function() {
            // Execute any logic that should take place after the object is saved.
            alert('Title images successfully uploaded!');
            $("title-preview-area").empty();
            $("#title-upload-dialog").dialog('close');
            $("#title-upload-btn").hide();
            $("#view-title-btn").show();
        },
        error: function(error) {
            // Execute any logic that should take place if the save fails.
            // error is a Parse.Error with an error code and description.
            alert('Failed to create new object, with error code: ' + error.description);
        }
    });

}
$(document).on('tap', "#upload-title-btn", function(e){
    loadFrontTitle();
});

$(document).on('tap', "#view-title-btn", function(e){
	$(document).find("#title-preview-view-area").empty();	
	var frontImgFile = SelectedAssetListing.get("frontTitleImage");
	var backImgFile = SelectedAssetListing.get("backTitleImage");
	
	const frontImg = document.createElement("img");
		frontImg.style.cssText = 'width:100%;height:auto;';
		frontImg.src = frontImgFile.url();
	
	const backImg = document.createElement("img");
		backImg.style.cssText = 'width:100%;height:auto;';
		backImg.src = backImgFile.url();
		
	var preview = document.getElementById("title-preview-view-area");
		preview.appendChild(frontImg);
		preview.appendChild(backImg);
	$.mobile.changePage("#title-preview-dialog", {transition: 'pop', role: 'dialog'});
});

$(document).on('tap', "#dismiss-title-preview-btn", function(e){
	$('#title-preview-dialog').dialog('close');
	$("title-preview-view-area").empty();
});

///CSV Image IMPORT///
function importMTImages(){
	console.log("syncing images...");
	$.ajax({
        url: "/docs/MT.csv",
    	async: false,
    	success: function (csvd) {
	        data = $.csv.toArrays(csvd);    	
    },
    dataType: "text",
    complete: function () {
		for(var i = 0; i < data.length; i++){
  			(function (i) {
				setTimeout(function(){
				var obj = data[i];
				var query = new Parse.Query(AssetListing);
				query.include("user");
				query.equalTo("assetOwnerStockNumber", obj[25]);
				query.each(function(result){
					var object = JSON.stringify(result);
						object = JSON.parse(object);
					var createdDate = new Date(result.get("createdAt"));
					var changeDate = new Date("09/03/2019");
					var baseType = obj[0];
						baseType = baseType.split("_").join(" ");
						console.log("base type = "+baseType);
					if (obj[3] == "INACTIVE"){
						if (object.status == "Sold"){
							result.set("equipImgs",CSVtoArray(obj[59]));
							if (!obj[5]){
								result.set("equipType",Unknown);
							}else{
								result.set("equipType",obj[5]);
							}
							if (!obj[6]){
								result.set("equipMake","Unknown");
							}else{
								result.set("equipMake",obj[6]);
							}
							if (!obj[7]){
								result.set("equipModel","Unknown");
							}else{
								result.set("equipModel",obj[7]);
							}
							var adL = "";
							adL += obj[10]+", "+obj[11];
							result.set("equipBaseType",baseType);
							result.set("activationDate", obj[61]);
							result.set("adLocation", adL);
								result.save({
									success: function(){
										console.log("saved");
									}, error: function(newPost, error){
										console.log("File Save ERROR!:"+error.message);
									}	
								});
						}
						if (object.status == "Pending" || object.status == "Rejected"){
							/*
							console.log("base type = "+baseType);
							result.set("equipBaseType",baseType);
							result.set("equipMake",obj[6]);
							result.set("equipModel",obj[7]);
							result.set("activationDate", obj[33]);
							result.save({
								success: function(){
									console.log("saved");
									callback();
								}, error: function(newPost, error){
									console.log("File Save ERROR!:"+error.message);
								}	
							});
							*/
						}
						if (object.status == "Active"){
							result.set("status","Removed");
							result.set("equipBaseType",baseType);
							if (!obj[5]){
								result.set("equipType",Unknown);
							}else{
								result.set("equipType",obj[5]);
							}
							var adL = "";
							adL += obj[10]+", "+obj[11];
							result.set("adLocation", adL);
							//result.set("equipMake",obj[6]);
							//result.set("equipModel",obj[7]);
							//result.set("activationDate", obj[33]);
								result.save({
									success: function(){
										console.log("saved");
									}, error: function(newPost, error){
										console.log("File Save ERROR!:"+error.message);
									}	
								});
								console.log("Found active, removed stock number "+object.assetOwnerStockNumber+" "+object.equipYear+" "+object.equipMake+" "+object.equipModel);
						}
					}
					if (obj[3] == "ACTIVE"){
							if (object.status == "Sale-Pending"){
								//if (createdDate < changeDate){
									result.set("equipImgs",CSVtoArray(obj[59]));
									if (!obj[5]){
										result.set("equipType",Unknown);
									}else{
										result.set("equipType",obj[5]);
									}
									if (!obj[6]){
										result.set("equipMake","Unknown");
									}else{
										result.set("equipMake",obj[6]);
									}
									if (!obj[7]){
										result.set("equipModel","Unknown");
									}else{
										result.set("equipModel",obj[7]);
									}
									var adL = "";
										adL += obj[10]+", "+obj[11];
									result.set("adLocation", adL);
									result.set("equipDescription",obj[27]);
									result.set("equipBaseType",baseType);
									result.set("activationDate", obj[61]);
									result.save({
										success: function(){
											console.log("saved");
										}, error: function(newPost, error){
											console.log("File Save ERROR!:"+error.message);
										}	
									});
								//}
							}
							if (object.status == "Sold"){
								console.log("Found sold, but active on MT stock number "+object.assetOwnerStockNumber+" "+object.equipYear+" "+object.equipMake+" "+object.equipModel);
								//if (createdDate < changeDate){
									result.set("equipImgs",CSVtoArray(obj[59]));
									if (!obj[5]){
										result.set("equipType",Unknown);
									}else{
										result.set("equipType",obj[5]);
									}
									if (!obj[6]){
										result.set("equipMake","Unknown");
									}else{
										result.set("equipMake",obj[6]);
									}
									if (!obj[7]){
										result.set("equipModel","Unknown");
									}else{
										result.set("equipModel",obj[7]);
									}
									var adL = "";
										adL += obj[10]+", "+obj[11];
									result.set("adLocation", adL);
									result.set("equipBaseType",baseType);
									result.set("activationDate", obj[61]);
										result.save({
											success: function(){
												console.log("saved");
											}, error: function(newPost, error){
												console.log("File Save ERROR!:"+error.message);
											}	
										});
								//}
							}
							if (object.status == "Removed"){
								console.log("Found removed, but active on MT stock number "+object.assetOwnerStockNumber+" "+object.equipYear+" "+object.equipMake+" "+object.equipModel);
								//if (createdDate < changeDate){
									console.log("base type = "+baseType);
									result.set("equipImgs",CSVtoArray(obj[59]));
									if (!obj[5]){
										result.set("equipType","Unknown");
									}else{
										result.set("equipType",obj[5]);
									}
									if (!obj[6]){
										result.set("equipMake","Unknown");
									}else{
										result.set("equipMake",obj[6]);
									}
									if (!obj[7]){
										result.set("equipModel","Unknown");
									}else{
										result.set("equipModel",obj[7]);
									}
									var adL = "";
										adL += obj[10]+", "+obj[11];
									result.set("adLocation", adL);
									result.set("equipBaseType",baseType);
									result.set("activationDate", obj[61]);
										result.save({
											success: function(){
												console.log("saved");
											}, error: function(newPost, error){
												console.log("File Save ERROR!:"+error.message);
											}	
										});
								//}
							}
							if (object.status == "Active"){
								
								if (!obj[53]){
									result.set("equipPrice","0");
								}else{
									result.set("equipPrice",obj[46]);
								}
								
								result.set("equipImgs",CSVtoArray(obj[59]));
								if (!obj[5]){
									result.set("equipType","Unknown");
								}else{
									result.set("equipType",obj[5]);
								}
								if (!obj[6]){
									result.set("equipMake","Unknown");
								}else{
									result.set("equipMake",obj[6]);
								}
								if (!obj[7]){
									result.set("equipModel","Unknown");
								}else{
									result.set("equipModel",obj[7]);
								}
								var adL = "";
									adL += obj[10]+", "+obj[11];
								result.set("adLocation", adL);
								result.set("equipDescription",obj[27]);
								result.set("equipBaseType",baseType);
								result.set("activationDate", obj[61]);
									result.save({
										success: function(){
											console.log("saved");
										}, error: function(newPost, error){
											console.log("File Save ERROR!: Stock#: "+obj[25]+" error:"+error.message);
										}	
									});
							}
							if (object.status == "Pending" || object.status == "Rejected"){
								
								//console.log("base type = "+baseType);
								//result.set("equipBaseType",baseType);
								//result.set("equipMake",obj[6]);
								//result.set("equipModel",obj[7]);
								//result.set("activationDate", obj[33]);
								//result.save({
									//success: function(){
										//console.log("saved");
										//callback();
									//}, error: function(newPost, error){
										//console.log("File Save ERROR!:"+error.message);
									//}	
								//});
							}
					}
					//result.set("equipPrice",obj[30]);
					//result.set("equipDescription", obj[24]);
				}).then(function() {
					console.log("Finished!");
				}, function(err) {
				  console.log(err);
				});
			},i*100)}).call(this, i);
		}
	}
	});
}


$('#sync-MT-DB').on('tap', function(e){
	$.ajax({
        url: "/docs/MT.csv",
    async: false,
    success: function (csvd) {
        data = $.csv.toArrays(csvd);    	
    },
    dataType: "text",
    complete: function () {
		for(var i = 1; i < data.length; i++){
  			(function (i) {
				var obj = data[i];
				var query = new Parse.Query(AssetListing);
				query.include("user");
				query.equalTo("assetOwnerStockNumber", obj[22]);
				query.find({
					success: function(results){
						if	(results.length == 0){
							var newPost = new AssetListing();
							newPost.set("status", "Active");
							//newPost.set("user", CurrentUser);
							newPost.set("assetOwnerFirstName", "Perry");
							newPost.set("assetOwnerLastName", "Kirkwood");
							newPost.set("assetOwnerContactPhone", obj[15]);
							newPost.set("assetOwnerContactEmail", "p.kirkwood@proxyequipment.com");
							newPost.set("assetOwnerStockNumber", obj[22]);		
							newPost.set("equipType", obj[5]);
							newPost.set("equipMake", obj[6]);
							newPost.set("equipModel", obj[7]);
							newPost.set("equipYear", obj[19]);
							newPost.set("equipHours", obj[49]);
							newPost.set("equipMileage", obj[120]);
							newPost.set("equipSerial", obj[21]);
							newPost.set("equipVIN", obj[21]);
							newPost.set("equipLocation", obj[11]);
							newPost.set("equipPrice", obj[30]);
							//newPost.set("equipCost", equipCost);
							newPost.set("equipDescription", obj[24]);
							newPost.set("equipImgs",CSVtoArray(obj[37]));
							newPost.save({
								success: function(){
									console.log("Imported");
								}, error: function(newPost, error){
									console.log("File Save ERROR!:"+error.message);
								}	
							})
						}	
					}, error: function(error){
					console.log("Query error:"+error.message);	
					}				
				});
 			 }).call(this, i);
		}
	}
	});
});
function returnRepsForManager(manager){
	var query = new Parse.Query(Users);
		query.equalTo("assignedManager", manager);
		query.equalTo(manager.toJSON().objectId);
		//query.notEqualTo("isSuspended",true);
		query.descending('lastName');
		query.find({
			success: function(results){
				results = results.reverse();
				return results;

			}, error: function(error){
				console.log("Query error:"+error.message);	
			}				
		});
};

function loadUserProfile(){
	$("#user-listings").empty();
	$("#list-title").empty();
	var firstName = "";
	var lastName = "";
	var viewingUser = (JSON.stringify(CurrentUser.attributes));
		viewingUser = JSON.parse(viewingUser);	
	if (SelectedUser == CurrentUser){
		$("#view-user-notes-btn").hide();
		$("#add-user-notes-btn").hide();

		userID = CurrentUser.toJSON().objectId;
		firstName = CurrentUser.get("firstName");
		lastName = CurrentUser.get("lastName");
		city = CurrentUser.get("city");
		state = CurrentUser.get("state");
		phone = CurrentUser.get("phone");
		username = CurrentUser.get("username");
		SelectedUser = CurrentUser;
	}else{
		if (SelectedUser != CurrentUser){	
			$("#view-user-notes-btn").show();
			$("#add-user-notes-btn").show();

			$("#user-options-btn-area").show();
			var selUser = SelectedUser;
				selUser = JSON.stringify(selUser);
				selUser = JSON.parse(selUser);
			 	userID = selUser.objectId;
			 	firstName = selUser.firstName;
				lastName = selUser.lastName;
				city = selUser.city;
				state = selUser.state;
				phone = selUser.phone;
				phone = phone.slice(0,3)+"-"+phone.slice(3,6)+"-"+phone.slice(6);
				username = selUser.username;
		}
	}
	$("#user-options-btn").text(firstName+" "+lastName);
	var su = JSON.stringify(SelectedUser.attributes);
		su= JSON.parse(su);
	var btnOutput = "";
		btnOutput += "<fieldset class=\"ui-grid-s\">";
		btnOutput += "<div class=\"ui-block-a\"><a href=\"tel:+1"+su.phone+"\" class=\"ui-btn ui-btn-corner-all ui-icon-phone ui-btn-icon-left ui-shadow ui-mini\" data-role=\"button\" role=\"button\">Call "+su.phone+"</a></div>";
		btnOutput += "<div class=\"ui-block-b\"><a href=\"mailto:"+su.username+"\" class=\"ui-btn ui-btn-corner-all ui-icon-mail ui-btn-icon-left ui-shadow ui-mini\" data-role=\"button\" role=\"button\">Email "+su.firstName+"</a></div>";
		btnOutput += "<div class=\"ui-block-c\"><a href=\"#user-settings-dialog\" id=\"user-settings-btn\" data-rel=\"dialog\" class=\"ui-btn ui-btn-a ui-mini ui-shadow ui-btn-corner-all ui-icon-gear ui-btn-icon-notext\" data-role=\"button\" data-theme=\"a\">Settings</a></div>";
		btnOutput += "</fieldset>";

	$("#user-options-btn-area").html(btnOutput);

	//$('#user-display-select-button').text("Select another user");
	$("#user-item-display-select-button").text("Select items to display");
	updateUserSelectDropdown();
	if (viewingUser.userType == "Super-Admin" || viewingUser.userType == "Admin" || viewingUser.userType == "Developer" || viewingUser.userType == "Manager"){
		//$("#user-item-display-select-button").text("Select items to display");		
		/*
		$("#profile-call-btn").attr("href", "tel:+1"+phone);
		$("#profile-call-btn").text(phone);
		
		$("#profile-email-btn").attr("href", "mailto:"+username+"?subject=\""+viewingUser.firstName+" from Proxy Equip.");				
		$("#new-listing-btn").hide();
		$("#manage-customer-btn").hide();
				
		if (viewingUser.userType == "Manager" || viewingUser.userType == "Admin" || viewingUser.userType == "Super-Admin" || viewingUser.userType == "Developer" ){
			$("#get-leads-for-user-btn").show();
			$("#manage-customer-btn").show();
			$("#go-to-admin").show();
		}else{
			$("#get-leads-for-user-btn").hide();
		}
		$("#profile-call-btn").show();
		$("#profile-email-btn").show();
		*/
	}else{
		//$("#user-display-select").hide();
		/*
		$("#profile-call-btn").hide();
		$("#profile-email-btn").hide();
		$("#new-listing-btn").show();
		$("#manage-customer-btn").show();
		$("#get-leads-for-user-btn").show();
		*/
	}
	/*
	var output = "";
		output += "<p>"+firstName+" "+lastName+"</br>"+city+", "+state+"</p></span>";
		
	$("#user-info").html(output);
	
	var listingBtnArray = document.getElementsByName("get-listings-for-user-btn");
	
	for (var i = 0; i < listingBtnArray.length; i++) {
		var btn = listingBtnArray[i].setAttribute("data-userid", userID);
	}
	*/
			 		
	
}

$('#user-lead-fwd-select').change(function(event) {
    var $option = $(this).find('option:selected');
    var value = $option.val(); //returns the value of the selected option.
	//$('input[name=equipType]').val(text);
});
$("#user-contract-status-btn").on('tap', function(event){
	var su = JSON.stringify(SelectedUser.attributes);
		su= JSON.parse(su);
	if (su.repSignatureRequestId != null){
		console.log("Getting contract status for "+su.firstName+" "+su.lastName);
		getRepContractStatus(su.repSignatureRequestId);
	}else{
		console.log("no ID");
		var repStatusOutput ="";
		repStatusOutput = "<h3>Rep contract status not available.</h3>";
		$(document).find("#rep-contract-status-area").html(repStatusOutput);
		$('#send-user-contract-btn').text("Send rep contract");
		$('#send-user-contract-btn').show();
	}
	$.mobile.changePage("#rep-contract-status-dialog", {transition: 'pop', role: 'dialog'});
});
$("#activate-new-user-btn").on('tap', function(event){
	$(".dialog-view-area").LoadingOverlay("show");
	event.preventDefault();
	var today = new Date();
	var u = JSON.stringify(SelectedUser.attributes);
		u = JSON.parse(u);

	var assMan = u.assignedManager;
	console.log("selected user = "+SelectedUser);
	SelectedUser.set("contractStatus","Active");
	SelectedUser.set("contractComplete",true);
	SelectedUser.set("signOnDate",today);
	SelectedUser.save({
		success: function(){
			console.log("User activated, prepare email to "+u.personalEmail);
			//sendRepContract();
		}, error: function(newPost, error){
			console.log("File Save ERROR!:"+error.message);
		}	
	}, {useMasterKey:true},
	);
	sendEmailNotification("Welcome aboard "+u.firstName, u.personalEmail, "Dear "+u.firstName+",\nThank you for your interest in working with Proxy Equipment and WELCOME! We invite you to take advantage of our website https://www.proxyequipment.com as it will give you an idea of who we are, what we are all about, and where we are headed!\n\nSummary: Proxy Equipment is engaged in the marketing and sale of used heavy construction equipment, used agricultural equipment, used forestry equipment, heavy-duty trucks & trailers, and other related products to the industry.\n\nGETTING STARTED\n\n1. Access our website by going to https://www.proxyequipment.com \n\n2. Click on the white arrow in the top, right corner of your screen to begin logging in to the backside of our site/control panel.\n\n3. LOGIN WITH:\nEMAIL: "+u.username+"\nPASSWORD: "+u.firstName+"2020\n**CASE SENSITIVE**\n\n4. CLICK ON MENU IN THE TOP LEFT CORNER TO ACCESS WEB TOOLS, EMAIL, FIELD MANUAL, TRAINING VIDEOS, INSPECTION FORMS, EQUIPMENT GUIDES AND MORE.\n\nOnce your first piece of equipment has sold, a commission will be paid on the \"Net Profit\" to you as the Independent Sales Contractor. This is when we will require you to complete a W-9 Tax Form and provide us with your banking information to receive payment by Direct Deposit (ACH).\nIf you have any questions or need additional information, we are happy to assist. Please do not hesitate to contact us by email, phone, or text.\n\nCurrent point of Contacts:\nRegional Mgr:"+assMan.firstName+" "+assMan.lastName+"\nPhone: "+assMan.phone+"\nEmail: "+assMan.username+"\n\nDavid Shiflett\nPhone: 850-417-5235\nEmail: d.shiflett@proxyequipment.com\n\nPerry Kirkwood\nPhone:225-572-2899\nEmail: p.kirkwood@proxyequipment.com\n\nBUSINESS CARDS\n"+u.firstName+", click this link to order business cards https://proxyequipment.go.customprintcenter.com/",function(){
		alert("Welcome aboard email sent!");
		$(".dialog-view-area").LoadingOverlay("hide");
		$('#rep-contract-status-dialog').dialog("close");
		addEmailAddress(u.firstName,u.lastName,u.username);
	});
});

$("#confirm-user-delete-btn").on('tap', function(event){
	var su = JSON.stringify(SelectedUser.attributes);
		su= JSON.parse(su);

	SelectedUser.set("status","Pending-Delete");
	SelectedUser.save({
		success: function(){
			console.log("Saved");
			sessionStorage.setItem('changingManager',"false");
		}, error: function(newPost, error){
			console.log("File Save ERROR!:"+error.message);
		}	
	}, {useMasterKey:true},
	);
});
$("#save-user-settings-btn").on('tap', function(event){
	var selMan = SelectedManager;
		selMan = JSON.stringify(selMan);
		selMan = JSON.parse(selMan);
		attributeID = selMan.objectId;
	var rep = SelectedUser;
		rep = JSON.stringify(rep);
		rep = JSON.parse(rep);
	var you = CurrentUser;
		you = JSON.stringify(you);
		you = JSON.parse(you);
	var pe = $('input[id=edit-personalemailsetup]').val();
	var p = $('input[id=edit-phonesetup]').val();
	var s = $('input[id=edit-streetsetup]').val();
	var c = $('input[id=edit-citynamesetup]').val();
	var z = $('input[id=edit-zipsetup]').val();
		z = z.trim();
	var f = $('select[name=user-lead-fwd-select] option:selected').val();
	var g = $('select[name=user-suspension-select] option:selected').val();
	var gg = false;
	if (g == "on"){
		gg=true;
	}
	var b = false;
	if (f == "on"){
		b=true;
	}
	if (p.length != 10){
		alert("Please enter a valid 10 digit phone number.");
		return false;
	}else 
		if (s.length < 8){
			alert("Please enter a valid address.");
			return false;
	}else
		if (c.length < 3){
			alert("Please enter a valid city.");
			return false;
	}else
		if (z.length != 5){
			alert("Please enter a valid zip code.");
			return false;
	}else
		if (gg != rep.isSuspended && rep.isSuspended){
			sendEmailNotification("Rep suspended", "sales@proxyequipment.com", ""+rep.firstName+" "+rep.lastName+" has been suspended by "+you.firstName+" "+you.lastName+".", function(){

			});
		}
		$('#user-settings-dialog').dialog("close");
		SelectedUser.set("phone",p);
		SelectedUser.set("personalEmail",pe);
		SelectedUser.set("streetAddress",s);
		SelectedUser.set("city",c);
		SelectedUser.set("zipCode",z);
		SelectedUser.set("leadForwarding",b);
		SelectedUser.set("isSuspended",gg);
		SelectedUser.set("assignedManager",{ "__type": "Pointer", "className": "_User", "objectId": attributeID });
		SelectedUser.save({
			success: function(){
				console.log("Saved");
				sessionStorage.setItem('changingManager',"false");
			}, error: function(newPost, error){
				console.log("File Save ERROR!:"+error.message);
			}	
		}, {useMasterKey:true},
		);
});
$(document).on('pagecontainerbeforeshow', function() {
    var activePage = $.mobile.pageContainer.pagecontainer("getActivePage");
   	$('[id="utility-bar"] ul:first', activePage).each(function(){
       var ul = this;
       var as = $('a', ul);
       $(as).click(function(){
       $(as).removeClass('ui-btn-active');
       $(this).addClass('ui-btn-active');
     });
       $(as).first().click();
     });
});

$("#launch-comp-search-btn").on('tap', function(e){
	cleanupCompSearchV3();
});
////dialog cleanup functions/////
function cleanupCompSearchV3(){
	$("#auction-avg-result-container").empty();
	$("#auction-container-collapsible").hide();
	$("#comp-search-status-message").empty();
	$("#run-v3-comps-btn").hide();

	// hide/reset buttons ///
	$("#auction-model-year-select-button span").text("Year");
	$("#auction-make-select-button span").text("Select category");
	$("#auction-make-select-button").hide();
	$("#auction-make-select-button span").text("Select make");
	$("#auction-model-select-button").hide();
	$("#auction-model-select-button span").text("Select model");
};

// ------------------------------------------------------ HOME PAGE CREATE------- //
$('#index').on('pagecontainerbeforechange', function (pageEvent) {
	if (CurrentUser) {
		//$('#welcome-msg').html("Welcome back, " + CurrentUser.getUsername());
		//$("#all-active-listings").trigger('tap');
	}else{			
    	$(":mobile-pagecontainer" ).pagecontainer( "change", "#signin" );
    }
});
$('#index').on('pageshow', function (pageEvent) {
	// if the user is logged in update the content.
	//var c = JSON.stringify(CurrentUser.attributes);
		//c = JSON.parse(c);
	if (CurrentUser ) {
		if	(CurrentUser != SelectedUser){
			$("#go-to-you-btn").show();
			$("#user-options-btn-area").show();
			//$("#view-user-notes-btn").show();
			$("#user-settings-button").hide();
			$("#new-listing-btn").hide();
		}else{
			$("#user-options-btn-area").hide();
			$("#go-to-you-btn").hide();
			//$("#view-user-notes-btn").hide();
		}
		//loadUserProfile();
		/*
		if (SelectedUser != CurrentUser){
			$("#left-nav-button").attr("href","javascript:history.go(-1)");
			$("#left-nav-button").attr("data-transition","slide");
			$("#left-nav-button").attr("data-direction","reverse");
			$("#left-nav-button").text("Back");
			$("#left-nav-button").removeClass("ui-icon-bars");
			$("#left-nav-button").addClass("ui-icon-arrow-l");
		}else{
			$("#left-nav-button").attr("href","#index-panel-01");
			$("#left-nav-button").removeAttr("data-direction","reverse");
			$("#left-nav-button").text("Menu");
			$("#left-nav-button").removeClass("ui-icon-arrow-l");
			$("#left-nav-button").addClass("ui-icon-bars");
		}
		*/
	}else{			
	// If the user is not logged in, ask them to log in.
    	$( ":mobile-pagecontainer" ).pagecontainer( "change", "#signin" );
	}
});
// ------------------------------------------------------ User Profile PAGE CREATE------- //
$(document).on("pageinit", "#index", function (pageEvent) {
	sessionStorage.clear();
	// if the user is logged in update the content.
	if (CurrentUser) {
		var c = JSON.stringify(CurrentUser.attributes);
			c = JSON.parse(c);
			if (c.userType == "Manager" || c.userType == "Admin" || c.userType == "Super-Admin" || c.userType == "Developer"){
				$("#add-new-user").show();
			}
			if (c.userType == "Developer"){
				$("#sync-images-btn").show();
			}
		loadUserProfile();
		returnVersion();
	}else{			
	// If the user is not logged in, ask them to log in.
    	$( ":mobile-pagecontainer" ).pagecontainer( "change", "#signin");
	}
});


$('#user-options-dialog').on('pageshow', function (pageEvent) {
	var su = JSON.stringify(SelectedUser.attributes);
		su= JSON.parse(su);
	var viewingUser = (JSON.stringify(CurrentUser.attributes));
		viewingUser = JSON.parse(viewingUser);
	//var startDate = formatDateNoTime(su.createdAt);
	var btnOutput = "";
		btnOutput += "<fieldset class=\"ui-grid-b\">";
		btnOutput += "<div class=\"ui-block-a\"><a href=\"tel:+1"+su.phone+"\" class=\"ui-btn ui-btn-corner-all ui-icon-phone ui-btn-icon-left ui-shadow ui-mini\" data-role=\"button\" role=\"button\">Call</a></div>";
		btnOutput += "<div class=\"ui-block-b\"><a href=\"mailto:"+su.username+"\" class=\"ui-btn ui-btn-corner-all ui-icon-mail ui-btn-icon-left ui-shadow ui-mini\" data-role=\"button\" role=\"button\">Email</a></div>";
		//salesmanOutput += "<div class=\"ui-block-c\"><a href=\"javascript:void(0)\" id=\"send-sms\" smsTo=\"+1"+salesmanPhone+"\" class=\"ui-btn ui-btn-corner-all ui-icon-mail ui-btn-icon-left ui-shadow\" data-role=\"button\" role=\"button\">Text</a></div>";
		btnOutput += "</fieldset>";
	var output = "";
		output += "<p>"+su.firstName+" "+su.lastName+"</p>";
	$("#edit-user-manager-select-button span").text(su.assignedManager.firstName+" "+su.assignedManager.lastName); 
	$("#user-options-info-area").html(output);
	$("#user-options-btn-area").html(btnOutput);
});	

$('#reports').on('pageinit', function (pageEvent) {
	// if the user is logged in update the content.
	if (CurrentUser) {
		SelectedUser = CurrentUser;
		var viewingUser = (JSON.stringify(CurrentUser.attributes));
			viewingUser = JSON.parse(viewingUser);
		if (viewingUser.userType == "Super-Admin" || viewingUser.userType == "Admin" || viewingUser.userType == "Developer"){
			$("#base-report-type-segment").show();
			$("#user-reports-btn").show();
			$("#team-reports-btn").show();
			$("#admin-reports-btn").show();
	 	}else if (viewingUser.userType == "Manager"){
			$("#base-report-type-segment").show();
			$("#user-reports-btn").show();
			$("#team-reports-btn").show();
		}else{
		 	$("#init-chart-btn").attr("base-type","user");
			updateUserReportListDropdown();
			$("#base-report-type-segment").hide();
 			$("#primary-report-type-select").show();
 			}
	 }else{			
	// If the user is not logged in, ask them to log in.
    	$(":mobile-pagecontainer" ).pagecontainer( "change", "#signin" );
    }
});


// ------------------------------------------------------ MANAGE CUSTOMERS PAGE INIT------- //
$(document).on("pageinit", "#manage-customers", function (pageEvent) {
	// if the user is logged in update the content.
	if (CurrentUser) {
		$("#get-customers-for-user-btn").trigger('tap');
	}else{			
	// If the user is not logged in, ask them to log in.
    	$(":mobile-pagecontainer" ).pagecontainer( "change", "#signin" );
	}
});
/*
$(document).on("pageinit", "#manage-leads", function (pageEvent) {
	// if the user is logged in update the content.
	if (CurrentUser) {
		$("#get-leads-for-user-btn").trigger('tap');
	}else{			
	// If the user is not logged in, ask them to log in.
    	$( ":mobile-pagecontainer" ).pagecontainer( "change", "#signin" );
	}
});
*/
$(document).on("pageinit", "#create-lead-dialog", function (pageEvent) {
	// if the user is logged in update the content.
	if (CurrentUser) {
		$("#lead-name-field").val("");
		$("#lead-phone-field").val("");
		$("#lead-email-field").val("");
		$("#lead-comment-textarea").val("");
	}else{			
	// If the user is not logged in, ask them to log in.
    	$( ":mobile-pagecontainer" ).pagecontainer( "change", "#signin" );
	}
});

$(document).on("pageinit", "#edit-listing-warning-dialog", function (pageEvent) {
	// if the user is logged in update the content.
	if (CurrentUser) {
		$("#edit-listing-admin-comment").val("");
	}else{			
		// If the user is not logged in, ask them to log in.
    	$( ":mobile-pagecontainer" ).pagecontainer( "change", "#signin" );
	}
});
$(document).on("pageinit", "#remove-listing-warning-dialog", function (pageEvent) {
	// if the user is logged in update the content.
	if (CurrentUser) {
		$("#remove-listing-admin-comment").val("");		
	}else{			
		// If the user is not logged in, ask them to log in.
    	$( ":mobile-pagecontainer" ).pagecontainer( "change", "#signin" );
	}
});
$(document).on("pageinit", "#reject-listing-warning-dialog", function (pageEvent) {
	// if the user is logged in update the content.
	if (CurrentUser) {
		$("#reject-listing-admin-comment").val("");		
	}else{			
		// If the user is not logged in, ask them to log in.
    	$( ":mobile-pagecontainer" ).pagecontainer( "change", "#signin" );
	}
});
$(document).on("pageshow", "#contract-status-dialog", function (pageEvent) {
	// if the user is logged in update the content.
	if (CurrentUser) {
				
	}else{			
		// If the user is not logged in, ask them to log in.
    	$( ":mobile-pagecontainer" ).pagecontainer( "change", "#signin" );
	}
});
// ------------------------------------------------------ NEW LISTING PAGE CREATE------- //
$(document).on("pageinit", "#new-listing", function (pageEvent) {
	// if the user is logged in update the content.
	if (CurrentUser) {
		updateCustomerListDropdown();
		selectedCompany = {};
	var dateArray = new Array();
	for (var i = 1930; i < 2022; i++){
		var obj = {
			value:i.toString(),
			text:i.toString()
		}
		dateArray.push(obj);
	}
	dateArray.reverse();
	createUlEleFromArrayOfObjs(dateArray,"new-listing-date-select", function (select){
		$("#new-listing-year-select-dialog-menu").replaceWith(select);
	});
	$("#new-listing-category-select-button").hide();
	$("#new-listing-make-select-button").hide();
	$("#new-listing-model-select-button").hide();
	$("#new-listing-category-select-button span").text("Select a category");
	createUlEleFromArrayOfObjs(auctionV3Categories,"new-listing-category-select", function (cats){
		$("#new-listing-category-select-dialog-menu").replaceWith(cats);
	});
	createUlEleFromArrayOfObjs(auctionV3Manufacturers,"new-listing-make-select", function (makes){
		$("#new-listing-make-select-dialog-menu").replaceWith(makes);
	});
	}else{			
		// If the user is not logged in, ask them to log in.
    	$( ":mobile-pagecontainer" ).pagecontainer( "change", "#signin" );
	}
});
// ------------------------------------------------------ Listing details PAGE CREATE------- //

$(document).on("pageinit", "#listing-details", function (pageEvent) {
	// if the user is logged in update the content.
	if (CurrentUser) {
	}else{			
	// If the user is not logged in, ask them to log in.
    	$( ":mobile-pagecontainer" ).pagecontainer( "change", "#signin" );
	}
});
$(document).on("pageinit", "#proxy-inventory", function (pageEvent) {
	if (CurrentUser) {
		var dateArray = new Array();
		for (var i = 1930; i < 2021; i++){
			var obj = {
				value:i.toString(),
				text:i.toString()
			}
			dateArray.push(obj);
		}
		dateArray.reverse();
		createUlEleFromArrayOfObjs(dateArray,"detailed-search-year-select", function (select){
			$("#detailed-search-year-select-dialog-menu").replaceWith(select);
		});
		getAvailableInventoryTypes();
		//updateEquipBaseTypeSelect();
		//updateEquipModelSelect();
	}else{			
	// If the user is not logged in, ask them to log in.
    	$( ":mobile-pagecontainer" ).pagecontainer( "change", "#signin" );
	}

});
$(document).on("pageshow", "#edit-user-manager-select-dialog", function (pageEvent) {
	console.log("Get them managers!");
	getAllManagers(function(members){
		var output = "";
		var xOutput = "";
		output += "<div class=\"ui-select\">";
		output += "<select name=\"edit-user-manager-select\" id=\"edit-user-manager-select\" data-native-menu=\"false\" tabindex=\"-1\">";
		for (var i = 0; i < members.length; i++) {
			console.log("Found "+members.length+" managers");
			var stringy = JSON.stringify(members[i]);
			var memberObj = JSON.parse(stringy);
			output += "<option value=\"1\">"+memberObj.firstName+" "+memberObj.lastName+"</option>";
			xOutput += "<li data-option-index=\""+i+"\" data-icon=\"false\" data-id="+memberObj.objectId+" objType=\"user\" class role=\"option\" aria-selected=\"false\">";
			xOutput += "<a href=\"#\" tabindex=\"-1\" class=\"ui-btn\">"+memberObj.firstName+" "+memberObj.lastName+"";
		}	
		output += "</select>";
		output += "<div style=\"display:none;\" id=\"edit-user-manager-select-listbox-placeholder\"><!---Placeholder---></div>";
		output += "</div>";
		$("#edit-user-manager-select").html(output);
		$("#edit-user-manager-select-dialog-menu").html(xOutput);		
	});

});

$(document).on("pageshow", "#user-settings-dialog", function (pageEvent) {
	// if the user is logged in update the content.
	if (CurrentUser) {
		var u = JSON.stringify(SelectedUser.attributes);
			u= JSON.parse(u);		
		var c = JSON.stringify(CurrentUser.attributes);
			c = JSON.parse(c);
		$("#settings-dialog-title").text(u.firstName+" "+u.lastName);
		console.log("manager at page show status "+sessionStorage.getItem('changingManager'));
		var state = sessionStorage.getItem('changingManager');
		
		if (state == "true"){
			console.log("Selecting manager at page show");
			var first = SelectedManager.get("firstName");
			var last = SelectedManager.get("lastName");
			$('#edit-user-manager-select-button span').text("Manager:"+first+" "+last);
		}else{
			console.log("Not selecting manager at page show");
			SelectedManager = u.assignedManager;
			$('#edit-user-manager-select-button span').text("Manager:"+SelectedManager.firstName+" "+SelectedManager.lastName);
		}
		$('input[id=edit-personalemailsetup]').val(u.personalEmail);
		$('input[id=edit-phonesetup]').val(u.phone);
		$('input[id=edit-streetsetup]').val(u.streetAddress);
		$('input[id=edit-citynamesetup]').val(u.city);
		$('input[id=edit-zipsetup]').val(u.zipCode);
		////admin controls
		if (c.userType == "Admin" || c.userType == "Super-Admin" || c.userType == "Developer"){
			$("#admin-user-setting-area").show();
		}
		////manager controls
		if (c.userType == "Manager" || c.userType == "Admin" || c.userType == "Super-Admin" || c.userType == "Developer"){
			
			if(u.contractComplete == true && u.contractStatus != "Pending"){
				///contract signed and complete //
				console.log("contract signed and complete");
				$("#user-contract-status-btn").hide();
				$("#user-manager-toggle-area").show();
			}else
			if(u.contractComplete == null  && u.contractSent == null){
				console.log("contract NEVER sent, signed or completed");
				if (c.userType == "Admin" || c.userType == "Super-Admin" || c.userType == "Developer"){
					$("send-user-contract-btn").show();
					$("#user-contract-status-btn").show();
				}
				$("#user-manager-toggle-area").hide();
			}else
			if(u.contractComplete == null  && u.contractSent == true){
				console.log("contract sent but NEVER signed or completed");
				$("#user-contract-status-btn").show();
				$("#user-manager-toggle-area").hide();
			}else{
				///contract not signed
				console.log("contract NOT signed or complete");
				$("#user-manager-toggle-area").hide();
				$("#user-contract-status-btn").show();
			}
			$("#manager-user-setting-area").show();
		}
		if (u.leadForwarding){
			$("#user-lead-fwd-select").val("on").trigger("create").slider("refresh");
		}else{
			$("#user-lead-fwd-select").val("off").trigger("create").slider("refresh");
		}
		if (u.isSuspended){
			$("#user-manager-toggle-area").show();
			$("#user-suspension-select").val("on").trigger("create").slider("refresh");
		}else{
			$("#user-suspension-select").val("off").trigger("create").slider("refresh");
		}
	}else			
	// If the user is not logged in, ask them to log in.
    	$( ":mobile-pagecontainer" ).pagecontainer( "change", "#signin" );
});

$( document ).on( "pagecontainerbeforetransition" , function ( event, data ) {
	if ( data.toPage[0].id == "pending-sale-details-dialog" ) {
		var listing = (JSON.stringify(SelectedAssetListing.attributes));
			listing= JSON.parse(listing);
		if (listing.buyerContractSent == true){
			$("#update-buyer-notes-btn").hide();
		}else{
			$("#update-buyer-notes-btn").show();
		}
		if (listing.sellerContractSent == true){
			$("#update-owner-notes-btn").hide();
		}else{
			$("#update-owner-notes-btn").show();
		}
	}
	if ( data.toPage[0].id == "send-wire-confirm-dialog" ) {
		var listing = (JSON.stringify(SelectedAssetListing.attributes));
			listing= JSON.parse(listing);
		$('input[name=wire-info-recipient-input]').val(listing.buyer.companyEmail);
	}
	if ( data.toPage[0].id == "confirm-send-seller-contract-dialog" ) {
		var listing = (JSON.stringify(SelectedAssetListing.attributes));
			listing= JSON.parse(listing);
		$('input[name=seller-agreement-recipient-input]').val(listing.seller.companyEmail);
	}
	if ( data.toPage[0].id == "confirm-send-buyer-contract-dialog" ) {
		var listing = (JSON.stringify(SelectedAssetListing.attributes));
			listing= JSON.parse(listing);
		$('input[name=buyer-agreement-recipient-input]').val(listing.buyer.companyEmail);
	}
	if ( data.toPage[0].id == "sale-notes-dialog" ) {
		$(document).find("#sale-notes-dialog-view").empty();
		var messageArray = data.options.notes;
		var output = "";
		for(var i = 0; i < messageArray.length; i++){

			var author = messageArray[i].get('user');
			var userObj = JSON.stringify(author);
				userObj = JSON.parse(userObj);
			var viewingUser = (JSON.stringify(CurrentUser.attributes));
		 		viewingUser = JSON.parse(viewingUser);
		 	
			var usersName = userObj.firstName+" "+userObj.lastName;
		 	var message = messageArray[i].get('message');
		 	var time = messageArray[i].createdAt;
		 		time = time.toString();

		 	if (userObj.username == viewingUser.username){
		 		output += "<div class=\"container\">";
		 		output += "<span><img src=\"https://www.proxyequipment.com/images/silhouette.png\" alt=\"Avatar\"><p>"+usersName+"</p></span>";
		 		output += "<p>"+message+"</p>";
		 	}else{
		 		output += "<div class=\"container darker\">";
		 		output += "<span><img src=\"https://www.proxyequipment.com/images/silhouette.png\" alt=\"Avatar\" class=\"right\"><p>"+usersName+"</p></span>";
		 		output += "<p>"+message+"</p>";
		 	}
		 	if (userObj.username == viewingUser.username){
				output += "<span class=\"time-left\">"+time+"</span></div>";
		 	}else{
				output += "<span class=\"time-left\">"+time+"</span></div>";
		 	}
		} 
		$(document).find("#sale-notes-dialog-view").append(output);
	}
	
	if ( data.toPage[0].id == "lead-notes-dialog" ) {
		$(document).find("#lead-notes-dialog-view").empty();
		var messageArray = data.options.notes;
		var output = "";
		for(var i = 0; i < messageArray.length; i++){
		
			var author = messageArray[i].get('user');
			var userObj = JSON.stringify(author);
				userObj = JSON.parse(userObj);
			var viewingUser = (JSON.stringify(CurrentUser.attributes));
		 		viewingUser = JSON.parse(viewingUser);
		 	
			var usersName = userObj.firstName+" "+userObj.lastName;
		 	var message = messageArray[i].get('message');
		 	var time = messageArray[i].createdAt;
		 		time = time.toString();

		 	if (userObj.username == viewingUser.username){
		 		output += "<div class=\"container\">";
		 		output += "<span><img src=\"https://www.proxyequipment.com/images/silhouette.png\" alt=\"Avatar\"><p>"+usersName+"</p></span>";
		 		output += "<p>"+message+"</p>";
		 	}else{
		 		output += "<div class=\"container darker\">";
		 		output += "<span><img src=\"https://www.proxyequipment.com/images/silhouette.png\" alt=\"Avatar\" class=\"right\"><p>"+usersName+"</p></span>";
		 		output += "<p>"+message+"</p>";
		 	}
		 	if (userObj.username == viewingUser.username){
				output += "<span class=\"time-left\">"+time+"</span></div>";
		 	}else{
				output += "<span class=\"time-left\">"+time+"</span></div>";
		 	}
		} 
		$(document).find("#lead-notes-dialog-view").append(output);
	}
	if ( data.toPage[0].id == "user-notes-dialog" ) {
		$(document).find("#user-notes-dialog-view").empty();
		var messageArray = data.options.notes;
		var output = "";
		for(var i = 0; i < messageArray.length; i++){
			var author = messageArray[i].get('author');
			var authorObj = JSON.stringify(author);
				authorObj = JSON.parse(authorObj);
			var viewingUser = (JSON.stringify(CurrentUser.attributes));
		 		viewingUser = JSON.parse(viewingUser);
		 	
			var authorsName = authorObj.firstName+" "+authorObj.lastName;
		 	var message = messageArray[i].get('message');
		 	var time = messageArray[i].createdAt;
		 		time = time.toString();

		 	if (authorObj.username == viewingUser.username){
		 		output += "<div class=\"container\">";
		 		output += "<span><img src=\"https://www.proxyequipment.com/images/silhouette.png\" alt=\"Avatar\"><p>"+authorsName+"</p></span>";
		 		output += "<p>"+message+"</p>";
		 	}else{
		 		output += "<div class=\"container darker\">";
		 		output += "<span><img src=\"https://www.proxyequipment.com/images/silhouette.png\" alt=\"Avatar\" class=\"right\"><p>"+authorsName+"</p></span>";
		 		output += "<p>"+message+"</p>";
		 	}
		 	if (authorObj.username == viewingUser.username){
				output += "<span class=\"time-left\">"+time+"</span></div>";
		 	}else{
				output += "<span class=\"time-left\">"+time+"</span></div>";
		 	}
		} 
		$(document).find("#user-notes-dialog-view").append(output);
	}

    if ( data.toPage[0].id == "fileViewer" ) {
		$("#pdf-view").empty();
		var pdfURL = data.options.foo;
		var extension = pdfURL.substr((pdfURL.lastIndexOf('.') +1));
		var output = "";
		if	(extension=="pdf"){
			output += "<script>";
			output += "PDFObject.embed(\""+pdfURL+"\");";
			output += "</script>";
			$(document).find("#pdf-view").append(output);
		}
	}
    if ( data.toPage[0].id == "auction-results" ) {
		$(document).find("#auction-results-list").empty();
		var results = auctionResultsArray;
		var output = "";
		for(var i = 0; i < results.length; i++){
			var obj = JSON.stringify(results[i]);
				obj = JSON.parse(obj);

			var imgURL = "https://www.rockanddirt.com/";
				imgURL += obj.thumbImgURL;

			output += "<li is=\"listview-li\">";
			output += "<a class=\"ui-btn-a ui-btn\" data-form=\"ui-btn-up-a\" data-swatch=\"a\" data-theme=\"a\">";
			output += "<p><img id=\"thumbnail-image\" class=\"ui-li-icon\" style=\"float:left;width:80px;height:80px; vertical-align: middle;\" src= "+imgURL+" is=\"image\">";
			output += "<span style=\"font-size: 16pt;\">"+obj.title+"</span></br>";
			output += "<span style=\"font-size: 14pt;\">Sale Location:"+obj.location+"</span></br>";
			output += "<span style=\"font-size: 14pt;\">Sold for:"+obj.price+"</span><br/>";
			output += "<span style=\"font-size: 14pt;\">"+obj.odom+"</span></p>";
			output += "</li>";
		} 
		$(document).find("#auction-results-list").html(output);
	}
	if ( data.toPage[0].id == "lead-details" ) {
		var id = "";
			id = data.options.foo;
			if(!id || id.length == 0){
				id = getUrlParam("id");
			}
			if (!id){
				var lead = JSON.stringify(SelectedLead);
					lead = JSON.parse(lead);
				id = lead.objectId;
				return;
			}
			if (!id){
				alert("ERROR!:Can't find selected lead id");
			}
			/*
			if(!id){
				id = getUrlParam("id");
				$("#left-lead-details-nav-button").attr("href","#");
				$("#left-lead-details-nav-button").attr("data-transition","fade");
				$("#left-lead-details-nav-button").removeClass("ui-icon-arrow-l");
				$("#left-lead-details-nav-button").addClass("ui-icon-bars");
				$("#left-lead-details-nav-button").text("Menu");
				$("#left-lead-details-nav-button").removeAttr("data-direction","reverse");
			}
			*/
				getLeadById(id,function(foundLead){
					console.log("getting lead = "+foundLead);
					SelectedLead = foundLead;
					SelectedLeadRecipient = SelectedLead.get('user');
					SelectedLeadListing = SelectedLead.get('assetListing');
					var stringLead = JSON.stringify(SelectedLead.attributes);
					var	leadObj= JSON.parse(stringLead);
					var stringRecipient = JSON.stringify(SelectedLeadRecipient.attributes);
					var	leadRecObj= JSON.parse(stringRecipient);
					var stringListing = JSON.stringify(SelectedLeadListing.attributes);
					var	leadListingObj= JSON.parse(stringListing);
					var name = leadObj.contactName;
					var email = leadObj.contactEmail;
					var phone = leadObj.contactPhone;
					var stockNumber = leadListingObj.assetOwnerStockNumber;
					var subject = leadObj.subject;
					var custComment = leadObj.custComment;
					var output = "";
						output +="<p style=\"font-size:18px\"><button id=\"view-listing-btn\" data-id=\""+id+"\" objType=\"lead\" class=\"ui-btn ui-btn-corner-all ui-shadow ui-icon-search\">View listing</button>"+subject+"<br/>Stock #: "+stockNumber+"</p><p style=\"font-size:18px\">"+name+"<br/>"+custComment+"<h3>Contact options</h3>";
					
					var callBtnOutput = "";
						callBtnOutput = "<a href=\"tel:+1"+phone+"\" class=\"ui-btn ui-btn-corner-all ui-icon-phone ui-btn-icon-left ui-shadow\" data-role=\"button\" role=\"button\">Call "+name+"</a>";
						
					var emailBtnOutput = "";
						emailBtnOutput = "<a href=\"mailto:"+email+"?subject=\""+subject+"\" class=\"ui-btn ui-btn-corner-all ui-icon-mail ui-btn-icon-left ui-shadow\" data-role=\"button\" role=\"button\">Email "+name+"</a>";
						
					if (phone.length > 0){
						$("#lead-call-button-area").html(callBtnOutput);
						$("#lead-call-button-area").show();
					}
					if (email.length > 0){
						$("#lead-email-button-area").html(emailBtnOutput);
						$("#lead-email-button-area").show();
					}
					if (email.length == 0){
						$("#lead-email-button-area").empty();
						$("#lead-email-button-area").hide();
					}
					output +="</p>";
					$(document).find("#lead-info-area").html(output);
					
					var addbtn = document.getElementById("create-customer-from-lead-btn");
					var nameEle = document.createAttribute("data-name");       // Create a "class" attribute
						nameEle.value = name;                           // Set the value of the class attribute
						addbtn.setAttributeNode(nameEle);
					var phoneEle = document.createAttribute("data-phone");       // Create a "class" attribute
						phoneEle.value = phone;                           // Set the value of the class attribute
						addbtn.setAttributeNode(phoneEle);
					var emailEle = document.createAttribute("data-email");       // Create a "class" attribute
						emailEle.value = email;                           // Set the value of the class attribute
						addbtn.setAttributeNode(emailEle);
					var viewingUser = (JSON.stringify(CurrentUser.attributes));
				 		viewingUser = JSON.parse(viewingUser);
				 	
					if (leadRecObj.username == viewingUser.username){
						SelectedLead.set("isNew", false);
		        		SelectedLead.save(null, {
						     success: function() {
						            console.log("lead saved");
						      },error: function(error) {
						            alert('Failed to create new object, with error code: ' + error.description);
						      }
						});
					}
				});
		//}
	}
	if ( data.toPage[0].id == "customer-profile" ) {
		var coName = SelectedCustomerObject.coName;
		var first = SelectedCustomerObject.contFirst;
		var last = SelectedCustomerObject.contLast;
		var email = SelectedCustomerObject.email;
		var phone = SelectedCustomerObject.contPhone;
		var customerID = SelectedCustomerObject.coID;
		var address = SelectedCustomerObject.coAddress;
		var city = SelectedCustomerObject.coCity;
		var state = SelectedCustomerObject.coState;
		var id = SelectedCustomerObject.objID;
		var output = "";
			output +="<h3>"+coName+"</h3>";
			output +="<p style=\"font-size:18px\">"+first+" "+last+"<br/>"+phone+"<br/>"+email+"<br/>"+address+"<br/>"+city+", "+state+"<br/>Customer ID: "+customerID+"<br/></p>";

		$(document).find("#customer-page-detail-window").html(output);
	}
	if ( data.toPage[0].id == "create-lead-dialog" ) {
		updateCreateLeadHeader();
	}
	if ( data.toPage[0].id == "editcustomer-dialog" ) {
		$('input[name=edit-customer-companyname]').val(SelectedCustomerObject.coName);
		$('input[name=edit-customer-companyaddress]').val(SelectedCustomerObject.coAddress);
		$('input[name=edit-customer-companycity]').val(SelectedCustomerObject.coCity);
		$('input[name=edit-customer-companyzip]').val(SelectedCustomerObject.coZip);
		$('input[name=edit-customer-firstname]').val(SelectedCustomerObject.contFirst);
		$('input[name=edit-customer-lastname]').val(SelectedCustomerObject.contLast);
		$('input[name=edit-customer-email]').val(SelectedCustomerObject.email);
		$('input[name=edit-customer-phone]').val(SelectedCustomerObject.contPhone);
	}
	if ( data.toPage[0].id == "edit-listing-warning-dialog" ) {
		$('input[name=edit-listing-admin-comment]').val("");
	}
	
	if ( data.toPage[0].id == "comp-search-v3" ) {
		var dateArray = new Array();
		for (var i = 1930; i < 2021; i++){
			var obj = {
				value:i.toString(),
				text:i.toString()
			}
			dateArray.push(obj);
		}
		dateArray.reverse();

		createUlEleFromArrayOfObjs(dateArray,"auction-model-year-select", function (select){
			$("#auction-model-year-select-dialog-menu").replaceWith(select);
		});
		//$(document).find("#auction-category-filter").parent().addClass("ui-focus");
		createUlEleFromArrayOfObjs(auctionV3Categories,"auction-category-select", function (cats){
			$("#auction-category-select-dialog-menu").replaceWith(cats);
		});
		createUlEleFromArrayOfObjs(auctionV3Manufacturers,"auction-make-select", function (cats){
			$("#auction-make-select-dialog-menu").replaceWith(cats);
		});
	}
	if ( data.toPage[0].id == "auction-make-select-dialog" ) {
		//$(document).find("#auction-make-filter").parent().addClass("ui-focus");
		setTimeout(function() {
			$('#auction-make-filter').get(0).focus();
		}, 200);
	}
	if ( data.toPage[0].id == "auction-model-select-dialog" ) {
		//$(document).find("#auction-make-filter").parent().addClass("ui-focus");
		setTimeout(function() {
			$('#auction-model-filter').get(0).focus();
		}, 200);
	}
	if ( data.toPage[0].id == "signup") {
		//$(document).find("#auction-make-filter").parent().addClass("ui-focus");
		var output = "";
		var xOutput = "";
		getAllManagers(function(members){
			output += "<div class=\"ui-select\">";
			output += "<select name=\"new-user-manager-select\" id=\"new-user-manager-select\" data-native-menu=\"false\" tabindex=\"-1\">";
			for (var i = 0; i < members.length; i++) {
				var stringy = JSON.stringify(members[i]);
				var memberObj = JSON.parse(stringy);
				output += "<option value=\"1\">"+memberObj.firstName+" "+memberObj.lastName+"</option>";
				xOutput += "<li data-option-index=\""+i+"\" data-icon=\"false\" data-id="+memberObj.objectId+" objType=\"user\" class role=\"option\" aria-selected=\"false\">";
				xOutput += "<a href=\"#\" tabindex=\"-1\" class=\"ui-btn\">"+memberObj.firstName+" "+memberObj.lastName+" </br><small>"+memberObj.city+", "+memberObj.state+"</small></a></li>";
			}	
			output += "</select>";
			output += "<div style=\"display:none;\" id=\"new-user-manager-select-listbox-placeholder\"><!---Placeholder---></div>";
			output += "</div>";
			$("#new-user-manager-select").html(output);
			$("#new-user-manager-select-area").show();	
			$("#new-user-manager-select-dialog-menu").html(xOutput);		
		});
	}
    if ( data.toPage[0].id == "edit-listing" ) {
		$("#save-listing-edit").empty();

		listingID = data.options.objid;
		var output = "";
			output += "<a href=\"#edit-listing-warning-dialog\" role=\"button\" aria-haspopup=\"true\" class=\"ui-btn ui-btn-corner-all\" data-objid=\""+listingID+"\" data-rel=\"dialog\">Update Listing</a>";
		$("#save-listing-edit").html(output);
		var stringy = JSON.stringify(SelectedAssetListing.attributes);
		var listing = JSON.parse(stringy);
		if (CurrentUser != ListingAuthor){
			$("#customer-select").hide();
		}
		$('input[name=editEquipType]').val(listing.equipType);
		$('input[name=editEquipYear]').val(listing.equipYear);
		$('input[name=editEquipMake]').val(listing.equipMake);
		$('input[name=editEquipModel]').val(listing.equipModel);
		$('input[name=editEquipHours]').val(listing.equipHours);
		$('input[name=editEquipMileage]').val(listing.equipMileage);
		$('input[name=editEquipSerial]').val(listing.equipSerial);
		$('input[name=editEquipVIN]').val(listing.equipVIN);
		$('input[name=editEquipLocation]').val(listing.equipLocation);
		$('input[name=editEquipPrice]').val(listing.equipPrice);
		$('input[name=editEquipCost]').val(listing.equipCost);
	 	$('textarea[name=editEquipDescription]').val(listing.equipDescription);
		var galleryOutput = "";
		var imageURLs =listing.equipImgs;
		$('#qq-upload-list-editor').empty();
		$('#fine-uploader-manual-editor').empty();
		var uploader = new qq.FineUploader({
  			element: document.getElementById("fine-uploader-manual-editor"),
			template: 'qq-template-manual-trigger',
			request: {
				endpoint: '/WebApp/view/fine-uploader/endpoint.php'
			},
			editFilename: {
			 	enabled: true
			},
			deleteFile: {
				enabled: true,
				forceConfirm: true,
				endpoint: '/WebApp/view/fine-uploader/endpoint.php'
			},
			thumbnails: {
				placeholders: {
				waitingPath: '/WebApp/placeholders/waiting-generic.png',
				notAvailablePath: '/WebApp/placeholders/not_available-generic.png'
				}
			},
			validation: {
				allowedExtensions: ['jpeg', 'jpg', 'png'],
				itemLimit: 50,
			},
			scaling: {
			        sendOriginal: false,
			        sizes: [
			            {name: "scaled", maxSize: 1080}
			        ]
			    },
			callbacks: {
				onComplete:function(id, filename, responseJSON){
					imageURLs.push('https://proxyequipment.com/WebApp/data/' + responseJSON.uuid + "/" + responseJSON.uploadName);
					sessionStorage.setItem('imageArray',JSON.stringify(imageURLs));
				},
				onDelete:function(id, filename, responseJSON){
					var ar = imageURLs;
					ar.splice(id,1);
					//sessionStorage.clear();
					sessionStorage.setItem('imageArray',JSON.stringify(ar));
				}
			},
			autoUpload: false,
		});
		
		var editingArray = imageURLs;
		var imgObjs = [];
		for (var j in editingArray){
			var object= new Object();
			var segments = editingArray[j].split("/");
			var lastDir = (segments.length > 1) ? segments[segments.length - 2] : "";
			object["name"]=editingArray[j].substring(editingArray[j].lastIndexOf('/')+1); 
			object["uuid"]=lastDir;
			object["thumbnailUrl"]=editingArray[j]; 
			imgObjs.push(object);
		}
		stringyIMGs = JSON.stringify(imgObjs);
		uploader.addInitialFiles(imgObjs);
		qq(document.querySelector("#fine-uploader-manual-editor #trigger-upload")).attach("click", function () {
    		uploader.uploadStoredFiles();
		});
		//$("#qq-upload-list-editor").html(galleryOutput);
	}
    if ( data.toPage[0].id == "listing-details" ) {
		$("#listing-details-panel-02-ul").empty();
		$("#right-panel-infobox").empty();
		//runCompsInSidePanel();
		listingID = data.options.foo;
		listingStatus = data.options.status;
		var listing = (JSON.stringify(SelectedAssetListing.attributes));
			listing= JSON.parse(listing);
		var author = (JSON.stringify(ListingAuthor.attributes));
			author= JSON.parse(author);
		var viewingUser = (JSON.stringify(CurrentUser.attributes));
		 	viewingUser = JSON.parse(viewingUser);
		var buyer = (JSON.stringify(Buyer.attributes));
		if	(buyer){
			buyer= JSON.parse(buyer);
		}
		var seller = (JSON.stringify(Seller.attributes));
		if	(seller){
			seller= JSON.parse(seller);
			var ownerCompanyName = seller.companyName;
		}
		var sellerOutput = "";
		var assetOutput = "";
		var salesmanOutput = "";
		var adminOutput = "";
		var imageOutput = "";
		var galleryOutput = "";
		var imageArray = "";
		var type = listing.equipType;
		var year = listing.equipYear;
		var make = listing.equipMake;
		var model = listing.equipModel;
		var description = listing.equipDescription;
		var hours = listing.equipHours;
		var mileage = listing.equipMileage;
		var vin = listing.equipVIN;
		var serial = listing.equipSerial;
		var location = listing.equipLocation;
		var price = listing.equipPrice;
		price = numberToDollars(price);
		var cost = listing.equipCost;
		var ownerStockNumber = listing.assetOwnerStockNumber;
		var salesmanFirstName = author.firstName;				 		
		var salesmanLstName = author.lastName;
		var salesmanPhone = author.phone;
		var salesmanEmail = author.username;
		var title = "";
			title+= "<p><b>"+year+" "+make+" "+model+"</b></br>";
			title+= ""+price+"</br>";
			title+= ""+location+"</p>";
		$("#listing-title").html(title);
		salesmanOutput += "<fieldset class=\"ui-grid-a\"><div class=\"ui-block-a\"><a href=\"tel:+1"+salesmanPhone+"\" class=\"ui-btn ui-btn-corner-all ui-icon-phone ui-btn-icon-left ui-shadow\" data-role=\"button\" role=\"button\">Call</a></div>";
		salesmanOutput += "<div class=\"ui-block-b\"><a href=\"mailto:"+salesmanEmail+"?subject=\""+ownerStockNumber+" "+year+" "+make+" "+model+"\" class=\"ui-btn ui-btn-corner-all ui-icon-mail ui-btn-icon-left ui-shadow\" data-role=\"button\" role=\"button\">Email</a></div>";
		//salesmanOutput += "<div class=\"ui-block-c\"><a href=\"javascript:void(0)\" id=\"send-sms\" smsTo=\"+1"+salesmanPhone+"\" class=\"ui-btn ui-btn-corner-all ui-icon-mail ui-btn-icon-left ui-shadow\" data-role=\"button\" role=\"button\">Text</a></div>";
		salesmanOutput += "</fieldset>";
		assetOutput += "<li>Asset type: "+type+"</li>";
		assetOutput += "<li>Asset year: "+year+"</li>";
		assetOutput += "<li>Asset make: "+make+"</li>";
		assetOutput += "<li>Asset model: "+model+"</li>";
		assetOutput += "<li>Asset hours: "+hours+"</li>";
		assetOutput += "<li>Asset mileage: "+mileage+"</li>";
		assetOutput += "<li>Asset serial: "+serial+"</li>";
		assetOutput += "<li>Asset VIN: "+vin+"</li>";
		assetOutput += "<li>Asset location: "+location+"</li>";
		assetOutput += "<li>Asset price: "+price+"</li>";
		if	(viewingUser.userType == "Super-Admin" || viewingUser.userType == "Developer" || viewingUser.userType == "Admin" || viewingUser.username == author.assignedManager.username || viewingUser.username == author.username){
			assetOutput += "<li>Asset cost: "+cost+"</li>";
			sellerOutput += "<a href=\"javascript:void(0)\" id=\"view-customer-details-page\" data-cust-type=\"seller\" data-rel=\"close\" class=\"ui-btn ui-btn-corner-all\" data-rel=\"close\">View seller details</a>";
			$("#listing-seller-btn").html(sellerOutput);
			$("#listing-seller-name-label").text("Seller: "+ownerCompanyName);
			$('#img-gallery-colapsible').show();
			$("#seller-info-colapsible").show();
		}
		assetOutput += "<li>Asset stock number: "+ownerStockNumber+"</li>";
		assetOutput += "<li>Asset description: "+description+"</li>";
		assetOutput += "<li>Sales Rep: "+salesmanFirstName+" "+salesmanLstName+"</li>";
		assetOutput += "<li>Phone: "+salesmanPhone+"</li>";
		var imageURLs = listing.equipImgs;
		imageArray = imageURLs;
		imgObjects = [];
		galleryImageIndex = 0;
		galleryImageCount = imageArray.length;

		for (var j in imageArray){
			var imgURL = imageArray[j];
			imgURL = fixedEncodeURI(imgURL);
			galleryOutput += "<img id=\"img-gal-"+j+"\" class=\"gallery-thumbnail\" style=\"border: 3px solid #ccc; cursor: pointer; margin: 2px; width: 85px; height: 64px; vertical-align: top;\" src="+imgURL+" draggable=\"true\" ondragstart=\"drag(event)\" ondragover=\"allowDrop(event)\" ondrop=\"drop(event)\"></img>";
			var imgObj = {};
				imgObj = {
					src:imgURL,
				};
			imgObjects.push(imgObj);
		}
		//var imageArray = JSON.parse(imageURLs);
		var mainImgURL = imageURLs[0];
		mainImgURL = fixedEncodeURI(mainImgURL);
		imageOutput += "<img id=\"main-image\" style=\"width:100%;\" src= "+mainImgURL+" is=\"image\">";
		sessionStorage.imageArray = JSON.stringify(imageArray);
		galleryOutput+="</br><div class=\"grid-wrap-center-item\"><button id=\"save-image-order-btn\" class=\"ui-btn ui-btn-corner-all\" data-theme=\"a\">Save</button></br></div>";
		$("#main-image").empty();
		$("#img-gallery").empty();
		$("#asset-info-set").html(assetOutput);
		$("#salesman-info-set").html(salesmanOutput);
		$("#main-image").html(imageOutput);
		$("#img-gallery").html(galleryOutput);
		var adminOutput = "";
		adminOutput += "<li is=\"listview-li\"><a href=\"javascript:void(0)\" id=\"approve-listing-tab\" style=\"display:none;\" data-rel=\"close\" class=\"ui-btn-a ui-btn ui-btn-icon-left ui-icon-check\" data-form=\"ui-btn-up-a\" data-swatch=\"a\" data-theme=\"a\">Activate</a></li>";
		adminOutput += "<li is=\"listview-li\"><a href=\"javascript:void(0)\" id=\"deactivate-listing-tab\" style=\"display:none;\"data-rel=\"close\" class=\"ui-btn-a ui-btn ui-btn-icon-left ui-icon-forbidden\" data-form=\"ui-btn-up-a\" data-swatch=\"a\" data-theme=\"a\">De-Activate</a></li>";
		adminOutput += "<li is=\"listview-li\"><a href=\"#reject-listing-warning-dialog\" id=\"reject-listing-tab\" style=\"display:none;\"data-rel=\"close\" class=\"ui-btn-a ui-btn ui-btn-icon-left ui-icon-alert\" data-form=\"ui-btn-up-a\" data-swatch=\"a\" data-theme=\"a\">Reject</a></li>";
		adminOutput += "<li is=\"listview-li\"><a href=\"javascript:void(0)\" id=\"edit-listing-tab\" style=\"display:none;\"data-rel=\"close\" class=\"ui-btn-a ui-btn ui-btn-icon-left ui-icon-edit\" data-form=\"ui-btn-up-a\" data-swatch=\"a\" data-theme=\"a\" data-objid=\""+listingID+"\">Edit</a></li>";
		adminOutput += "<li is=\"listview-li\"><a href=\"#remove-listing-warning-dialog\" id=\"remove-listing-tab\" style=\"display:none;\"data-rel=\"dialog\" class=\"ui-btn-a ui-btn ui-btn-icon-left ui-icon-edit\" data-form=\"ui-btn-up-a\" data-swatch=\"a\" data-theme=\"a\" data-objid=\""+listingID+"\">Remove</a></li>";
		adminOutput += "<li is=\"listview-li\"><a href=\"#pending-sale-details-dialog\" id=\"view-pending-sale-tab\" style=\"display:none;\"data-rel=\"dialog\" class=\"ui-btn-a ui-btn ui-btn-icon-left ui-icon-clock\" data-form=\"ui-btn-up-a\" data-swatch=\"a\" data-theme=\"a\">View pending sale</a></li>";
		adminOutput += "<li is=\"listview-li\"><a href=\"#sold-listing-details\" id=\"view-sale-details-tab\" style=\"display:none;\"data-rel=\"close\" class=\"ui-btn-a ui-btn ui-btn-icon-left ui-icon-search\" data-form=\"ui-btn-up-a\" data-swatch=\"a\" data-theme=\"a\">View sale details</a></li>";
		adminOutput += "<li is=\"listview-li\"><a href=\"#create-lead-dialog\" id=\"generate-lead-tab\" style=\"display:none;\"data-rel=\"dialog\" class=\"ui-btn-a ui-btn ui-btn-icon-left ui-icon-tag\" data-form=\"ui-btn-up-a\" data-swatch=\"a\" data-theme=\"a\" data-objid=\""+listingID+"\">Generate lead</a></li>";
		adminOutput += "<li is=\"listview-li\"><a href=\"#titled-vehicle-confirmation-dialog\" id=\"generate-sale-tab\" style=\"display:none;\"data-rel=\"dialog\" class=\"ui-btn-a ui-btn ui-btn-icon-left ui-icon-tag\" data-form=\"ui-btn-up-a\" data-swatch=\"a\" data-theme=\"a\" data-objid=\""+listingID+"\">Generate sale</a></li>";
		adminOutput += "<li is=\"listview-li\"><a href=\"javascript:void(0)\" id=\"export-imgs-tab\" data-rel=\"close\" class=\"ui-btn-a ui-btn ui-btn-icon-left ui-icon-action\" data-form=\"ui-btn-up-a\" data-swatch=\"a\" data-theme=\"a\" data-objid=\""+listingID+"\" data-stknum=\""+ownerStockNumber+"\">Export this listing</a></li>";

		$(document).find("#listing-details-panel-02-ul").append(adminOutput);
		///	ADMIN AND LISTER OPTIONS
		if	(viewingUser.userType == "Super-Admin" || viewingUser.userType == "Developer" || viewingUser.userType == "Admin" || viewingUser.username == author.username || viewingUser.userType == "Manager"){
			if	(listingStatus == "Active"){
				$(document).find("#edit-listing-tab").show();
				$(document).find("#remove-listing-tab").show();
				$(document).find("#generate-sale-tab").show();
				if (viewingUser.userType == "Super-Admin" || viewingUser.userType == "Developer" || viewingUser.userType == "Admin"){
					$(document).find("#deactivate-listing-tab").show();
					$(document).find("#generate-lead-tab").show();
				}
			}
			if	(listingStatus == "Pending"){
				$(document).find("#edit-listing-tab").show();
				$(document).find("#remove-listing-tab").show();
				$(document).find("#generate-sale-tab").hide();
				if (viewingUser.userType == "Super-Admin" || viewingUser.userType == "Developer" || viewingUser.userType == "Admin"){
					$(document).find("#approve-listing-tab").show();
					$(document).find("#reject-listing-tab").show();
				}
			}
			if	(listingStatus == "Rejected"){
				$(document).find("#edit-listing-tab").show();
				$(document).find("#remove-listing-tab").show();
			}
			if	(listingStatus == "Removed"){
				$(document).find("#edit-listing-tab").show();
			}
			if	(listingStatus == "Sale-Pending"){
				$(document).find("#view-pending-sale-tab").show();
				$(document).find("#generate-lead-tab").show();
				$(document).find("#generate-sale-tab").hide();
				if (viewingUser.userType == "Super-Admin" || viewingUser.userType == "Developer" ){
					$(document).find("#complete-sale-btn").show();
				}
			}
			if (listingStatus == "Sold"){
				$(document).find("#view-sale-details-tab").show();
			}
		}
		var infoboxInfo = "";
			infoboxInfo +="<p style=\"font-size: 12pt;\">You created this item on "+listing.createdAt+" for your customer "+ownerCompanyName+".</p>";
		if	(viewingUser.username == author.username){
			$(document).find("#right-panel-infobox").append(infoboxInfo);
		}
	}
	if ( data.toPage[0].id == "sold-listing-details" ) {
		var assetOutput = "";
		var buyerOutput = "";
		var sellerOutput = "";
		
		var listing = (JSON.stringify(SelectedAssetListing.attributes));
			listing= JSON.parse(listing);
		var author = (JSON.stringify(ListingAuthor.attributes));
			author= JSON.parse(author);
		var viewingUser = (JSON.stringify(CurrentUser.attributes));
		 	viewingUser = JSON.parse(viewingUser);
		var price = listing.soldForPrice;
		var cost = listing.totalCost;
		var profit = Number(price)-Number(cost);
		  	profit = String(profit);
		console.log("profit = "+profit);
		var soldForPrice = numberToDollars(price);
		var totalCost = numberToDollars(cost);
		var totalProfit = numberToDollars(profit);

		var saleDate = new Date(listing.dateSold);
		var dateString = formatDateNoTime(saleDate);
			dateString = dateString.toString();
			assetOutput += "<p>Stock number: "+listing.assetOwnerStockNumber+"<br/>"+listing.equipYear+" "+listing.equipMake+" "+listing.equipModel+"<br/>Sold for "+soldForPrice+" on "+dateString+".<br/>Cost total: "+totalCost+"</br>Profit: "+totalProfit+"</br>Representative: "+author.firstName+" "+author.lastName+"</p>";
		var buyer = (JSON.stringify(Buyer.attributes));
		if	(buyer){
			buyer= JSON.parse(buyer);
			buyerOutput += "<h4>Buyer:"+buyer.companyName+"</h4>";
			if (listing.buyerContractName == null || listing.buyerContractName == ""){
				buyerOutput += "<a href=\"javascript:void(0)\" id=\"view-customer-details-page\" data-cust-type=\"buyer\" data-rel=\"close\" class=\"ui-btn ui-btn-corner-all\" data-rel=\"close\">View buyer details</a>";
			}else{
				buyerOutput += "<p>Buyer contract name: "+listing.buyerContractName+"</p>"; 
				buyerOutput += "<a href=\"javascript:void(0)\" id=\"view-customer-details-page\" data-cust-type=\"buyer\" data-rel=\"close\" class=\"ui-btn ui-btn-corner-all\" data-rel=\"close\">View buyer details</a>";
			}
		}
		var seller = (JSON.stringify(Seller.attributes));
		if	(seller){
			seller = JSON.parse(seller);
			sellerOutput += "<h4>Seller:"+seller.companyName+"</h4>";
			if (listing.sellerContractName == null || listing.sellerContractName == ""){
				sellerOutput += "<a href=\"javascript:void(0)\" id=\"view-customer-details-page\" data-cust-type=\"seller\" data-rel=\"close\" class=\"ui-btn ui-btn-corner-all\" data-rel=\"close\">View seller details</a>";
			}else{
				sellerOutput += "<p>Seller contract name: "+listing.sellerContractName+"</p>"; 
				sellerOutput += "<a href=\"javascript:void(0)\" id=\"view-customer-details-page\" data-cust-type=\"seller\" data-rel=\"close\" class=\"ui-btn ui-btn-corner-all\" data-rel=\"close\">View seller details</a>";
			}
		}
			
		$(document).find("#sold-asset-description").html(assetOutput);
		$(document).find("#sold-asset-buyer-info").html(buyerOutput);
		$(document).find("#sold-asset-seller-info").html(sellerOutput);
	}

});

