$(document).ready(function() {
    // All the functions that need to be triggered as soon as the entire page loads
    // Each one has it's own check to see whether they need to do anything or not
    initHeader();
    initMenu();
    initCarousel();
    initFeaturedLots();
    initInputs();
    initTooltips();
    initBackGrounds();
    initContactSelect();
    initOutlook();
    initLotInfo();
    initCatImage();
    initKavelDetail();
    initInternalLinks();
    initNewsLetter();
    initLocations();
    initFaq();
    initAttention();
    initProcess();
});


// The speed of the fade ins/outs
var tempo = 500;
var clockpos = 0;

// Initialise the thickbox dynamics once it's been loaded
var imagePopup_pageLength = 1;
var imagePopup_current = 1;
var imagePopup_max = 30;
var imagePopup_images;
var imagePopup_test = new Array();

var viewerImages;

var _Mpage = 'url';

var baseURL;
var begin;
var languageText = new Object();
var projectValidationServiceUrl = 'project/views/shared/validationhandler.ashx';
var registrationUrl;
var searchUrl = '';
var twkTimeOuts = new Object();

// Initialise the info popup for the menu items
function initMenu() {

    if ($('.categories').length) {

        // On click of the little 'i' in the menu, show the sub options
        $('.categories .info').click(function() {

            t = $(this);
            li = t.parent();
            v = 53;

            li.siblings().removeClass('active');
            li.addClass('active');
            itemHeight = li.height() + 9;
            $('.whiteBg', li).height(itemHeight);

            // Double check the positioning
            pop = $('.categoriesPopup', li);
            pop.css('margin-top', '-' + v + 'px');
            pos = pop.offset();
            height = pop.height();
            bottom = pos.top + height;

            win = $(window).height() + $(window).scrollTop();
            bottomOffset = bottom - win;

            // if the bottom of the popup is below the window's edge we need to move it up
            if (bottomOffset > 0) {
                // Calculate the new margin
                min = (height - (v + itemHeight));
                max = -v;

                // Where we really want to put it
                desired = (bottomOffset + v);

                if (desired > min) {
                    nmar = -min;
                } else {
                    nmar = -desired;
                }

                if (nmar > max) {
                    nmar = max;
                }
            } else {
                nmar = -v;
            }

            pop.css('margin-top', nmar + 'px');

            whiteMar = ((-nmar) - 5);
            $('.whiteBg', pop).css('margin-top', whiteMar + 'px');
        });

        // Remove the sub options on click of the little 'x' in the submenu
        $('.categories .closeCatPopup').click(function() {
            $(this).parent().parent().removeClass('active');
        });
    }

}


// Initialise the header (show the three info lines)
function initHeader() {
    if ($('.aankeiler').length) {

        // Display text information when people click in the "aankeiler"
        $('.readmore_i').click(function() {
            if (!$('.introinfo .infoHidden').is(':visible')) {
                $('.introinfo li, .aankeiler .readmore').hide();
                $('.introinfo .infoHidden').slideDown();
            } else {
                $('.introinfo .infoHidden').hide();
                $('.introinfo li, .aankeiler .readmore').show();
            }
        });

        //start the fade in of the red text
        setTimeout("showFirst()", tempo);
    }
    if ($('.header h1').length) {
        $('.header h1').hide();
    }
}

// change the color of the first item in the "aankeiler"
function showFirst() {
    $('.introinfo .one_grey').fadeOut(tempo, showSecond);
}

// change the color of the second item in the "aankeiler"
function showSecond() {
    $('.introinfo .two_grey').fadeOut(tempo, showThird);
    $('.introinfo li').eq(0).removeClass('payment');
}

// change the color of the third item in the "aankeiler"
function showThird() {
    $('.introinfo .three_grey').fadeOut(tempo, enableThird);
    $('.introinfo li').eq(1).removeClass('payment');
}

// Make the third text in the list white
function enableThird() {
    $('.introinfo li').eq(2).removeClass('payment');
}


// Initialise the features slider box carousel
function initCarousel() {
    var carousel = $('.carousel');
    if (carousel != null && carousel.find('ul').children().length > 0) {
        carousel.jCarouselLite({
            btnNext: ".previous",
            btnPrev: ".next",
            visible: 1,
            auto: 3000,
            speed: 750
        });
    }
}


// Initialise the features slider box carousel
function initFeaturedLots() {
    var featuredlots = $('.featuredLots');
    if (featuredlots != null && featuredlots.find('ul').children().length > 0) {
        featuredlots.jCarouselLite({
            btnNext: ".featuredlots_left",
            btnPrev: ".featuredlots_right",
            visible: 4,
            auto: 3000,
            speed: 750
        });
    }
}

// Initialse the click and blur actions on inputs
// If an input has a title variable set, remove the initial value when people focus on it
// If an input has nothing in it on blur, reset the value to the title tag
function initInputs() {
    if ($('input:text').length) {
        $('input:text').each(function() {
            t = $(this);
            if (t.attr('title') == t.val()) {
                t.click(function() {
                    t = $(this);
                    if (t.attr('title') == t.val()) {
                        t.val('');
                    }
                });
                t.blur(function() {
                    t = $(this);
                    if (t.val() == '') {
                        t.val(t.attr('title'));
                    }
                });
            }
        });
    }
}


// Replace all the tooltips with custom code
// If an item has the .tooltip class set create a nice tooltip on hover
function initTooltips() {
    if ($('.tooltip').length) {

        $(".tooltip[title!='']").each(function() {

            $("*[title!='']", this).attr('title', '');

            $(this).hover(function(e) {

                this.t = $(this).attr('title');
                $(this).attr('title', '');
                $('.tip span').html(this.t);

                // Make sure the tooltip stays in a nice position relative to the mouse
                $(this).mousemove(function(e) { positionTip(e); });

                positionTip(e);
                $('.tip').show();

            }, function() {
                $(this).attr('title', this.t);
                $('.tip').hide();
            });
        });
    }
}

// Position a tooltip
function positionTip(e) {
    $('.tip').css("top", (e.pageY + 21) + "px").css("left", (e.pageX + -1) + "px");
}

// Initialise internal links
function initInternalLinks() {
    if (!document.getElementsByTagName) return;
    var anchors = document.getElementsByTagName("a");
    for (var i = 0; i < anchors.length; i++) {
        var anchor = anchors[i];
        if (anchor.getAttribute("href") &&
		anchor.getAttribute("rel") == "external")
            anchor.target = "_blank";
    }
}

// Initialse the background hover on regular list items making them pink on hover
function initBackGrounds() {
    $('.highlight').hover(function() {
        $(this).addClass('over');
    }, function() {
        $(this).removeClass('over');
    });
}


// Initialise the contact selection function
// Show the contact form on changing the select box entry
function initContactSelect() {
    $('.contactus .select').change(function() {
        $('.contactus div div').removeClass('active');
        $('.contactus div div').eq(parseInt($(this).val())).addClass('active');
    });
}

// Start the outlook popup on click
function initOutlook() {
    if ($('.outlook').length) {
        $('.kaveldetail .addto').click(function() {
            $('.outlook').show();
        });
        $('.outlook .close a').click(function() {
            $('.outlook').hide();
        });
    }
}

// Initialise lot omfp
// This adds a "more" link to a chunk of text
function initLotInfo() {
    var collapsed = $('.collapsed');
    if (collapsed.length) {
        function initMore() {
            $('.collapsed').before(' <a href="javascript: void(0);" title="' + languageText.more + '" class="more_link">' + languageText.more + '</a>');
            $('.more_link').click(function() {
                $(this).next('.collapsed').show();
                $(this).remove();
                initLess();
            });
        }
        function initLess() {
            $('.collapsed').after(' <a href="javascript: void(0);" title="' + languageText.less + '" class="less_link">' + languageText.less + '</a>');
            $('.less_link').click(function() {
                $(this).prev('.collapsed').hide('slow', function() { initMore(); });
                $(this).remove();
            });
        }

        collapsed.hide('slow', function() { initMore(); });
    }
}

// Initialise the image swap for category images
function initCatImage() {
    if ($('.imageRotator .go_right').length) {
        setInterval("rotateCatImage()", 3000);
    }
}

// Rotate a single category image
function rotateCatImage() {
    var gos = $('.kaveldetail .go_right');
    var go = 0;
    gos.each(function(e) {
        if (!$(this).is('.go_right_hidden')) {
            $(this).addClass('go_right_hidden');
            go = e + 1;
            if ((go + 1) > gos.length) { go = 0; }
        }
    });
    gos.eq(go).removeClass('go_right_hidden');
}


