﻿// JScript File
var loadingBarAnimating = false;
var returnedScriptCount;
var targetWidthPercentage = 0;
var currentWidthPercentage = 0;
var unreceivedRetailerProducts;
var unreceivedRetailers;
var totalUnreceivedRetailers;
var unreceivedCount;
var requestCount = 0;
var TIME_BETWEEN_REQUESTS = 2000;
var TIMEOUT_BETWEEN_REQUESTS = 7000;
var REQUEST_LIMIT = 5;
var requestTimerId;
var resultCells;
function executeScript()
{
    resultCells = [count];
    var iterator6 = 0;
    for (iterator6 = 0; iterator6 < count; iterator6++)
    {
        resultCells[iterator6] = document.getElementById("productDiv" + iterator6).innerHTML;
    }
    PrepareRetailerProductStatusRequests();
    returnedScriptCount = 0;
    
    
    SetStatus("");
    sortTable();

    UpdateProgressBar();
    AjaxPro.timeoutPeriod = (7 * 1000);
    
    RequestRetailerProductStatus();
}

function PrepareRetailerProductStatusRequests()
{
    unreceivedRetailers = [count];
    unreceivedRetailerProducts = [count];
    unreceivedCount = 0;
    var i;
    for(i=0; i<count; i++)
    {
        if (retailerProductIds[i]!=-1)
        {
            unreceivedRetailerProducts[unreceivedCount] = retailerProductIds[i];
            unreceivedRetailers[unreceivedCount] = retailerIDs[i];
            unreceivedCount++;
        }
    }
    totalUnreceivedRetailers = unreceivedCount;
}

function RequestRetailerProductStatus()
{
    
    if (unreceivedCount > 0)
    {
        requestCount++;
        var iterator2;
        var unreceivedRetailerProductsTemp = [unreceivedCount];
        for(iterator2=0; iterator2<unreceivedCount; iterator2++)
        {
            unreceivedRetailerProductsTemp[iterator2] = unreceivedRetailerProducts[iterator2];
        }
        PriceComparer.RequestRetailerProductStatusList(unreceivedRetailerProductsTemp, RequestRetailerProductStatus_callback);
        
        if (requestCount < REQUEST_LIMIT)
        {
            requestTimerId = setTimeout("RequestRetailerProductStatus()", TIMEOUT_BETWEEN_REQUESTS);
        }
	else
	{
		var iterator4;
		var retailerId1;
		var retailerProductId1;
		for(iterator4=0; iterator4<unreceivedCount; iterator4++)
		{
		    retailerProductId1=unreceivedRetailerProducts[iterator4];
			retailerId1 = unreceivedRetailers[iterator4];
		    document.getElementById("existsField" + retailerId1).value = false;
        	document.getElementById("quoteLinkField" + retailerId1).value = "";
        	RemoveRetailerProductIdFromUnreceivedRetailerProducts(retailerProductId1);
        	setTimeout("DisplayResult(" + retailerId1 + ")", 400);
		}
	}
    }
}

