Subversion Repositories munaweb

Rev

Rev 8 | Rev 53 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

<!DOCTYPE html>
<html lang="en">

<head>
    <title>eBay Listing Search</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
    <link rel="icon" href="favicon.ico" type="image/x-icon">

    <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
    <script src="js/datetimepicker_css.js"></script>
    <script src="js/moment.js"></script>
    <script src="js/moment-timezone.js"></script>
    <script src="js/jquery.js"></script>
    <script src="js/chart.js"></script>
    <link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet">
    <link rel="stylesheet" href="css/style.css">
    <link rel="stylesheet" href="css/chosen.min.css">
    <script src="js/muna-tools.js"></script>
</head>

<body onload="readParameters()">
    <div class="w3-main">
        <div class="w3-container w3-padding w3-margin w3-card-4">
            <div class="w3-container w3-gray" style="max-height:100px">
                <img class="w3-image" src="images/MUNA%20-%20Logo%20100x100.png" alt="MUNA Trading Logo" style="max-height:100%">
                <p class="w3-xxlarge w3-right">eBay Listing Search</p>
            </div>

            <form id="searchForm" class="w3-container w3-light-grey w3-padding w3-small" onsubmit="return eBaySearch(1);">

                <div class="w3-row">
                    <div class="w3-container w3-card-2 w3-col l4 m7 s12">
                        <h4>Keyword <a href="javascript:void(0)" class="w3-ripple w3-hide-medium w3-hide-small" style="text-decoration:none;" onclick="showKeywordHelp()">&#128712;</a></h4>

                        <input id="keyword" name="keyword" class="w3-input w3-border-0" style="height:2em" type="text" autofocus="autofocus">
                        <div class="w3-bar">
                            <a href="javascript:void(0)" id="keywordRecommendations" class="w3-btn w3-black w3-margin w3-round-large w3-ripple w3-hide-medium w3-hide-small" onclick="getKeywordRecommendations()">Keyword Check</a>
                            <a href="javascript:void(0)" id="checkUPC" class="w3-btn w3-black w3-margin w3-round-large w3-ripple" onclick="checkUPC()">UPC Check</a>
                        </div>
                        <p id="recommendation"></p>
                    </div>
                    <div class="w3-container w3-card-2 w3-col l2 m5 s12">
                        <h4>Category</h4>
                        <select id="category" name="category" data-placeholder="Choose up to 3 Categories..." class="chosen-container chosen-select-3 chosen-select-label chosen-search-contains" multiple="multiple">
                            <option value="0">All</option>
                            <option value="20081">Antiques</option>
                            <option value="550">Art</option>
                            <option value="2984">Baby</option>
                            <option value="267">Books</option>
                            <option value="12576">Business Industrial</option>
                            <option value="625">Cameras Photo</option>
                            <option value="15032">Cell Phones Accessories</option>
                            <option value="11450">Clothing, Shoes Accessories</option>
                            <option value="11116">Coins Paper Money</option>
                            <option value="1">Collectibles</option>
                            <option value="58058">Computers/Tablets Networking</option>
                            <option value="293">Consumer Electronics</option>
                            <option value="14339">Crafts</option>
                            <option value="237">Dolls Bears</option>
                            <option value="11232">DVDs Movies</option>
                            <option value="45100">Entertainment Memorabilia</option>
                            <option value="172008">Gift Cards Coupons</option>
                            <option value="26395">Health Beauty</option>
                            <option value="11700">Home Garden</option>
                            <option value="281">Jewelry Watches</option>
                            <option value="11233">Music</option>
                            <option value="619">Musical Instruments Gear</option>
                            <option value="1281">Pet Supplies</option>
                            <option value="870">Pottery Glass</option>
                            <option value="10542">Real Estate</option>
                            <option value="316">Specialty Services</option>
                            <option value="888">Sporting Goods</option>
                            <option value="64482">Sports Mem, Cards Fan Shop</option>
                            <option value="260">Stamps</option>
                            <option value="1305">Tickets Experiences</option>
                            <option value="220">Toys Hobbies</option>
                            <option value="3252">Travel</option>
                            <option value="1249">Video Games Consoles</option>
                            <option value="99">Everything Else</option>
                            <optgroup label="Antiques">
                                <option value="37903">Antiquities</option>
                                <option value="4707">Architectural Garden</option>
                                <option value="20082">Asian Antiques</option>
                                <option value="20086">Decorative Arts</option>
                                <option value="2207">Ethnographic</option>
                                <option value="20091">Furniture</option>
                                <option value="163008">Home Hearth</option>
                                <option value="22422">Incunabula</option>
                                <option value="181677">Linens Textiles (Pre-1930)</option>
                                <option value="23048">Manuscripts</option>
                                <option value="37958">Maps, Atlases Globes</option>
                                <option value="37965">Maritime</option>
                                <option value="163091">Mercantile, Trades Factories</option>
                                <option value="181726">Musical Instruments (Pre-1930)</option>
                                <option value="100927">Periods Styles</option>
                                <option value="1217">Primitives</option>
                                <option value="163101">Restoration Care</option>
                                <option value="37978">Rugs Carpets</option>
                                <option value="20094">Science Medicine (Pre-1930)</option>
                                <option value="156323">Sewing (Pre-1930)</option>
                                <option value="20096">Silver</option>
                                <option value="22608">Reproduction Antiques</option>
                                <option value="12">Other Antiques</option>
                            </optgroup>
                            <optgroup label="Art">
                                <option value="28009">Art Posters</option>
                                <option value="552">Art Drawings</option>
                                <option value="2211">Art Photographs</option>
                                <option value="360">Art Prints</option>
                                <option value="553">Art Sculptures</option>
                                <option value="357">Folk Art Indigenous Art</option>
                                <option value="554">Mixed Media Art Collage Art</option>
                                <option value="551">Paintings</option>
                                <option value="156196">Textile Art Fiber Art</option>
                                <option value="20158">Other Art</option>
                            </optgroup>
                            <optgroup label="Baby">
                                <option value="100223">Baby Gear</option>
                                <option value="20433">Baby Safety Health</option>
                                <option value="20394">Bathing Grooming</option>
                                <option value="66692">Car Safety Seats</option>
                                <option value="100982">Carriers, Slings Backpacks</option>
                                <option value="45455">Diapering</option>
                                <option value="20400">Feeding</option>
                                <option value="117388">Keepsakes Baby Announcements</option>
                                <option value="20416">Nursery Bedding</option>
                                <option value="66697">Nursery Decor</option>
                                <option value="20422">Nursery Furniture</option>
                                <option value="37631">Potty Training</option>
                                <option value="66698">Strollers Accessories</option>
                                <option value="19068">Toys for Baby</option>
                                <option value="1261">Other Baby</option>
                                <option value="48757">Wholesale Lots</option>
                            </optgroup>
                            <optgroup label="Books">
                                <option value="45110">Accessories</option>
                                <option value="29223">Antiquarian Collectible</option>
                                <option value="29792">Audiobooks</option>
                                <option value="118254">Catalogs</option>
                                <option value="182882">Children Young Adults</option>
                                <option value="11104">Cookbooks</option>
                                <option value="171228">Fiction Literature</option>
                                <option value="280">Magazine Back Issues</option>
                                <option value="171243">Nonfiction</option>
                                <option value="2228">Textbooks, Education</option>
                                <option value="29399">Wholesale Bulk Lots</option>
                                <option value="268">Other Books</option>
                            </optgroup>
                            <optgroup label="Business Industrial">
                                <option value="109471">Adhesives, Sealants Tapes</option>
                                <option value="11748">Agriculture Forestry</option>
                                <option value="42892">Automation, Motors Drives</option>
                                <option value="46534">Cleaning Janitorial Supplies</option>
                                <option value="11765">Construction</option>
                                <option value="92074">Electrical Test Equipment</option>
                                <option value="11897">Facility Maintenance Safety</option>
                                <option value="183900">Fasteners Hardware</option>
                                <option value="159693">Fuel Energy</option>
                                <option value="11815">Healthcare, Lab Life Science</option>
                                <option value="177641">Heavy Equipment</option>
                                <option value="177647">Heavy Equipment Attachments</option>
                                <option value="41489">Heavy Equipment Parts Accs</option>
                                <option value="42909">HVAC</option>
                                <option value="183978">Hydraulics, Pneumatics Pumps</option>
                                <option value="61573">Light Equipment Tools</option>
                                <option value="11804">Manufacturing Metalworking</option>
                                <option value="26221">Material Handling</option>
                                <option value="25298">Office</option>
                                <option value="26238">Printing Graphic Arts</option>
                                <option value="11874">Restaurant Catering</option>
                                <option value="11890">Retail Services</option>
                                <option value="11759">Websites Businesses for Sale</option>
                                <option value="26261">Other Business Industrial</option>
                            </optgroup>
                            <optgroup label="Cameras Photo">
                                <option value="28179">Binoculars Telescopes</option>
                                <option value="11724">Camcorders</option>
                                <option value="15200">Camera Photo Accessories</option>
                                <option value="179697">Camera Drones</option>
                                <option value="182969">Camera Drone Parts Accs</option>
                                <option value="4684">Camera Manuals Guides</option>
                                <option value="31388">Digital Cameras</option>
                                <option value="150044">Digital Photo Frames</option>
                                <option value="69323">Film Photography</option>
                                <option value="64353">Flashes Flash Accessories</option>
                                <option value="78997">Lenses Filters</option>
                                <option value="30078">Lighting Studio</option>
                                <option value="182074">Replacement Parts Tools</option>
                                <option value="30090">Tripods Supports</option>
                                <option value="21162">Video Production Editing</option>
                                <option value="3326">Vintage Movie Photography</option>
                                <option value="45086">Wholesale Lots</option>
                                <option value="27432">Other Cameras Photo</option>
                            </optgroup>
                            <optgroup label="Cell Phones Accessories">
                                <option value="9355">Cell Phones Smartphones</option>
                                <option value="178893">Smart Watches</option>
                                <option value="182064">Smart Watch Accessories</option>
                                <option value="9394">Cell Phone Accessories</option>
                                <option value="136699">Display Phones</option>
                                <option value="146492">Phone Cards SIM Cards</option>
                                <option value="m43304">Cell Phone Smartphone Parts</option>
                                <option value="182073">Vintage Cell Phones</option>
                                <option value="45065">Wholesale Lots</option>
                                <option value="42428">Other Cell Phones Accs</option>
                            </optgroup>
                            <optgroup label="Clothing, Shoes Accessories">
                                <option value="3082">Baby Toddler Clothing</option>
                                <option value="171146">Kids' Clothing, Shoes Accs</option>
                                <option value="163147">Costumes, Reenactment, Theater</option>
                                <option value="155240">Cultural Ethnic Clothing</option>
                                <option value="112425">Dancewear</option>
                                <option value="4250">Men's Accessories</option>
                                <option value="1059">Men's Clothing</option>
                                <option value="93427">Men's Shoes</option>
                                <option value="28015">Uniforms Work Clothing</option>
                                <option value="155184">Unisex Clothing, Shoes Accs</option>
                                <option value="3259">Wedding Formal Occasion</option>
                                <option value="4251">Women's Accessories</option>
                                <option value="15724">Women's Clothing</option>
                                <option value="169291">Women's Handbags Bags</option>
                                <option value="3034">Women's Shoes</option>
                                <option value="175759">Vintage</option>
                                <option value="41964">Wholesale, Large Small Lots</option>
                            </optgroup>
                            <optgroup label="Coins Paper Money">
                                <option value="39482">Bullion</option>
                                <option value="253">Coins: US</option>
                                <option value="3377">Coins: Canada</option>
                                <option value="4733">Coins: Ancient</option>
                                <option value="18466">Coins: Medieval</option>
                                <option value="256">Coins: World</option>
                                <option value="3452">Exonumia</option>
                                <option value="3412">Paper Money: US</option>
                                <option value="3411">Paper Money: World</option>
                                <option value="83274">Publications Supplies</option>
                                <option value="3444">Stocks Bonds, Scripophily</option>
                                <option value="179197">Virtual Currency</option>
                                <option value="169305">Other Coins Paper Money</option>
                            </optgroup>
                            <optgroup label="Collectibles">
                                <option value="34">Advertising</option>
                                <option value="1335">Animals</option>
                                <option value="13658">Animation Art Characters</option>
                                <option value="66502">Arcade, Jukeboxes Pinball</option>
                                <option value="14429">Autographs</option>
                                <option value="66503">Banks, Registers Vending</option>
                                <option value="3265">Barware</option>
                                <option value="156277">Beads</option>
                                <option value="29797">Bottles Insulators</option>
                                <option value="562">Breweriana, Beer</option>
                                <option value="898">Casino</option>
                                <option value="397">Clocks</option>
                                <option value="63">Comics</option>
                                <option value="1462">Credit, Charge Cards</option>
                                <option value="3913">Cultures Ethnicities</option>
                                <option value="13777">Decorative Collectibles</option>
                                <option value="137">Disneyana</option>
                                <option value="m10860">Fantasy, Mythical Magic</option>
                                <option value="13877">Historical Memorabilia</option>
                                <option value="907">Holiday Seasonal</option>
                                <option value="13905">Kitchen Home</option>
                                <option value="1401">Knives, Swords Blades</option>
                                <option value="1404">Lamps, Lighting</option>
                                <option value="940">Linens Textiles (1930-Now)</option>
                                <option value="1430">Metalware</option>
                                <option value="13956">Militaria</option>
                                <option value="182982">Non-Sport Trading Cards</option>
                                <option value="124">Paper</option>
                                <option value="966">Pens Writing Instruments</option>
                                <option value="14005">Pez, Keychains, Promo Glasses</option>
                                <option value="1463">Phone Cards</option>
                                <option value="14277">Photographic Images</option>
                                <option value="39507">Pinbacks, Bobbles, Lunchboxes</option>
                                <option value="914">Postcards</option>
                                <option value="29832">Radio, Phonograph, TV, Phone</option>
                                <option value="1446">Religion Spirituality</option>
                                <option value="3213">Rocks, Fossils Minerals</option>
                                <option value="152">Science Fiction Horror</option>
                                <option value="412">Science Medicine (1930-Now)</option>
                                <option value="113">Sewing (1930-Now)</option>
                                <option value="165800">Souvenirs Travel Memorabilia</option>
                                <option value="593">Tobacciana</option>
                                <option value="13849">Tools, Hardware Locks</option>
                                <option value="417">Transportation</option>
                                <option value="597">Vanity, Perfume Shaving</option>
                                <option value="69851">Vintage, Retro, Mid-Century</option>
                                <option value="45058">Wholesale Lots</option>
                            </optgroup>
                            <optgroup label="Computers/Tablets Networking">
                                <option value="183062">3D Printers Supplies</option>
                                <option value="171485">Tablets eBook Readers</option>
                                <option value="176970">Tablet eBook Reader Accs</option>
                                <option value="180235">Tablet eBook Reader Parts</option>
                                <option value="175672">Laptops Netbooks</option>
                                <option value="171957">Desktops All-In-Ones</option>
                                <option value="31530">Laptop Desktop Accessories</option>
                                <option value="182094">Computer Cables Connectors</option>
                                <option value="175673">Computer Components Parts</option>
                                <option value="165">Drives, Storage Blank Media</option>
                                <option value="175698">Enterprise Networking, Servers</option>
                                <option value="11176">Home Networking Connectivity</option>
                                <option value="3676">Keyboards, Mice Pointers</option>
                                <option value="162497">Monitors, Projectors Accs</option>
                                <option value="86722">Power Protection, Distribution</option>
                                <option value="171961">Printers, Scanners Supplies</option>
                                <option value="18793">Software</option>
                                <option value="3516">Manuals Resources</option>
                                <option value="11189">Vintage Computing</option>
                                <option value="159260">Wholesale Lots</option>
                                <option value="162">Other Computers Networking</option>
                            </optgroup>
                            <optgroup label="Consumer Electronics">
                                <option value="184435">Voice-Enabled Smart Assistants</option>
                                <option value="183067">Virtual Reality</option>
                                <option value="15052">Portable Audio Headphones</option>
                                <option value="32852">TV, Video Home Audio</option>
                                <option value="3270">Vehicle Electronics GPS</option>
                                <option value="50582">Home Automation</option>
                                <option value="48633">Home Surveillance</option>
                                <option value="3286">Home Telephones Accessories</option>
                                <option value="48446">Multipurpose Batteries Power</option>
                                <option value="1500">Radio Communication</option>
                                <option value="14948">Gadgets Other Electronics</option>
                                <option value="183077">Vintage Electronics</option>
                                <option value="61494">Wholesale Lots</option>
                            </optgroup>
                            <optgroup label="Crafts">
                                <option value="11783">Art Supplies</option>
                                <option value="31723">Beads Jewelry Making</option>
                                <option value="28162">Fabric</option>
                                <option value="183118">Fabric Painting Decorating</option>
                                <option value="163778">Glass Mosaics</option>
                                <option value="71183">Handcrafted Finished Pieces</option>
                                <option value="160667">Home Arts Crafts</option>
                                <option value="116652">Kids' Crafts</option>
                                <option value="28131">Leathercrafts</option>
                                <option value="28102">Multi-Purpose Craft Supplies</option>
                                <option value="160706">Needlecrafts Yarn</option>
                                <option value="11788">Scrapbooking Paper Crafts</option>
                                <option value="160737">Sewing</option>
                                <option value="183302">Sculpting, Molding Ceramics</option>
                                <option value="3122">Stamping Embossing</option>
                                <option value="75576">Other Crafts</option>
                                <option value="45074">Wholesale Lots</option>
                            </optgroup>
                            <optgroup label="Dolls Bears">
                                <option value="50253">Bear Making Supplies</option>
                                <option value="386">Bears</option>
                                <option value="238">Dolls</option>
                                <option value="1202">Dollhouse Miniatures</option>
                                <option value="2440">Paper Dolls</option>
                                <option value="52546">Wholesale Lots</option>
                            </optgroup>
                            <optgroup label="DVDs Movies">
                                <option value="617">DVDs Blu-ray Discs</option>
                                <option value="63821">Film Stock</option>
                                <option value="381">Laserdiscs</option>
                                <option value="132975">UMDs</option>
                                <option value="309">VHS Tapes</option>
                                <option value="41676">Other Formats</option>
                                <option value="52554">Storage Media Accessories</option>
                                <option value="31606">Wholesale Lots</option>
                            </optgroup>
                            <optgroup label="Entertainment Memorabilia">
                                <option value="57">Autographs-Original</option>
                                <option value="104412">Autographs-Reprints</option>
                                <option value="196">Movie Memorabilia</option>
                                <option value="2329">Music Memorabilia</option>
                                <option value="1424">Television Memorabilia</option>
                                <option value="2362">Theater Memorabilia</option>
                                <option value="45101">Video Game Memorabilia</option>
                                <option value="2312">Other Entertainment Mem</option>
                            </optgroup>
                            <optgroup label="Gift Cards Coupons">
                                <option value="172009">Gift Cards</option>
                                <option value="172036">eBay Gift Cards</option>
                                <option value="31411">Gift Certificates</option>
                                <option value="172010">Coupons</option>
                                <option value="176950">Digital Gifts</option>
                            </optgroup>
                            <optgroup label="Health Beauty">
                                <option value="11838">Bath Body</option>
                                <option value="180345">Fragrances</option>
                                <option value="11854">Hair Care Styling</option>
                                <option value="67588">Health Care</option>
                                <option value="31786">Makeup</option>
                                <option value="36447">Massage</option>
                                <option value="11778">Medical, Mobility Disability</option>
                                <option value="47945">Nail Care, Manicure Pedicure</option>
                                <option value="67659">Natural Alternative Remedies</option>
                                <option value="31769">Oral Care</option>
                                <option value="177731">Salon Spa Equipment</option>
                                <option value="31762">Shaving Hair Removal</option>
                                <option value="11863">Skin Care</option>
                                <option value="31772">Sun Protection Tanning</option>
                                <option value="33914">Tattoos Body Art</option>
                                <option value="31414">Vision Care</option>
                                <option value="180959">Vitamins Dietary Supplements</option>
                                <option value="40965">Wholesale Lots</option>
                                <option value="1277">Other Health Beauty</option>
                            </optgroup>
                            <optgroup label="Home Garden">
                                <option value="26677">Bath</option>
                                <option value="20444">Bedding</option>
                                <option value="14308">Food Beverages</option>
                                <option value="178069">Fresh Cut Flowers Supplies</option>
                                <option value="3197">Furniture</option>
                                <option value="16086">Greeting Cards Party Supply</option>
                                <option value="38227">Holiday Seasonal Decor</option>
                                <option value="10033">Home Decor</option>
                                <option value="159907">Home Improvement</option>
                                <option value="299">Household Supplies Cleaning</option>
                                <option value="176988">Kids Teens at Home</option>
                                <option value="20625">Kitchen, Dining Bar</option>
                                <option value="20697">Lamps, Lighting Ceiling Fans</option>
                                <option value="20710">Major Appliances</option>
                                <option value="20571">Rugs Carpets</option>
                                <option value="631">Tools</option>
                                <option value="11827">Wedding Supplies</option>
                                <option value="63514">Window Treatments Hardware</option>
                                <option value="159912">Yard, Garden Outdoor Living</option>
                                <option value="31605">Wholesale Lots</option>
                                <option value="181076">Other Home Garden</option>
                            </optgroup>
                            <optgroup label="Jewelry Watches">
                                <option value="84605">Children's Jewelry</option>
                                <option value="91427">Engagement Wedding</option>
                                <option value="11312">Ethnic, Regional Tribal</option>
                                <option value="10968">Fashion Jewelry</option>
                                <option value="4196">Fine Jewelry</option>
                                <option value="110633">Handcrafted, Artisan Jewelry</option>
                                <option value="10321">Jewelry Boxes Organizers</option>
                                <option value="164352">Jewelry Design Repair</option>
                                <option value="179264">Loose Beads</option>
                                <option value="491">Loose Diamonds Gemstones</option>
                                <option value="10290">Men's Jewelry</option>
                                <option value="48579">Vintage Antique Jewelry</option>
                                <option value="14324">Watches, Parts Accessories</option>
                                <option value="98863">Other Jewelry Watches</option>
                                <option value="40131">Wholesale Lots</option>
                            </optgroup>
                            <optgroup label="Music">
                                <option value="176983">Cassettes</option>
                                <option value="176984">CDs</option>
                                <option value="176985">Records</option>
                                <option value="618">Other Formats</option>
                                <option value="52473">Storage Media Accessories</option>
                                <option value="31608">Wholesale Lots</option>
                            </optgroup>
                            <optgroup label="Musical Instruments Gear">
                                <option value="16212">Brass</option>
                                <option value="48458">DJ Equipment</option>
                                <option value="3858">Guitars Basses</option>
                                <option value="182150">Instruction Books, CDs Video</option>
                                <option value="175696">Karaoke Entertainment</option>
                                <option value="180012">Percussion</option>
                                <option value="180010">Pianos, Keyboards Organs</option>
                                <option value="180014">Pro Audio Equipment</option>
                                <option value="180015">Sheet Music Song Books</option>
                                <option value="12922">Stage Lighting Effects</option>
                                <option value="180016">String</option>
                                <option value="10181">Wind Woodwind</option>
                                <option value="180008">Equipment</option>
                                <option value="181162">Vintage Musical Instruments</option>
                                <option value="52555">Wholesale Lots</option>
                                <option value="308">Other Musical Instruments</option>
                            </optgroup>
                            <optgroup label="Pet Supplies">
                                <option value="177801">Backyard Poultry Supplies</option>
                                <option value="20734">Bird Supplies</option>
                                <option value="20737">Cat Supplies</option>
                                <option value="20742">Dog Supplies</option>
                                <option value="20754">Fish Aquariums</option>
                                <option value="1285">Reptile Supplies</option>
                                <option value="26696">Small Animal Supplies</option>
                                <option value="116391">Pet Memorials Urns</option>
                                <option value="48760">Wholesale Lots</option>
                                <option value="301">Other Pet Supplies</option>
                            </optgroup>
                            <optgroup label="Pottery Glass">
                                <option value="50693">Glass</option>
                                <option value="18875">Pottery China</option>
                            </optgroup>
                            <optgroup label="Real Estate">
                                <option value="15825">Commercial</option>
                                <option value="15841">Land</option>
                                <option value="94825">Manufactured Homes</option>
                                <option value="12605">Residential</option>
                                <option value="15897">Timeshares for Sale</option>
                                <option value="1607">Other Real Estate</option>
                            </optgroup>
                            <optgroup label="Specialty Services">
                                <option value="47126">Artistic Services</option>
                                <option value="50343">Custom Clothing Jewelry</option>
                                <option value="50349">eBay Auction Services</option>
                                <option value="47131">Graphic Logo Design</option>
                                <option value="170048">Home Improvement Services</option>
                                <option value="175814">Item Based Services</option>
                                <option value="50355">Media Editing Duplication</option>
                                <option value="20943">Printing Personalization</option>
                                <option value="47119">Restoration Repair</option>
                                <option value="47104">Web Computer Services</option>
                                <option value="317">Other Specialty Services</option>
                            </optgroup>
                            <optgroup label="Sporting Goods">
                                <option value="179767">Boxing, Martial Arts MMA</option>
                                <option value="7294">Cycling</option>
                                <option value="1492">Fishing</option>
                                <option value="15273">Fitness, Running Yoga</option>
                                <option value="1513">Golf</option>
                                <option value="7301">Hunting</option>
                                <option value="36274">Indoor Games</option>
                                <option value="159043">Outdoor Sports</option>
                                <option value="159049">Team Sports</option>
                                <option value="159134">Tennis Racquet Sports</option>
                                <option value="159136">Water Sports</option>
                                <option value="36259">Winter Sports</option>
                                <option value="310">Other Sporting Goods</option>
                                <option value="40146">Wholesale Lots</option>
                            </optgroup>
                            <optgroup label="Sports Mem, Cards Fan Shop">
                                <option value="51">Autographs-Original</option>
                                <option value="50115">Autographs-Reprints</option>
                                <option value="24409">Fan Apparel Souvenirs</option>
                                <option value="50116">Game Used Memorabilia</option>
                                <option value="50123">Vintage Sports Memorabilia</option>
                                <option value="56080">Wholesale Lots</option>
                                <option value="141755">Sports Stickers, Sets Albums</option>
                                <option value="212">Sports Trading Cards</option>
                            </optgroup>
                            <optgroup label="Stamps">
                                <option value="261">United States</option>
                                <option value="3478">Canada</option>
                                <option value="3499">Great Britain</option>
                                <option value="181423">Africa</option>
                                <option value="181416">Asia</option>
                                <option value="181424">Australia Oceania</option>
                                <option value="65174">British Colonies Territories</option>
                                <option value="179377">Caribbean</option>
                                <option value="4742">Europe</option>
                                <option value="181417">Latin America</option>
                                <option value="181422">Middle East</option>
                                <option value="181420">Worldwide</option>
                                <option value="4752">Topical Stamps</option>
                                <option value="7898">Specialty Philately</option>
                                <option value="181421">Publications Supplies</option>
                                <option value="170137">Other Stamps</option>
                            </optgroup>
                            <optgroup label="Tickets Experiences">
                                <option value="173633">Sports Tickets</option>
                                <option value="173634">Concert Tickets</option>
                                <option value="173635">Theater Tickets</option>
                                <option value="170594">Theme Park Club Passes</option>
                                <option value="178892">Parking Passes</option>
                                <option value="170591">Special Experiences</option>
                                <option value="1306">Other Tickets Experiences</option>
                            </optgroup>
                            <optgroup label="Toys Hobbies">
                                <option value="246">Action Figures</option>
                                <option value="49019">Beanbag Plush</option>
                                <option value="183446">Building Toys</option>
                                <option value="19016">Classic Toys</option>
                                <option value="2536">Collectible Card Games</option>
                                <option value="222">Diecast Toy Vehicles</option>
                                <option value="11731">Educational</option>
                                <option value="19071">Electronic, Battery Wind-Up</option>
                                <option value="19077">Fast Food Cereal Premiums</option>
                                <option value="233">Games</option>
                                <option value="58799">Marbles</option>
                                <option value="180250">Model Railroads Trains</option>
                                <option value="1188">Models Kits</option>
                                <option value="11743">Outdoor Toys Structures</option>
                                <option value="19169">Preschool Toys Pretend Play</option>
                                <option value="2613">Puzzles</option>
                                <option value="m2562">Radio Control Control Line</option>
                                <option value="19192">Robots, Monsters Space Toys</option>
                                <option value="2616">Slot Cars</option>
                                <option value="436">Stuffed Animals</option>
                                <option value="2631">Toy Soldiers</option>
                                <option value="2624">TV, Movie Character Toys</option>
                                <option value="717">Vintage Antique Toys</option>
                                <option value="40149">Wholesale Lots</option>
                            </optgroup>
                            <optgroup label="Travel">
                                <option value="3253">Airline</option>
                                <option value="164802">Campground RV Parks</option>
                                <option value="147399">Car Rental</option>
                                <option value="16078">Cruises</option>
                                <option value="16123">Lodging</option>
                                <option value="16080">Luggage</option>
                                <option value="173520">Luggage Accessories</option>
                                <option value="164803">Maps</option>
                                <option value="98982">Rail</option>
                                <option value="93838">Travel Accessories</option>
                                <option value="29578">Vacation Packages</option>
                                <option value="183477">Vintage Luggage Travel Accs</option>
                                <option value="1310">Other Travel</option>
                            </optgroup>
                            <optgroup label="Video Games Consoles">
                                <option value="139973">Video Games</option>
                                <option value="139971">Video Game Consoles</option>
                                <option value="54968">Video Game Accessories</option>
                                <option value="182174">Manuals, Inserts Box Art</option>
                                <option value="182175">Original Game Cases Boxes</option>
                                <option value="156597">Prepaid Gaming Cards</option>
                                <option value="171833">Replacement Parts Tools</option>
                                <option value="156595">Strategy Guides Cheats</option>
                                <option value="38583">Video Game Merchandise</option>
                                <option value="187">Other Video Games Consoles</option>
                                <option value="48749">Wholesale Lots</option>
                            </optgroup>
                            <optgroup label="Everything Else">
                                <option value="319">Adult Only</option>
                                <option value="3143">Career Development Education</option>
                                <option value="177600">eBay Special Offers</option>
                                <option value="20924">eBay User Tools</option>
                                <option value="88739">Funeral Cemetery</option>
                                <option value="20925">Genealogy</option>
                                <option value="102480">Information Products</option>
                                <option value="19266">Metaphysical</option>
                                <option value="102329">Personal Development</option>
                                <option value="102535">Personal Security</option>
                                <option value="102545">Religious Products Supplies</option>
                                <option value="102553">Reward Points Incentives</option>
                                <option value="1466">Weird Stuff</option>
                            </optgroup>
                            <optgroup label="Hunting">
                                <option value="177909">Blinds Treestands</option>
                                <option value="7304">Books Video</option>
                                <option value="159037">Bow</option>
                                <option value="36239">Clothing, Shoes Accessories</option>
                                <option value="36249">Decoys</option>
                                <option value="36252">Game Calls</option>
                                <option value="52505">Game Trail Cameras</option>
                                <option value="73943">Gun Parts</option>
                                <option value="177880">Gun Smithing Maintenance</option>
                                <option value="73937">Gun Storage</option>
                                <option value="73963">Holsters, Belts Pouches</option>
                                <option value="52502">Accessories</option>
                                <option value="71110">Dog Supplies</option>
                                <option value="14110">Trips Leases</option>
                                <option value="42574">Knives Tools</option>
                                <option value="31823">Reloading Equipment</option>
                                <option value="177904">Range Shooting Accessories</option>
                                <option value="31710">Scopes, Optics Lasers</option>
                                <option value="177890">Tactical Duty Gear</option>
                                <option value="36271">Taxidermy</option>
                                <option value="71131">Vintage Hunting</option>
                                <option value="383">Other</option>
                            </optgroup>
                            <optgroup label="Outdoor Sports">
                                <option value="20835">Archery</option>
                            </optgroup>
                            <optgroup label="Sports Trading Cards">
                                <option value="666">Auto Racing Cards</option>
                                <option value="213">Baseball Cards</option>
                                <option value="214">Basketball Cards</option>
                                <option value="133072">College Cards</option>
                                <option value="215">Football Cards</option>
                                <option value="4240">Golf Cards</option>
                                <option value="216">Ice Hockey Cards</option>
                                <option value="183444">Soccer Cards</option>
                            </optgroup>
                        </select>
                        <div>
                            <h4>Duplicate Checking</h4>
                            <p>
                                <input id="duplicateCheck" name="duplicateCheck" value="Duplicate" class="w3-check" style="height:1em;vertical-align:super;" type="checkbox">
                                <label for="duplicateCheck">Show Duplicates</label>
                            </p>
                        </div>
                    </div>

                    <div class="w3-container w3-card-2 w3-col l1 w3-hide-medium w3-hide-small">
                        <h4>Price</h4>
                        <p>
                        <label for="minPrice" class="w3-small">Minimum</label>
                        <input id="minPrice" name="minPrice" class="w3-input w3-border-0" style="height:2em">
                        <label for="maxPrice" class="w3-small">Maximum</label>
                        <input id="maxPrice" name="maxPrice" class="w3-input w3-border-0" style="height:2em">
                        </p>
                    </div>

                    <div class="w3-container w3-card-2 w3-col l1 w3-hide-medium w3-hide-small">
                        <h4>Bids</h4>
                        <p>
                        <label for="minBids" class="w3-small">Minimum</label>
                        <input id="minBids" name="minBids" class="w3-input w3-border-0" type="number" style="height:2em">
                        <label for="maxBids" class="w3-small">Maximum</label>
                        <input id="maxBids" name="maxBids" class="w3-input w3-border-0" type="number" style="height:2em">
                        </p>
                    </div>

                    <div class="w3-container w3-card-2 w3-col l1 w3-hide-medium w3-hide-small">
                        <h4>Feedback</h4>
                        <p>
                        <label for="minFeedback" class="w3-small">Minimum</label>
                        <input id="minFeedback" name="minFeedback" class="w3-input w3-border-0" type="number" style="height:2em">
                        <label for="maxFeedback" class="w3-small">Maximum</label>
                        <input id="maxFeedback" name="maxFeedback" class="w3-input w3-border-0" type="number" style="height:2em">
                        </p>
                    </div>

                    <div class="w3-container w3-card-2 w3-col l1 w3-hide-medium w3-hide-small">
                        <h4>Quantity</h4>
                        <p>
                        <label for="minQuantity" class="w3-small">Minimum</label>
                        <input id="minQuantity" name="minQuantity" class="w3-input w3-border-0" type="number" style="height:2em">
                        <label for="maxQuantity" class="w3-small">Maximum</label>
                        <input id="maxQuantity" name="maxQuantity" class="w3-input w3-border-0" type="number" style="height:2em">
                        </p>
                    </div>

                    <div class="w3-container w3-card-2 w3-col l1 w3-hide-medium w3-hide-small">
                        <h4>Start Date</h4>
                        <p>
                        <label for="minStartDate" class="w3-small">On or After <img src="images2/cal.gif" alt="Calendar Picker" onclick="javascript:NewCssCal('minStartDate','yyyyMMdd','arrow',false,'24',false,'past')" style="cursor:pointer" /></label>
                        <input id="minStartDate" name="minStartDate" class="w3-input w3-border-0" style="height:2em" type="text">
                        <label for="maxStartDate" class="w3-small">On or Before <img src="images2/cal.gif" alt="Calendar Picker" onclick="javascript:NewCssCal('maxStartDate','yyyyMMdd','arrow',false,'24',false,'past')" style="cursor:pointer" /></label>
                        <input id="maxStartDate" name="maxStartDate" class="w3-input w3-border-0" style="height:2em" type="text">
                        </p>
                    </div>

                    <div class="w3-container w3-card-2 w3-col l1 w3-hide-medium w3-hide-small">
                        <h4>End Date</h4>
                        <p>
                        <label for="minEndDate" class="w3-small">On or After <img src="images2/cal.gif" alt="Calendar Picker" onclick="javascript:NewCssCal('minEndDate','yyyyMMdd','arrow',false,'24')" style="cursor:pointer" /></label>
                        <input id="minEndDate" name="minEndDate" class="w3-input w3-border-0" style="height:2em" type="text">
                        <label for="maxEndDate" class="w3-small">On or Before <img src="images2/cal.gif" alt="Calendar Picker" onclick="javascript:NewCssCal('maxEndDate','yyyyMMdd','arrow',false,'24')" style="cursor:pointer" /></label>
                        <input id="maxEndDate" name="maxEndDate" class="w3-input w3-border-0" style="height:2em" type="text">
                        </p>
                    </div>
                </div>

                <!-- https://developer.ebay.com/DevZone/finding/Concepts/FindingAPIGuide.html#advopers -->
                <div id="keywordHelp" class="w3-container w3-card-2 w3-padding w3-hide">
                    <a href="javascript:void(0)" class="w3-right w3-xlarge w3-ripple" style="text-decoration:none;" onclick="hideKeywordHelp()">Close &#10006;</a>
                    <h3>Advanced Keyword Search Operators</h3>
                    <p>The value specified in the keywords field can contain one or more keywords. The words "and" and "or" are treated like any other word. Only use "and," "or," or "the" if you are searching for listings containing these words. You can
                        use AND or OR logic by including certain modifiers. Be careful when using spaces before or after modifiers, such as plus signs ("+") or minus signs ("-").</p>
                    <p>The following table shows the operators and character punctuation that can be used in keyword queries, and the effects they have.</p>
                    <table class="w3-table-all">
                        <tr>
                            <th>Operator</th>
                            <th>Description</th>
                            <th>Example</th>
                            <th>Returns</th>
                        </tr>
                        <tr>
                            <td>Space between words</td>
                            <td>Applies AND logic to multiple keywords.</td>
                            <td>baseball card</td>
                            <td>Items with both the words "baseball" and "card".
                                <br/>Note: Keyword queries consisting of keywords separated by spaces only are subject to automatic keyword expansions.</td>
                        </tr>
                        <tr>
                            <td>Comma (,) between words, with no parentheses or spaces</td>
                            <td>Requires an exact sequence of words.</td>
                            <td>baseball,card</td>
                            <td>Items with the exact phrase "baseball card" in the title. This is equivalent to specifying the keywords, separated by spaces, in order within quotation marks (e.g., "baseball card").</td>
                        </tr>
                        <tr>
                            <td>Comma between words in parentheses with no spaces</td>
                            <td>Applies OR logic to multiple keywords.</td>
                            <td>(baseball,card)</td>
                            <td>Items with either the word "baseball" or the word "card" in the title.</td>
                        </tr>
                        <tr>
                            <td>Quoted (" ") words</td>
                            <td>Requires an exact sequence of words.</td>
                            <td>"baseball card"</td>
                            <td>Items with the exact phrase "baseball card" in the title.</td>
                        </tr>
                        <tr>
                            <td>Minus ("-") sign before a word</td>
                            <td>Applies NOT logic to a single word. Specified word cannot be present.</td>
                            <td>baseball -autograph</td>
                            <td>Items that have the word "baseball" but not "autograph".
                                <br/>Note: A keyword query cannot consist of excluded words only. You must include one or more search terms in order to use the NOT operator ("-"). For example, "-autograph" is not a valid keywords value on its own, but
                                "baseball -autograph" (i.e., &lt;keywords&gt;baseball -autograph&lt;/keywords&gt;) will work.
                                <br/>When excluding words, you must have a space before the minus sign and no space between the minus sign and the word you are excluding.</td>
                        </tr>
                        <tr>
                            <td>Minus ("-") sign before a group of words in parentheses</td>
                            <td>Applies NOT logic to a group of words. Specified words cannot be present.</td>
                            <td>baseball -(autograph,card,star)</td>
                            <td>Items with the word "baseball" but not "autograph," "card," or "star".</td>
                        </tr>
                        <tr>
                            <td>At sign ("@")</td>
                            <td>Search must find two of three words from a list.</td>
                            <td>@1 baseball autograph card</td>
                            <td>Items with two of the three words "baseball," "autograph," and "card". For a "3 out of 4" search, use @2 and a list of four words.</td>
                        </tr>
                        <tr>
                            <td>Plus sign ("+")</td>
                            <td>Concatenates a query string using AND logic with another keyword.</td>
                            <td>@1 baseball autograph card +star</td>
                            <td>Items with any two of the three words "baseball," "autograph," or "card" in the title plus the word "star".</td>
                        </tr>
                    </table>
                    <p>With the exception of the advanced search operators, punctuation marks, such as hyphens (-), commas followed by spaces (, ), exclamation points (!), question marks (?), slashes (/), and forward slashes (\) are excluded from matching.
                        For example, a search for "3/4 sleeve" (i.e., &lt;keywords&gt;"3/4 sleeve"&lt;/keywords&gt;) will match "3-4 sleeve", "3\4 sleeve", "3/4-sleeve", etc.</p>
                    <h3>Automatic Keyword Expansions</h3>
                    <p>Keyword queries always search item titles for words or phrases that match exactly the keywords you specified. In some cases, eBay automatically expands keyword queries to increase the number of relevant results in the response. Keyword
                        searches can be expanded by expanding the query and/or expanding the places in which to search for matching terms. This is why search results may contain items with titles that do not have all the keywords you specified in your
                        query.
                    </p>
                    <p>Using advanced search operators (e.g., " ", ( ), -, +, *, or @) in your keyword query disables automatic keyword expansions. For example, an exact phrase search, such as &lt;keywords&gt;"baseball card"&lt;/keywords&gt; will limit the
                        search results to items with the exact phrase in the title only.</p>
                    <table class="w3-table-all">
                        <tr>
                            <th>Expansion Type</th>
                            <th>Description</th>
                        </tr>
                        <tr>
                            <td>Keyword to keyword</td>
                            <td>Modifies your keyword query to search for either your original keywords, or a synonymous keyword from eBay's dictionary, such as a root word or a plural form.</td>
                        </tr>
                        <tr>
                            <td>Keyword to category</td>
                            <td>Modifies your query to search for items that have a specific keyword in the title or for items listed in a specific related category.</td>
                        </tr>
                        <tr>
                            <td>Keyword to structured item data</td>
                            <td>Modifies your query to search for items that have the keywords from the original query in the title or in the item's structured data, such as item specifics or parts compatibility information.</td>
                        </tr>
                    </table>
                </div>

                <div class="w3-row">
                    <div class="w3-container w3-card-2 w3-col l3 m6">
                        <h4>Listing Type</h4>
                        <p class="no-pad">
                            <input id="ltAll" name="listingType" value="All" class="w3-check" style="height:1em;vertical-align:super;" type="checkbox" checked="checked">
                            <label for="ltAll">All</label>
                        </p>
                        <p class="no-pad">
                            <input id="ltAuction" name="listingType" value="Auction" class="w3-check" style="height:1em;vertical-align:super;" type="checkbox">
                            <label for="ltAuction">Auction</label>
                        </p>
                        <p class="no-pad">
                            <input id="ltAuctionWithBIN" name="listingType" value="AuctionWithBIN" class="w3-check" style="height:1em;vertical-align:super;" type="checkbox">
                            <label for="ltAuctionWithBIN">Auction with BIN</label>
                        </p>
                        <p class="no-pad">
                            <input id="ltClassified" name="listingType" value="Classified" class="w3-check" style="height:1em;vertical-align:super;" type="checkbox">
                            <label for="ltClassified">Classified</label>
                        </p>
                        <p class="no-pad">
                            <input id="ltFixedPrice" name="listingType" value="FixedPrice" class="w3-check" style="height:1em;vertical-align:super;" type="checkbox">
                            <label for="ltFixedPrice">Fixed Price</label>
                        </p>
                        <p class="no-pad">
                            <input id="ltStoreInventory" name="listingType" value="StoreInventory" class="w3-check" style="height:1em;vertical-align:super;" type="checkbox">
                            <label for="ltStoreInventory">Store Inventory</label>
                        </p>
                        <br/>
                        <h4>Seller</h4>
                        <p>
                            <input id="sellerName" name="sellerName" class="w3-input w3-border-0" style="height:2em;" type="text">
                            <label for="sellerName">Seller Name</label>
                        </p>

                    </div>
                    <div class="w3-container w3-card-2 w3-col l3 m6">
                        <h4>Condition</h4>
                        <p class="no-pad">
                            <input id="condNew" name="condition" value="New" class="w3-check" style="height:1em;vertical-align:super;" type="checkbox">
                            <label for="condNew">New</label>
                        </p>
                        <p class="no-pad">
                            <input id="condUsed" name="condition" value="Used" class="w3-check" style="height:1em;vertical-align:super;" type="checkbox">
                            <label for="condUsed">Used</label>
                        </p>
                        <p class="no-pad">
                            <input id="condUnspecified" name="condition" value="Unspecified" class="w3-check" style="height:1em;vertical-align:super;" type="checkbox">
                            <label for="condUnspecified">Unspecified</label>
                        </p>
                        <br/>
                        <h4>Located</h4>
                        <select id="locatedIn" class="w3-select" style="height:3em" name="locatedIn">
                            <option value="North%20America" selected="selected">North America</option>
                            <option value="WorldWide">World Wide</option>
                        </select>
                        <br/>
                        <p>
                            <input id="localSearchOnly" name="localSearchOnly" class="w3-check" type="checkbox" style="height:1em;vertical-align:super;">
                            <label for="localSearchOnly">Local Search Only</label>
                            <input id="maxDistance" name="maxDistance" class="w3-input w3-border-0" type="number" style="height:3em">
                            <label for="maxDistance" class="w3-small">Maximum Distance (Miles)</label>
                        </p>
                    </div>

                    <div class="w3-container w3-card-2 w3-col l2  w3-hide-medium w3-hide-small">
                        <h4>Detail Condition</h4>
                        <p class="no-pad">
                            <input id="cond1000" name="conditionDetail" value="1000" class="w3-check" style="height:1em;vertical-align:super;" type="checkbox">
                            <label for="cond1000">1000 - New</label>
                        </p>
                        <p class="no-pad">
                            <input id="cond1500" name="conditionDetail" value="1500" class="w3-check" style="height:1em;vertical-align:super;" type="checkbox">
                            <label for="cond1500">1500 - New other (see details)</label>
                        </p>
                        <p class="no-pad">
                            <input id="cond1750" name="conditionDetail" value="1750" class="w3-check" style="height:1em;vertical-align:super;" type="checkbox">
                            <label for="cond1750">1750 - New with defects</label>
                        </p>
                        <p class="no-pad">
                            <input id="cond2000" name="conditionDetail" value="2000" class="w3-check" style="height:1em;vertical-align:super;" type="checkbox">
                            <label for="cond2000">2000 - Manufacturer refurbished</label>
                        </p>
                        <p class="no-pad">
                            <input id="cond2500" name="conditionDetail" value="2500" class="w3-check" style="height:1em;vertical-align:super;" type="checkbox">
                            <label for="cond2500">2500 - Seller refurbished</label>
                        </p>
                        <p class="no-pad">
                            <input id="cond2750" name="conditionDetail" value="2750" class="w3-check" style="height:1em;vertical-align:super;" type="checkbox">
                            <label for="cond2750">2750 - Like New</label>
                        </p>
                        <p class="no-pad">
                            <input id="cond3000" name="conditionDetail" value="3000" class="w3-check" style="height:1em;vertical-align:super;" type="checkbox">
                            <label for="cond3000">3000 - Used / Pre-owned</label>
                        </p>
                        <p class="no-pad">
                            <input id="cond4000" name="conditionDetail" value="4000" class="w3-check" style="height:1em;vertical-align:super;" type="checkbox">
                            <label for="cond4000">4000 - Very Good</label>
                        </p>
                        <p class="no-pad">
                            <input id="cond5000" name="conditionDetail" value="5000" class="w3-check" style="height:1em;vertical-align:super;" type="checkbox">
                            <label for="cond5000">5000 - Good</label>
                        </p>
                        <p class="no-pad">
                            <input id="cond6000" name="conditionDetail" value="6000" class="w3-check" style="height:1em;vertical-align:super;" type="checkbox">
                            <label for="cond6000">6000 - Acceptable</label>
                        </p>
                        <p class="no-pad">
                            <input id="cond7000" name="conditionDetail" value="7000" class="w3-check" style="height:1em;vertical-align:super;" type="checkbox">
                            <label for="cond7000">7000 - For parts or not working</label>
                        </p>
                    </div>

                    <div class="w3-container w3-card-2 w3-col l2 m6">
                        <h4>Miscellaneous</h4>
                        <p class="no-pad">
                            <input id="freeShippingOnly" name="freeShippingOnly" class="w3-check" style="height:1em;vertical-align:super;" type="checkbox">
                            <label for="freeShippingOnly">Free Shipping Only</label>
                        </p>
                        <p class="no-pad">
                            <input id="bestOfferOnly" name="bestOfferOnly" class="w3-check" style="height:1em;vertical-align:super;" type="checkbox">
                            <label for="bestOfferOnly">Best Offer Only</label>
                        </p>
                        <p class="no-pad">
                            <input id="lotsOnly" name="lotsOnly" class="w3-check" style="height:1em;vertical-align:super;" type="checkbox">
                            <label for="lotsOnly">Lots Only</label>
                        </p>
                        <p class="no-pad">
                            <input id="hideDuplicateItems" name="hideDuplicateItems" class="w3-check" style="height:1em;vertical-align:super;" type="checkbox" checked="checked">
                            <label for="hideDuplicateItems">Hide Duplicate Items</label>
                        </p>
                        <p class="no-pad">
                            <input id="outletSellerOnly" name="outletSellerOnly" class="w3-check" style="height:1em;vertical-align:super;" type="checkbox">
                            <label for="outletSellerOnly">Outlet Seller Only</label>
                        </p>
                        <p class="no-pad">
                            <input id="completedItemsOnly" name="completedItemsOnly" class="w3-check" style="height:1em;vertical-align:super;" type="checkbox">
                            <label for="completedItemsOnly">Completed Items</label>
                        </p>
                        <p class="no-pad">
                            <input id="searchDescription" name="searchDescription" class="w3-check" style="height:1em;vertical-align:super;" type="checkbox">
                            <label for="searchDescription">Search Description</label>
                        </p>
                        <p class="no-pad">
                            <input id="soldOnly" name="soldOnly" class="w3-check" type="checkbox" style="height:1em;vertical-align:super;" disabled="disabled">
                            <label for="soldOnly">Sold Items Only</label>
                        </p>
                        <p class="no-pad">
                            <input id="localPickupOnly" name="localPickupOnly" class="w3-check" type="checkbox" style="height:1em;vertical-align:super;">
                            <label for="localPickupOnly">Local Pickup Only</label>
                        </p>
                    </div>

                    <div class="w3-container w3-card-2 w3-col l2 m6 w3-hide-small">
                        <h4>Sort Order</h4>
                        <p class="no-pad">
                            <input id="soBestMatch" name="sortOrder" value="BestMatch" class="w3-radio" style="height:1em;vertical-align:super;" type="radio">
                            <label for="soBestMatch">Best Match</label>
                        </p>
                        <p class="no-pad">
                            <input id="soBidCountFewest" name="sortOrder" value="BidCountFewest" class="w3-radio" style="height:1em;vertical-align:super;" type="radio">
                            <label for="soBidCountFewest">Bid Count Fewest (Auctions Only)</label>
                        </p>
                        <p class="no-pad">
                            <input id="soBidCountMost" name="sortOrder" value="BidCountMost" class="w3-radio" style="height:1em;vertical-align:super;" type="radio">
                            <label for="soBidCountMost">Bid Count Most (Auctions Only)</label>
                        </p>
                        <p class="no-pad">
                            <input id="soCurrentPriceHighest" name="sortOrder" value="CurrentPriceHighest" class="w3-radio" style="height:1em;vertical-align:super;" type="radio">
                            <label for="soCurrentPriceHighest">Current Price Highest</label>
                        </p>
                        <p class="no-pad">
                            <input id="soEndTimeSoonest" name="sortOrder" value="EndTimeSoonest" class="w3-radio" style="height:1em;vertical-align:super;" type="radio">
                            <label for="soEndTimeSoonest">End Time Soonest</label>
                        </p>
                        <p class="no-pad">
                            <input id="soPricePlusShippingHighest" name="sortOrder" value="PricePlusShippingHighest" class="w3-radio" style="height:1em;vertical-align:super;" type="radio">
                            <label for="soPricePlusShippingHighest">Price Plus Shipping Highest</label>
                        </p>
                        <p class="no-pad">
                            <input id="soPricePlusShippingLowest" name="sortOrder" value="PricePlusShippingLowest" class="w3-radio" style="height:1em;vertical-align:super;" type="radio" checked="checked">
                            <label for="soPricePlusShippingLowest">Price Plus Shipping Lowest</label>
                        </p>
                        <p class="no-pad">
                            <input id="soStartTimeNewest" name="sortOrder" value="StartTimeNewest" class="w3-radio" style="height:1em;vertical-align:super;" type="radio">
                            <label for="soStartTimeNewest">Start Time Newest</label>
                        </p>
                        <p class="no-pad">
                            <input id="soWatchCountDecreaseSort" name="sortOrder" value="WatchCountDecreaseSort" class="w3-radio" style="height:1em;vertical-align:super;" type="radio">
                            <label for="soWatchCountDecreaseSort">Watch Count Decrease Sort</label>
                        </p>
                        <p class="no-pad">
                            <input id="soDistance" name="sortOrder" value="Distance" class="w3-radio" style="height:1em;vertical-align:super;" type="radio">
                            <label for="soDistance">Distance</label>
                        </p>
                    </div>
                </div>

                <input type="submit" class="w3-btn w3-black w3-margin w3-round-large w3-ripple" value="Search" />
                <input type="button" class="w3-btn w3-black w3-margin w3-round-large w3-ripple" onclick="resetForm()" value="Reset form">
                <a href="javascript:void(0)" id="pricing" class="w3-btn w3-black w3-margin w3-right w3-round-large w3-hide w3-ripple" onclick="getPricing()">Pricing</a>
                <a href="javascript:void(0)" id="download" class="w3-btn w3-black w3-margin w3-right w3-round-large w3-hide w3-ripple" onclick="downloadAsCSV()">Download</a>
            </form>
        </div>

        <div id="warnings" class="w3-container w3-padding w3-margin w3-card-4 w3-red w3-hide"></div>
        <div id="progressBarDiv" class="w3-container w3-padding w3-margin w3-card-4 w3-hide">
                <h2 id="progressBarHeader"></h2>
            <div class="w3-light-grey">
                <div id="progressBar" class="w3-container w3-green w3-center" style="width:0%">0%</div>
            </div>
        </div>
        <div id="duplicates" class="w3-container w3-padding w3-margin w3-card-4 w3-hide">
            <h2>Duplicates</h2>
            <p id="duplicatesText"></p>
        </div>
        <div id="prices" class="w3-container w3-padding w3-margin w3-card-4 w3-hide"></div>
        <div id="results" class="w3-container w3-padding w3-margin w3-card-4 w3-hide"></div>
        <div id="query" class="w3-container w3-padding w3-margin w3-card-4 w3-hide"></div>
        <div id="csv" class="w3-container w3-padding w3-margin w3-card-4 w3-hide"></div>
        <div id="parameter" class="w3-container w3-padding w3-margin w3-card-4 w3-hide"></div>

        <footer class="w3-container w3-center w3-border-top w3-margin">
            <p>Copyright &#169; 2019 MUNA Trading. All rights reserved.</p>
        </footer>

    </div>

    <script>

