﻿//Auction status Consts
var AuctionStatus_Live = '1';
var AuctionStatus_SoldEx = '2';
var AuctionStatus_Sold = '4';
var AuctionStatus_TimeOut = '3';

// Global variables
var TotalSeconds = 0;
var IsTimerRunning = false;

// Global constents
var CaptionCount = 3;

// Auction url constents
var BidUrl = '/confirmbid.aspx?AuctionCode=';
var ItemDetailUrl = ' /popups/viewdetail.aspx?StockCode=';
var FallingAuctionsHelpUrl = '/popups/fallingauctionshelp.aspx';

function setRequest() {
    try {
        var request = new createRequest();
        if (request) {
            var url = "/codehouse_auctionhandler.ashx?command=3&timestamp=" + new Date().getTime();
            request.open("GET", url, true);
            request.onreadystatechange = function() { managestatechange(request); };
            request.send("");
        }
    }
    catch (ie6Fail) {
        var request = new ActiveXObject("Microsoft.XMLHTTP");
        if (request) {
            var url = "/codehouse_auctionhandler.ashx?command=3&timestamp=" + new Date().getTime();
            request.open("GET", url, true);
            request.onreadystatechange = function() { managestatechange(request); };
            request.send("");
        }
    }
}

function managestatechange(request) {
    try {
        if (request.readyState == 4 && request.responseXML)
            setFallingAuction(request.responseXML);
    }
    catch (e) {
        //alert(e);
    }
}

function setFallingAuction(response) {
    // customerId is id of the customer who logged in the TJC
    // value can be zero, no customer is logged in yet
    var customerId = parseInt(document.getElementById('CustomerID').value, 10);

    var showAuction = response && response.documentElement && response.documentElement.childNodes.length != 0;

    if (showAuction) {
        for (var i = 0; i < response.getElementsByTagName("Auction").length; i++) {
            // creates and intializes auction item properties
            var auctionItemProperty = new AuctionItemProperty();
            auctionItemProperty.Initalizes(i);

            if (auctionItemProperty.Validates()) {
                var wsAuctionItem = new WsAuctionItem(response.getElementsByTagName("Auction")[i]);
                if (wsAuctionItem) {
                    auctionItemProperty.Updates(wsAuctionItem, customerId)

                    if (wsAuctionItem.auctionStatus == AuctionStatus_TimeOut)
                        IsTimerRunning = false;

                    var timeRemaining = wsAuctionItem.bidCount;
                    if (!IsTimerRunning && timeRemaining > 0)
                        TotalSeconds = timeRemaining;
                }
            }
        }
    }

    ShowOrHideAuction(showAuction);
}


function WsAuctionItem(xmlElement) {
    var moz = (typeof document.implementation != 'undefined')
           && (typeof document.implementation.createDocument != 'undefined');
    var ie = typeof window.ActiveXObject != 'undefined';

    if (moz) {
        this.auctionCode = xmlElement.getElementsByTagName("AuctionCode")[0].firstChild.nodeValue;
        this.startPrice = xmlElement.getElementsByTagName("StartPrice")[0].firstChild.nodeValue;
        this.currentPrice = xmlElement.getElementsByTagName("CurrentPrice")[0].firstChild.nodeValue;
        this.stockRemaining = xmlElement.getElementsByTagName("StockRemaining")[0].firstChild.nodeValue;
        this.bidCount = xmlElement.getElementsByTagName("BidCount")[0].firstChild.nodeValue;
        this.stockCode = xmlElement.getElementsByTagName("StockCode")[0].firstChild.nodeValue;
        this.stockDescription = xmlElement.getElementsByTagName("StockDescription")[0].firstChild.nodeValue;
        this.imageName = xmlElement.getElementsByTagName("ImageName")[0].firstChild.nodeValue;
        this.auctionStatus = xmlElement.getElementsByTagName("AuctionStatus")[0].firstChild.nodeValue;
    }
    if (ie) {
        this.auctionCode = xmlElement.childNodes[0].text;
        this.startPrice = xmlElement.childNodes[1].text;
        this.currentPrice = xmlElement.childNodes[2].text;
        this.stockRemaining = xmlElement.childNodes[3].text;
        this.bidCount = xmlElement.childNodes[4].text;
        this.stockCode = xmlElement.childNodes[5].text;
        this.stockDescription = xmlElement.childNodes[6].text;
        this.imageName = xmlElement.childNodes[7].text;
        this.auctionStatus = xmlElement.childNodes[8].text;
    }
}

// Object that holds all the falling auction related controls
// Their values will be updated by TLC's web service provided periodically
function AuctionItemProperty() {
    this.lblItemDescription;
    this.lblStock;
    this.imgFAuction;
    this.lblStartingPrice;
    this.lblCurrentPrice;
    this.ImgLogin;
    //     this.ImgLoginLink;
    this.ImgPlaceBid;
    this.ImgPlaceBidLink;
    this.ImageView;
    this.ImageViewLink;
}