// Initialise the little kavel detail gallery
function initKavelDetail() {

    // When clicking an image on a "kaveldetail" pagina, show it in medium size form
    // Also set the medium size link to the correct data (the rel attribute of the small link), for the large image popup display
    if ($('.kaveldetail').length) {
        $('.thumbnails a').click(function() {
            $(this).parent().siblings('.image').children('img').attr('src', $(this).attr('href'));
            $('.enlarge a').attr('href', $(this).attr('rel'));
            this.blur();
            return false;
        });
    }

}


// Initialise the newsletter popup
function initNewsLetter() {

    // Show the popup on click or submit of the form
    if ($('.getupdates').length) {
        $('.getupdates .buttom').click(function() {
            tb_show('', 'hoofdcategorie%20pagina%20getupdates.html?height=500&amp;width=400&amp;TB_iframe=true');
        });
        $('.getupdates form').submit(function() {
            tb_show('', 'hoofdcategorie%20pagina%20getupdates.html?height=500&amp;width=400&amp;TB_iframe=true');
            this.blur();
            return false;
        });
    }

    // If this script is loaded inside the iframe initialise the multi select function
    if ($('.getupdates_tb').length) {

        // Select all or none
        $('.selectall input').click(function() {
            if ($(this).is(':checked')) {
                $(this).parent().siblings().children('input').attr('checked', 'checked');
            } else {
                $(this).parent().siblings().children('input').attr('checked', '');
            }
        });

        // Set the input fields to those of the parent window on load of the iframe popup
        $('input[@name="email"]').val($('input[@name="email"]', parent.document).val());
        $('input[@name="country"]').val($('input[@name="country"]', parent.document).val());
    }

}


// Initialise folding/unfolding of locations
function initLocations() {

    if ($('.auctionLocation').length) {
        $('.auctionLocation .opener').click(function() {
            det = $(this).siblings('.locationDetails');
            if (det.is(':visible')) {
                det.slideUp('fast');
                $(this).parent().removeClass('activeAuction');
            } else {
                $(this).parent().siblings().children('.locationDetails:visible').slideUp('fast');
                $(this).parent().siblings().removeClass('activeAuction');
                det.slideDown('fast');
                $(this).parent().addClass('activeAuction');
            }
        });
    }
}


// Fold/unfold the faq blocks
function initFaq() {
    if ($('.faq').length) {

        $('.faq h5 a').click(function() {

            li = $(this).parent().parent();
            if (li.is('.active')) {
                li.removeClass('active');
            } else {
                li.addClass('active');
            }
            this.blur();
            return false;

        });

    }
}

function initAttention() {
    if ($('.removeIn5').length) {
        setInterval("hideAttention()", 5000);
    }
}

function hideAttention() {
    $(".removeIn5").fadeOut(500);
}

/* Process start */
// Initialise the infographic process
function initProcess() {
    if ($('.process').length) {

        $('.process > div > ul > li').eq(0).moveProcessTo();
        processStep = setInterval("moveProcessUp()", 5000);

        // On click of this function
        $('.process > div > ul > li > a').click(function() {
            window.clearInterval(processStep);
            $(this).parents('li').moveProcessTo();
        });

        $('.process > div > ul > li > a').hover(function() {
            li = $(this).parent();
            if (!li.is('.active')) { li.css({ marginTop: "1px" }); }
        }, function() {
            li = $(this).parent();
            if (!li.is('.active')) { li.css({ marginTop: "0px" }); }
        });

    }
}


/* Auction grid */
// Initialise the auction grid
function initAuctionGrid(showDutchBiddingPeriod, hideDescendingBidTab) {
    if (hideDescendingBidTab && $(".tabs").length) {
        $(".tabs").hide();
    }
    if ($('.auction_kavels').length) {
    
        $('.auction_kavels .auction_head').each(function() {
            if ($(this).hasClass("active")) {
                $(this).children(".collapse_arrow").removeClass("auction_normal");
                $(this).children(".collapse_arrow").addClass("auction_collapsed");
            } else {
                $(this).next(".auction_content").hide();
            }
        });

        $(".auction_head").click(function() {
            if ($(this).hasClass("active")) {
                // Stop the autorefresh
                if (ContentItemDashboard.Timeout != 0) {
                    clearTimeout(ContentItemDashboard.Timeout);
                }
                if (ContentItemDashboard.Clocks[ContentItemDashboard.SaleID]) {
                    clearInterval(ContentItemDashboard.Clocks[ContentItemDashboard.SaleID].myInterval);
                };
                
                $(this).removeClass("active");
                $(this).children(".collapse_arrow").addClass("auction_normal");
                $(this).children(".collapse_arrow").removeClass("auction_collapsed");
                $(this).next(".auction_content").slideToggle(600);
            } else {
                $('.auction_kavels .active').each(function() {
                    $(this).removeClass("active");
                    $(this).children(".collapse_arrow").addClass("auction_normal");
                    $(this).children(".collapse_arrow").removeClass("auction_collapsed");
                    $(this).next(".auction_content").slideToggle(600);
                });

                $(this).addClass("active");
                $(this).children(".collapse_arrow").removeClass("auction_normal");
                $(this).children(".collapse_arrow").addClass("auction_collapsed");
                ContentItemDashboard.GetLots(this, 0, showDutchBiddingPeriod);
            }
        });

        $("div.auction_head:has(input[value='" + $("input[id$='CurrentSale']").val() + "'])").click();
        initCountdown();
    }
}

function initCountdown() {
    return setInterval(function() {
        $(".countdown").each(function() {
            var element = $(this);
            var parts = element.html().split(":");
            var minutes = parseInt(parts[0]);
            var seconds = (parts[1].indexOf("0") == 0 ? parseInt(parts[1].substr(1, 1)) : parseInt(parts[1])) - 1;
            //alert(element.html() + " | " + seconds);
            if (seconds < 0) {
                if (minutes == 0) {
                    seconds = 0;
                } else {
                    minutes--;
                    seconds = 59;
                }
            }
            if (minutes == 0 && seconds == 0) {
                element.parent().html("0:00");
            } else {
                if (minutes >= 15) {
                    if (element.hasClass("important")) { element.removeClass("important"); }
                    if (element.hasClass("very-important")) { element.removeClass("very-important"); }
                } else if (minutes > 3) {
                    if (element.hasClass("very-important")) { element.removeClass("very-important"); }
                    if (element.hasClass("important") == false) { element.addClass("important"); }
                } else {
                    if (element.hasClass("important")) { element.removeClass("important"); }
                    if (element.hasClass("very-important") == false) { element.addClass("very-important"); }
                }
                element.html(minutes + (seconds < 10 ? ":0" : ":") + seconds);
            }
        });
    }, 1000);
}

