/*	Script: my.products.js
		This document is legacy code for the My Products application. It will be rewritten and documented when time permits.
	*/

var userProducts = new Array();
var shopListProducts = new Array();
var validSiteIds = [1, 7, 9, 15, 16];
var isOnList = false;
var element;
var ursRegId;
var profileUrl;
var avgRating = -1;
var userRating = -1;
var numRatings = -1;
var messageId;
var no204 = false;
var nodeId;
var addUrl;
var listTypeId;
var infoUrl = "/4520-33_7-6370591.html";
var urs_reg_id;
var howManyCoCoProds = -1;
var mpList = new Array();
var listItemToProductMap = new Object();

function setButtons(u, li, pList) {
    for (var i = 0; i < pList.length; i++) {
        isProductOnList(u, li, pList[i]);
    }
};

function isProductOnList(u, li, p) {
    loadMpForNm(p);
};

function fetchUoData(u, p, n) {
    var siteId = getSiteIdFromOid();
    var search = location.search;
    var re = /noAjax/;
    if (!re.test(search)) {
        var ursRegID = u;
        nodeId = n;
        if (ursRegID && p) {
            loadUoDataXML("http://" + correctHostForSite(siteId) + "/5261-4" + tokenizeSiteId(siteId) + "0-18.html?assetID=" + p + "&ursRegID=" + ursRegID);
            showUoData(p);
        } else {
            // Alright, we didn't get any UO Data.  Just show the defaults.
            showUoData(p);
        }
    }
};

function loadUoDataXML(url) {
    if (window.XMLHttpRequest) {
        uoReq = new XMLHttpRequest();
        uoReq.open("GET", url, false);
        uoReq.send(null);
    } else if (window.ActiveXObject) {
        isIE = true;
        uoReq = new ActiveXObject("Microsoft.XMLHTTP");
        if (uoReq) {
            uoReq.open("GET", url, false);
            uoReq.send();
        }
    }
    // If everything returns successfully, parse out the avgRating and userRating
    if (uoReq.status == 200) {
        var xml = uoReq.responseXML;
        if (xml) {
            parseUoData(xml);
        }
    }
};

function parseUoData(xml) {
    avgRating = xml.getElementsByTagName("avgRating")[0].childNodes[0].nodeValue;
    numRatings = xml.getElementsByTagName("numRatings")[0].childNodes[0].nodeValue;
    userRating = xml.getElementsByTagName("userRating")[0].childNodes[0].nodeValue;
    messageId = xml.getElementsByTagName("messageID")[0].childNodes[0].nodeValue;
};

function showUoData(productId) {
    // Grab some stuff to build the link properly
    var host = location.host;
    var re = /^www/;
    if (re.test(host)) {
        host = host.replace(re, 'reviews');
    }
    // First deal with the Average Rating piece
    if (avgRating != -1 && numRatings > 4) { // Make sure the value is not -1 (our default no-data value) and there are at least 5 ratings
        // Set all the attributes of the relevant elements
        var avgRatingFloor = Math.floor(avgRating);
        document.getElementById(productId + "_avgImg").setAttribute("src", "/i/rev/rate_" + avgRatingFloor + ".gif");
        document.getElementById(productId + "_avgImg").setAttribute("alt", avgRating);
        document.getElementById(productId + "_avgRating").innerHTML = avgRating;
        document.getElementById(productId + "_avgReview").innerHTML = "Average users' rating:";
        document.getElementById(productId + "_avgReview").setAttribute("href", "http://" + host + "/4852-" + nodeId + "_7-" + productId + ".html?tag=qlph");
    } else {
        // There is no average rating, so get that element out of here
        if (document.getElementById(productId + "_uoAvg")) {
            document.getElementById(productId + "_uoAvg").style.display = "none";
        }
    }

    // Now deal with the User specific rating
    if (userRating != -1) {
        // First get rid of the no opinion HTML
        if (document.getElementById(productId + "_noRating")) {
            document.getElementById(productId + "_noRating").style.display = "none";
        }
        // Now set all the attributes of the relevant elements
        var userRatingFloor = Math.floor(userRating);
        document.getElementById(productId + "_userImg").setAttribute("src", "/i/rev/rate_" + userRatingFloor + ".gif");
        document.getElementById(productId + "_userImg").setAttribute("alt", userRating);
        document.getElementById(productId + "_userRating").innerHTML = userRating;
        document.getElementById(productId + "_userReview").innerHTML = "My rating:";
        document.getElementById(productId + "_userReview").setAttribute("href", "http://" + host + "/4864-" + nodeId + "_7-" + productId + ".html?messageSiteID=7&messageID=" + messageId + "&tag=mpuo");
    } else {
        // Ok, the user hasn't rated this product.  Remove that rating element if it is there.
        if (document.getElementById(productId + "_uoUser")) {
            document.getElementById(productId + "_uoUser").style.display = "none";
        }
        // Now set all the attributes for the no rating element, if it exists
        if (document.getElementById(productId + "_noRating")) {
            document.getElementById(productId + "_share").setAttribute("href", "http://" + host + "/" + eval("pp_" + productId) + "/5260-3000_7-0.html?nodeID=" + nodeId + "&assetID=" + productId + "&tag=mpuo");
        }
    }
};

