var environment = "patbrweb_release";
var api_url = "http://patbrapi.americantire.org/tirebuyer/api/getTireAPI.php";
var bv_url = "http://reviews.tirebuyer.com/3433/{productid}/reviews.xml?&apiversion=3.3&format=embedded&page=1&num=10&sort=submissionTime&dir=desc";
var siteurl = "http://www.tirebuyer.com/tb_pages/";
var builder_url = "http://patbrweb01.americantire.org/tirebuyer/landingsite/";
var flashsite = "https://www.tirebuyer.com/";
var omniture_id = "atdtirebuyercomprod";
var real_target = "/usr/local/apache-tomcat-6.0.18/webapps/release";
var default_tire_thumb_img = "http://www.tirebuyer.com/assets/images/TempImage_82x82.jpg";
var default_tire_img = "http://www.tirebuyer.com/tirepreviews/TempImage_386x386.jpg";
var default_wheel_thumb_img = "http://www.tirebuyer.com/wheelpreviews/tempWheelImage.png";
var default_wheel_img = "http://www.tirebuyer.com/wheelpreviews/tempWheelImage386x386.jpg";

if (typeof environment == "undefined") {
    environment = "development";
}

if (typeof siteurl == "undefined") {
    siteurl = "http://datbrweb01.americantire.org/~pbrenner/sandboxes/tirebuyer/landingsite/tb_pages/";
}

if (typeof builder_url == "undefined") {
	builder_url = "http://datbrweb01.americantire.org/~pbrenner/sandboxes/tirebuyer/landingsite/_build/";
} else {
	builder_url = builder_url + "_build/";
}


if (typeof flashsite == "undefined") {
    flashsite = 'https://www.tirebuyer.com/';
}
if (typeof omniture_id == "undefined") {
    omniture_id = "tirebuyercomdev";
}

var omniture = [
    { "name" : "pagename", "variable" : "s.pagename" }, 
    { "name" : "channel", "variable" : "s.channel" },
    { "name" : "category", "variable" : "s.prop1" },
    { "name" : "category1", "variable" : "s.prop2" },
    { "name" : "category2", "variable" : "s.prop3" },
    { "name" : "pagetype", "variable" : "s.prop4" },
    { "name" : "caryear", "variable" : "s.prop5" },
    { "name" : "carmake", "variable" : "s.prop6" },
    { "name" : "carmodel", "variable" : "s.prop7" },
    { "name" : "cartrim", "variable" : "s.prop8" },
    { "name" : "makemodel", "variable" : "s.prop9" },
    { "name" : "findmethod", "variable" : "s.eVar3" },
    { "name" : "merchcat", "variable" : "s.eVar4" },
    { "name" : "caryear", "variable" : "s.eVar7" },
    { "name" : "carmake", "variable" : "s.eVar8" },
    { "name" : "carmodel", "variable" : "s.eVar9" },
    { "name" : "cartrim", "variable" : "s.eVar10" },
    { "name" : "makemodel", "variable" : "s.eVar14" },
    { "name" : "tirebrand", "variable" : "s.eVar19" },
    { "name" : "wheelbrand", "variable" : "s.eVar21" },
    { "name" : "dealerzip", "variable" : "s.eVar28" },
    { "name" : "userzip", "variable" : "s.eVar29" },
    { "name" : "tirestyle", "variable" : "s.eVar32" },
    { "name" : "wheelstyle", "variable" : "s.eVar33" }
];

var jsv = "javascript:void(0);";

