function GetXmlHttpObject() {
    var xmlHttp=null;
    try {
        // Firefox, Opera 8.0+, Safari
        xmlHttp=new XMLHttpRequest();
    }
    catch (e) {
        // Internet Explorer
        try {
            xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e) {
            xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
    }
    return xmlHttp;
}

function imei_search() {
    xmlHttp=GetXmlHttpObject();
    if (xmlHttp==null) {
        alert ("Your browser does not support AJAX - this is supported in the majority of modern browsers. For best results we recommend using Internet Explorer 7");
        return;
    }
    if (document.mainform._imei.value != '') {
        var imeiNumber = document.mainform._imei.value;
        imeiNumber = imeiNumber.replace(/\D/g, "");
        if (imeiNumber.length != 15) {
            alert('Your IMEI number must be 15 digits long. The number you entered has '+imeiNumber.length+' digits');
            return;
        }
        var url=encodeURI("/cgi-bin/tmobile.cgi?_rm=get_models&_imei="+document.mainform._imei.value+"&sid="+Math.random());
        xmlHttp.onreadystatechange=imei_return_data;
        xmlHttp.open("GET",url,true);
        xmlHttp.send(null);
    } else {
        alert('Please enter your IMEI number');
        return;
    }
}

function imei_return_data() {
    if (xmlHttp.readyState==4) {
        if (xmlHttp.status == 200) {
            if (xmlHttp.responseXML != null) {
                var tacs = xmlHttp.responseXML.getElementsByTagName('tactable')[0];
                if (tacs.getElementsByTagName('row').length == 1) {
                    if (document.getElementById('successtext') != null) {
                        var formTable = document.getElementById('formtable');
                        formTable.deleteRow(formTable.rows.length-1);
                    }
                    if (document.getElementById('emailrow') != null) {
                        var formTable = document.getElementById('formtable');
                        formTable.deleteRow(formTable.rows.length-1);
                        formTable.deleteRow(formTable.rows.length-1);
                        formTable.deleteRow(formTable.rows.length-1);
                    }
                    // show final phone
                    // get make and model
                    firstRow = tacs.getElementsByTagName('row')[0];
                    makeCell = firstRow.getElementsByTagName('cell')[1];
                    modelCell = firstRow.getElementsByTagName('cell')[2];
                    show_list(tacs);
                    document.getElementById('tactable').style.display = 'block';
                    show_final(makeCell.lastChild.nodeValue, modelCell.lastChild.nodeValue);
                    // disable model dropdown
                    document.mainform._model.disabled = true;
                    // show email field
                    show_email_field();
                } else if (tacs.getElementsByTagName('row').length > 1) {
                    // show list of phones
                    if (document.getElementById('successtext') != null) {
                        var formTable = document.getElementById('formtable');
                        formTable.deleteRow(formTable.rows.length-1);
                    }
                    if (document.getElementById('emailrow') != null) {
                        var formTable = document.getElementById('formtable');
                        formTable.deleteRow(formTable.rows.length-1);
                        formTable.deleteRow(formTable.rows.length-1);
                        formTable.deleteRow(formTable.rows.length-1);
                    }
                    document.getElementById('tactable').style.display = 'block';
                    show_list(tacs);
                } else {
                    // show "no phones" message
                    alert('Sorry no phones were returned');
                }
            } else {
                alert('Sorry but feature is not available currently. Please try again later and inform us if you receive the same problem.');
            }
        } else {
            alert('Sorry but this feature is not available currently. Please try again later and inform us if you receive the same problem.');
        }
    }
}

function make_search() {
    xmlHttp=GetXmlHttpObject();
    if (xmlHttp==null) {
        alert ("Your browser does not support AJAX - this is supported in the majority of modern browsers. For best results we recommend using Internet Explorer 7");
        return;
    }
    if (document.mainform._make.value != '') {
        document.getElementById('loading').style.display = 'block';
        var url="/cgi-bin/tmobile.cgi?_rm=get_models&_make="+document.mainform._make.value+"&sid="+Math.random();
        xmlHttp.onreadystatechange=make_return_data;
        xmlHttp.open("GET",url,true);
        xmlHttp.send(null);
    } else {
        alert('Please enter your IMEI number');
        return;
    }
}

function make_return_data() {
    if (xmlHttp.readyState==4) {
        if (xmlHttp.status == 200) {
            if (xmlHttp.responseXML != null) {
                // show list of phones
                var tacs = xmlHttp.responseXML.getElementsByTagName('tactable')[0];
                if (tacs != null) {
                    if (document.getElementById('successtext') != null) {
                        var formTable = document.getElementById('formtable');
                        formTable.deleteRow(formTable.rows.length-1);
                    }
                    if (document.getElementById('emailrow') != null) {
                        var formTable = document.getElementById('formtable');
                        formTable.deleteRow(formTable.rows.length-1);
                        formTable.deleteRow(formTable.rows.length-1);
                        formTable.deleteRow(formTable.rows.length-1);
                    }
                    document.getElementById('tactable').style.display = 'block';
                    show_list(tacs);
                    // populate model dropdown
                    document.mainform._model.disabled = false;
                    var options = xmlHttp.responseXML.getElementsByTagName('modeldropdown')[0];
                    populate_model_dropdown(options);
                    document.getElementById('loading').style.display = 'none';
                } else {
                    document.getElementById('loading').style.display = 'none';
                    alert('Sorry but no phones were returned for this manufacturer in our database.');
                }   
            } else {
                alert('Sorry but this manufacturer list is not available currently. Please try again later and inform us if you receive the same problem.');
                document.getElementById('loading').style.display = 'none';
            }
        } else {
            alert('Sorry but this manufacturer list is not available currently. Please try again later and inform us if you receive the same problem.');
            document.getElementById('loading').style.display = 'none';
        }   
    }
}

// get XML for tac table 
function show_list(tacs) {
    for(var j=0;j<document.getElementById('tactable').childNodes.length;j++) {
        document.getElementById('tactable').childNodes[j].parentNode.removeChild(document.getElementById('tactable').childNodes[j]);
    }
    var msgDiv = document.getElementById('message');
    if (document.getElementById('message').childNodes.length == 0) {
        var msgPara = document.createElement('p');
        var msgTextNode = document.createTextNode('Please click on one of the images below which identifies your phone.');
        msgPara.appendChild(msgTextNode);
        msgDiv.appendChild(msgPara);
    }
    var tbl = document.getElementById('tactable');
    var headers = tbl.insertRow(lastRow);
    var corner = document.createElement('th');
    headers.appendChild(corner);
    var header1 = document.createElement('th');
    var textNode1 = document.createTextNode('Manufacturer');
    header1.appendChild(textNode1);
    headers.appendChild(header1);
    var header2 = document.createElement('th');
    var textNode2 = document.createTextNode('Model');
    header2.appendChild(textNode2);
    headers.appendChild(header2);
    var header3 = document.createElement('th');
    var textNode3 = document.createTextNode('Value');
    header3.style.display = 'none';
    header3.appendChild(textNode3);
    headers.appendChild(header3);
    j = 0;
    while (j < tacs.getElementsByTagName('row').length) {
        var thisNode = tacs.getElementsByTagName('row')[j];
        if (thisNode.nodeType != 1) {
            continue;
        }
        j++;
        var tbl = document.getElementById('tactable');
        var lastRow = tbl.rows.length;
        var row = tbl.insertRow(lastRow);
        row.setAttribute('onclick', 'select_model(\''+thisNode.getElementsByTagName('cell')[1].lastChild.nodeValue+'\', \''+thisNode.getElementsByTagName('cell')[2].lastChild.nodeValue+'\')');
        // next line is for IE
        row.onclick = new Function("select_model('"+thisNode.getElementsByTagName('cell')[1].lastChild.nodeValue+"', '"+thisNode.getElementsByTagName('cell')[2].lastChild.nodeValue+"');"); 
        row.setAttribute('id',thisNode.getElementsByTagName('cell')[2].lastChild.nodeValue);
        row.className = 'pointercursor';
        var imageCell = row.insertCell(0);
        if (thisNode.getElementsByTagName('cell')[0].lastChild != null) {
            var image = document.createElement('img');
            image.src = thisNode.getElementsByTagName('cell')[0].lastChild.nodeValue;
            imageCell.appendChild(image);
        }
        var manCell = row.insertCell(1);
        var manCellText = document.createTextNode(thisNode.getElementsByTagName('cell')[1].lastChild.nodeValue);
        manCell.appendChild(manCellText);
        var modCell = row.insertCell(2);
        var modCellText = document.createTextNode(thisNode.getElementsByTagName('cell')[2].lastChild.nodeValue);
        modCell.appendChild(modCellText);
        var valueCell = row.insertCell(3);
//        var valueCellImagePound = document.createElement('img');
//        valueCellImage.src = '/images/valueimages/pound.gif';
//        valueCell.appendChild(valueCellImagePound);
        for (var k=0; k < thisNode.getElementsByTagName('cell')[3].getElementsByTagName('image').length; k++) {
            var valueCellImage = document.createElement('img');
            valueCellImage.src = '/images/valueimages/'+thisNode.getElementsByTagName('cell')[3].getElementsByTagName('image')[k].lastChild.nodeValue+'.gif';
            valueCell.appendChild(valueCellImage);
        }
    
        valueCell.style.display = 'none';
    }
}

// populate dropdown with models 
function populate_model_dropdown(models) {
    document.mainform._model.options.length = 0;
    var defaultOption = new Option('Please Select', '', false, false);
    document.mainform._model.options[0] = defaultOption;
    for (var j=0;j<models.childNodes.length;j++) {
        if (models.childNodes[j].nodeType != 1) {
            continue;
        }
        var thisOption = new Option(models.childNodes[j].lastChild.nodeValue, models.childNodes[j].lastChild.nodeValue, false, false);
        var length = document.mainform._model.options.length;
        document.mainform._model.options[length] = thisOption;
    }
}

// make HTTP request for email and go to show_final
function select_model(make,model) {
    xmlHttp=GetXmlHttpObject();
    if (xmlHttp==null) {
        alert ("Your browser does not support AJAX - this is supported in the majority of modern browsers. For best results we recommend using Internet Explorer 7");
        return;
    }
    var url="/cgi-bin/tmobile.cgi?_rm=get_final_model&_make="+make+"&_model="+model+"&sid="+Math.random();
    xmlHttp.onreadystatechange=final_model_return_data;
    xmlHttp.open("GET",url,true);
    xmlHttp.send(null);
}

function final_model_return_data() {
    if (xmlHttp.readyState==4) {
        if (xmlHttp.status == 200) {
            if (xmlHttp.responseXML != null) {
                if (document.getElementById('successtext') != null) {
                    var formTable = document.getElementById('formtable');
                    formTable.deleteRow(formTable.rows.length-1);
                }
                var make = xmlHttp.responseXML.getElementsByTagName('make')[0].lastChild.nodeValue; 
                var model = xmlHttp.responseXML.getElementsByTagName('model')[0].lastChild.nodeValue; 
                show_final(make, model);
            } else {
                alert('Sorry but this service is temporarily unavailable. Please try again later.');
            }
        } else {
            alert('Sorry but this service is temporarily unavailable. Please try again later.');
        }
    }
}


// show final chosen model
function show_final(make, model) {
    var rows = document.getElementById('tactable').rows.length;
    for(var j=rows-1;j>0; j--) {
        if (document.getElementById('tactable').rows[j].id != model) {
            document.getElementById('tactable').rows[j].style.display = 'none';
            document.getElementById('tactable').rows[j].className = '';
        } else {
            document.getElementById('tactable').rows[j].style.display = '';
            document.getElementById('tactable').rows[j].className = 'displayrow';
            document.getElementById('tactable').rows[j].cells[3].style.display = '';
            document.getElementById('tactable').rows[0].cells[3].style.display = '';
        }
    }
    var newRow = document.getElementById('tactable').insertRow(document.getElementById('tactable').rows.length);
    var newRowCell = newRow.insertCell(0);
    newRowCell.colSpan= '4';
    newRowCell.setAttribute('id', 'whattodo');
    newRowCellP = document.createElement('p');
    newRowCellPLink = document.createElement('a');
    newRowCellPLink.href = '/how_to_recycle.html#top';
    newRowCellPLinkImg = document.createElement('img');
    newRowCellPLinkImg.id = 'whattodoimg';
    newRowCellPLinkImg.src = '/images/what-to-do-up.gif';
    newRowCellPLinkImg.setAttribute('alt', 'What to do next');
    newRowCellPLinkImg.setAttribute('onmouseover', 'change_image(\'whattodoimg\',\'/images/what-to-do-over.gif\')');
    newRowCellPLinkImg.setAttribute('onmouseout', 'change_image(\'whattodoimg\',\'/images/what-to-do-up.gif\')');
    // next line is for IE
    newRowCellPLinkImg.onmouseover = new Function("change_image('whattodoimg', '/images/what-to-do-over.gif')"); 
    newRowCellPLinkImg.onmouseout = new Function("change_image('whattodoimg', '/images/what-to-do-up.gif')"); 
    newRowCellPLink.appendChild(newRowCellPLinkImg);
    newRowCellP.appendChild(newRowCellPLink);
    newRowCell.appendChild(newRowCellP);
    for (var i=0;i<document.mainform._model.options.length;i++) {
        if (document.mainform._model.options[i].value == model) {
            document.mainform._model.options[i].selected = true;
        } else {
            document.mainform._model.options[i].selected = false;
        }
    }
    // show email field
    show_email_field();
}

function change_image(id, imagesrc) {
    document.getElementById(id).src = imagesrc; 
}

function show_email_field() {
    var formTable = document.getElementById('formtable');
    var exists = document.getElementById('emailrow');
    if (exists == null) {
        var instructionRow = formTable.insertRow(formTable.rows.length);
        var instructionCell = instructionRow.insertCell(0);
        instructionCell.colSpan = '2';
        var instructionH4 = document.createElement('h4');
        instructionH4.className = 'pink';
        var instructionH4Text = document.createTextNode('Want a copy of this valuation?');
        instructionH4.appendChild(instructionH4Text);
        instructionCell.appendChild(instructionH4);
        var instructionP = document.createElement('p');
        var instructionPText = document.createTextNode('Enter your email address if you want this valuation sent to you.');
        instructionP.appendChild(instructionPText);
        instructionCell.appendChild(instructionP);
        var emailRow = formTable.insertRow(formTable.rows.length);
        emailRow.setAttribute('id', 'emailrow');
        var headCell = document.createElement('th');
        var headCellText = document.createTextNode('Email address:');
        headCell.appendChild(headCellText);
        emailRow.appendChild(headCell);
        var inputCell = emailRow.insertCell(1);
        var inputCellInput = document.createElement('input');
        inputCellInput.setAttribute('name', '_contact');
        inputCellInput.setAttribute('id', '_contact');
        inputCellInput.setAttribute('type', 'text');
        inputCellInput.className = 'inputform';
        inputCellInput.value = '';
        inputCell.appendChild(inputCellInput);
        var lineBreak = document.createElement('br');
        inputCell.appendChild(lineBreak);
        var submitButton = document.createElement('img');
        submitButton.src = '/images/submit.gif';
        submitButton.setAttribute('alt', 'Submit');
        submitButton.setAttribute('onmouseover', 'src=\'/images/submit_over.gif\'');
        submitButton.setAttribute('onmouseout', 'src=\'/images/submit.gif\'');
        submitButton.setAttribute('onclick', 'email_me()');
        // now sort for IE
        submitButton.onclick = new Function("email_me()");
        submitButton.onmouseover = new Function("swapImage(this, '/images/submit_over.gif')");
        submitButton.onmouseout = new Function("swapImage(this, '/images/submit.gif')");
        inputCell.appendChild(submitButton);
        emailRow.appendChild(inputCell);
        var comfortTextRow = formTable.insertRow(formTable.rows.length);
        comfortTextRow.setAttribute('id', 'emailcomforttext');
        var comfortTextCell = comfortTextRow.insertCell(0);
        comfortTextCell.colSpan = '2';
        var comfortTextP = document.createElement('p');
        comfortTextCell.appendChild(comfortTextP);
        var comfortTextSpan = document.createElement('span');
        comfortTextSpan.className = 'pink';
        comfortTextSpanText = document.createTextNode('Tip: ');
        comfortTextSpan.appendChild(comfortTextSpanText);
        comfortTextP.appendChild(comfortTextSpan);
        var comfortTextPText = document.createTextNode('We won\'t use this email address for anything else.');
        comfortTextP.appendChild(comfortTextPText);
    }
}

function swapImage(imgElement, imgSrc) {
    imgElement.src = imgSrc;
}

function email_me() {
    xmlHttp=GetXmlHttpObject();
    if (xmlHttp==null) {
        alert ("Your browser does not support AJAX - this is supported in the majority of modern browsers. For best results we recommend using Internet Explorer 7");
        return;
    }
    // get information from HTML
    var rows = document.getElementById('tactable').rows.length;
    for(var j=rows-1;j>0; j--) {
        if (document.getElementById('tactable').rows[j].className == 'displayrow') {
            var make = document.getElementById('tactable').rows[j].cells[1].lastChild.nodeValue;
            var model = document.getElementById('tactable').rows[j].cells[2].lastChild.nodeValue;
            var valueimg = document.getElementById('tactable').rows[j].cells[3].lastChild.src;
            var url="/cgi-bin/tmobile.cgi?_rm=get_valuation_email&_make="+make+"&_model="+model+"&_contact="+document.getElementById('_contact').value+"&sid="+Math.random();
            var valueImgCell = document.getElementById('tactable').rows[j].cells[3];
            for(var k = 0; k < valueImgCell.childNodes.length; k++) {
                if (valueImgCell.childNodes[k].nodeType != 1) {
                    continue;
                }
                url = url + "&_value="+valueImgCell.childNodes[k].src;
            }
            // send information 
            xmlHttp.onreadystatechange=email_me_result;
            xmlHttp.open("GET",url,true);
            xmlHttp.send(null);
        }
    }
}

function email_me_result() {
    if (xmlHttp.readyState==4) {
        if (xmlHttp.status == 200) {
            if (xmlHttp.responseXML != null) {
                var info = xmlHttp.responseXML.getElementsByTagName('info')[0];
                if (info.lastChild.nodeValue == 'success') {
                    // replace with success message
                    var formTable = document.getElementById('formtable');
                    formTable.deleteRow(formTable.rows.length-1);
                    formTable.deleteRow(formTable.rows.length-1);
                    formTable.deleteRow(formTable.rows.length-1);
                    var successTextRow = formTable.insertRow(formTable.rows.length);
                    var successTextCell = successTextRow.insertCell(0);
                    successTextCell.colSpan = '2';
                    var successTextP = document.createElement('p');
                    successTextP.setAttribute('id', 'successtext');
                    var emailAddress = xmlHttp.responseXML.getElementsByTagName('info')[1];
                    var successTextPText = document.createTextNode('We have sent you an email with your valuation to '+emailAddress.lastChild.nodeValue+'. Thank you for using this service.');
                    successTextP.appendChild(successTextPText);
                    successTextCell.appendChild(successTextP);
                } else if (info.lastChild.nodeValue == 'email not valid') {
                    alert('Sorry but your email address is not valid. Please re-check and submit again.');
                }
            } else {
                alert('Sorry but the email feature is not available currently. Please try again later and inform us if you receive the same problem.');
            }
        } else {
            alert('Sorry but email feature is not available currently. Please try again later and inform us if you receive the same problem.');
        }   
    }
}