function MlpProduct(p, n) {
    this.productId = p;
    this.nodeId = n;
};

function fetchMiniMlp(p, n) {
    var search = location.search;
    var re = /noAjax/;
    if (!re.test(search)) {
        var product = new MlpProduct(p, n);
        product.loadMlpData();
    }
};

MlpProduct.prototype.loadMlpData = function() {
    var siteId = getSiteIdFromOid();
    var url = "http://" + correctHostForSite(siteId) + "/4591-4" + tokenizeSiteId(siteId) + this.productId + ".html?nodeId=" + this.nodeId + "&_siteid_=1";
    var productId = this.productId;
    var noPricingData = "<div class=\"myp_clock\"><div align=\"center\">" +
                        "<p style=\"float:none;\">Unable to retrieve pricing data<p>" +
                        "</div></div><br clear=\"all\" /></div></div><div class=\"hrw hrprices\"><hr /></div>";
    var mlpReq;
    if (window.XMLHttpRequest) {
        mlpReq = new XMLHttpRequest();
        mlpReq.onreadystatechange = function() {
            if (mlpReq.readyState == 4) {
                if (mlpReq.status == 200) {
                    var re = /Page Not Found/;
                    if (!re.test(mlpReq.responseText)) {
                        document.getElementById(productId + "_mlp").innerHTML = mlpReq.responseText;
                    } else {
                        document.getElementById(productId + "_mlp").innerHTML = noPricingData;
                    }
                }
            }
        };
        mlpReq.open("GET", url, true);
        mlpReq.send(null);
    } else if (window.ActiveXObject) {
        mlpReq = new ActiveXObject("Microsoft.XMLHTTP");
        if (mlpReq) {
            mlpReq.onreadystatechange = function() {
                if (mlpReq.readyState == 4) {
                    if (mlpReq.status == 200) {
                        var re = /Page Not Found/;
                        if (!re.test(mlpReq.responseText)) {
                            document.getElementById(productId + "_mlp").innerHTML = mlpReq.responseText;
                        } else {
                            document.getElementById(productId + "_mlp").innerHTML = noPricingData;
                        }
                    }
                }
            };
            mlpReq.open("GET", url, true);
            mlpReq.send();
        }
    }
};

function openPopWindow(url, name, width, height) {
    self.name = "productPageWin";
    popUpWin = window.open(url, name, 'toolbar=0,location=no,directories=0,status=0,top=0,scrollbars=yes,resizable=1,width=' + width + ',height=' + height);
    if (navigator.appName == 'Netscape') {
        popUpWin.focus();
    }
};

function correctHostForSite(siteId) {
    var host = location.host;
    if (siteId == 1) {
        var re1 = /^reviews/;
        var re2 = /^shopper/;
        if (re1.test(host)) {
            host = host.replace(re1, 'www');
        } else if (re2.test(host)) {
            host = host.replace(re2, 'www');
        }
    } else if (siteId == 7) {
        var re1 = /^www/;
        var re2 = /^shopper/;
        if (re1.test(host)) {
            host = host.replace(re1, 'reviews');
        } else if (re2.test(host)) {
            host = host.replace(re2, 'reviews');
        }
    } else if (siteId == 9) {
        var re1 = /^www/;
        var re2 = /^reviews/;
        if (re1.test(host)) {
            host = host.replace(re1, 'shopper');
        } else if (re2.test(host)) {
            host = host.replace(re2, 'shopper');
        }
    }
    return host;
};

function getSiteIdFromOid() {
    // Gonna parse the siteId out of the oid safely.  First grab the path.
    var path = location.pathname;
    // Find the last occurrence of the underscore, so we know we are right before the siteId
    var underScoreIndex = path.lastIndexOf("_");
    // Get the chunk that starts with that underscore
    var pathChunk = path.substring(underScoreIndex, path.length);
    // Now find the index of the first dash after that underscore
    var dashIndex = pathChunk.indexOf("-");
    // Now using both indices, grab just the siteId out of the path
    var siteId = parseInt(pathChunk.substring(1, dashIndex));
    // Check to see if this is a number, if not, then return invalid
    if (siteId == "NaN") {
        // If we didn't a valid siteId, hopefully we can get by without it.  Return invalid.
        return "invalid";
    } else {
        // Ok, we got a number, so see if it is in our list of valid siteIds
        for (var i = 0; i < validSiteIds.length; i++) {
            if (siteId == validSiteIds[i]) {
                // This is a valid siteId, so return it
                return siteId;
            }
        }
        // If we get here, then we didn't find a valid siteId, return invalid
        return "invalid";
    }
};