function RequestRetailerProductStatus_callback(result)
{
    if (result.value.error == true)
    {
        document.getElementById("errorDiv").innerHTML = result.value.errorText;
    }
    var iterator1=0;
    var retailerId;
    var retailerProductId;
    for(iterator1=0; iterator1<result.value.resultCount; iterator1++)
    {
        retailerId = result.value.retailerProductStatusResultSet.Tables[0].Rows[iterator1]["retailerId"];
        retailerProductId = result.value.retailerProductStatusResultSet.Tables[0].Rows[iterator1]["retailerProductId"];
        if (retailerProductIdUnreceived(retailerProductId) == true)
        {
            RemoveRetailerProductIdFromUnreceivedRetailerProducts(retailerProductId);
            if (result.value.retailerProductStatusResultSet.Tables[0].Rows[iterator1]["exists"] == false)
            {
                document.getElementById("existsField" + retailerId).value = false;
                document.getElementById("quoteLinkField" + retailerId).value = "";
            }            
            else
            {
            
                document.getElementById("existsField" + retailerId).value = true;
                document.getElementById("inStockField" + retailerId).value = result.value.retailerProductStatusResultSet.Tables[0].Rows[iterator1]["inStock"];
                document.getElementById("priceField" + retailerId).value = result.value.retailerProductStatusResultSet.Tables[0].Rows[iterator1]["price"];
                document.getElementById("deliveryChargeField" + retailerId).value = result.value.retailerProductStatusResultSet.Tables[0].Rows[iterator1]["deliveryCharge"];
                document.getElementById("totalPriceField" + retailerId).value = result.value.retailerProductStatusResultSet.Tables[0].Rows[iterator1]["totalPrice"];
                document.getElementById("oldPriceField" + retailerId).value = result.value.retailerProductStatusResultSet.Tables[0].Rows[iterator1]["oldPrice"];
                document.getElementById("oldDeliveryChargeField" + retailerId).value = result.value.retailerProductStatusResultSet.Tables[0].Rows[iterator1]["oldDeliveryCharge"];
                document.getElementById("oldTotalPriceField" + retailerId).value = result.value.retailerProductStatusResultSet.Tables[0].Rows[iterator1]["oldTotalPrice"];
                document.getElementById("discountCodeField" + retailerId).value = result.value.retailerProductStatusResultSet.Tables[0].Rows[iterator1]["discountCode"];
                document.getElementById("quoteLinkField" + retailerId).value = result.value.retailerProductStatusResultSet.Tables[0].Rows[iterator1]["quoteLink"];
            }
            setTimeout("DisplayResult(" + retailerId + ")", 400);
            
        }
        
    }
    if (requestCount < REQUEST_LIMIT)
    {
        clearTimeout(requestTimerId);
        setTimeout("RequestRetailerProductStatus()", TIME_BETWEEN_REQUESTS);
    }

}

function Pause(millis)
{
var date = new Date();
var curDate = null;

do { curDate = new Date(); }
while(curDate-date < millis);
} 

function retailerProductIdUnreceived(retailerProductId)
{
    var found = false;
    if (unreceivedCount > 0)
    {
        var iterator3 = 0;
        
        while((iterator3 < unreceivedCount)&&(found==false))
        {
            if (unreceivedRetailerProducts[iterator3] == retailerProductId)
            {
                found = true;
            }
            else
            {
                iterator3++;
            }
        }
        
    } 
    return found;
}

function RemoveRetailerProductIdFromUnreceivedRetailerProducts(retailerProductId)
{
    if (unreceivedCount > 0)
    {
        var eye = 0;
        var found = false;
        while((eye < unreceivedCount)&&(found==false))
        {
            if (unreceivedRetailerProducts[eye] == retailerProductId)
            {
                found = true;
            }
            else
            {
                eye++;
            }
        }
        if (found == true)
        {
            if (eye != unreceivedCount-1)
            {
                var tempRetailerProductId;

                tempRetailerProductId= unreceivedRetailerProducts[eye];
                unreceivedRetailerProducts[eye] = unreceivedRetailerProducts[unreceivedCount-1];
                unreceivedRetailerProducts[unreceivedCount-1] = tempRetailerProductId;
                
                
                
                tempRetailerId= unreceivedRetailers[eye];
		unreceivedRetailers[eye] = unreceivedRetailers[unreceivedCount-1];
                unreceivedRetailers[unreceivedCount-1] = tempRetailerId;
            }
            unreceivedRetailerProducts.length--;
            unreceivedCount--;
            unreceivedRetailers.length--;
        }  
    } 
}

