/**
 * @author Prince
 */
var d;
var tree;
//selTest();

$(document).ready(function() {
    //selTest(); 
$("table.colors_lines_light").css({"margin":"10px 0 10px 0","border":"2px solid #bbb","padding":"10px"}).insertBefore($("#Header_ProductDetail_ProductDetails_span").parents("table")[0]);

    writeExtDesc();
    UPSFix();
    $("#ctejqslider").nivoSlider({
        effect: 'fold',
        animSpeed:500,
        pauseTime:4000,
        pauseOnHover: false,
        controlNav: false,
        directionNav: false
    });
    $("#myWelcome").parents("td").find("br").each(function() {
        $(this).remove();
    });
    /*
	if (jQuery.browser.msie) { 
		$("img[src$='guest.gif']").css({ "text-align": "right" });
		$("input[src$='guest.gif']").css({ "text-align": "right" });
	}
	else {
	    $("img[src$='guest.gif']").css({ "position": "relative", "left": "355px" });
	    $("input[src$='guest.gif']").css({ "position": "relative", "left": "330px" });
	}
	if ($("#princemarker").length > 0){
		//var o = $("#princemarker").offset();
		$("#footnotesprince").css("display","block");
		var o = document.getElementById("footnotesprince");
		alert(getY(o));
		//$("#footnotesprince").offset(o).css("display","block");
		//alert(jQuery.uaMatch(navigator.userAgent).browser + " l: " + o.left + " t: " + o.top);
	}
*/
    $(".colors_productprice:contains('Our Price')").css('color','green');
    $("#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");
        }
    });
    if ($("#princemarker").length > 0){
        //var o = $("#princemarker").offset();
        //var o = getY(document.getElementById("footnotesprince"));
        //var n = getY(document.getElementById("princemarker"));
        var o = $("#footnotesprince").offset();
        var n = $("#princemarker").offset();
        //var d = o.top - n.top;
        //alert("O: " + o.top + "\nN: " + n.top + "\nDiff: " + d);
        var of = $("#footnotesprince").offset();
        //of.top = o.top - d;
        var d = 1240;
        if (jQuery.browser.msie && parseFloat(jQuery.browser.version.substr(0,3)) < 8) {
            d = 1310;
        }
        of.top = o.top - d;
        of.left += 175;
        $("#footnotesprince").offset(of);
    //$("#footnotesprince").offset(o).css("display","block");
    //alert(jQuery.uaMatch(navigator.userAgent).browser + " l: " + o.left + " t: " + o.top);
    } else {
        $("#footnotesprince").css("display","none");
    }

    /*
$("form[name='OnePageCheckoutForm'] table").css("border-collapse","collapse");
$("input[name='BillingPhoneNumber']").parents("tr").each(function(i){ if (i == 0){ $(this).css({ 'background':'#EFEFEF','height':'40px' }); } });
$("input[name='BillingFaxNumber']").parents("tr").each(function(i){ if (i == 0){ $(this).css({ 'background':'#EFEFEF','height':'40px' }); } });
$("input[name='Email']").parents("tr").each(function(i){ if (i == 0){ $(this).css({ 'background':'#EFEFEF','height':'40px' }); } });
$("input[name='BillingPostalCode']").parents("tr").each(function(i){ if (i == 0){ $(this).css({ 'height':'40px' }); $(this).attr("valign","top"); } });
*/
    $("input[name='emailsubscriber']").parents("td").each(function(i){
        if (i == 0){
            $(this).attr("valign","top").next().html("<b>Send me ColorTonerExpert&rsquo;s email updates featuring:</b><ul><li>Exclusive Offers</li><li>Special Discounts</li><li>Contest announcements and more!</li></ul>");
        }
    });
$("input[name='passwordagain']").after("<div style='font-size: smaller;color: gray'>Your password must be 8-20 alpha-numeric characters</div>");


    $("span.cteSalePriceName").each(function() {
        $(this).before("<br />");
        var x = $(this).parents("font").html();
        var l = x.split(" ").length - 2;
        var spantxt = "<span class='cteSalePriceAmount'>" + x.split(" ")[l] + "</span>";
        $(this).parents("font").html(x.replace(x.split(" ")[l], spantxt));
    });
    $(".newNavMenu h3").click(function() {

        $(this).next().slideToggle("slow");
    });
    $("img[src$='register.gif']").after("<div style='color: #555; margin: 10px;'>Registration is <em>OPTIONAL</em>. Fill out the password field below if you wish to associate your email address with an account.</div>");
    detectCoupon();
    $.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);
            });
        }
    });
    $(".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);
    });