function tokenizeSiteId(siteId) {
    if (siteId != "invalid") {
        siteId = "_" + siteId + "-";
    } else {
        siteId = "-";
    }
    return siteId;
};

function emailMyProductsListSubmit() {
    if (document.emailMemberForm.toAddress.value == '') {
        alert("Please enter at least one recipient!");
        return false;
    }
    if (document.emailMemberForm.toAddress.value.length > 0) {
        // Check to make sure all email addresses are valid
        var toAddress = document.emailMemberForm.toAddress.value;
        if (toAddress.indexOf(",") > -1) {
            var addressList = toAddress.split(",");
            var isValid = true;
            for (var i = 0; i < addressList.length; i++) {
                trimmedAddress = addressList[i].replace(/^\s*|\s*$/g, "");
                if (trimmedAddress.indexOf("@") == -1 || (trimmedAddress.lastIndexOf(".") < trimmedAddress.indexOf("@")) || trimmedAddress.indexOf(' ') > -1) {
                    alert(trimmedAddress + " is not a valid email address!");
                    isValid = false;
                }
            }
            if (!isValid) {
                return false;
            }
        } else {
            if (toAddress.indexOf("@") == -1 || (toAddress.lastIndexOf(".") < toAddress.indexOf("@")) || toAddress.indexOf(' ') > -1) {
                alert(toAddress + " is not a valid email address!");
                return false;
            }
        }
    }
    if (document.emailMemberForm.messageBody.value == '') {
        alert("Please enter a message!");
        return false;
    }
    document.emailMemberForm.submit();
    return true;
};
function myProductsBodyMaximumLength(element, maxvalue) {
    var q = eval("document.emailMemberForm." + element + ".value.length");
    var r = q - maxvalue;
    var msg = "You have entered " + q + " characters which exceeds the Field limit. " +
              "Please abbreviate " +
              "your text to " + maxvalue + " characters or it'll be truncated.";
    if (q > maxvalue) alert(msg);
};
function myProductsBodyCheckLength(obj, n) {
    var theValue = obj.value;
    var theLength = obj.value.length;
    window.status = theLength + ' of ' + n + ' maximum characters';
    if (theLength > n) {
        obj.value = theValue.substring(0, n);
        window.status = n + ' of ' + n + ' maximum characters';
    }
};

/**
 * Fetches the contents of the given url, and puts it in as the innerHTML of the give ID
 */
function includeVirtual(url, whereToPutItID) {
    // make sure we have something for each...
    if (url.length > 0 && whereToPutItID && whereToPutItID.length > 0) {
        var whereToPutIt = document.getElementById(whereToPutItID);
        if (whereToPutIt) {
            // ok, good... fetch the url then...

            // now run off and so out biznet...
            var xmlhttp = newXMLHttpRequest();
            if (!xmlhttp) {
                return false;
            }
            xmlhttp.onreadystatechange = function() {
                if (xmlhttp.readyState == 4) {
                    if (xmlhttp.status == 200) {
                        var response = xmlhttp.responseText;
                        if (response && response.length > 0) {
                            whereToPutIt.innerHTML = response;
                        }
                    }
                }
            };
            xmlhttp.open("GET", url, true);
            xmlhttp.send(null);
        }
    }
};

