/**************************

author: Prince :)

**************************/
function tbMailingList() {
    window.open("http://tonerboss1.activehosted.com/form/html/1001", "subscription_form_popup", "toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=779,height=700,left=0,top=0");
}

var tbHoverTimer;
var testimonials = [
{
    'imgsrc': '\/v\/v5\/vspfiles\/templates\/Prince\/myimages\/onlinetradingacdmy.jpg',
    'text': 'Thank you TonerBoss for helping our company save money! We have numerous printers in our office so toner cost can quickly add up. However, your toner prices are considerably low compared to other companies and that\'s really helpful. Not only are your prices low but the quality of your products are great and so is the fast delivery.',
    'customer': '<b>EYAL SHACHAR</b><br />Operations Administrator<br />Online Trading Academy<br />'
},
{
    'imgsrc': '\/v\/v5\/vspfiles\/templates\/Prince\/myimages\/quantumrealtor.jpg',
    'text': 'We have been very happy with the quality of product and service from TonerBoss.  Whenever we have any issue it is handled immediately and very courteously.  I would very highly recommend Toner Boss to any business in need of their products.',
    'customer': '<b>Nita Hoyle</b><br />Quantum Realtors'
}
];

var featuredClients = [
'Arizona Animal Welfare League',
'Harding Academy',
'Hilton Garden',
'IBM',
'Lake Michigan College',
'Make-A-Wish Foundation',
'The Middeltown News',
'Monongalia Co Health Department',
'Nicholville Telephone Company',
'PsychHealth Ltd',
'RE\/MAX Equity Group',
'Sierra College',
'University Liggett School',
'University of Maryland',
'University of Massachusetts',
'University of Wisconsin-Madison',
'Volunteers of America',
'White River School District'
];