function swap(swapIndex)
{   
  
    var tempInnerHtml;
    
    tempInnerHtml= resultCells[swapIndex];
    resultCells[swapIndex] = resultCells[swapIndex+1];
    resultCells[swapIndex+1] = tempInnerHtml;
    
    var tempRetailerStatus;

    tempRetailerStatus = retailerStatus[swapIndex];
    retailerStatus[swapIndex] = retailerStatus[swapIndex+1];
    retailerStatus[swapIndex+1] = tempRetailerStatus;
    
    var tempScriptID;
    
    tempScriptID = retailerIDs[swapIndex];
    retailerIDs[swapIndex] = retailerIDs[swapIndex+1];
    retailerIDs[swapIndex+1] = tempScriptID;
                
    var tempScriptTitle;
    
    tempScriptTitle = retailerTitles[swapIndex];
    retailerTitles[swapIndex] = retailerTitles[swapIndex+1];
    retailerTitles[swapIndex+1] = tempScriptTitle;
        
    var tempRetailerName;
    
    tempRetailerName = retailerNames[swapIndex];
    retailerNames[swapIndex] = retailerNames[swapIndex+1];
    retailerNames[swapIndex+1] = tempRetailerName;
    
    var tempRetailerImage;
    
    tempRetailerImage = retailerImages[swapIndex];
    retailerImages[swapIndex] = retailerImages[swapIndex+1];
    retailerImages[swapIndex+1] = tempRetailerImage;
    
    var tempRetailerUrl;
    
    tempRetailerUrl = retailerUrls[swapIndex];
    retailerUrls[swapIndex] = retailerUrls[swapIndex+1];
    retailerUrls[swapIndex+1] = tempRetailerUrl;
}

function sortTable()
{
    
    var orderChanged = false;
    
    var i;

    i=0;
    if (count>1)
    {
        var swapPerformed = true;
        while (swapPerformed == true)
        {
            swapPerformed = false;
            for(i=0; i < count-1; i++)
            {   
                if (parseInt(retailerStatus[i+1]) > 1)
                { 
                    //window.alert("swap stage start - 2nd item contains a value");
                    if (parseInt(retailerStatus[i]) < 2)
                    {
                        //window.alert("1st item no value returned - swap");
                        swap(i);
                        swapPerformed = true;
                        orderChanged = true;
                    }
                    else 
                    {   
                        var currentItemPrice = document.getElementById("totalPriceField" + retailerIDs[i]).value;
                        var nextItemPrice = document.getElementById("totalPriceField" + retailerIDs[i+1]).value;
                        
                        //window.alert("2nd item is less expensive - swap");
                        if (parseFloat(currentItemPrice) > parseFloat(nextItemPrice))
                        {
                            swap(i);
                            swapPerformed = true;
                            orderChanged = true;
                        }
                       
                    }
                    
                }
                
            }
        }     
        swapPerformed = true;
        while (swapPerformed == true)
        {
            swapPerformed = false;
            for(i=0; i < count-1; i++)
            {   
                if ((parseInt(retailerStatus[i])) < (parseInt(retailerStatus[i+1])))
                {
                    swap(i);
                    swapPerformed = true;
                    orderChanged = true;
                }
            }
        }     
    }
    
    RefreshResultCells();
}

function RefreshResultCells()
{
    var productDiv;
    for (i=0; i < count; i++)
    {
        productDiv = document.getElementById("productDiv" + i);
        
        productDiv.innerHTML = resultCells[i];
    }
}

