function DownloadLink(ProjectName, URL, URLName) {
    this.ProjectName = ProjectName;
    this.URL = URL;
    this.URLName = URLName;
    this.OS = new Array();
}

function buildViewFields(fields) {
    var viewFields = "";
    $(fields).each(function(i, f) {
        viewFields += "<FieldRef Name='" + f + "' />";
    });
    return viewFields;
}

var baseUrl = "/_vti_bin/";
function queryList(url, listName, viewFields, query, callback) {

    var soapRequest =
            "<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/'> \
                <soapenv:Body> \
                     <GetListItems xmlns='http://schemas.microsoft.com/sharepoint/soap/'> \
                        <listName>" + listName + "</listName> \
						<viewFields> \
                            <ViewFields>" + viewFields + "</ViewFields> \
                        </viewFields> \
                         <query> \
                            <Query>" + query + "</Query>\
                        </query> \
			<rowLimit Paged='TRUE'>1000</rowLimit> \
                    </GetListItems> \
                </soapenv:Body> \
            </soapenv:Envelope>";

    $.ajax({
        type: "POST",
        url: url + "Lists.asmx",
        data: soapRequest,
        processData: false,
        contentType: "text/xml; charset=utf-8",
        dataType: "xml",
        complete: callback,
        error: function(xmlHttp, textStatus, errorThrown) {
            // Do not alert since error could be for any number of reasons
            //alert("Error: " + textStatus + ", " + errorThrown);
        }
    });

}

function queryProjectList(listName, projectName, query, callback) {
    var url = "/projects/" + projectName + baseUrl;
    queryList(url, listName, buildViewFields(["URL", "OperatingSystems"]), query, callback);
}

function InitializeTryItLinks(projectName, projectFullName, listName) {
    var query = "<Where><Eq><FieldRef Name='TreatmentName' /><Value Type='Text'>c</Value></Eq></Where>";
    queryProjectList(listName, projectName, query, function(data, textStatus) { var links = getTryItLinks(data, textStatus); setTryItLinks(projectName, projectFullName, links); });
}

function setTryItLinks(projectName, projectFullName, links) {
    var tryItLinksDiv = "#cdTryItPopupHtml_" + projectName;
    var templateDivId = "#cdTryItPopupHtmlTemplate";
    var linkRowId = "#cdTryItHtmlPopupTemplateLink";
    var linkName = "cdTryItHtmlDisplayLink_" + projectName;
    var displayLinkQuery = "a[name='" + linkName + "']";

    var linksDiv = $(templateDivId).clone();
    var linkRow = $(linksDiv).find(linkRowId);

    if (null != linksDiv && null != linkRow) {
        var linkHtml = $(linkRow).html();
        var html = $(linksDiv).html();

        var displayLink = links.pop();
        var tryItLinks = links.pop();

        if (null == displayLink) {
            $(displayLinkQuery).parent().remove();
            return;
        } else {
            $(displayLinkQuery).parent().css("visibility", "visible");
        }

        var tempLinksHtml = "";

        $(tryItLinks).each(function(i, link) {
            var tempLinkHtml = linkHtml;
            tempLinkHtml = tempLinkHtml.replace(/%LINK_URL%/ig, link.URL);
            tempLinkHtml = tempLinkHtml.replace(/%LINK_TEXT%/ig, link.URLName);

            if (i < tryItLinks.length - 1) {
                tempLinkHtml += "</tr><tr>";
            }

            tempLinksHtml += tempLinkHtml;
        });

        html = html.replace(linkHtml, tempLinksHtml);
        html = html.replace(/%PROJECT_NAME%/ig, projectFullName);

        $(tryItLinksDiv).append(html);

        var linkOnclick = $(displayLinkQuery).attr("onclick").toString();
        var linkHref = $(displayLinkQuery).attr("href").toString();

        var popupWidth = $(displayLinkQuery).attr("popupwidth");
        if (null != popupWidth && "" != popupWidth) {
            $(tryItLinksDiv).css("width", popupWidth);
        } else {
            $(tryItLinksDiv).css("width", "300px");
        }

        linkOnclick = linkOnclick.replace(/%LINK_URL%/ig, displayLink.URL);
        linkOnclick = linkOnclick.replace(/%PROJECT_NAME%/ig, projectFullName);

        linkHref = linkHref.replace(/%LINK_URL%/ig, displayLink.URL);
        linkHref = linkHref.replace(/%PROJECT_NAME%/ig, projectFullName);

        $(displayLinkQuery).attr("href", linkHref);
        $(displayLinkQuery).attr("onclick", linkOnclick);
    }
}

