var PLUS = 'img/btn/clrPlus10x2.gif',
    MINUS = 'img/btn/clrMinus10x2.gif';

/**
 * Array.filter calls a provided callback function once for each element in an array, 
 * and constructs a new array of all the values for which callback returns a true value.
 * If Array.filter is not supported, patch with this.
 * Source: Mozilla (Spidermonkey/Firefox) changed to single var pattern.
 */
if (!Array.prototype.filter) {  
    Array.prototype.filter = function (fun /*, thisp*/) {  
        var len = this.length >>> 0,
            res = [],
            thisp = arguments[1],
            i,
            val;             
        
        if (typeof fun !== "function") { 
            throw new TypeError();  
        }
        for (i = 0; i < len; i++) {  
            if (i in this) {
                val = this[i]; // in case fun mutates 'this'  
                if (fun.call(thisp, val, i, this)) {
                    res.push(val);
                }
            }
        }  
        return res;
    };  
}

/**
 * Add ES5 String.trim() if it does not exist.
 *
 * Source: Crockford lecture 2 on Javascript. 
 */
if (typeof String.prototype.trim !== 'function') {
    String.prototype.trim = function () {
        return this.replace(/^\s*(\S*(\s+\S+)*)\s*$/,"$1");
    };
}

/**
 * Wrapper for getElementById.
 * @param {string} id of a DOM element.
 * @return {elem} the DOM element matching the id.
 */
function gEBID(id) {
    return document.getElementById(id);
}

/**
 * Wrapper for getElementsByTagName.
 * @param {string} tag (nodeName) to match.
 * @param {elem} elem starting DOM element to begin search. If undefined, 'document'.
 * @return {node list} node list of html elements of nodeName tag which are descendents of targ.
 */    
function gEBTN(tag, targ) {
    targ = targ || document;
    return targ.getElementsByTagName(tag);
}

/**
 * Get an array of elements that have a class name with a specified value using XPath.
 * @param {string} className class name to match.
 * @param {elem} context starting DOM element to begin search.
 * @return {array of elements} array of DOM elements which possess a certain class value.
 * Source: The Art & Science of JavaScript (adapted).
 * This function doesn't worry about IE5 and uses the
 * the Array.filter method in the non-XPath branch.
 * Returns an array snapshot, not a node-list. (see pm.js for note).
 */
function gEBCN(className, context) {
    context = context || document;
    var els = [];
    if (typeof document.evaluate === "function") {
        var xpath = document.evaluate(".//*[ contains(concat(' ', @class, ' '), ' " + className + " ')]", context, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
        for (var i = 0; i < xpath.snapshotLength; i++) {
            els.push(xpath.snapshotItem(i));
        }
    } else {
        var nodelist = context.getElementsByTagName("*");
        nodelist.filter = Array.prototype.filter;
        var re = new RegExp('(^|\\s)' + className + '(\\s|$)');
        els = nodelist.filter(function (node) {
            return node.className.match(re);
        });
    }
    return els;
}

/** 
 * Adds a class value to a target element if it doesn't already exist. 
 * @param {elem} elem DOM element
 * @param {string} classValue class value
 * @return {none} Adds class value to elem as a side effect.
 * Source: adapted from The Javascript Anthology by Sitepoint.
 */
function addClass(elem, classValue) {
    var pattern = new RegExp("(^| )" + classValue + "( |$)");
    if (!pattern.test(elem.className)) {
        if (elem.className === "") {
            elem.className = classValue;
        } else {
            elem.className += " " + classValue;
        }
    }
    return true;
}

/** 
 * Remove a class value to a target element if it exists. 
 * @param elem DOM element
 * @param classValue class value
 * @return none. Removes class value from elem as a side effect.
 * Source: adapted from The Javascript Anthology by Sitepoint.
 */
function removeClass(elem, classValue) {
    var removedClass = elem.className;
    if (typeof removedClass === 'undefined') { 
        return true;
    }
    var pattern = new RegExp("(^| )" + classValue + "( |$)");
    removedClass = removedClass.replace(pattern, "$1");
    removedClass = removedClass.replace(/ $/, "");
    elem.className = removedClass;
    return true;
}

/**
 * Get the XML http request object.
 * @return the XML http request object, or null.  
 * Ignore ActiveX versions 4.0 and 5.0.
 */
function getXhr() {
    var xhr = null;
    if (typeof window.XMLHttpRequest !== 'undefined') {
        xhr = new XMLHttpRequest();
    } else if (typeof window.ActiveXObject !== 'undefined') { 
        var xhrVersions = ['Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.3.0', 'Microsoft.XMLHTTP'];
        for (var i = 0; i < xhrVersions.length; i++) {
            try {
                xhr = new ActiveXObject(xhrVersions[i]);
                if (typeof xhr === 'object') { 
                    return xhr; 
                }
            } catch (ignore) {
            }
        }
    }
    return xhr;
}

/**
 * Get the productDetails for a given product (container) id.
 * from /data/getData.php.
 * @param {string} id in product_container table.
 * @return {string} A JS object that contains the name, description etc.
 */
function getProductDetails(id) {
    var path = 'data/getData.php?pid=' + id,
        txt = '',
        obj,
        xhr;
    xhr = getXhr();
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status === 200) {
            //txt = xhr.responseText;
            //txt = txt.replace(/'/g, "&rsquo;");
            //txt = txt.replace(/"/g, "'");
            eval('obj = ' + xhr.responseText + ';'); 
            // JSON.parse(xhr.responseText); // better?
            paintUi(obj);
        }
    };
    xhr.open('GET', path, true);
    xhr.send();
}