var widget = {
    sections: [ "Year", "Make", "Model", "Trim" ],
    current: null,
    
    zip_value: "Your ZIP Code",
    make_filter: "",
    
    deeplink_url: "",
    deeplink_values: Array(),
    
    init: function() {
        $("#widget").each( function() {
            $(".options .inp")

                .find("input").attr("value", "").end()
                
                .filter(".year")
                .each( function() {
                    widget.get("Year", null);
                });
        });

        $("#widget .inp input").blur( widget.checkReady )
            .filter(".zip")
                .attr("value", widget.zip_value)
                .focus( function() {
                    if ($(this).attr("value").trim() == widget.zip_value) {
                        $(this).attr("value", "");
                    }
                    $(this).parents(".inp").removeClass("zip-set").removeClass("set").addClass("active");
                })
                .blur( function() {
                    widget.validate($(this).parents(".inp"));
                    
                    if ($(this).attr("value").length >= 5) {
                        $(this).parents(".inp").addClass("zip-set").addClass("set");
                    } else {
                        $(this).parents(".inp").removeClass("active");
                    }
                })
                .keyup( function() {
                    $(this).attr("value", $(this).attr("value").replace(/[^0-9.-]/g, ''));
                    
                    if ($(this).attr("value").length >= 5) {
                        $(this).parents(".inp").addClass("zip-set").addClass("set");
                        widget.checkReady();
                    }
                })
                .keypress( function (e) {
                    if (e.which == 13) { 	 
                    	if ($(this).attr("value").length >= 5) {
                    		//$("#widget a.go").click();
                    		var section  = $("#widget input[name='page']").attr("value");
                            var account  = $("#widget input[name='account']").attr("value");
                            var store    = $("#widget input[name='store']").attr("value");
                            
                            var zip      = $("#widget input[name='zip']").attr("value");
                            var vyear    = $("#widget input[name='year']").attr("value").replace("year-","");
                            var vmake    = escape($("#widget .options .make .t").text());
                            var vmakeid  = $("#widget input[name='make']").attr("value").replace("make-","");
                            var vmodel   = escape($("#widget .options .model .t").text());
                            var vmodelid = $("#widget input[name='model']").attr("value").replace("model-","");
                            var vtrim    = escape($("#widget .options .trim .t").text());
                            var vtrimid  = $("#widget input[name='trim']").attr("value").replace("trim-","");
                            
                            
                            if (section == "index")
                            {
                            	section = "tires";
                            }
                            if (store.length > 0) {	
                            	store = '&store=' + store;
                            }
                            if (account.length > 0) {	
                            	store = '&account=' + account;
                            }
                            
                            var url = '#section=' + section + store + account + '&zip=' + zip + '&browseBy=trim&vYear=' 
                                + vyear + '&vMake=' + vmake + '&vModel=' + vmodel + '&vTrim=' + vtrim + '&vTrimID=' + vtrimid;
                            
                            if (widget.make_filter != "") {
                                var w = escape(widget.make_filter.toLowerCase());
                                
                                switch (section) {
                                    default:
                                        url += "&filter=make&makeName=" + w;
                                    break;
                                    case "wheels":
                                        url += "&makeFilter=" + w;
                                    break;
                                }
                            }
                                
                            url = flashsite + url;
                            
                            // Fire Omniture tracking for the car they chose and the zip code.
                            //
                            widget.omniture( { "caryear" : vyear, "carmake" : vmake, "carmodel" : vmodel, "cartrim" : vtrim, "userzip" : zip } );
                                
                            // Push the visitor to the Flash site.
                            //
                           document.location=url;
                           return false;
                    	}
                    }
                });

        $("#widget").find("a.go").each( function() {
            $(this).attr("href", "javascript:void(0);");
        })
        .click( function() {
            $("#widget").filter(".ready").each( function() {
                
                var section  = $("#widget input[name='page']").attr("value");
                var account  = $("#widget input[name='account']").attr("value");
                var store    = $("#widget input[name='store']").attr("value");
                
                var zip      = $("#widget input[name='zip']").attr("value");
                var vyear    = $("#widget input[name='year']").attr("value").replace("year-","");
                var vmake    = escape($("#widget .options .make .t").text());
                var vmakeid  = $("#widget input[name='make']").attr("value").replace("make-","");
                var vmodel   = escape($("#widget .options .model .t").text());
                var vmodelid = $("#widget input[name='model']").attr("value").replace("model-","");
                var vtrim    = escape($("#widget .options .trim .t").text());
                var vtrimid  = $("#widget input[name='trim']").attr("value").replace("trim-","");
 
                if (section == "index")
                {
                	section = "tires";
                }
                if (store.length > 0) {	
                	store = '&store=' + store;
                }
                if (account.length > 0) {	
                	account = '&account=' + account;
                }
                
                var url = '#section=' + section + store + account + '&zip=' + zip + '&browseBy=trim&vYear=' 
                    + vyear + '&vMake=' + vmake + '&vModel=' + vmodel + '&vTrim=' + vtrim + '&vTrimID=' + vtrimid;
                
                if (widget.make_filter != "") {
                    var w = escape(widget.make_filter.toLowerCase());
                    
                    switch (section) {
                        default:
                            url += "&filter=make&makeName=" + w;
                        break;
                        case "wheels":
                            url += "&makeFilter=" + w;
                        break;
                    }
                }
                    
                url = flashsite + url;
                
                // Fire Omniture tracking for the car they chose and the zip code.
                //
                widget.omniture( { "caryear" : vyear, "carmake" : vmake, "carmodel" : vmodel, "cartrim" : vtrim, "userzip" : zip } );
                    
                // Push the visitor to the Flash site.
                //
                $("#widget a.go").attr("href",url);
                return true;
            });
            
            if (!$("#widget .options .make").hasClass("active") && !$("#widget .options .year").hasClass("open")) {
                $("#widget .options .year .t").click();
            }
        });
        
        // Set up "Check Availability" button on the product detail page.
        //
        $("#focus a.check_availability")
            .attr("href",jsv)
            .click( function() {
            	if ( $("#widget").hasClass("ready")) {
            		$("#widget a.go").trigger("click");
            		document.location.href=$("#widget a.go").attr("href");
            	} else {
            		alert("Please enter your vehicle information in the blue bar above to see all " + widget.make_filter + " products\nthat fit your vehicle. You may also shop without a vehicle by entering a size in the left box to see all products available in your desired size.");
            	}
        });
    },

    activate: function(inp) {
        $(inp).not(".set")
            .addClass("active")
            .hover(
                function() { $(this).addClass("hover"); },
                function() { $(this).removeClass("hover"); }
            )
                
            .find(".t").click( function() {
                // Clear the ready status.
                $("#widget").removeClass("ready");

                $(inp).siblings(".inp").filter(".open").find(".t").click();
                
                if ($(inp).hasClass("open")) {
                    $(inp).removeClass("open").find("ul").hide();
                    $(widget.current).bgiframe({height:0});
                } else {
                    $(inp).addClass("open");

                    widget.current = $(inp).find("ul");
                    $(inp).find("ul").show();
                    $(widget.current).css("visibility","hidden").show().css("height", "auto");
                    $(widget.current).bgiframe({height:$(widget.current).height()+10 });
                    if ($(widget.current).height() > 260) {
                        $(widget.current).height("260px");
                    }
                    $(widget.current).hide().css("visibility", "visible").slideDown(200);
                    $(widget.current).hide().slideDown(200);
                }
            }).end()
            
            .find("ul li")
                .hover( 
                    function() {
                        $(this).addClass("hover");
                    },
                    function() {
                        $(this).removeClass("hover");
                })
                .click( function() {
                    var clicked = this;
                    var current = $(this).parents(".inp");
                    var next = null;
                    
                    $(clicked).addClass("current").siblings("li").removeClass("current");
                    $(current).find(".t").click().text($(this).text());
                    
                    $(this).parents(".inp").find("input").attr("value", $(this).attr("id")).change();
                    ;
                    widget.clear(current, clicked);
                    widget.checkReady();
                }).end()
            
            .filter(".trim").find("ul li").click( function() {
                $(this).parents(".inp").addClass("set");
            });
    },

    clear: function(current, clicked) {
        var item = "";
        var beyond = false;
        
        for (var i=0; i < widget.sections.length; i++) {
            item = widget.sections[i].toLowerCase();
            
            if ($(current).hasClass(widget.sections[i].toLowerCase()) && i < widget.sections.length - 1) {
                next = $(current).siblings("." + widget.sections[i+1].toLowerCase());
                
                if (clicked) {
                    $(next).addClass("active").each( function() {
                        for (var j = i + 1; j < widget.sections.length; j++) {
                            $("#widget").find("." + widget.sections[j].toLowerCase())
                                .removeClass("active").removeClass("set").removeClass("none").unbind()
                                .find("input").attr("value", "").end()
                                .find(".t").unbind().text("Select " + widget.sections[j]);
                        }
                    });

                    widget.get(widget.sections[i+1], clicked);
                }
            }
            
            if (!clicked) {
                // If clicked is null, we're doing a different kind of clear. 
                // In this case we're showing that there's no availability.
                
                if ($(current).hasClass(item)) beyond = true;
                if (beyond) {
                    $("#widget ." + item)
                        .addClass("set").addClass("none")
                        .find("input").attr("value","NONE").change().end()
                        .find(".t").text("No " + item + "s available.");
                }
            }
        }
    },
    
    validate: function(what) {
        var val = $(what).find("input").attr("value");
        $(what).removeClass("set");

        $(what).filter(".zip").each( function() {
            val = validate.zipcode(val, widget.zip_value);
            if (val.length == 5 || val.length == 10) {
                $(what).addClass("zip-set").addClass("set");
            }
        });

        $(what).filter(".year, .make, .model, .trim")
            .each (function() {
                if (val.length > 0) {
                    if (val != "NONE" || $(what).hasClass("trim")) {
                        $(what).addClass("set");
                    }
                }
        });
        
        $(what).find("input").attr("value", val);
    },
    
    checkReady: function() {
        var ready = true;
        $("#widget .inp input").each( function() {
            widget.validate($(this).parents(".inp"));
            if (!$(this).parents(".inp").hasClass("set")) ready = false;
        });
        
        if (ready) {
            $("#widget").addClass("ready");
        } else {
            $("#widget").removeClass("ready");
        }
    },
    
    get: function(what, where) {
        var vbl = what.toLowerCase();
        var val = (where) ? $(where).attr("id").replace(vbl + "-","") : "";
        var next = (where) ? $(where).parents(".inp").siblings("." + vbl) : $("#widget .year"); 

        $.ajax({
            url:siteurl + "xml-widget.php",
            dataType: "xml",
            type: "POST",
            data: "lookup=" + vbl + "&value=" + val,
            timeout: 5000,
            
            beforeSend: function() {
                $(next)
                    .addClass("loading").removeClass("set")
                    .find("ul").remove().end()
                    .find(".t").text("Loading " + what + "s...");
            },
            
            // After successful load, create a new UL with values, remove the "loading" text, then "activate" the input.
            //
            success: function(xml) {
                var list = $("list", xml);
                if (list.length > 0) {
                    var ltype = $(list).attr("type");

                    var ul = $("<ul></ul>");
                    var items = $("item", list);

                    for (var i = 0; i < items.length; i++) {
                        $(ul).append("<li id='" + $(items[i]).attr("id") + "'>" + $(items[i]).text() + "</li>");
                    }
                    
                    where ? $(where).parents(".inp").addClass("set") : $("#widget").addClass("loaded");
                    $(next).removeClass("loading").append(ul);
                    
                    if (items.length > 1) {
                        $(next).find(".t").text("Select " + what);
                        widget.activate(next);
                    } else {
                        if (items.length == 1) { 
                            $(next).find(".t").text($(items[0]).text()).end().addClass("set").addClass("active");
                            $(next).find("input").attr("value", $(items[0]).attr("id"));
                            widget.clear(next, $(ul).find("li"));
                        } else {
                            widget.clear(next, null);
                        }
                    }
                }
                // $("#widget .inp").not(".set").fadeTo(0,0.67).end().filter(".active").fadeTo(200,1);
            },
            error: function(req, err) {
                
            }
        });
    },
    
    deeplink: function(node, values) {
        // Send a request to CIE with the appropriate data.
        // Every time we'll need to pass the vehicle information, so if it's not filled out, request it.
        //
        if (widget.deeplink_url == "") {
            $.get(siteurl + "xml/TireBuyerSitemap.xml", {}, function(xml) {
                $(xml).find("page").each( function() {
                    if ($(this).find("id").text() == node) {
                        widget.deeplink_url = $(this).find("deeplink").text();
                        widget.deeplink_values = values;
                        widget.fire();
                    }
                });
            });
        } else {
            widget.deeplink_values = values;
            widget.fire();
        }
    },
    fire: function() {
        var url = widget.deeplink_url;
        
        $.each(
            widget.deeplink_values,
            function(key, value) {
                url = url.replace("{" + key + "}", value);
            }
        );

        
        if (url.match("{zip}") && widget.zip_value == "Your ZIP Code") {
            widget.getZip();
        } else {
            url = url.replace("{zip}", widget.zip_value);
            window.open(url,"_self");
        }
    },
    
    getZip: function() {
        $("#getzip").remove();
        
        var box = $("<div></div>").attr("id","getzip").appendTo(document.body);
        
        var scroll = $(document.body).scrollTop();
        var height = Math.ceil( $(window).height() / 2 )  - 100;
        
        $(box).append("<h4>Your ZIP code</h4>")
            .append("<p>Please enter your ZIP code in order to check the availability of this item in your area.</p>")
            .append("<input type='text' name='zip' class='zip text' value='' />")
            .append("<a href='" +jsv+ "' class='btn_cancel btn'>Cancel</a> <a href='" +jsv+ "' class='btn_search btn'>Search</a>")
            .append("<a class='close'>Close</a>").attr("href",jsv)
            .css("top", (scroll+height)+"px").css("opacity","0").css("display","block")
            .fadeTo(500,1);
        
        $(box)
            .find("input.zip").focus().end()
            .find("a.close, a.btn_cancel").click( function() { $("#getzip").fadeTo(500,0).remove(); }).end()
            .find("a").hoverClass("hover").end()
            .find("input.zip").keypress( function (e) {
                    if (e.which == 13) {
                        var zip = $("#getzip input.zip").attr("value").replace(/[^0-9]/g, '');
                        if (zip.length == 9) {
                            zip = zip.substr(0,5) + "-" + zip.substr(5,4);
                        } else {
                            zip = zip.substr(0,5);
                        }
                 
                        $("#getzip input.zip").attr("value", zip);
                
                        if (zip.length == 5 || zip.length == 10) {
                            widget.zip_value = zip.substr(0,5);
                            widget.fire();
                        } else {
                        	alert('Zip Code not correct');
                        }
                        return false;
                     }
                }).end()
            .find("a.btn_search").click( function() {
                var zip = $("#getzip input.zip").attr("value").replace(/[^0-9]/g, '');
                if (zip.length == 9) {
                    zip = zip.substr(0,5) + "-" + zip.substr(5,4);
                } else {
                    zip = zip.substr(0,5);
                }
                
                $("#getzip input.zip").attr("value", zip);
                
                if (zip.length == 5 || zip.length == 10) {
                    widget.zip_value = zip.substr(0,5);
                    widget.fire();
                } else {
                	alert('Zip Code not correct');
                }
                return false;
            });
    },
    
    omniture: function(extras) {
        // Gather the current Omniture values, adding in the "extras" value.
        //
        for (var i = 0; i < omniture.length; i++) {
            eval("omniture[" + i + "]['value'] = " + omniture[i]["variable"] + ";");
            
            $.each( extras, function(n, v){
                if (n == omniture[i]["name"]) {
                    eval("omniture[" + i + "]['value'] = '" + v + "';");
                }
            });
        }

        // Write these omniture values back to a new s object, then go!
        //
        var snew = s_gi(omniture_id);

        for (i = 0; i < omniture.length; i++) {
            if (omniture[i]["value"] && omniture[i]["value"] != "") {
                s.linkTrackVars += omniture[i]["variable"].replace("s.","") + ",";
                eval( omniture[i]["variable"].replace("s.","snew.") + " = '" + omniture[i]['value'] + "';");
            }
        }
        
        snew.linkTrackEvents = "event22";
        snew.events = "event22";
        snew.tl(this, "o", "Widget");
    }
}