/*
    if (typeof SearchParams != 'undefined'){
        var re = new RegExp("cat=(\\d+)");
        var m = re.exec(SearchParams);
        if (m == null) {
        //alert("No match");
        } else {
            var id= m[1];
            var t = getProductTree(id);
            tree = t.split(",");
        }

    }
*/
    //bind change handlers for stepsearch
    $("#mc-steps select").change(function(){
        
        stepHandler(this);
    });

});
var lcTimerID;
var ns4;
var poAdded = false;
function getIEVersionNumber(){
    var ua = navigator.userAgent;
    var MSIEOffset = ua.indexOf("MSIE ");
    
    if (MSIEOffset == -1) {
        return 0;
    }
    else {
        return parseFloat(ua.substring(MSIEOffset + 5, ua.indexOf(";", MSIEOffset)));
    }
}

function toggleMenu(id, show,parentID){
    var aID = id + "A";
    if (!parentID) {
        parentID = aID;
    }
    var top =  getY(document.getElementById(parentID)) ;
    var left = getX(document.getElementById(parentID)) + 5;
	
   
    
    if (!navigator.userAgent.toLowerCase().match("firefox")) { // if its not
        // fire fox
        // check ie version
        if (navigator.appName == "Microsoft Internet Explorer") {
            if (getIEVersionNumber() < 8) {
        // left += 5;
	           
        }
        } else { // no ie
    // left += 5;
    }
    }
    
    var whichDiv = document.getElementById(id);
    
    // define display type
    var myshow = show == 'show' ? 'block' : 'none';
    
    // define class to be applied to calling <a> tag
    // a tag mustbe in the form mnu<brand>A
    var myclass = show == 'show' ? 'hoverActiveA' : 'hoverInactiveA';
    
    document.getElementById(aID).className = myclass;
    

    
    // var divArray = new Array("mnuBrowse", "mnuBrother", "mnuCanon",
    // "mnuDell", "mnuEpson", "mnuKonica", "mnuHP", "mnuLexmark", "mnuOkidata",
    // "mnuPanasonic", "mnuSamsung", "mnuSharp", "mnuXerox");
    var divArray = new Array("mnuBrother", "mnuCanon", "mnuDell", "mnuEpson","mnuKonica", "mnuHP", "mnuLexmark", "mnuOkidata", "mnuPanasonic", "mnuSamsung", "mnuSharp", "mnuXerox", "mnuNEC", "mnuRicoh", "mnuKyocera");
    // var timeOut = show == 'hide' ? 0 : 4000;
    var i;
    for (i = 0; i <= divArray.length - 1; i++) {
        var tmpDiv = document.getElementById(divArray[i]);
        if (divArray[i] == id) {
            tmpDiv.style.display = myshow;
            tmpDiv.style.top = top + "px";
            tmpDiv.style.left = left + 160  + "px";
        }
        else {
            tmpDiv.style.display = 'none';
        }
    }
    
}

function pHide(whichDiv){
    document.getElementById(whichDiv).style.display = 'none';
}

function getY(oElement){
    var iReturnValue = 0;
    while (oElement != null) {
        iReturnValue += oElement.offsetTop;
        oElement = oElement.offsetParent;
    }
    return iReturnValue;
}
function getX(oElement){
    var iReturnValue = 0;
    while (oElement != null) {
        iReturnValue += oElement.offsetLeft;
        oElement = oElement.offsetParent;
    }
    return iReturnValue;
}

// ***************************************
// * AJAX SEGMENT *
// ***************************************
var xmlhttp;