function toggleSection(evt) {
    evt = evt || window.event;
    var targ = evt.target || evt.srcElement,
        h3 = targ.parentNode,
        nxt = h3.nextSibling;
    while (nxt && nxt.nodeName.toUpperCase() !== 'UL' &&  nxt.nodeName.toUpperCase() !== 'H3') {
        nxt = nxt.nextSibling;
    }
    if (nxt && nxt.nodeName.toUpperCase() == 'UL') { 
        if (targ.src.match('Minus')) {
            nxt.style.display = 'none';
            targ.src = PLUS;
        } else {
            nxt.style.display = 'block';
            targ.src = MINUS;
        }
    }        
}

function search(evt) {
    evt = evt || window.evt;
    var targ = evt.target || evt.srcElement;
    /*
    alert("Search by keyword is not hooked up yet...");
    if (evt.preventDefault) {
        evt.preventDefault();
    }
    return false;
    */
}

function searchByKey(evt) {
    evt = evt || window.evt;
    var targ = evt.target || evt.srcElement;
}


/**
 * Matches pt.product_type_id and pt.code in DB.
 * Loads category page using query string without posting the data.
 */
function searchByType(evt) {
    evt = evt || window.evt;
    var targ = evt.target || evt.srcElement
        srchProd = gEBID('prodSearch');

    switch (srchProd.options.selectedIndex) {

    case 1:
        document.location.href = 'category.php?type=acc';
        break;
        
    case 2:
        document.location.href = 'category.php?type=bag';
        break;
        
    case 3:
        document.location.href = 'category.php?type=dress';
        break;
        
    case 4:
        document.location.href = 'category.php?type=combo';
        break;   
    
    case 5:
        document.location.href = 'category.php?type=foot';
        break;

    case 6:
        document.location.href = 'category.php?type=hat';
        break;
        
    case 7:
        document.location.href = 'category.php?categoryId=38';
        //document.location.href = 'category.php?categoryId=home';
        break;
        
    case 8:
        document.location.href = 'category.php?type=jacket';
        break;
        
    case 9:
        document.location.href = 'category.php?type=jewelry';
        break;
        
    case 10:
        document.location.href = 'category.php?type=pants';
        break;
    
    case 11:
        document.location.href = 'category.php?type=skirt';
        break;
        
    case 12:
        document.location.href = 'category.php?type=top';
        break;
        
    default:
        break;
    }
    
    if (evt.preventDefault) {
        evt.preventDefault();
    }
}

/*
    } else if (targ.nodeName.toUpperCase() == 'INPUT' && !srchWord.blocked) {
        srchProd.blocked = true;
        srchProd.options.selectedIndex = 0;
        if (evt.preventDefault) {
            evt.preventDefault();
        }
    }
    srchWord.blocked = false;
    srchProd.blocked = false;
}
*/
 
/**
 * All the shopping pages use the same left menu.
 * Scripted browsers use JS to search by type and
 * start with the minor menus closed up. 
 */
function initSales() {
    var i,
        leg = gEBID('collLegacy'),
        des = gEBID('collDesigner'),
        prt = gEBID('collPortfolio'),
        btns = gEBCN('clrButton'),
        srchProd = gEBID('prodSearch'),
        srchWord = gEBID('keySearch'),
        subm = gEBID('btnSubmit'); 
        
    for (i = 0; i < btns.length; i++) {
        btns[i].onclick = toggleSection;
    }
    subm.style.display = 'none';
    srchProd.onchange = searchByType;
    subm.onclick = search;
}






