var myButtons = new Array("prodBtn1","prodBtn2","prodBtn3","prodBtn4","prodBtn5","prodBtn6");
var naceByProdFam = new Array();
var naceByMBoOEM = new Array();
var indCollect = new Array();
var prodtbl;
var myBannerCode;
var myPartURLs = new Array();
var mySales = new Array();
var j;
var rowCount;
var tsnum;
var compareCount = 0;
var compareNumsOne;

function compareMe(myPart) {
	var mySelect = document.getElementById('selectID' + myPart);
	if (mySelect.checked) {
		compareCount++;
		if (compareCount!=2){ // first part has been checked
			compareNumsOne = myPart;
		} else { // second part has been checked
			var myCompareUrl = "http://www.ifm.com/products/us/diff/" + compareNumsOne + ".htm&" + myPart ;// create URL for compare pop-up window
			window.open(myCompareUrl,"_blank","toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=yes, copyhistory=yes, width=640, height=550");
			var mySelectBoxes = document.getElementById('partsList').getElementsByTagName('input');
			for (var i = 0; i<mySelectBoxes.length; i++) {
				mySelectBoxes[i].checked = false;
			}
			compareCount = 0;
		}
	} else { // selected part number has been un-selected
		compareCount = 0;
	}
}

function resetMyVars() {
    naceByProdFam.length = 0;
    naceByMBoOEM.length = 0;
    mySales.length = 0;
	myPartURLs.length = 0;
    indCollect.length = 0;
    rowCount = 0;
    compareCount = 0;
    document.getElementById('indList').innerHTML = "<table id=\"tbl\" width=\"95%\"><tr><td></td></tr></table>";
    document.getElementById("middiv").style.display = 'none';
    document.getElementById("botdiv").style.display = 'none';
    document.getElementById("oemlink").style.color = '#000000';
    document.getElementById("enduserlink").style.color = '#000000';
    clearTable();
    clearBotTable();
}

function miniReset() {
    naceByProdFam.length = 0;
    naceByMBoOEM.length = 0;
    mySales.length = 0;
	myPartURLs.length = 0;
    compareCount = 0;
    document.getElementById('indList').innerHTML = "<table id=\"tbl\" width=\"95%\"><tr><td></td></tr></table>";
    document.getElementById("botdiv").style.display = 'none';
    clearBotTable();
}

function overChange(overBtn) {
    for (i in myButtons) {
        if ( overBtn == myButtons[i]) { // change color of button being hovered over
            myBtn = document.getElementById(overBtn).style;
            myBtn.color = "#ff9900";
        } else { // change color of buttons not being hovered over
            myBtn = document.getElementById(myButtons[i]).style;
            myBtn.color = "#000000";
        }
    }
}

function clearTable() {
    var indTable = document.getElementById('tbl');
    while (indTable.rows.length >= 1) {
        indTable.deleteRow(indTable.rows.length - 1);
    }
}

function clearBotTable() {
    try {
        var indTable = document.getElementById('partsList');
        var myTable = indTable.getElementsByTagName('table')[0];
        myTable.parentNode.removeChild(myTable);
    } catch (err) {
        return;
    }
}

function clickChange(clickBtn) {
    resetMyVars();
    for (i in myButtons) {
        if ( clickBtn == myButtons[i]) { // show 'over' layer of clicked button
            document.getElementById(clickBtn + 'ovr').style.visibility = 'visible';
            var mbeuCh = document.getElementById('topdiv2'); // adjust location of sub-nav
            mbeuCh.style.display = 'block'; //make sub-nav visible
            document.getElementById("topdiv").style.background = "#ffffff url('/img/stp1-off.gif') no-repeat 5px 7px";
            document.getElementById("topdiv2").style.background = "#ffffff url('/img/stp2-on.gif') no-repeat 5px 7px";
            // set javascript links for OEM and End User anchors
            // step 1 - create array of the links
            var myLink1 = document.getElementById("oemlink");
            var myLink2 = document.getElementById("enduserlink");
            myLink1.onclick= function() {
                myLink1.style.color = '#ff9900';
                myLink2.style.color = '#000000';
                runMe = 'oem' + clickBtn;
                populateInd(runMe);
                return false;
            }
            myLink2.onclick = function() {
                myLink2.style.color = '#ff9900';
                myLink1.style.color = '#000000';
                runMe = 'eu' + clickBtn;
                populateInd(runMe);
                return false;
            }
        } else {
            document.getElementById(myButtons[i] + 'ovr').style.visibility = 'hidden'; // hide non-clicked buttons
        }
    }
}

