/* v1.01 Added specials v1.02 Properly handled querystring for return to stock page, added viewport autoheight depends on comments,remove features field if has no value, efficiency ratings added, data access security, preload images, added thumbnails v1.03 datasource fetched from jquery.dealerbase.co.nz or jquery service, optional not to provide */ (function ($) { $.fn.stocklist = function (options) { var defaults = $.extend({ ver: 1.03, branchId: 0, datasource: null, pagetype: 0, /*0 - stocklist, 1 - details, 2- compare*/ detailspage: 'http:\/\/' + document.domain + '\/details.html', stockpage: 'http:\/\/' + document.domain + '\/vehicle.html', viewtype: 0, /*0 - galleryview, 1 - listview*/ marker: null, loancalculator: false, loanparam: null, financethisvehicle: false, playvideo: false, maxgalleryview: 12, maxlistview: 5, mediapath: 'https://trademe.tmcdn.co.nz/photoserver', mediapathautobase: 'http://media.autobase.co.nz', jsonpath: 'http://jquery.dealerbase.co.nz', scriptautoload: true, css: null, branches: null, queryvehicleid: 'id', gstincluded: true }, options); var loan = { "PPSR": 10, "rate": 15.95, "processfee": 325, "amount": 0, "deposit": 0, "depositrate": "0.10", "year": 0, "years": 0, "months": 24, "GETPVIFA": function (rate, years, period) { var monthly_rate = rate / period; var factor = 0; var base_rate = 1 + monthly_rate; var denominator = base_rate; for (var i = 0; i < (years * period); i++) { factor += (1 / denominator); denominator *= base_rate; } return factor; } }; var fuelefficiency = { "rating": null, "value": null, "cost": null, "message": null, "toString": function () { var effinfo = []; if (this.rating) { effinfo.push("This vehicle has a Fuel Economy Star Rating of " + this.rating + " out of 6."); } if (this.value && parseFloat(this.value) > 0) { effinfo.push("It consumes " + this.value + "L litres per 100km travelled."); } if (this.cost) { effinfo.push("The Estimated Annual Cost of running this vehicle is " + this.cost + "."); } if (this.message) { effinfo.push(this.message); } //blank fillup if (parseFloat(this.value) == 0) { effinfo.push("

"); } if (effinfo.length > 0) { return effinfo.join(" "); } return null; }, "tooltip": function () { var tooltip = trademe.structure.create("div", "fuel-economy-tooltip", "ui-curve-med ui-shadow-large"); if (this.toString()) { tooltip .append(trademe.structure.create("div", null, "arrow-left-border")) .append(trademe.structure.create("div", null, "arrow-left")) .append(trademe.structure.create("div", null, "fuel-rating-medium fuel-rating-medium-" + this.rating.replace(".", "_"))) .append(trademe.structure.create("h5", null, null).html("Vehicle Fuel Economy Labelling")) .append(trademe.structure.create("p", null, null).html(this.toString())) .append(trademe.structure.create("p", null, "disclaimer").html("Disclaimer: The Fuel Saver Information displayed here is provided for comparative purposes. Your actual cost per year and fuel consumption will vary from that shown, depending on factors such as vehicle condition and any vehicle modifications, driving style, traffic conditions, distance travelled and fuel price variations. You should not expect to meet exactly what this information says. Visit www.fuelsaver.govt.nz to find out more about this information and fuel saver labels, and how to improve fuel economy.")) .css("display", "none"); if ($("#fuel-economy-tooltip").length > 0) { $("#fuel-economy-tooltip").remove(); } $("body").append(tooltip); var tooltipfunc = function () { //do tooltip var _pt = window.setInterval(function () { //if (listing.listingdatafetched != 'undefined' && listing.listingdatafetched == true) { if (defaults.datasource) { $("." + trademe.cssclass.fueleconomyhelp).TradeMeMotorsTooltip({ tooltipid: "fuel-economy-tooltip" }); window.clearInterval(_pt); } //} }, 100); }; //load tooltip script if (defaults.scriptautoload) { $.getScript(defaults.jsonpath + "\/trademe.motors.tooltip.js", function (data, textStatus, jqxhr) { tooltipfunc(); }); } else { tooltipfunc(); } return true; } return null; } }; var carousel = { "create": function () { if ($("#carousel").length > 0) { $("#carousel").remove(); } var c = trademe.structure.create("div", "carousel", null); trademe.structure.target.after(c); var carouselfunc = function () { //populate data var _populate = window.setInterval(function () { //if (listing.listingdatafetched != 'undefined' && listing.listingdatafetched == true) { if (defaults.datasource) { $("#carousel").TradeMeMotorsCarousel({ datasource: defaults.datasource, carouseltype: 0 }); $("#carousel").appendTo("#details-viewport .details-form"); window.clearInterval(_populate); } //} }, 100); }; //load carousel script if (defaults.scriptautoload) { $.getScript(defaults.jsonpath + "\/trademe.motors.carousel.js", function (data, textStatus, jqxhr) { carouselfunc(); }); } else { carouselfunc(); } } }; var listing = { minpage: 0, maxpage: 0, totalpage: 0, currentpage: 0, currentmakeId: 0, currentsortby: 7, currentviewtype: 0, populatecallback: null, init: function () { if (!listing.hasViewport()) { return; } if (!trademe.structure.target.hasClass(trademe.cssclass.viewportcontainer)) { trademe.structure.target.addClass(trademe.cssclass.viewportcontainer); } //load data listing.loaddata(); //do load cookie 1st listing.loadcookie(); if (!listing.hasHeader()) { listing.createHeader(); trademe.structure.fetchlistingextra(); listing.addFilterOption(); } //populate data var _populate = window.setInterval(function () { if (listing.listingdatafetched != 'undefined' && listing.listingdatafetched == true && typeof trademe.selection.fetched != 'undefined' && trademe.selection["fetched"] == true) { if (listing.populatecallback) { listing.populatecallback(); window.clearInterval(_populate); } if (!defaults.scriptautoload) { listing.populatecallback(); window.clearInterval(_populate); } } }, 100); if (!listing.hasFooter()) { listing.createFooter(); } listing.createContainer(); }, hasViewport: function () { if (defaults.pagetype == trademe.enume.pagetype.stock) { return (trademe.structure.target.attr("id") == trademe.id.viewport); } return false; }, hasHeader: function () { return (trademe.structure.target.find("." + trademe.cssclass.header).length > 0); }, hasFooter: function () { return (trademe.structure.target.find("." + trademe.cssclass.footer).length > 0); }, loadcookie: function () { //can be optimized, todo next var cookienames = [{ listingobj: "currentpage", name: "currentpage" }, { listingobj: "currentmakeId", name: "ManufacturerId" }, { listingobj: "currentsortby", name: "SortBy" }, { listingobj: "currentviewtype", name: "viewtype" }, { listingobj: "branchId", name: "branchId"}]; $.each(cookienames, function (i, v) { if (cookie(v.name)) { listing[v.listingobj] = $.IsNumber(cookie(v.name)) ? parseInt(cookie(v.name)) : cookie(v.name); } }); }, createHeader: function () { var header = trademe.structure.create("div", null, trademe.cssclass.header); var galleryview = trademe.structure.create("a", null, trademe.cssclass.galleryview).attr("href", ""); var listview = trademe.structure.create("a", null, trademe.cssclass.listview).attr("href", ""); var label = trademe.structure.create("span", trademe.id.totallisting, null); var makelabel = trademe.structure.create("span", trademe.id.makelabel, null).html("Make"); var sortbylabel = trademe.structure.create("span", trademe.id.sortbylabel, null).html("Sort By"); var makeselect = trademe.structure.create("select", trademe.id.makeoption, null); var sortbyselect = trademe.structure.create("select", trademe.id.sortoption, null); trademe.structure.target .append(header .append(galleryview) .append(listview) .append(label) .append(sortbyselect) .append(sortbylabel) .append(makeselect) .append(makelabel) ); galleryview.bind("click", trademe.event.galleryviewclicked); listview.bind("click", trademe.event.listviewclicked); $("#" + trademe.id.makeoption).bind("change", trademe.event.makeoptionclicked); $("#" + trademe.id.sortoption).bind("change", trademe.event.sortbyclicked); }, createFooter: function () { var footer = trademe.structure.create("div", null, trademe.cssclass.footer); var poweredby = trademe.structure.create("div", null, trademe.cssclass.poweredby).html("Powered by ").append($("").attr("href", "http://www.trademe.co.nz/motors").attr("target", "_new").html("TradeMe Motors")); trademe.structure.target .append(footer.append(poweredby)); var f = window.setTimeout(function () { footer.css({ marginTop: parseInt(trademe.structure.target.css("height").replace("px", "")), width: trademe.structure.target.width() }); window.clearTimeout(f); }, 100); }, createContainer: function () { var container = trademe.structure.create("div", trademe.id.itemcontainerlist, trademe.cssclass.itemcontainerlist); if (trademe.structure.target.find("." + trademe.cssclass.itemcontainerlist).length == 0) { trademe.structure.target.append(container); } }, arrangeGalleryView: function () { if ($(".item-container").length == 0) return; var parentWidth = $(".gallery-view").innerWidth(); var item_per_row = Math.floor(parentWidth / $(".item-container").innerWidth()); //var marginLeft = parseInt($(".item-container").css("marginLeft").replace("px", "")); var marginRight = parseInt($(".item-container").css("marginRight").replace("px", "")); var marginTop = parseInt($(".item-container").css("marginTop").replace("px", "")); //set position of each item-container var item_index = 1; var item_left = 0; var item_top = 0; $.each($(".gallery-view .item-container"), function (i, v) { if (item_index > item_per_row) { item_index = 1; item_left = 0; item_top += $(".item-container").outerHeight() + marginTop; } $(this).css({ 'left': item_left, 'top': item_top }); item_left = ($(".item-container").outerWidth() + marginRight) * item_index; $(this).data("imageindex", 0); //$(this).prepend("
DetailsVideoCompare
"); item_index++; }); }, setpage: function (a) { var maxpaging = listing.currentviewtype == trademe.enume.pagetype.stock ? defaults.maxgalleryview : defaults.maxlistview; listing.totalpage = Math.ceil((a.length) / maxpaging); listing.currentpage = listing.totalpage > 0 && listing.currentpage == 0 ? listing.currentpage = 1 : listing.currentpage; listing.minpage = Math.min(Math.round(Math.max(1, listing.currentpage - (maxpaging / 2))), Math.max(1, listing.totalpage - maxpaging + 1)); listing.maxpage = Math.max(maxpaging, listing.minpage + maxpaging); listing.maxpage = (listing.maxpage > listing.totalpage ? listing.totalpage : listing.maxpage); $("." + trademe.cssclass.pagecontainer).remove(); if (listing.maxpage == 1) return; var pg = trademe.structure.create("div", null, trademe.cssclass.pagecontainer); pg.append(trademe.structure.create("a", null, trademe.cssclass.pageprev + " ui-curve-small ui-shadow-small").html("Prev").attr("href", "")); for (var i = listing.minpage; i <= listing.maxpage; i++) { var p = trademe.structure.create("a", null, trademe.cssclass.pagelink + " ui-curve-small ui-shadow-small" + (listing.currentpage == i ? " selected" : "")).html(i).attr("href", "").data("number", i); pg.append(p); } pg.append(trademe.structure.create("a", null, trademe.cssclass.pagenext + " ui-curve-small ui-shadow-small").html("Next").attr("href", "")); $("." + trademe.cssclass.footer).append(pg); $("." + trademe.cssclass.pagelink).bind("click", trademe.event.pagelinkclicked); $("." + trademe.cssclass.pagenext).bind("click", trademe.event.pagenextclicked); $("." + trademe.cssclass.pageprev).bind("click", trademe.event.pageprevclicked); if (listing.currentpage <= 1) { $("." + trademe.cssclass.pageprev).hide(); } else { $("." + trademe.cssclass.pageprev).show(); } if (listing.currentpage >= listing.maxpage) { $("." + trademe.cssclass.pagenext).hide(); } else { $("." + trademe.cssclass.pagenext).show(); } }, populate: function () { if (!defaults.datasource) { return; } var container = trademe.structure.target.find("." + trademe.cssclass.itemcontainerlist); container.html(""); container.focus(); container.removeClass("gallery-view").removeClass("list-view"); //get from querystring var _datasource = []; $.each(defaults.datasource, function (i, v) { if (trademe.structure.foundinquery({ "ManufacturerId": v.manufacturerId, "ModelId": v.modelId, "PriceFrom": v.price.replace("$", "").replace(",", ""), "PriceTo": v.price.replace("$", "").replace(",", ""), "TransmissionTypeId": v.transmissiontypeid, "OdometerFrom": v.odometer.replace(",", ""), "OdometerTo": v.odometer.replace(",", ""), "VehicleTypeId": v.vehicletypeid, "new": v.isnew == "true" ? "1" : "0", "specials": v.isspecial == "true" ? "1" : "0", "intransit": typeof v.details.Status != 'undefined' && v.details.Status.toLowerCase() == "in transit" ? "1" : "0", "branchId": v.branchId }) && trademe.structure.foundinfilter({ "ManufacturerId": v.manufacturerId })) { _datasource.push(v); } }); //lets sort _datasource = trademe.structure.sortthis(_datasource); //set page control listing.setpage(_datasource); //initially display all counts if (_datasource.length > 0) { $("#" + trademe.id.totallisting).html("We have " + _datasource.length + " vehicle(s) listed."); } //gallery view if (listing.currentviewtype == trademe.enume.viewtype.galleryview) { container.addClass("gallery-view"); $.each(_datasource.slice((listing.currentpage * (defaults.maxgalleryview)) - defaults.maxgalleryview, listing.currentpage * (defaults.maxgalleryview)), function (i, v) { /**************/ //create items var item = trademe.structure.create("div", "item-" + v.id, "item-container"); var img = trademe.structure.create("img", null, "preview-image").attr("src", v.images.length > 0 ? defaults.mediapath + "/Med/" + v.images[0].split('_')[1] + ".jpg" : defaults.jsonpath + "\/images\/imageunavailable_medium.png"); var price = trademe.structure.create("label", null, "price").html(defaults.gstincluded ? v.price : listing.gstexclude(v.price)); //var year = trademe.structure.create("label", null, "year").html(v.year); var pricelabel = trademe.structure.create("label", null, "pricelabel").html("Price"); var title = trademe.structure.create("label", null, "title").html((v.year ? v.year + " " : "") + "" + v.makemodel + "" + (v.modeldetails ? " " + v.modeldetails : "")); var previcon = trademe.structure.create("a", null, "prev-icon").attr("href", ""); var nexticon = trademe.structure.create("a", null, "next-icon").attr("href", ""); var imgindex = trademe.structure.create("span", null, "img-index").html((v.images.length > 0 ? "1" + " of " + v.images.length : "")); if (v.images.length < 2) { previcon.attr("style", "display:none;"); nexticon.attr("style", "display:none;"); } item.append("\r\n"); item.append(img).append("\r\n") .append(price).append("\r\n") .append(pricelabel).append("\r\n") .append(title).append("\r\n") .append(previcon).append("\r\n") .append(imgindex).append("\r\n") .append(nexticon).append("\r\n"); //execute extrascript if (typeof listing.fetchedlistingextra != 'undefined' && listing.fetchedlistingextra == true) { if (listing.listingextra.display) { $.each(listing.listingextra.display, function (_i, _v) { //type object - function, array if (_v["label"] && _v["label"].indexOf("|") > -1 && typeof v[_v["label"].split("|")[0]][_v["label"].split("|")[1]] != "undefined") { var label = trademe.structure.create("label", _v["label"].split("|")[0].replace("#", "").toLowerCase() + "-" + _v["label"].split("|")[1].replace("#", "").toLowerCase(), null); label.html(_v["label"].split("|")[1] + " " + v[_v["label"].split("|")[0]][_v["label"].split("|")[1]]); item.append(label); } }); } } container.append("\r\n"); container.append(item.clone()).append("\r\n"); item = null; /**************/ }); listing.arrangeGalleryView(); $(".item-container a.prev-icon").bind("click", trademe.event.prevclick); $(".item-container a.next-icon").bind("click", trademe.event.nextclick); } //[2] list view type if (listing.currentviewtype == trademe.enume.viewtype.listview) { container.addClass("list-view"); $.each(_datasource.slice((listing.currentpage * (defaults.maxlistview)) - defaults.maxlistview, listing.currentpage * (defaults.maxlistview)), function (i, v) { if (trademe.structure.foundinquery({ "ManufacturerId": v.manufacturerId, "ModelId": v.modelId, "PriceFrom": v.price.replace("$", "").replace(",", ""), "PriceTo": v.price.replace("$", "").replace(",", ""), "TransmissionTypeId": v.transmissiontypeid, "OdometerFrom": v.odometer.replace(",", ""), "OdometerTo": v.odometer.replace(",", ""), "VehicleTypeId": v.vehicletypeid, "new": v.isnew == "true" ? "1" : "0", "specials": v.isspecial == "true" ? "1" : "0" })) { //create items var item = trademe.structure.create("div", "item-" + v.id, "item-container"); var img = trademe.structure.create("img", null, "preview-image").attr("src", v.images.length > 0 ? defaults.mediapath + "/Med/" + v.images[0].split('_')[1] + ".jpg" : defaults.jsonpath + "\/images\/imageunavailable_medium.png"); var price = trademe.structure.create("label", null, "price").html(defaults.gstincluded ? v.price : listing.gstexclude(v.price)); var title = trademe.structure.create("label", null, "title").html((v.year ? v.year + " " : "") + "" + v.makemodel + "" + (v.modeldetails ? " " + v.modeldetails : "")); var description = trademe.structure.create("label", null, "description").html(v.description); item.append("\r\n"); item.append(img).append("\r\n") .append(price).append("\r\n") .append(title).append("\r\n") .append(description).append("\r\n"); //execute extrascript if (typeof listing.fetchedlistingextra != 'undefined' && listing.fetchedlistingextra == true) { if (listing.listingextra.display) { $.each(listing.listingextra.display, function (_i, _v) { //type object - function, array if (_v["label"] && _v["label"].indexOf("|") > -1 && typeof v[_v["label"].split("|")[0]][_v["label"].split("|")[1]] != "undefined") { var label = trademe.structure.create("label", _v["label"].split("|")[0].replace("#", "").toLowerCase() + "-" + _v["label"].split("|")[1].replace("#", "").toLowerCase(), null); label.html(_v["label"].split("|")[1] + " " + v[_v["label"].split("|")[0]][_v["label"].split("|")[1]]); item.append(label); } }); } } container.append("\r\n"); container.append(item.clone()).append("\r\n"); } }); var marginTop = parseInt($(".item-container").css("marginTop").replace("px", "")); var item_top = 0; $.each($(".list-view .item-container"), function (i, v) { $(this).css({ 'top': item_top }); item_top += $(".item-container").outerHeight() + marginTop; }); } //bind item click $(".item-container").bind("click", trademe.event.itemclick); }, populatemakeoption: function (func) { if (typeof trademe.selection.fetched == 'undefined') { $.support.cors = true; $.getJSON(defaults.jsonpath + "/quicksearchdata.js?branchId=" + defaults.branchId + "&callback=" + (browser && browser.msie ? "?" : ""), function (data) { var json = data; if (typeof trademe.selection.fetched == 'undefined') { trademe.selection["fetched"] = true; } trademe.selection["makeoption"] = json ? json["manufacturermodel"] : "{}"; var c = window.setTimeout(function () { $("#" + trademe.id.makeoption).html(""); $("#" + trademe.id.makeoption).append($("").attr("value", "0").attr("selected", "true").html("All Makes")); $.each(trademe.selection.makeoption, function (i, v) { $("#" + trademe.id.makeoption).append($("").attr("value", v.ManufacturerId).html(v.ManufacturerName)); }); if (listing.currentmakeId) { $("#" + trademe.id.makeoption).val(listing.currentmakeId); } $.each(trademe.selection.sortoption, function (i, v) { $("#" + trademe.id.sortoption).append($("").attr("value", v.value).html(v.display)); }); if (listing.currentsortby) { $("#" + trademe.id.sortoption).val(listing.currentsortby); } if (func) { func(); } window.clearTimeout(c); }, 10); }) .fail(function (jqxhr, settings, exception) { var x = 0; }); } }, addFilterOption: function () { listing.populatemakeoption(trademe.structure.loadbranches); }, loaddefaultstyle: function () { if ($("head").find("link#_stock-list-theme").length == 0) { var link = trademe.structure.create("link", "_stock-list-theme", null); var url = defaults.jsonpath + "/css/trademe.motors.stocklist.css"; link.attr("rel", "stylesheet").attr("type", "text/css").attr("href", url); //for IE if ((typeof $.browser != 'undefined' && $.browser.msie) || document.createStyleSheet) { document.createStyleSheet(url); } $("head").prepend(link); } }, loaddata: function () { if (defaults.datasource == null) { if (listing.listingdatafetched != 'undefined' && listing.listingdatafetched == true) { return; } $.support.cors = true; $.getJSON(defaults.jsonpath + "/trademe.motors.stocklistdata.js?branchId=" + defaults.branchId + "&callback=" + (browser && browser.msie ? "?" : ""), function (data) { if (typeof listing.listingdatafetched == 'undefined' && data) { listing["listingdatafetched"] = true; } defaults.datasource = data; }) .fail(function (jqxhr, settings, exception) { var x = 0; }); } }, loaddatascript: function (filename, containerobject, postfunc) { $.support.cors = true; //$.getJSON(defaults.jsonpath + "/" + filename + "?branchId=" + defaults.branchId + "&callback=" + (browser && browser.msie ? "?" : "?"), function (data) { $.getJSON(defaults.jsonpath + "/" + filename + "?branchId=" + (typeof listing.currentbranchId == "undefined" || listing.currentbranchId == 0 ? defaults.branchId : listing.currentbranchId) + "&callback=" + (browser && browser.msie ? "?" : "?"), function (data) { if (typeof trademe.structure[containerobject + "fetched"] == 'undefined' && data) { trademe.structure[containerobject + "fetched"] = true; } trademe.structure[containerobject] = data; if (postfunc) { postfunc(); } }) .error(function (jqxhr, settings, exception) { var x = 0; }); }, gstexclude: function (price) { return price ? $.currency(Math.round(parseFloat(price.replace("$", "").replace(",", "")) / 1.15), { roundToDecimalPlace: false }) : "$0"; } }; var extracss = { "load": function (css) { if (!css) return; var style = {}; if ($("head style").length == 0) { style = $("style"); style.attr("type", "text/css"); $("head").append(style); } else { style = $("head style:first"); } //do insert the style $.each(css, function (k, v) { var val = []; $.each(v, function (_k, _v) { val.push(_k + ": " + _v); }); style.append(k + " {" + val.join(";\r\n") + "}"); }); } }; var printform = { "print": function () { if (!defaults.datasource) return; var vehicleId = querystring("id") ? querystring("id") : 0; $.each(defaults.datasource, function (i, v) { if (v.id == vehicleId) { if ($("#print-form").length > 0) { $("#print-form").remove(); } //load branch details listing.loaddatascript("trademe.motors.branchdata.js", "branchdata", function () { var branch = trademe.structure["branchdata"]; var frameName = ("printer-" + (new Date()).getTime()); var jFrame = $("