var arrChnl = [];
var genericUnsubscribe = false;
var isAuctionBroadcast = true;
var channelGeneric = '/AB';

//subscribeAuctionBroadcast();

function subscribeAuctionBroadcast(channel) {
    //channel = '/' + channel;

    client.subscribe({
        channel: channel,
        onSuccess: function(args) {
            //util.log('Subscribed to ' + channel + '.');


        },
        onFailure: function(args) {
            //util.log('The client could not subscribe to ' + channel + '... ' + args.error);
        },
        onReceive: function(args) {

	//if (args.data.IsRe) return;

            if (args.data.Lot == '' && !args.data.IsOver)
                return;

            // Channel Limit
            var chnlLimit = 3;
            if (!searchArray(arrChnl, args.data.UniqueAuctionID) && arrChnl.length >= chnlLimit) {
                abUnsubscribe(channelGeneric, arrChnl);
                return;
            }

            var ID = args.data.UniqueAuctionID.toString();

            setLabel('divABHeader', getValue(localPrefix + (args.data.IsRe ? 'hdnLastAuctionReplay' : 'hdnFeaturedLive')));

            // Add Channel
            if (!searchArray(arrChnl, args.data.UniqueAuctionID) && arrChnl.length < chnlLimit) {
                arrChnl[arrChnl.length] = args.data.UniqueAuctionID;

                // Add Template Header
                if (getLabel('divAB') == '') {
                    setLabel('divAB', getLabel('abHeaderTemplate'));
                    setLabel('abHeaderTemplate', '');
                }

                var abRowTemplate = getLabel('abRowTemplate');
                setLabel('divABTable', getLabel('divABTable') + abRowTemplate.replace(/\###/g, ID));



            }

            // New Item
            if (args.data.Lot != getLabel('abLot' + ID)) {
                setLabel('abVehicle' + ID, args.data.Vehicle);
                setLabel('abLot' + ID, args.data.Lot);
                setLabel('abImage' + ID, '<img src="/images/noimage.jpg" width="96" height="72" />');
                setLabel('abTitle' + ID, '&nbsp;');
                setLabel('abMileage' + ID, '&nbsp;');
                setLabel('abInventoryID' + ID, '');
            }

            // Statndard Update
            setLabel('abBid' + ID, args.data.BidShow);
            setLabel('abBuyer' + ID, (args.data.Buyer == 'Starting Bid' ? '&nbsp;' : (args.data.Bid == 0 ? '&nbsp;' : getValue(localPrefix + 'hdnABFrom')) + ' ') + args.data.Buyer.toUpperCase());

            if (args.data.IsSold && args.data.IsOnApproval) {
                str = '<div style="color: green;">Sold - On Approval!</div>';
            }
            else if (args.data.IsSold && !args.data.IsOnApproval) {
                str = '<div style="color: green;">Sold!</div>';
            }
            else if (args.data.IsCountdown) {
                str = '<div style="color: red;">Closing...</div>';
            }
            else {
                str = '<div class="header">&nbsp;</div>';
            }

            setLabel('abStatus' + ID, str);

            if (args.data.Lot != getLabel('abLot' + ID) || getLabel('abTitle' + ID) == '&nbsp;') {
                SearchByLot(args.data.AuctionHouse, args.data.Lot, ID);
            }

            return;



        }
    });

}

function SearchByLot(AuctionHouse, Lot, UniqueAuctionID) {

    client.publish({
    requestUrl: 'http://api.ridesafely.com/WebSync/Action.aspx',
    // requestUrl: '/WebSync/Action.aspx',
        channel: '/LocateRec',
        data: {
            AuctionHouse: AuctionHouse,
            UniqueAuctionID: UniqueAuctionID,
            Lot: Lot,
            Action: 'INVBYLOT'
        },
        onSuccess: function(args) {

            var ID = args.data.UniqueAuctionID;

            // Update
            if (getLabel('abLot' + ID) == args.data.Lot) {
                setLabel('abImage' + ID, '<img src="' + args.data.ImgURL + '" width="96" height="72" />');
                setLabel('abTitle' + ID, args.data.TitleType);
                setLabel('abMileage' + ID, formatNumber(args.data.Mileage) + ' - ' + getValue(localPrefix + 'lblHdnMileage_' + args.data.MileageStatus));
                setLabel('abIID' + ID, args.data.InventoryID);
            }

            return;

        },
        onFailure: function(args) {
            // DO NOTHING
        }
    });

}

function abNavigate(row) {
    if (getLabel('abIID' + row) != '') {
        window.location.href = '/Inventory.aspx?InventoryID=' + getLabel('abIID' + row);
    }
}

function formatCurrency(num) {
    num = num.toString().replace(/\$|\,/g, '');
    if (isNaN(num)) num = '0';
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num * 100 + 0.50000000001);
    cents = num % 100;
    num = Math.floor(num / 100).toString();
    if (cents < 10) cents = '0' + cents;
    for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
        num = num.substring(0, num.length - (4 * i + 3)) + ',' + num.substring(num.length - (4 * i + 3));
    // return (((sign) ? '' : '-') + '$' + num + '.' + cents);
    return (((sign) ? '' : '-') + '$' + num);
}
function searchArray(arr, obj) {
    for (var i = 0; i < arr.length; i++) {
        if (arr[i] == obj) return true;
    }
    return false;
}
function formatNumber(nStr) {
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

function getTestimonials() {
    setLabel('divTestimonial', '<img src="/images/ajax-loader.gif" />');
    setLabel('divTestFrom', '');

    client.publish({
        requestUrl: 'http://api.ridesafely.com/WebSync/Action.aspx',
        channel: '/Testimonials',
        data: {
            Action: 'TESTIMONIAL',
            TestimonialID: getLabel('hdnTestID')
        },
        onSuccess: function(args) {


            setLabel('divTestimonial', args.data.Testimonial);
            setLabel('divTestFrom', args.data.Initials + ', ' + args.data.Location);
            setLabel('hdnTestID', args.data.TestimonialID);

            return;

        },
        onFailure: function(args) {
            // DO NOTHING
        }
    });
}

function abUnsubscribe(unsubscribeChannel, chnlArray) {

    if (genericUnsubscribe) return;

    genericUnsubscribe = true;    

    client.unsubscribe({
        channel: unsubscribeChannel,
        onComplete: function() {
            //util.log('unsubscribe complete');
        },
        onSuccess: function(args) {
            for (var i = 0; i < chnlArray.length; i++) {
                subscribeAuctionBroadcast('/AB' + chnlArray[i]);
            }
        },
        onFailure: function(args) {
            //util.log('unsubscribe fail');
        }
    });
}