function newXMLHttpRequest() {
    var xmlhttp = false;
    if (window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        try {
            xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e1) {
            try {
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e2) {
            }
        }
    }
    return xmlhttp;
};
var localStoresTabOriginalState = new Array();
var currentUsersZipCode = "";
function checkLocalAvailabilityMP(productId, sku, mfg) {
    // first, make sure they have a zip available...
    if (currentUsersZipCode && currentUsersZipCode.length > 0) {
        // see if we should 0 pad it...
        var numZeros = 5 - currentUsersZipCode.length;
        if (numZeros > 0) {
            for (var i = 0; i < numZeros; i++) {
                currentUsersZipCode = "0" + currentUsersZipCode;
            }
        }
        // ok, good, insert it into the right spot, ya know...
        document.getElementById("zipCode_" + productId).innerHTML = currentUsersZipCode;
        document.getElementById("zipCode2_" + productId).innerHTML = currentUsersZipCode;
        document.getElementById("zipCode3_" + productId).innerHTML = currentUsersZipCode;

        // now run off and so out biznet...
        var xmlhttp = newXMLHttpRequest();
        if (!xmlhttp) {
            return false;
        }
        var url = "/4589-1-0.html?sku=" + sku + "&zip=" + currentUsersZipCode + "&mfg=" + mfg;
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4) {
                if (xmlhttp.status == 200) {
                    var merchants = eval('(' + xmlhttp.responseText + ')');
                    if (merchants.count > 0) {
                        var key = 'lct_local_with_prices_off_';
                        document.getElementById(key + productId).style.display = "block";
                        localStoresTabOriginalState[productId] = key;
                    } else {
                        var key = 'lct_noprices_';
                        document.getElementById('lct_noprices_' + productId).style.display = "block";
                        localStoresTabOriginalState[productId] = key;
                    }
                }
            }
        };
        xmlhttp.open("GET", url, true);
        xmlhttp.send(null);
    } else {
        // turn on the version for nozip...
        var key = 'lct_nozip_';
        document.getElementById('lct_nozip_' + productId).style.display = "block";
        localStoresTabOriginalState[productId] = key;
    }
};
var mlpAreas = new Array();
function showLocalShoppingArea(productId) {
    // need to short-circuit IE, in the way it handles the bubble-up events.
    // If we see this condition below it means we are hitting this as a secondary
    // event to the showChangeZipCodeForm function... and that we need not continue...
    if (document.getElementById("lct_local_change_zip_on_" + productId).style.display == "none") {

        // now run off and so out biznet...
        var xmlhttp = newXMLHttpRequest();
        if (!xmlhttp) {
            return false;
        }
        var url = "/4140-4-" + productId + ".html";
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4) {
                if (xmlhttp.status == 200) {
                    var response = xmlhttp.responseText;
                    if (response && response.length > 0) {
                        // make sure we have our backup of the existing info...
                        var areaForThisProduct = document.getElementById(productId + "_mlp");
                        // if we haven't saved the original state of the online mlp area yet, do so...
                        if (!mlpAreas[productId] || mlpAreas[productId].length < 1) {
                            mlpAreas[productId] = areaForThisProduct.innerHTML;
                        }
                        // and now assin what we got in...
                        areaForThisProduct.innerHTML = response;
                        // and switch the local stores tabs...
                        document.getElementById(localStoresTabOriginalState[productId] + productId).style.display = "none";
                        document.getElementById('lct_local_with_prices_on_' + productId).style.display = "block";
                        // and now the online stores tab...
                        document.getElementById('lct_online_off_' + productId).style.display = "block";
                        document.getElementById('lct_online_on_' + productId).style.display = "none";
                    }
                }
            }
        };
        xmlhttp.open("GET", url, true);
        xmlhttp.send(null);
    }
};
function processZipChange(productId, newZip) {
    // now run off and so out biznet...
    var xmlhttp = newXMLHttpRequest();
    if (!xmlhttp) {
        return false;
    }
    var url = "/4139-4-0.html?ccmd=add&zip=" + newZip;
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4) {
            if (xmlhttp.status == 200) {
                var response = xmlhttp.responseText;
                if (response && response.length > 0 && parseInt(response) > 0) {
                    // great, that means it worked... go ahead and reload the page...
                    location.reload();
                } else {
                    // ok, tell them it no good...
                    document.getElementById('tct_chgzip_text_' + productId).innerHTML = '<!--' + response + '-->You entered "' + newZip + '" which is not a valid zip code. Please enter a five digit zip code below.'
                }
            }
        }
    };
    xmlhttp.open("GET", url, true);
    xmlhttp.send(null);
};
function showChangeZipCodeForm(productId, dontSwitchTabs) {
    document.getElementById(productId + "_mlp").style.display = "none";
    document.getElementById("lcl_chgzip_form_" + productId).style.display = "block";
    document.getElementById("lct_local_change_zip_on_" + productId).style.display = "block";
    document.getElementById(localStoresTabOriginalState[productId] + productId).style.display = "none";
    //    if (dontSwitchTabs) {
    //        document.getElementById("lct_onl_off_" + productId).style.display = "block";
    //        document.getElementById("lct_lcl_on_" + productId).style.display = "block";
    //    }
    document.getElementById('lct_online_off_' + productId).style.display = "block";
    document.getElementById('lct_online_on_' + productId).style.display = "none";
    document.getElementById('lct_local_with_prices_on_' + productId).style.display = "none";
};
function showMlpArea(productId) {
    // turn the mlp area back on...
    var areaForThisProduct = document.getElementById(productId + "_mlp");
    areaForThisProduct.style.display = "block";
    // and if it's in a false state, put it back...
    if (mlpAreas[productId] && mlpAreas[productId].length > 0) {
        areaForThisProduct.innerHTML = mlpAreas[productId];
    }
    document.getElementById("lcl_chgzip_form_" + productId).style.display = "none";
    // incase it's on...

    // now switch the tabs...
    document.getElementById("lct_local_change_zip_on_" + productId).style.display = "none";
    document.getElementById("lct_online_off_" + productId).style.display = "none";
    document.getElementById("lct_online_on_" + productId).style.display = "block";
    document.getElementById("lct_local_with_prices_on_" + productId).style.display = "none";
    document.getElementById(localStoresTabOriginalState[productId] + productId).style.display = "block";
};


