﻿var ScriptServiceUrl = "../ScriptService.asmx";
function retrieveModels(idx, manu, type) {
    jQuery.ajax({ url: ScriptServiceUrl+"/GetModels", data: '{"idx":"' + idx + '", "manufacturer":"' + manu + '", "catid":"' + type + '"}', success: popModels, type: "POST", contentType: "application/json; charset=utf-8", dataType: "json" });
}

function popModels(data) {
    data = data.d;
    var list = data.Models;
    var select = document.getElementsByName("models" + data.Index)[0];

    select.innerHTML = "";
    for (var i = 0; i < list.length; i++) {
        var op = document.createElement("option");
        op.value = list[i].ID;
        op.innerHTML = list[i].ModelName;
        op.code = list[i].PartCode;
        select.appendChild(op);
    }

    var val = new Function("try { return models" + data.Index + "; } catch(er) { return ''; }")();
    if (val != "")
        jQuery(select).val(val);

    if (list.length > 0) {
        retrievePrice(data.Index, list[0].PartCode);
        retrieveModelImages(data.Index, list[0].ID);
        document.getElementById("partno" + data.Index).innerHTML = list[0].PartCode;
    }
}

function retrievePrice(idx, code) {
    jQuery.ajax({ url: ScriptServiceUrl+"/GetPartPrice", data: '{"idx":"' + idx + '", "code":"' + code + '"}', success: popPrice, type: "POST", contentType: "application/json; charset=utf-8", dataType: "json" });
}

function popPrice(data) {
    data = data.d;
    document.getElementById("price" + data.Index).innerHTML = data.Price;
}

function retrieveModelImages(idx, modelid) {
    jQuery.ajax({ url: ScriptServiceUrl + "/GetModelImages", data: '{"idx":"' + idx + '", "modelid":"' + modelid + '"}', success: popImages, type: "POST", contentType: "application/json; charset=utf-8", dataType: "json" });
};

var j = 0;
function popImages(data) {
    data = data.d;
    var list = data.Images;
    var elm = document.getElementById("imagelist" + data.Index);
    var select = document.getElementsByName("models" + data.Index).item(0);
    var title = select.options.item(select.selectedIndex).innerHTML;

    elm.innerHTML = "";
    for (var i = 0; i < list.length; i++) {
        elm.innerHTML += "<a href='../images/models/" + list[i].ID + ".jpg' rel='model" + j + "' title='" + list[i].Comment + "'>" + (i == 0 ? "Click here to view images." : "") + "</a>";
    }

    if (list.length == 0)
        elm.innerHTML = "There are no images for this model.";
    else
        $("a[rel=model" + j + "]").fancybox({ titlePosition: "inside" });

    j++;
};