function GetXmlHttpObject(){
    if (window.XMLHttpRequest){
        // code for IE7+, Firefox, Chrome, Opera, Safari
        return new XMLHttpRequest();
    }
    if (window.ActiveXObject){
        // code for IE6, IE5
        return new ActiveXObject("Microsoft.XMLHTTP");
    }
    return null;
}
function selChangeManager(sid) {
    var value = document.getElementById(sid).value;
	
    if (sid == "selManufacturer"){ // for the manufacturer selection
        if (value == "null"){
            return 0;
        } else {
            window.location.href = "/v/printersearch.asp?manufacturer=" + value;
        }
		
    }
}
function selNavigate(where){
    if (where == "null") {
        return 0;
    }
    window.location.href = where;
}
function sbplSubmit(){
    

    // sanity check

    var val,err;

    val = document.getElementById("sbplSelManufacturer");

    if ((val.value == "") || (val.value == "default")) {
        alert("Please Select Manufacturer");
        val.focus();
        return false;
    }
    val = document.getElementById("sbplSelMake");

    if ((val.value == "") || (val.value == "default")) {
        alert("Please Select Make");
        val.focus();
        return false;
    }
    val = document.getElementById("sbplSelModel");

    if ((val.value == "") || (val.value == "default")) {
        alert("Please Select Model");
        val.focus();
        return false;
    }
	
}
var sbplRequest;
function sbplManufacturer(manu) {
    sbplRequest = "manu";
    if (manu == "default") {
    // no go
    } else if (trim(manu) != "") {
        xmlhttp = GetXmlHttpObject();
        if (xmlhttp == null) {
            alert("Browser does not support HTTP Request");
            return;
        }
        // var url = "http://localhost/v/jaxer2.asp?sid=" + Math.random();
        // url = url + "q=manu&p=" + manu;
        var img = document.getElementById("imgAjaxMake");

        img.className = "mspanOn";
        var url = "/v/jaxer2.asp?q=manu&p=" + manu + "&sid=" + Math.random();
        xmlhttp.onreadystatechange = changeStateHandler;
        xmlhttp.open("GET", url, true);
        xmlhttp.send(null);
    }
	
}
function sbplMake(make){
    sbplRequest = "make";
    if (manu == "default") {
    // no go
    } else if (trim(make) != "") {

        xmlhttp = GetXmlHttpObject();
        if (xmlhttp == null) {
            alert("Browser does not support HTTP Request");
            return;
        }
        // var url = "http://localhost/v/jaxer2.asp?sid=" + Math.random();
        // url = url + "q=manu&p=" + manu;
        var img = document.getElementById("imgAjaxModel");

        img.className = "mspanOn";

        var manu = document.getElementById("sbplSelManufacturer").value;
        var url = "/v/jaxer2.asp?q=make&p=" + manu + "&r=" + make + "&sid=" + Math.random();

        xmlhttp.onreadystatechange = changeStateHandler;
        xmlhttp.open("GET", url, true);
        xmlhttp.send(null);
    }
}
function changeStateHandler() {
    // alert(xmlhttp.readyState + ":" + xmlhttp.responseText);
    if (xmlhttp.readyState == 4) { // parse reply
        var targetSel;
        var targetImg;
        if (sbplRequest == "manu") {
            targetSel = "sbplSelMake";
            targetImg = "imgAjaxMake";
        } else if (sbplRequest = "make") {
            targetSel = "sbplSelModel";
            targetImg = "imgAjaxModel";
        }
        var arrRes,rsp;
        rsp = xmlhttp.responseText;
        // alert("r: " + rsp);
        arrRes = rsp.split("$");
        // alert("len: " + arrRes.length);

        var sel;
        sel = document.getElementById(targetSel);
        sel.options.length = 0;
        sel.disabled = false;
        var opt;

        opt = document.createElement("option");
        opt.text = "Please Choose";
        opt.value = "default";
   
        try {
            sel.add(opt, null);
        } catch (e) {
            sel.add(opt);
        }

        var img;
        var img = document.getElementById(targetImg);

            
        for (i = 0; i < arrRes.length; i++) {
            var tt = arrRes[i];

            if (trim(tt) != "") {
                opt = document.createElement("option");
                opt.text = tt.replace("(DCP Series)","");
                opt.value = tt;
                try {
                    sel.add(opt, null);
                } catch (e) {
                    sel.add(opt);
                }
            }

        }
        img.className = "mspanOff";
    }
}
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"), "");
}
function princeTest(){
    var opt = document.getElementsByName("PaymentMethodType")[0];
    if (!opt) {
        return 0;
    } //sanity check
    if (poAdded) {
        alert('Option Already Displayed');
        return 0;
    }
    var elOptNew = document.createElement('option');
    elOptNew.text = 'Purchase Order Number';
    elOptNew.value = 'Purchase Order Number';
    var elSel =  document.getElementsByName("PaymentMethodType")[0];

    try {
        elSel.add(elOptNew, null); // standards compliant; doesn't work in IE
    }
    catch(ex) {
        elSel.add(elOptNew); // IE only
    }
    alert("PO Option Added!");
    poAdded = true;
    return false;
}
function removeOptionLast()	{

    var elSel = document.getElementsByName("PaymentMethodType")[0];
    if (!elSel) {
        return 0;
    } //sanity check
    elSel.remove(3);

}