// Globals
var pagenumber = 1;
var totalEntries = 0;
var asyncFlag = false;
var maxPages = 0;
var currentPage = 0;
var valueStartMin;
var valueStartMax;
var valueEndMin;
var valueEndMax;
var getShippingCostsDone = false;
var ship_str = "";
var ship_str_cost = "";
var ship_str_tax = "";
var maxPricingPages = [-1, -1];
var totalPricingEntries = [0, 0];


function paginationNav(strCurrentPage, strMaxPage) {
        var str = "";

        var currentPage = parseInt(strCurrentPage);
        var maxPage = parseInt(strMaxPage);

        if (maxPage == 1) {
                return str;
        }

        if (currentPage > 1) {
                str += '<a href="javascript:void(0)" class="w3-button" onclick="prevPage()">&laquo;</a>';
        } else {
                str += '<a href="javascript:void(0)" class="w3-button w3-disabled" onclick="#">&laquo;</a>';
        }

        if (currentPage < 100 && currentPage < maxPage) {
                str += '<a href="javascript:void(0)" class="w3-button" onclick="nextPage()">&raquo;</a>';
        } else {
                str += '<a href="javascript:void(0)" class="w3-button w3-disabled" onclick="#">&raquo;</a>';
        }

        return str;
}

function prevPage() {
        pagenumber--;
        eBaySearch(pagenumber);
}