function DisplayResult(retailerId)
{

    var currentID = retailerId;
    var exists = document.getElementById("existsField" + retailerId).value;
    var inStock = document.getElementById("inStockField" + retailerId).value;
    var productPrice = "£" + document.getElementById("priceField" + retailerId).value;
    var deliveryPrice = "£" + document.getElementById("deliveryChargeField" + retailerId).value;
    var totalPrice = "£" + document.getElementById("totalPriceField" + retailerId).value;
    var oldPrice = "£" + document.getElementById("oldPriceField" + retailerId).value;
    var oldDeliveryPrice = "£" + document.getElementById("oldDeliveryChargeField" + retailerId).value;
    var oldTotalPrice = "£" + document.getElementById("oldTotalPriceField" + retailerId).value;
    var discountCode = document.getElementById("discountCodeField" + retailerId).value;
    var quoteLink = document.getElementById("quoteLinkField" + retailerId).value;
    var stock = "notinstock";
    var stockmsg = "Not in Stock";
    var found = false;
    var i=0;
    
    if (currentID > -1)
    {
        while ((found == false) && (i < count))
        {
            if (retailerIDs[i] == currentID)
            {
                found = true;
            }
            else
            {
                i++;
            }                   
        }     
        if (found == true)
        {
            var retailerTitle = retailerTitles[i];
            var retailerName = retailerNames[i];
            retailerStatus[i] = 0;
            if (exists == "true")
            {                           
                if (inStock == "true")
                {
                    retailerStatus[i] = 4;
                    stock = "instock";
                    stockmsg = "In Stock";
                } 
                else
                {
                    retailerStatus[i] = 3;
                }
                var j=0;
               
                if (productPrice == "£0.00")
                {
                    productPrice = "FREE";
                }
                
                if (deliveryPrice == "£0.00")
                {
                    deliveryPrice = "FREE";
                }
                
                if (totalPrice == "£0.00")
                {
                    totalPrice = "FREE";
                }
                
                if (oldPrice != "£")
                {
                    
                    if (oldPrice == "£0.00")
                    {
                        oldPrice = "FREE";
                    }
                    productPrice = "<span>" + oldPrice + "</span>" + productPrice;
                }
                
                if (oldDeliveryPrice != "£")
                {
                    if (oldDeliveryPrice == "£0.00")
                    {
                        oldDeliveryPrice = "FREE";
                    }
                    
                    deliveryPrice = "<span>" + oldDeliveryPrice + "</span>" + deliveryPrice;
                }
                
                if (oldTotalPrice != "£")
                {
                    
                    
                    if (oldTotalPrice == "£0.00")
                    {
                        oldTotalPrice = "FREE";
                    }
                
                    totalPrice = "<span>" + oldTotalPrice + "</span>" + totalPrice;
                }
                
                if (discountCode == "")
                {
                    discountCode = "&nbsp; ";
                }
                 
                resultCells[i] =        "<table id=\"outputTable" + retailerName + "\" border=\"0\" width=\"100%\"  height=\"40\" class=\"compareResult\" cellpadding=\"0\" cellspacing=\"0\"><tr id=\"outputRow" + retailerName + "\">"
                                      + "<td id=\"titleCell" + retailerName + "\" width=\"160\"><a href=\"GotoLink.aspx?retailer=" + currentID + "&link=" + quoteLink + "\" target=\"_blank\">"
                                      + "<img style=\"border-right:1px solid #cccccc;\" title=\"" + retailerName + "\" alt=\"" + retailerName + "\" onMouseOver=\"SetStatus(' Buy Now from "
                                      + retailerName + "');return true;\" onMouseOut=\"SetStatus('');return true;\" src=\"" + retailerImages[i] + "\" /></a></td>"
                                      + "<td id=\"discountCodeCell" + retailerName + "\" style=\"font-size:15px;font-weight:bold;color:#00d10f;\">" + discountCode + "</td>"
                                      + "<td id=\"priceCell" + retailerName + "\"  width=\"100\">" + productPrice + "</td>"
                                      + "<td id=\"deliveryCell" + retailerName + "\" width=\"100\">" + deliveryPrice + "</td>"
                                      + "<td id=\"totalCell" + retailerName + "\" width=\"100\">" + totalPrice + "</td>"
                                      + "<td id=\"stockCell" + retailerName + "\" width=\"60\"><img src=\"images/" + stock + ".gif\"  alt=\"" + stockmsg +"\" title=\"" + stockmsg +"\" /></td>"
                                      + "<td id=\"buyQuoteCell" + retailerName + "\" valign=\"middle\" width=\"100\"><a href=\"GotoLink.aspx?retailer=" + currentID + "&link=" + quoteLink
                                      + "\" alt=\"More Information on this Quote\" target=\"_blank\" onMouseOver=\"SetStatus(' Buy Now from " + retailerName + "');return true;\" onMouseOut=\"SetStatus('');return true;\">"
                                      + "<img id=\"buyNowButton" + retailerName 
                                      + "\" src=\"images/buynow.gif\" alt=\"Buy Now\"></a></td></tr></table>";
            }
            else
            {
            resultCells[i] =        "<table id=\"outputTable" + retailerName + "\" border=\"0\" width=\"100%\"  height=\"40\" class=\"fetching\" cellpadding=\"0\" cellspacing=\"0\"><tr id=\"outputRow" + retailerName + "\">"
                              + "<td id=\"titleCell" + retailerName + "\" width=\"160\">" + retailerTitle + "</td>"
                              + "<td id=\"priceCell" + retailerName + "\">Unavailable from this Retailer</td></tr></table>";
            }
            
        }
        else
        {
            resultCells[i] =        "<table id=\"outputTable" + retailerName + "\" border=\"0\" width=\"100%\"  height=\"40\" class=\"compareResult\" cellpadding=\"0\" cellspacing=\"0\"><tr id=\"outputRow" + retailerName + "\">"
                              + "<td id=\"titleCell" + retailerName + "\" width=\"160\">Error</td>"
                              + "<td id=\"priceCell" + retailerName + "\">Error Querying This Retailer. Error 1A</td></tr></table>";
        }
    }
    else
    {
        resultCells[i] =        "<table id=\"outputTable" + retailerName + "\" border=\"0\" width=\"100%\"  height=\"40\" class=\"compareResult\" cellpadding=\"0\" cellspacing=\"0\"><tr id=\"outputRow" + retailerName + "\">"
                              + "<td id=\"titleCell" + retailerName + "\" width=\"160\">Error</td>"
                              + "<td id=\"priceCell" + retailerName + "\">Error Querying This Retailer. Error 2A</td></tr><tr><td colspan=\"7\" style=\"height:1px;background:#085c82;\"></td></tr></table>";
        /*resultCells[i] =        "<table id=\"outputTable" + currentID + "\" border=\"0\" width=\"100%\"  height=\"40\" class=\"result\"><tr id=\"insurerRow" + currentID + "\">"
                              + "<td id=\"titleCell" + currentID + "\" width=\"60%\">" + retailerTitle + "</td>"
                              + "<td id=\"priceCell" + currentID + "\" width=\"13%\">Unavailable</td></tr></table>";*/
    }
 
    
    sortTable();
    returnedScriptCount++;
    UpdateProgressBar();
}