$.widget("custom.catcomplete", $.ui.autocomplete, {
    _renderMenu: function(ul, items) {
        var self = this,
        currentCategory = "";
        $.each(items, function(index, item) {
            if (item.category != currentCategory) {
                ul.append("<li class='ui-autocomplete-category'>" + item.category + "</li>");
                currentCategory = item.category;
            }
            self._renderItem(ul, item);
        });
    }
});
function hideHoverMenu(menuItem) {
    if (menuItem == "sub-") {
        return 0;
    }
    $("#" + menuItem.replace("sub-", "")).removeClass("left-nav-hover-on");
    $("#" + menuItem).hide();
    return 0;
}
$(document).ready(function() {
    catchAffCode();
    $("#nono-form-submit").click(function(){
        //alert($("#nono-Email").val());
        if ($("#nono-Email").val() != "Your Email") {
            window.open("/v/promosignup.asp?email=" + $("#nono-Email").val(), "subscription_form_popup", "toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=779,height=700,left=0,top=0");
        }
    });
    $("#nono-form input[type='text']").blur(function(){
        var valueText = this.id.replace("nono-","Your ");
        if ($(this).val() == "") {
            $(this).val(valueText);
        }
        ($(this).val() == valueText) ? $(this).addClass("nono-blurred") : $(this).removeClass("nono-blurred");
    });
    $("#nono-form input[type='text']").focus(function(){
        var valueText = this.id.replace("nono-","Your ");
        if ($(this).val() == valueText) {
            $(this).val("");
            $(this).removeClass("nono-blurred");
        }
    });
    //gemini req
    $("#hp-findbycart select").change(function(){
        if (this.value != "") {
            location.href = this.value;
        }
    })

    //cat page fix

    $("form[action='https://www.paypal.com/cgi-bin/webscr']").before("<div><b style='color:red'>Notice: </B>To ensure proper processing of your order, please click on the '<b>Return to Toner Cartridges</b>' link on Paypal after completing your payment.</div><br />");
    $("#tb-email-signup").click(tbMailingList);

    //testimonial
    var testiContent = "";
    var r = Math.floor(Math.random() * testimonials.length);
    var chosenTesti = testimonials[r];
    testiContent = "<table border='0'><tr>";
    testiContent += "<td width='35%' align='center'><img src=\"" + chosenTesti.imgsrc + "\" alt=\"Customer Logo\" /></td><td class='tb-testi-text'>";
    testiContent += "<p>" + chosenTesti.text + "</p>";
    testiContent += "<div>" + chosenTesti.customer + "</div></td></tr></table>";

    $("#tb-customer-testimonial").html(testiContent);

    //featured client
    r = Math.floor(Math.random() * featuredClients.length);
    var chosenClient = featuredClients[r];
    var featuredContent = "<img src='\/v\/vspfiles\/templates\/Prince\/myimages\/clients-" + chosenClient.replace(/[-|\s]/ig, '').toLowerCase() + ".gif' alt='" + chosenClient + "' />";
    featuredContent += "<p>" + chosenClient + "</p>";
    $("#tb-featured-clients-inner").html(featuredContent);
    
    //auto expand 1-2-3
    /*
    $("#tb-advanced-search-header").click(function() {
        $(this).next().slideToggle();
        $(this).toggleClass("advance-search-active");
    });
	$("#tb-advanced-search-header").click();
    */
    /*
    #### Temporarily disabled, 'no submenus' being implemented ###
    $("#tb-leftnav-menu a").hover(function() {
    $("#sub-" + this.id).show();
    $(this).addClass("left-nav-hover-on");

    }, function() {
    tbHoverTimer = setTimeout("hideHoverMenu('sub-" + this.id + "')", 10);

    });
    $(".hovermenu").hover(function() {
    clearTimeout(tbHoverTimer);
    $("#" + this.id.replace("sub-", "")).addClass("left-nav-hover-on");
    }, function() {
    hideHoverMenu(this.id);
    });
    */
    $(".SearchBoxForm").catcomplete({
        source: "/v/onsitesearch.asp",
        minLength: 3,
        delay: 100,
        select: function(event, ui) {
            if (ui.item.landingpage != "") {
                var jsurl = "http://api.tonerboss.com/referral.php?term=" + escape(ui.item.value) + "&url=" + escape(ui.item.landingpage);

                $.getJSON(jsurl, function(data) {
                    window.location.href = ui.item.landingpage;
                });

            //window.location.href = ui.item.landingpage;
            } else {
                //run search
                window.location.href = "/v/onsitesearch.asp?q=" + ui.item.value;
            }
        }
    });

    $(".oss-filter-by-brand").click(function() {
        var ot = ".out" + $(this).text();
        $(this).toggleClass("oss-filter-inactive");
        $(ot).each(function() {
            $(this).slideToggle(0);
        });
    });
    $("#oss-buttonset").buttonset();
    $("#oss-toggle-products").click(function() {
        $("#oss-products-ul").toggle("fast");
    });
    $("#oss-toggle-articles").click(function() {
        $("#oss-articles-ul").toggle("fast");
        document.getElementById("oss-articles-ul").scrollIntoView(true);
    });
    //add td - COMBO SAVING
    computeSavings();
    $(".colors_backgroundlight ~ tr").each(function() {
        //alert($(this).text());
        if ($(this).text().match("Check the items you wish to purchase")) {
            //alert("ok");
            var trtxt = "<tr><td align='right' colspan='" + $(".colors_backgroundlight > td").length + "' id='myComboDiscount'></td></tr>";
            $(this).before(trtxt);
            $(this).css("padding-top", "10px");
        }
    });

    $("#tb-email-form input[type='text']").blur(function() {
        if ($(this).val() == "") {
            $(this).val("your@email.here");
        }
        ($(this).val() == "your@email.here") ? $(this).addClass("text-blurred") : $(this).removeClass("text-blurred");
    });
    $("#tb-email-form input[type='text']").focus(function() {

        if ($(this).val() == "your@email.here") {
            $(this).val("");
            $(this).removeClass("text-blurred")
        }
    });

    //combo events

    $("input[name^='QTY']").keyup(computeSavings);
    $("input[name='ProductCode']").click(computeSavings);

    $("#sbp_form > select").change(function() {
        sbpHandler2(this);
    });
    $("#sbp-manufacturer").selectOptions("").change();
    UPSFix();

});
function SBPResultListMakes(brand) {

    $.get('/v/psearchapi.asp?manufacturer=' + brand + "&r=" + Math.random(), function(data) {
        $("#SBPResultAjax").html(headerDataFormatter(data, brand, 1));
    });
}
function headerDataFormatter(rawData, brand, style) {
    //**********************************
    //configuration
    //**********************************
    //lval = leftvalue
    var searchPageURL = "/v/psearch.asp";
    var tempDescription = "<h1>" + brand + " Compatible Cartridges</h1>";
    //Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum. Typi non habent claritatem insitam; est usus legentis in iis qui facit eorum claritatem. Investigationes demonstraverunt lectores legere me lius quod ii legunt saepius. Claritas est etiam processus dynamicus, qui sequitur mutationem consuetudium lectorum. Mirum est notare quam littera gothica, quam nunc putamus parum claram, anteposuerit litterarum formas humanitatis per seacula quarta decima et quinta decima. Eodem modo typi, qui nunc nobis videntur parum clari, fiant sollemnes in futurum."

    var objHotMakes = new Object;
    objHotMakes['HPColor LaserJet'] = true; //format brand+make (nospace)
    objHotMakes['HPLaserJet'] = true;


    var objDesc = new Object;
    objDesc['Brother'] = "Tonerboss' Brother compatible cartridges are guaranteed to have premium quality. Get premium compatible inks and toners for your Brother printers at the best values. Why pay more for OEM cartridges if you can get the same quality for a cheaper price with Brother compatible cartridges from Tonerboss? We guarantee that our printer cartridges can give you the same quality prints as their genuine brand counterparts.";
    objDesc['Canon'] = "Tonerboss' Canon compatible cartridges are guaranteed to have premium quality. Get premium compatible inks and toners for your Canon printers at bargain prices. Why pay more for OEM cartridges if you can get the same quality for a cheaper price with Canon compatible cartridges from Tonerboss? Each Tonerboss product guarantees that you will get the same quality prints that you get from genuine brand cartdridges.";
    objDesc['Dell'] = "Tonerboss offers only top quality compatible inks and toners for your Dell printers. Get premium quality printer cartridges at lower prices. Why buy more expensive original cartridges if you can get the same quality with Dell compatible inks and toners from Tonerboss? Only Tonerboss can guarantee to give you the same quality prints as you get from OEM brand cartridges.";
    objDesc['Epson'] = "Tonerboss offers reliable and premium quality Epson compatible printer cartridges. No need to shell out your precious cash for more expensive OEM cartridges. At Tonerboss, we provide high quality products without the hefty price tags. What's more, Tonerboss products give the same quality prints as genuine brand cartridges. Try our Epson compatible printer cartridges and see for yourself.";
    objDesc['Konica-Minolta'] = "Tonerboss' Konica-Minolta printer cartridges are guaranteed to have premium quality. Get the same quality prints at a fraction of the price that you'll pay for OEM cartridges. Try our Konica-Minolta compatible inks and toners today and experience fine quality that's not heavy on your pockets. ";
    objDesc['HP'] = "Tonerboss offers a wide range of HP compatible ink and toner cartridges. Name your HP printer model and surely, there's a Tonerboss compatible printer cartridge for you. The Tonerboss brand speaks of top quality and low price so you can expect our compatible inks and toners to give you the same quality prints at only a fraction of OEM price.";
    objDesc['Lexmark'] = "Tonerboss' Lexmark compatible cartridges are manufactured and quality tested so you can expect only premium quality. Get the best value from top quality compatible inks and toners for your Lexmark printers. Why pay more for OEM cartridges if you can get the same quality for a cheaper price with Lexmark compatible cartridges from Tonerboss? We guarantee that our printer cartridges can give you the same quality prints as their genuine brand counterparts.";
    objDesc['Okidata'] = "Tonerboss' Okidata printer cartridges are guaranteed to have premium quality. Each cartridge has been quality tested to ensure same quality prints at a fraction of the price that you'll pay for OEM cartridges. Try our Okidata compatible inks and toners today and experience reliable quality that's not heavy on your pocket. ";
    objDesc['Panasonic'] = "Tonerboss' Panasonic compatible printer cartridges are guaranteed to have high quality at very affordable prices. Now, you can enjoy crisp and quality prints without the hefty price tag. So what are you waiting for? Try Panasonic compatible inks and toners from Tonerboss today.";
    objDesc['Samsung'] = "Tonerboss offers Samsung compatible ink and toner cartridges. Each cartridge has been manufactured and quality tested. Our customers attest that there's hardly any difference between our Samsung compatible cartridges and OEM cartridges in terms of print and color quality. Best of all, Tonerboss' Samsung compatible inks and toners give you as much as 60% to 70% savings.";
    objDesc['Sharp'] = "Tonerboss offers top-quality Sharp compatible cartridges. Manufactured and quality-tested, our products are ensured to meet standards and to give you quality prints similar to what you can get from OEM cartrdiges. Our Sharp compatible inks and toners are cheaper so you can get brand new quality at bargain prices.";
    objDesc['Xerox'] = "Tonerboss offers a wide array of compatible cartridges for Xerox copiers and printers. Get the best value and great quality only from Tonerboss. Our compatible cartridges are guaranteed to give you the same quality as you get from OEM cartridges. The only difference is on the price tag: our Xerox compatible cartridges can save you as much as 60% compared to OEMs.";

    tempDescription += (objDesc[brand] != undefined ? objDesc[brand] : "Product description coming soon!");

    var lval = "<table cellspacing='0' cellpadding='0' border='0' style=\"border-collapse: collapse; width: 400px;\">";
    lval += "<tr><td><img src=\"/v/vspfiles/templates/Prince/myimages/images/header-" + brand + ".png\" alt=\"" + brand + " Compatible Cartridges\" width=\"400\" height=\"100\" /></td></tr>";
    lval += "<tr><td>" + tempDescription + "</td></tr>";
    lval += "</table>";

    
    //rval = right value
    var rval = "<form><table id='modelTable' cellspacing='0' cellpadding='0' border='1' style=\"border-collapse: collapse; width: 400px;\">";
    rval += "<col style=\"width: 180px;\" />";
    //rval += "<col style=\"width: 100px;\" />";
    var lines = rawData.split("\n");
    var line, i;
    var oddLine = false;
    for (i = 0; i <= lines.length - 1; i++) {
        line = lines[i].replace("\n", "").replace("\r", "");
        if (line == "") { /* blank line, skip quietely */ }
        else { //process
            var make = line.split(",")[0];
            var modelArray = line.split(",")[1].split("$");
            modelArray.sort();
            var classStr = "oddLine";
            rval += "<tr" + (oddLine == true ? " class='" + classStr + "'" : "") + " style='height: 20px;'>";
            oddLine = !oddLine;
            rval += "<td class='" + (objHotMakes[brand + make] != undefined ? "hotMake " : "") + "mtMakeName" + "'>" + make + "</td>";
            rval += "<td><select onchange=\"tbSBPNavigate(this.value);\">";
            //list models in a select
            var j;

            rval += "<option value=\"null\">- - - Please Choose - - - </option>";
            for (j = 0; j <= modelArray.length - 1; j++) {
                rval += "<option value='" + searchPageURL + "?manufacturer=" + brand + "&make=" + escape(make) + "&model=" + escape(modelArray[j]) + "'>" + modelArray[j] + "</option>";
            }
            rval += "</select><td>";
            rval += "</tr>";
        }
    }
    rval += "</table></form>"
    if (style == 1) {
        //return "<table class='SBPListingTable' style='width: 820px; margin: 0 auto; padding: 10px;'><tr><td valign='top'>" + lval + "</td><td valign='top'><h1>Choose your model:</h1>" + rval + "</td></tr></table>";
        return rval;
    }
    //return "<table class='SBPListingTable' style='width: 820px; margin: 0 auto; padding: 10px; border-left: 2px solid #DDD;border-right: 2px solid #DDD; background: white;'><tr><td valign='top'>" + lval + "</td><td valign='top'><img src='/v/vspfiles/templates/Prince/myimages/images/exit.png' onclick=\"tbNavigate('brand" + brand + "');\" alt='Close' title='Click to close' id='exitImage' height='20' width='54' /><h1>Choose your model:</h1>" + rval + "</td></tr></table>";
    return rval;
}