/**
 * http://www.openjs.com/scripts/events/keyboard_shortcuts/
 * Version : 2.01.B
 * By Binny V A
 * License : BSD
 */
shortcut = {
    'all_shortcuts':{},//All the shortcuts are stored in this array
    'add': function(shortcut_combination,callback,opt) {
        //Provide a set of default options
        var default_options = {
            'type':'keydown',
            'propagate':false,
            'disable_in_input':false,
            'target':document,
            'keycode':false
        }
        if(!opt) opt = default_options;
        else {
            for(var dfo in default_options) {
                if(typeof opt[dfo] == 'undefined') opt[dfo] = default_options[dfo];
            }
        }

        var ele = opt.target;
        if(typeof opt.target == 'string') ele = document.getElementById(opt.target);
        var ths = this;
        shortcut_combination = shortcut_combination.toLowerCase();

        //The function to be called at keypress
        var func = function(e) {
            e = e || window.event;
			
            if(opt['disable_in_input']) { //Don't enable shortcut keys in Input, Textarea fields
                var element;
                if(e.target) element=e.target;
                else if(e.srcElement) element=e.srcElement;
                if(element.nodeType==3) element=element.parentNode;

                if(element.tagName == 'INPUT' || element.tagName == 'TEXTAREA') return;
            }
	
            //Find Which key is pressed
            if (e.keyCode) code = e.keyCode;
            else if (e.which) code = e.which;
            var character = String.fromCharCode(code).toLowerCase();
			
            if(code == 188) character=","; //If the user presses , when the type is onkeydown
            if(code == 190) character="."; //If the user presses , when the type is onkeydown

            var keys = shortcut_combination.split("+");
            //Key Pressed - counts the number of valid keypresses - if it is same as the number of keys, the shortcut function is invoked
            var kp = 0;
			
            //Work around for stupid Shift key bug created by using lowercase - as a result the shift+num combination was broken
            var shift_nums = {
                "`":"~",
                "1":"!",
                "2":"@",
                "3":"#",
                "4":"$",
                "5":"%",
                "6":"^",
                "7":"&",
                "8":"*",
                "9":"(",
                "0":")",
                "-":"_",
                "=":"+",
                ";":":",
                "'":"\"",
                ",":"<",
                ".":">",
                "/":"?",
                "\\":"|"
            }
            //Special Keys - and their codes
            var special_keys = {
                'esc':27,
                'escape':27,
                'tab':9,
                'space':32,
                'return':13,
                'enter':13,
                'backspace':8,
	
                'scrolllock':145,
                'scroll_lock':145,
                'scroll':145,
                'capslock':20,
                'caps_lock':20,
                'caps':20,
                'numlock':144,
                'num_lock':144,
                'num':144,
				
                'pause':19,
                'break':19,
				
                'insert':45,
                'home':36,
                'delete':46,
                'end':35,
				
                'pageup':33,
                'page_up':33,
                'pu':33,
	
                'pagedown':34,
                'page_down':34,
                'pd':34,
	
                'left':37,
                'up':38,
                'right':39,
                'down':40,
	
                'f1':112,
                'f2':113,
                'f3':114,
                'f4':115,
                'f5':116,
                'f6':117,
                'f7':118,
                'f8':119,
                'f9':120,
                'f10':121,
                'f11':122,
                'f12':123
            }
	
            var modifiers = {
                shift: {
                    wanted:false,
                    pressed:false
                },
                ctrl : {
                    wanted:false,
                    pressed:false
                },
                alt  : {
                    wanted:false,
                    pressed:false
                },
                meta : {
                    wanted:false,
                    pressed:false
                }	//Meta is Mac specific
            };
                        
            if(e.ctrlKey)	modifiers.ctrl.pressed = true;
            if(e.shiftKey)	modifiers.shift.pressed = true;
            if(e.altKey)	modifiers.alt.pressed = true;
            if(e.metaKey)   modifiers.meta.pressed = true;
                        
            for(var i=0; k=keys[i],i<keys.length; i++) {
                //Modifiers
                if(k == 'ctrl' || k == 'control') {
                    kp++;
                    modifiers.ctrl.wanted = true;

                } else if(k == 'shift') {
                    kp++;
                    modifiers.shift.wanted = true;

                } else if(k == 'alt') {
                    kp++;
                    modifiers.alt.wanted = true;
                } else if(k == 'meta') {
                    kp++;
                    modifiers.meta.wanted = true;
                } else if(k.length > 1) { //If it is a special key
                    if(special_keys[k] == code) kp++;
					
                } else if(opt['keycode']) {
                    if(opt['keycode'] == code) kp++;

                } else { //The special keys did not match
                    if(character == k) kp++;
                    else {
                        if(shift_nums[character] && e.shiftKey) { //Stupid Shift key bug created by using lowercase
                            character = shift_nums[character];
                            if(character == k) kp++;
                        }
                    }
                }
            }
			
            if(kp == keys.length &&
                modifiers.ctrl.pressed == modifiers.ctrl.wanted &&
                modifiers.shift.pressed == modifiers.shift.wanted &&
                modifiers.alt.pressed == modifiers.alt.wanted &&
                modifiers.meta.pressed == modifiers.meta.wanted) {
                callback(e);
	
                if(!opt['propagate']) { //Stop the event
                    //e.cancelBubble is supported by IE - this will kill the bubbling process.
                    e.cancelBubble = true;
                    e.returnValue = false;
	
                    //e.stopPropagation works in Firefox.
                    if (e.stopPropagation) {
                        e.stopPropagation();
                        e.preventDefault();
                    }
                    return false;
                }
            }
        }
        this.all_shortcuts[shortcut_combination] = {
            'callback':func,
            'target':ele,
            'event': opt['type']
        };
        //Attach the function with the event
        if(ele.addEventListener) ele.addEventListener(opt['type'], func, false);
        else if(ele.attachEvent) ele.attachEvent('on'+opt['type'], func);
        else ele['on'+opt['type']] = func;
    },

    //Remove the shortcut - just specify the shortcut and I will remove the binding
    'remove':function(shortcut_combination) {
        shortcut_combination = shortcut_combination.toLowerCase();
        var binding = this.all_shortcuts[shortcut_combination];
        delete(this.all_shortcuts[shortcut_combination])
        if(!binding) return;
        var type = binding['event'];
        var ele = binding['target'];
        var callback = binding['callback'];

        if(ele.detachEvent) ele.detachEvent('on'+type, callback);
        else if(ele.removeEventListener) ele.removeEventListener(type, callback, false);
        else ele['on'+type] = false;
    }
}
function selTest(){
	//if (typeof inCheckout != "undefined") { return 0; }
    //var vx = $("#ShippingSpeedChoiceCarriers").val();
    $("select").each(function(i, select){

        var $select = $(select);
        if (!select.name.match(/ShippingSpeedChoice\d/gi)){
            return 0;
        }
        var $div = $('<div></div>');
        $div.addClass("shipOptionsDivPrince");
        $div.attr("id",select.name);

        //$div.append();
        var chkFirst = true;
        var $chkd = $;
        $select.find('option').each(function(j, option){
            
            var $option = $(option);
            //if ($option.val() == 0) {return 0;}
            var $radio = $('<input type="radio" />');
            $radio.attr('name', $select.attr('name')).attr('value', $option.val());
            
            var $lab = $("<label />").attr('for', $select.attr('name')).text($option.text());
            if ($option.attr('selected')) {
                $radio.attr('checked', 'checked');
                $chkd = $lab;
            } else {
		/*
                if (chkFirst){
                    $radio.attr('checked', 'checked');
                    $chkd = $lab;
                    chkFirst = false;
                }
		*/
            }
		//if (typeof inCheckout != "undefined") {
			$radio.mouseup(function(){
				$("#hidden_btncalc_shipping").next().html("&gt;&gt; Recalculate Shipping &amp; Tax").css({"color":"blue","text-decoration":"underline"});
				$("label:contains('" + $option.text() + "')").css("color","blue");
			});
		//} else {
			//$radio.mouseup(function(){ this.form.submit(); });
		//}
            //$radio.mouseup(function(){ this.form.submit(); });
            $div.append($radio);
            $div.append($lab);
            $div.append('<br />');
            /*
            $select.before($radio);
            $select.before(
              $("<label />").attr('for', $select.attr('name')).text($option.text())
            );
            $select.before("<br/>");
            */
            
        });
        $chkd.css("color","red");
        $select.before($div);
        $select.remove();
    });
    $("#ShippingSpeedChoiceCarriers").change(function(){
        $("#ShippingSpeedChoice1").css("display",(this.value == 1) ? "block" : "none");
        $("#ShippingSpeedChoice2").css("display",(this.value == 1) ? "none" : "block");
    });
    $("#ShippingSpeedChoice1").css("display",(this.value == 1) ? "block" : "none");
    $("#ShippingSpeedChoice2").css("display",(this.value == 1) ? "none" : "block");
}