// Initialize object properties by asssigning their correspondent page contorls
AuctionItemProperty.prototype.Initalizes = function(count) {
    // Auction item controls
    this.lblItemDescription = document.getElementById('lblItemDescription' + count);
    this.lblStock = document.getElementById('lblStock' + count);
    this.imgFAuction = document.getElementById('imgFAuction' + count);
    this.lblStartingPrice = document.getElementById('lblStartingPrice' + count);
    this.lblCurrentPrice = document.getElementById('lblCurrentPrice' + count);
    // Auction item buttons
    this.ImgLogin = document.getElementById('ctl12_ImgLogin' + count); // !!! ctl03 hard coded
    // this.ImgLoginLink = document.getElementById('bidLink' + count);
    this.ImgPlaceBid = document.getElementById('ctl12_ImgPlaceBid' + count); // !!! ctl03 hard coded
    this.ImgPlaceBidLink = document.getElementById('placeBid' + count);
    this.ImageView = document.getElementById('ImageView' + count);
    this.ImageViewLink = document.getElementById('ImageLink' + count);
}

// Only returns true, if all the following controls exist in the falling auction page
AuctionItemProperty.prototype.Validates = function() {
    return this.Exists('lblItemDescription') && this.Exists('lblStock') && this.Exists('imgFAuction')
            && this.Exists('lblStartingPrice') && this.Exists('lblCurrentPrice');
}

// Only returns true, if the control with the given id is present in the page
AuctionItemProperty.prototype.Exists = function(idPrefix) {
    switch (idPrefix) {
        case 'lblItemDescription':
            return this.lblItemDescription != null
        case 'lblStock':
            return this.lblStock != null;
        case 'imgFAuction':
            return this.imgFAuction != null;
        case 'lblStartingPrice':
            return this.lblStartingPrice != null;
        case 'lblCurrentPrice':
            return this.lblCurrentPrice != null;
        case 'ImgLogin':
            return this.ImgLogin != null;
        case 'ImgPlaceBid':
            return this.ImgPlaceBid != null;
        case 'ImgPlaceBidLink':
            return this.ImgPlaceBidLink != null;
        case 'ImageView':
            return this.ImageView != null;
        case 'ImageViewLink':
            return this.ImageViewLink != null;
            // case 'ImgLoginLink':
            // return this.ImgLoginLink != null;
    }
}

// Apart from auction' current price, 
// all the auction item controls are updated with the given auction info
AuctionItemProperty.prototype.Updates = function(auctionItem, customerId) {
    this.lblItemDescription.innerHTML = auctionItem.stockDescription;
    this.lblStock.innerHTML = 'Item Code:'+ '<b class="itemcode">'+ auctionItem.stockCode+'</b>';
    
    this.imgFAuction.src = auctionItem.imageName;
   
    this.imgFAuction.style.display = '';
    this.lblStartingPrice.innerHTML = 'Starting Price: £' + auctionItem.startPrice;
    this.UpdatesCurrentPrice(auctionItem);
    this.ResetButtonsStatus(auctionItem, customerId);
    this.ImageViewLink.href = ItemDetailUrl + auctionItem.stockCode;
}

// Updates only auction current price
AuctionItemProperty.prototype.UpdatesCurrentPrice = function(auctionItem) {
    switch (auctionItem.auctionStatus) {
        case AuctionStatus_Live:
            if (parseInt(auctionItem.stockRemaining) > 0)
                this.lblCurrentPrice.innerHTML = 'Current Price: £' + auctionItem.currentPrice;
            else
                this.lblCurrentPrice.innerHTML = 'Sold for £' + auctionItem.currentPrice;
            break;
        case AuctionStatus_SoldEx:
        case AuctionStatus_Sold:
            this.lblCurrentPrice.innerHTML = 'Sold for £' + auctionItem.currentPrice;
            break;
        case AuctionStatus_TimeOut:
            this.lblCurrentPrice.innerHTML = 'Time out for £' + auctionItem.currentPrice;
            break;
        default:
            this.lblCurrentPrice.innerHTML = 'Current Price: £' + auctionItem.currentPrice;
            break;
    }
}

// Updates status of the buttons, namely "Login to bid" and "View product"
AuctionItemProperty.prototype.ResetButtonsStatus = function(auctionItem, customerId) {
    if (auctionItem.auctionStatus == AuctionStatus_Live && parseInt(auctionItem.stockRemaining) > 0)
        this.ToggleLoginAndPlaceBidButtons(false, auctionItem, customerId);
    else
        this.ToggleLoginAndPlaceBidButtons(true, auctionItem, customerId);
    this.VisulizeViewProductButton(auctionItem.stockCode);
}

