/*
	
	Prince 2010

*/
var bbitemsglobal = 0;
var navTimerID;
var membersPrince = false;
$(document).ready(function() {
    detectPage();
    (function(d){
        var js, id = 'facebook-jssdk';
        if (d.getElementById(id)) {
            return;
        }
        js = d.createElement('script');
        js.id = id;
        js.async = true;
        js.src = "//connect.facebook.net/en_US/all.js#appId=244477062262731&xfbml=1";
        d.getElementsByTagName('head')[0].appendChild(js);
    }(document));
    (function() {
        var po = document.createElement('script');
        po.type = 'text/javascript';
        po.async = true;
        po.src = 'https://apis.google.com/js/plusone.js';
        var s = document.getElementsByTagName('script')[0];
        s.parentNode.insertBefore(po, s);
    })();
	

    $("#reqmembercode").val("").attr("disabled",false);
    $("table.colors_lines_light").css("margin","10px 0 10px 0").insertBefore($("#Header_ProductDetail_ProductDetails_span").parents("table")[0]);
    $("#divLeftCol h3 a").mouseenter(function(){
        leftNavHover(this) ;
    }).mouseleave(function(){
        leftNavHover(this,1);
    });

    $("#hoverNavDiv").mouseenter(function(){
        clearTimeout(navTimerID);
    }).mouseleave(function(){
        leftNavHover(this,1);
    });

    $("#tgReferralNumber").change(function(){
        var refId = "" + $(this).val();

        $.cookie("referrerID",refId,{
            expires: 1
        });

    });
    $("#tabHeaders td").click(function() {
        tabClick(this);
    });
    $("#innerContents").html($("#dataItemDeals").html());
    $('a').each(function() {
        if ($(this).attr('href') == undefined) {
            $(this).attr('href', 'javascript:void(0)');
            $(this).click(function() {
                alert('Content Coming Soon!')
            });
        }
    });
    $("#bbremovecode").click(function(){
        alert("k");
    });
    $("#dvBuyBack h1").click(function() {
        $(this).next().toggle('slow');
    });
    $("#reqmembercode").keyup(function(){
        var text = "" + $(this).val();
        text = text.toLowerCase();
        var affs = {
            "esrecycles":"EarthShare",
            "aasherecycles":"AASHE",
            "garecycles":"Green America"
        };

        if (typeof affs[text] != 'undefined'){
            $("#reqmembercodeinfo").html("<b>" + affs[text] + " Membership Pricing enabled!<b> <a id='bbremovecode' href='javascript:bbremovecodes()'>[change/remove]</a>").show();
            $("td.p").each(function(){
                var rate = parseFloat($(this).html());
                $(this).html(rate * 2).attr('title','Regular price: $' + rate).css('color','green');
            });
            $(this).attr('disabled',true).css({
                "color":"gray",
                "backgroundColor":"#efefef"
            });
        } else {
            $("#reqmembercodeinfo").text("");
        }

    });
    $("input.bb").keyup(function() {
        var tid = this.id + "-pricetd";
        //alert('tid: ' + tid);
        //var realPrice = $(tid).html();
        var realPrice = parseFloat(document.getElementById(tid).innerHTML);
        realPrice = isNaN(realPrice) ? 0 : realPrice;
        var thisval = "";
        thisval = $(this).val();
        thisval = thisval.replace(/[a-zA-Z]/gi,"");
        if (thisval.match(/^0\d+/gi)) {
            $(this).val(thisval.replace(/^0/gi,""));
        }
        if (thisval == "") {
            $(this).val(0);
        }
        
        //thisval = isNaN(thisval) ? 0 : thisval;

        var actual = (parseFloat(thisval) * realPrice).toFixed(2);
        actual = isNaN(actual) ? 0 : actual;
        var cid = this.id + "-computedprice";
        document.getElementById(cid).innerHTML = "$" + actual;

        var hid = this.id;
        hid = hid.replace(/^bbCart/i, "bbCartH");

        document.getElementById(hid).value = "$" + actual;

        //summary
        var sum = 0;
        var count = 0;
        $("input[id^=" + this.id.split("^")[0] + "]").each(function() {
            //if (!isNaN(parseInt($(this).val()))) {
            sum += parseInt($(this).val());
            count += 1;
        //}
        });
        //alert(count + " : " + sum);
        var txtsum = "";
        if (sum > 0) {
            txtsum = "&nbsp;&nbsp;[" + sum + " Item(s) selected]";
        }

        //alert(hid.replace(/^bbCartH_/i, "").split("^")[0]);
        $("#summary" + hid.replace(/^bbCartH_/i, "").split("^")[0]).html(txtsum);
        bbitemsglobal = 0;
        $("span[id^=summary]").each(function() {

            var ihtm = "";
            ihtm = $(this).html();
            ihtm = ihtm.replace(/[^0-9]/ig, "");
            bbitemsglobal += isNaN(ihtm) ? 0 : ihtm;
        });
    });
});