shortcut.add("Ctrl+Shift+1",function(){
    var opt = document.getElementsByName("PaymentMethodType")[0];
    if (!opt) {
        return 0;
    } //sanity check
    if (poAdded) {
        alert('Option Already Displayed');
        return 0;
    }
    var elOptNew = document.createElement('option');
    elOptNew.text = 'Purchase Order Number';
    elOptNew.value = 'Purchase Order Number';
    var elSel =  document.getElementsByName("PaymentMethodType")[0];

    try {
        elSel.add(elOptNew, null); // standards compliant; doesn't work in IE
    }
    catch(ex) {
        elSel.add(elOptNew); // IE only
    }
    alert("PO Option Added!");
    poAdded = true;
    return false;
});
//****** UPS FIX *******
function UPSFix() {
	//return 0;
    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();

    
}
function getManu(){
    var m,legitManu;
    legitManu = ["HP","Dell","Canon","Samsung","Okidata","Kyocera-Mita","Konica-Minolta","Brother","Epson","Lexmark","NEC","Panasonic","Ricoh","Sharp","Xerox"];
    $("font.productnamecolorLARGE").each(function(){
        m = this.innerHTML;
    });
    var cManu,rgx;
    for (var i in legitManu) {
        cManu  = legitManu[i];
        regx = new RegExp(cManu.replace("-","|"),"i");
        if (m.search(regx) > -1) {
            return cManu;
        }
    }
	
	
}