var validate = {
    
    numeric: function(val) {
        if (isNaN(val)) {
            val = val.replace(/[^0-9.-]/g, '').trim() * 1;
        }
        return val;
    },
    zipcode: function(val, defval) {
        val = (validate.numeric(val.replace("-","")) + " ").trim();

        while (val.length < 5) {
            val = "0" + val;
        }
        if (val.length > 5 && val.length < 9) {
            val = val.substr(0,5);
        }
        if (val.length > 9) {
            val = val.substr(0,9);
        }
        
        if (val.length == 9) {
            val = val.substr(0,5) + "-" + val.substr(5,4);
        }
        
        if (val == "00000") {
            val = defval;
        }
        
        return val;
    }
}

var products = {
    init: function() {
        $("#features .option, #secondary div.title").addClass("cnred");
        products.fitTire();
        products.setPrefCat();
        setTimeout(products.setTable, 5);
    },
    
    setPrefCat: function() {
    	$("#perf-cat li[id]").each( function() {
    		var id = $(this).attr("id");
    		
    		var found = false;
    		
    		$("#focus ul.categories li").each( function() {
    			if( $(this).attr("id") == id ) {
    				found = true;
    				return false;
    			}
    		})
    		    		
    		if (found) {
    		
    			$(this).click( function() {
    				var tireCntr = 0;
    				
    				// Hide or display checkmark on filter
    				if ($(this).is('.on')) {
    					$(this).removeClass("on");
    				} else {
    					$(this).addClass("on");
    				}
    				
    				// Check to see if any have been selected
    				if ($("#perf-cat ul li[id]").filter('.on').length > 0) {
    					
						//find all the perf cat's that are set to on and show them
						$("#perf-cat ul li[id]").filter('.on').each( function() {
							var onId = $(this).attr("id");
							
							$("#focus ul.categories li").each( function() {
								if( $(this).attr("id") == onId ) {
									$(this).parents(".style").css("display","block");
									tireCntr += 1;
								}
							})						
						});
					
    					// Find all perf cat's that are not on and set the display off and hide them
    					$("#perf-cat ul li[id]").not('.on').each( function() {
    						var offId = $(this).attr("id");
    						
    						$("#focus ul.categories li").each( function() {
    							if( $(this).attr("id") == offId  || $(this).attr("id") == 'cat-0') {
    								$(this).parents(".style").css("display","none");
    							}
    						})
    					});
    					
    				} else {
    					// None selected so show all
    					$("#focus ul.categories li").each( function() {
    						$(this).parents(".style").css("display","block");
							tireCntr += 1;
						})

    				}
    				
    				// Now reset the Styles Found text
    				$("span.count").html(tireCntr);
    				
    				// resize the page
    				products.setFocusHeight();
    					
    			});
    		} else {
    			$(this).addClass("off");	
    		}
    			
    	});         
    	products.setFocusHeight();
    	
    },
    
    setFocusHeight: function() {
    	
    	var sideHeight = $("#side").outerHeight();
    	var focusHeight = $("#focus").outerHeight();
    	if ($("#side #wide").length == 0) {
    		if (sideHeight > focusHeight) {
    			$("#focus").css("height", sideHeight + "px");
    		}
    		$("#focus").css("padding-left","292px");
    	}
    	$("#focus").css("min-height", sideHeight + "px");
    },
    
    setTable: function() {
        $("table.details").tablesorter().find("th").click( function() {
            setTimeout(products.sortTable,5);
        }).filter(":first").siblings("th:first").click()
        
        //$("table.details").find("tr").hoverClass("hover")
        //    .find("td img.toggle").parents("td").addClass("image");

        $("table.details").find("tr td").not(".image").click( function() {
            var prodtype = $("#main").attr("class").replace(" submenu", "");
            
            widget.deeplink(prodtype + "-products", { 'type' : prodtype, 'itemid' : $(this).parents("tr").attr("id") });
        });
    },
    
    sortTable: function() {
        $("table.details tr:even").not(".head").addClass("alt").removeClass("norm");
        $("table.details tr:odd").not(".head").addClass("norm").removeClass("alt");
    },
    
    fitTire: function() {
        $("#focus.tires .thumb, #focus.wheels .thumb").each( function() {
            var w = $(this).find("img").attr("width") + 20;
            var h = $(this).find("img").attr("height");
            
            var that = $(this).clone(true).insertBefore(this);
            $(that).css("position","absolute").css("float","none").css("right","0").css("z-index","5").css("overflow", "hidden");
            $(this).css("width","1px").css("height", "1px").find(".photo").css("width","1px");
            
            if ($(this).siblings("p.desc").length > 0) {
            	var lh = Math.floor($(this).siblings("p.desc").css("line-height").replace("px",""));
            } else {
            	var lh = 19;
            }
            
            var rh = h;
            var step = Math.round(h / lh);
            for (var i = 0; i < step; i++) {
            	var sw = Math.floor((5*i*lh/9)+225);
            	sw = sw <= w ? sw : w;

            	rh -= lh;
            	lh = rh > lh ? lh : rh;
                
            	$("<div></div>").addClass("spacer").css("width",sw+"px").css("height",lh+"px").insertBefore(this);
            }
            //$("<div></div>").addClass("clear").appendTo($(this).parents("#focus"));
            $(this).remove();
        });
    },
    
    fitOptions: function() {
        var max = 0;
        $("#features .option .body ul").each( function() {
            var height = $(this).outerHeight();
            if (height > max) {
                max = height;
            }
        }).height(max);
    }
   
}
    
