﻿if (typeof (window['wsHelperObj']) == 'undefined') {
    var wsHelperObj = new wsHelper();
}
function wsHelper() {
    this.opacity = 0.5;
    this.domain = window.location.protocol + '//' + window.location.host;
    this.lists = {};

    this.GetData = function(webBasedUrl, getMode, itemDetails, completeFunction) {
        // First we get the web url from the itemUrl.
        //Web/Library/ItemSpecific
        //bl/specchem/en-us/Pages/12dimethylcyclohexane.aspx

        var itemParts = webBasedUrl.toString().split('\/');
        var webUrl = "";

        var j = 0;
        for (i = itemParts.length - 1; i >= 0; i--) {
            if (j >= 2) {
                webUrl = itemParts[i] + '/' + webUrl;
            }
            j++;
        }
        // Correct webUrl if we were just given the top level domain.
        if (webUrl == "http:/" || webUrl == "https:/") { webUrl = this.domain; }
        if (webUrl.lastIndexOf('/') != webUrl.length - 1) { webUrl = webUrl + '/'; }
        itemDetails.webUrl = webUrl;

        // Check to see if the listGuid was passed to us.
        if (itemDetails.listGuid != undefined && itemDetails.listGuid != null && itemDetails.listGuid != '') {
            this.fetchItemXml(itemDetails, completeFunction);
        } else if (this.lists[(webUrl + '_sep_' + itemDetails.listName)] == undefined || this.lists[(webUrl + '_sep_' + itemDetails.listName)] == null) {
            // Now that we've got the web url, we need to call the lists webservice to get the guid of the listName.
            jQuery.ajax({
                url: webUrl + "/_vti_bin/lists.asmx",
                type: "POST",
                dataType: "xml",
                data: this.GetListRequest(itemDetails.listName),
                context: this,
                complete: function(result, textStatus) {
                    if (textStatus == "success") {
                        this.setListGuid(result, textStatus, itemDetails);
                        itemDetails.listGuid = this.lists[(webUrl + '_sep_' + itemDetails.listName)];
                        if (getMode == "ListItem" || getMode == "ListItems") {
                            this.fetchItemXml(itemDetails, completeFunction);
                        }
                    }
                },
                contentType: "text/xml; charset=\"urf-8\""
            });
        } else {
            itemDetails.listGuid = this.lists[(webUrl + '_sep_' + itemDetails.listName)]; ;
            // We've already got the guid for that list.
            this.fetchItemXml(itemDetails, completeFunction);
        }


    };

    this.fetchItemXml = function(itemDetails, completeFunction) {
        jQuery.ajax({
            url: itemDetails.webUrl + "/_vti_bin/dspsts.asmx",
            type: "POST",
            dataType: "xml",
            data: this.GetDspQueryRequest(itemDetails.listGuid, itemDetails.fieldsXml, itemDetails.whereXml, itemDetails.orderByXml),
            context: this,
            complete: function(result, textStatus) {
                itemDetails.ajaxResult = result.responseText;
                itemDetails.ajaxStatus = textStatus;
                completeFunction(itemDetails);
            },
            contentType: "text/xml; charset=\"urf-8\""
        });
    }

    this.setListGuid = function(result, textStatus) {
        if (textStatus == "success") {
            var ID = jQuery(result.responseText).find('List').attr('ID');
            var webUrl = jQuery(result.responseText).find('List').attr('WebFullUrl');
            if (webUrl.lastIndexOf('/') != webUrl.length - 1) { webUrl = webUrl + '/'; }
            var listName = jQuery(result.responseText).find('List').attr('Title');

            this.lists[(this.domain + webUrl + '_sep_' + listName)] = ID;
        }
    };
}
wsHelper.prototype.GetItem = function(itemUrl, listName, itemID, completeFunction) {
    this.GetData(
        itemUrl,
        "ListItem",
        {
            listName: listName,
            itemID: itemID,
            fieldsXml: '<Field Name="Title" /><Field Name="EncodedAbsUrl" />',
            whereXml: '<Where><Eq><FieldRef Name="ID" /><Value Type="Counter">' + itemID + '</Value></Eq></Where>',
            orderByXml: ''
        },
        completeFunction
    );
};