function drawCompatPrinterTable() {
    //return 0;
    if (typeof(global_URL_Encode_Current_ProductCode) != "undefined") {
        var mTable = $.ajax({
            url: "/v/printertable3.asp?p=" + global_URL_Encode_Current_ProductCode + "&manu=" + getManu(),
            async: false
        }).responseText;
        document.write(mTable);
    }
}

$(window).scroll(function() {

    //$("#floatLiveChat").css('top', $(document).scrollTop() + 10 + 'px');
    if (lcTimerID > 0) {
        clearTimeout(lcTimerID);
    }
    //window.status = lcTimerID;
    lcTimerID = setTimeout('moveLC()', 500);
});

function moveLC() {
  
    $("#floatLiveChat").animate({
        'top': $(document).scrollTop() + 10 + 'px'
        }, 'slow');
}



function writeExtDesc() {
    var o = "";
    o = "<table style='width: 470px;'><tr><td valign='top'><h3>Shop with confidence!</h3>This cartridge is backed with ColorTonerExpert&rsquo;s <br /><em><b>1 Year Warranty</b></em>!</td><td>";
    //o += "<div id=\"NoShadow\"><form name=\"lpClickToTalk\" method=\"get\"><table cellpadding=\"0\" cellspacing=\"0\" class=\"tableWidth\"><tr><td class=\"topImage\"></td></tr><tr><td id=\"contentCell\">Chat with a representative now <br><a href='https://server.iad.liveperson.net/hc/53112383/?cmd=file&file=visitorWantsToChat&site=53112383&byhref=1' target='chat53112383'  onClick=\"javascript:window.open('https://server.iad.liveperson.net/hc/53112383/?cmd=file&file=visitorWantsToChat&site=53112383&SESSIONVAR!skill=&referrer='+escape(document.location),'chat53112383','width=472,height=320');return false;\" ><img src='https://server.iad.liveperson.net/hc/53112383/?cmd=repstate&site=53112383&ver=1&imageUrl=https://server.iad.liveperson.net/visitor/livecall/form/images/chat&skill=' name='hcIcon' style=\"margin-top: 5px\" border=0></a><p class=\"line\"></p>Or enter your phone number and we will call you in about <b><span id=\"lpcttApproximatedTimeInQueue\"></span></b><br><input type=\"text\" name=\"lpcttPhoneNumber\" id=\"lpcttPhoneNumber\" value=\"\" size=\"15\" style=\"width:130px\"><br>  <a name=\"lpctcClickToTalk\" onClick=\"onOneStepClickToTalk(); return false;\" href=\"#\"><img name='hcIcon' id='hcIcon' border=\"0\" src=\"http://server.iad.liveperson.net/hc/53112383/?cmd=repstate&channel=voice&skill=&site=53112383&imageUrl=https://server.iad.liveperson.net/visitor/livecall/form/images/call\" /></a> <script type=\"text/javascript\"> var lpNumber = '53112383'; var lpcttPrePopulatePhone = true; var lpMinPhoneNumberLength = 5; var lpcttDisplayQueueStatus = true; var lpcttPrefix = \"1\";</script><script type=\"text/javascript\" src=\"http://server.iad.liveperson.net/hcp/html/lpOneStepClickToTalk.js\"></script>     <script type=\"text/javascript\" src=\"http://server.iad.liveperson.net/hcp/html/lpCheckVisitorQueueStats.js\"></script>                     <br>        <span class=\"small\">US only. Other countries,                  <a href='http://server.iad.liveperson.net/hc/53112383/?cmd=file&file=visitorWantsToTalk&site=53112383&SESSIONVAR!skill=&onlineURL=http://server.iad.liveperson.net/hcp/voice/forms/precall.asp?site=53112383%26identifier=1&ResponseURL=http://server.iad.liveperson.net/hcp/voice/forms/callStatus.asp&byhref=1&imageUrl=https://server.iad.liveperson.net/visitor/livecall/clickcall2' target='call53112383'  onClick=\"javascript:window.open('http://server.iad.liveperson.net/hc/53112383/?cmd=file&file=visitorWantsToTalk&site=53112383&SESSIONVAR!skill=&onlineURL=http://server.iad.liveperson.net/hcp/voice/forms/precall.asp?site=53112383%26identifier=1%26ResponseURL=http://server.iad.liveperson.net/hcp/voice/forms/callStatus.asp&imageUrl=https://server.iad.liveperson.net/visitor/livecall/clickcall2&referrer='+escape(document.location),'call53112383','width=472,height=320');return false;\" >click here</a>.</span></td></tr><tr><td class=\"btmImage\"></td></tr></tr></table></form></div>";
    //o += "<div align=\"center\" id=\"VolusionLiveChat\"><a href=\"http://www.volusion.com/livechat_software.asp\">Free Live Chat Software</a></div><script type=\"text/javascript\" src=\"https://livechat.volusion.com/script.aspx?id=452377\"></script>";
    o += "</td></tr></table>";
    $("#extProdDesc").html(o);
}