function nextPage() {
        pagenumber++;
        eBaySearch(pagenumber);
}

// Parse the response and build an HTML table to display search results
function _cb_findItemsAdvanced(root) {
        var response;

        // Error Handling
        if (root.findItemsAdvancedResponse !== undefined) {
                response = root.findItemsAdvancedResponse[0];
        } else if (root.findItemsByProductResponse !== undefined) {
                response = root.findItemsByProductResponse[0];
        } else {
                return;
        }

        var ack = response.ack;
        if (ack != 'Success') {
                printeBayAPIError(response);

                if (ack == 'Failure' || ack == 'PartialFailure') {
                        return;
                }
        }

        var i;
        var items = response.searchResult[0].item || [];
        var html = [];
        var distance;
        var distanceUnit;

        totalEntries = Number(response.paginationOutput[0].totalEntries);
        html.push('<p class="w3-center">Page ' + response.paginationOutput[0].pageNumber + ' of ' + response.paginationOutput[0].totalPages + ' ' + paginationNav(response.paginationOutput[0].pageNumber, response.paginationOutput[0].totalPages) + ' | Total Entries: ' + response.paginationOutput[0].totalEntries + '</p>');
        html.push('<table class="w3-table-all w3-hoverable">');
        html.push('<tr><th>Picture</th><th>Description</th><th>Price</th><th>Duration</th><th>Style</th><th>Seller</th><th>Shipping</th></tr><tbody>');

        for (i = 0; i < items.length; ++i) {
                var item = items[i];
                var title = item.title;
                var pic = '';
                if (item.galleryURL !== undefined) {
                        pic = item.galleryURL[0].replace('http:', 'https:');
                }
                var viewitem = item.viewItemURL;
                var price = Number(item.sellingStatus[0].convertedCurrentPrice[0].__value__);
                var shPrice = 0;
                if (item.shippingInfo[0].shippingServiceCost) {
                        shPrice = Number(item.shippingInfo[0].shippingServiceCost[0].__value__);
                }
                var timeleftStr = formatTimeleft(moment.duration(item.sellingStatus[0].timeLeft).asSeconds());
                var startTime = moment(item.listingInfo[0].startTime, moment.ISO_8601).format("YYYY-MM-DD hh:MMA");
                var endTime = moment(item.listingInfo[0].endTime, moment.ISO_8601).format("YYYY-MM-DD hh:MMA");
                var condition = item.condition ? item.condition[0].conditionDisplayName : "Unknown";
                var bidCount = item.sellingStatus[0].bidCount;
                var sellingState = item.sellingStatus[0].sellingState;
                var listingType = item.listingInfo[0].listingType;
                var BO = item.listingInfo[0].bestOfferEnabled;
                var location = item.location;
                var shippingType = item.shippingInfo[0].shippingType;
                var shippingLocation = item.shippingInfo[0].shipToLocations;
                var sellerUserName = item.sellerInfo[0].sellerUserName;
                var feedbackScore = item.sellerInfo[0].feedbackScore;
                var positiveFeedbackPercent = item.sellerInfo[0].positiveFeedbackPercent;
                var convertedBuyItNowPrice = item.listingInfo[0].convertedBuyItNowPrice;
                if (item.distance) {
                        distance = item.distance[0].__value__;
                        distanceUnit = item.distance[0]["@unit"];
                }
                var watchCount = item.listingInfo[0].watchCount ? item.listingInfo[0].watchCount : 0;

                if (title && viewitem) {
                        var str = '<tr><td> (' + (i + 1) + ') ' + '<a href="javascript:void(0)" onclick="findSingleItem(' + item.itemId + ')"><img src="' + pic + '" alt="Gallery Image"></a></td>' + '<td><a href="javascript:void(0)" onclick="findSingleItem(' + item.itemId + ')">' + title + '</a>';
                        if (item.subtitle) {
                                str += '<br/>' + item.subtitle;
                        }
                        str += '<br/>';
                        str += '<a href="' + viewitem + '" target="_blank">' + item.itemId + '</a>';
                        str += '<a href="' + window.location.protocol + "//" + window.location.hostname + window.location.pathname + '?keyword=' + String(title).replace(/ /g, "+").replace(/\"/g, "").replace(/#/g, "") + '&listingType=All&hideDuplicateItems=on&completedItemsOnly=on&locatedIn=North+America&sortOrder=BestMatch" class="w3-btn w3-black w3-margin w3-round-large w3-ripple w3-left" style="font-size:8px!important" target="_blank">Search Completed</a>';
                        str += '</td><td>$' + price.toFixed(2);
                        if (convertedBuyItNowPrice) {
                                str += '<br/>BIN $' + Number(convertedBuyItNowPrice[0].__value__).toFixed(2);
                        }
                        if (item.shippingInfo[0].shippingServiceCost && shPrice) {
                                str += '<br/>S&H $' + shPrice.toFixed(2);
                        }
                        str += "<br/>" + condition;
                        if (item.sellingStatus[0].bidCount) {
                                str += '<br/>' + bidCount + ' Bid(s)';
                        }

                        str += '</td><td>' + timeleftStr + '<br/>' + startTime + '<br/>' + endTime;
                        if (item.listingInfo[0].watchCount) {
                                str += '<br/>' + watchCount + ' Watcher(s)';
                        }
                        str += '</td>';
                        str += '<td>' + sellingState + '<br/>' + listingType;
                        if (BO == 'true') {
                                str += '<br/>Best Offer';
                        }
                        str += '</td><td>' + sellerUserName + '<br/>' + feedbackScore + '<br/>' + positiveFeedbackPercent + '%</td>';
                        str += '<td>' + location;
                        if (item.distance) {
                                str += ' (' + distance + ' ' + distanceUnit + ')';
                        }
                        str += '<br/>' + shippingType + '<br/>' + shippingLocation + '</td>';
                        str += '</tr>';

                        html.push(str);
                }
        }
        html.push('</tbody></table>');
        html.push('<p class="w3-center">Page ' + response.paginationOutput[0].pageNumber + ' of ' + response.paginationOutput[0].totalPages + ' ' + paginationNav(response.paginationOutput[0].pageNumber, response.paginationOutput[0].totalPages) + ' | Total Entries: ' + response.paginationOutput[0].totalEntries + '</p>');

        var x = document.getElementById("results");
        x.innerHTML = html.join("");
        if (x.className.indexOf("w3-show") == -1) {
                x.className += " w3-show";
        }
        x.scrollIntoView(true);

        if (Number(response.paginationOutput[0].totalEntries) > 0) {
                x = document.getElementById("download");
                if (x.className.indexOf("w3-show") == -1) {
                        x.className += " w3-show";
                }

                x = document.getElementById("pricing");
                if (x.className.indexOf("w3-show") == -1) {
                        x.className += " w3-show";
                }
        }
} // End _cb_findItemsAdvanced() function

// Parse the response and build an HTML table to display search results
function _cb_findCompletedItems(root) {
        // Error Handling
        var i;
        var response = root.findCompletedItemsResponse[0];
        var ack = response.ack;
        if (ack != 'Success') {
                printeBayAPIError(response);

                if (ack == 'Failure' || ack == 'PartialFailure') {
                        return;
                }
        }

        var items = root.findCompletedItemsResponse[0].searchResult[0].item || [];
        var html = [];
        var distance;
        var distanceUnit;

        totalEntries = Number(response.paginationOutput[0].totalEntries);
        html.push('<p class="w3-center">Page ' + response.paginationOutput[0].pageNumber + ' of ' + response.paginationOutput[0].totalPages + ' ' + paginationNav(response.paginationOutput[0].pageNumber, response.paginationOutput[0].totalPages) + ' | Total Entries: ' + response.paginationOutput[0].totalEntries + '</p>');
        html.push('<table class="w3-table-all w3-hoverable">');
        html.push('<tr><th>Picture</th><th>Description</th><th>Price</th><th>Duration</th><th>Style</th><th>Seller</th><th>Shipping</th></tr><tbody>');

        for (i = 0; i < items.length; ++i) {
                var item = items[i];
                var title = item.title;
                var pic = item.galleryURL[0].replace('http:', 'https:');
                var viewitem = item.viewItemURL;
                var price = Number(item.sellingStatus[0].convertedCurrentPrice[0].__value__);
                var shPrice = 0;
                if (item.shippingInfo[0].shippingServiceCost) {
                        shPrice = Number(item.shippingInfo[0].shippingServiceCost[0].__value__);
                }
                var startTime = moment(item.listingInfo[0].startTime, moment.ISO_8601).format("YYYY-MM-DD hh:MMA");
                var endTime = moment(item.listingInfo[0].endTime, moment.ISO_8601).format("YYYY-MM-DD hh:MMA");
                var condition = item.condition ? item.condition[0].conditionDisplayName : "Unknown";
                var bidCount = item.sellingStatus[0].bidCount;
                var sellingState = item.sellingStatus[0].sellingState;
                var sold = (sellingState == "EndedWithSales");
                var listingType = item.listingInfo[0].listingType;
                var BO = item.listingInfo[0].bestOfferEnabled;
                var location = item.location;
                var shippingType = item.shippingInfo[0].shippingType;
                var shippingLocation = item.shippingInfo[0].shipToLocations;
                var sellerUserName = item.sellerInfo[0].sellerUserName;
                var feedbackScore = item.sellerInfo[0].feedbackScore;
                var positiveFeedbackPercent = item.sellerInfo[0].positiveFeedbackPercent;
                var convertedBuyItNowPrice = item.listingInfo[0].convertedBuyItNowPrice;
                if (item.distance) {
                        distance = item.distance[0].__value__;
                        distanceUnit = item.distance[0]["@unit"];
                }
                var watchCount = item.listingInfo[0].watchCount ? item.listingInfo[0].watchCount : 0;

                if (title && viewitem) {
                        var str = '<tr><td>(' + (i + 1) + ') ' + '<a href="javascript:void(0)" onclick="findSingleItem(' + item.itemId + ')"><img src="' + pic + '" alt="Gallery Image"></a></td><td><a href="javascript:void(0)" onclick="findSingleItem(' + item.itemId + ')">' + title + '</a><br/>';
                        str += '<a href="' + viewitem + '" target="_blank">' + item.itemId + '</a>';
                        str += '</td><td style="color:';
                        if (sold) {
                                str += 'green';
                        } else {
                                str += 'red';
                        }

                        str += '">$' + price.toFixed(2);
                        if (convertedBuyItNowPrice) {
                                str += '<br/>BIN $' + Number(convertedBuyItNowPrice[0].__value__).toFixed(2);
                        }
                        if (item.shippingInfo[0].shippingServiceCost && shPrice) {
                                str += '<br/>S&H $' + shPrice.toFixed(2);
                        }
                        str += "<br/>" + condition;
                        if (item.sellingStatus[0].bidCount) {
                                str += '<br/>' + bidCount + ' Bid(s)';
                        }
                        str += '</td><td>' + startTime + '<br/>' + endTime + '<br/>';
                        str += listingType;
                        if (BO == 'true') {
                                str += '<br/>Best Offer';
                        }
                        if (item.listingInfo[0].watchCount) {
                                str += '<br/>' + watchCount + ' Watcher(s)';
                        }
                        str += '</td><td>' + sellerUserName + '<br/>' + feedbackScore + '<br/>' + positiveFeedbackPercent + '%</td>';
                        str += '<td>' + location;
                        if (item.distance) {
                                str += ' (' + distance + ' ' + distanceUnit + ')';
                        }
                        str += '<br/>' + shippingType + '<br/>' + shippingLocation + '</td>';
                        str += '</tr>';

                        html.push(str);
                }
        }
        html.push('</tbody></table>');
        html.push('<p class="w3-center">Page ' + response.paginationOutput[0].pageNumber + ' of ' + response.paginationOutput[0].totalPages + ' ' + paginationNav(response.paginationOutput[0].pageNumber, response.paginationOutput[0].totalPages) + ' | Total Entries: ' + response.paginationOutput[0].totalEntries + '</p>');


        var x = document.getElementById("results");
        x.innerHTML = html.join("");
        if (x.className.indexOf("w3-show") == -1) {
                x.className += " w3-show";
        }
        x.scrollIntoView(true);

        if (Number(response.paginationOutput[0].totalEntries) > 0) {
                x = document.getElementById("download");
                if (x.className.indexOf("w3-show") == -1) {
                        x.className += " w3-show";
                }

                x = document.getElementById("pricing");
                if (x.className.indexOf("w3-show") == -1) {
                        x.className += " w3-show";
                }
        }
} // End _cb_findCompletedItems() function

var ebayRecommendedKeywords = "";

// Parse the response and build an HTML table to display search results
function _cb_getKeywordRecommendations(root) {
        // Error Handling
        var response = root.getSearchKeywordsRecommendationResponse[0];
        var ack = response.ack;
        var x;
        if (ack == 'Success') {
                x = document.getElementById("recommendation");
                x.innerHTML = 'Keyword Recommendation:<br/><a href="javascript:void(0)" onclick="copyKeywordRecommendations()">' + response.keywords + '</a>';
                ebayRecommendedKeywords = response.keywords;
        } else if (ack == 'Warning' && response.errorMessage[0].error[0].errorId == 59) {
                x = document.getElementById("recommendation");
                x.innerHTML = "No Keyword Recommendations";
        } else {
                printeBayAPIError(response);

                if (ack == 'Failure' || ack == 'PartialFailure') {
                        return;
                }
        }
} // End _cb_getKeywordRecommendations() function

function copyKeywordRecommendations() {
        document.getElementById("keyword").value = ebayRecommendedKeywords;
        document.getElementById("recommendation").innerHTML = "";
}

function printeBayAPIError(root) {
        var x = document.getElementById("warnings");
        x.innerHTML = "<h2>eBay API Error<h2>";
        x.innerHTML += "<p>Id: " + root.errorMessage[0].error[0].errorId + "<br/>";
        x.innerHTML += "<p>Domain: " + root.errorMessage[0].error[0].domain + "<br/>";
        x.innerHTML += "<p>Severity: " + root.errorMessage[0].error[0].severity + "<br/>";
        x.innerHTML += "<p>Category: " + root.errorMessage[0].error[0].category + "<br/>";
        x.innerHTML += "<p>Message: " + root.errorMessage[0].error[0].message + "<br/>";
        x.innerHTML += "<p>Subdomain: " + root.errorMessage[0].error[0].subdomain + "<br/>";
        x.innerHTML += "<p>Parameter: " + root.errorMessage[0].error[0].parameter + "</p>";
        x.innerHTML += "<p>URL: " + "<a href=\"" + url + "\" target=\"_blank\">" + url + "</a>" + "</p>";

        if (x.className.indexOf("w3-show") == -1) {
                x.className += " w3-show";
        }

        if (root.ack == 'Failure' || root.ack == 'PartialFailure') {
                x.scrollIntoView(true);
        }
}

// item filters for request
var filterarray = [];

// Fill the array of item filters from input form
function fillFilterArray() {
        var value = "";
        var listingType = [];
        var conditions = [];
        var obj = [{
                "name": "",
                "value": "",
                "paramName": "",
                "paramValue": ""
        }];

        filterarray = [{
                "name": "AvailableTo",
                "value": "US",
                "paramName": "",
                "paramValue": ""
        }];

        value = document.getElementById('sellerName').value;
        if (value) {
                obj = {
                        "name": "Seller",
                        "value": value,
                        "paramName": "",
                        "paramValue": ""
                };
                filterarray.push(obj);
        }

        value = document.getElementById('minPrice').value;
        if (value > 0) {
                obj = {
                        "name": "MinPrice",
                        "value": Number(value).toFixed(2),
                        "paramName": "Currency",
                        "paramValue": "USD"
                };
                filterarray.push(obj);
        }

        value = document.getElementById('maxPrice').value;
        if (value > 0) {
                obj = {
                        "name": "MaxPrice",
                        "value": Number(value).toFixed(2),
                        "paramName": "Currency",
                        "paramValue": "USD"
                };
                filterarray.push(obj);
        }

        value = document.getElementById('minBids').value;
        if (value > 0) {
                obj = {
                        "name": "MinBids",
                        "value": Number(value).toFixed(0),
                        "paramName": "",
                        "paramValue": ""
                };
                filterarray.push(obj);
        }

        value = document.getElementById('maxBids').value;
        if (value && value >= 0) {
                obj = {
                        "name": "MaxBids",
                        "value": Number(value).toFixed(0),
                        "paramName": "",
                        "paramValue": ""
                };
                filterarray.push(obj);
        }

        value = document.getElementById('minFeedback').value;
        if (value > 0) {
                obj = {
                        "name": "FeedbackScoreMin",
                        "value": Number(value).toFixed(0),
                        "paramName": "",
                        "paramValue": ""
                };
                filterarray.push(obj);
        }

        value = document.getElementById('maxFeedback').value;
        if (value && value >= 0) {
                obj = {
                        "name": "FeedbackScoreMax",
                        "value": Number(value).toFixed(0),
                        "paramName": "",
                        "paramValue": ""
                };
                filterarray.push(obj);
        }

        value = document.getElementById('minQuantity').value;
        if (value > 0) {
                obj = {
                        "name": "MinQuantity",
                        "value": Number(value).toFixed(0),
                        "paramName": "",
                        "paramValue": ""
                };
                filterarray.push(obj);
        }

        value = document.getElementById('maxQuantity').value;
        if (value && value >= 0) {
                obj = {
                        "name": "MaxQuantity",
                        "value": Number(value).toFixed(0),
                        "paramName": "",
                        "paramValue": ""
                };
                filterarray.push(obj);
        }

        if (document.getElementById('freeShippingOnly').checked) {
                obj = {
                        "name": "FreeShippingOnly",
                        "value": "true",
                        "paramName": "",
                        "paramValue": ""
                };
                filterarray.push(obj);
        }

        if (document.getElementById('bestOfferOnly').checked) {
                obj = {
                        "name": "BestOfferOnly",
                        "value": "true",
                        "paramName": "",
                        "paramValue": ""
                };
                filterarray.push(obj);
        }

        if (document.getElementById('lotsOnly').checked) {
                obj = {
                        "name": "LotsOnly",
                        "value": "true",
                        "paramName": "",
                        "paramValue": ""
                };
                filterarray.push(obj);
        }

        if (document.getElementById('hideDuplicateItems').checked) {
                obj = {
                        "name": "HideDuplicateItems",
                        "value": "true",
                        "paramName": "",
                        "paramValue": ""
                };
                filterarray.push(obj);
        }

        if (document.getElementById('outletSellerOnly').checked) {
                obj = {
                        "name": "OutletSellerOnly",
                        "value": "true",
                        "paramName": "",
                        "paramValue": ""
                };
                filterarray.push(obj);
        }

        if (document.getElementById('soldOnly').checked) {
                obj = {
                        "name": "SoldOnly",
                        "value": "true",
                        "paramName": "",
                        "paramValue": ""
                };
                filterarray.push(obj);
        }

        if (document.getElementById('localPickupOnly').checked) {
                obj = {
                        "name": "LocalPickupOnly",
                        "value": "true",
                        "paramName": "",
                        "paramValue": ""
                };
                filterarray.push(obj);
        }

        if (document.getElementById('localSearchOnly').checked) {
                obj = {
                        "name": "LocalSearchOnly",
                        "value": "true",
                        "paramName": "",
                        "paramValue": ""
                };
                filterarray.push(obj);

                value = document.getElementById('maxDistance').value;
                if (value && value >= 0) {
                        obj = {
                                "name": "MaxDistance",
                                "value": Number(value).toFixed(0),
                                "paramName": "",
                                "paramValue": ""
                        };
                        filterarray.push(obj);
                }
        }

        if (document.getElementById('ltAll').checked) {
                listingType.push("All");
        }

        if (document.getElementById('ltAuction').checked) {
                listingType.push("Auction");
        }

        if (document.getElementById('ltAuctionWithBIN').checked) {
                listingType.push("AuctionWithBIN");
        }

        if (document.getElementById('ltClassified').checked) {
                listingType.push("Classified");
        }

        if (document.getElementById('ltFixedPrice').checked) {
                listingType.push("FixedPrice");
        }

        if (document.getElementById('ltStoreInventory').checked) {
                listingType.push("StoreInventory");
        }

        if (listingType.length) {
                obj = {
                        "name": "ListingType",
                        "value": listingType,
                        "paramName": "",
                        "paramValue": ""
                };
                filterarray.push(obj);
        }

        if (document.getElementById('condNew').checked) {
                conditions.push("New");
        }

        if (document.getElementById('condUsed').checked) {
                conditions.push("Used");
        }

        if (document.getElementById('condUnspecified').checked) {
                conditions.push("Unspecified");
        }

        if (document.getElementById('cond1000').checked) {
                conditions.push("1000");
        }

        if (document.getElementById('cond1500').checked) {
                conditions.push("1500");
        }

        if (document.getElementById('cond1750').checked) {
                conditions.push("1750");
        }

        if (document.getElementById('cond2000').checked) {
                conditions.push("2000");
        }

        if (document.getElementById('cond2500').checked) {
                conditions.push("2500");
        }

        if (document.getElementById('cond2750').checked) {
                conditions.push("2750");
        }

        if (document.getElementById('cond3000').checked) {
                conditions.push("3000");
        }

        if (document.getElementById('cond4000').checked) {
                conditions.push("4000");
        }

        if (document.getElementById('cond5000').checked) {
                conditions.push("5000");
        }

        if (document.getElementById('cond6000').checked) {
                conditions.push("6000");
        }

        if (document.getElementById('cond7000').checked) {
                conditions.push("7000");
        }

        if (conditions.length) {
                obj = {
                        "name": "Condition",
                        "value": conditions,
                        "paramName": "",
                        "paramValue": ""
                };
                filterarray.push(obj);
        }

        if (document.getElementById('locatedIn').options[0].selected) {
                obj = {
                        "name": "LocatedIn",
                        "value": document.getElementById('locatedIn').options[0].value,
                        "paramName": "",
                        "paramValue": ""
                };
                filterarray.push(obj);
        } else {
                obj = {
                        "name": "LocatedIn",
                        "value": document.getElementById('locatedIn').options[1].value,
                        "paramName": "",
                        "paramValue": ""
                };
                filterarray.push(obj);
        }

        if (valueStartMin) {
                obj = {
                        "name": "StartTimeFrom",
                        "value": valueStartMin,
                        "paramName": "",
                        "paramValue": ""
                };
                filterarray.push(obj);
        }

        if (valueStartMax) {
                obj = {
                        "name": "StartTimeTo",
                        "value": valueStartMax,
                        "paramName": "",
                        "paramValue": ""
                };
                filterarray.push(obj);
        }

        if (valueEndMin) {
                obj = {
                        "name": "EndTimeFrom",
                        "value": valueEndMin,
                        "paramName": "",
                        "paramValue": ""
                };
                filterarray.push(obj);
        }

        if (valueEndMax) {
                obj = {
                        "name": "EndTimeTo",
                        "value": valueEndMax,
                        "paramName": "",
                        "paramValue": ""
                };
                filterarray.push(obj);
        }
}

// Check the item filter parameters from input form
function checkFilterArray() {
        var x = document.getElementById("warnings");
        var warnings = 0;
        var value = "";
        var value2 = "";
        var valueMin = 0;
        var valueMax = 0;
        var html = [];
        var categoryCounter = 0;

        x.innerHTML = "";

        value = document.getElementById('keyword').value;
        value2 = document.getElementById('sellerName').value;
        for (var categoryIndex = 1; categoryIndex < document.getElementById('category').options.length; categoryIndex++) {
                if (document.getElementById('category').options[categoryIndex].selected) {
                        categoryCounter++;
                }
        }

        if (!value && !value2 && !categoryCounter) {
                warnings++;
                html.push("<p>No Keyword, Category or Seller Name specified</p>");
        }

        if (categoryCounter > 3) {
                warnings++;
                html.push("<p>Only up to 3 categories allowed</p>");
        }

        valueMin = document.getElementById('minPrice').value;
        valueMax = document.getElementById('maxPrice').value;

        if (valueMin && valueMin < 0) {
                warnings++;
                html.push("<p>Minimum Price under $0</p>");
        }

        if (valueMax && valueMax <= 0) {
                warnings++;
                html.push("<p>Maximum Price at or under $0</p>");
        }

        if (valueMin && valueMax) {
                if (Number(valueMin) > Number(valueMax)) {
                        warnings++;
                        html.push("<p>Minimum Price " + Number(valueMin).toFixed(0) + " greater than Maximum Price " + Number(valueMax).toFixed(0) + "</p>");
                }
        }

        valueMin = document.getElementById('minBids').value;
        valueMax = document.getElementById('maxBids').value;

        if (valueMin && valueMin < 0) {
                warnings++;
                html.push("<p>Minimum Bids under 0</p>");
        }

        if (valueMax && valueMax < 0) {
                warnings++;
                html.push("<p>Maximum Bids under 0</p>");
        }

        if (valueMin && valueMax) {
                if (Number(valueMin) > Number(valueMax)) {
                        warnings++;
                        html.push("<p>Minimum Bids greater than Maximum Bids</p>");
                }
        }

        valueMin = document.getElementById('minFeedback').value;
        valueMax = document.getElementById('maxFeedback').value;

        if (valueMin && valueMin < 0) {
                warnings++;
                html.push("<p>Minimum Feedback under 0</p>");
        }

        if (valueMax && valueMax < 0) {
                warnings++;
                html.push("<p>Maximum Feedback under 0</p>");
        }

        if (valueMin && valueMax) {
                if (Number(valueMin) > Number(valueMax)) {
                        warnings++;
                        html.push("<p>Minimum Feedback greater than Maximum Feedback</p>");
                }
        }

        valueMin = document.getElementById('minQuantity').value;
        valueMax = document.getElementById('maxQuantity').value;

        if (valueMin && valueMin <= 0) {
                warnings++;
                html.push("<p>Minimum Quantity at or under 0</p>");
        }

        if (valueMax && valueMax <= 0) {
                warnings++;
                html.push("<p>Maximum Quantity at or under 0</p>");
        }

        if (valueMin && valueMax) {
                if (Number(valueMin) > Number(valueMax)) {
                        warnings++;
                        html.push("<p>Minimum Quantity greater than Maximum Quantity</p>");
                }
        }

        if (document.getElementById('ltAll').checked &&
                (document.getElementById('ltAuction').checked ||
                        document.getElementById('ltAuctionWithBIN').checked ||
                        document.getElementById('ltClassified').checked ||
                        document.getElementById('ltFixedPrice').checked ||
                        document.getElementById('ltStoreInventory').checked)) {
                warnings++;
                html.push("<p>Listing Type All Combined with other Type(s)</p>");
        }

        if (document.getElementById('completedItemsOnly').checked &&
                document.getElementById('searchDescription').checked) {
                warnings++;
                html.push("<p>Completeted Items does work together with Search Description</p>");
        }

        valueStartMin = document.getElementById('minStartDate').value;

        if (valueStartMin) {
                if (isNaN(valueStartMin)) {
                        valueStartMin = moment(valueStartMin).format('YYYY-MM-DD');
                        if (!moment(valueStartMin).isValid) {
                                warnings++;
                                html.push("<p>Invalid Minimum Start Date</p>");
                        } else if (moment(valueStartMin).isAfter()) {
                                warnings++;
                                html.push("<p>Minimum Start Date in future</p>");
                        }
                } else {
                        var valueStartMinNumber = Number(valueStartMin);
                        if (valueStartMinNumber > 0) {
                                warnings++;
                                html.push("<p>Minimum Start Date in future</p>");
                        } else {
                                valueStartMin = moment().add(valueStartMinNumber, "days").format('YYYY-MM-DD');
                        }
                }
        }

        valueStartMax = document.getElementById('maxStartDate').value;

        if (valueStartMax) {
                if (isNaN(valueStartMax)) {
                        valueStartMax = moment(valueStartMax).format('YYYY-MM-DD');
                        if (!moment(valueStartMax).isValid) {
                                warnings++;
                                html.push("<p>Invalid Maximum Start Date</p>");
                        } else if (moment(valueStartMax).isAfter()) {
                                warnings++;
                                html.push("<p>Maximum Start Date in future</p>");
                        }
                } else {
                        var valueStartMaxNumber = Number(valueStartMax);
                        if (valueStartMaxNumber > 0) {
                                warnings++;
                                html.push("<p>Maximum Start Date in future</p>");
                        } else {
                                valueStartMax = moment().add(valueStartMaxNumber, "days").format('YYYY-MM-DD');
                        }
                }
        }

        valueEndMin = document.getElementById('minEndDate').value;

        if (valueEndMin) {
                if (isNaN(valueEndMin)) {
                        valueEndMin = moment(valueEndMin).format('YYYY-MM-DD');
                        if (!moment(valueEndMin).isValid) {
                                warnings++;
                                html.push("<p>Invalid Minimum End Date</p>");
                        } else if (!document.getElementById('completedItemsOnly').checked && moment(valueEndMin).isBefore()) {
                                warnings++;
                                html.push("<p>Minimum End Date in past");
                        }
                } else {
                        var valueEndMinNumber = Number(valueEndMin);
                        if (!document.getElementById('completedItemsOnly').checked && valueEndMinNumber < 0) {
                                warnings++;
                                html.push("<p>Minimum End Date in past</p>");
                        } else {
                                valueEndMin = moment().add(valueEndMinNumber, "days").format('YYYY-MM-DD');
                        }
                }
        }

        valueEndMax = document.getElementById('maxEndDate').value;

        if (valueEndMax) {
                if (isNaN(valueEndMax)) {
                        valueEndMax = moment(valueEndMax).format('YYYY-MM-DD');
                        if (!moment(valueEndMax).isValid) {
                                warnings++;
                                html.push("<p>Invalid Maximum End Date</p>");
                        } else if (!document.getElementById('completedItemsOnly').checked && moment(valueEndMax).isBefore()) {
                                warnings++;
                                html.push("<p>Maximum End Date in past");
                        }
                } else {
                        var valueEndMaxNumber = Number(valueEndMax);
                        if (!document.getElementById('completedItemsOnly').checked && valueEndMaxNumber < 0) {
                                warnings++;
                                html.push("<p>Maximum End Date in past</p>");
                        } else {
                                valueEndMax = moment().add(valueEndMaxNumber, "days").format('YYYY-MM-DD');
                        }
                }
        }

        if (valueStartMin && valueStartMax && valueStartMin > valueStartMax) {
                warnings++;
                html.push("<p>Maximum Start Date less than Minimum Start Date</p>");
        }

        if (valueEndMin && valueEndMax && valueEndMin > valueEndMax) {
                warnings++;
                html.push("<p>Maximum End Date less than Minimum End Date</p>");
        }

        if (valueStartMin && valueEndMin && valueStartMin > valueEndMin) {
                warnings++;
                html.push("<p>Minimum End Date less than Minimum Start Date</p>");
        }

        if (valueStartMin && valueEndMax && valueStartMin > valueEndMax) {
                warnings++;
                html.push("<p>Maximum End Date less than Minimum Start Date</p>");
        }

        if (valueStartMax && valueEndMin && valueStartMax > valueEndMin) {
                warnings++;
                html.push("<p>Minimum End Date less than Maximum Start Date</p>");
        }

        if (valueStartMax && valueEndMax && valueStartMax > valueEndMax) {
                warnings++;
                html.push("<p>Maximum End Date less than Maximum Start Date</p>");
        }

        // Generate ISO dates
        if (valueStartMin) {
                valueStartMin = moment(valueStartMin + " 00:00:00", "YYYY-MM-DD HH:mm:ss").tz("UTC").toISOString();
        }

        if (valueStartMax) {
                if (moment().isBefore(valueStartMax + "T23:59:59.999Z")) {
                        valueStartMax = moment().tz("UTC").toISOString();
                } else {
                        valueStartMax = moment(valueStartMax + " 23:59:59", "YYYY-MM-DD HH:mm:ss").tz("UTC").toISOString();
                }
        }

        if (document.getElementById('completedItemsOnly').checked) {
                if (valueEndMin) {
                        valueEndMin = moment(valueEndMin + " 00:00:00", "YYYY-MM-DD HH:mm:ss").tz("UTC").toISOString();
                }

                if (valueEndMax) {
                        if (moment().isBefore(valueEndMax + "T23:59:59.999Z")) {
                                valueEndMax = moment().subtract(1, 'minute').tz("UTC").toISOString();
                        } else {
                                valueEndMax = moment(valueEndMax + " 23:59:59", "YYYY-MM-DD HH:mm:ss").tz("UTC").toISOString();
                        }
                }
        } else {
                if (valueEndMin) {
                        if (moment().isAfter(valueEndMin + "T00:00:00.000Z")) {
                                var valueEndMinMoment = new moment().add(1, 'minute');
                                valueEndMin = valueEndMinMoment.tz("UTC").toISOString();
                        } else {
                                valueEndMin = moment(valueEndMin + " 00:00:00", "YYYY-MM-DD HH:mm:ss").tz("UTC").toISOString();
                        }
                }

                if (valueEndMax) {
                        valueEndMax = moment(valueEndMax + " 23:59:59", "YYYY-MM-DD HH:mm:ss").tz("UTC").toISOString();
                }
        }

        if (document.getElementById('localSearchOnly').checked) {
                value = document.getElementById('maxDistance').value;
                if (value === undefined || value <= 0) {
                        warnings++;
                        html.push("<p>Local Search Only requires Maximum Distance</p>");
                }
        }

        // Print warnings
        if (warnings) {
                x.innerHTML = html.join("");
                if (x.className.indexOf("w3-show") == -1) {
                        x.className += " w3-show";
                }
                x.scrollIntoView();
        } else {
                x.className = x.className.replace(" w3-show", "");
        }

        return warnings;
}

// Define global variable for the URL filter
var urlfilter = "";

// Generates an indexed URL snippet from the array of item filters
function buildURLArray() {
        urlfilter = "";
        // Iterate through each filter in the array
        for (var i = 0; i < filterarray.length; i++) {
                //Index each item filter in filterarray
                var itemfilter = filterarray[i];
                // Iterate through each parameter in each item filter
                for (var index in itemfilter) {
                        // Check to see if the paramter has a value (some don't)
                        if (itemfilter[index] !== "") {
                                if (itemfilter[index] instanceof Array) {
                                        for (var r = 0; r < itemfilter[index].length; r++) {
                                                var value = itemfilter[index][r];
                                                urlfilter += "&itemFilter\(" + i + "\)." + index + "\(" + r + "\)=" + value;
                                        }
                                } else {
                                        urlfilter += "&itemFilter\(" + i + "\)." + index + "=" + itemfilter[index];
                                }
                        }
                }
        }
} // End buildURLArray() function

var url = "";
var searchUrl = "";

function eBaySearch(paramPage) {
        pagenumber = paramPage;

        // Clear results outputs and download button
        var x = document.getElementById("results");
        x.innerHTML = "";
        x.className = x.className.replace(" w3-show", "");
        x.scrollIntoView(true);

        x = document.getElementById("download");
        x.className = x.className.replace(" w3-show", "");

        x = document.getElementById("pricing");
        x.className = x.className.replace(" w3-show", "");

        x = document.getElementById("prices");
        x.className = x.className.replace(" w3-show", "");

        x = document.getElementById("duplicates");
        x.className = x.className.replace(" w3-show", "");
    document.getElementById("duplicatesText").innerHTML = "";
    
        endProgressBar();

        x = document.getElementById("recommendation");
        x.innerHTML = "";

        if (document.getElementById("duplicateCheck").checked) {
                findDuplicateListing();
                findPotentialDuplicateListing();
                findShopifyDuplicateListing();
        }

        // Print serialized search parameters
        if (pagenumber == 1) {
                x = document.getElementById("parameter");
                if (x.className.indexOf("w3-show") == -1) {
                        x.className += " w3-show";
                }
                searchUrl = window.location.protocol + "//" + window.location.hostname + window.location.pathname + '?' + $("form").serialize();
                x.innerHTML = "<a href=\"" + searchUrl + "\" target=\"_blank\" title=\"eBay Search\">" + searchUrl + "</a>";
        }

        // Check Parameters
        if (checkFilterArray()) {
                return false;
        }

        // Fill the filter array from form input
        fillFilterArray();
        // Execute the function to build the URL filter
        buildURLArray(filterarray);

        var keyword = document.getElementById('keyword').value;

        // Construct the request
        url = configeBayFinding + "?";
        if (document.getElementById('completedItemsOnly').checked) {
                url += "OPERATION-NAME=findCompletedItems";
        } else if (keyword.includes("ReferenceID:")) {
                url += "OPERATION-NAME=findItemsByProduct";
        } else {
                url += "OPERATION-NAME=findItemsAdvanced";
        }
    url += "&SERVICE-VERSION=" + configeBayFindingVersion;
        url += "&SECURITY-APPNAME=" + configAppid;
        url += "&GLOBAL-ID=EBAY-US";
        url += "&RESPONSE-DATA-FORMAT=JSON";
        url += "&REST-PAYLOAD";
        if (keyword.length > 0) {
                if (keyword.includes("ReferenceID:")) {
                        url += "&productId.@type=ReferenceID";
                        url += "&productId=";
                        url += keyword.substr(12);
                } else {
                        url += "&keywords=";
                        url += encodeURIComponent(keyword.trim().replace(/ /g, "+"));
                }
        }

        var catNo = 0;
        for (var index = 1; index < document.getElementById('category').options.length; index++) {
                if (document.getElementById('category').options[index].selected) {
                        url += "&categoryId(" + catNo + ")=";
                        url += document.getElementById('category').options[index].value;
                        ++catNo;
                }
        }

        url += "&paginationInput.entriesPerPage=100";
        url += "&paginationInput.pageNumber=";
        if (pagenumber === undefined) {
                pagenumber = 1;
        }
        url += pagenumber;
        url += "&sortOrder=";
        url += getSortOrder();
        url += "&buyerPostalCode=";
        url += configZip;
        url += "&outputSelector=SellerInfo";
        if (document.getElementById('searchDescription').checked) {
                url += "&descriptionSearch=true";
        }
        url += urlfilter;

        var xhttp = new XMLHttpRequest();

        xhttp.onreadystatechange = function() {
        if (this.readyState == 4) {
                        if (document.getElementById('completedItemsOnly').checked) {
                                _cb_findCompletedItems(JSON.parse(this.responseText));
                        } else {
                                _cb_findItemsAdvanced(JSON.parse(this.responseText));
                        }
        }
    };

        xhttp.open("GET", configProxyUrl, true);
        xhttp.setRequestHeader("X-Proxy-Url", encodeURI(url));
        xhttp.send();

        return false;
}

function getKeywordRecommendations() {
        if (!document.getElementById("keyword").value) {
                return false;
        }

        // Clear results outputs and download button
        var x = document.getElementById("results");
        x.innerHTML = "";
        x.className = x.className.replace(" w3-show", "");

        x = document.getElementById("download");
        x.className = x.className.replace(" w3-show", "");

        x = document.getElementById("pricing");
        x.className = x.className.replace(" w3-show", "");

        x = document.getElementById("prices");
        x.className = x.className.replace(" w3-show", "");

        endProgressBar();

        // Construct the request
        url = configeBayFinding + "?";
        url += "OPERATION-NAME=getSearchKeywordsRecommendation";
        url += "&SERVICE-VERSION=" + configeBayFindingVersion;
        url += "&SECURITY-APPNAME=" + configAppid;
        url += "&RESPONSE-DATA-FORMAT=JSON";
        url += "&REST-PAYLOAD";
        url += "&keywords=";
        url += encodeURIComponent(document.getElementById('keyword').value.trim().replace(/ /g, "+"));

        // Submit the request
        var xhttp = new XMLHttpRequest();

        xhttp.onreadystatechange = function() {
        if (this.readyState == 4) {
                _cb_getKeywordRecommendations(JSON.parse(this.responseText));
        }
    };

        xhttp.open("GET", configProxyUrl, true);
        xhttp.setRequestHeader("X-Proxy-Url", encodeURI(url));
        xhttp.send();

        return false;
}

function formatTimeleft(timeleft) {
        var timeleftDays = Math.floor(timeleft / 86400);
        timeleft = timeleft % 86400;
        var timeleftHours = Math.floor(timeleft / 3600);
        timeleft = timeleft % 3600;
        var timeleftMinutes = Math.floor(timeleft / 60);
        return timeleftDays + ' days ' + timeleftHours + ' hours ' + timeleftMinutes + ' minutes';
}

function getSortOrder() {
        if (document.getElementById("soBestMatch").checked) {
                return "BestMatch";
        } else if (document.getElementById("soCurrentPriceHighest").checked) {
                return "CurrentPriceHighest";
        } else if (document.getElementById("soEndTimeSoonest").checked) {
                return "EndTimeSoonest";
        } else if (document.getElementById("soPricePlusShippingHighest").checked) {
                return "PricePlusShippingHighest";
        } else if (document.getElementById("soPricePlusShippingLowest").checked) {
                return "PricePlusShippingLowest";
        } else if (document.getElementById("soStartTimeNewest").checked) {
                return "StartTimeNewest";
        } else if (document.getElementById("soWatchCountDecreaseSort").checked) {
                return "WatchCountDecreaseSort";
        } else if (document.getElementById("soDistance").checked) {
                return "DistanceNearest";
        }
        // Auctions Only!
        else if (document.getElementById("soBidCountFewest").checked) {
                return "BidCountFewest";
        }
        // Auctions Only!
        else if (document.getElementById("soBidCountMost").checked) {
                return "BidCountMost";
        }

        return "BestMatch";
}

function downloadAsCSV() {
        var categoryIndex = 0;
        asyncFlag = false;

        initProgressBar('Creating CSV Download File');

        var x = document.getElementById("csv");
        x.innerHTML = ConvertToCSVHeader();

        maxPages = (totalEntries / 100) > 100 ? 100 : Math.trunc(totalEntries / 100.0) + 1;
        currentPage = 0;

        var keyword = document.getElementById('keyword').value;

        for (var index = 0; index < maxPages; ++index) {
                // Construct the request
                var url = configeBayFinding + "?";
                if (document.getElementById('completedItemsOnly').checked) {
                        url += "OPERATION-NAME=findCompletedItems";
                } else if (keyword.includes("ReferenceID:")) {
                        url += "OPERATION-NAME=findItemsByProduct";
                } else {
                        url += "OPERATION-NAME=findItemsAdvanced";
                }
                url += "&SECURITY-APPNAME=" + configAppid;
                url += "&GLOBAL-ID=EBAY-US";
                url += "&RESPONSE-DATA-FORMAT=JSON";
                url += "&SERVICE-VERSION=" + configeBayFindingVersion;
                url += "&REST-PAYLOAD";
                if (keyword.length > 0) {
                        if (keyword.includes("ReferenceID:")) {
                                url += "&productId.@type=ReferenceID";
                                url += "&productId=";
                                url += keyword.substr(12);
                        } else {
                                url += "&keywords=";
                                url += encodeURIComponent(keyword.trim().replace(/ /g, "+"));
                        }
                }

                var catNo = 0;
                for (categoryIndex = 1; categoryIndex < document.getElementById('category').options.length; categoryIndex++) {
                        if (document.getElementById('category').options[categoryIndex].selected) {
                                url += "&categoryId(" + catNo + ")=";
                                url += document.getElementById('category').options[categoryIndex].value;
                                ++catNo;
                        }
                }

                url += "&paginationInput.entriesPerPage=100";
                url += "&paginationInput.pageNumber=";
                url += (index + 1);
                url += "&sortOrder=";
                url += getSortOrder();
                url += "&buyerPostalCode=";
                url += configZip;
                url += "&outputSelector(0)=SellerInfo&outputSelector(1)=StoreInfo";
                if (document.getElementById('searchDescription').checked) {
                        url += "&descriptionSearch=true";
                }

                url += urlfilter;

                var xhttp = new XMLHttpRequest();

                xhttp.onreadystatechange = function() {
                if (this.readyState == 4) {
                                if (document.getElementById('completedItemsOnly').checked) {
                                        _cb_ConvertToCSVfindCompletedItems(JSON.parse(this.responseText));
                                } else {
                                        _cb_ConvertToCSVfindItemsAdvanced(JSON.parse(this.responseText));
                                }
                }
            };

                xhttp.open("GET", configProxyUrl, true);
                xhttp.setRequestHeader("X-Proxy-Url", encodeURI(url));
                xhttp.send();
        }

        function checkAsyncFlag() {
                if (asyncFlag === false) {
                        window.setTimeout(checkAsyncFlag, 100); // wait 100 milliseconds
                } else {
                        var textToSaveAsBlob = new Blob([String(document.getElementById("csv").innerHTML)], {
                                type: "text/csv"
                        });
                        var textToSaveAsURL = window.URL.createObjectURL(textToSaveAsBlob);
                        var fileNameToSaveAs = "eBaySearch.csv";

                        var downloadLink = document.createElement("a");
                        downloadLink.download = fileNameToSaveAs;
                        downloadLink.innerHTML = "Download File";
                        downloadLink.href = textToSaveAsURL;
                        downloadLink.onclick = destroyClickedElement;
                        downloadLink.style.display = "none";
                        document.body.appendChild(downloadLink);

                        endProgressBar();
                        downloadLink.click();
                }
        }

        checkAsyncFlag();
}

function destroyClickedElement(event) {
        document.body.removeChild(event.target);
}

function _cb_ConvertToCSVfindItemsAdvanced(objArray) {
        var array;

        if (objArray.findItemsAdvancedResponse !== undefined) {
                array = typeof objArray.findItemsAdvancedResponse[0] != 'object' ? JSON.parse(objArray.findItemsAdvancedResponse[0]) : objArray.findItemsAdvancedResponse[0].searchResult[0].item;
        } else if (objArray.findItemsByProductResponse !== undefined) {
                array = typeof objArray.findItemsByProductResponse[0] != 'object' ? JSON.parse(objArray.findItemsByProductResponse[0]) : objArray.findItemsByProductResponse[0].searchResult[0].item;
        } else {
                return;
        }

        ConvertToCSV(array);
}

function _cb_ConvertToCSVfindCompletedItems(objArray) {
        var array = typeof objArray.findCompletedItemsResponse[0] != 'object' ? JSON.parse(objArray.findCompletedItemsResponse[0]) : objArray.findCompletedItemsResponse[0].searchResult[0].item;
        ConvertToCSV(array);
}

function findSingleItem(itemId) {
        // Construct the getShippingCosts request
        getShippingCostsDone = false;

        url = configeBayShopping + "?";
        url += "callname=GetShippingCosts";
        url += "&responseencoding=JSON";
        url += "&appid=" + configAppid;
        url += "&version=" + configeBayShoppingVersion;
        url += "&DestinationCountryCode=US";
        url += "&DestinationPostalCode=";
        url += configZip;
        url += "&IncludeDetails=true";
        url += "&QuantitySold=1";
        url += "&ItemID=";
        url += itemId;

        var xhttp = new XMLHttpRequest();

        xhttp.onreadystatechange = function() {
        if (this.readyState == 4) {
                _cb_GetShippingCosts(JSON.parse(this.responseText));
        }
    };

        xhttp.open("GET", configProxyUrl, true);
        xhttp.setRequestHeader("X-Proxy-Url", encodeURI(url));
        xhttp.send();

        function checkAsyncFlag() {
                if (getShippingCostsDone !== true) {
                        window.setTimeout(function() {
                                checkAsyncFlag();
                        }, 100); // wait 100 milliseconds
                } else {
                        // Construct the getSingleItem request
                        url = configeBayShopping + "?";
                        url += "callname=GetSingleItem";
                        url += "&responseencoding=JSON";
                        url += "&appid=" + configAppid;
                        url += "&version=" + configeBayShoppingVersion;
                        url += "&IncludeSelector=Details,Description,ItemSpecifics";
                        url += "&ItemID=";
                        url += itemId;

                        var xhttp = new XMLHttpRequest();

                        xhttp.onreadystatechange = function() {
                        if (this.readyState == 4) {
                                _cb_GetSingleItem(JSON.parse(this.responseText));
                        }
                    };

                        xhttp.open("GET", configProxyUrl, true);
                        xhttp.setRequestHeader("X-Proxy-Url", encodeURI(url));
                        xhttp.send();
                }
        }

        checkAsyncFlag();
}

// Create new page for single item
function _cb_GetSingleItem(root) {
        var ack = root.Ack;
        if (ack != 'Success') {
                var x = document.getElementById("warnings");
                x.innerHTML = "<h2>eBay API Error<h2>";
                x.innerHTML += "<p>Id: " + root.Errors[0].ErrorCode + "<br/>";
                x.innerHTML += "<p>Domain: " + root.Errors[0].ErrorClassification + "<br/>";
                x.innerHTML += "<p>Severity: " + root.Errors[0].SeverityCode + "<br/>";
                x.innerHTML += "<p>Category: " + root.Errors[0].category + "<br/>";
                x.innerHTML += "<p>Short Message: " + root.Errors[0].ShortMessage + "<br/>";
                x.innerHTML += "<p>Long Message: " + root.Errors[0].LongMessage + "<br/>";
                x.innerHTML += "<p>Build/Version: " + root.Build + '/' + root.Version + "</p>";
                x.innerHTML += "<p>URL: " + "<a href=\"" + url + "\" target=\"_blank\">" + url + "</a>" + "</p>";

                if (x.className.indexOf("w3-show") == -1) {
                        x.className += " w3-show";
                }

                if (ack == 'Failure' || ack == 'PartialFailure') {
                        x.scrollIntoView(true);
                        return;
                }
        }

        var str = "";
        var i = 0;
        var JsonObj = typeof root.Item != 'object' ? JSON.parse(root.Item) : root.Item;

        var autoPay = JsonObj.autoPay;
        var BestOfferEnabled = JsonObj.BestOfferEnabled;
        var BidCount = JsonObj.BidCount;
        var BusinessSellerDetails = JsonObj.BusinessSellerDetails;
        if (BusinessSellerDetails) { // not yet
        }
        var BuyItNowAvailable = JsonObj.BuyItNowAvailable;
        var BuyItNowPrice = JsonObj.BuyItNowPrice;
        var BuyItNowPriceValue = BuyItNowPrice === undefined ? 0.00 : BuyItNowPrice.Value;
        var BuyItNowPriceCurrencyID = BuyItNowPrice === undefined ? "" : BuyItNowPrice.CurrencyID;
        var Charity = JsonObj.Charity;
        if (Charity) { // not yet
        }
        var ConditionDescription = JsonObj.ConditionDescription;
        var ConditionDisplayName = JsonObj.ConditionDisplayName;
        var ConditionID = JsonObj.ConditionID;
        var ConvertedBuyItNowPrice = JsonObj.ConvertedBuyItNowPrice;
        var ConvertedBuyItNowPriceValue = ConvertedBuyItNowPrice === undefined ? 0.00 : ConvertedBuyItNowPrice.Value;
        var ConvertedBuyItNowPriceCurrencyID = ConvertedBuyItNowPrice === undefined ? "" : ConvertedBuyItNowPrice.CurrencyID;
        var ConvertedCurrentPrice = JsonObj.ConvertedCurrentPrice;
        var ConvertedCurrentPriceValue = ConvertedCurrentPrice === undefined ? 0.00 : ConvertedCurrentPrice.Value;
        var ConvertedCurrentPriceCurrencyID = ConvertedCurrentPrice === undefined ? "" : ConvertedCurrentPrice.CurrencyID;
        var Country = JsonObj.Country;
        var CurrentPrice = JsonObj.CurrentPrice;
        var CurrentPriceValue = CurrentPrice === undefined ? 0.00 : CurrentPrice.Value;
        var CurrentPriceCurrencyID = CurrentPrice === undefined ? "" : CurrentPrice.CurrencyID;
        var Description = JsonObj.Description;
        var DiscountPriceInfo = JsonObj.DiscountPriceInfo;
        if (DiscountPriceInfo) { // not yet
        }
        var EndTime = JsonObj.EndTime;
        var GalleryURL = JsonObj.GalleryURL;
        var HandlingTime = JsonObj.HandlingTime;
        var HighBidder = JsonObj.HighBidder;
        var HighBidderFeedbackPrivate = HighBidder === undefined ? "" : HighBidder.FeedbackPrivate;
        var HighBidderFeedbackScore = HighBidder === undefined ? "" : HighBidder.FeedbackScore;
        var HighBidderUserAnonymized = HighBidder === undefined ? "" : HighBidder.UserAnonymized;
        var HighBidderUserID = HighBidder === undefined ? "" : HighBidder.UserID;
        var HitCount = JsonObj.HitCount;
        var IgnoreQuantity = JsonObj.IgnoreQuantity;
        var IntegratedMerchantCreditCardEnabled = JsonObj.IntegratedMerchantCreditCardEnabled;
        var ItemID = JsonObj.ItemID;
        var ItemSpecifics = JsonObj.ItemSpecifics;
        var ListingStatus = JsonObj.ListingStatus;
        var ListingType = JsonObj.ListingType;
        var Location = JsonObj.Location;
        var LotSize = JsonObj.LotSize;
        var MinimumToBid = JsonObj.MinimumToBid;
        var MinimumToBidCurrencyID = MinimumToBid === undefined ? "" : MinimumToBid.CurrencyID;
        var MinimumToBidValue = MinimumToBid === undefined ? 0.00 : MinimumToBid.Value;
        var PaymentAllowedSite = JsonObj.PaymentAllowedSite;
        if (PaymentAllowedSite) { // not yet
        }
        var PaymentMethods = JsonObj.PaymentMethods;
        var PictureURL = JsonObj.PictureURL;
        var PostalCode = JsonObj.PostalCode;
        var PrimaryCategoryID = JsonObj.PrimaryCategoryID;
        var PrimaryCategoryIDPath = JsonObj.PrimaryCategoryIDPath;
        var PrimaryCategoryName = JsonObj.PrimaryCategoryName;
        var ProductIDValue = JsonObj.ProductID ? JsonObj.ProductID.Value : undefined;
        var ProductIDType = JsonObj.ProductID ? JsonObj.ProductID.Type : undefined;
        var Quantity = JsonObj.Quantity;
        var QuantitySold = JsonObj.QuantitySold;
        var QuantitySoldByPickupInStore = JsonObj.QuantitySoldByPickupInStore;
        var ReserveMet = JsonObj.ReserveMet;
        var ReturnPolicy = JsonObj.ReturnPolicy;
        var ReturnPolicyRefund = ReturnPolicy === undefined ? "" : ReturnPolicy.Refund;
        var ReturnPolicyReturnsWithin = ReturnPolicy === undefined ? "" : ReturnPolicy.ReturnsWithin;
        var ReturnPolicyReturnsAccepted = ReturnPolicy === undefined ? "" : ReturnPolicy.ReturnsAccepted;
        var ReturnPolicyDescription = ReturnPolicy === undefined ? "" : ReturnPolicy.Description;
        var ReturnPolicyShippingCostPaidBy = ReturnPolicy === undefined ? "" : ReturnPolicy.ShippingCostPaidBy;
        var ReturnPolicyRestockingFeeValue = ReturnPolicy === undefined ? "" : ReturnPolicy.RestockingFeeValue;
        var ReturnPolicyRestockingFeeValueOption = ReturnPolicy === undefined ? "" : ReturnPolicy.RestockingFeeValueOption;
        var ReturnPolicyWarrantyDuration = ReturnPolicy === undefined ? "" : ReturnPolicy.WarrantyDuration;
        var ReturnPolicyWarrantyOffered = ReturnPolicy === undefined ? "" : ReturnPolicy.WarrantyOffered;
        var ReturnPolicyWarrantyType = ReturnPolicy === undefined ? "" : ReturnPolicy.WarrantyType;
        var SecondaryCategoryID = JsonObj.SecondaryCategoryID;
        var SecondaryCategoryIDPath = JsonObj.SecondaryCategoryIDPath;
        var SecondaryCategoryName = JsonObj.SecondaryCategoryName;
        var Seller = JsonObj.Seller;
        var SellerFeedbackScore = Seller === undefined ? 0 : Seller.FeedbackScore;
        var SellerPositiveFeedbackPercent = Seller === undefined ? 0.00 : Seller.PositiveFeedbackPercent;
        var SellerTopRatedSeller = Seller === undefined ? "" : Seller.TopRatedSeller;
        var SellerUserID = Seller === undefined ? "" : Seller.UserID;
        var Site = JsonObj.Site;
        var SKU = JsonObj.SKU;
        var StartTime = JsonObj.StartTime;
        var Storefront = JsonObj.Storefront;
        var StorefrontStoreName = Storefront === undefined ? "" : Storefront.StoreName;
        var StorefrontStoreURL = Storefront === undefined ? "" : Storefront.StoreURL;
        var Subtitle = JsonObj.Subtitle;
        var TimeLeft = JsonObj.TimeLeft;
        var Title = JsonObj.Title;
        var TopRatedListing = JsonObj.TopRatedListing;
        var UnitInfo = JsonObj.UnitInfo;
        var UnitInfoUnitQuantity = UnitInfo === undefined ? 0 : UnitInfo.UnitQuantity;
        var UnitInfoUnitType = UnitInfo === undefined ? 0 : UnitInfo.UnitType;
        var ViewItemURLForNaturalSearch = JsonObj.ViewItemURLForNaturalSearch; // contains UPC

        str = '<!DOCTYPE html>';
        str += '<html lang="en">';
        str += '<head>';
        str += '<title>' + ItemID + ' - ' + Title + '</title>';
        str += '<meta charset="UTF-8">';
        str += '<meta name="viewport" content="width=device-width, initial-scale=1.0">';
        str += '<link rel="shortcut icon" href="favicon.ico" type="image/x-icon">';
        str += '<link rel="icon" href="favicon.ico" type="image/x-icon">';
        str += '<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">';
        str += '<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">';
        str += '<link rel="stylesheet" href="css/style.css">';
        str += '<style>.w3-table td,.w3-table th{padding: 0 10px 0 10px;display:table-cell;text-align:left;vertical-align:top}</style>';
        str += '<script src="js/jquery.js"><\/script>';
        str += '<script src="js/muna-tools.js"><\/script>';
        str += '<script src="js/ebayProduct.js"><\/script>';
        str += '</head>';
        str += '<body>';
        str += '<div class="w3-main">';
        str += '<div class="w3-container w3-padding w3-margin w3-card-4">';
        str += '<img class="w3-image w3-right" src="images/MUNA%20-%20Logo%20100x100.png" alt="MUNA Trading Logo" style="height:100px">';
        str += '<p class="w3-xlarge">' + Title + ' (EBAY-' + Site + '<a href="' + ViewItemURLForNaturalSearch + '" target="_blank">' + ' #' + ItemID + '</a>' + ')</p>';

        if (Subtitle) {
                str += '<p class="w3-large">' + Subtitle + '</p>';
        }
        if (PrimaryCategoryID) {
                str += '<p>' + PrimaryCategoryName + ' (' + PrimaryCategoryIDPath + ')</p>';
        }
        if (SecondaryCategoryID) {
                str += '<p>' + SecondaryCategoryName + ' (' + SecondaryCategoryIDPath + ')</p>';
        }
        str += '</div>';

        str += '<div class="w3-container w3-padding w3-margin w3-card-4">';
        str += '<div class="w3-cell-row">';
        str += '<div class="w3-container w3-card-2 w3-cell w3-padding w3-third">';
        if (GalleryURL) {
                str += '<img class="w3-image w3-right w3-margin" src="' + GalleryURL + '" alt="Gallery Image" style="max-height:100px;max-width:100px;">';
        } else if (PictureURL) {
                str += '<img class="w3-image w3-right w3-margin" src="' + PictureURL[0].replace('http:', 'https:') + '" alt="Gallery Image" style="max-height:100px;max-width:100px;">';
        }
        str += '<h2>Item</h2>';
        str += '<table class="w3-table w3-bordered">';

        if (ConditionID) {
                str += '<tr><td>' + ConditionDisplayName + ' (' + ConditionID + ')</td><td></td></tr>';
        }
        str += '<tr><td>Condition</td><td>' + (ConditionDescription ? ConditionDescription : 'None entered') + '</td></tr>';

        if (ProductIDValue) {
                str += '<tr><td>ProductID</td><td><a href="javascript:void(0)" onclick="findProductInfo(' + ProductIDValue + ')">' + ProductIDValue + ' (' + ProductIDType + ')</a></td></tr>';
        }

        if (SKU) {
                str += '<tr><td>SKU</td><td>' + SKU + '</td></tr>';
        }

        if (ItemSpecifics) {
                for (i = 0; i < ItemSpecifics.NameValueList.length; i++) {
                        str += '<tr><td>' + ItemSpecifics.NameValueList[i].Name + '</td><td>' + ItemSpecifics.NameValueList[i].Value + '</td></tr>';
                }
        }

        str += '</table>';

        if (Seller) {
                str += '<h2>Seller</h2>';
                str += '<table class="w3-table w3-bordered">';
                str += '<tr><td>' + SellerUserID + feebackStarImage(SellerFeedbackScore);
                str += ' (' + SellerFeedbackScore + ' / ' + SellerPositiveFeedbackPercent + '%)</td><td></td></tr>';
                if (SellerTopRatedSeller) {
                        str += '<tr><td>Top Rated Seller</td><td></td></tr>';
                }
                str += '<tr><td>' + Location + ' ' + (PostalCode ? PostalCode + ' ' : '') + Country + '</td><td></td></tr>';
                if (Storefront) {
                        str += '<tr><td>Store: <a href="' + StorefrontStoreURL + '" target="_blank">' + StorefrontStoreName + '</a></td><td></td></tr>';
                }
                str += '</table>';

                str += '<div id="map" style="width:100%;height:300px;"></div>';
                str += '<script>';
                str += '  function initMap() {';
                str += '    var address = \'' + Location + ' ' + (PostalCode ? PostalCode + ' ' : '') + Country + '\';';
                str += '        var geocoder = new google.maps.Geocoder;';
                str += '    geocoder.geocode({"address": address}, function(results, status) {';
                str += '    if (status === "OK") {';
                str += '        if (results[0]) {';
                str += '                        var infowindow = new google.maps.InfoWindow;';
                str += '                var map = new google.maps.Map(document.getElementById("map"), {';
                str += '                  zoom: 10,';
                str += '                  center: {lat: 40.72, lng: -73.96}';
                str += '                });';
                str += '            map.setCenter(results[0].geometry.location);';
                str += '            var marker = new google.maps.Marker({';
                str += '              map: map,';
                str += '              position: results[0].geometry.location';
                str += '            });';
                str += '            infowindow.setContent(results[0].formatted_address);';
                str += '            infowindow.open(map, marker);';
                str += '        } else {';
                str += '            document.getElementById("map").style.display = "none";';
                str += '        }';
                str += '    } else {';
                str += '        document.getElementById("map").style.display = "none";';
                str += '    }';
                str += '  });';
                str += '  }';
                str += '<\/script>';
        }

        str += '</div>';

        str += '<div class="w3-container w3-card-2 w3-cell w3-padding w3-third">';
        str += '<h2>Payment</h2>';
        str += '<table class="w3-table w3-bordered">';
        if (autoPay && autoPay == 'true' && BidCount && BidCount === 0) {
                str += '<tr><td>Requires Immediate Payment</td><td></td></tr>';
        }
        if (IntegratedMerchantCreditCardEnabled && IntegratedMerchantCreditCardEnabled == 'true') {
                str += '<tr><td>Merchant Credit Cards enabled</td><td></td></tr>';
        }

        str += '<tr><td>Payment Methods</td><td>';
        var paymentsArray = String(PaymentMethods).split(',');
        for (i = 0; i < PaymentMethods.length; i++) {
                str += (i > 0 ? ', ' : '') + paymentsArray[i];
        }
        str += '</td></tr>';

        str += '</table>';

        if (HandlingTime !== undefined) {
                str += '<h2>Shipping/Handling:</h2>';
                str += '<table class="w3-table w3-bordered" style="width:100%;">';
                str += '<colgroup><col span="1" style="width:35%;"><col span="1" style="width:65%;"></colgroup>';
                str += '<tr><td>Handling Time</td><td>' + HandlingTime + ' ' + (HandlingTime == 1 ? 'day' : 'days') + '</td></tr>';
                str += ship_str;
                str += '</table>';
        }

        if (ReturnPolicy) {
                str += '<h2>Return Policy</h2><p>';
                str += '<table class="w3-table w3-bordered">';
                str += '<tr><td>' + (ReturnPolicyReturnsAccepted ? 'Return Accepted' : 'No Return') + '</td><td></td></tr>';
                str += ReturnPolicyDescription ? '<tr><td>Return Policy Description</td><td>' + ReturnPolicyDescription + '</td></tr>' : '';
                str += ReturnPolicyReturnsWithin ? '<tr><td>Returns Within</td><td>' + ReturnPolicyReturnsWithin + '</td></tr>' : '';
                str += ReturnPolicyRefund ? '<tr><td>Refund</td><td>' + ReturnPolicyRefund + '</td></tr>' : '';
                str += ReturnPolicyShippingCostPaidBy ? '<tr><td>Shipping Cost Paid By</td><td>' + ReturnPolicyShippingCostPaidBy + '</td></tr>' : '';
                str += ReturnPolicyRestockingFeeValueOption ? '<tr><td>Restocking Fee Value Option</td><td>' + ReturnPolicyRestockingFeeValueOption + '</td></tr>' : '';
                str += ReturnPolicyRestockingFeeValue ? '<tr><td>Restocking Fee Value</td><td>' + ReturnPolicyRestockingFeeValue + '</td></tr>' : '';
                str += ReturnPolicyWarrantyOffered ? '<tr><td>Warranty Offered</td><td>' + ReturnPolicyWarrantyOffered + '</td></tr>' : '<tr><td>No Warranty</td><td></td></tr>';
                str += ReturnPolicyWarrantyType ? '<tr><td>Warranty Type</td><td>' + ReturnPolicyWarrantyType + '</td></tr>' : '';
                str += ReturnPolicyWarrantyDuration ? '<tr><td>Warranty Duration</td><td>' + ReturnPolicyWarrantyType + '</td></tr>' : '';
        }
        str += '</table>';
        str += '</div>';

        str += '<div class="w3-container w3-card-2 w3-cell w3-padding w3-third">';
        str += '<h2>Listing</h2>';
        str += '<table class="w3-table w3-bordered">';
        str += '<tr><td>Status</td><td>' + ListingStatus + '</td></tr>';
        if (TopRatedListing === true) {
                str += '<tr><td>Top Rated Listing</td><td></td></tr>';
        }
        str += '<tr><td>Listing Type</td><td>' + ListingType + '</td></tr>';
        str += '<tr><td>Current Price</td><td>' + (CurrentPriceCurrencyID == 'USD' ? '$' : CurrentPriceCurrencyID + ' ') + CurrentPriceValue.toFixed(2) + '</td></tr>';
        if (CurrentPriceCurrencyID != ConvertedCurrentPriceCurrencyID || CurrentPriceValue != ConvertedCurrentPriceValue) {
                str += '<tr><td>Converted Current Price</td><td>' + (ConvertedCurrentPriceCurrencyID = 'USD' ? '$' : ConvertedCurrentPriceCurrencyID + ' ') + ConvertedCurrentPriceValue.toFixed(2) + '</td></tr>';
        }
        str += ship_str_cost;
        str += ship_str_tax;
        if (BuyItNowAvailable === true) {
                str += '<tr><td>Buy It Now Price</td><td>' + (BuyItNowPriceCurrencyID == 'USD' ? '$' : BuyItNowPriceCurrencyID + ' ') + BuyItNowPriceValue.toFixed(2) + '</td></tr>';
                if (BuyItNowPriceCurrencyID != ConvertedBuyItNowPriceCurrencyID || BuyItNowPriceValue != ConvertedBuyItNowPriceValue) {
                        str += '<tr><td>Converted Buy It Now Price</td><td>' + (ConvertedBuyItNowPriceCurrencyID = 'USD' ? '$' : ConvertedBuyItNowPriceCurrencyID + ' ') + ConvertedBuyItNowPriceValue.toFixed(2) + '</td></tr>';
                }
        }
        if (LotSize) {
                str += '<tr><td>LotSize</td><td>' + LotSize + '</td></tr>';
        }

        if (IgnoreQuantity === undefined) {
                str += '<tr><td>Quantity</td><td>' + Quantity + '</td></tr>';
                str += '<tr><td>Quantity Sold</td><td>' + QuantitySold + '</td></tr>';
                str += '<tr><td>Quantity Sold Store Pickup</td><td>' + QuantitySoldByPickupInStore + '</td></tr>';
        }

        if (UnitInfo) {
                str += '<tr><td>Unit Info: ' + UnitInfoUnitQuantity + ' ' + UnitInfoUnitType + '</td></tr>';
        }

        str += '<tr><td>Start</td><td>' + moment(StartTime, moment.ISO_8601).format("YYYY-MM-DD hh:MMA") + '</td></tr>';
        str += '<tr><td>End</td><td>' + moment(EndTime, moment.ISO_8601).format("YYYY-MM-DD hh:MMA") + '</td></tr>';
        str += '<tr><td>Time Left</td><td>' + formatTimeleft(moment.duration(TimeLeft).asSeconds()) + '</td></tr>';
        if (BestOfferEnabled === true) {
                str += '<tr><td>Best Offer Enabled</td><td></td></tr>';
        }

        if (ReserveMet === false) {
                str += '<tr><td>Reserve not met</td><td></td></tr>';
        }
        if (HitCount) {
                str += '<tr><td>Views</td><td>' + HitCount + '</td></tr>';
        }
        if (BidCount) {
                str += '<tr><td>Bids</td><td>' + BidCount + '</td></tr>';
        }
        if (MinimumToBid) {
                str += '<tr><td>Minimum to Bid</td><td>' + (MinimumToBidCurrencyID == 'USD' ? '$' : MinimumToBidCurrencyID + ' ') + MinimumToBidValue.toFixed(2) + '</td></tr>';
        }
        if (HighBidder) {
                str += '<tr><td>High Bidder</td><td>' + HighBidderUserID;
                if (HighBidderFeedbackPrivate === false) {
                        str += feebackStarImage(HighBidderFeedbackScore) + ' (' + HighBidderFeedbackScore + ')';
                }
                str += '</td></tr>';
                if (HighBidderUserAnonymized === true) {
                        str += '<tr><td>High Bidder User Anonymized</td><td></td></tr>';
                }
        }
        str += '</table>';

        str += '</div>';
        str += '</div>';
        str += '</div>';

        if (PictureURL.length > 1) {
                str += '<div class="w3-container w3-padding w3-margin w3-card-4">';
                str += '<h2>Pictures</h2>';
                for (i = 0; i < PictureURL.length; i++) {
                        str += '<img class="w3-image" src="' + PictureURL[i].replace('http:', 'https:') + '" alt="Item Image ' + (i + 1) + '">';
                }
                str += '</div>';
        }

        if (Description) {
                str += '<div class="w3-container w3-padding w3-margin w3-card-4"><h2>Description</h2>' + Description + '</div>';
        }

        str += '<div id="warnings" class="w3-container w3-padding w3-margin w3-card-4 w3-red w3-hide"></div>';
        str += '<footer class="w3-container w3-center w3-border-top w3-margin">';
        str += 'Copyright &#169; ' + new Date().getFullYear() + ' MUNA Trading. All rights reserved.';
        str += '</footer>';
        str += '<script async defer src="https://maps.googleapis.com/maps/api/js?key=' + configGoogleMapsKey + '&callback=initMap"><\/script>';
        str += '</div>';
        str += '</body>';
        str += '</html>';

        var newWin = window.open("", ItemID + ' ' + Title);
        if (newWin) {
                newWin.document.open().write(str);
                newWin.document.close();
        }
}

function _cb_GetShippingCosts(root) {
        var ack = root.Ack;
        var i;
        var j;
        var taxTableEntries = 0;
        ship_str = "";

        if (ack != 'Success') {
                var x = document.getElementById("warnings");
                x.innerHTML = '<a href="javascript:void(0)" class="w3-right w3-xlarge w3-ripple" style="text-decoration:none;" onclick="hideErrorBox()">Close &#10006;</a>';
                x.innerHTML += "<h2>eBay API Error<h2>";
                x.innerHTML += "<p>Id: " + root.Errors[0].ErrorCode + "<br/>";
                x.innerHTML += "<p>Domain: " + root.Errors[0].ErrorClassification + "<br/>";
                x.innerHTML += "<p>Severity: " + root.Errors[0].SeverityCode + "<br/>";
                x.innerHTML += "<p>Short Message: " + root.Errors[0].ShortMessage + "<br/>";
                x.innerHTML += "<p>Long Message: " + root.Errors[0].LongMessage + "<br/>";
                x.innerHTML += "<p>Build/Version: " + root.Build + '/' + root.Version + "</p>";
                x.innerHTML += "<p>URL: " + "<a href=\"" + url + "\" target=\"_blank\">" + url + "</a>" + "</p>";

                if (x.className.indexOf("w3-show") == -1) {
                        x.className += " w3-show";
                }

                if (ack == 'Failure' || ack == 'PartialFailure') {
                        x.scrollIntoView(true);
                        getShippingCostsDone = true;
                        return;
                }
        }

        ship_str += '<tr><td><strong>Shipping Cost Summary</strong></td><td></td></tr>';
        ship_str_cost = "";
        if (root.ShippingCostSummary.ShippingServiceCost) {
                if (root.ShippingCostSummary.ShippingServiceCost.Value === 0) {
                        ship_str += '<tr><td>Shipping Service Cost</td><td>Free</td></tr>';
                        ship_str_cost = '<tr><td>Shipping</td><td>Free (' + root.ShippingCostSummary.ShippingServiceName + ')</td></tr>';
                } else {
                        ship_str += '<tr><td>Shipping Service Cost</td><td>' + (root.ShippingCostSummary.ShippingServiceCost.CurrencyID == 'USD' ? '$' : root.ShippingCostSummary.ShippingServiceCost.CurrencyID + ' ') + root.ShippingCostSummary.ShippingServiceCost.Value.toFixed(2) + '</td></tr>';
                        ship_str_cost = '<tr><td>Shipping</td><td>' + (root.ShippingCostSummary.ShippingServiceCost.CurrencyID == 'USD' ? '$' : root.ShippingCostSummary.ShippingServiceCost.CurrencyID + ' ') + root.ShippingCostSummary.ShippingServiceCost.Value.toFixed(2) + ' (' + root.ShippingCostSummary.ShippingServiceName + ')</td></tr>';
                }
        }

        if (root.ShippingCostSummary.ShippingServiceName) {
                ship_str += '<tr><td>Shipping Service Name</td><td>' + root.ShippingCostSummary.ShippingServiceName + '</td></tr>';
        }

        if (root.ShippingCostSummary.ShippingType) {
                ship_str += '<tr><td>Shipping Type</td><td>' + root.ShippingCostSummary.ShippingType + '</td></tr>';
        }

        if (root.ShippingCostSummary.ImportCharge) {
                ship_str += '<tr><td>Import Charge</td><td>' + (root.ShippingCostSummary.ImportCharge.CurrencyID == 'USD' ? '$' : root.ShippingCostSummary.ImportCharge.CurrencyID + ' ') + root.ShippingCostSummary.ImportCharge.Value.toFixed(2) + '</td></tr>';
        }

        if (root.ShippingCostSummary.InsuranceCost) {
                ship_str += '<tr><td>Insurance Cost</td><td>' + (root.ShippingCostSummary.InsuranceCost.CurrencyID == 'USD' ? '$' : root.ShippingCostSummary.InsuranceCost.CurrencyID + ' ') + root.ShippingCostSummary.InsuranceCost.Value.toFixed(2) + '</td></tr>';
        }

        if (root.ShippingCostSummary.InsuranceOption) {
                ship_str += '<tr><td>Insurance Option</td><td>' + root.ShippingCostSummary.InsuranceOption + '</td></tr>';
        }

        if (root.ShippingCostSummary.InternationalInsuranceCost) {
                ship_str += '<tr><td>International Insurance Cost</td><td>' + (root.ShippingCostSummary.InternationalInsuranceCost.CurrencyID == 'USD' ? '$' : root.ShippingCostSummary.InternationalInsuranceCost.CurrencyID + ' ') + root.ShippingCostSummary.InternationalInsuranceCost.Value.toFixed(2) + '</td></tr>';
        }

        if (root.ShippingCostSummary.InternationalInsuranceOption) {
                ship_str += '<tr><td>International Insurance Option</td><td>' + root.ShippingCostSummary.InternationalInsuranceOption + '</td></tr>';
        }

        if (root.ShippingDetails.ExcludeShipToLocation) {
                var excludeArray = String(root.ShippingDetails.ExcludeShipToLocation).split(',');
                ship_str += '<tr><td>Exclude Ship to Location</td><td>';
                for (i = 0; i < excludeArray.length; i++) {
                        ship_str += (i > 0 ? ', ' : '') + mapCountryCode(excludeArray[i]);
                }
                ship_str += '</td></tr>';
        }

        if (root.ShippingDetails.SalesTax) {
                if (root.ShippingDetails.SalesTax.SalesTaxAmount) {
                        ship_str += '<tr><td>Sales Tax Amount</td><td>' + (root.ShippingDetails.SalesTax.SalesTaxAmount.CurrencyID == 'USD' ? '$' : root.ShippingDetails.SalesTax.SalesTaxAmount.CurrencyID + ' ') + root.ShippingDetails.SalesTax.SalesTaxAmount.Value.toFixed(2) + '</td></tr>';
                }
                if (root.ShippingDetails.SalesTax.SalesTaxPercent) {
                        ship_str += '<tr><td>Sales Tax Percentage</td><td>' + root.ShippingDetails.SalesTax.SalesTaxPercent.toFixed(3) + '%</td></tr>';
                }
                if (root.ShippingDetails.SalesTax.SalesTaxState) {
                        ship_str += '<tr><td>Sales Tax State</td><td>' + root.ShippingDetails.SalesTax.SalesTaxState + '</td></tr>';
                }
                if (root.ShippingDetails.SalesTax.ShippingIncludedInTax === true) {
                        ship_str += '<tr><td>Shipping Included In Tax</td><td></td></tr>';
                }
        }

        ship_str_tax = "";
        if (root.ShippingDetails.TaxTable && root.ShippingDetails.TaxTable.TaxJurisdiction.length > 0) {
                for (i = 0; i < root.ShippingDetails.TaxTable.TaxJurisdiction.length; i++) {
                        if (root.ShippingDetails.TaxTable.TaxJurisdiction[i].JurisdictionID !== undefined) {
                                taxTableEntries++;
                        }
                }
        }

        if (taxTableEntries) {
                ship_str += '<tr><td><strong>Tax Table</strong></td><td></td></tr>';
                for (i = 0; i < root.ShippingDetails.TaxTable.TaxJurisdiction.length; i++) {
                        if (root.ShippingDetails.TaxTable.TaxJurisdiction[i].JurisdictionID !== undefined) {
                                if (root.ShippingDetails.TaxTable.TaxJurisdiction[i].JurisdictionID == configTaxStateId) {
                                        ship_str_tax += '<tr><td>Tax</td><td>' + root.ShippingDetails.TaxTable.TaxJurisdiction[i].JurisdictionID + ' ' + root.ShippingDetails.TaxTable.TaxJurisdiction[i].SalesTaxPercent.toFixed(3) + '%';
                                        if (root.ShippingDetails.TaxTable.TaxJurisdiction[i].ShippingIncludedInTax && root.ShippingDetails.TaxTable.TaxJurisdiction[i].ShippingIncludedInTax === true) {
                                                ship_str_tax += '<br/>Shipping included in Tax';
                                        }
                                        ship_str_tax += '</td></tr>';
                                }
                                ship_str += '<tr><td>' + root.ShippingDetails.TaxTable.TaxJurisdiction[i].JurisdictionID + '</td><td>' + root.ShippingDetails.TaxTable.TaxJurisdiction[i].SalesTaxPercent.toFixed(3) + '%';
                                if (root.ShippingDetails.TaxTable.TaxJurisdiction[i].ShippingIncludedInTax && root.ShippingDetails.TaxTable.TaxJurisdiction[i].ShippingIncludedInTax === true) {
                                        ship_str += '<br/>Shipping included in Tax';
                                }
                                ship_str += '</td></tr>';
                        }
                }
        }

        for (i = 0; root.ShippingDetails.ShippingServiceOption && i < root.ShippingDetails.ShippingServiceOption.length; i++) {
                ship_str += '<tr><td><strong>Shipping Option ' + root.ShippingDetails.ShippingServiceOption[i].ShippingServicePriority + '</strong></td><td></td></tr>';

                if (root.ShippingDetails.ShippingServiceOption[i].ShippingServiceCost) {
                        if (root.ShippingDetails.ShippingServiceOption[i].ShippingServiceCost.Value === 0) {
                                ship_str += '<tr><td>Shipping Service Cost</td><td>Free</td></tr>';
                        } else {
                                ship_str += '<tr><td>Shipping Service Cost</td><td>' + (root.ShippingDetails.ShippingServiceOption[i].ShippingServiceCost.CurrencyID == 'USD' ? '$' : root.ShippingDetails.ShippingServiceOption[i].ShippingServiceCost.CurrencyID + ' ') + root.ShippingDetails.ShippingServiceOption[i].ShippingServiceCost.Value.toFixed(2) + '</td></tr>';
                        }
                }

                if (root.ShippingDetails.ShippingServiceOption[i].ShippingInsuranceCost) {
                        ship_str += '<tr><td>Shipping Insurance Cost</td><td>' + (root.ShippingDetails.ShippingServiceOption[i].ShippingInsuranceCost.CurrencyID == 'USD' ? '$' : root.ShippingDetails.ShippingServiceOption[i].ShippingInsuranceCost.CurrencyID + ' ') + root.ShippingDetails.ShippingServiceOption[i].ShippingInsuranceCost.Value.toFixed(2) + '</td></tr>';
                }

                if (root.ShippingDetails.ShippingServiceOption[i].ShippingServiceAdditionalCost) {
                        ship_str += '<tr><td>Shipping Additional Item Cost</td><td>' + (root.ShippingDetails.ShippingServiceOption[i].ShippingServiceAdditionalCost.CurrencyID == 'USD' ? '$' : root.ShippingDetails.ShippingServiceOption[i].ShippingServiceAdditionalCost.CurrencyID + ' ') + root.ShippingDetails.ShippingServiceOption[i].ShippingServiceAdditionalCost.Value.toFixed(2) + '</td></tr>';
                }

                if (root.ShippingDetails.ShippingServiceOption[i].ShippingSurcharge) {
                        ship_str += '<tr><td>Shipping Surcharge</td><td>' + (root.ShippingDetails.ShippingServiceOption[i].ShippingSurcharge.CurrencyID == 'USD' ? '$' : root.ShippingDetails.ShippingServiceOption[i].ShippingSurcharge.CurrencyID + ' ') + root.ShippingDetails.ShippingServiceOption[i].ShippingSurcharge.Value.toFixed(2) + '</td></tr>';
                }

                if (root.ShippingDetails.ShippingServiceOption[i].ShippingServiceName) {
                        ship_str += '<tr><td>Shipping Service Name</td><td>' + root.ShippingDetails.ShippingServiceOption[i].ShippingServiceName + '</td></tr>';
                }

                if (root.ShippingDetails.ShippingServiceOption[i].ShippingServiceOptionType) {
                        ship_str += '<tr><td>Shipping Type</td><td>' + root.ShippingDetails.ShippingServiceOption[i].ShippingServiceOptionType + '</td></tr>';
                }

                if (root.ShippingDetails.ShippingServiceOption[i].ShippingTimeMin && root.ShippingDetails.ShippingServiceOption[i].ShippingTimeMax) {
                        ship_str += '<tr><td>Delivery Time</td><td>';
                        if (root.ShippingDetails.ShippingServiceOption[i].ShippingTimeMin != root.ShippingDetails.ShippingServiceOption[i].ShippingTimeMax) {
                                ship_str += 'Between ' + root.ShippingDetails.ShippingServiceOption[i].ShippingTimeMin + ' and ';
                        }
                        ship_str += root.ShippingDetails.ShippingServiceOption[i].ShippingTimeMax + ' days</td></tr>';
                }

                if (root.ShippingDetails.ShippingServiceOption[i].ShippingServiceCutOffTime) {
                        ship_str += '<tr><td>Shipping Type</td><td>' + root.ShippingDetails.ShippingServiceOption[i].ShippingServiceCutOffTime + '</td></tr>';
                }

                if (root.ShippingDetails.ShippingServiceOption[i].ExpeditedService && root.ShippingDetails.ShippingServiceOption[i].ExpeditedService === true) {
                        ship_str += '<tr><td>Expedited Service</td><td></td></tr>';
                }

                if (root.ShippingDetails.ShippingServiceOption[i].FastAndFree && root.ShippingDetails.ShippingServiceOption[i].FastAndFree === true) {
                        ship_str += '<tr><td>Fast and Free</td><td></td></tr>';
                }

                if (root.ShippingDetails.ShippingServiceOption[i].ShipsTo) {
                        var includeArray = String(root.ShippingDetails.ShippingServiceOption[i].ShipsTo).split(',');
                        ship_str += '<tr><td>Ship to Location</td><td>';
                        for (j = 0; j < includeArray.length; j++) {
                                ship_str += (j > 0 ? ', ' : '') + includeArray[j];
                        }
                        ship_str += '</td></tr>';
                }
                ship_str += '<tr><td>' + '</td><td>' + '</td></tr>';
        }

        for (i = 0; root.ShippingDetails.InternationalShippingServiceOption && i < root.ShippingDetails.InternationalShippingServiceOption.length; i++) {
                ship_str += '<tr><td><strong>International Shipping Option ' + root.ShippingDetails.InternationalShippingServiceOption[i].ShippingServicePriority + '</strong></td><td></td></tr>';

                if (root.ShippingDetails.InternationalShippingServiceOption[i].ShippingServiceCost) {
                        if (root.ShippingDetails.InternationalShippingServiceOption[i].ShippingServiceCost.Value === 0) {
                                ship_str += '<tr><td>Shipping Service Cost</td><td>Free</td></tr>';
                        } else {
                                ship_str += '<tr><td>Shipping Service Cost</td><td>' + (root.ShippingDetails.InternationalShippingServiceOption[i].ShippingServiceCost.CurrencyID == 'USD' ? '$' : root.ShippingDetails.InternationalShippingServiceOption[i].ShippingServiceCost.CurrencyID + ' ') + root.ShippingDetails.InternationalShippingServiceOption[i].ShippingServiceCost.Value.toFixed(2) + '</td></tr>';
                        }
                }

                if (root.ShippingDetails.InternationalShippingServiceOption[i].ShippingInsuranceCost) {
                        ship_str += '<tr><td>Shipping Insurance Cost</td><td>' + (root.ShippingDetails.InternationalShippingServiceOption[i].ShippingInsuranceCost.CurrencyID == 'USD' ? '$' : root.ShippingDetails.InternationalShippingServiceOption[i].ShippingInsuranceCost.CurrencyID + ' ') + root.ShippingDetails.InternationalShippingServiceOption[i].ShippingInsuranceCost.Value.toFixed(2) + '</td></tr>';
                }

                if (root.ShippingDetails.InternationalShippingServiceOption[i].ShippingServiceAdditionalCost) {
                        ship_str += '<tr><td>Shipping Additional Item Cost</td><td>' + (root.ShippingDetails.InternationalShippingServiceOption[i].ShippingServiceAdditionalCost.CurrencyID == 'USD' ? '$' : root.ShippingDetails.InternationalShippingServiceOption[i].ShippingServiceAdditionalCost.CurrencyID + ' ') + root.ShippingDetails.InternationalShippingServiceOption[i].ShippingServiceAdditionalCost.Value.toFixed(2) + '</td></tr>';
                }

                if (root.ShippingDetails.InternationalShippingServiceOption[i].ImportCharge) {
                        ship_str += '<tr><td>Import Charge</td><td>' + (root.ShippingDetails.InternationalShippingServiceOption[i].ImportCharge.CurrencyID == 'USD' ? '$' : root.ShippingDetails.InternationalShippingServiceOption[i].ImportCharge.CurrencyID + ' ') + root.ShippingDetails.InternationalShippingServiceOption[i].ImportCharge.Value.toFixed(2) + '</td></tr>';
                }

                if (root.ShippingDetails.InternationalShippingServiceOption[i].ShippingServiceName) {
                        ship_str += '<tr><td>Shipping Service Name</td><td>' + root.ShippingDetails.InternationalShippingServiceOption[i].ShippingServiceName + '</td></tr>';
                }

                if (root.ShippingDetails.InternationalShippingServiceOption[i].InternationalShippingServiceOptionType) {
                        ship_str += '<tr><td>Shipping Type</td><td>' + root.ShippingDetails.InternationalShippingServiceOption[i].InternationalShippingServiceOptionType + '</td></tr>';
                }

                if (root.ShippingDetails.InternationalShippingServiceOption[i].EstimatedDeliveryMinTime && root.ShippingDetails.InternationalShippingServiceOption[i].EstimatedDeliveryMaxTime) {
                        ship_str += '<tr><td>Delivery Time</td><td>';
                        if (root.ShippingDetails.InternationalShippingServiceOption[i].EstimatedDeliveryMinTime != root.ShippingDetails.InternationalShippingServiceOption[i].EstimatedDeliveryMaxTime) {
                                ship_str += 'Between ' + moment(root.ShippingDetails.InternationalShippingServiceOption[i].EstimatedDeliveryMinTime, moment.ISO_8601).format("YYYY-MM-DD") + ' and ';
                        }
                        ship_str += moment(root.ShippingDetails.InternationalShippingServiceOption[i].EstimatedDeliveryMinTime, moment.ISO_8601).format("YYYY-MM-DD");
                        ship_str += (moment(root.ShippingDetails.InternationalShippingServiceOption[i].EstimatedDeliveryMaxTime).isValid() ? '' : ' days') + '</td></tr>';
                }

                if (root.ShippingDetails.InternationalShippingServiceOption[i].ShippingServiceCutOffTime) {
                        ship_str += '<tr><td>Shipping Type</td><td>' + root.ShippingDetails.InternationalShippingServiceOption[i].ShippingServiceCutOffTime + '</td></tr>';
                }

                if (root.ShippingDetails.InternationalShippingServiceOption[i].ShipsTo) {
                        var includeInternationalArray = String(root.ShippingDetails.InternationalShippingServiceOption[i].ShipsTo).split(',');
                        ship_str += '<tr><td>Ship to Location</td><td>';
                        for (j = 0; j < includeInternationalArray.length; j++) {
                                ship_str += (j > 0 ? ', ' : '') + includeInternationalArray[j];
                        }
                        ship_str += '</td></tr>';
                }
                ship_str += '<tr><td>' + '</td><td>' + '</td></tr>';
        }

        getShippingCostsDone = true;
}

function ConvertToCSVHeader() {
        var header = "";

        header += "itemId,";
        header += "title,";
        header += "subtitle,";
        header += "globalId,";
        header += "primaryCategory.categoryId,";
        header += "primaryCategory.categoryName,";
        header += "galleryURL,";
        header += "viewItemURL,";
        header += "paymentMethod,";
        header += "autoPay,";
        header += "location,";
        header += "country,";
        header += "sellerUserName,";
        header += "feedbackScore,";
        header += "positiveFeedbackPercent,";
        header += "feedbackRatingStar,";
        header += "topRatedSeller,";
        header += "storeName,";
        header += "storeURL,";
        header += "shippingInfo.shippingServiceCost.currencyId,";
        header += "shippingInfo.shippingServiceCost.value,";
        header += "shippingInfo.shippingType,";
        header += "shippingInfo.shipToLocations,";
        header += "shippingInfo.expeditedShipping,";
        header += "shippingInfo.oneDayShippingAvailable,";
        header += "shippingInfo.handlingTime,";
        header += "sellingStatus.currentPrice.currencyId,";
        header += "sellingStatus.currentPrice.value,";
        header += "sellingStatus.convertedCurrentPrice.currencyId,";
        header += "sellingStatus.convertedCurrentPrice.value,";
        header += "sellingStatus.bidCount,";
        header += "sellingStatus.sellingState,";
        header += "sellingStatus.timeLeft,";
        header += "listingInfo.bestOfferEnabled,";
        header += "listingInfo.buyItNowAvailable,";
        header += "listingInfo.convertedBuyItNowPrice.currencyId,";
        header += "listingInfo.convertedBuyItNowPrice.value,";
        header += "listingInfo.startTime,";
        header += "listingInfo.endTime,";
        header += "listingInfo.listingType,";
        header += "listingInfo.gift,";
        header += "listingInfo.watchCount,";
        header += "returnsAccepted,";
        header += "galleryPlusPictureURL,";
        header += "condition.conditionId,";
        header += "condition.conditionDisplayName,";
        header += "isMultiVariationListing,";
        header += "topRatedListing,";
        header += "distance,";
        header += "distance unit";
        header += "\r\n";

        return header;
}

function readParameters() {
        if (window.location.search[0] == '?') {
             var str = window.location.search.split('?')[1];
                $('form').deserialize(str);
        $(document.getElementById("category")).trigger("chosen:updated");
            eBaySearch(1);
        }
}

jQuery.fn.deserialize = function(data) {
        var f = this,
                map = {},
                find = function(selector) {
                        return f.is("form") ? f.find(selector) : f.filter(selector);
                };
        // Get map of values
        data = data.replace(/\+/g, " ");
        jQuery.each(data.split("&"), function() {
                var nv = this.split("="),
                        n = decodeURIComponent(nv[0]),
                        v = nv.length > 1 ? decodeURIComponent(nv[1]) : null;
                if (!(n in map)) {
                        map[n] = [];
                }
                map[n].push(v);
        });
        // Set values for all form elements in the data
        jQuery.each(map, function(n, v) {
                find("[name='" + n + "']").val(v);
        });
        // Clear all form elements not in form data
        find("input:text,select,textarea").each(function() {
                if (!(jQuery(this).attr("name") in map)) {
                        jQuery(this).val("");
                }
        });
        find("input:checkbox:checked,input:radio:checked").each(function() {
                if (!(jQuery(this).attr("name") in map)) {
                        this.checked = false;
                }
        });
        return this;
};

// Function to convert eBay JSON item to CSV format.
function ConvertToCSV(array) {
        var str = "";

        ++currentPage;
        updateProgressBar(maxPages, currentPage);

        for (var i = 0; i < array.length; i++) {
                var line = "";

                var JsonObj = array[i];
                line += "'" + JsonObj.itemId + ",";

                var title = String(JsonObj.title).replace(/\"/g, "");
                line += "\"" + title + "\",";

                if (JsonObj.subtitle) {
                        var subtitle = String(JsonObj.subtitle).replace(/\"/g, "");
                        line += "\"" + subtitle + "\",";
                } else {
                        line += ",";
                }

                line += JsonObj.globalId + ",";

                var primaryCategory = JsonObj.primaryCategory;
                line += primaryCategory[0].categoryId + ",";
                var categoryName = String(primaryCategory[0].categoryName).replace(/\"/g, "");
                line += "\"" + categoryName + "\",";

                line += JsonObj.galleryURL + ",";
                line += "\"" + JsonObj.viewItemURL + "\",";
                line += "\"" + JsonObj.paymentMethod + "\",";
                line += JsonObj.autoPay + ",";
                line += "\"" + JsonObj.location + "\",";
                line += JsonObj.country + ",";

                var sellerInfo = JsonObj.sellerInfo;
                line += sellerInfo[0].sellerUserName + ",";
                line += sellerInfo[0].feedbackScore + ",";
                line += sellerInfo[0].positiveFeedbackPercent + ",";
                line += sellerInfo[0].feedbackRatingStar + ",";
                line += sellerInfo[0].topRatedSeller + ",";

                var storeInfo = JsonObj.storeInfo;
                if (storeInfo) {
                        var storeName = String(storeInfo[0].storeName).replace(/\"/g, "");
                        line += "\"" + storeName + "\",";
                        line += storeInfo[0].storeURL + ",";
                } else {
                        line += ",";
                        line += ",";
                }
                var shippingInfo = JsonObj.shippingInfo;
                var shippingServiceCost = shippingInfo[0].shippingServiceCost;
                if (shippingServiceCost) {
                        line += shippingServiceCost[0]["@currencyId"] + ",";
                        line += shippingServiceCost[0].__value__ + ",";
                } else {
                        line += ",";
                        line += ",";
                }
                line += shippingInfo[0].shippingType + ",";
                line += shippingInfo[0].shipToLocations + ",";
                line += shippingInfo[0].expeditedShipping + ",";
                line += shippingInfo[0].oneDayShippingAvailable + ",";
                line += shippingInfo[0].handlingTime + ",";

                var sellingStatus = JsonObj.sellingStatus;
                var currentPrice = sellingStatus[0].currentPrice;
                var convertedCurrentPrice = sellingStatus[0].convertedCurrentPrice;
                line += currentPrice[0]["@currencyId"] + ",";
                line += currentPrice[0].__value__ + ",";
                line += convertedCurrentPrice[0]["@currencyId"] + ",";
                line += convertedCurrentPrice[0].__value__ + ",";
                if (sellingStatus[0].bidCount) {
                        line += sellingStatus[0].bidCount + ",";
                } else {
                        line += ",";
                }
                line += sellingStatus[0].sellingState + ",";
                line += formatTimeleft(moment.duration(sellingStatus[0].timeLeft).asSeconds()) + ",";

                var listingInfo = JsonObj.listingInfo;
                line += listingInfo[0].bestOfferEnabled + ",";
                line += listingInfo[0].buyItNowAvailable + ",";

                var convertedBuyItNowPrice = listingInfo[0].convertedBuyItNowPrice;
                if (convertedBuyItNowPrice) {
                        line += convertedBuyItNowPrice[0]["@currencyId"] + ",";
                        line += convertedBuyItNowPrice[0].__value__ + ",";
                } else {
                        line += ",";
                        line += ",";
                }
                line += listingInfo[0].startTime + ",";
                line += listingInfo[0].endTime + ",";
                line += listingInfo[0].listingType + ",";
                line += listingInfo[0].gift + ",";
                if (listingInfo[0].watchCount) {
                        line += listingInfo[0].watchCount + ",";
                } else {
                        line += ",";
                }

                line += JsonObj.returnsAccepted + ",";
                if (JsonObj.galleryPlusPictureURL) {
                        line += JsonObj.galleryPlusPictureURL + ",";
                } else {
                        line += ",";
                }

                var condition = JsonObj.condition;
                if (condition) {
                        line += condition[0].conditionId + ",";
                        line += condition[0].conditionDisplayName + ",";
                        line += JsonObj.isMultiVariationListing + ",";
                        line += JsonObj.topRatedListing + ",";
                } else {
                        line += ",";
                        line += ",";
                        line += ",";
                        line += ",";
                }

                if (JsonObj.distance !== undefined) {
                        line += JsonObj.distance[0].__value__ + ",";
                        line += JsonObj.distance[0]["@unit"] + ",";
                } else {
                        line += ",";
                        line += ",";
                }

                line += '\r\n';

                str += line;
        }

        var x = document.getElementById("csv");
        x.innerHTML += str;

        if (currentPage >= maxPages) {
                asyncFlag = true;
        }
}

function resetForm() {
        document.getElementById("searchForm").reset();
        $(document.getElementById("category")).trigger("chosen:updated");
}

function showKeywordHelp() {
        var x = document.getElementById("keywordHelp");
        if (x.className.indexOf("w3-show") == -1) {
                x.className += " w3-show";
        }
}

function hideKeywordHelp() {
        var x = document.getElementById("keywordHelp");
        x.className = x.className.replace(" w3-show", "");
}

function hideErrorBox() {
        var x = document.getElementById("warnings");
        x.className = x.className.replace(" w3-show", "");
}

function mapCountryCode(code) {
        var mappedCode = code;
        var countryCodes = {};

        countryCodes.AA = "APO/FPO";
        countryCodes.AD = "Andorra";
        countryCodes.AE = "United Arab Emirates";
        countryCodes.AF = "Afghanistan";
        countryCodes.AG = "Antigua and Barbuda";
        countryCodes.AI = "Anguilla";
        countryCodes.AL = "Albania";
        countryCodes.AM = "Armenia";
        countryCodes.AN = "Netherlands Antilles";
        countryCodes.AO = "Angola";
        countryCodes.AQ = "Antarctica";
        countryCodes.AR = "Argentina";
        countryCodes.AS = "American Samoa";
        countryCodes.AT = "Austria";
        countryCodes.AU = "Australia";
        countryCodes.AW = "Aruba";
        countryCodes.AZ = "Azerbaijan";
        countryCodes.BA = "Bosnia and Herzegovina";
        countryCodes.BB = "Barbados";
        countryCodes.BD = "Bangladesh";
        countryCodes.BE = "Belgium";
        countryCodes.BF = "Burkina Faso";
        countryCodes.BG = "Bulgaria";
        countryCodes.BH = "Bahrain";
        countryCodes.BI = "Burundi";
        countryCodes.BJ = "Benin";
        countryCodes.BM = "Bermuda";
        countryCodes.BN = "Brunei Darussalam";
        countryCodes.BO = "Bolivia";
        countryCodes.BR = "Brazil";
        countryCodes.BS = "Bahamas";
        countryCodes.BT = "Bhutan";
        countryCodes.BV = "Bouvet Island";
        countryCodes.BW = "Botswana";
        countryCodes.BY = "Belarus";
        countryCodes.BZ = "Belize";
        countryCodes.CA = "Canada";
        countryCodes.CC = "Cocos (Keeling) Islands";
        countryCodes.CD = "The Democratic Republic of the Congo";
        countryCodes.CF = "Central African Republic";
        countryCodes.CG = "Congo";
        countryCodes.CH = "Switzerland";
        countryCodes.CI = "Cote d'Ivoire";
        countryCodes.CK = "Cook Islands";
        countryCodes.CL = "Chile";
        countryCodes.CM = "Cameroon";
        countryCodes.CN = "China";
        countryCodes.CO = "Colombia";
        countryCodes.CR = "Costa Rica";
        countryCodes.CU = "Cuba";
        countryCodes.CV = "Cape Verde";
        countryCodes.CX = "Christmas Island";
        countryCodes.CY = "Cyprus";
        countryCodes.CZ = "Czech Republic";
        countryCodes.DE = "Germany";
        countryCodes.DJ = "Djibouti";
        countryCodes.DK = "Denmark";
        countryCodes.DM = "Dominica";
        countryCodes.DO = "Dominican Republic";
        countryCodes.DZ = "Algeria";
        countryCodes.EC = "Ecuador";
        countryCodes.EE = "Estonia";
        countryCodes.EG = "Egypt";
        countryCodes.EH = "Western Sahara";
        countryCodes.ER = "Eritrea";
        countryCodes.ES = "Spain";
        countryCodes.ET = "Ethiopia";
        countryCodes.FI = "Finland";
        countryCodes.FJ = "Fiji";
        countryCodes.FK = "Falkland Islands (Malvinas)";
        countryCodes.FM = "Federated States of Micronesia";
        countryCodes.FO = "Faroe Islands";
        countryCodes.FR = "France";
        countryCodes.GA = "Gabon";
        countryCodes.GB = "United Kingdom";
        countryCodes.GD = "Grenada";
        countryCodes.GE = "Georgia";
        countryCodes.GF = "French Guiana";
        countryCodes.GG = "Guernsey";
        countryCodes.GH = "Ghana";
        countryCodes.GI = "Gibraltar";
        countryCodes.GL = "Greenland";
        countryCodes.GM = "Gambia";
        countryCodes.GN = "Guinea";
        countryCodes.GP = "Guadeloupe";
        countryCodes.GQ = "Equatorial Guinea";
        countryCodes.GR = "Greece";
        countryCodes.GS = "South Georgia and the South Sandwich Islands";
        countryCodes.GT = "Guatemala";
        countryCodes.GU = "Guam";
        countryCodes.GW = "Guinea-Bissau";
        countryCodes.GY = "Guyana";
        countryCodes.HK = "Hong Kong";
        countryCodes.HM = "Heard Island and McDonald Islands";
        countryCodes.HN = "Honduras";
        countryCodes.HR = "Croatia";
        countryCodes.HT = "Haiti";
        countryCodes.HU = "Hungary";
        countryCodes.ID = "Indonesia";
        countryCodes.IE = "Ireland";
        countryCodes.IL = "Israel";
        countryCodes.IN = "India";
        countryCodes.IO = "British Indian Ocean Territory";
        countryCodes.IQ = "Iraq";
        countryCodes.IR = "Islamic Republic of Iran";
        countryCodes.IS = "Iceland";
        countryCodes.IT = "Italy";
        countryCodes.JE = "Jersey";
        countryCodes.JM = "Jamaica";
        countryCodes.JO = "Jordan";
        countryCodes.JP = "Japan";
        countryCodes.KE = "Kenya";
        countryCodes.KG = "Kyrgyzstan";
        countryCodes.KH = "Cambodia";
        countryCodes.KI = "Kiribati";
        countryCodes.KM = "Comoros";
        countryCodes.KN = "Saint Kitts and Nevis";
        countryCodes.KP = "Democratic People's Republic of Korea";
        countryCodes.KR = "Republic of Korea";
        countryCodes.KW = "Kuwait";
        countryCodes.KY = "Cayman Islands";
        countryCodes.KZ = "Kazakhstan";
        countryCodes.LA = "Lao People's Democratic Republic";
        countryCodes.LB = "Lebanon";
        countryCodes.LC = "Saint Lucia";
        countryCodes.LI = "Liechtenstein";
        countryCodes.LK = "Sri Lanka";
        countryCodes.LR = "Liberia";
        countryCodes.LS = "Lesotho";
        countryCodes.LT = "Lithuania";
        countryCodes.LU = "Luxembourg";
        countryCodes.LV = "Latvia";
        countryCodes.LY = "Libyan Arab Jamahiriya";
        countryCodes.MA = "Morocco";
        countryCodes.MC = "Monaco";
        countryCodes.MD = "Republic of Moldova";
        countryCodes.ME = "Montenegro";
        countryCodes.MG = "Madagascar";
        countryCodes.MH = "Marshall Islands";
        countryCodes.MK = "The Former Yugoslav Republic of Macedonia";
        countryCodes.ML = "Mali";
        countryCodes.MM = "Myanmar";
        countryCodes.MN = "Mongolia";
        countryCodes.MO = "Macao";
        countryCodes.MP = "Northern Mariana Islands";
        countryCodes.MQ = "Martinique";
        countryCodes.MR = "Mauritania";
        countryCodes.MS = "Montserrat";
        countryCodes.MT = "Malta";
        countryCodes.MU = "Mauritius";
        countryCodes.MV = "Maldives";
        countryCodes.MW = "Malawi";
        countryCodes.MX = "Mexico";
        countryCodes.MY = "Malaysia";
        countryCodes.MZ = "Mozambique";
        countryCodes.NA = "Namibia";
        countryCodes.NC = "New Caledonia";
        countryCodes.NE = "Niger";
        countryCodes.NF = "Norfolk Island";
        countryCodes.NG = "Nigeria";
        countryCodes.NI = "Nicaragua";
        countryCodes.NL = "Netherlands";
        countryCodes.NO = "Norway";
        countryCodes.NP = "Nepal";
        countryCodes.NR = "Nauru";
        countryCodes.NU = "Niue";
        countryCodes.NZ = "New Zealand";
        countryCodes.OM = "Oman";
        countryCodes.PA = "Panama";
        countryCodes.PE = "Peru";
        countryCodes.PF = "French Polynesia Includes Tahiti";
        countryCodes.PG = "Papua New Guinea";
        countryCodes.PH = "Philippines";
        countryCodes.PK = "Pakistan";
        countryCodes.PL = "Poland";
        countryCodes.PM = "Saint Pierre and Miquelon";
        countryCodes.PN = "Pitcairn";
        countryCodes.PR = "Puerto Rico";
        countryCodes.PS = "Palestinian territory, Occupied";
        countryCodes.PT = "Portugal";
        countryCodes.PW = "Palau";
        countryCodes.PY = "Paraguay";
        countryCodes.QA = "Qatar";
        countryCodes.QM = "Guernsey";
        countryCodes.QN = "Jan Mayen";
        countryCodes.QO = "Jersey";
        countryCodes.RE = "Reunion";
        countryCodes.RO = "Romania";
        countryCodes.RS = "Serbia";
        countryCodes.RU = "Russian Federation";
        countryCodes.RW = "Rwanda";
        countryCodes.SA = "Saudi Arabia";
        countryCodes.SB = "Solomon Islands";
        countryCodes.SC = "Seychelles";
        countryCodes.SD = "Sudan";
        countryCodes.SE = "Sweden";
        countryCodes.SG = "Singapore";
        countryCodes.SH = "Saint Helena";
        countryCodes.SI = "Slovenia";
        countryCodes.SJ = "Svalbard and Jan Mayen";
        countryCodes.SK = "Slovakia";
        countryCodes.SL = "Sierra Leone";
        countryCodes.SM = "San Marino";
        countryCodes.SN = "Senegal";
        countryCodes.SO = "Somalia";
        countryCodes.SR = "Suriname";
        countryCodes.ST = "Sao Tome and Principe";
        countryCodes.SV = "El Salvador";
        countryCodes.SY = "Syrian Arab Republic";
        countryCodes.SZ = "Swaziland";
        countryCodes.TA = "Tristan da Cunha";
        countryCodes.TC = "Turks and Caicos Islands";
        countryCodes.TD = "Chad";
        countryCodes.TF = "French Southern Territories";
        countryCodes.TG = "Togo";
        countryCodes.TH = "Thailand";
        countryCodes.TJ = "Tajikistan";
        countryCodes.TK = "Tokelau";
        countryCodes.TM = "Turkmenistan";
        countryCodes.TN = "Tunisia";
        countryCodes.TO = "Tonga";
        countryCodes.TR = "Turkey";
        countryCodes.TT = "Trinidad and Tobago";
        countryCodes.TV = "Tuvalu";
        countryCodes.TW = "Taiwan, Province of China";
        countryCodes.TZ = "Tanzania, United Republic of";
        countryCodes.UA = "Ukraine";
        countryCodes.UG = "Uganda";
        countryCodes.UM = "United States Minor Outlying Islands";
        countryCodes.US = "United States";
        countryCodes.UY = "Uruguay";
        countryCodes.UZ = "Uzbekistan";
        countryCodes.VA = "Holy See (Vatican City state)";
        countryCodes.VC = "Saint Vincent and the Grenadines";
        countryCodes.VE = "Venezuela";
        countryCodes.VG = "Virgin Islands, British";
        countryCodes.VI = "Virgin Islands, US";
        countryCodes.VN = "Vietnam";
        countryCodes.VU = "Vanuatu";
        countryCodes.WF = "Wallis and Futuna";
        countryCodes.WS = "Samoa";
        countryCodes.YE = "Yemen";
        countryCodes.YT = "Mayotte";
        countryCodes.ZA = "South Africa";
        countryCodes.ZM = "Zambia";
        countryCodes.ZW = "Zimbabwe";

        if (countryCodes[code] !== undefined) {
                mappedCode = countryCodes[code];
        }

        return mappedCode;
}

var minActive = [0.0, 0.0, 0.0];
var maxActive = [0.0, 0.0, 0.0];
var avgActive = [0.0, 0.0, 0.0];
var noActive = [0, 0, 0];
var minSold = [0.0, 0.0, 0.0];
var maxSold = [0.0, 0.0, 0.0];
var avgSold = [0.0, 0.0, 0.0];
var noSold = [0, 0, 0];
var minUnsold = [0.0, 0.0, 0.0];
var maxUnsold = [0.0, 0.0, 0.0];
var avgUnsold = [0.0, 0.0, 0.0];
var noUnsold = [0, 0, 0];
var newActiveBreakdown = [];
var usedActiveBreakdown = [];
var newSoldBreakdown = [];
var usedSoldBreakdown = [];
var duplicateCheckFlag;
var duplicateCheckText;

function getPricing() {
        minActive = [0.0, 0.0, 0.0];
        maxActive = [0.0, 0.0, 0.0];
        avgActive = [0.0, 0.0, 0.0];
        noActive = [0, 0, 0];
        minSold = [0.0, 0.0, 0.0];
        maxSold = [0.0, 0.0, 0.0];
        avgSold = [0.0, 0.0, 0.0];
        noSold = [0, 0, 0];
        minUnsold = [0.0, 0.0, 0.0];
        maxUnsold = [0.0, 0.0, 0.0];
        avgUnsold = [0.0, 0.0, 0.0];
        noUnsold = [0, 0, 0];
        maxPricingPages = [-1, -1];
        totalPricingEntries = [0, 0];
        newActiveBreakdown = [];
        usedActiveBreakdown = [];
        newSoldBreakdown = [];
        usedSoldBreakdown = [];
        duplicateCheckFlag = false;
        duplicateCheckText = '';

        getPricingData(0);
        getPricingData(1);
}

function getPricingData(searchIndex) {
        var index = 0;
        var keyword = document.getElementById('keyword').value;

        // Construct the request
        var url = configeBayFinding + "?";
        if (searchIndex === 0) {
                if (keyword.includes("ReferenceID:")) {
                        url += "OPERATION-NAME=findItemsByProduct";
                } else {
                        url += "OPERATION-NAME=findItemsAdvanced";
                }
        } else {
                url += "OPERATION-NAME=findCompletedItems";
        }
        url += "&SECURITY-APPNAME=" + configAppid;
        url += "&GLOBAL-ID=EBAY-US";
        url += "&RESPONSE-DATA-FORMAT=JSON";
        url += "&SERVICE-VERSION=" + configeBayFindingVersion;
        url += "&REST-PAYLOAD";
        if (keyword.length > 0) {
                if (keyword.includes("ReferenceID:")) {
                        url += "&productId.@type=ReferenceID";
                        url += "&productId=";
                        url += keyword.substr(12);
                } else {
                        url += "&keywords=";
                        url += encodeURIComponent(keyword.trim().replace(/ /g, "+"));
                }
        }

        var catNo = 0;
        for (var categoryIndex = 1; categoryIndex < document.getElementById('category').options.length; categoryIndex++) {
                if (document.getElementById('category').options[categoryIndex].selected) {
                        url += "&categoryId(" + catNo + ")=";
                        url += document.getElementById('category').options[categoryIndex].value;
                        ++catNo;
                }
        }

        url += "&paginationInput.entriesPerPage=100";
        url += "&paginationInput.pageNumber=";
        url += (index + 1);
        url += "&sortOrder=";
        url += getSortOrder();
        url += "&buyerPostalCode=";
        url += configZip;
        url += "&outputSelector(0)=SellerInfo&outputSelector(1)=StoreInfo";
        if (document.getElementById('searchDescription').checked) {
                url += "&descriptionSearch=true";
        }

        url += urlfilter;

        var xhttp = new XMLHttpRequest();

        xhttp.onreadystatechange = function() {
        if (this.readyState == 4) {
                        if (searchIndex === 0) {
                                _cb_PriceActiveItems(JSON.parse(this.responseText));
                        } else {
                                _cb_PriceCompletedItems(JSON.parse(this.responseText));
                        }
        }
    };

        xhttp.open("GET", configProxyUrl, true);
        xhttp.setRequestHeader("X-Proxy-Url", encodeURI(url));
        xhttp.send();

        function waitForMaxPricingPages(i) {
                if (maxPricingPages[i] < 0) {
                        window.setTimeout(waitForMaxPricingPages, 500, i); // wait 500 milliseconds
                } else {
                        for (index = 1; index < maxPricingPages[searchIndex]; index++) {
                                // Construct the request
                                var url = configeBayFinding + "?";
                                if (searchIndex === 0) {
                                        if (keyword.includes("ReferenceID:")) {
                                                url += "OPERATION-NAME=findItemsByProduct";
                                        } else {
                                                url += "OPERATION-NAME=findItemsAdvanced";
                                        }
                                } else {
                                        url += "OPERATION-NAME=findCompletedItems";
                                }
                                url += "&SECURITY-APPNAME=" + configAppid;
                                url += "&GLOBAL-ID=EBAY-US";
                                url += "&RESPONSE-DATA-FORMAT=JSON";
                                url += "&SERVICE-VERSION=" + configeBayFindingVersion;
                                url += "&REST-PAYLOAD";
                                keyword = document.getElementById('keyword').value;
                                if (keyword.length > 0) {
                                        if (keyword.includes("ReferenceID:")) {
                                                url += "&productId.@type=ReferenceID";
                                                url += "&productId=";
                                                url += keyword.substr(12);
                                        } else {
                                                url += "&keywords=";
                                                url += encodeURIComponent(keyword.trim().replace(/ /g, "+"));
                                        }
                                }

                                var catNo = 0;
                                for (var categoryIndex = 1; categoryIndex < document.getElementById('category').options.length; categoryIndex++) {
                                        if (document.getElementById('category').options[categoryIndex].selected) {
                                                url += "&categoryId(" + catNo + ")=";
                                                url += document.getElementById('category').options[categoryIndex].value;
                                                ++catNo;
                                        }
                                }

                                url += "&paginationInput.entriesPerPage=100";
                                url += "&paginationInput.pageNumber=";
                                url += (index + 1);
                                url += "&sortOrder=";
                                url += getSortOrder();
                                url += "&buyerPostalCode=";
                                url += configZip;
                                url += "&outputSelector(0)=SellerInfo&outputSelector(1)=StoreInfo";
                                if (document.getElementById('searchDescription').checked) {
                                        url += "&descriptionSearch=true";
                                }

                                url += urlfilter;

                                var xhttp = new XMLHttpRequest();

                                xhttp.onreadystatechange = function() {
                                if (this.readyState == 4) {
                                                if (searchIndex === 0) {
                                                        _cb_PriceActiveItems(JSON.parse(this.responseText));
                                                } else {
                                                        _cb_PriceCompletedItems(JSON.parse(this.responseText));
                                                }
                                }
                            };

                                xhttp.open("GET", configProxyUrl, true);
                                xhttp.setRequestHeader("X-Proxy-Url", encodeURI(url));
                                xhttp.send();                   }
                }
        }

        waitForMaxPricingPages(searchIndex);
}

function _cb_PriceActiveItems(objArray) {
        var array;

        if (objArray.findItemsAdvancedResponse !== undefined) {
                array = typeof objArray.findItemsAdvancedResponse[0] != 'object' ? JSON.parse(objArray.findItemsAdvancedResponse[0]) : objArray.findItemsAdvancedResponse[0].searchResult[0].item;
                totalPricingEntries[0] = Number(objArray.findItemsAdvancedResponse[0].paginationOutput[0].totalEntries);
        } else if (objArray.findItemsByProductResponse !== undefined) {
                array = typeof objArray.findItemsByProductResponse[0] != 'object' ? JSON.parse(objArray.findItemsByProductResponse[0]) : objArray.findItemsByProductResponse[0].searchResult[0].item;
                totalPricingEntries[0] = Number(objArray.findItemsByProductResponse[0].paginationOutput[0].totalEntries);
        } else {
                return;
        }
        //      var array = typeof objArray.findItemsAdvancedResponse[0] != 'object' ? JSON.parse(objArray.findItemsAdvancedResponse[0]) : objArray.findItemsAdvancedResponse[0].searchResult[0].item;
        if (totalPricingEntries[0] > 0) {
                priceItem(array, 0);
        }
}

function _cb_PriceCompletedItems(objArray) {
        var array = typeof objArray.findCompletedItemsResponse[0] != 'object' ? JSON.parse(objArray.findCompletedItemsResponse[0]) : objArray.findCompletedItemsResponse[0].searchResult[0].item;
        totalPricingEntries[1] = Number(objArray.findCompletedItemsResponse[0].paginationOutput[0].totalEntries);
        if (totalPricingEntries[1] > 0) {
                priceItem(array, 1);
        }
}

function priceItem(array, index) {
        var shippingCost = 0.0;
        var itemCost = 0.0;
        var totalCost = 0.0;
        var totalCostInt = 0;
        var sellingStatus;
        var sellingState;
        var bidCount;
        var condInd;
        var conditionId;

        if (totalPricingEntries[index] < 1) {
                maxPricingPages[index] = 0;
        } else {
                maxPricingPages[index] = (totalPricingEntries[index] / 100) > 100 ? 100 : Math.trunc(totalPricingEntries[index] / 100.0) + 1;
        }

        for (var i = 0; i < array.length; i++) {
                var JsonObj = array[i];

                var shippingInfo = JsonObj.shippingInfo;
                var shippingServiceCost = shippingInfo[0].shippingServiceCost;
                if (shippingServiceCost) {
                        shippingCost = Number(shippingServiceCost[0].__value__);
                } else {
                        shippingCost = 0.0;
                }

                sellingStatus = JsonObj.sellingStatus;
                sellingState = sellingStatus[0].sellingState;
                bidCount = sellingStatus[0].bidCount;
                var convertedCurrentPrice = sellingStatus[0].convertedCurrentPrice;
                itemCost = Number(convertedCurrentPrice[0].__value__);

                var listingInfo = JsonObj.listingInfo;
                var convertedBuyItNowPrice = listingInfo[0].convertedBuyItNowPrice;
                if (bidCount === 0 && convertedBuyItNowPrice) {
                        itemCost = Number(convertedBuyItNowPrice[0].__value__);
                }

                var condition = JsonObj.condition;
                if (condition) {
                        conditionId = condition[0].conditionId;
                        if (conditionId == 1000 || conditionId == 1500 || conditionId == 2750) {
                                condInd = 1;
                        } else {
                                condInd = 2;
                        }
                } else {
                        condInd = 2;
                }

                totalCost = itemCost + shippingCost;
                totalCostInt = Math.ceil(totalCost);

                if (sellingState == "Active") {
                        if (totalCost < minActive[0] || !minActive[0]) {
                                minActive[0] = totalCost;
                        }
                        if (totalCost > maxActive[0]) {
                                maxActive[0] = totalCost;
                        }
                        avgActive[0] += totalCost;
                        ++noActive[0];

                        if (totalCost < minActive[condInd] || !minActive[condInd]) {
                                minActive[condInd] = totalCost;
                        }
                        if (totalCost > maxActive[condInd]) {
                                maxActive[condInd] = totalCost;
                        }
                        avgActive[condInd] += totalCost;
                        ++noActive[condInd];

                        if (condInd == 1) {
                                if (newActiveBreakdown[totalCostInt] === undefined) {
                                        newActiveBreakdown[totalCostInt] = 0;
                                }
                                ++newActiveBreakdown[totalCostInt];
                        } else {
                                if (usedActiveBreakdown[totalCostInt] === undefined) {
                                        usedActiveBreakdown[totalCostInt] = 0;
                                }
                                ++usedActiveBreakdown[totalCostInt];
                        }
                } else if (sellingState == "EndedWithSales") {
                        if (totalCost < minSold[0] || !minSold[0]) {
                                minSold[0] = totalCost;
                        }
                        if (totalCost > maxSold[0]) {
                                maxSold[0] = totalCost;
                        }
                        avgSold[0] += totalCost;
                        ++noSold[0];

                        if (totalCost < minSold[condInd] || !minSold[condInd]) {
                                minSold[condInd] = totalCost;
                        }
                        if (totalCost > maxSold[condInd]) {
                                maxSold[condInd] = totalCost;
                        }
                        avgSold[condInd] += totalCost;
                        ++noSold[condInd];

                        if (condInd == 1) {
                                if (newSoldBreakdown[totalCostInt] === undefined) {
                                        newSoldBreakdown[totalCostInt] = 0;
                                }
                                ++newSoldBreakdown[totalCostInt];
                        } else {
                                if (usedSoldBreakdown[totalCostInt] === undefined) {
                                        usedSoldBreakdown[totalCostInt] = 0;
                                }
                                ++usedSoldBreakdown[totalCostInt];
                        }
                } else {
                        if (totalCost < minUnsold[0] || !minUnsold[0]) {
                                minUnsold[0] = totalCost;
                        }
                        if (totalCost > maxUnsold[0]) {
                                maxUnsold[0] = totalCost;
                        }
                        avgUnsold[0] += totalCost;
                        ++noUnsold[0];

                        if (totalCost < minUnsold[condInd] || !minUnsold[condInd]) {
                                minUnsold[condInd] = totalCost;
                        }
                        if (totalCost > maxUnsold[condInd]) {
                                maxUnsold[condInd] = totalCost;
                        }
                        avgUnsold[condInd] += totalCost;
                        ++noUnsold[condInd];
                }
        }

        var x = document.getElementById("prices");
        if (x.className.indexOf("w3-show") == -1) {
                x.className += " w3-show";
        }

        var str = '<h2>Pricing Information (Shipping included)</h2>';
        str += '<div id="duplicates">' + duplicateCheckText + '</div>';
        str += '<table class="w3-table-all">';
        str += '        <tr>';
        str += '                <th></th>';
        str += '                <th>Number</th>';
        str += '        <th>Minimum</th>';
        str += '        <th>Maximum</th>';
        str += '        <th>Average</th>';
        str += '        </tr>';
        str += '        <tr>';
        str += '                <td>Active</td>';
        str += '                <td>' + noActive[0] + '<br/>' + noActive[1] + ' / ' + noActive[2] + '</td>';
        str += '                <td>$' + Number(minActive[0]).toFixed(2) + '<br/>$' + Number(minActive[1]).toFixed(2) + ' / $' + Number(minActive[2]).toFixed(2) + '</td>';
        str += '                <td>$' + Number(maxActive[0]).toFixed(2) + '<br/>$' + Number(maxActive[1]).toFixed(2) + ' / $' + Number(maxActive[2]).toFixed(2) + '</td>';
        str += '                <td>';
        if (noActive[0]) {
                str += '$' + Number(avgActive[0] / noActive[0]).toFixed(2);
                str += '<br/>$' + (noActive[1] > 0 ? Number(avgActive[1] / noActive[1]).toFixed(2) : 0.00);
                str += ' / $' + (noActive[2] > 0 ? Number(avgActive[2] / noActive[2]).toFixed(2) : 0.00);
        }
        str += '</td>';
        str += '        </tr>';

        str += '<tr><td colspan="5">';
        str += '<canvas id="activeChart"></canvas>';
        str += '</td></tr>';

        str += '        <tr>';
        str += '                <td>Sold</td>';
        str += '                <td>' + noSold[0] + '<br/>' + noSold[1] + ' / ' + noSold[2] + '</td>';
        str += '                <td>$' + Number(minSold[0]).toFixed(2) + '<br/>$' + Number(minSold[1]).toFixed(2) + ' / $' + Number(minSold[2]).toFixed(2) + '</td>';
        str += '                <td>$' + Number(maxSold[0]).toFixed(2) + '<br/>$' + Number(maxSold[1]).toFixed(2) + ' / $' + Number(maxSold[2]).toFixed(2) + '</td>';
        str += '                <td>';
        if (noSold[0]) {
                str += '$' + Number(avgSold[0] / noSold[0]).toFixed(2);
                str += '<br/>$' + (noSold[1] > 0 ? Number(avgSold[1] / noSold[1]).toFixed(2) : 0.00);
                str += ' / $' + (noSold[2] > 0 ? Number(avgSold[2] / noSold[2]).toFixed(2) : 0.00);
        }
        str += '</td>';
        str += '        </tr>';

        str += '<tr><td colspan="5">';
        str += '<canvas id="soldChart"></canvas>';
        str += '</td></tr>';

        str += '        <tr>';
        str += '                <td>Unsold</td>';
        str += '                <td>' + noUnsold[0] + '<br/>' + noUnsold[1] + ' / ' + noUnsold[2] + '</td>';
        str += '                <td>$' + Number(minUnsold[0]).toFixed(2) + '<br/>$' + Number(minUnsold[1]).toFixed(2) + ' / $' + Number(minUnsold[2]).toFixed(2) + '</td>';
        str += '                <td>$' + Number(maxUnsold[0]).toFixed(2) + '<br/>$' + Number(maxUnsold[1]).toFixed(2) + ' / $' + Number(maxUnsold[2]).toFixed(2) + '</td>';
        str += '                <td>';
        if (noUnsold[0]) {
                str += '$' + Number(avgUnsold[0] / noUnsold[0]).toFixed(2);
                str += '<br/>$' + (noUnsold[1] > 0 ? Number(avgUnsold[1] / noUnsold[1]).toFixed(2) : 0.00);
                str += ' / $' + (noUnsold[2] > 0 ? Number(avgUnsold[2] / noUnsold[2]).toFixed(2) : 0.00);
        }
        str += '</td>';
        str += '        </tr>';
        str += '</table>';

        x.innerHTML = str;

        pricingGraphs(0, usedActiveBreakdown, newActiveBreakdown);
        pricingGraphs(1, usedSoldBreakdown, newSoldBreakdown);
}

function pricingGraphs(index, usedBreakdown, newBreakdown) {
        var i;
        var newData = [];
        var usedData = [];
        var labelData = [];
        var ctx = document.getElementById(index === 0 ? 'activeChart' : 'soldChart').getContext('2d');
        var min = findMin(usedBreakdown, newBreakdown);
        var max = findMax(usedBreakdown, newBreakdown);

        for (i = min; i < max; i++) {
                labelData.push('<$' + i);

                if (usedBreakdown[i] === undefined) {
                        usedData.push(0);
                } else {
                        usedData.push(usedBreakdown[i]);
                }

                if (newBreakdown[i] === undefined) {
                        newData.push(0);
                } else {
                        newData.push(newBreakdown[i]);
                }
        }

        var myChart = new Chart(ctx, {
          type: 'bar',
          options: {
            scales: {
                yAxes: [{
                    ticks: {
                        fixedStepSize: 1
                    }
                }],
            },
          },
          data: {
        labels: labelData,
            datasets: [{
          label: 'Used',
                  data: usedData,
          backgroundColor: "rgba(0,102,0,1)"
            }, {
          label: 'New',
              data: newData,
          backgroundColor: "rgba(204,0,0,1)"
            }]
          }
        });
}

function findMin(Used, New) {
        var i;
        var minUsed = 0, minNew = 0;
        var min = 0;

        for (i = 0; i < Used.length; i++) {
                if (Used[i] !== undefined) {
                        minUsed = i;
                        break;
                }
        }

        for (i = 0; i < New.length; i++) {
                if (New[i] !== undefined) {
                        minNew = i;
                        break;
                }
        }

        if (minUsed > 0 && minUsed <= minNew) {
                min = minUsed;
        } else if (minNew > 0 && minNew <= minUsed) {
                min = minNew;
        }

        return min;
}

function findMax(Used, New) {
        var max = 0;

        if (Used.length >= New.length) {
                max = Used.length;
        } else if (New.length >= Used.length) {
                max = New.length;
        }

        return max;
}

function _cb_findDuplicateListing(root) {
        var x;
        var txt;
        var response = root.findItemsAdvancedResponse[0];
        var ack = response.ack;
        if (ack != 'Success') {
                if (ack == 'Failure' || ack == 'PartialFailure') {
                        return;
                }
        }

        var items = response.searchResult[0].item || [];

        if (Number(response.paginationOutput[0].totalEntries) > 0) {
                var txt = '<p class="w3-red"><strong>Duplicate, see Item Id <a href="https://www.ebay.com/itm/' + items[0].itemId + '" target="_blank">' + items[0].itemId + '</a></strong></p>';
                document.getElementById("duplicatesText").innerHTML += txt;
                x = document.getElementById("duplicates");
                if (x.className.indexOf("w3-show") == -1) {
                        x.className += " w3-show";
                }
        }
}

function findDuplicateListing() {
        var keywordURL;
        var keyword = document.getElementById('keyword').value;

        // Construct the request
        url = configeBayFinding + "?";
        url += "OPERATION-NAME=findItemsAdvanced";
        url += "&SERVICE-VERSION=" + configeBayFindingVersion;
        url += "&SECURITY-APPNAME=" + configAppid;
        url += "&GLOBAL-ID=EBAY-US";
        url += "&RESPONSE-DATA-FORMAT=JSON";
        url += "&REST-PAYLOAD";

        if (keyword.length > 0) {
                if (keyword.includes("ReferenceID:")) {
                        url += "&productId.@type=ReferenceID";
                        url += "&productId=";
                        url += keyword.substr(12);
                } else {
                        url += "&keywords=";
                        url += encodeURIComponent(keyword.trim().replace(/ /g, "+"));
                }
        }

        url += "&paginationInput.entriesPerPage=1";
        url += "&paginationInput.pageNumber=1";
        url += "&itemFilter(0).name=Seller";
        url += "&itemFilter(0).value=";
        url += configeBaySellerName;
        url += "&outputSelector=SellerInfo";

        // Submit the request
        var xhttp = new XMLHttpRequest();

        xhttp.onreadystatechange = function() {
        if (this.readyState == 4) {
                _cb_findDuplicateListing(JSON.parse(this.responseText));
        }
    };

        xhttp.open("GET", configProxyUrl, true);
        xhttp.setRequestHeader("X-Proxy-Url", encodeURI(url));
        xhttp.send();

        return false;
}

function _cb_findPotentialDuplicateListing(root) {
        var x;
        var response = root.findCompletedItemsResponse[0];
        var ack = response.ack;
        if (ack != 'Success') {
                if (ack == 'Failure' || ack == 'PartialFailure') {
                        return;
                }
        }

        var items = response.searchResult[0].item || [];

        if (Number(response.paginationOutput[0].totalEntries) > 0) {
                var txt = '<p class="w3-orange"><strong>Potential Duplicate, see Item Id <a href="https://www.ebay.com/itm/' + items[0].itemId + '" target="_blank">' + items[0].itemId + '</a></strong></p>';
                document.getElementById("duplicatesText").innerHTML += txt;
                x = document.getElementById("duplicates");
                if (x.className.indexOf("w3-show") == -1) {
                        x.className += " w3-show";
                }
        }
}

function findPotentialDuplicateListing() {
        var keywordURL;
        var keyword = document.getElementById('keyword').value;

        // Construct the request
        url = configeBayFinding + "?";
        url += "OPERATION-NAME=findCompletedItems";
        url += "&SERVICE-VERSION=" + configeBayFindingVersion;
        url += "&SECURITY-APPNAME=" + configAppid;
        url += "&GLOBAL-ID=EBAY-US";
        url += "&RESPONSE-DATA-FORMAT=JSON";
        url += "&REST-PAYLOAD";
        url += "&keywords=";
        url += encodeURIComponent(keyword.trim().replace(/ /g, "+"));
        url += "&paginationInput.entriesPerPage=1";
        url += "&paginationInput.pageNumber=1";
        url += "&itemFilter(0).name=Seller";
        url += "&itemFilter(0).value=";
        url += configeBaySellerName;
        url += "&outputSelector=SellerInfo";

        var xhttp = new XMLHttpRequest();

        xhttp.onreadystatechange = function() {
        if (this.readyState == 4) {
                _cb_findPotentialDuplicateListing(JSON.parse(this.responseText));
        }
    };

        xhttp.open("GET", configProxyUrl, true);
        xhttp.setRequestHeader("X-Proxy-Url", encodeURI(url));
        xhttp.send();
        return false;
}

function findShopifyDuplicateListing() { // Barcode Search Only
        var handle;
        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
                if (this.readyState == 4 && this.status == 200) {
                        //window.alert(this.responseText);
                        var json = JSON.parse(this.responseText);
                        if (json.products[0] !== undefined) {
                            var sku = getJsonValue(json.products[0].variants[0].sku);
                                var txt = '<p class="w3-orange"><strong>Potential Duplicate, see Shopify Item Id <a href="https://munatrading.com/products/b' + handle + '" target="_blank">' + handle + '</a> (SKU=' + sku + ')</strong></p>';
                                document.getElementById("duplicatesText").innerHTML += txt;
                        x = document.getElementById("duplicates");
                        if (x.className.indexOf("w3-show") == -1) {
                                x.className += " w3-show";
                        }
                        }
                }
        };

        handle = parseInt(document.getElementById('keyword').value, 10);

        xhttp.open("GET", configProxyUrl, true);
        xhttp.setRequestHeader("X-Proxy-Url", encodeURI(configShopifyUrl + configShopifyProductsUrl + '?handle=b' + handle + '&fields=id,variants'));
        xhttp.send();
}

function checkUPC() {
    if (isValidUpcCode(document.getElementById("keyword").value)) {
        document.getElementById("recommendation").innerHTML = 'Valid UPC Code';
    } else {
        var res = calculateUpcRes(document.getElementById("keyword").value);
        if (res > -1) {
            document.getElementById("keyword").value += res;
            document.getElementById("recommendation").innerHTML = 'Finalized UPC Code';
        } else {
            document.getElementById("recommendation").innerHTML = 'Invalid UPC Code';
        }
    }
}

    </script>

    <script src="js/chosen.jquery.min.js"></script>
    <script src="js/chosen.init.js"></script>

</body>
</html>