google.load("feeds", "1");
function initialize() {
    var feedControl = new google.feeds.FeedControl();
    feedControl.addFeed("http://feeds.feedburner.com/treehuggersite", "Tree Hugger");
    feedControl.addFeed("http://feeds.feedburner.com/EcoGeek", "EcoGeek");
    feedControl.addFeed("http://feeds.earth911.com/earth911/", "Earth 911");

    feedControl.draw(document.getElementById("dataItemNews"));
/*
    var feedControl2 = new google.feeds.FeedControl();
    feedControl2.addFeed("http://www.envirogadget.com/feeds-rss", "EnviroGadget");
    feedControl2.addFeed("http://www.furniturehomedesign.com/feed/", "Furniture Home Design");
    feedControl2.addFeed("http://feeds.feedburner.com/Inhabitat", "Inhabitat");
    feedControl2.draw(document.getElementById("dataItemStuff"));
    */
}
google.setOnLoadCallback(initialize);

function bbremovecodes(){
    $("#reqmembercodeinfo").html("").hide();
    $("td.p").each(function(){
        var rate = $(this).attr('title');
        //var rate = $(this).attr('title');
        $(this).html(rate.split("$")[1]).attr('title','').css('color','inherit');
    });
    $("#reqmembercode").val("").attr('disabled',false).css({
        "color":"inherit",
        "backgroundColor":"inherit"
    });
}
function showSSL(){
    window.open('https://www.volusion.com/ssl.asp?url=www.tonergreen.com', 'VolusionSSL', 'top=10,left=10,menubar=0,resizable=0,scrollbars=0,width=467,height=467');
}
function SBPNavigate(q) {
    if (q == "null") {
        return 0;
    }
    location.href = q;
}
function sbpManuChange(){
	
	
}
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);
	
    SBPNavigate(searchPageURL);
	
}
var objSBPModels = new Object();
var objSBPmods = [];
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 = {
                "": "Please Choose Your Series"
            };
            $("#sbp-make").attr('disabled', true).addOption(tmpOpt, true);
			
            $("#sbp-model").removeOption(/./);
            var tmpOpt = {
                "": "Please Choose Your 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 = {
                    "": "Please Choose Your 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 = {
                "": "Please Choose Your Model"
            };
            $("#sbp-model").attr('disabled', true).addOption(tmpOpt, true);
        } else {
            if (!objSBPModels) {
                'error '
				
            } else {
                $("#sbp-model").removeOption(/./);
                var tmpOpt = {
                    "": "Please Choose Your 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("");
            }
        }
    }
    if ("sbp-model" == objSel.id) {
        doStepSearch();
    }
}

function tabClick(whichtab) {

    var dataid = "#"  + whichtab.id.replace("tab", "data");

    var datahtm = $(dataid).html();
    
    $("#tabHeaders td").each(function() {

        if (this.id == whichtab.id) {
            $(this).addClass("activeTab");
            $("#innerContents").html(datahtm);
            $(".gfc-control a").each(function() {
                $(this).attr("target", "_blank");
            });
            
        }
        else {
            $(this).removeClass("activeTab");
        }
    });
}

function bbFormSubmit() {
    var bc = "white";
    var val = true;
    var errmsg = "";
    var parms = new Object();

    $("*[name^=req]").each(function() {
        bc = "white";
        if (($(this).val() == "") && ($(this).attr('name') != 'reqmembercode')) {
            //alert("testing: " + $(this).attr('name'));
            bc = "yellow";
            val = false;
            errmsg = "&raquo; Please fill in the highlighted fields (yellow)<br />";

        }
        var xpart = this.name;
        //alert(xpart.replace(/^req/ig, ""));
        parms[xpart.replace(/^req/ig, "")] = $(this).val();
        $(this).css('background', bc);
    });
    //alert(parms['email1']);
    if (parms['email1'] != parms['email2']) {
        $("*[name^=reqemail]").css('background', 'red');
        val = false;
        errmsg += "&raquo; Email addresses do not match (red)<br />";
    } else {
        //matches, test for format
        var re = /^[\w-\.]+@([\w-]+\.)+[\w-]{2,6}$/i;
        if (!re.test(parms['email1'])) {
            val = false;
            $("*[name^=reqemail]").css('background', 'red');
            errmsg += "&raquo; Incorrect Email address format (red)<br />";   
        }
    }
    if (bbitemsglobal < 1) {
        val = false;
        errmsg += "&raquo; No Items were selected! Click on the green bars below to add items.<br />";   
    }
    
    if (!val) {
        $("#errmac").slideDown('slow').html(errmsg);
    }
    return val;
}
function detectPage(){
    //var p = document.location.pathname;
    if ($("#tgOrderNumber").text() != "") {
        if ($.cookie("referrerID") != "") {
            //submit cookie and order id here
            $.get('/v/referral.asp?o=' + $("#tgOrderNumber").text() + '&r=' + $.cookie("referrerID"),function(data){
                $.cookie("referrerID",null);
            });

        }
    }
}

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 leftNavHover(itm,hide){
    if (hide != 1){
        var eid = $(itm).attr('title').replace(" ", "_");
        $("#printer_series").html($("#"+eid).html());
        $("#hoverNavDiv").css({
            display:"block", 
            top: $(itm).position().top + "px",
            left: $(itm).position().left + 140 + "px"
        });
        clearTimeout(navTimerID);
        $("#divLeftCol h3 a").removeClass("myHover");
        $(itm).addClass("myHover");
    } else {
        
        if ($("#hoverNavDiv").css("display") == "none"){
            $("#divLeftCol h3 a").removeClass("myHover");
        }
        navTimerID = setTimeout(hideHoverNav, 20);
    }
}
function hideHoverNav(){
    $("#hoverNavDiv").css({
        display:"none"
    });
    $("#divLeftCol h3 a").removeClass("myHover");
}