var thumblist = {
    pageLabel: "",
    perPage: 1200,
    currentItem: -1,
    
    init: function() {
        $("#focus .thumblist")
            .css("opacity", "1")

            .find("li.area").remove().end()

            .not(".brandlist").each( function() { thumblist.paginate(this, null); }).end()
            
            .parent().siblings("div.title").each( function() {
               // $(this).append("<div class='switch'>Switch View</div>");

                $(this).find("h1 a").each( function() {
                    var href = $(this).attr("href");
                    $(this).parents("div.title").addClass("clickable").find("h1").click( function() {
                        window.open(href,"_self");
                    })
                });
            })
            
            .find("div.switch")
                .toggle( function () {
                    $(this).removeClass("switched");
                    $(this).parents("#focus").find("ul.thumblist")
                        .fadeOut(500, function() {
                            var ul = this;
                            $(ul).fadeIn(200).removeClass("list_rows").addClass("list_grid");
                        })
                        .find("li h4").css("opacity","0.8");
                },  function() {
                    $(this).addClass("switched");
                    $(this).parents("#focus").find("ul.thumblist")
                        .fadeOut(500, function() {
                            var ul = this;
                            $(ul).fadeIn(200).removeClass("list_grid").addClass("list_rows");
                        })
                        .find("li h4").css("opacity","1");
                })
                .hover( function() { $(this).parent().addClass("switching"); },
                        function() { $(this).parent().removeClass("switching"); });
                
        $("#focus .thumblist")
            .find("li").filter(".area, .brand, .style").each( function() {
                $(this).addClass("cnred")
                    .append("<div class='tl cnr'>&nbsp;</div>")
                    .append("<div class='tr cnr'>&nbsp;</div>")
                    .append("<div class='bl cnr'>&nbsp;</div>")
                    .append("<div class='br cnr'>&nbsp;</div>")
                    .append("<div class='connector'>&nbsp;</div>");
            }).end()

            .find("a.image")
            .hover( 
                function() { 
                    $(this).parents("li").addClass("hover");
                    $(this).parents(".list_grid").length > 0 ? $(this).parents("li").find("h4").fadeTo(150,1) : null;
                },
                function() { 
                    $(this).parents("li").removeClass("hover"); 
                    $(this).parents(".list_grid").length > 0 ? $(this).parents("li").find("h4").fadeTo(150,0.8) : null;
            })
            .click( function() {
                var li = $(this).parents("li");
                var target = $("#" + $(this).attr("area"));
                var styles = $(this).siblings(".styles").clone(true);

                $(li).parents(".thumblist").find("li.current").not(li).removeClass("current");
                
                // Hide the other areas.
                $(target).siblings(".area").filter(".open").each( function() {
                    $(this).removeClass("first").removeClass("last")
                        .slideUp(500).find(".styles").fadeTo(500,0);
                });
                
                if ($(li).filter(".current").length > 0) {
                    thumblist.slideUp(li, target, styles);
                    return true;
                }
            
                if ($(target).hasClass("open")) {
                    thumblist.slideUp(li, target, styles);
                }
                
                var delay = function() { thumblist.slideDown(li, target, styles); };
                setTimeout(delay, 500);
            })

            // Keeping around the slide-up/down code for now.
            .unbind("click");
            
        // If it's a product list, we do not allow the switch.
        //
        $("#focus .productlist").siblings(".title").find(".switch").remove();
        
        // Add different pagination to brandlists.
        //
        $("#focus .brandbox").each( function() {
            $(this).find(".brandlist").css("visibility", "visible");
            thumblist.pageBrands($(this).find("ul.brandlist"));
            $(this).siblings("ul.brandoptions").addClass($("#submenu ul:first").attr("class"));
        });
    },
    
    pageBrands: function(bl) {
        var li = $(bl).find("li");
        if (li.length > thumblist.perPage) {
            var start = thumblist.currentItem;
            var end = start + thumblist.perPage;
            for (var i=0; i < li.length; i++) {
                if (i > start && i <= end) {
                    $(li[i]).removeClass("offpage");
                } else {
                    $(li[i]).addClass("offpage");
                }
            }
            
            $(bl).find(".nav").remove();
            var nav = $("<div class='nav'></div>").appendTo(bl);

            if (thumblist.currentItem + thumblist.perPage < li.length - 1) {
                $("<div class='next'>&nbsp; Next Group &#187;</div>").click( function() {
                    thumblist.currentItem += thumblist.perPage;
                    thumblist.pageBrands(bl);
                }).appendTo(nav);
            }
            if (thumblist.currentItem >= 0) {
                $("<div class='prev'>&#171; Previous Group</div>").click( function() {
                    thumblist.currentItem -= thumblist.perPage;
                    thumblist.pageBrands(bl);
                }).appendTo(nav);
            }
            
        }
        
        
    },

    slideUp: function(li, target, styles) {
        $(li).removeClass("current").siblings("li").removeClass("current");
        $(styles).fadeTo(0,0);
        $(target).removeClass("first").removeClass("last").slideUp(500)
            .find(".cnr").hide().end()
            .find(".styles").fadeTo(500,0);
    },
    slideDown: function(li, target, styles) {
        $(li).addClass("current")
            .filter(".first").each( function() { $(target).addClass("first"); }).end()
            .filter(".last").each( function() { $(target).addClass("last"); });
        
        $(target).find(".styles").remove().end().append(styles);
        $(styles).find("ul").append("<li class='clear'>&nbsp;</li>");
        $(target).addClass("open").slideDown(500).find(".styles").fadeTo(500,1);
        
        var delay = function() { thumblist.showCorners(target); };
        setTimeout(delay, 500);
    },
    showCorners: function(target) {
        $(target).find(".cnr").show();
        $(target).filter(".first").find(".tl").hide();
        $(target).filter(".last").find(".tr").hide();
    },
    
    paginate: function(list, start) {
        var li = $(list).find("li").not(".filtered");
        $(li).removeClass("offpage");

        if (!start) {
            $(list).siblings(".thumbnav").remove();
            thumblist.pageLabel = $("#submenu").hasClass("sub-tires") ? "Tires" : thumblist.pageLabel;
            thumblist.pageLabel = $("#submenu").hasClass("sub-wheels") ? "Wheels" : thumblist.pageLabel;
            thumblist.pageLabel = $(list).hasClass("stylelist") ? thumblist.pageLabel.substr(0, thumblist.pageLabel.length - 1) + " styles" : thumblist.pageLabel;
            
            var nav = $("<div></div>").addClass("thumbnav").insertBefore(list);
            $("<div></div>").addClass("label").html(thumblist.pageLabel + " found: <span class='count'>" + $(li).length + "</span>").appendTo(nav);
            var pages = $("<div></div>").addClass("pages").insertBefore($(list).siblings(".thumbnav").find(".label"));
        }
        
        if (!start || start == -1) {
            $(list).siblings(".thumbnav_bottom").empty();
            var pages = $(list).siblings(".thumbnav").find(".pages").empty();
            thumblist.buildNav(list, pages);

            return thumblist.paginate(list, 1);
        }

        if ($(li).length > thumblist.perPage) {
            thumblist.currentItem = start;
            var end = start + thumblist.perPage - 1;

            var current = -1;
            for (var i = 1; i <= $(list).find("li").not(".filtered").length; i++) {
                if (i < start || i > end) {
                    $(li[i-1]).addClass("offpage");
                } else {
                    if (current < 0) current = Math.ceil( i / thumblist.perPage );
                }
            }
            
            $(list).siblings(".thumbnav").find(".current").removeClass("current").end()
                .siblings(".thumbnav").find(".page" + current).addClass("current");
            
            $(list).siblings(".thumbnav").find(".prev").unbind("click").each( function() {
                var prev = start - thumblist.perPage;
                if (prev <= 0) {
                    $(this).addClass("off");
                } else {
                    $(this).removeClass("off").click( function() { thumblist.paginate(list, prev); } );
                }
            });
            
            $(list).siblings(".thumbnav").find(".next").unbind("click").each( function() {
                var next = start + thumblist.perPage;
                if (next > $(li).length) {
                    $(this).addClass("off");
                } else {
                    $(this).removeClass("off").click( function() { thumblist.paginate(list, next); } );
                }
            });
        }

        // page.resize();
    },
    
    buildNav: function(list, pages) {
        $(list).siblings(".thumbnav_bottom").empty();

        var nav = $(list).siblings(".thumbnav");
        var pages = $(pages);
        var itemcount = $(list).find("li").not(".filtered").length;

        var pagecount = Math.ceil(itemcount / thumblist.perPage);
        $(nav).find(".label .count").text(itemcount);
        if (pagecount < 2) return true;
        
        for (var i = 0; i < pagecount; i++) {
            $("<a></a>").addClass("page").addClass("page"+(i + 1)).text(i + 1)
                .each( function() {
                    var np = (i * thumblist.perPage) + 1;
                    if (i == 0) $(this).addClass("current");
                    $(this).click( function() { thumblist.paginate(list, np); } );
                })
                .hoverClass("hover")
                .appendTo(pages);
        }
        $("<a></a>").addClass("page").addClass("prev").addClass("off").html("&lt;")
            .hoverClass("hover")
            .insertBefore($(pages).find("a.page:first"));
        $("<a></a>").addClass("page").addClass("next").html("&gt;")
            .click( function() { thumblist.paginate(list, thumblist.perPage + 1); })
            .hoverClass("hover")
            .insertAfter($(pages).find("a.page:last"));
    
        $(list).siblings(".thumbnav_bottom").remove();
        $(nav).clone(true).addClass("thumbnav_bottom").find(".label").remove().end().insertAfter(list);
    }
}