var ContentItemDashboard = {
    Currency: '',
    Clocks: new Object(),
    DisplayDutchLots: function(data, head) {
        this.Currency = data.currency;
        this.Labels = data.labels;
        var currentDate = data.currentDate;
        var highestBidLabel = data.labels.highestBid;
        var nextRefreshLabel = data.labels.nextRefreshIn;
        var html = "<table cellpadding='0' cellspacing='0' class='trackedlots'>" + data.header;
        for (var n = 0; n < data.lots.length; n++) {
            var lot = data.lots[n];
            html += "<tr id='tr" + lot.ID + "' class='" + (n % 2 == 0 ? "" : "odd") + "'><td class='number'>" + lot.Number + "</td>"
                + "<td><div class='kavel_info'>"
                    + "<div class='resize'><img src='" + baseURL + lot.Image + "' border='0' onload='resize(this);' /></div>"
                    + "<p class='title'>" + lot.Title + (lot.NumberOfItems > 1 ? " <span>(" + lot.NumberOfItems + "x)</span>" : "") + "</p>"
                    + "<br /><p></p>"
                    + "<br /><p>" + highestBidLabel + ": " + lot.CurrentBid + "</p></div>"
                    + "<div class='kavel_timer'>";
            if (lot.IsClosed) {
                html += this.GetResultMessage(lot.NextAcceptedBid, lot.IsHighestBidder, lot.IsPremiumEntitled, lot.Premium);
            } else {
                html += "<div class='timer'><div class='dynamic_clock'></div>"
                        + "<p><span>" + nextRefreshLabel + " <span class='seconds'>0</span> sec.</span>"
                        + "<br /><strong id='refresh" + lot.ID + "'>" + currentDate + "</strong></p></div>"
                    + "<div class='price'><span class='price_after_update'>(" + this.Labels.afterUpdate + ": " + this.Currency + ")</span>"
                        + "<span class='current_price'>" + this.Labels.currentPrice + ": " + lot.CurrentBid + "</span></div>"
                    + "<div class='validation hidden'>" + this.Labels.validationRequired + ": <a class='view_conditions' href='" + this.SaleTerms + "'>" + this.Labels.particularTerms + "</a></div>"
                    + "<button type='button' class='kavelButton hidden' title='" + this.Labels.placeBid + "' onclick='ContentItemDashboard.Mine(" + lot.ID + ");'><span><span>" + this.Labels.isMine + "!</span></span></button>"
            }
            html += "</div></td><td class='alignCenter last'>" + this.GetStopFollowingLink(lot.ID, lot.IsHighestBidder) + "</td></tr>";
            ContentItemDashboard.GetDutchLot(lot.ID, (n * 50) + 100);
        }
        html += "</table>";
        head.next().html(html);
        head.next().slideToggle(600);
    },
    DisplayLots: function(data, head) {
        ContentItemDashboard.SetCurrentDate(data.currentDate);
        this.Currency = data.currency;
        this.Labels = data.labels;
        var dutchAttention = false;
        var isOutbid = false;
        var html = "<table cellpadding='0' cellspacing='0' class='trackedlots'>" + data.header;
        if (data.isTender) {
            for (var n = 0; n < data.lots.length; n++) {
                var lot = data.lots[n];
                var cssClass = (n % 2 == 0 ? "" : "odd");
                html += "<tr id='tr" + lot.ID + "' class='" + cssClass + "'>"
                        + "<td class='number'>" + lot.Number + "</td>"
                        + "<td class='alignCenter'>" + lot.Indicators + "</td>"
                        + "<td class='tooltip description highlight'>"
                            + "<h3><a href='" + lot.Url + "' title='" + lot.Title + "'>"
                            + lot.Title + (lot.NumberOfItems > 1 ? " <span>(" + lot.NumberOfItems + "x)</span>" : "")
                            + "</a></h3></td>"
                        + "<td>" + lot.RelationBid + "</td>"
                        + "<td>" + lot.CurrentBid + "</td>"
                        + "<td>" + lot.Closing + "</td>"
                        + "<td class='alignCenter last'>" + this.GetStopFollowingLink(lot.ID, lot.IsHighestBidder) + "</td>"
                        + "</tr>";
            }
        } else {
            for (var n = 0; n < data.lots.length; n++) {
                var lot = data.lots[n];
                if (lot.IsOutbid) {
                    isOutbid = true;
                }
                var cssClass = (n % 2 == 0 ? "" : "odd") + (lot.IsHighestBidder ? " lightDark" : (lot.IsOutbid ? " light" : ""));
                html += "<tr id='tr" + lot.ID + "' class='" + cssClass + "'>"
                        + "<td class='number'>" + lot.Number + "</td>"
                        + "<td class='alignCenter'>" + lot.Indicators + "</td>"
                        + "<td class='tooltip description highlight'>"
                            + "<h3><a href='" + lot.Url + "' title='" + lot.Title + "'>"
                            + lot.Title + (lot.NumberOfItems > 1 ? " <span>(" + lot.NumberOfItems + "x)</span>" : "")
                            + "</a></h3></td>";
                if (data.showBiddingValues) {
                    html += "<td>" + lot.RelationBid + "</td>"
                        + "<td>" + lot.CurrentBid + "</td>"
                        + "<td class='nextbidexcepted'>"
                            + lot.NextAcceptedBid
                            + "<br /><button type='button' class='BidThisButton" + (lot.IsClosed || lot.IsHighestBidder ? " hidden" : "") + "' title='" + this.Labels.bidDirect + "' onclick='location.href=\"" + lot.Url + "?direct=1\";'>"
                                + "<span><span>" + this.Labels.bidThis + "</span></span></button></td>";
                }
                html += "<td>" + lot.Closing + "</td>"
                        + "<td class='alignCenter last'>" + this.GetStopFollowingLink(lot.ID, lot.IsHighestBidder) + "</td>"
                        + "</tr>";

                if (lot.SecondsTillDutchStart >= 0) {
                    dutchAttention = true;
                }
            }
        }
        html += "</table>"

        if (dutchAttention) {
            this.ShowDutchAttention();
        }
        if (isOutbid && data.showBiddingValues) {
            this.ShowAttention();
        }
        head.next().html(html);
        head.next().slideToggle(600, function() { ContentItemDashboard.GetLots(null, data.interval, false); });
    },
    GetDutchLot: function(lotID, interval) {
        setTimeout(function() {
            getJsonCI(
                    ContentItemDashboard.TypeName,
                    'GetDutchLot',
                    function(data) { ContentItemDashboard.UpdateDutchLot(data); },
                    { sid: ContentItemDashboard.SaleID, lid: lotID });
        }, interval);
    },
    GetLots: function(header, interval, showDutchBiddingPeriod) {
        if (interval == 0) {
            var head = $(header);
            if (this.Timeout != 0) {
                clearTimeout(this.Timeout);
            }
            if (this.Clocks[this.SaleID]) {
                clearInterval(this.Clocks[this.SaleID].myInterval);
            };
            this.SaleID = head.children("input:eq(0)").val();
            var terms = head.children("input:eq(1)").val();
            if (terms) {
                this.SaleTerms = terms;
            } else {
                this.SaleTerms = '';
            }
            $("input[id$='CurrentSale']").val(this.SaleID);
            if (showDutchBiddingPeriod) {
                getJsonCI(
                    ContentItemDashboard.TypeName,
                    'GetLots',
                    function(data) { ContentItemDashboard.DisplayDutchLots(data, head); },
                    { sid: ContentItemDashboard.SaleID, isUpdate: false, showDutch: true });
            } else {
                getJsonCI(
                        ContentItemDashboard.TypeName,
                        'GetLots',
                        function(data) { ContentItemDashboard.DisplayLots(data, head); },
                        { sid: ContentItemDashboard.SaleID, isUpdate: false, showDutch: false });
            }
        } else {
            if (this.Clocks[this.SaleID]) {
                clearInterval(this.Clocks[this.SaleID].myInterval);
            };
            var seconds = parseInt(interval / 1000);
            var clock = $(".content .timer");
            clock.find(".seconds").html(seconds < 10 ? "0" + seconds : seconds);
            this.Clocks[this.SaleID] = clock.find(".dynamic_clock").tzineClock();
            this.Timeout = setTimeout(function() {
                getJsonCI(
                    ContentItemDashboard.TypeName,
                    'GetLots',
                    function(data) { ContentItemDashboard.UpdateLots(data); },
                    { sid: ContentItemDashboard.SaleID, isUpdate: true, showDutch: showDutchBiddingPeriod });
            }, interval);
        }
    },
    GetOneHourToGoRow: function(cssClass, lotID, secondsToGo) {
        return "<tr class='" + cssClass + " onehour_row'>"
                    + "<td colspan='8' class='last'><div>" + this.Labels.descendingBidStartsIn + " <span id='tg" + lotID + "'>" + setTimeout(function() { fTwkCountDown("tg" + lotID, secondsToGo, ""); }, 100) + "</span>"
                    + " <a href='?dutch=1&sid=" + this.SaleID + "' style='margin-left:50px;' target='_self'>" + this.Labels.view + "</a></div></td></tr>";
    },
    GetResultMessage: function(highestBid, isHighestBidder, isPremiumEntitled, premium) {
        var html = "<div class='price'><span class='current_price'>" + this.Labels.currentPrice + ": " + highestBid + "</span></div>";
        if (isHighestBidder) {
            html += "<div class='bidding_success'><p>" + this.Labels.highestBidder + ".</p></div>";
        } else if (isPremiumEntitled) {
            html += "<div class='bidding_success'><p>" + this.Labels.dutchBiddersPremiumEntitled + ". (" + this.Currency + premium + ")</p></div>";
        } else {
            html += "<div class='bidding_failed'><p>" + this.Labels.notHighestBidder + ".</p></div>";
        }
        return html;
    },
    GetStopFollowingLink: function(lotID, isHighestBidder) {
        return "<a href='javascript:void(0);'" + (isHighestBidder ? " class='hidden'" : "") + " onclick='fTwkFollowMyTwk(" + lotID + ");' title='" + this.Labels.stopFollowing + "'>"
                                + "<img src='" + baseURL + "project/content/img/remove.gif' alt='remove' /></a>";
    },
    Labels: null,
    Mine: function(lotID) {
        getJsonCI(
            ContentItemDashboard.TypeName,
            'Mine',
            function(data) {
                if (ContentItemDashboard.Clocks[lotID]) {
                    clearInterval(ContentItemDashboard.Clocks[lotID].myInterval);
                };
                var row = $("#tr" + lotID);
                if (!row.find(".bidding_success").length && !row.find(".bidding_failed").length) {
                    row.find(".kavel_timer").html(ContentItemDashboard.GetResultMessage(data.bid, data.isHighestBidder, data.isPremiumEntitled, data.premium));
                }
                tb_show('', baseURL + 'Project/Views/Website/Popups/Message.aspx?width=300&height=200&message=' + encodeURIComponent(data.msg));
            },
            { sid: ContentItemDashboard.SaleID, lid: lotID });
    },
    SaleID: 0,
    SaleTerms: '',
    SetCurrentDate: function(currentDate) { $("#refreshTime").html(currentDate); },
    ShowAttention: function() {
        // show attention
        $("p[id$='attention']").show();
        initAttention();
    },
    ShowDutchAttention: function() {
        var row = $("#ciDashboard").find(".auction_head:has(input[value='" + this.SaleID + "'])");
        if (row.find(".onehourleft").length == 0) {
            var img = row.find("img");
            img.attr("src", img.attr("src").replace(".gif", "_important.gif"));
            img.after("<span class='onehourleft'>!</span>");
        }
    },
    Timeout: 0,
    TypeName: "Octavalent.Project.Views.Shared.Controls.ContentItemDashboard, Octavalent.Project",
    UpdateDutchLot: function(data) {
        if (data.success) {
            var lot = data.lot;
            if (this.Clocks[lot.ID]) {
                clearInterval(this.Clocks[lot.ID].myInterval);
            };
            if (data.status == 1 || data.interval <= 0) {
                $("#refresh" + lot.ID).html(this.Labels.closed);
            } else {
                $("#refresh" + lot.ID).html(data.currentDate);
            }
            var row = $("#tr" + lot.ID);
            if (data.interval <= 0) {
                if (!row.find(".bidding_success").length && !row.find(".bidding_failed").length) {
                    row.find(".kavel_timer").html(this.GetResultMessage(this.Currency + lot.CurrentBid, lot.IsHighestBidder, lot.IsPremiumEntitled, lot.Premium));
                }
            } else {
                row.find("span.current_price").html(this.Labels.currentPrice + ": " + this.Currency + lot.CurrentBid);
                if (lot.HasBidPermission) {
                    if (data.status == 0) {
                        var button = row.find(".kavelButton");
                        button.show();
                        row.find(".validation").hide();
                    }
                } else {
                    row.find(".validation").show();
                }
                if (data.status == -1) {
                    row.find("span.price_after_update").hide();
                } else {
                    row.find("span.price_after_update").html("(" + this.Labels.afterUpdate + ": " + this.Currency + lot.NextAcceptedBid + ")").show();
                }
                var seconds = parseInt(data.interval / 1000);
                var clock = row.find(".timer");
                clock.find(".seconds").html(seconds < 10 ? "0" + seconds : seconds);
                this.Clocks[lot.ID] = clock.find(".dynamic_clock").tzineClock();
                this.GetDutchLot(lot.ID, data.interval);
            }
        }
    },
    UpdateLots: function(data) {
        this.SetCurrentDate(data.currentDate);
        var dutchAttention = false;
        var isOutbid = false;
        if (data.isTender) {
            for (var n = 0; n < data.lots.length; n++) {
                var lot = data.lots[n];
                var cell;
                var index = 0;
                var row = $("#tr" + lot.ID);

                // check indicators
                index++;
                if (row.children(":eq(" + index + ")").html() != lot.Indicators) {
                    row.children(":eq(" + index + ")").html(lot.Indicators);
                }

                // check relation bid
                index += 2;
                if (row.children(":eq(" + index + ")").html() != lot.RelationBid) {
                    row.children(":eq(" + index + ")").html(lot.RelationBid);
                }

                // check current bid
                index++;
                if (row.children(":eq(" + index + ")").html().toLowerCase() != lot.CurrentBid.toLowerCase()) {
                    row.children(":eq(" + index + ")").html(lot.CurrentBid);
                }

                // set closing
                if (row.children(":eq(" + index + ")").html() != lot.Closing) {
                    row.children(":eq(" + index + ")").html(lot.Closing);
                }

                // check follow
                index++;
                if (lot.IsHighestBidder) {
                    row.children(":eq(" + index + ")").children("a").hide();
                } else {
                    row.children(":eq(" + index + ")").children("a").show();
                }
            }
        } else {
            for (var n = 0; n < data.lots.length; n++) {
                var lot = data.lots[n];
                var cell;
                var index = 0;
                var row = $("#tr" + lot.ID);

                // check class
                if (lot.IsHighestBidder) {
                    if (row.hasClass("lightDark") == false) {
                        row.removeClass("light").addClass("lightDark");
                    }
                } else if (lot.IsOutbid) {
                    if (row.hasClass("lightDark")) {
                        isOutbid = true;
                        row.removeClass("lightDark").addClass("light");
                    } else if (row.hasClass("light") == false) {
                        isOutbid = true;
                        row.addClass("light");
                    }
                }

                // check indicators
                index++;
                if (row.children(":eq(" + index + ")").html() != lot.Indicators) {
                    row.children(":eq(" + index + ")").html(lot.Indicators);
                }

                index += 2;
                if (data.showBiddingValues) {
                    // check relation bid
                    if (row.children(":eq(" + index + ")").html() != lot.RelationBid) {
                        row.children(":eq(" + index + ")").html(lot.RelationBid);
                    }

                    // check current bid
                    index++;
                    if (row.children(":eq(" + index + ")").html().toLowerCase() != lot.CurrentBid.toLowerCase()) {
                        row.children(":eq(" + index + ")").html(lot.CurrentBid);
                        // if the current bid changed, the next accepted will also have changed
                        index++;
                        cell = row.children(":eq(" + index + ")");
                        var nabHtml = cell.html();
                        cell.html(nabHtml.replace(nabHtml.substr(0, nabHtml.toLowerCase().indexOf("<br")), lot.NextAcceptedBid));
                        if (lot.IsOpen == false || lot.IsClosed || lot.IsHighestBidder || lot.HasBidPermission == false) {
                            cell.children("button.BidThisButton").hide();
                        } else {
                            cell.children("button.BidThisButton").show();
                        }
                    } else {
                        // the current bid remains the same, but the lot could have closed since last update
                        if (lot.IsOpen == false || lot.IsClosed || lot.IsHighestBidder || lot.HasBidPermission == false) {
                            row.children(":eq(" + index + ")").children("button.BidThisButton").hide();
                        } else {
                            row.children(":eq(" + index + ")").children("button.BidThisButton").show();
                        }
                        index++;
                    }
                    index++;
                }

                // set closing
                if (row.children(":eq(" + index + ")").html() != lot.Closing) {
                    row.children(":eq(" + index + ")").html(lot.Closing);
                }

                // check follow
                index++;
                if (lot.IsHighestBidder) {
                    row.children(":eq(" + index + ")").children("a").hide();
                } else {
                    row.children(":eq(" + index + ")").children("a").show();
                }

                // check time till dutch start
                if (lot.SecondsTillDutchStart >= 0) {
                    if (row.hasClass("onehour_toprow") == false) {
                        dutchAttention = true;
                        row.after(this.GetOneHourToGoRow(row.attr("class"), lot.ID, lot.SecondsTillDutchStart));
                        row.addClass("onehour_toprow");
                    }
                }
            }
        }
        if (dutchAttention) {
            this.ShowDutchAttention();
        }
        if (isOutbid && data.showBiddingValues) {
            this.ShowAttention();
        }
        this.GetLots(null, data.interval, false);
    }
};