var GOT_IT_TYPE = 1;
var WANT_IT_TYPE = 2;
var MPWRAP_PREFIX = "mpwrap_";
/**
 * Keeps looking up until it find the div is marked with an id like mpwrap_12931028
 */
function findMpWrapper(element, wrap_prefix) {
    wrap_prefix = wrap_prefix || MPWRAP_PREFIX;
    var re = new RegExp('^' + wrap_prefix + '[0-9]+$', 'i');
    var par = element;
    while (par && !(par.id && par.id.match(re))) {
        par = par.parentNode;
        if (par.className == 'mp_wrap') {
            return par;
        } else {
            if (par.parentNode.id == 'dfll') {
                return par;
            }
        }
    }
    // If we don't find a parent with mpwrap_ prefix
    // look for the parent with numbers as the id.  If we find that, check
    // if the class of that element is "mp_wrap" and retun it if true
    if (!par) {
        // Set it back to the original element again and do another search
        par = element;
        var re2 = new RegExp('^[0-9]+$', 'i');
        while (par && !(par.id && par.id.match(re2))) {
            par = par.parentNode;
            if (par.className == 'mp_wrap') {
                return par;
            } else {
                // If the className isn't mp_wrap, see if the parent id is
                // 'dfll' because then we are should return this element too
                if (par.parentNode.id == 'dfll') {
                    return par;
                }
            }
        }
    }
    return par;
};

function notOnListClick(obj, idName, wrap_prefix) {
    wrap_prefix = wrap_prefix || MPWRAP_PREFIX;
    obj.style.display = "none";
    if (!idName || idName.length <= 0) idName = "mp3_add_exp";
    // keep looping through the prents till we find the wrapper...
    var theOne;
    var par = findMpWrapper(obj, wrap_prefix);
    // test it...
    if (par) {
        // great... now find the right child...
        theOne = findChildElementById(par, idName);
    }
    if (theOne) {
        theOne.style.display = "block";
        var disNum = (location.href.match(/\/4540-/)) ? howManyCoCoProds + 1 : howManyCoCoProds;
        if (howManyCoCoProds > -1 && disNum < 6) {
            theOne.className = "mp3_add_exp_marg" + disNum + " v1";
        }
    }

};

function notOnListClick2(obj, idName, wrap_prefix) {
    wrap_prefix = wrap_prefix || MPWRAP_PREFIX;
    obj.style.display = "none";
    if (!idName || idName.length <= 0) idName = "mp3_add_exp";
    // keep looping through the prents till we find the wrapper...
    var theOne;
    var par = findMpWrapper(obj, wrap_prefix);
    // test it...
    if (par) {
        // great... now find the right child...
        theOne = findChildElementById(par, idName);
    }
    if (theOne) {
        theOne.style.display = "block";
//        var disNum = (location.href.match(/\/4540-/)) ? howManyCoCoProds + 1 : howManyCoCoProds;
//        if (howManyCoCoProds > -1 && disNum < 6) {
//            theOne.className = "mp3_add_exp_marg" + disNum + " v1";
//        }
    }

};

function doMpClose(element, wrap_prefix) {
    var wrap = findMpWrapper(element, wrap_prefix);
    // turn off each sub element..
    for (var i = 0; i < wrap.childNodes.length; i++) {
        if (wrap.childNodes[i] && wrap.childNodes[i].innerHTML) {
            wrap.childNodes[i].style.display = "none";
        }
    }
    // now turn the notonlist area back on...
    findChildElementById(wrap, "notonlist").style.display = "block";
};

/**
 * Does a recursive lookup of all the children
 * of the given element, and finds one with the given attribute Name Value Pair
 */
function findElementByAttributeNVP(element, attName, attValue) {
    if (element && element.hasChildNodes) {
        for (var i = 0; i < element.childNodes.length; i++) {
            var child = element.childNodes[i];
            if (child && child.innerHTML && child.getAttribute(attName) && child.getAttribute(attName) == attValue) {
                return child;
            } else {
                var newChild = findElementByAttributeNVP(child, attName, attValue);
                if (newChild) {
                    return newChild;
                } // else, keep looping...
            }
        }
    }
};