function populateInd(myInd) {
    // first, let's show and clear the table and declare some variables
    miniReset();
    document.getElementById("middiv").style.display = 'inline';
    document.getElementById("topdiv2").style.background = "#ffffff url('/img/stp2-off.gif') no-repeat 5px 7px";
    document.getElementById("middiv").style.background = "#ffffff url('/img/stp3-on.gif') no-repeat 5px 7px";
    if(navigator.appName == 'Microsoft Internet Explorer') {
        clearTable();
    }
    var myCollect = new Array();
    var newCount = 0;
    var taOld;
    var xmlDoc=null;
    if (window.ActiveXObject) { // code for IE
        xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
    } else if (document.implementation.createDocument) {// code for Mozilla, Firefox, Opera, etc.
        xmlDoc=document.implementation.createDocument("","",null);
    } else {
        alert('Your browser cannot handle this script');
    }
    if (xmlDoc!=null) {
        switch(myInd) {
            case 'oemprodBtn1':
                myProdPick = 'INDUCTIVE';
                MyBusType = 'Machine Builder';
                break;
            case 'euprodBtn1':
                myProdPick = 'INDUCTIVE';
                MyBusType = 'End User';
                break;
            case 'oemprodBtn2':
                myProdPick = 'OPTO';
                MyBusType = 'Machine Builder';
                break;
            case 'euprodBtn2':
                myProdPick = 'OPTO';
                MyBusType = 'End User';
                break;
            case 'oemprodBtn3':
                myProdPick = 'PRESSURE';
                MyBusType = 'Machine Builder';
                break;
            case 'euprodBtn3':
                myProdPick = 'PRESSURE';
                MyBusType = 'End User';
                break;
            case 'oemprodBtn4':
                myProdPick = 'FLOW';
                MyBusType = 'Machine Builder';
                break;
            case 'euprodBtn4':
                myProdPick = 'FLOW';
                MyBusType = 'End User';
                break;
            case 'oemprodBtn5':
                myProdPick = 'CAPACITIVE';
                MyBusType = 'Machine Builder';
                break;
			case 'euprodBtn5':
				myProdPick = 'CAPACITIVE';
				MyBusType = 'End User';
				break;
			case 'oemprodBtn6':
				myProdPick = 'TEMPERATURE';
				MyBusType = 'Machine Builder';
				break;
            default:
            myProdPick = 'TEMPERATURE';
            MyBusType = 'End User';
            break;
        }
        xmlDoc.async=false;
        xmlDoc.load("/img/" + myProdPick + "-w-url.xml"); // Assemble the name of the XML file to pull
        var x=xmlDoc.getElementsByTagName('nace');
        //select only OEMs or EUs
        for (var tc = 0; tc<x.length;tc++) {
            checkME = x[tc].getElementsByTagName('MBoOEM')[0].childNodes[0].nodeValue;
            if (checkME == MyBusType) {
                naceByMBoOEM.push(x[tc]);
            } else {
                continue;
            }
        }
        var t = document.getElementById('tbl');
        for (var i=0;i<naceByMBoOEM.length;i++) {
            var r = document.createElement('tr');
            var ca = document.createElement('td');
            var an = document.createElement('a');
            // set description as a link
            var descText = naceByMBoOEM[i].getElementsByTagName('desc')[0].childNodes[0].nodeValue;
            var descRep1 = descText.replace(/ /g,"1");
            var descRep2 = descRep1.replace(/,/g,"2");
            var descRep3 = descRep2.replace(/-/g,"3");
            an.setAttribute('href','javascript:popParts(\''+ descRep3 +'\');');
            an.setAttribute('id','myIndLink'+newCount+';');
            an.setAttribute('onclick','colorCorrect(this.id);this.style.color=\"#ff9900\";')
            descText = descText.toLowerCase();
            newDesc = descText.substring(0,1).toUpperCase() + descText.substring(1,descText.length);
            var ta = document.createTextNode(newDesc);
            // dupe check
            if (newDesc == taOld) {
                continue;
            }
            if (navigator.appName == 'Microsoft Internet Explorer') {
                if (newCount % 2 == 1) {
                    ca.setAttribute("className","listEven");
                }
                t.tBodies[0].appendChild(r);
            } else {
                if (newCount % 2 == 1) {
                    ca.setAttribute("class","listEven");
                }
                t.appendChild(r);
            }
            r.appendChild(ca);
            ca.appendChild(an);
            an.appendChild(ta);
            // collect description to compare with next - dupe check
            taOld = newDesc;
            // add 1 to newCount, for setting style of even rows
            newCount++;
        }
    }
}