function tbSBPNavigate(q) {
    if (q == "null") {
        return 0;
    }
    location.href = q;
}
function launchLiveChat() {
    window.open('https://livechat09.volusion.com/livechat.aspx?ID=385625&location=' + escape(location.href) + '&auto=0&cookieGuid=y4myuqra2xoyivq5fkupk02x&DeptID=&Agent=&tType=', 'mailingList', 'width=590,height=400,location=0');
}
function searchString(arrayToSearch, stringToSearch) {
    arrayToSearch.sort();

    for (var i = 0; i < arrayToSearch.length; i++) {

        if (arrayToSearch[i] == stringToSearch)
            return true;
    }
    return false;
}
function UPSFix() {
    var defOpt = 1;
    var sel = document.getElementById("ShippingSpeedChoiceCarriers");

    if (!sel) { //no ups selction, maybe address is visible?
        var country = document.getElementById("ShipCountry");
        if (!country) {
            return 0;
        }
        //country.setAttribute("disabled", true);
        //var ht = $(country).parents("tr").html();
        //$(country).parents("tr").html("<span style='visibility:hidden;'>"+ht+"</span>");
        //alert(ht);
        return 0;
    }
    var sel2 = document.getElementsByName("ShippingSpeedChoice1")[0];

    if (sel2) {
        if (sel2.innerHTML.indexOf("Free Shipping (7 Day Ground") > 0) {
            defOpt = 0;
        }
    }

    sel.options[defOpt].selected = true;
    sel.onchange();
}
var objSBPModels = new Object();