// Activate the next process in the infographic
function moveProcessUp() {
    if ($('.process > div > ul > li.active').length) {
        var current = parseInt($('.process > div > ul > li.active > a > span').html());
        if (current >= $('.process > div > ul > li').length) { current = 0; }
        $('.process > div > ul > li').eq(current).moveProcessTo();
    }
}

// Move the process to a specific step
jQuery.fn.moveProcessTo = function() {
    if (this.is('.active')) {
        this.animate({ marginTop: "0px" }, 300).hideSubList(200).removeClass('active');
        $('.process').height(60);
    } else {
        $('.process > div > ul > li.active').animate({ marginTop: "0px" }, 300).hideSubList().removeClass('active');
        this.animate({ marginTop: "5px" }, 300).showSubList(200).addClass('active').setProcessHeight();
    }
    return this;
}

jQuery.fn.showSubList = function(speed) {
    $('ul', this).slideDown(speed);
    return this;
}

jQuery.fn.hideSubList = function(speed) {
    $('ul', this).slideUp(speed);
    return this;
}

// Set the height of the entire process block relative to the current one
jQuery.fn.setProcessHeight = function() {
    $('.process').height((($('ul li', this).length * 28) + 60));
    return this;
}
/* Process end */
function initLoggedin() {
    if ($('.mytroostwijkHolder').length) {
        var container = $('.loggedIn');

        $('.mytroostwijkHolder').animate({ backgroundColor: "#DFEDFD" }, 250, "easeOutExpo");
        $('.mytroostwijkHolder').animate({ backgroundColor: "#BEDAFB" }, 250, "easeOutExpo");
        $('.mytroostwijkHolder').animate({ backgroundColor: "#DFEDFD" }, 250, "easeOutExpo");
        $('.mytroostwijkHolder').animate({ backgroundColor: "#BEDAFB" }, 250, "easeOutExpo");
        $('.mytroostwijkHolder').animate({ backgroundColor: "#DFEDFD" }, 250, "easeOutExpo");
        $('.mytroostwijkHolder').animate({ backgroundColor: "#BEDAFB" }, 250, "easeOutExpo");

        // allow positioning child div relative to parent
        $('.loggedIn').css('position', 'relative')
        // create and append background div 
        // (initially visible, obscuring parent's background)
        $('.loggedIn').append($("<div>")
		  .attr('class', 'animationBackground')
		  .css({
		      backgroundColor: '#FFFFFF',
		      position: 'absolute',
		      top: 0,
		      left: 0,
		      zIndex: -1,
		      opacity: 0,
		      width: container.width(),
		      height: container.height()
		  })
		);

        $(".animationBackground", container).animate({ opacity: .7 }, 250, "easeOutExpo");
        $(".animationBackground", container).animate({ opacity: 0 }, 250, "easeOutExpo");
        $(".animationBackground", container).animate({ opacity: .7 }, 250, "easeOutExpo");
        $(".animationBackground", container).animate({ opacity: 0 }, 250, "easeOutExpo");
        $(".animationBackground", container).animate({ opacity: .7 }, 250, "easeOutExpo");
        $(".animationBackground", container).animate({ opacity: 0 }, 250, "easeOutExpo");
    }
}