function popParts(descrp) {
    j=0;
    mySales.length = 0;
    indCollect.length = 0;
    window.scrollTo(0,500);
    document.getElementById("middiv").style.background = "#ffffff url('/img/stp3-off.gif') no-repeat 5px 7px";
    if (document.getElementById("botdiv").style.display != 'inline') {
        document.getElementById("botdiv").style.display = 'inline';
    }
    document.getElementById("partsList").innerHTML = "<div width=\"95%\" align=\"center\"><img src=\"/img/wait.gif\"></div>";
    // try {
    // assemble the industry
    indstryA = descrp.replace(/1/g," ");
    indstryB = indstryA.replace(/2/g,",");
    indstryC = indstryB.replace(/3/g,"-");
    for (w=0; w<naceByMBoOEM.length;w++) {
        if (naceByMBoOEM[w].getElementsByTagName('desc')[0].childNodes[0].nodeValue == indstryC) {
            indCollect.push(naceByMBoOEM[w]);
        } else {
            continue;
        }
    }
    if (indCollect.length < 5) {
        myCount = indCollect.length;
    } else {
        myCount = 5;
    }
        
    for (w=0;w<myCount;w++) { // Pull needed info from the XML file
        myEntry1 = indCollect[w].getElementsByTagName('partQty')[0].childNodes[0].nodeValue;
        myEntry2 = indCollect[w].getElementsByTagName('partNo')[0].childNodes[0].nodeValue;
		if (indCollect[w].getElementsByTagName('partURL')[0]) {
			myPartURLs[w] = indCollect[w].getElementsByTagName('partURL')[0].childNodes[0].nodeValue;
		}
        mySales.push(myEntry1 + '-' + myEntry2);
    }
    mySales = mySales.reverse();
    // get the reference for the part list div
    var holder = document.getElementById("partsList");
    
    // creates a <table> element and a <tbody> element
    prodtbl = "<form action=\"#\"><table class=\"partable\" width=\"98%\"><tbody><tr><td colspan=4>Selected industry: <span class=\"boldo\">"+indstryC+"</span><br>Click two boxes to compare products</td></tr>";
    rowCount = 0;
    // creating all cells
    cellCreate();
    // }
    // catch(err) {
    // alert("Error: " + err);
    // return;
    // }
}

function cellCreate() {
    if (j>=myCount) {
        end(prodtbl);
        return;
    }
    
    rowCount++;
    //get part numbers from top of array
    tsnum = myCount - j;
    
    // see if we hit the end of the array
    if (tsnum == 0) {
        // if so, output results
        end(prodtbl);
    }
    a = mySales[tsnum-1].split("-");
    ptNum = a.pop();
    request = createRequest();
    if (request == null) {
        alert("Unable to create request");
        return;
    }
    var url = "/products/us/jsonld/" + ptNum + ".htm";
    request.open("GET",url,true);
    request.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
    request.send(null);
    request.onreadystatechange = function() {
        if (request.readyState == 4) {
            if (request.status == 200) {
                var myJSONObject = eval('(' + request.responseText + ')');
                // style the even rows
                if (rowCount % 2 == 1) {
                    prodtbl = prodtbl + "<tr class=\"listEven\">";
                } else {
                    prodtbl = prodtbl + "<tr>";
                }
                // rank col
                prodtbl = prodtbl + "<td class=\"rankclmn\">" + j +"</td>";
                
                // compare select column
                prodtbl = prodtbl + "<td class=\"compareclmn\"><input type=\"checkbox\" name=\"compselect" + myJSONObject.partno + "\" value=\"" + myJSONObject.partno + "\" id=\"selectID" + myJSONObject.partno + "\" onclick=\"compareMe(this.value)\"></td>";
                
                // image col
                prodtbl = prodtbl + "<td width=\"60\"><img src=\"http://www.ifm.com" + imageCheck(myJSONObject.imageurl) + "\"></td>";
                
                // description col
                prodtbl = prodtbl + "<td>" + cleanDesc(myJSONObject.description) + "</td>";
                
                // link col
				if (!myPartURLs[j-1]) {
					prodtbl = prodtbl + "<td class=\"linkclmn\"><a class=\"link\" href=\"dsfs!" + myJSONObject.partno + ".html\" target=\"_blank\">" + myJSONObject.partno + "</a></td></tr>";
				} else {
					prodtbl = prodtbl + "<td class=\"linkclmn\"><a class=\"link\" href=\"" + myPartURLs[j-1] + "\" target=\"_blank\">" + myJSONObject.partno + "</a></td></tr>";
				}
                
            } else {
                // if JSON data isn't there, go to next product in the list
                j++;
                cellCreate();
            }
            http_request = null;
        }
    }
    j=j+1;
    setTimeout( "cellCreate();", 2000);
}

function end(q) {
    prodtbl = q + "</tbody></table></form>";
    document.getElementById("partsList").innerHTML = prodtbl;
}

function imageCheck(imageURL) {
    if (imageURL == ''){
        imageURL = '/img/suv_missing.gif';
    }
	return imageURL;
}

function cleanDesc(desc) {
    arr = desc.split(" , ");
    arr.splice(0,1);
    myCleandesc = arr.join(", ");
    return myCleandesc;
}

function colorCorrect(myClickedLinkId) {
    var myLinkList = document.getElementById('tbl').getElementsByTagName('a');
    for(xyz = 0;xyz<myLinkList.length;xyz++) {
        if(myLinkList[xyz].id != myClickedLinkId) {
            document.getElementById(myLinkList[xyz].id).style.color = "#000000";
        } else {
            continue;
        }
    }
}

function createRequest() {
    try {
        request = new XMLHttpRequest();
    } catch (tryMS) {
        try {
            request = new ActiveXObject("MSxml2.XMLHTTP") ;
        } catch (otherMS) {
            try {
                request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (failed) {
                alert("Error: " + err);
                request = null;
            }
        }
    } return request;
}

