var products = new Array();
var poppedId;
var processedProducts = new Array();
var xHRObject;
var scriptLocation = 'http://www.nichecomparison.com/';
/*var scriptLocation = 'http://localhost:49503/';*/

function getRequestObj() {  
    if (window.XMLHttpRequest) {
        return new XMLHttpRequest()
    }
    else if (window.ActiveXObject) {
        return new ActiveXObject("Microsoft.XMLHTTP")
    }
}
  
function nc_render() {
    document.writeln('<div id="ncResults">');
    document.writeln('  <div id="ncFetchingData"><span>Fetching comparison data..</span></div>');
    document.writeln('</div>');

    nc_fetchNiche(nicheId);
}

function nc_fetchNiche(id) {
    xHRObject = getRequestObj();
    xHRObject.open('GET', scriptLocation+'proxy.aspx?nicheId=' + id + '&rnd=' + Math.random(), true);
    xHRObject.onreadystatechange = nc_fetchNicheRSC;
    
    xHRObject.send(null);
}

function nc_fetchNicheRSC () {
    if (xHRObject.readyState == 4) {
        // Parse output XML and populate interface
        var ncResults = document.getElementById('ncResults');

        var xml = xHRObject.responseXML
        var headerElement
        var productElement
        var productImageElement
        var nameElement
        var logoElement
        var statusElement
        var fetchingPriceElement
        var voucherCodesElement
        var voucherCodeCount
        var linkElement

        ncResults.innerHTML = '';

        /*
        if (xml.getElementsByTagName('niche')[0].getAttribute('description')) {
            headerElement = document.createElement('h2');
            headerElement.appendChild(document.createTextNode(xml.getElementsByTagName('niche')[0].getAttribute('description')));
            ncResults.appendChild(headerElement);
        }*/

        for (i = 0; i <= xml.getElementsByTagName('products')[0].childNodes.length - 1; i++) {
            productElement = document.createElement('div');
            productElement.setAttribute('id', 'nc' + xml.getElementsByTagName('products')[0].childNodes[i].getAttribute('id'));
            productElement.className = 'ncProduct';
            ncResults.appendChild(productElement);

            productImageElement=document.createElement('img');
            productImageElement.className='ncProductImage';
            productImageElement.setAttribute('width','75');
            productImageElement.setAttribute('height','55');
            productImageElement.setAttribute('alt', 'Product Image');
            if (xml.getElementsByTagName('products')[0].childNodes[i].getAttribute('productImage')) {
                productImageElement.src=xml.getElementsByTagName('products')[0].childNodes[i].getAttribute('productImage');
            }
            else if (xml.getElementsByTagName('niche')[0].getAttribute('defaultImageURL')) {
                productImageElement.src = xml.getElementsByTagName('niche')[0].getAttribute('defaultImageURL');
            }
            else {
                productImageElement.src = '/images/noproductimage.gif';
            }
            productElement.appendChild(productImageElement);

            nameElement = document.createElement('span')
            nameElement.className='ncRetailer';
            nameElement.innerHTML = xml.getElementsByTagName('products')[0].childNodes[i].getAttribute('retailer');
            productElement.appendChild(nameElement)

            if (xml.getElementsByTagName('products')[0].childNodes[i].getAttribute('retailerLogo')) {           
                logoElement = document.createElement('img');
                logoElement.setAttribute('src', xml.getElementsByTagName('products')[0].childNodes[i].getAttribute('retailerLogo'));
                logoElement.setAttribute("width", "88");
                logoElement.setAttribute("height", "30");
                logoElement.setAttribute("alt", "Visit " + xml.getElementsByTagName('products')[0].childNodes[i].getAttribute('retailer'));

                linkElement = document.createElement('a');
                linkElement.setAttribute('href', 'http://www.nichecomparison.com/redirect.aspx?productId=' + xml.getElementsByTagName('products')[0].childNodes[i].getAttribute('id'));
                linkElement.setAttribute('target', '_blank');
                linkElement.className = 'ncRetailerLogo';
                linkElement.appendChild(logoElement);            
                
                productElement.appendChild(linkElement)
            }

            statusElement = document.createElement('div');
            statusElement.className='ncStatus';
            productElement.appendChild(statusElement);

            fetchingPriceElement = document.createElement('span');
            fetchingPriceElement.className='ncFetchingPrice';
            fetchingPriceElement.appendChild(document.createTextNode('Fetching Price'));
            statusElement.appendChild(fetchingPriceElement);

            voucherCodesElement = document.createElement('span');
            voucherCodesElement.className = 'ncVoucherCodes';

            voucherCodeCount = parseInt(xml.getElementsByTagName('products')[0].childNodes[i].getAttribute('codes'));

            if (voucherCodeCount > 0) {
                voucherCodesElement.innerHTML = '<a href=\'http://www.nichecomparison.com/viewcodes.aspx?retailerId='+ xml.getElementsByTagName('products')[0].childNodes[i].getAttribute('retailerId')+'\' class=\'ncShowCodesLink\' target=\'_blank\' onClick=\'openWindow("http://www.nichecomparison.com/viewcodes.aspx?retailerId='+ xml.getElementsByTagName('products')[0].childNodes[i].getAttribute('retailerId')+'","voucherCodes",400,400);return false;\'>' + voucherCodeCount + ' Voucher Code(s) Found</a>';
 

/*
                voucherCodesElement.appendChild(document.createTextNode(voucherCodeCount + ' voucher code(s) found for this store - '));

                linkElement = document.createElement('a');
                linkElement.setAttribute('href', 'http://www.nichecomparison.com/viewcodes.aspx?retailerId=' + xml.getElementsByTagName('products')[0].childNodes[i].getAttribute('retailerId'));
                linkElement.setAttribute('target', '_blank');
                linkElement.onclick = openWindow(eval('http://www.nichecomparison.com/viewcodes.aspx?retailerId=' + xml.getElementsByTagName('products')[0].childNodes[i].getAttribute('retailerId')), 'voucherCodes', 400, 400);
                linkElement.className = 'ncShowCodesLink';
                linkElement.appendChild(document.createTextNode('show'));

                voucherCodesElement.appendChild(linkElement)*/

            }
            else {
                voucherCodesElement.appendChild(document.createTextNode('No Voucher Codes Found'));
            }

            productElement.appendChild(voucherCodesElement);
            
            
            products.push(xml.getElementsByTagName('products')[0].childNodes[i].getAttribute('id'));
//            insertArray(products, 1, xml.getElementsByTagName('products')[0].childNodes[i].getAttribute('id'));
        }
        products=products.reverse();

        nc_popProduct();
    }
}