function sbpHandler(objSel) {
    if ("sbp-manufacturer" == objSel.id) { //************************* MANUFACTURER 
        //manufacturer, list makes, models
        var manu = $(objSel).selectedValues();
        if (manu == "") { //blank, reset fields
            $("#sbp-make").removeOption(/./);
            var tmpOpt = {
                "": "Step 2: Choose Series"
            };
            $("#sbp-make").attr('disabled', true).addOption(tmpOpt, true);

            $("#sbp-model").removeOption(/./);
            var tmpOpt = {
                "": "Step 3: Choose Model"
            };
            $("#sbp-model").attr('disabled', true).addOption(tmpOpt, true);
        }
        else {
            //populate data
            objSBPModels = null;
            objSBPModels = new Object();

            $.get('/v/psearchapi.asp?manufacturer=' + manu + "&r=" + Math.random(), function(data) {
                //alert(data);
                var lines = data.split("\n");
                var i;
                var line = "";
                for (i = 0; i <= lines.length - 1; i++) {

                    line = lines[i].replace("\n", "").replace("\r", "");

                    if (line.length > 1) {
                        var make = line.split(",")[0];
                        var modelArray = line.split(",")[1].split("$");
                        modelArray.sort();
                        //alert(make);
                        objSBPModels[make] = modelArray; //fill object for use with [make] = models
                    }
                }
                //populate Makes
                $("#sbp-make").removeOption(/./);
                var tmpOpt = {
                    "": "Step 2: Choose Series"
                };
                $("#sbp-make").attr('disabled', false).addOption(tmpOpt, true);
                var objOptions = new Object();
                for (x in objSBPModels) {
                    objOptions[x] = x;
                }
                $("#sbp-make").addOption(objOptions).selectOptions("");
            });


        }
    }
    if ("sbp-make" == objSel.id) {
        var make = $(objSel).selectedValues();
        if (make == "") {
            //blank selection, reset models
            $("#sbp-model").removeOption(/./);
            var tmpOpt = {
                "": "Step 3: Choose Model"
            };
            $("#sbp-model").attr('disabled', true).addOption(tmpOpt, true);
        } else {
            if (!objSBPModels) {
                'error '

            } else {
                $("#sbp-model").removeOption(/./);
                var tmpOpt = {
                    "": "Step 3: Choose Model"
                };
                $("#sbp-model").attr('disabled', false).addOption(tmpOpt, true);
                var i;
                var objOptions = new Object();
                for (i = 0; i <= objSBPModels[make].length - 1; i++) {
                    objOptions[objSBPModels[make][i]] = objSBPModels[make][i];
                }
                $("#sbp-model").addOption(objOptions).selectOptions("");
            }
        }
    }
}
function doStepSearch() {
    var manu = $("#sbp-manufacturer").selectedValues();
    var make = $("#sbp-make").selectedValues();
    var model = $("#sbp-model").selectedValues();

    if (manu == "") {
        alert("Please Complete the information before proceeding.");
        return 0;
    }
    if (make == "") {
        alert("Please Complete the information before proceeding.");
        return 0;
    }
    if (model == "") {
        alert("Please Complete the information before proceeding.");
        return 0;
    }

    var searchPageURL = "/v/psearch.asp?manufacturer=" + manu + "&make=" + escape(make) + "&model=" + escape(model);

    tbSBPNavigate(searchPageURL);

}
function emailContact() {
    window.open('/v/contact.html', 'Email Tonerboss', 'top=10,left=10,menubar=0,resizable=0,scrollbars=1,width=470,height=500')
}
function isPhoneNumber(str){
    var re = /^\(?[2-9]\d{2}[\)\.-]?\s?\d{3}[\s\.-]?\d{4}$/
    return re.test(str);
}
function showMailinglist(){
    window.open('https://secure.campaigner.com/Campaigner/Public/Form10.aspx?fid=86750','mailingList','width=590,height=700,location=0');
}