var tiresize = {
    init: function() {
	
        $("#tires-size").each( function() {
            var ts = $(this).parents("form");
            
            $(this).find("a.go").attr("href",jsv).click( function(e) { tiresize.validate(e, ts); });
            
            $(this).find("h4,h5").hoverClass("hover");
            $(this).find("h4,h5").click( function() {
                var p = $(this).parent();
                var fr = $(p).siblings(".row");
                
                if ($(p).hasClass("open")) {
                    $(p).removeClass("open").find(".hidden,h5").slideUp(500).end().find("h4").slideDown(300);
                    $(fr).filter(".front").find("label").text("Tire size:"); 
                    $(ts).removeClass("rear");
                } else {
                    $(p).addClass("open").find(".hidden,h5").slideDown(500).end().find("h4").slideUp(300);
                    $(fr).filter(".front").find("label").text("Front tire size:"); 
                    $(ts).addClass("rear");
                }
                
            });
            
            $(this).find("select").change( function(e) { tiresize.lookahead(this); })
                .filter(".sel_whl").each( function() { this.selectedIndex = 0; });
            
            $(this).find("input.zip").blur( function() {
                var val = $(this).attr("value").substr(0,5);
                val = validate.zipcode(val, "");
                $(this).attr("value",val);
            });

        });
    },
    
    lookahead: function(sel) {
        var cls = $(sel).attr("class");
        var val = $(sel).attr("value");
        var brandId = $("#frm_tires-size #brandID").attr("value");
        
        var tgt = null;
        var clr = "";
        switch(cls) {
            case "sel_whl":
                tgt = $(sel).siblings("select.sel_rim");
                clr = ".sel_rim,.sel_dia";
            break;
            case "sel_rim":
                tgt = $(sel).siblings("select.sel_dia");
                clr = ".sel_dia";
            break;
        }
        if (clr != "") {
            $(sel).siblings(clr).empty().append("<option value=''>&nbsp;&nbsp;&nbsp;</option>");
        }

        if (tgt) {
            $.ajax({
                url:siteurl + "xml-tiresize.php",
                dataType: "xml",
                type: "POST",
                data: "lookup=" + cls + "&value=" + val,
                timeout: 5000,
                
                // After successful load, create a new UL with values, remove the "loading" text, then "activate" the input.
                //
                success: function(xml) {
                    var list = $("list", xml);
                    if (list.length > 0) {
                        var items = $("item", list);

                        for (var i = 0; i < items.length; i++) {
                            $(tgt).append("<option value='" + $(items[i]).attr("id") + "'>" + $(items[i]).text() + "</option>");
                        }
                    }
                }
            });
        }
        
    },
    
    validate: function(event, frm) {
        var zip = $(frm).find("input.zip").attr("value");
        
        var fw = $(frm).find("select[name='fw']").attr("value");
        var fr = $(frm).find("select[name='fr']").attr("value");
        var fd = $(frm).find("select[name='fd']").attr("value");
        
        var rw = $(frm).find("select[name='rw']").attr("value");
        var rr = $(frm).find("select[name='rr']").attr("value");
        var rd = $(frm).find("select[name='rd']").attr("value");

        var brandNm = $("#frm_tires-size #brandNm").attr("value");
        
        var okaytopost = (fw == "" || fr == "" || fd == "" || zip.trim() == "") ? false: true;
        if ($(frm).hasClass("rear") && (rw == "" || rr == "" || rd == "")) {
            okaytopost = false;
        }
        if (!okaytopost) {
            var frontrear = $(frm).hasClass("rear") ? "(front and rear) " : "";
            alert("Please enter out your zip code and all 3 size attributes " +frontrear+ "in order to check tire availability.");
        } else {
            // build the url
            var url = '#section=tires&zip=' + zip + '&browseBy=size&filter=make&makeName=' + brandNm + '&fw=' + fw + '&fr=' + fr + '&fd=' + fd + 
                ($(frm).hasClass("rear") ? '&staggered=1&rw=' + rw + '&rr=' + rr + '&rd=' + rd : '&staggered=0'); 
            url = flashsite + url;

            $(frm).find("a.go").attr("href",url);
            return true;
        }
        
    }
}