/**
 * Does a recursive lookup of all the children
 * of the given element, and finds one with the given id
 */
function findChildElementById(element, id) {
    if (element.id == id) return element;
    if (element && element.hasChildNodes) {
        for (var i = 0; i < element.childNodes.length; i++) {
            var child = element.childNodes[i];
            if (child && child.id == id) {
                return child;
            } else {
                var newChild = findChildElementById(child, id);
                if (newChild) {
                    return newChild;
                } // else, keep looping...
            }
        }
    }
};


function markAsOnList(productId, type, wrap_prefix) {
    // Correct the type if necessary
    if (type == 4) {
        type = 1;
    } else if (type == 5) {
        type = 2;
    }

    // first, find the right area...
    var mpArea = document.getElementById(wrap_prefix + productId);

    // If we didn't get anything back, check for the old wrapper
    if (!mpArea) {
        mpArea = document.getElementById(productId);
    }

    if (mpArea) {
        // now find the appropriate ON button, and turn it on...
        var onBtnName;
        switch (type) {
            case GOT_IT_TYPE:
                onBtnName = "onlist_gotit";
                break;
            case WANT_IT_TYPE:
                onBtnName = "onlist_wantit";
                break;
            default:
                return false;

        }
        // great, find the notonlist area, so we can turn it off...
        var notOnListArea = findChildElementById(mpArea, "notonlist");
        if (notOnListArea) notOnListArea.style.display = "none";
        var onBtnArea = findChildElementById(mpArea, onBtnName);
        if (onBtnArea) onBtnArea.style.display = "block";
    }
};

function setMpLink(element, type, wrap_prefix) {
    wrap_prefix = wrap_prefix || MPWRAP_PREFIX;
    var wrap = findMpWrapper(element, wrap_prefix);
    if (wrap.id.indexOf('mpwrap') > -1) {
        productId = wrap.id.substring(wrap_prefix.length);
    } else {
        productId = wrap.id;
    }
    var url = '/5302-4_92-0-1.html?gtProductId=' + productId + '&tag=mpnav&listTypeId=' + type + '#gt_' + productId;
    element.href = url;
};

function addProductToList(element, type, idName, wrap_prefix) {
    // Correct the type if we need to
    var userListType;
    if (type == 1) {
        userListType = 4;
    } else if (type == 2) {
        userListType = 5;
    }

    wrap_prefix = wrap_prefix || MPWRAP_PREFIX;
    needLogin = !(urs_reg_id && urs_reg_id.length > 5 && logged_in && remember_me && (parseInt(logged_in) + parseInt(remember_me) > 0));
    // first hide where we came from...
    // keep looping through the prents till we find the wrapper...
    var thisOne;
    var par = findMpWrapper(element, wrap_prefix);
    // test it...
    if (par) {
        idName = idName || "mp3_add_exp";
        // great... now find the right child...
        var notOnListArea = findChildElementById(par, "notonlist");
        if (notOnListArea) notOnListArea.style.display = "none";
        thisOne = findChildElementById(par, idName);
        if (thisOne) thisOne.style.display = "none";
        var waiting = findChildElementById(par, "waiting");
        if (waiting) waiting.style.display = "block";

        // now find the productId we are lookign at...
        var productId;
        if (par.id.indexOf('mpwrap') > -1) {
            productId = par.id.substring(wrap_prefix.length);
        } else {
            productId = par.id;
        }

        var addUrl = '/9800-1-0.xml?referencedType=10&referencedId=' + productId + '&listItemType=' + userListType + '&cmd=createListItem';
        if (needLogin) {
            addUrl += "&viewName=redirect:";

            if (document.returnUrl) {
                addUrl += returnUrl;
            } else {
                addUrl += escape(location.href);
            }

            window.location = addUrl;
            return;
        } else {
            // Use AJAX
            var xmlhttp = newXMLHttpRequest();
            if (xmlhttp) {
                xmlhttp.onreadystatechange = function() {
                    if (xmlhttp.readyState >= 4) {
                        if (waiting) waiting.style.display = "none";
                        var attName = (type == WANT_IT_TYPE) ? "onlist_wantit" : "onlist_gotit";
                        var theOne = findChildElementById(par, attName);
                        if (theOne) {
                            theOne.style.display = "block";
                        }
                    }
                };

                xmlhttp.open("GET", addUrl, true);
                xmlhttp.send(null);
            }
        }
    }
};

