// ******************************************************************
// cdsCADService.js
//
// Copyright (c) 2007 Catalog Data Solutions. All Rights Reserved.
//
// Displays a schematic image with hotlinks to products or other
// schematics
//
// Note: For some retarded reason, attribute.default doesn't work
// in IE, you have to use attribute["default"].
// ******************************************************************
if (typeof ajaxCaller != "object") document.write('<script type="text/javascript" src="scripts/ajaxCaller.js"></script>');
if (typeof fixUrl != "function") document.write('<script type="text/javascript" src="scripts/cdsUtilities.js"></script>');
if (pageArguments === null) parsePageArguments();

function cdsCADService() {
    this.elementId = null;
    this.product = entities.ProductDetailsEntity.productNumber;
    this.attributes = entities.CADEntity.attributes;
    this.viewFormat = properties["cadService.viewerFormat"];
    this.view2DFormat = properties["cadService.viewer2DFormat"];
    this.downloadFormats = properties["cadService.cadDownloadFormats"];
    this.downloadButtonLabel = properties["cadService.downloadButtonLabel"];
    this.view3DButtonLabel = properties["cadService.view3DButtonLabel"];
    this.view2DButtonLabel = properties["cadService.view2DButtonLabel"];
    this.waitingForServer = false;
    this.downloadIsView = false;
    this.format = null;

    // =====================================================
    // initialize the cad service widget
    // =====================================================
    this.init = function() {
    }

    // =====================================================
    // event handler for clicking download button
    // =====================================================
    this.onClickDownload = function() {
        if (this.waitingForServer) return;
        var e = document.getElementById("cdsCADDownloadFormatList");
        this.format = e.options[e.selectedIndex].value;
        if (this.format == null || this.format == "none") {
            alert("Please select a download format.");
            return;
        }
        this.downloadIsView = false;
        this.getCADUrl(this.format);
    }

    // =====================================================
    // event handler for clicking view button
    // =====================================================
    this.onClickView = function() {
        if (this.waitingForServer) return;
        this.format = this.viewFormat;
        this.downloadIsView = true;
        this.getCADUrl(this.format);
    }

    // =====================================================
    // event handler for clicking 2D view button
    // =====================================================
    this.onClickView2D = function() {
        if (this.waitingForServer) return;
        this.format = this.view2DFormat;
        this.downloadIsView = true;
        this.getCADUrl(this.format);
    }

    // =====================================================
    // event handler for clicking download button
    // =====================================================
    this.doOnBlurAttribute = function(idx) {
        var e = document.getElementById("cdsShowProductCADAttribute" + idx);
        if (this.attributes[idx].type.toUpperCase() != "STRING") {
            var val = parseFloat(e.value);
            var vals = this.attributes[idx].values.split(",");

            if (val == null || isNaN(val) || val < vals[0] || val > vals[1]) {
                alert("Please enter a value between " + vals[0] + " and " + vals[1] + ".");
                document.getElementById("cdsShowProductCADAttribute" + idx).value = this.attributes[idx]["default"];
                return 0;
            }
        }
        return 1;
    }

    // =====================================================
    // ajax server calls
    // =====================================================
    this.redirectToCad = function(url) {
        var div = document.getElementById("cdsCADModelProgress");
        document.body.removeChild(div);
        this.waitingForServer = false;
        if (!this.downloadIsView) {
            location.href = fixUrl(url);
        } else {
            if (this.format == "pview") window.open("viewpvl.jsp?ms=" + encodeURIComponent(fixUrl(url)), "viewer_window");
            else if (this.format == "edrawings") window.open("viewedz.jsp?ms=" + encodeURIComponent(fixUrl(url)), "viewer_window");
            else if (this.format == "3dpdf") window.open(fixUrl(url), "viewer_window");
            else if (this.format == "pdf") window.open(fixUrl(url), "viewer_window");
        }
    }

    this.getSearchCallback = function(text, headers, callingContext) {
        eval("var o = " + text + ";");

        // check for authentication errors
        if (o.error != null && o.error == "authenticationRequired") {
            var tloc = location.href;
            var pos = tloc.indexOf("?");
            if (pos != -1) tloc = "service" + tloc.substring(pos);
            location.href = "service?domain=" + domain + "&command=showLogin&redirect=" + encodeURIComponent(tloc);

        } else {
            var url = o.url;
            var isView = widgets.cdsCADService.downloadIsView;

            var div = document.getElementById("cdsCADModelProgress");
            while (div.hasChildNodes()) div.removeChild(div.lastChild);
            var table = document.createElement("table");
            div.appendChild(table);
            var tbody = document.createElement("tbody");
            table.appendChild(tbody);
            var tr = document.createElement("tr");
            tbody.appendChild(tr);
            var td = document.createElement("td");
            tr.appendChild(td);
            var str = document.createElement("strong");
            td.appendChild(str);
            str.appendChild(document.createTextNode((url != null) ? "Done!" : "Error!"));

            td = document.createElement("td");
            tr.appendChild(td);
            td.innerHTML = (url != null) ? "Click <a href='javascript:widgets.cdsCADService.redirectToCad(\"" + url + "\")'>here</a> to " + ((isView) ? "view" : "download") + " your model." : "There was an error generating the model you have requested.  Please wait a few minutes and try again.";
        }
    }

    this.getCADUrl = function(format) {
        var i, o = {}, s = "service?domain=" + domain + "&entity=CAD&product=" + encodeURIComponent(this.product) + "&format=" + encodeURIComponent(format) + "&xarg=" + (new Date()).getTime();
        // add attributes
        if (this.attributes != null) {
            for (i = 0; i < this.attributes.length; i++) {
                var e = document.getElementById("cdsShowProductCADAttribute" + i);
                if (this.attributes[i].type.toUpperCase() == "STRING") {
                    var val = e[e.selectedIndex].value;
                    var name = this.attributes[i].parameter;
                    o[name] = val;
                } else if (this.attributes[i].type.toUpperCase() != "SET") {
                    var val = parseFloat(e.value);
                    var vals = this.attributes[i].values.split(",");
                    if (val == null || isNaN(val)) {
                        return;
                    }
                    var name = this.attributes[i].parameter;
                    o[name] = val;
                }
            }
        }
        if (typeof cdsHandleDynamicAttributes === "function") {
            o = cdsHandleDynamicAttributes(o);
        }
        for (i in o) {
            s += "&" + i + "=" + encodeURIComponent(o[i]);
        }

        this.waitingForServer = true;

        if (pageArguments["debug"] === "true") {
            var pos = location.href.lastIndexOf("/");
            var l = location.href.substring(0, pos + 1);
            alert(l + s);
            // return;
        }

        var div = document.createElement("div");
        div.setAttribute("id", "cdsCADModelProgress");
        document.body.appendChild(div);
        var table = document.createElement("table");
        div.appendChild(table);
        var tbody = document.createElement("tbody");
        table.appendChild(tbody);
        var tr = document.createElement("tr");
        tbody.appendChild(tr);
        var td = document.createElement("td");
        tr.appendChild(td);
        td.rowSpan = "2";
        var img = document.createElement("img");
        td.appendChild(img);
        img.setAttribute("src", "images/progress_animation.gif");
        td = document.createElement("td");
        tr.appendChild(td);
        var str = document.createElement("strong");
        td.appendChild(str);
        str.appendChild(document.createTextNode("Generating Model"));
        tr = document.createElement("tr");
        tbody.appendChild(tr);
        td = document.createElement("td");
        tr.appendChild(td);
        td.appendChild(document.createTextNode("The model you requested is being generated.  This could take up to a minute, please wait..."));

        ajaxCaller.getPlainText(s, this.getSearchCallback);
    }

    // =====================================================
    // display ourself
    //
    // Returns it's own element to be embedded in an element
    // within the calling script.
    // =====================================================
    this.display = function() {
        var odiv = document.createElement("div");
        var div = document.createElement("div");
        odiv.appendChild(div);

        var btn = document.createElement("input");
        btn.setAttribute("type", "button");
        btn.setAttribute("value", this.downloadButtonLabel);
        btn.controller = this;
        btn.onclick = function(e) { this.controller.onClickDownload(); };
        div.appendChild(btn);

        var sel = document.createElement("select");
        sel.setAttribute("id", "cdsCADDownloadFormatList");
        div.appendChild(sel);

        var opt = document.createElement("option");
        opt.setAttribute("value", "none");
        opt.appendChild(document.createTextNode("Choose Format"));
        opt.setAttribute("selected", "selected");
        sel.appendChild(opt);

        var flist = this.downloadFormats.split("|");
        for (var i = 0; i < flist.length; i++) {
            var flistList = flist[i].split("=");
            var name = flistList[0];
            var value = flistList[1];
            opt = document.createElement("option");
            opt.setAttribute("value", value);
            opt.appendChild(document.createTextNode(name));
            sel.appendChild(opt);
        }

        div = document.createElement("div");
        odiv.appendChild(div);

        btn = document.createElement("input");
        btn.setAttribute("type", "button");
        btn.setAttribute("value", this.view3DButtonLabel);
        btn.controller = this;
        btn.onclick = function(e) { this.controller.onClickView(); };
        div.appendChild(btn);

        // 2d view button
        if (this.view2DFormat && this.view2DFormat !== "") {
            div = document.createElement("div");
            odiv.appendChild(div);
            btn = document.createElement("input");
            btn.setAttribute("type", "button");
            btn.setAttribute("value", this.view2DButtonLabel);
            btn.controller = this;
            btn.onclick = function(e) { this.controller.onClickView2D(); };
            div.appendChild(btn);
        }

        return odiv;
    }
}