var page = {
    init: function() {
		$(document).pngFix();
		
        $(".cnred").each( function() {
            var cnr = $("<div></div>").addClass("cnr");
            
            $(this).find(".cnr").remove();
            $(cnr).clone(true).addClass("tl").appendTo(this);
            $(cnr).clone(true).addClass("tr").appendTo(this);
            $(cnr).clone(true).addClass("bl").appendTo(this);
            $(cnr).clone(true).addClass("br").appendTo(this);
        });

        // setTimeout(page.resize, 2);
        
        $('a.thickbox').click( function() { 
            $.scrollTo('#top', 300);
            $(window).scroll( function() { window.scrollTo(0,0) } );
        });
        
        var margin = 0;
        var count = 1;
        $('.brandbox .content.tires p').each( function() {
            margin += 180 / (count*count) + 20;
            $(this).css("margin-right", margin + "px");
            count++;
        });
        
        // Replace any <a target=""> values with javascript popups.
        //
        var popup = $("<div></div>").attr("id","popup").appendTo("body");
        var iframe = $("<iframe></iframe>").attr("name","popup")
            .attr("frameborder","0").attr("marginheight","0").attr("marginwidth","0")
            .appendTo(popup);
        var closebox = $("<div></div>").addClass("closeBox").appendTo(popup);
        var close = $("<a></a>").attr("href",jsv).addClass("close").text("Close Window")
            .click( function() {
                $("#popup").hide().find("a.close").slideUp("fast");
            }).appendTo(closebox);
        var overlay = $("<div></div>").addClass("overlay")
            .click( function() { $("#popup a.close").click(); }).appendTo(popup);
        
        $("a").each( function() {
            var t = $(this).attr("target");
            if (t != "") {
                var href = $(this).attr("href");
                $(this).attr("href",jsv).removeAttr("target");

                $(this).click( function() {
                    switch (t) {
                        case "_review_popup":
                            fillIFrame($("#popup").find("iframe"), $("#reviews .list").html(), "reviews");
                            $("#popup").fadeIn(500).find(".close").slideDown();
                        break;
                        
                        case "_tirebuyer_popup":
                            $("#popup").find("iframe").empty().attr("src", href).end()
                                .fadeIn(500);
                            $("#popup").find(".close").slideDown();
                        break;
                        
                        default:
                            var w = window.open(href, t, "menubar=0,location=0,directories=0,status=0,toolbar=0,resizable=1,width=800,height=600");
                            w.focus();
                        break;
                    }
                });
            }
        });
    },

    resize: function() {
        $("#main").each( function() {
            $(this).css("height", "auto");

            var h = 0;
            var mt = $("#main").offset().top;
            var mb = $("#main").height();
            var sb = $("#side").offset().top + $("#side").height() - mt;
            h = sb > mb ? sb : mb;

            $(this).height(h);
        });
    },
    
    scroll: function() {
        // Set it so that whenever the page scrolls, the location of a#current is set to the top of the visible area.
        //
        $.scrollTo('#top', 300);
        $(window).scroll( function() { 
            var scroll = $(document.body).scrollTop();
            $("#current").css("top",scroll+"px");

            $("#popup").css("top", (scroll+70)+'px');
        });
        
    },
    
    foot: function() {
        $("#foot").each( function() {
            
            var maxheight = 0;
            $(this).find("ul").css("height", "auto").each( function() {
                maxheight = ($(this).height() > maxheight) ? $(this).height() : maxheight;
            });
            $(this).find("ul").height(maxheight).end().height(maxheight+15);
            
          }).fadeTo(0,0).fadeTo(100,0).fadeTo(500,1);
        
    }
}