function loadProductListJSON(url) {
    // Only do this if we don't already have the mpList object
    if (!mpList.list) {
        // branch for native XMLHttpRequest object
        if (window.XMLHttpRequest) {
            pListReq = new XMLHttpRequest();
            pListReq.open("GET", url, false);
            pListReq.send(null);
            // branch for IE/Windows ActiveX version
        } else if (window.ActiveXObject) {
            isIE = true;
            pListReq = new ActiveXObject("Microsoft.XMLHTTP");
            if (pListReq) {
                pListReq.open("GET", url, false);
                pListReq.send();
            }
        }
        // Parse out the productIds if everything comes back OK
        if (pListReq.status == 200) {
            var res = pListReq.responseText;
            mpList = eval('(' + res + ')');

        }
    }
};

function loadMpForCoco(prods, wrap_prefix) {
    wrap_prefix = wrap_prefix || MPWRAP_PREFIX;
    howManyCoCoProds = prods.length;
    for (var i = 0; i < prods.length; i++) {
       // this part is temporary... to make sure everything is centered (without a UAT rebuild...)
       document.getElementById(wrap_prefix + prods[i]).align="center";
    }
    if (urs_reg_id && urs_reg_id.length > 5 && ("1" == logged_in || "1" == remember_me)) {
        var daUrl = "/9801-1-0.html?cmd=getChildFolders&viewName=.json-my-products-list";
        loadProductListJSON(daUrl);
        for (var i = 0; i < prods.length; i++) {
            for (var j = 0; j < mpList.list.length; j++) {
                if (prods[i] == mpList.list[j].referencedId) {
                    markAsOnList(prods[i], mpList.list[j].listItemType.value, wrap_prefix);
                    break;
                }
            }
        }
    }
};

function loadMpForNm(prodId) {
    if (urs_reg_id && urs_reg_id.length > 5 && ("1" == logged_in || "1" == remember_me)) {
        var daUrl = "/9801-1-0.html?cmd=getChildFolders&viewName=.json-my-products-list";
        loadProductListJSON(daUrl);
        for (var i = 0; i < mpList.list.length; i++) {
            if (prodId == mpList.list[i].referencedId) {
                markAsOnList(prodId, mpList.list[i].listItemType.value, MPWRAP_PREFIX);
                break;
            }
        }
    }
};

function loadMpForMp(prods, wrap_prefix) {
    wrap_prefix = wrap_prefix || MPWRAP_PREFIX;
    if (urs_reg_id && urs_reg_id.length > 5 && ("1" == logged_in || "1" == remember_me)) {
        var daUrl = "/9801-1-0.html?cmd=getChildFolders&viewName=.json-my-products-list";
        loadProductListJSON(daUrl);
        for (var i = 0; i < prods.length; i++) {
            for (var j = 0; j < mpList.list.length; j++) {
                if (prods[i] == mpList.list[j].referencedId) {
                    markAsOnList(prods[i], mpList.list[j].listItemType.value, wrap_prefix);
                    break;
                }
            }
        }
    }
};

function loadMpForOff(prods, wrap_prefix) {
    wrap_prefix = wrap_prefix || MPWRAP_PREFIX;
    howManyCoCoProds = prods.length;
    if (urs_reg_id && urs_reg_id.length > 5 && ("1" == logged_in || "1" == remember_me)) {
        var daUrl = "/5301-4-0-3.html?action=findUserProductsJSON";
        loadProductListJSON(daUrl);
        for (var i = 0; i < prods.length; i++) {
            if (mpList[prods[i]]) {
                markAsOnList(prods[i], mpList[prods[i]], wrap_prefix);
            }
        }
    }
    for (var i = 0; i < prods.length; i++) {
        document.getElementById(wrap_prefix + prods[i]).style.display="block";
    }
};

function reloadPage() {
    location.reload(true);
}

function changeMpView2(selector, fieldName) {
    var currentUrl = location.href;
    var newView = selector.options[selector.selectedIndex].value;
    if (currentUrl) {
        if (currentUrl.indexOf('?') > -1) {
            var whereItIs = currentUrl.indexOf(fieldName);
            if (whereItIs > -1) {
                var sub = currentUrl.substring(whereItIs);
                var otSpot = sub.indexOf('&');
                var finalUrl = currentUrl.substring(0, whereItIs) + fieldName + "=" + newView;
                if (otSpot > -1) {
                     finalUrl += sub.substring(otSpot);
                }
                location.href=finalUrl;
            } else {
                location.href = currentUrl + '&' + fieldName + '=' + newView;
            }
        } else {
            location.href = currentUrl + '?' + fieldName + '=' + newView;
        }
    }
};