wsHelper.prototype.GetTDSUrl = function(productPageUrl, itemID, completeFunction) {
    this.GetData(
        productPageUrl,
        "ListItem",
        {
            listName: "TDS Library",
            itemID: itemID,
            fieldsXml: '<Field Name="Title" /><Field Name="EncodedAbsUrl" />',
            whereXml: '<Where><Eq><FieldRef Name="ID" /><Value Type="Counter">' + itemID + '</Value></Eq></Where>',
            orderByXml: ''
        },
        completeFunction
    );
};
wsHelper.prototype.GetSpecificationUrl = function(productPageUrl, itemID, completeFunction) {
    this.GetData(
        productPageUrl,
        "ListItem",
        {
            listName: "Specification Library",
            itemID: itemID,
            fieldsXml: '<Field Name="Title" /><Field Name="EncodedAbsUrl" />',
            whereXml: '<Where><Eq><FieldRef Name="ID" /><Value Type="Counter">' + itemID + '</Value></Eq></Where>',
            orderByXml: ''
        },
        completeFunction
    );
};
wsHelper.prototype.GetMSDSDetails = function(specificationID, completeFunction) {
    var hiddenListGuidElement = document.getElementById("mpHiddenMSDSListID");
    var msdsListGuid = "";
    if (hiddenListGuidElement != null && hiddenListGuidElement.innerHTML != "") {
        msdsListGuid = hiddenListGuidElement.innerHTML;
    }
    this.GetData(
        this.domain,
        "ListItems",
        {
            listName: "MSDS Library",
            listGuid: msdsListGuid,
            specificationID: specificationID,
            fieldsXml: '<Field Name="EncodedAbsUrl" /><Field Name="MSDSGenerationVariant" /><Field Name="MSDSLanguage" />',
            whereXml: '<Where><Eq><FieldRef Name="MSDSSpecificationID" /><Value Type="Text">' + specificationID + '</Value></Eq></Where>',
            orderByXml: '<OrderField Name="MSDSGenerationVariant"/><OrderField Name="MSDSLanguage"/>'
        },
        completeFunction
    );
};