function applyCoupon() {
    var hrefstr = "";
    hrefstr = window.location.pathname;
    if (($.cookie("autoCoupon") != null) && (hrefstr.match(/shoppingcart.asp$/ig))) {
        $("input[name=CouponCode]").val($.cookie("autoCoupon"));
        $.cookie("autoCoupon", null); //remove coupon afterappplying
        $("form[name=form]").submit();
    }
}
function storeCoupon(ccode,desc) {
    if (ccode != null) {
        if (($.cookie("autoCoupon") != null) && ( $.cookie("autoCoupon") != ccode)) { //a coupon is stored, confirm overwrite
            if (confirm("You currently have \"" + $.cookie("autoCoupon") + "\" waiting to be applied. We are currently limited to one stored coupon.\n\nDo you wish to change \"" + $.cookie("autoCoupon") + "\" to \"" + ccode + "\"?")) {
                $.cookie("autoCoupon", ccode);
                $.cookie("autoCouponDesc", desc);
            }
        } else {
            $.cookie("autoCoupon", ccode);
            $.cookie("autoCouponDesc", desc);
        }
        detectCoupon();
    } //fail silently if no coupon is passed -> developer error, user doesnt need to know

}
function detectCoupon() {
    
    var hrefstr = "";
    hrefstr = window.location.pathname;
    var wl = "";
    wl = window.location.href.split("?");
    var globalCoupon = "";
    var globalDesc = "";
    if (wl.length > 1) { //has params
        var params = wl[1];
        
        for (var pi = 0; pi < params.split("&").length; pi++) {
            
            var paramName = "";
            var paramVal = "";

            var cparam = params.split("&");
            
            if (cparam[pi].split("=").length > 1) {
                paramName = cparam[pi].split("=")[0];
                paramVal = cparam[pi].split("=")[1];

                if (paramName.toLowerCase() == "vCoupon".toLowerCase()) {
                    globalCoupon = paramVal;
                }
                if (paramName.toLowerCase() == "vDesc".toLowerCase()) {
                    globalDesc = unescape( paramVal );
                }
            }
        }
    
    }
    if (globalCoupon != "") {
        if (($.cookie("autoCoupon") != null) && ($.cookie("autoCoupon") != globalCoupon) && (globalCoupon != $.cookie("autoCoupon"))) { //a coupon is stored, confirm overwrite
            if (confirm("You currently have \"" + $.cookie("autoCoupon") + "\" waiting to be applied. We are currently limited to one stored coupon.\n\nDo you wish to change \"" + $.cookie("autoCoupon") + "\" to \"" + globalCoupon + "\"?")) {
                $.cookie("autoCoupon", globalCoupon);
                $.cookie("autoCouponDesc", globalDesc);
                window.location.href = window.location.pathname;
                return 0;
            }
        } else {
            $.cookie("autoCoupon", globalCoupon);
            $.cookie("autoCouponDesc", globalDesc);
            window.location.href = window.location.pathname;
            return 0;
        }
        
    }
    var h = "";
    var color = "white";
    h = "<div class='ccode'>" + $.cookie("autoCoupon") + "</div><div>" + $.cookie("autoCouponDesc") + "</div>";  
    

    if (hrefstr.match(/shoppingcart.asp$/ig)) {
        color = "#FFFFCC";
        h += "<div><button onclick='applyCoupon()'>Apply!</button></div>";
    }
    h += "<div style='font-size: 9px; margin-top: 10px'><a href='javascript:removeCoupon()'>Remove</a></div>";
    $("#storedCoupon").css('background-color', color);
    if ($.cookie("autoCoupon") != null) {
        $("#storedCoupon").css('display', 'block').html(h); //show if coupon
        animateCoupon();
    } else {
        $("#storedCoupon").css('display', 'none'); //no coupon, hide
    }
    
}
function animateCoupon() {
    $("#storedCoupon").css({
        'width': '270px',
        'height': '200px'
    }).animate({
        width: '170',
        height: '90'
    }, 1000);
}
function removeCoupon() {
    if (confirm("Confirm coupon removal?")) {
        $.cookie("autoCoupon", null);
        $.cookie("autoCouponDesc", null);
        detectCoupon();
    }
}