function getTryItLinks(xData, status) {
    var tryItLinks = new Array();
    var displayLink = null;

    var rows = null;
    if (xData.responseXML.getElementsByTagName("z:row").length == 0) {
        rows = xData.responseXML.getElementsByTagNameNS('*', 'row');
    } else {
        rows = xData.responseXML.getElementsByTagName("z:row");
    }

    if (null != rows) {

        $(rows).each(function() {


            var urlwName = $(this).attr("ows_URL").toString();
            var url = urlwName.split(", ")[0];
            var name = urlwName.split(", ")[1];
            var os = $(this).attr("ows_OperatingSystems").toString();

            var link = new DownloadLink("", url, name);

            var oss = os.split(",");
            $(oss).each(function(i, op) {
                link.OS.push(op);

                if (null == displayLink &&
			    navigator.userAgent.indexOf(op) > 0) {
                    displayLink = link;
                }
            });

            tryItLinks.push(link);
        });
    }

    var links = new Array();
    links.push(tryItLinks);
    links.push(displayLink);
    return links;
}

TryItLinkControlHtml = function() {
    // CONSTRUCTOR: Sets event handlers.
    // DO NOTHING
}

TryItLinkControlHtml.prototype = {

    // Initializes the bookmarking control.
    Initialize: function(parent, control, projectName, projectFullName, listName) {

        //alert("Initialize:\nprojectName=" + projectName + "\nprojectFullName=" + projectFullName + "\nlistName=" + listName);

        InitializeTryItLinks(projectName, projectFullName, listName);

        if ($.browser.safari) {
            // Safari bug fix: Delay resize event to give the page a chance to update.
            $(window).resize(
    function() {
        if (typeof (control) != 'undefined')
            window.setTimeout(control.Reposition, 1);
    }
   );
        } else {
            $(window).resize(function() {
                if (typeof (control) != 'undefined')
                    control.Reposition(control, projectName);
            });
        }

        $(document).click(
   function() {
       if (typeof (control) != 'undefined') {
           if (!control.hasFocus)
               control.TogglePopup("hide", control, projectName);
       }
   }
  );
        $(document).keypress(
   function(eventObject) {
       if (typeof (control) != 'undefined') {
           if (eventObject.keyCode == 27) // 'Esc' key.
               control.TogglePopup("hide", control, projectName);
       }
   }
  );

        $("#cdTryItPopupHtml_" + projectName).hover(
   function() {
       control.hasFocus = true;
   },
   function() {
       control.hasFocus = false;
   }
  );

        // Clone the bookmarking control, and place it into the parent element.
        control.elem = $("#cdTryItHtml_" + projectName).clone();
        control.elem.appendTo(parent);

        // Initialize the bookmarking control events.
        control.elem.click(
    function(eventObject) {
        control.elem = $(this);
        control.TogglePopup("", control, projectName);
    }
   );
        control.elem.hover(
    function() {
        control.hasFocus = true;
    },
    function() {
        control.hasFocus = false;
    }
   );

        control.elem.css("display", "inline");
    },

    // Toggles the popup.
    TogglePopup: function(state, control, projectName) {
        if (!control.toggling) {
            control.toggling = true;

            if (typeof (state) == 'undefined' || (state != "show" && state != "hide"))
                state = "toggle";

            var newLeft = control.hideLeft;
            if ($("#cdTryItPopupHtml_" + projectName).css("display") == "none") {
                control.Reposition(control, projectName);
                newLeft = control.showLeft;
                $("#cdTryItPopupHtml_" + projectName).css("left", control.hideLeft);
            }

            $("#cdTryItPopupHtml_" + projectName).animate({
                left: newLeft,
                height: state,
                width: state,
                opacity: state
            }, "normal", function() { control.toggling = false; });
        }
    },

    // Re-position the bookmarking popup to line-up with the bookmarking button.
    Reposition: function(control, projectName) {
        var links = control.elem;
        if (typeof (links) != 'undefined') {

            var popup = $("#cdTryItPopupHtml_" + projectName);

            // make sure popup was found on page
            if (null == popup || typeof (popup) == 'undefined') {
                return;
            }


            var leftPadding = $("#wt_MainContent").offset().left;

            var linkName = "cdTryItHtmlDisplayLink_" + projectName;
            var linkQuery = "a[name='" + linkName + "']";
            var link = $(linkQuery);

            popup.css("position", "absolute");

            control.showLeft = link.offset().left - leftPadding;
            control.hideLeft = link.offset().left - leftPadding;

            if (navigator.userAgent.match(/firefox/i)) {
                popup.css("top", link.offset().top + link.height());
            }
            else if (navigator.userAgent.match(/safari/i)) {
                popup.css("top", link.offset().top + link.height());
            }
            else {

                control.showLeft = link.offset().left - 191 - leftPadding;
                control.hideLeft = link.offset().left - 191 - leftPadding;

                if (popup.css("display") != "none")
                    popup.css("left", control.showLeft);

                popup.css("top", link.offset().top - 68);
            }
        }
    },

    // Move the control to the specified parent, and set a new bookmarking asset.
    Reset: function(parent) {
        this.Initialize(parent);
    }
}