var vis = {
    fit: function(item) {
        var w = Math.ceil($(item).outerWidth());
        var h = Math.ceil($(item).outerHeight());
        var pos = $(item).offset();

        var it = Math.floor(pos.top);
        var ib = it + h;
        var il = Math.floor(pos.left);
        var ir = il + w;
        
        var ww = Math.floor($(window).width());
        var wh = Math.floor($(window).height());
        
        if (it < 0) { $(item).each( function() { $(this).addClass("moved"); }).animate({ top: "5px" }, 300); }
        if (ib > wh) { $(item).each( function() { $(this).addClass("moved"); }).animate({ bottom: "5px" }, 300); }
        
        if (il < 0) { $(item).each( function() { $(this).addClass("moved"); }).animate({ left: "5px" }, 300); }
        if (ir > ww) { $(item).each( function() { $(this).addClass("moved"); }).animate({ right: "5px" }, 300); }
    },
    
    unfit: function(item) {
        var t = parseFloat($(item).css("top").replace("px",""));
        var b = parseFloat($(item).css("bottom").replace("px",""));
        var l = parseFloat($(item).css("left").replace("px",""));
        var r = parseFloat($(item).css("right").replace("px",""));
        
        if (t != 0) $(item).each( function() { $(this).css("top",""); });
        if (b != 0) $(item).each( function() { $(this).css("bottom",""); });
        if (l != 0) $(item).each( function() { $(this).css("left",""); });
        if (r != 0) $(item).each( function() { $(this).css("right",""); });
        
        $(item).removeClass("moved");
    }
}