/* Photo Viewer */
function initPhotoViewer(viewer) {
    $(".photoviewer_controls .previous_link").click(function() {
        var current = $(".photoviewer_thumbs .active");
        var previous = current.prev();
        if (previous.length) {
            previous.click();
        }
        photoViewerScrollDown();
    });

    $(".photoviewer_controls .next_link").click(function() {
        var current = $(".photoviewer_thumbs .active");
        var next = current.next();
        if (next.length) {
            next.click();
        }
        photoViewerScrollUp();
    });


    if ($(".photoviewer_thumbs img").length > 5) {

        $(".photoviewer_thumbs_top a").click(function() {
            photoViewerScrollDown();
        });
        $(".photoviewer_thumbs_bottom a").click(function() {
            photoViewerScrollUp();
        });

    } else {
        // if there are no more then 6 thumbs hide the controls cause we don't need them.
        $(".photoviewer_thumbs_top, .photoviewer_thumbs_bottom").hide();
    }
}
function photoViewerHide() {
    var viewer = $("div.photoviewer");
    if (viewer.length) {
        viewer.next().hide();
        viewer.hide();
        viewer.prev().hide();
        $("div.rightContent").show();
    }
}
function photoViewerScrollUp() {
    $(".photoviewer_thumbs").scrollTop($(".photoviewer_thumbs").scrollTop() + 77);
}
function photoViewerScrollDown() {
    $(".photoviewer_thumbs").scrollTop($(".photoviewer_thumbs").scrollTop() - 77);
}
function photoViewerShow() {
    $("div.rightContent").hide();
    var viewer = $("div.photoviewer");
    if (viewer.length) {
        viewer.prev().show();
        viewer.show();
        viewer.next().show();
        var thumbsHolder = viewer.find("div.photoviewer_thumbs");
        if (thumbsHolder.children().length == 0) {
            viewerImages = JSON.parse(viewerImages);
            var alt = $("img[id$='imgFirstThumbnail']").attr('alt');
            for (var n = 0; n < viewerImages.length; n++) {
                var thumb = "<a href='javascript:void(0);' class='resize' onclick='photoViewerView(this, " + n + ", false);'><img src='" + viewerImages[n].Path + 'th_' + viewerImages[n].File + "' alt='" + alt + "' onload='resize(this);' /></a>";
                thumbsHolder.append(thumb);
            }
            initPhotoViewer(viewer);
        }
    }
}
function photoViewerView(domObj, index, init) {
    if (init)
        photoViewerShow();
    var link = init ? $($("div.photoviewer_thumbs").find("img")[index]).parent() : $(domObj);
    link.siblings().removeClass("active");
    link.addClass("active");
    if (link.prev().length == 0) {
        $(".photoviewer_controls .previous_link").addClass("disabled");
    } else {
        $(".photoviewer_controls .previous_link").removeClass("disabled");
    }
    if (link.next().length == 0) {
        $(".photoviewer_controls .next_link").addClass("disabled");
    } else {
        $(".photoviewer_controls .next_link").removeClass("disabled");
    }
    var alt = $("img[id$='imgFirstThumbnail']").attr('alt');
    var imageHolder = $("div.photoviewer_photos");
    imageHolder.parent().find("div.photoviewer_numberOf").children("span").html(index + 1);
    imageHolder.append("<img alt='" + alt + "' id='imgPV" + index + "' height='" + viewerImages[index].Height + "' src='" + viewerImages[index].Path + viewerImages[index].File + "' width='" + viewerImages[index].Width + "' />");
    //    var image = $("<img alt='' id='imgPV" + index + "' height='" + viewerImages[index].Height + "' width='" + viewerImages[index].Width + "'></image>");
    //    imageHolder.append(image);
    //    image
    //        .attr('src', viewerImages[index].Path + viewerImages[index].File)
    //        .load(function() { alert(document.getElementById('imgPV' + index).src); });

    resize(document.getElementById('imgPV' + index), true);

    if (imageHolder.children().length > 1)
        imageHolder.children(":first").remove();
}

function hidePopup() {
    $('#TB_window,#TB_overlay,#TB_HideSelect').trigger('unload').unbind().remove();
}

function doLogin(suffix) {
    if (!suffix) {
        suffix = '';
    }
    var fld = $("input[id$='txtLoginName" + suffix + "']");
    if (fld.length) {
        var loginName = fld.val();
        if (loginName.length == 0) {
            fld.focus();
        } else {
            fld = $("input[id$='txtLoginPassword" + suffix + "']");
            var password = fld.val();
            if (password.length == 0) {
                fld.focus();
            } else {
                var loginType = 'Forget';
                fld = $("input[id$='rbRemember']");
                if (fld.length && fld.attr('checked')) loginType = 'Remember';
                fld = $("input[id$='rbAutoLogin']");
                if (fld.length && fld.attr('checked')) loginType = 'AutoLogin';
                $.post(baseURL + 'project/views/website/callbacks.ashx', { action: 'login', loginName: loginName, password: password, loginType: loginType },
                    function(data) {
                        if (data.msg.length == 0) {
                            window.location.reload(true);
                        } else {
                            $("#loginMsg" + suffix).html(data.msg);
                        }
                    }, 'json');
            }
        }
    }
}

function goToRegistration() {
    setTimeout(function() { window.location = registrationUrl; }, 0);
}

function showLogin() {
    hidePopup();
    var upgradeIE = false;  //$.browser.msie && $.browser.version != 7;
    if (upgradeIE) {
        goToRegistration();
    } else {
        //tb_show('', baseURL + 'Project/Views/Website/Popups/Login.aspx?TB_iframe=true&keepThis=true&width=600&height=450');
        tb_show('', baseURL + 'Project/Views/Website/Popups/Login.aspx?width=600&height=450');
    }
}