function UpdateProgressBar()
{
 
    targetWidthPercentage = Math.round((((totalUnreceivedRetailers-unreceivedCount)+1) / (totalUnreceivedRetailers+1)) * 100);
    
    if (loadingBarAnimating == false)
    {
        StartAnimatingProgressBar();                
    }
}

function StartAnimatingProgressBar()
{
    
    if (targetWidthPercentage > 99)
    {
        targetWidthPercentage = 99;
    }
    loadingBarAnimating = true;
    AnimateNextFrame("progressInner", currentWidthPercentage, targetWidthPercentage, -1, -1, 200, 1, "%", "FinishedAnimatingProgressBar()");
    currentWidthPercentage = targetWidthPercentage;
}

function FinishedAnimatingProgressBar()
{
    loadingBarAnimating = false;

    if (currentWidthPercentage != targetWidthPercentage)
    {
        StartAnimatingProgressBar();
    }
    else if (unreceivedCount == 0)
    {
        var progressBarOuter = document.getElementById("progressOuter");
        progressBarOuter.className = "progressOuterCompleted";
        
        
        var preloadedBookmarkImage = document.getElementById("preloadedBookmarkImage");
        var bookmarkPlaceholder = document.getElementById("bookmarkPlaceholder");
        bookmarkPlaceholder.innerHTML = "<img id=\"bookmarkImage\" style=\"float: left\" src=\"" + preloadedBookmarkImage.src + "\" />";
        
    }
}

window.onload = executeScript;