// Enable or disable the buttons
AuctionItemProperty.prototype.ToggleLoginAndPlaceBidButtons = function(disabled, auctionItem, customerId) {
    if (this.Exists('ImgPlaceBid') && this.Exists('ImgPlaceBidLink')) {
        var placeBidUrl = BidUrl + auctionItem.auctionCode;
        this.EnableDisableButton(this.ImgPlaceBid, this.ImgPlaceBidLink, placeBidUrl, disabled);
    }
}

AuctionItemProperty.prototype.VisulizeViewProductButton = function(stockCode) {
    if (this.Exists('ImageView') && this.Exists('ImageViewLink'))
        this.EnableDisableButton(this.ImageView, this.ImageViewLink, ItemDetailUrl + stockCode, false);
        
    if (this.Exists('imgFAuction') && this.Exists('imgFAuction'))
        this.EnableDisableButton(this.imgFAuction, this.ImageViewLink, ItemDetailUrl + stockCode, false);
        
}

AuctionItemProperty.prototype.EnableDisableButton = function(btn, btnLink, btnHref, disabled) {
    btn.style.display = '';
    btn.style.cursor = disabled ? 'arrow' : 'normal';
    btn.disabled = disabled;
    if (btnLink)
        btnLink.href = disabled ? '/Falling-Auctions.aspx' : btnHref;
}

function ShowOrHideAuction(show) {
    document.getElementById('tblFallingAuction').style.display = show ? '' : 'none';
    document.getElementById('tblFallingAuctionLoad').style.display = show ? '' : 'none';
    document.getElementById('lblNoFallingAuction').style.display = show ? 'none' : '';
    document.getElementById('lblNoFallingAuction').style.display = show ? 'none' : '';
}

function CountDown() {
    try {
        if (TotalSeconds > 0) {
            TotalSeconds--;
            var min = parseInt(TotalSeconds / 60, 10);
            var sec = TotalSeconds % 60;
            SetCaptionInnerHtml('Time Remaining: ' + min + ' Minutes and ' + sec + ' Seconds');
            IsTimerRunning = true;
        }
        else {
            SetCaptionInnerHtml('Our next auctions will start in a few minutes');
            IsTimerRunning = false;
        }
    }
    catch (e) {
        IsTimerRunning = false;
    }
}

function SetCaptionInnerHtml(innerHtml) {
    for (i = 1; i <= CaptionCount; i++)
        document.getElementById('Caption' + i).innerHTML = innerHtml;
}

function ShowHelp() {
    try {
        window.open(FallingAuctionsHelpUrl, 'imgwindow', 'WIDTH=900,HEIGHT=300,TOP=70,LEFT=160,scrollbars=yes,menubar=no,toolbars=no,resizable =yes');
    }
    catch (e)
	{ }
}

function init() {
    window.setInterval('setRequest()', 3000);
    window.setInterval('CountDown()', 1000);
}

init();

function requireCustomerLogin() {
    alert('Please login!');
}



function togglePannelStatus(content)
{
    var expand = (content.style.display=="none");
    content.style.display = (expand ? "block" : "none");
    toggleChevronIcon(content);
}

// current animated collapsible panel content
var currentContent = null;

function togglePannelAnimatedStatus(content, interval, step)
{
    // wait for another animated expand/collapse action to end
    if (currentContent==null)
    {
        currentContent = content;
        var expand = (content.style.display=="none");
        if (expand)
            content.style.display = "block";
        var max_height = content.offsetHeight;

        var step_height = step + (expand ? 0 : -max_height);
        toggleChevronIcon(content);
                
        // schedule first animated collapse/expand event
        content.style.height = Math.abs(step_height) + "px";
        setTimeout("togglePannelAnimatingStatus("
            + interval + "," + step
            + "," + max_height + "," + step_height + ")", interval);
    }
}

function togglePannelAnimatingStatus(interval,
    step, max_height, step_height)
{
    var step_height_abs = Math.abs(step_height);

    // schedule next animated collapse/expand event
    if (step_height_abs>=step && step_height_abs<=(max_height-step))
    {
        step_height += step;
        currentContent.style.height = Math.abs(step_height) + "px";
        setTimeout("togglePannelAnimatingStatus("
            + interval + "," + step
            + "," + max_height + "," + step_height + ")", interval);
    }
    // animated expand/collapse done
    else
    {
        if (step_height_abs<step)
            currentContent.style.display = "none";
        currentContent.style.height = "";
        currentContent = null;
    }
}

// change chevron icon into either collapse or expand
function toggleChevronIcon(content)
{
    var chevron = content.parentNode
        .firstChild.childNodes[1].childNodes[0];
    var expand = (chevron.src.indexOf("arrow-up.gif")>0);
    chevron.src = chevron.src
        .split(expand ? "arrow-up.gif" : "arrow-down.gif")
        .join(expand ? "arrow-down.gif" : "arrow-up.gif");
}
    
 