function showRecoverPassword(strCode) {
    hidePopup();
    tb_show('', baseURL + 'Project/Views/Website/Popups/Login.aspx?c=recover&code=' + strCode + '&width=600&height=230');
}
function recoverPassword() {
    var fld = $('#txtRecoverCode');
    if (fld.length) {
        var btn = $('#cmdRecover');
        btn.attr('disabled', 'disabled');
        var code = fld.val();
        var password = $('#txtRecoverPassword01').val();
        var passwordConfirm = $('#txtRecoverPassword02').val();
        $.post(baseURL + 'project/views/website/callbacks.ashx', { action: 'recoverpassword', code: code, password: password, passwordConfirm: passwordConfirm },
                    function(data) {
                        if (data.success) {
                            $('#divRecoverMessage').html(data.message);
                            $('#divRecoverForm').hide();
                        } else {
                            $('#divRecoverMessage').html(data.message);
                            btn.removeAttr('disabled');
                            if (data.showCode) {
                                $('#trRecoverCode').show();
                                setTimeout(function() { document.getElementById('txtRecoverCode').focus(); }, 50);
                            }
                        }
                    }, 'json');
    }
}

function showRequestPassword() {
    hidePopup();
    tb_show('', baseURL + 'Project/Views/Website/Popups/Login.aspx?c=forgot&width=600&height=220');
}
function requestPassword() {
    var fld = $('#txtRequestEmail');
    if (fld.length) {
        var email = fld.val();
        if (email.length > 0) {
            $.post(baseURL + 'project/views/website/callbacks.ashx', { action: 'requestpassword', email: email },
                    function(data) {
                        if (data.sent) {
                            $('#divRequestMessage').html(data.message);
                            $('#divRequestForm').hide();
                        } else {
                            $('#divRequestMessage').html(data.message);
                        }
                    }, 'json');
        }
    }
}

// should be valid phone number
function addShouldBeValidPhoneNumber(phoneNumberControl, countryCodeControl, valid, invalid, isMobile) {
    $(phoneNumberControl).blur(function() {
        var phoneNumber = $(phoneNumberControl).val();
        var countryCode = $(countryCodeControl).val();
        var isValid = shouldBeValidPhoneNumber(phoneNumber, countryCode, isMobile);
        handleValidation(isValid, valid, invalid);
    });
    $(valid).hide();
    $(invalid).hide();
}
function shouldBeValidPhoneNumber(phoneNumber, countryCode, isMobile) {
    var isValid = null;
    jQuery.ajax({
        url: baseURL + projectValidationServiceUrl +
                  '?action=ShouldBeValidPhoneNumber' +
                  '&phoneNumber=' + phoneNumber +
                  '&countryCode=' + countryCode +
                  '&isMobile=' + isMobile,
        success: function(result) {
            var json = JSON.parse(result.toString());
            isValid = json.isValid;
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            alert('status: ' + textStatus + '\n' + 'error: ' + errorThrown + '\n' + XMLHttpRequest.responseText);
        },
        async: false
    });
    return isValid;
}
function addPhoneNumberExampleSwitch(countryCodeControl, phoneNumberExampleControl, isMobile) {
    $(countryCodeControl).change(function() {
        var countryCode = $(countryCodeControl).val();
        $(phoneNumberExampleControl).html(switchPhoneNumberExample(countryCode, isMobile));
    });
}
function switchPhoneNumberExample(countryCode, isMobile) {
    var example = '';
    jQuery.ajax({
        url: baseURL + projectValidationServiceUrl +
                  '?action=SwitchPhoneNumberExample' +
                  '&countryCode=' + countryCode +
                  '&isMobile=' + isMobile,
        success: function(result) {
            var json = JSON.parse(result.toString());
            example = json.example;
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            alert('status: ' + textStatus + '\n' + 'error: ' + errorThrown + '\n' + XMLHttpRequest.responseText);
        },
        async: false
    });
    return example;
}

function fTwkLogoff() {
    $.post(baseURL + 'project/views/website/callbacks.ashx', { action: 'logoff' },
        function(data) { window.location.reload(true); }, 'json');
}

function fTwkToggleThumbs() {
    $.post(baseURL + 'project/views/website/callbacks.ashx', { action: 'togglethumbs' },
        function(data) { window.location.reload(true); }, 'json');
}

function fTwkFollow(checkboxID, lotID) {
    $.post(baseURL + 'project/views/website/callbacks.ashx', { action: 'follow', lotID: lotID, checkboxID: checkboxID },
        function(data) {
            $("#" + data.checkboxID).attr('checked', data.follow);
            if (data.maxExceeded) {
                tb_message('', data.maxExceededMessage, 300, 75);
            }
        }
    , 'json');
}

function fTwkFollowMyTwk(lotID) {
    $.post(baseURL + 'project/views/website/callbacks.ashx', { action: 'follow', lotID: lotID },
        function(data) { $("tr[id$='tr" + data.lotID + "']").hide(); }, 'json');
}

function fTwkCountDown(objID, intSec, strFunction) {
    if (objID.length == 0) return;

    intSec = parseInt(intSec);
    
    if (intSec >= 0) {
        var obj = $("#" + objID);
        if (!obj.length) return;

        if (intSec == 0) {
            obj.html('0:00');
            if (obj.hasClass("important")) obj.removeClass("important");
            if (obj.hasClass("very-important")) obj.removeClass("very-important");
            twkTimeOuts[objID] = setTimeout('fTwkCountDown(\'' + objID + '\', ' + (intSec - 1) + ',\'' + strFunction + '\');', 1000);
            return;
        }

        var intDays = 0;
        var intHours = 0;
        var intMinutes = 0;
        var intSecs = intSec;

        if ((intSecs / 86400) > 0) {
            intDays = Math.floor(intSecs / 86400);
            intSecs -= (intDays * 86400);
        }
        if ((intSec / 3600) > 0) {
            intHours = Math.floor(intSecs / 3600);
            intSecs -= (intHours * 3600);
        }
        if ((intSec / 60) > 0) {
            intMinutes = Math.floor(intSecs / 60);
            intSecs -= (intMinutes * 60);
        }
        if (intMinutes < 10) {
            intMinutes = '0' + intMinutes;
        }
        if (intSecs < 10) {
            intSecs = '0' + intSecs;
        }

        var strOutput = '';
        if (intDays > 0) {
            strOutput = intDays + ' - ' + intHours + ':' + intMinutes + ':' + intSecs;
        } else {
            if (intHours > 0) {
                strOutput = intHours + ':' + intMinutes + ':' + intSecs;
            } else {
                strOutput = intMinutes + ':' + intSecs;
            }
        }
        obj.html(strOutput);

        if (intMinutes >= 15) {
            if (obj.hasClass("important")) obj.removeClass("important");
            if (obj.hasClass("very-important")) obj.removeClass("very-important");
        } else if (intMinutes > 3) {
            if (obj.hasClass("very-important")) obj.removeClass("very-important");
            if (obj.hasClass("important") == false) obj.addClass("important");
        } else {
            if (obj.hasClass("important")) obj.removeClass("important");
            if (obj.hasClass("very-important") == false) obj.addClass("very-important");
        }
        
        twkTimeOuts[objID] = setTimeout('fTwkCountDown(\'' + objID + '\', ' + (intSec - 1) + ',\'' + strFunction + '\');', 1000);
    } else {
        if (twkTimeOuts[objID]) {
            clearTimeout(objID);
        }
        if (strFunction.length > 0) {
            var func = new Function(strFunction);
            func();
        }
    }
}

function fMyTwkRefresh(saleID, secRefresh, isTender) {
    begin = new Date();
    if (isTender) {
        $.post(baseURL + 'project/views/website/callbacks.ashx', { action: 'mytwk', sid: saleID, secRefresh: secRefresh },
        fMyTwkResponseTender, 'json');
    } else {
        $.post(baseURL + 'project/views/website/callbacks.ashx', { action: 'mytwk', sid: saleID, secRefresh: secRefresh },
        fMyTwkResponse, 'json');
    }
}