wsHelper.prototype.GetListRequest = function(listName) {
    var r = '<?xml version="1.0" encoding="utf-8"?>' +
            '<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">' +
                '<soap:Body>' +
                    '<GetList xmlns="http://schemas.microsoft.com/sharepoint/soap/">' +
                        '<listName>' + listName + '</listName>' +
                    '</GetList>' +
                '</soap:Body>' +
            '</soap:Envelope>';
    return r;
};
wsHelper.prototype.GetDspQueryRequest = function(listGuid, fieldsXml, whereXml, orderByXml) {
    var r = '<?xml version="1.0" encoding="utf-8"?>' +
            '<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">' +
                '<soap:Header>' +
                    '<request document="content" method="query" xmlns="http://schemas.microsoft.com/sharepoint/dsp" service="DspSts" />' +
                    '<versions xmlns="http://schemas.microsoft.com/sharepoint/dsp">' +
                        '<version>1.0</version>' +
                    '</versions>' +
                '</soap:Header>' +
                '<soap:Body>' +
                    '<queryRequest xmlns="http://schemas.microsoft.com/sharepoint/dsp">' +
                        '<dsQuery select="/list[@id=\'' + listGuid + '\']" resultContent="dataOnly" columnMapping="attribute" resultRoot="Rows" resultRow="Row">' +
                        '<Query>' +
                            '<Fields>' +
                                fieldsXml +
                            '</Fields>' +
                            whereXml +
                            '<OrderBy>' +
                                orderByXml +
                            '</OrderBy>' +
                        '</Query>' +
                      '</dsQuery>' +
                    '</queryRequest>' +
                  '</soap:Body>' +
                '</soap:Envelope>';
    return r;
};
wsHelper.prototype.getDownloadAnchor = function(webUrl, docUrl, innerHTML) {

    var ancHTML = "<a href='javascript:STSNavigate(\"" + webUrl + "_layouts/CPChem/download.aspx?sourceUrl=\" + escapeProperly(\"" + docUrl + "\"))'>" + innerHTML + "</a>";
    return ancHTML;
};
wsHelper.prototype.GetTDS = function(pageUrl, lookupValue) {
    jQuery.fn.colorbox({ opacity: this.opacity, html: "<div style='padding: 1em'><img src='/_layouts/images/cpchem/internet/ajax-loading.gif' alt='loading' /></div>" });
    var itemID;
    if (lookupValue.indexOf(';') != -1) {
        itemID = lookupValue.substring(0, lookupValue.indexOf(';'));
    } else {
        itemID = lookupValue;
    }
    this.GetTDSUrl(pageUrl, itemID, this.DisplayTDS);
};
wsHelper.prototype.DisplayTDS = function(itemDetails) {
    if (itemDetails.ajaxStatus == "success") {
        // Build html to display
        var htmlDisp = '<table border="0" cellspacing="0" cellpadding="0" class="fileDisp_tbl">' +
                  '<tr class="fileDisp_lbl">' +
                      '<td colspan="5" class="fileDisp_left fileDisp_right">Technical Data Sheets</td>' +
                  '</tr>';
        jQuery(itemDetails.ajaxResult).find('Row').each(function(i) {
            htmlDisp += '<tr class="fileDisp_bottom">';
            var dAnc = wsHelperObj.getDownloadAnchor(itemDetails.webUrl, jQuery(this).attr('EncodedAbsUrl'), "Download");
            htmlDisp += '<td class="fileDisp_left" style="text-decoration:none;">&nbsp;</td><td colspan="2">' + jQuery(this).attr('Title') + '</td><td><a href="' + jQuery(this).attr('EncodedAbsUrl') + '" target="_blank">View</a></td><td class="fileDisp_right">' + dAnc + '</td></tr>';
        });
        htmlDisp += '</table>';
        jQuery.fn.colorbox({ opacity: this.opacity, html: htmlDisp });
    } else {
        jQuery.fn.colorbox({ opacity: this.opacity, html: '<div style="padding: 1em">There was an error looking up the TDS for this product.<br />Please <a href="/en-us/Pages/contactus.aspx">contact us</a> for more information about this product.</div>' });
    }
};