function mpMoveMultipleProducts2(form, fromListTypeId) {
    var formQs = form.toQueryString();
    var toListTypeId = 4;
    if (fromListTypeId == 4) {
        toListTypeId = 5;
    }
    if (formQs && formQs.length > 0) {
        var moveUrl = '/9800-1_92-0.xml?component=&cmd=moveListItems&toFolderType=' + toListTypeId + '&' + formQs + '&viewName=.empty';
        var xmlhttp = newXMLHttpRequest();
        if (!xmlhttp) {
            return false;
        }
        xmlhttp.open("GET", moveUrl, false);
        xmlhttp.send(null);
        if (xmlhttp.status == 200) {
            if (!returnUrl) {
                returnUrl = window.returnUrl;
            }
            returnUrl = unescape(returnUrl);
            window.location = returnUrl;
        }
    }
};

function mpRemoveMultipleProducts2(form) {
    var formQs = form.toQueryString();
    if (formQs && formQs.length > 0) {
        var removeUrl = '/9800-1_92-0.xml?component=&cmd=deleteListItems&' + formQs + '&viewName=.empty';
        var xmlhttp = newXMLHttpRequest();
        if (!xmlhttp) {
            return false;
        }
        xmlhttp.open("GET", removeUrl, false);
        xmlhttp.send(null);
        if (xmlhttp.status == 200) {
            if (!returnUrl) {
                returnUrl = window.returnUrl;
            }
            returnUrl = unescape(returnUrl);
            window.location = returnUrl;
        }
    }
};

function mpCompareMultipleProducts(form) {
    var formQs = form.toQueryString();
    if (formQs && formQs.length > 0) {
        var re = new RegExp('listItemIds=[0-9]+');
        while (formQs.match(re)) {
            var match = formQs.match(re)[0];
            var startIndex = match.indexOf('=') + 1;
            if (startIndex > -1) {
                var listItemId = match.substring(startIndex);
                var productId = listItemToProductMap[listItemId];
                match = match.replace(listItemId, productId);
            }
            match = match.replace("listItemIds", "id");
            formQs = formQs.replace(re, match);
            var re2 = new RegExp('&q=');
            formQs = formQs.replace(re2, '');
        }
        var cocoUrl = '/4504-5_7-0.html?tag=pageNav&' + formQs;
        location.href=cocoUrl;
    } else {
        alert("Please select several Products to continue.");
    }
};

function refreshMySubmissions(url) {
    mySubmissionsReq = false;
    if (window.XMLHttpRequest) {
        try {
            mySubmissionsReq = new XMLHttpRequest();
        } catch (e) {
            mySubmissionsReq = false;
        }
    } else if (window.ActiveXObject) {
        try {
            mySubmissionsReq = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                mySubmissionsReq = new ActiveXObject("Microsoft.XMLHTP");
            } catch (e) {
                mySubmissionsReq = false;
            }
        }
    }
    if (mySubmissionsReq) {
        mySubmissionsReq.onreadystatechange = processMySubmissionsReqChange;
        mySubmissionsReq.open("GET", url, true);
        mySubmissionsReq.send("");
    }
};

function processMySubmissionsReqChange() {
    if (mySubmissionsReq.readyState >= 4) {
        if (mySubmissionsReq.status == 200) {
            document.getElementById('mysubmissions_wrapper').innerHTML = mySubmissionsReq.responseText;
        }
    }
};

function addToProductMap(listItemId, productId) {
    listItemToProductMap[listItemId] = productId;
};

var totalProducts = 0;
var gotItProducts = 0;
var wantItProducts = 0;

function buildMyProductsAggregateCounts(regId) {
    var url = "/9801-1-0.html?cmd=getChildFolders&ownerId=" + regId + "&viewName=.json-my-products-list";
    loadProductListJSON(url);
    if (mpList.list.length > 0) {
        totalProducts = mpList.list.length;
        for (var i = 0; i < mpList.list.length; i++) {
            if (mpList.list[i].listItemType.value == 4) {
                gotItProducts++;
            } else if (mpList.list[i].listItemType.value == 5) {
                wantItProducts++;
            }
        }
        $('totalProdCount').innerHTML = totalProducts;
        $('gotItProdCount').innerHTML = gotItProducts;
        $('wantItProdCount').innerHTML = wantItProducts;
    }
};

/* do not edit below this line */   
/* Section: Change Log 

$Source: /cvs/main/flatfile/html/rb/js/commerce/implementations/my.products/my.products.js,v $
$Log: my.products.js,v $
Revision 1.2  2007/02/21 21:39:15  kruegerw
Form.serialize no longer works... use form.toQueryString from mootools

Revision 1.1  2007/01/09 02:44:55  newtona
moved files from previous directories in commerce.global.utils and commerce.implementations

Revision 1.1  2006/12/04 18:45:18  newtona
moved from the global directory; no code changes; previously mpButtons.js

*/