function getProductTree(catID){
    var rv = "";
    if (myCats[catID] != undefined) {
        rv = myCats[catID].name;
        if (myCats[catID].parent != 0) {
            rv += "," + getProductTree(myCats[catID].parent);
        }
    }
    return rv;
}
var objSBPmods = [];
function stepHandler(obj){
    
    if (obj.id == "mc-steps-1"){
        
        if (obj.value == "") {return 0;}
        $("#mc-steps-2-load").removeClass("vishidden");
        $.get('/v/psearchapi2.asp?manufacturer='+obj.value,function(data){
           objSBPmods = eval(data);
           applyMakeData();
        });
    }
    if (obj.id == "mc-steps-2"){
        if (obj.value == "") {return 0;}
        $("#mc-steps-3-load").removeClass("vishidden");
        $("#mc-steps-3").attr('disabled','disabled');
       applyModelData(obj.value);

    }
    
    return 0;
}
function applyModelData(make){
    $("#mc-steps-3").removeOption(/./).addOption("","Choose Your Printer 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){
                $("#mc-steps-3").addOption(modsz[m],modsz[m]);
            }
        }

    }
    $("#mc-steps-3").selectOptions("");
    $("#mc-steps-3-load").css('visibility','hidden');
    $("#mc-steps-3").removeAttr('disabled').focus();
$("#mc-steps-3").sortOptions();
}
function applyMakeData(){
   //prep the select
   $("#mc-steps-2").removeOption(/./).addOption("","Choose Your Printer Family");
    for (x in objSBPmods){
        //objOptions[x] = objSBPmods[x].make;
        $("#mc-steps-2").addOption(objSBPmods[x].make,objSBPmods[x].make);
    }
    $("#mc-steps-2").selectOptions("");
    $("#mc-steps-2-load").css('visibility','hidden');
    $("#mc-steps-2").removeAttr('disabled').focus();
}

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;
}