wsHelper.prototype.GetSpecification = function(pageUrl, lookupValue) {
    jQuery.fn.colorbox({opacity: this.opacity, html: "<div style='padding: 1em'><img src='/_layouts/images/cpchem/internet/ajax-loading.gif' alt='loading' /></div>" });
    var itemID;
    if (lookupValue.indexOf(';') != -1) {
        itemID = lookupValue.substring(0, lookupValue.indexOf(';'));
    } else {
        itemID = lookupValue;
    }
    this.GetSpecificationUrl(pageUrl, itemID, this.DisplaySpecification);
};
wsHelper.prototype.DisplaySpecification = function(itemDetails) {
    if (itemDetails.ajaxStatus == "success") {
        // Build html to display
        var htmlDisp = '<table border="0" cellspacing="0" cellpadding="0" class="fileDisp_tbl">' +
                  '<tr class="fileDisp_lbl">' +
                      '<td colspan="5" class="fileDisp_left fileDisp_right">Specification Documents</td>' +
                  '</tr>';
        jQuery(itemDetails.ajaxResult).find('Row').each(function(i) {
            htmlDisp += '<tr class="fileDisp_bottom">';
            var dAnc = wsHelperObj.getDownloadAnchor(itemDetails.webUrl, jQuery(this).attr('EncodedAbsUrl'), "Download");
            htmlDisp += '<td class="fileDisp_left" style="text-decoration:none;">&nbsp;</td><td colspan="2">' + jQuery(this).attr('Title') + '</td><td><a href="' + jQuery(this).attr('EncodedAbsUrl') + '" target="_blank">View</a></td><td class="fileDisp_right">' + dAnc + '</td></tr>';
        });
        htmlDisp += '</table>';
        jQuery.fn.colorbox({ opacity: this.opacity, html: htmlDisp });
    } else {
        jQuery.fn.colorbox({ opacity: this.opacity, html: '<div style="padding: 1em">There was an error looking up the Specification Document for this product.<br />Please <a href="/en-us/Pages/contactus.aspx">contact us</a> for more information about this product.</div>' });
    }
};
wsHelper.prototype.GetMSDS = function(specID) {
    jQuery.fn.colorbox({ opacity: this.opacity, html: "<div style='padding: 1em'><img src='/_layouts/images/cpchem/internet/ajax-loading.gif' alt='loading' /></div>" });
    this.GetMSDSDetails(specID,this.DisplayMSDS);
};
wsHelper.prototype.DisplayMSDS = function(itemDetails) {
    if (itemDetails.ajaxStatus == "success") {
        var msdsList = new Array();
        var numMsds = 0;
        jQuery(itemDetails.ajaxResult).find('Row').each(function(i) {
            msdsList.push({ EncodedAbsUrl: jQuery(this).attr('EncodedAbsUrl'), Language: jQuery(this).attr('MSDSLanguage'), Area: jQuery(this).attr('MSDSGenerationVariant') });
            numMsds++;
        });
        var htmlDisp;
        if (numMsds == 0)
        {
          htmlDisp = '<div style="padding: 1em;">There were no Material Safety Data Sheets found for this product. Please <a href="/en-us/Pages/contactus.aspx">contact us</a> for more information about this product.</div>';
        } else {
          // Build html to display.
          htmlDisp = '<table border="0" cellspacing="0" cellpadding="0" class="fileDisp_tbl">' +
                            '<tr class="fileDisp_lbl">' +
                                '<td colspan="5" class="fileDisp_left fileDisp_right">Material Safety Data Sheets</td>' +
                            '</tr>' +
                            '<tr class="fileDisp_MSDShead">' +
                                '<td class="fileDisp_left" style="text-decoration:none;">&nbsp;</td><td>Area</td><td>Language</td><td  style="text-decoration:none;">&nbsp;</td><td class="fileDisp_right" style="text-decoration:none;">&nbsp;</td>' +
                            '</tr>';
          for (var i = 0; i < numMsds; i++) {
              if (i == numMsds - 1) { htmlDisp += '<tr class="fileDisp_bottom">'; }
              else { htmlDisp += '<tr>'; }
              var dAnc = wsHelperObj.getDownloadAnchor(itemDetails.webUrl, msdsList[i].EncodedAbsUrl, "Download");
              htmlDisp += '<td class="fileDisp_left" style="text-decoration:none;">&nbsp;</td><td>' + msdsList[i].Area + '</td><td>' + msdsList[i].Language + '</td><td><a href="' + msdsList[i].EncodedAbsUrl +'" target="_blank">View</a></td><td class="fileDisp_right">' + dAnc + '</td></tr>';
          }
          htmlDisp += '</table>';
        }
        jQuery.fn.colorbox({ opacity: this.opacity, html: htmlDisp });
    } else {
        jQuery.fn.colorbox({ opacity: this.opacity, html: '<div style="padding: 1em">There was an error looking up the MSDS for this product.<br />Please <a href="/en-us/Pages/contactus.aspx">contact us</a> for more information about this product.</div>' });              
    }
};