function fMyTwkResponse(data) {
    //var tmpTimer = document.getElementById('tmpTimer');
    var start = new Date();
    switch (data.status) {
        case 'timeout':
            showLogin();
            return;
        case 'noSale':
            alert('nosale');
            return;
        case 'refresh':
            break;
    }

    $("#refreshTime").html(data.time);

    var outBid = false;
    var isInt = new RegExp(/^\d+$/);
    for (var index = 0; index < data.lots.length; index++) {
        var lot = data.lots[index];
        var tr = $("tr[id$='tr" + lot.id + "']");
        var row = document.getElementById(tr.attr('id'));

        if (twkTimeOuts['t' + lot.id]) clearTimeout(twkTimeOuts['t' + lot.id]);
        if (twkTimeOuts['time' + lot.id]) clearTimeout(twkTimeOuts['time' + lot.id]);

        // indicators
        var indicators = ''

        // part of a combination
        if (lot.combination)
            indicators += '<img src="' + baseURL + 'project/content/img/c.gif" width="12" height="12" alt="c" class="tooltip" title="' + data.titles.lotPartOfCombination + '" />';

        // highest bidder
        if (lot.highestBidder) {
            if (lot.allocated) {
                indicators += '<img src="' + baseURL + 'project/content/img/buyer.gif" width="12" height="12" alt="*" class="tooltip" title="' + data.titles.buyer + '" />';
            } else {
                indicators += '<img src="' + baseURL + 'project/content/img/star.gif" width="12" height="12" alt="*" class="tooltip" title="' + data.titles.highestBidder + '" />';
            }

            // add highest bidder class
            tr.removeClass('light');
            if (tr.hasClass('lightDark') == false) tr.addClass('lightDark');

            // highest bidder always follow a lot
            tr.find("a[id$='hplFollow']").hide();
        } else {
            // remove highest bidder class
            if (tr.hasClass('lightDark')) {
                tr.removeClass('lightDark');
                if (lot.outBid) {
                    outBid = true;
                }
            }

            // not highest bidder, possibilty to uncheck a lot
            tr.find("a[id$='hplFollow']").show();
        }

        // out bid
        if (lot.outBid) {
            indicators += '<img src="' + baseURL + 'project/content/img/highlight.gif" width="12" height="12" alt="!" class="tooltip" title="' + data.titles.outbid + '" />';

            if (tr.hasClass('light') == false) tr.addClass('light');
            tr.removeClass('lightDark');
        } else {
            tr.removeClass('light');
        }

        // a lot of bidders
        if (lot.hot)
            indicators += '<img src="' + baseURL + 'project/content/img/vlam.gif" width="12" height="12" alt="flame" class="tooltip" title="' + data.titles.aLotOfBids + '" />';

        indicators += '&nbsp;';
        row.cells[1].innerHTML = indicators;

        if (row.cells.length > 5) {
            // lot is closed all underlying stuff don't change anymore
            if (lot.closed) {
                row.cells[5].innerHTML = '&nbsp;';
                row.cells[6].innerHTML = lot.remaining;
                continue;
            }

            // your bid + your proxy
            row.cells[3].innerHTML = lot.yourBid + '<br />' + lot.yourProxy;

            // current bid + count of bids
            if (lot.hot) {
                row.cells[4].innerHTML = lot.currentBid + '<br /><span class="blue">' + lot.bidCount + '</span>';
            } else {
                row.cells[4].innerHTML = lot.currentBid + '<br />' + lot.bidCount;
            }

            // next accepted bid
            row.cells[5].innerHTML = lot.nextBid;

            // time remaining
            if (isInt.test(lot.remaining)) {
                fTwkCountDown("time" + lot.id, lot.remaining, '');
            } else {
                row.cells[6].innerHTML = '<span id="time' + lot.id + '">' + lot.remaining + '</span>';
            }
        } else {
            // lot is closed all underlying stuff don't change anymore
            if (lot.closed) {
                row.cells[3].innerHTML = lot.remaining;
                continue;
            }

            // time remaining
            if (isInt.test(lot.remaining)) {
                fTwkCountDown("time" + lot.id, lot.remaining, '');
            } else {
                row.cells[3].innerHTML = '<span id="time' + lot.id + '">' + lot.remaining + '</span>';
            }
        }
    }

    if (outBid) {
        // show attention
        $("p[id$='attention']").show();
        initAttention();
    } else {
        // hide attention
        hideAttention();
    }

    clockpos = 38;
    setTimeout('fMyTwkRefresh(' + data.saleID + ', ' + data.secondsBeforeRefresh + ', false);', (parseInt(data.secondsBeforeRefresh) * 1000));

    var stop = new Date();
    //tmpTimer.innerHTML = 'server: ' + (start.getTime() - begin.getTime()) + 'ms | client:' + (stop.getTime() - start.getTime()) + 'ms';
}

function fMyTwkResponseTender(data) {
    //var tmpTimer = document.getElementById('tmpTimer');
    var start = new Date();
    switch (data.status) {
        case 'timeout':
            showLogin();
            return;
        case 'noSale':
            alert('nosale');
            return;
        case 'refresh':
            break;
    }

    $("#refreshTime").html(data.time);

    var outBid = false;
    var isInt = new RegExp(/^\d+$/);
    for (var index = 0; index < data.lots.length; index++) {
        var lot = data.lots[index];
        var tr = $("tr[id$='tr" + lot.id + "']");
        var row = document.getElementById(tr.attr('id'));

        if (twkTimeOuts['t' + lot.id]) clearTimeout(twkTimeOuts['t' + lot.id]);
        if (twkTimeOuts['time' + lot.id]) clearTimeout(twkTimeOuts['time' + lot.id]);

        // your bid
        row.cells[3].innerHTML = lot.yourBid;
        // your bids
        row.cells[4].innerHTML = lot.bidCount;
        // time remaining
        if (isInt.test(lot.remaining)) {
            fTwkCountDown("time" + lot.id, lot.remaining, '');
        } else {
            row.cells[5].innerHTML = '<span id="time' + lot.id + '">' + lot.remaining + '</span>';
        }
    }

    clockpos = 38;
    setTimeout('fMyTwkRefresh(' + data.saleID + ', ' + data.secondsBeforeRefresh + ', true);', (parseInt(data.secondsBeforeRefresh) * 1000));

    var stop = new Date();
    //tmpTimer.innerHTML = 'server: ' + (start.getTime() - begin.getTime()) + 'ms | client:' + (stop.getTime() - start.getTime()) + 'ms';
}

function fTwkCheckBid(lotID, lotNr, lotName, saleID, saleName, saleCountry, tender) {
    var proxy = 0;
    var bid = jQuery.trim($("input[id$='txtBid']").val());
    var agree = $("input[id$='chkAgreeConditions']").attr('checked') ? 1 : 0;
    if (tender == 0 && $("#proxy").attr('checked')) {
        proxy = 1;
    }
    tb_show('', baseURL + 'project/views/website/popups/bidPreview.aspx?lid=' + lotID + '&bid=' + bid + '&tender=' + tender + '&proxy=' + proxy + '&agree=' + agree +
        '&lotnr=' + lotNr + '&lotName=' + lotName.replace(/ /g, '+') + '&sid=' + saleID + '&saleName=' + saleName.replace(/ /g, '+') + '&saleCountry=' + saleCountry + '&width=400&height=220');
}

function fTwkPlaceBid(lotID, lotNr, lotName, saleID, saleName, saleCountry, tender, proxy, bid) {
    tb_show('', baseURL + 'project/views/website/popups/bidpreview.aspx?lid=' + lotID + '&bid=' + bid + '&tender=' + tender + '&proxy=' + proxy + '&agree=1&final=1' +
        '&lotnr=' + lotNr + '&lotName=' + lotName.replace(/ /g, '+') + '&sid=' + saleID + '&saleName=' + saleName.replace(/ /g, '+') + '&saleCountry=' + saleCountry + '&width=400&height=220');
}

function fTwkSwitchLanguage(languageID) {
    $.getJSON(baseURL + 'project/views/website/callbacks.ashx', { action: 'switchlanguage', lan: languageID },
        function(data) { if (data.languageID != '0') { window.location.href = window.location.href.replace(new RegExp('/[A-Za-z]{2}/'), '/' + data.languageID + '/'); } });
}

function fTwkSearchInLots() {
    var val = $("#txtSearchLots").val();

    if (val.length > 0) {
        var href = location.href;
        location.href = href.replace(location.search, '') + '?s=' + val
    }
}

function fTwkSearch(search) {
    if (!search) search = $("#txtSearch").val();
    if (search.length > 0) location.href = searchUrl + '?s=' + search;
}

function fTwkReloadLot(saleID, lotID, combination) {
    $.post(baseURL + 'project/views/website/callbacks.ashx', { action: 'lotdetails', sid: saleID, lid: lotID, combination: combination },
    function(data) {
        fTwkReloadLotProps(data.BidCount, data.CurrentBid, data.NextAcceptedBid, data.ReserveBid, data.Closing, true);
    }, 'json');
}