var classifications = {
    init: function() {
        $("#focus .brandbox ul.types")
            .find("li").hoverClass("hover").click( function() {
                $(this).addClass("selected").siblings("li").removeClass("selected");
                $("#focus .brandbox ul.types-secondary li").hide().filter("[rel='" +$(this).attr("id")+ "']").show().filter(".:first").hover();
            });
        $("#focus .brandbox ul.types-secondary")
            .find("li").hover( function() {
                $(this).addClass("selected").siblings("li").removeClass("selected");
                $("#focus .brandbox ul.types-descriptions li").hide().filter("[rel='" +$(this).attr("id")+ "']").show();
            }).end()
            .find("li:first").click();
            
        setTimeout(classifications.set,100);
    },
    set: function() {
        $("#focus .brandbox ul.types").find("li:first").click();
    }
}

var track = {
    init: function() {
        track.channelAdvisor();
    },
    
    channelAdvisor: function() {
        var url = "http://tracking.searchmarketing.com/welcome.asp?SMCID=1332&x=" + escape(document.referrer);
        
        $("<img></img>").addClass("tracking")
            .attr("width","1").attr("height","1")
            .attr("src", url)
            .appendTo(document.body);
    }
}

var newsletter = {
    init: function() {
        $("#foot form.email").each( function() {
            var frm = this;
            $(this).find("a.btn").attr("href",jsv).click( function() {
                newsletter.validate(frm);
            });
        });
    },
    
    validate: function(frm) {
        var email = $(frm).find("input[name='email']").attr("value");
        if (isValidEmailAddress(email)) {
            newsletter.post(frm, email);
        } else {
            alert("Please enter a valid email address.");
        }
    },
    
    post: function(frm, email) {
        $.ajax({
            url:builder_url + "xml-newsletter.php",
            dataType: "xml",
            type: "POST",
            data: "email=" + escape(email) + "&environment=" + environment,
            timeout: 5000,
            
            // After successful load, alert the user then remove the signup box.
            //
            success: function(xml) {
                var response = $("response", xml);
                if (response.length > 0) {
                    response = $(response[0]).text();
                    switch (response) {
                        case "1":
                            $(frm).find("p").remove();
                            $(frm).append("<p></p>")
                                .find("p").addClass("response").html("Thank you for signing up.").slideDown(800);
                        break;
                        
                        default:
                            alert("There was a problem saving your email address. Please try again later.");
                        break;
                    }
                }
            }
        });
    }
}

$(document).ready( function() {
    products.init();
    widget.init();
    tiresize.init();
    thumblist.init();
    classifications.init();
    newsletter.init();
    page.init();
    track.init();
});

$(window).load( function() {
	products.fitOptions();
	page.foot();
    // Balance any necessary columns.
    $("#focus.dealers ul.cols").vjustify();
    //$("#focus, #side").vjustify();
    
    page.scroll();
});



// Standard functions.
//
String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g,""); }
String.prototype.ltrim = function() { return this.replace(/^\s+/,""); }
String.prototype.rtrim = function() { return this.replace(/\s+$/,""); }

function numOrdAsc(a, b){ return (a-b); }
function numOrdDesc(a, b){ return (b-a); } 

function addCommas(number) {
    number += '';
    x = number.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

function in_array(needle, haystack, argStrict) {
    // Checks if the given value exists in the array  
    // 
    // version: 903.1614
    // discuss at: http://phpjs.org/functions/in_array
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: in_array('van', ['Kevin', 'van', 'Zonneveld']);
    // *     returns 1: true
    var found = false, key, strict = !!argStrict;

    for (key in haystack) {
        if ((strict && haystack[key] === needle) || (!strict && haystack[key] == needle)) {
            found = true;
            break;
        }
    }

    return found;
}

function fillIFrame(frame, html, pageclass) {
    var css = "<link rel='stylesheet' href='" + siteurl +  "css/shared.css' type='text/css' />\n" +
        "<link rel='stylesheet' href='" +siteurl +  "css/boilerplate.css' type='text/css' />\n" +
        "<!--[if IE]><link rel='stylesheet' type='text/css' href='" + siteurl +  "css/boilerplate.ie.css' media='all' /><![endif]-->\n\n";
        
    html = "<html><head>" + css + "</head>" +
        "<body id='popup' class='" + pageclass + "'>" + html + "</body></html>" + css;
    
    $(frame).each( function() {
        var iframeDoc;
        if (this.contentDocument) {
            iframeDoc = this.contentDocument;
        } else if (this.contentWindow) {
            iframeDoc = this.contentWindow.document;
        } else if (window.frames[this.name]) {
            iframeDoc = window.frames[this.name].document;
        }
        
        if (iframeDoc) {
            iframeDoc.open();
            iframeDoc.write(html);
            iframeDoc.close();
        }
    });
}

function isValidEmailAddress(emailAddress) {
    var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
    return pattern.test(emailAddress);
}

jQuery.fn.vjustify=function() {
    var maxHeight=0;
    this.each(function(){
        if (this.offsetHeight>maxHeight) {maxHeight=this.offsetHeight;}
    });
    this.each(function(){
        $(this).height(maxHeight + "px");
        if (this.offsetHeight>maxHeight) {
            $(this).height((maxHeight-(this.offsetHeight-maxHeight))+"px");
        }
    });
};

jQuery.fn.hoverClass = function(value) {
  return this.hover(function() {
    jQuery(this).addClass(value);
    jQuery(this).find("td span.tool").addClass("showtip");
  }, function() {
    jQuery(this).removeClass(value);
     jQuery(this).find("td span.tool").removeClass("showtip");
  });
};