function trim(str, chars) {
    return ltrim(rtrim(str, chars), chars);
}

function ltrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function rtrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

var SavingsArray = new Array();
function computeSavings(){
    //populate values
    $("input[name^='QTY']").each(function(i){
        var str = "";
        var tdObj = $(this).parent("td");
        str += tdObj.prev().text();
        str = trim(str.replace("$","").replace(" ",""));
        var SavingsObj = new Object();
        SavingsObj['valid'] = $(tdObj).next().find("input").is(':checked');
        SavingsObj['qty'] = parseInt($(this).val());
        SavingsObj['value'] = parseFloat(str) * parseInt($(this).val());
        SavingsArray[i] = SavingsObj;
    });



    var htmlTxt = "";
    var totalprice = 0;
    var totalqty = 0;


    var i = 0;
    for (i = 0;i<= SavingsArray.length - 1;i++){
        if (SavingsArray[i]['valid']) {
            totalqty += SavingsArray[i]['qty'];
            totalprice += SavingsArray[i]['value'];
        }
    }
    var qtytxt = "";

    if (totalqty < 4) {
        qtytxt =  "<span style='color: red'>" +  totalqty + "</span>";
    }
    else {
        qtytxt =  "<span style='color: green'>" +  totalqty + "</span>";
    }

    htmlTxt = "<span style='font-size: 14px'>Total Number of Cartridges: " + qtytxt + "<br />";
    htmlTxt += "Total Amount: $" + totalprice.toFixed(2) + "<br />";
    if (totalqty > 3) {
        htmlTxt += "<hr /><b>Combo Price: $" + (totalprice * .85).toFixed(2) + "<br /><span  style='color: #0A0;'>$" + (totalprice * .15).toFixed(2) + " INSTANT SAVINGS!</span></b>" ;
    }

    $('#myComboDiscount').html(htmlTxt + "</span>");
}
function isPhoneNumber(str) {
    var re = /^\(?[2-9]\d{2}[\)\.-]?\s?\d{3}[\s\.-]?\d{4}$/
    return re.test(str);
}
function showMailinglist() {
    window.open('https://secure.campaigner.com/Campaigner/Public/Form10.aspx?fid=86750', 'mailingList', 'width=590,height=700,location=0');
}