function fTwkReloadLotProps(bidcount, currentbid, nextbid, reservebid, closing, autoRefresh) {
    $("td[id$='tdNumberOfBids']").html(bidcount);
    $("td[id$='tdCurrentBid']").html(currentbid);
    $("td[id$='tdNextAcceptedBid']").html(nextbid);
    if (autoRefresh) {
        $("td[id$='tdReserveBid']").html(reservebid);
        $("div[id$='divClosingDate']").html(closing);
    }
}
function changeCountryData(countryCode, languageID) {
    if (!countryCode || countryCode.length == 0) return;
    if (!languageID) languageID = '';

    changeCountryDataExtended(countryCode, languageID, 0);
}
function changeCountryDataExtended(countryCode, languageID, simple) {
    var container;
    if (simple == 0) {
        container = $(".countryDetails");
    } else {
        container = $(".country");
    }
    container.load(baseURL + 'Project/Views/Shared/Handlers/ContactMapHandler.ashx?action=LoadCountry&countryCode=' + countryCode + '&languageID=' + languageID + '&simple=' + simple, null,
        function(responseText, textStatus, XMLHttpRequest) {
            if (simple == 0) {
                $("input[id$='emailTo']").val($(this).find("a[href^='mailto']").text());
                $("input[id$='countryCode']").val(countryCode);
            } else {
                $("select[id$='cboOffices']").val(countryCode);
            }
            container.show();
        }
    );
}

function getContactCountries(languageID) {
    if (!languageID) languageID = '';

    $.get(baseURL + 'Project/Views/Shared/Handlers/ContactMapHandler' + languageID + '-.ashx?action=GetXml',
        function(data) {
            var countries = $(data).find('country[activeInCountry="true"]');
            var options = '';
            countries.each(function() { options += '<option value="' + $(this).attr('countryId') + '">' + $(this).attr('countryDesc') + '</option>'; });
            $("select[id$='cboOffices']").html(options);
        },
        'xml'
    );
}

function resetFilterSales() {
    $(".bycountry").val('');
    $(".bycategory").val('');
    $(".bycountry option").show();
    $(".bycategory option").show();
    filterSales();
}
var reCountry = new RegExp(/\s*([A-Z]{2})/);
var reCategory = new RegExp(/(br[0-9]+)/);
function filterSales() {
    var country = $(".bycountry").val();
    var category = $(".bycategory").val();
    var hasCountry = country.length > 0;
    var hasCategory = category.length > 0;

    if (hasCountry == false && hasCategory == false)
        list = $(".saleslist tr");
    else if (hasCountry && hasCategory == false)
        list = $(".saleslist tr" + country);
    else if (hasCategory && hasCountry == false)
        list = $(".saleslist tr" + category);
    else
        list = $(".saleslist tr" + country).filter(category);

    var rows = $(".saleslist tr");
    rows.hide().removeClass('last');
    list.show();
    $(".headNumber").html('(' + list.length + ')');
    $(".saleslist tr:visible:last").addClass('last');

    if (hasCountry) $(".bycategory option").hide();
    if (hasCategory) $(".bycountry option").hide();

    if (hasCountry || hasCategory) {
        $(".saleslist tr:visible").each(function() {
            var css = $(this).attr('class');
            if (hasCountry) {
                m = reCategory.exec(css);
                if (m) $(".bycategory option[value='." + m[1] + "']").show();
            }
            if (hasCategory) {
                var m = reCountry.exec(css);
                if (m) $(".bycountry option[value='." + m[1] + "']").show();
            }
        });
    }

    $("a.showall")
        .removeClass('filterActive')
        .addClass(rows.length != list.length ? 'filterActive' : '');
}

/* Dutch auction */
var ContentItemDutchAuctionRegistration = {
    Register: function(saleID, agreeAlert) {
        var div = $("div.register_auction");
        if (div.find("input:checkbox[id$='chkConditions']").is(":checked") == false) {
            tb_message('', agreeAlert, 300, 75);
            return;
        }
        div.find("button").attr("disabled", "disabled");
        getJsonCI(
            'Octavalent.Project.Views.Shared.Controls.ContentItemDutchAuctionRegistration, Octavalent.Project',
            'Register',
            function(data) { ContentItemDutchAuctionRegistration.HandleResponse(data); },
            { sid: saleID });
    },
    HandleResponse: function(data) {
        if (data.success) {
            if (data.message) {
                tb_message('', data.message, 300, 250, 'location.reload(true);');
            } else {
                location.reload(true);
            }
        } else {
            if (data.message) {
                tb_message('', data.message, 300, 75, 'location.reload(true);');
            } else {
                location.reload(true);
            }
        }
    }
};

/* webcast */
var ContentItemWebcastRegistration = {
    Register: function(saleID, agreeAlert) {
        var div = $("div.register_auction");
        if (div.find("input:checkbox[id$='chkConditions']").is(":checked") == false) {
            tb_message('', agreeAlert, 300, 75);
            return;
        }
        div.find("button").attr("disabled", "disabled");
        getJsonCI(
            'Octavalent.Project.Views.Shared.Controls.ContentItemWebcastRegistration, Octavalent.Project',
            'Register',
            function(data) { ContentItemWebcastRegistration.HandleResponse(data); },
            { sid: saleID });
    },
    HandleResponse: function(data) {
        if (data.success) {
            if (data.message) {
                tb_message('', data.message, 320, 300, 'location.reload(true);');
            } else {
                location.reload(true);
            }
        } else {
            if (data.message) {
                tb_message('', data.message, 300, 75, 'location.reload(true);');
            } else {
                location.reload(true);
            }
        }
    }
};

function listGo(obj) {
    var links = $(obj).find("a")
    location.href = links.length == 1 ? $(links[0]).attr("href") : $(links[1]).attr("href");
}

// resize a image
function resize(image, fitContainer) {
    var parent = $(image);
    while (parent && parent.hasClass('resize') == false) {
        parent = parent.parent();
    }

    var maxwidth = parseInt(parent.css("width").replace('px', ''), 10);
    var maxheight = parseInt(parent.css("height").replace('px', ''), 10);

    var width = image.width | 0;
    var height = image.height | 0;

    if (width == 0) width = maxwidth;
    if (height == 0) height = maxheight;

    var widthPerc = maxwidth / width;
    var heightPerc = maxheight / height;

    var perc = fitContainer
                ? widthPerc > heightPerc ? heightPerc : widthPerc
                : widthPerc > heightPerc ? widthPerc : heightPerc;
    var newwidth = parseInt(perc * width);
    var newheight = parseInt(perc * height);
    //alert(maxwidth + 'x' + maxheight + '\n' + width + 'x' + height + '\n' + newwidth + 'x' + newheight);

    if (newwidth > maxwidth) {
        $(image).css("margin-left", "-" + ((newwidth - maxwidth) / 2) + 'px');
    } else {
        $(image).css("margin-left", ((maxwidth - newwidth) / 2) + 'px');
    }
    if (newheight > maxheight) {
        $(image).css("margin-top", "-" + ((newheight - maxheight) / 2) + 'px');
    } else {
        $(image).css("margin-top", ((maxheight - newheight) / 2) + 'px');
    }

    image.width = newwidth;
    image.height = newheight;
}

// replace a unordered list to a dropdown list
function unorderedListToDropDownList() {
    $("ul.toDDL").each(function() {
        var ul = $(this);

        // create the dropdown list
        var select = document.createElement("select");
        select.onchange = function() { fTwkSwitchLanguage(this.value); };
        $(select).addClass(ul.attr("class"));

        // add the items
        ul.find("li a").each(function() {
            var link = $(this);
            var lan = link.attr("lang");
            var option = document.createElement("option");
            option.value = lan.toLowerCase() == 'en' ? 'uk' : lan;
            option.appendChild(document.createTextNode(link.attr("title")));
            if (document.location.href.indexOf(link.attr("href")) != -1) option.selected = true;
            select.appendChild(option);
        });

        // add the dropdown list
        ul.before(select);

        // hide the unordered list
        ul.hide();
    });
}

function keyEnter(e) {
    var keynum = 0;
    if (window.event) { keynum = e.keyCode; }
    else if (e.which) { keynum = e.which; }
    //enter
    if (keynum == 13)
        return true;

    return false;
}

function keySubmit(e) {
    var keynum = 0;
    if (window.event) { keynum = e.keyCode; }
    else if (e.which) { keynum = e.which; }
    switch (keynum) {
        case 13: //enter
        case 32: //space
            return true;
        default:
            return false;
    }
}