function nc_popProduct() {
    poppedId = products.pop();

    nc_fetchProduct(poppedId);
}

var timerID;

function nc_fetchProduct(id) {
    var resultsElement = document.getElementById('ncResults');
    var productElement = document.getElementById('nc' + poppedId);
    
    resultsElement.insertBefore(productElement,resultsElement.firstChild);
    
    
    xHRObject = getRequestObj();
    xHRObject.open('GET', scriptLocation+'proxy.aspx?productId=' + id + '&rnd=' + Math.random(), true);
    xHRObject.onreadystatechange = nc_fetchProductRSC;

//    timerID=window.setTimeout('abortConnection()', 2000);
    xHRObject.send(null);
}

var aborted = false;

function abortConnection() {
    aborted=true;
    xHRObject.abort();
}

function nc_fetchProductRSC() {
    var productElement = document.getElementById('nc' + poppedId);
    var statusElement;
    var statusSpanElement;
    var priceSpanElement;
    var LinkElement;
    var xml;

    if (xHRObject.readyState == 4) {

        for (i = 0; i <= productElement.childNodes.length; i++) {
            if (productElement.childNodes[i].className == 'ncStatus') {
                statusElement = productElement.childNodes[i];
                break;
            }
        }

        xml = xHRObject.responseXML;

        statusElement.innerHTML = '';

        statusSpanElement = document.createElement("span");
        statusSpanElement.appendChild(document.createTextNode(xml.getElementsByTagName('status')[0].childNodes[0].nodeValue));
        statusElement.appendChild(statusSpanElement);

        switch (xml.getElementsByTagName('status')[0].childNodes[0].nodeValue) {
            case 'In Stock':
                statusSpanElement.className = 'ncInStock';
                break;

            case 'Pre-Order':
                statusSpanElement.className = 'ncPreOrder';
                break;
              
            case 'Out Of Stock':
                statusSpanElement.className = 'ncNoStock';
                break;

            case 'Error':
                statusSpanElement.className = 'ncError';
                break;
        }

        if (xml.getElementsByTagName('price').length>0) {
            priceSpanElement = document.createElement('span');
            priceSpanElement.className = 'ncPrice';
            priceSpanElement.appendChild(document.createTextNode('£' + xml.getElementsByTagName('price')[0].childNodes[0].nodeValue));
            statusElement.appendChild(priceSpanElement);

            insertProduct(xml.getElementsByTagName('price')[0].childNodes[0].nodeValue, productElement);
            
        } else {
            insertProduct(-1, productElement);
        }

        linkElement = document.createElement('a');
        linkElement.setAttribute('href', 'http://www.nichecomparison.com/redirect.aspx?productId=' + xml.getElementsByTagName('product')[0].getAttribute('id'));
        linkElement.setAttribute('target', '_blank');
        linkElement.className = 'ncBuyLink';
        linkElement.appendChild(document.createTextNode('Buy Now'));
        statusElement.appendChild(linkElement, statusElement);

        sort();

        if (products.length>0) {        
            nc_popProduct();    
        }

    ///    }
    }
}

function sort() {
    var resultsElement = document.getElementById('ncResults');
       
    for (i = 0; i < processedProducts.length; i++) {
        resultsElement.appendChild(processedProducts[i][1]);
    }
}

function insertProduct(price, product) {
    for (i = 0; i < processedProducts.length; i++) {
        if (parseFloat(price) < parseFloat(processedProducts[i][0]) && parseFloat(price) != -1) {
//            window.alert('insert - i=' + i + ', l=' + processedProducts.length);
            processedProducts=insertArray(processedProducts, i-1, new Array(price, product));
//            window.alert(processedProducts.length);
            return;
        }    
    }

//    window.alert('add - l='+processedProducts.length);
    processedProducts[processedProducts.length] = new Array(price, product);
}

function insertArray(array, afterIndex, item) {
//    if (array.length > 0) {
        var first = array.slice(0, afterIndex + 1);
        var second = array.slice(afterIndex + 1);
        first.push(item);
        return first.concat(second);
   // }
  //  else {
      //  array[0]=item;
    //}
}

function openWindow(url, name, width, height) {
    var leftVal = (screen.width/2) - (width/2);
    var topVal = (screen.height / 2) - (height / 2);

    var win = window.open(url, name, 'width=' + width + ',height=' + height + ',left=' + leftVal + ',top=' + topVal + ',scrollbars=yes,resizable=yes,status=no,toolbar=no,location=no,menubar=no');

    win.focus();
}