function hp_fbc_load(){
    $("#hp-findbycart select").attr('disabled','disabled');
    $.getJSON("/v/gulejson.asp",function(data){
        
        for (x in data){
            
            if (data[x].oempart != ""){
                //alert(data[x].oempart);
                $("#hp-fbc-2").addOption("/HP-Cartridges-p/" + data[x].productcode + ".htm",data[x].oempart + "(" + data[x].type + ")");
            }
        }
        $("#hp-fbc-2").selectOptions("").removeAttr('disabled');
        $("#hp-fbc-2-load").css('display','none');
    });
    var brand = 'HP';
    $.get('/v/psearchapi.asp?manufacturer=' + brand, function(data) {
        var nSplit = data.split("\n");
        for (x in nSplit){
            if (nSplit[x].split(",").length > 1){
                var make = nSplit[x].split(",")[0];
                var mods = nSplit[x].split(",")[1].split("$");
                for (m in mods){
                    //alert("m: " + mods[m]);
                    $("#hp-fbc-1").addOption("/v/psearch.asp?manufacturer=" + brand + "&make=" + escape(make) + "&model=" + escape(mods[m]), mods[m]);
                }
            }
        }
        $("#hp-fbc-1").selectOptions("").removeAttr('disabled');
        $("#hp-fbc-1-load").css('display','none');
    });
}
var objSBPmods = [];
function sbpHandler2(element){

    if ((element.id == "sbp-manufacturer") && (element.value != "")) {
        $("#sbp-make-load").css('visibility','visible');
        $("#sbp-make").attr('disabled','disabled');
        $("#sbp-model").attr('disabled','disabled').selectOptions("");
        $.get('/v/psearchapi2.asp?manufacturer=' + element.value, function(data) {
            objSBPmods = eval(data);
            applyMakeData();
        });
    }
    if ((element.id == "sbp-make") && (element.value != "")) {
        $("#sbp-model-load").css('visibility','visible');
        $("#sbp-model").attr('disabled','disabled');
        applyModelData(element.value);
    }
    if ((element.id == "sbp-model") && (element.value != "")) {
        doStepSearch();
    }

}
function applyMakeData(){
    //prep the select
    $("#sbp-make").removeOption(/./).addOption("","Please Choose Series");
    for (x in objSBPmods){
        //objOptions[x] = objSBPmods[x].make;
        $("#sbp-make").addOption(objSBPmods[x].make,objSBPmods[x].make);
    }
    $("#sbp-make").selectOptions("");
    $("#sbp-make-load").css('visibility','hidden');
    $("#sbp-make").removeAttr('disabled').focus();
}
function applyModelData(make){
    $("#sbp-model").removeOption(/./).addOption("","Please Choose Model");
    for (x in objSBPmods){
        //objOptions[x] = objSBPmods[x].make;
        if (objSBPmods[x].make == make) {
            var modsz = objSBPmods[x].models.split(",");
            for (m in modsz){
                $("#sbp-model").addOption(modsz[m],modsz[m]);
            }
        }

    }
    $("#sbp-model").selectOptions("");
    $("#sbp-model-load").css('visibility','hidden');
    $("#sbp-model").removeAttr('disabled').focus();

}
function catchAffCode(){
    if ($.deparam.querystring(true).affcode != undefined){
        $.cookie("affsource",$.deparam.querystring(true).affcode,{
            path:'/',
            expires:45
        });
    }
//todo: remove  cookie after rendering pixel
}
function drawAffcode(){
    if ($.cookie("affsource") != undefined) {
        if ($.cookie("affsource") != "") {
            //alert("got here!");
            var aff = $.cookie("affsource").toLowerCase();

            var hblock = "";
            switch(aff){
                case "pjx":
                   hblock = "<iframe src=\"https://t.pepperjamnetwork.com/track?PID=3576&AMOUNT=" + Order[2] + "&TYPE=1&OID=" + Order[0] + "&CURRENCY=USD\" height=\"1\" width=\"1\" frameborder=\"0\"></iframe>";
                   break;
                case "pj":
                   //hblock = "<iframe src=\"https://t.pepperjamnetwork.com/track?PID=3576&AMOUNT=" + Order[2] + "&TYPE=1&OID=" + Order[0] + "&CURRENCY=USD\" height=\"1\" width=\"1\" frameborder=\"0\"></iframe>";

                   hblock = "<iframe src=\"https://t.pepperjamnetwork.com/track?PID=5741&INT=ITEMIZED&OID=" + Order[0];

                   var items = "",qtys = "",amts = "",counter = 1;
                    for (x in OrderDetails){

                        if (OrderDetails[x][2].match(/^DSC/i)){ //matches Discount
                            //skip discounts
                        }
                        else { //not disc, must be product

                            items += "&ITEM" + counter + "=" + OrderDetails[x][2];
                            amts += "&AMOUNT" + counter + "=" + OrderDetails[x][5];
                            qtys += "&QTY" + counter + "=" + OrderDetails[x][6];
                            counter += 1;

                        }
                    }
                    hblock += items + qtys + amts;

                    //close hblock
                    hblock += "\" width=\"1\" height=\"1\" frameborder=\"0\"></iframe> "

                    break;
                case "sas":
                    hblock = "<img src=\"https://shareasale.com/sale.cfm?amount=" + Order[2] + "&tracking=" + Order[0] + "&transtype=SALE&merchantID=29450\" width=\"1\" height=\"1\">";
                    break;
                case "cj":

                    hblock = "<img src=\"https://www.emjcd.com/u?CID=1519652&TYPE=341624&METHOD=IMG&CURRENCY=USD&OID=" + Order[0];

                    var disc,params,counter;
                    
                    disc = 0.0;
                    counter = 1;
                    for (x in OrderDetails){
                        
                        if (OrderDetails[x][2].match(/^DSC/i)){ //matches Discount
                            disc += Math.abs(parseFloat(OrderDetails[x][5]));
                        }
                        else { //not disc, must be product
                            params = "";
                            params += "&ITEM" + counter + "=" + OrderDetails[x][2];
                            params += "&AMT" + counter + "=" + OrderDetails[x][5];
                            params += "&QTY" + counter + "=" + OrderDetails[x][6];
                            counter += 1;
                            hblock += params;
                        }
                    }
                    if (disc > 0){
                        hblock += "&DISCOUNT=" + disc;
                    }
                    hblock += "\" height=\"1\" width=\"20\" alt=\"blank\" />"

                    break;
            }
            if (hblock != ""){
                //alert("Debug <output>: " + hblock);
                //document.write("<!-- hblock -->" + hblock);
                document.write(hblock);
                if (aff == "pjx") {
                    //alert('PJ test detected. Appending element to source:\n\n'+hblock);
                }
                $.cookie("affsource","");
            }
        }
    }
}
function mcCheckOrderStatus(){
    var orderID = "";
    orderID = $("#stat-ordernumber").val();
    var zip = $("#stat-zip").val();
    $("#stat-results").hide("fast");
    if (orderID != "") {
        if (zip == "") {
            alert("Please fill out all the fields");
            return 0;
        }

        $.ajax({
            url: '/v/orderstat.asp?id='+orderID+"&zip="+zip+"&rand="+Math.random(),
            type: "GET",
            dataType: 'xml',
            success: function(res){
                var m = "";

               var s = $(res).find("result").text();

               if (s == "success") {
                   m = $(res).find("stat").text();
               } else {
                   m = "Sorry but the information submitted seems invalid.";
               }

               $("#stat-results").html(m).show("slow");
               }

        });
    }
    return 0;
}
function showRMAForm() {
    window.open("http://api.tonerboss.com/tbrmaform.html", "rma_form", "toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=779,height=700,left=0,top=0");
}
function testPJPixel(){
    $.cookie("affsource","pjx",{
            path:'/',
            expires:1
        });
    //alert('Test Cookie Successfully baked! Proceed with order');
}
