$(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();
    initFiles();
    initAttention();
    initProcess();
    initHighlight();
    initHomeSlider();
    initFeaturedOverview();
    //initFixedScroll();
    initNew();
});

/* initNew(); */
var newTimeOut = 0;
function initNew() {
    $(".new .item").each(function () {
        $(".new .navigation a").append("<span />");
    });

    $(".new .navigation a").click(function () {
        changeNew();
    });

    $(".new .item:first").addClass("active");
    $(".new .item:first").show();

    changeNavigation(0);

    newTimeOut = setTimeout(changeNew, 10000);
}
function changeNew() {
    clearTimeout(newTimeOut);
    
    var list = $(".new .item");
    var index = list.index(".item.active");
    var current = $(".new .item.active");
    var next = list.eq(index + 1);

    if (next.length) {
        current.hideMe();
        next.showMe();
    } else {
        current.hideMe();
        list.eq(0).showMe("active");
    }

    changeNavigation(list.index(".item.active"));
}
jQuery.fn.hideMe = function () {
    this.slideUp("slow");
    this.removeClass("active");
    return this;
};
jQuery.fn.showMe = function () {
    this.delay(200).slideDown("slow", function () {
        newTimeOut = setTimeout(changeNew, 10000);
    });
    this.addClass("active");
    return this;
};
function changeNavigation(activeIndex) {
    $(".new .navigation span.active").removeClass("active");
    var i = activeIndex;//  $(".new .item.active").index() - 1;
    $(".new .navigation span").eq(i).addClass("active");
}
/* Einde initNew(); */

function initFixedScroll() {
    if ($.browser.msie && $.browser.version.substr(0, 1) < 7) {
        return;
    }
    if ($(".tabs").length) {
        $(window).scroll(function () {
            if ($(document).scrollTop() > 565) {
                if (!$(".footerHolder").hasClass("fixed")) {
                    $("body").css("padding-bottom", "230px");
                    $(".footerHolder").stop().animate({
                        marginBottom: "0px"
                    }, 500);
                    $(".footerHolder").addClass("fixed");
                }
            } else {
                $(".footerHolder").stop().animate({
                    marginBottom: "-260px"
                }, 500, function () {
                    if ($(".footerHolder").hasClass("fixed")) {
                        $(".footerHolder").removeClass("fixed");
                    }
                });
            }
        });
    };
}

function initFeaturedOverview() {
    $(".featuredblock").unbind("mouseover");
    $(".featuredblock").live("mouseover", function (e) {
        e.preventDefault();

        if (!$(this).hasClass("open")) {

            // remove active featuredblock (if there is)
            $(".featuredblock.open").find(".h").fadeOut("fast");
            $(".featuredblock.open").removeClass("open");

            $(".featuredblock").css("z-index", "98");
            $(this).css("z-index", "99");

            // remove alignment if already aligned
            if ($(this).hasClass("alignleft")) {
                $(this).removeClass("alignleft");
            }
            if ($(this).hasClass("alignright")) {
                $(this).removeClass("alignright");
            }

            // give certain alignment depending on position
            if ($(this).nextAll(".featuredheader ").length == 0) {
                // alignleft
                $(this).addClass("alignleft");
            } else {
                // alignright
                $(this).addClass("alignright");
            }

            // show info
            $(this).find(".h").fadeIn("fast");
            $(this).addClass("open");

            // Function: cleck if there is a mouseout
            $("body").unbind("mousemove");
            $("body").mousemove(function (event) {
                event.preventDefault();

                var b = $(".featuredblock.open");
                if (b.length) {
                    var h = b.find(".h");
                    var padding = 5;

                    if ((event.pageX < (h.offset().left - padding)) || (event.pageX > (h.offset().left + h.width() + padding)) || (event.pageY < (h.offset().top - padding)) || (event.pageY > (h.offset().top + h.height() + padding))) {

                        h.fadeOut("fast");
                        b.removeClass("open");
                    }
                }

            });
        };

    });
}

var welcomeTimeout = 5000;
function initHomeSlider() {
    if ($(".tabs").length) {
        $(".tabs li").each(function() {
            var h = $(this).find("div a").height();
            var y = (62 - h) / 2;

            $(this).find("div a").css("padding-top", y + "px");
            $(this).find("div a").css("height", (62 - y));
        });
    }

    var sliderListLinks = $(".sliderlist .tabs li a"),
        sliderContainerListItems = $(".sliderContainer .output li.slide");
    if (sliderListLinks.length > 0 &&
        sliderContainerListItems.length > 0) {
        $.featureList(
            sliderListLinks,
            sliderContainerListItems,
            {
                start_item: welcomeTimeout > -1 ? sliderContainerListItems.length - 1 : 0
            });
    }
}

function initHighlight() {
    var s = $(document).getUrlParam('s') || $(document).getUrlParam('S');
    if (s) {
        $("body").highlight(s, 'searchText');
    }
}

// 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 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 () {

            var t = $(this);
            var li = t.parent();
            var v = 53;

            li.siblings().removeClass('active');
            li.addClass('active');
            var itemHeight = li.height() + 9;
            $('.whiteBg', li).height(itemHeight);

            // Double check the positioning
            var pop = $('.categoriesPopup', li);
            pop.css('margin-top', '-' + v + 'px');
            var pos = pop.offset();
            var height = pop.height();
            var bottom = pos.top + height;

            var win = $(window).height() + $(window).scrollTop();
            var bottomOffset = bottom - win;

            // if the bottom of the popup is below the window's edge we need to move it up
            var nmar;
            if (bottomOffset > 0) {
                // Calculate the new margin
                var min = (height - (v + itemHeight));
                var max = -v;

                // Where we really want to put it
                var desired = (bottomOffset + v);
                nmar = (desired > min) ? -min : -desired;
                if (nmar > max) {
                    nmar = max;
                }
            } else {
                nmar = -v;
            }

            pop.css('margin-top', nmar + 'px');

            var 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 () {
            var 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(selector) {
    if (!selector) selector = $(".tooltip[title!='']");

    if (selector.length) {

        selector.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 (event) { positionTip(event); });

                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 () {
            var 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');
            }
        });
    }
}

// Initialise folding/unfolding of locations
function initFiles() {

    if ($('.files').length) {
        $('.files .opener').click(function () {
            var det = $(this).parents(".files").find('.filesDetails');
            if (det.is(':visible')) {
                det.slideUp('fast');
                $(this).parents(".files").removeClass('activeDetails');
            } else {
                $(this).parents(".files").find('.filesDetails:visible').slideUp('fast');
                det.slideDown('fast');
                $(this).parents(".files").addClass('activeDetails');
            }
        });
    }
}

// Fold/unfold the faq blocks
function initFaq() {
    if ($('.faq').length) {

        $('.faq h5 a').click(function () {

            var li = $(this).parent().parent();
            if (li.is('.active')) {
                li.removeClass('active');
            } else {
                li.addClass('active');
            }
            this.blur();
            return false;

        });

    }
}

function initAttention(alterPageTitle) {
    if ($('.removeIn5').length) {
        setInterval("hideAttention()", 5000);
        if (alterPageTitle) {
            document.title = "(!) " + document.title;
        }
    }
}

function hideAttention() {
    $(".removeIn5").fadeOut(500);
    var pageTitle = document.title;
    if (pageTitle.substr(0, 4) == "(!) ") {
        document.title = pageTitle.substr(4);
    }
}

/* Process start */
// Initialise the infographic process
function initProcess() {
    if ($('.process').length) {

        $('.process > div > ul > li').eq(0).moveProcessTo();
        var 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 () {
            var li = $(this).parent();
            if (!li.is('.active')) { li.css({ marginTop: "1px" }); }
            }, function () {
            var 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);

                // hide remove auction link
                ContentItemDashboard.ToggleRemoveAuctionLink($(this), false);
            } 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;
        this.HasSmsActivated = data.hasSmsActivated;
        var dutchAttention = false;
        var isHighestBidder = false;
        var isOutbid = false;
        if (null == data.lots) {
            return;
        }

        var html = "<table cellpadding='0' cellspacing='0' class='trackedlots'>" + data.header;
        if (data.isTender) {
            for (var i = 0; i < data.lots.length; i++) {
                var tLot = data.lots[i];
                if (tLot.IsHighestBidder) {
                    isHighestBidder = true;
                }
                var cssclass = (i % 2 == 0 ? "" : " class='odd'");
                html += "<tr id='tr" + tLot.ID + "'" + cssclass + ">"
                        + "<td class='number'>" + tLot.Number + "</td>"
                        + "<td class='alignCenter'>" + tLot.Indicators + "</td>"
                        + "<td class='tooltip description highlight'>"
                            + "<h3><a href='" + tLot.Url + "' title='" + tLot.Title + "'>"
                            + tLot.Title + (tLot.NumberOfItems > 1 ? " <span>(" + tLot.NumberOfItems + "x)</span>" : "")
                            + "</a></h3></td>"
                        + "<td>" + tLot.RelationBid + "</td>"
                        + "<td>" + tLot.CurrentBid + "</td>"
                        + "<td>" + tLot.Closing + "</td>"
                        + "<td class='alignCenter last'>" + this.GetStopFollowingLink(tLot.ID, tLot.IsHighestBidder) + "</td>"
                        + "</tr>";
            }
        } else {
            for (var n = 0; n < data.lots.length; n++) {
                var lot = data.lots[n];
                if (lot.IsHighestBidder) {
                    isHighestBidder = true;
                }
                if (lot.IsOutbid) {
                    isOutbid = true;
                }
                var hasBid = (lot.IsHighestBidder || lot.IsOutbid);
                var cssClass = (n % 2 == 0 ? "" : "odd") + (lot.IsHighestBidder ? " lightDark" : (lot.IsOutbid ? " light" : ""));

                // add combination class
                if (hasBid == false && lot.IsCombination) {
                    cssClass += " combination-underline";
                }

                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 + "'>"
                            + "<span class='title'>" + lot.Title + "</span>" + (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.IsOpen == false || lot.IsClosed == true || lot.IsHighestBidder == true || lot.HasBidPermission == false) ? " 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)
                            + this.GetFollowBySmsLink(lot.ID, lot.IsFollowingBySms, hasBid)
                        + "</td></tr>";
                if (lot.SecondsTillDutchStart >= 0) {
                    dutchAttention = true;
                }
            }
        }
        html += "</table>";

        if (dutchAttention) {
            this.ShowDutchAttention(head);
        }
        this.ToggleRemoveAuctionLink(head, isHighestBidder == false);
        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); },
                    { SaleID: ContentItemDashboard.SaleID, lid: lotID });
        }, interval);
    },
    GetFollowBySmsLink: function (lotID, isFollowingBySms, hasBid) {
        if (this.HasSmsActivated == false || hasBid == false) {
            return "";
        }
        // toggle the title, image and alternative text of the link by the value of isFollowingBySms.
        var title;
        var image;

        if (isFollowingBySms) {
            title = this.Labels.stopFollowingBySms;
            image = "mobilephone.png";
        }
        else {
            title = this.Labels.followBySms;
            image = "mobilephone_grey.png";
        }

        return "<a id='" + ContentItemDashboard.Name + "_FollowBySmsLink_ " + lotID + "' href='javascript:void(0);' onclick='ContentItemDashboard.ToggleFollowBySms(" + lotID + ", this.id);' class='tooltip' title='" + title + "'>"
                                + "<img src='" + baseURL + "valentnet/content/icons/16x16/" + image + "' alt='' /></a>";
    },
    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); },
                    { SaleID: ContentItemDashboard.SaleID, isUpdate: false, showDutch: true });
            } else {
                getJsonCI(
                        ContentItemDashboard.TypeName,
                        'GetLots',
                        function (data) { ContentItemDashboard.DisplayLots(data, head); },
                        { SaleID: 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); },
                    { SaleID: 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&SaleID=" + 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>";
    },
    HasSmsActivated: false,
    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));
            },
            { SaleID: ContentItemDashboard.SaleID, lid: lotID });
    },
    Name: "ContentItemDashboard",
    RemoveAuction: function () {
        getJsonCI(
            ContentItemDashboard.TypeName,
            'RemoveAuction',
            function (data) {
                if (data.success) {
                    tb_remove();
                    $("#ciDashboard")
                        .find(".auction_head:has(input[value='" + ContentItemDashboard.SaleID + "'])")
                        .click()
                        .remove();
                }
            },
            { SaleID: this.SaleID });
    },
    SaleID: 0,
    SaleTerms: '',
    SetCurrentDate: function (currentDate) { $("#refreshTime").html(currentDate); },
    ShowAttention: function () {
        // show attention
        $("p[id$='attention']").show();
        initAttention(true);
    },
    ShowDutchAttention: function (head) {
        if (head.find(".onehourleft").length == 0) {
            var img = head.find("img");
            img.attr("src", img.attr("src").replace(".gif", "_important.gif"));
            img.after("<span class='onehourleft'>!</span>");
        }
    },
    ShowRemoveAuctionConfirmation: function () {
        var div = $("#ciDashboardRemoveAuctionMessage");
        if (!div.length) {
            getJsonCI(
                ContentItemDashboard.TypeName,
                'GetRemoveAuctionConfirmation',
                function (data) {
                    $("#ciDashboard").append("<div id='ciDashboardRemoveAuctionMessage' class='hidden'>" + data.message + "</div>");
                    $("#ciDashboardRemoveAuctionMessage button.kavelButton").click(function () { ContentItemDashboard.RemoveAuction(); });
                    ContentItemDashboard.ShowRemoveAuctionConfirmationWindow();
                });
        } else {
            ContentItemDashboard.ShowRemoveAuctionConfirmationWindow();
        }
    },
    ShowRemoveAuctionConfirmationWindow: function () {
        tb_show("", "#TB_inline?inlineId=ciDashboardRemoveAuctionMessage&width=260&height=147");
        $("#TB_closeWindowButton").attr("href", "javascript:void(0);").click(function () { tb_remove(); });
    },
    Timeout: 0,
    ToggleFollowBySms: function (lotID, followBySmsLinkID) {
        getJsonCI(
            ContentItemDashboard.TypeName,
            'ToggleFollowBySms',
            function (data) {
                // update link
                $("a[id$='" + followBySmsLinkID + "']").html(ContentItemDashboard.GetFollowBySmsLink(lotID, data.isFollowingBySms, true));
            },
            { LotID: lotID, SaleID: this.SaleID });
    },
    ToggleRemoveAuctionLink: function (head, show) {
        var link = head.find("a.removeAuction");
        if (show == link.is(":visible")) {
            // the required/desired state equals the current state
            return;
        }
        if (show) {
            link.click(function () {
                ContentItemDashboard.ShowRemoveAuctionConfirmation();
                return false;
            });
            link.show();
        } else {
            link.removeAttr("onclick");
            link.hide();
        }
    },
    TypeName: "Octavalent.Project.Views.Shared.Controls.ContentItemDashboard, Octavalent.Project.Controls",
    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 isHighestBidder = false;
        var isOutbid = false;
        if (data.isTender) {
            for (var i = 0; i < data.lots.length; i++) {
                var tLot = data.lots[i];
                if (tLot.IsHighestBidder) {
                    isHighestBidder = true;
                }
                var tIndex = 0;
                var tRow = $("#tr" + tLot.ID);
                var tCell;

                // check indicators
                tIndex++;
                tCell = tRow.children(":eq(" + tIndex + ")");
                if (tCell.length && tCell.html() != tLot.Indicators) {
                    tCell.html(tLot.Indicators);
                }

                // check relation bid
                tIndex += 2;
                tCell = tRow.children(":eq(" + tIndex + ")");
                if (tCell.length && tCell.html() != tLot.RelationBid) {
                    tCell.html(tLot.RelationBid);
                }

                // check current bid
                tIndex++;
                tCell = tRow.children(":eq(" + tIndex + ")");
                if (tCell.length && tCell.html().toLowerCase() != tLot.CurrentBid.toLowerCase()) {
                    tCell.html(tLot.CurrentBid);
                }

                // set closing
                tIndex++;
                tCell = tRow.children(":eq(" + tIndex + ")");
                if (tCell.length && tCell.html() != tLot.Closing) {
                    tCell.html(tLot.Closing);
                }

                // check follow
                tIndex++;
                tCell = tRow.children(":eq(" + tIndex + ")");
                if (tCell.length && tLot.IsHighestBidder) {
                    tCell.children("a:eq(0)").hide();
                } else {
                    tCell.children("a:eq(0)").show();
                }
            }
        } else {
            for (var n = 0; n < data.lots.length; n++) {
                var lot = data.lots[n];
                if (lot.IsHighestBidder) {
                    isHighestBidder = true;
                }
                var index = 0;
                var row = $("#tr" + lot.ID);
                var cell;

                // check class
                row.removeClass("combination-underline");

                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");
                    }
                } else if (lot.IsCombination) {
                    row.addClass("combination-underline");
                }

                // check indicators
                index++;
                cell = row.children(":eq(" + index + ")");
                if (cell.length && cell.html() != lot.Indicators) {
                    cell.html(lot.Indicators);
                }

                index += 2;
                if (data.showBiddingValues) {
                    // check relation bid
                    cell = row.children(":eq(" + index + ")");
                    if (cell.length && cell.html() != lot.RelationBid) {
                        cell.html(lot.RelationBid);
                    }

                    // check current bid
                    index++;
                    cell = row.children(":eq(" + index + ")");
                    if (cell.length) {
                        if (cell.html().toLowerCase() != lot.CurrentBid.toLowerCase()) {
                            cell.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));
                        } else {
                            // the current bid remains the same, but the lot could have closed since last update
                            index++;
                            cell = row.children(":eq(" + index + ")");
                        }

                        if (lot.IsOpen == false || lot.IsClosed == true || lot.IsHighestBidder == true || lot.HasBidPermission == false) {
                            cell.children("button.BidThisButton").hide();
                        } else {
                            var bidButton = cell.children("button.BidThisButton");
                            if (bidButton.is(":hidden")) {
                                bidButton.show();
                            }
                        }
                    }
                    index++;
                }

                // set closing
                cell = row.children(":eq(" + index + ")");
                if (cell.length && cell.html() != lot.Closing) {
                    cell.html(lot.Closing);
                }

                // check follow
                index++;
                cell = row.children(":eq(" + index + ")");
                if (cell.length && lot.IsHighestBidder) {
                    cell.children("a:eq(0)").hide();
                } else {
                    cell.children("a:eq(0)").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");
                    }
                }
            }
        }
        var head = $("#ciDashboard").find(".auction_head:has(input[value='" + this.SaleID + "'])");
        if (dutchAttention) {
            this.ShowDutchAttention(head);
        }
        this.ToggleRemoveAuctionLink(head, isHighestBidder == false);
        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 */

/* 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 = $.parseJSON(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 + "' />");
    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 goToRegistration() {
    setTimeout(function () { window.location = registrationUrl; }, 0);
}

function showLogin() {
    hidePopup();
    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 = $.parseJSON(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 = $.parseJSON(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 () { window.location.reload(true); }, 'json');
}

function fTwkToggleThumbs() {
    $.post(baseURL + 'project/views/website/callbacks.ashx', { action: 'togglethumbs' },
        function () { 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, 110);
            }
        }
    , '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 fTwkCheckBid(lotID, lotNr, lotName, saleID, saleName, saleCountry, tender) {
    var proxy = 0;
    var bid = $("input[id$='txtBid']").val().replace(/ /g, '');
    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, '+') + '&SaleID=' + saleID + '&saleName=' + saleName.replace(/ /g, '+') + '&saleCountry=' + saleCountry + '&width=400&height=220&lan=' + languageID);
}

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, '+') + '&SaleID=' + saleID + '&saleName=' + saleName.replace(/ /g, '+') + '&saleCountry=' + saleCountry + '&width=400&height=220&lan=' + languageID);
}

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=' + encodeURIComponent(val);
    }
}

function fTwkSearch(search) {
    if (!search) search = $("#txtSearch").val();
    if (search.length > 0) location.href = searchUrl + '?s=' + encodeURIComponent(search);
}

function fTwkReloadLot(saleID, lotID, combination) {
    $.post(baseURL + 'project/views/website/callbacks.ashx', { action: 'lotdetails', SaleID: 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'
    );
}

/* Sale Registration */
var ContentItemSaleRegistration = {
    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.ContentItemSaleRegistration, Octavalent.Project.Controls',
            'Register',
            function (data) { ContentItemSaleRegistration.HandleResponse(data); },
            { SaleID: 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.Controls',
            'Register',
            function (data) { ContentItemWebcastRegistration.HandleResponse(data); },
            { SaleID: 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").not(":has(img[src*='flyer'])");
    location.href = links.length == 1 ? $(links[0]).attr("href") : $(links[1]).attr("href");
}

// resize a image
function resize(image, fitContainer, onReady) {

    if (onReady == undefined && $.browser.msie && parseInt($.browser.version) == 7) {
        // IE7 sometimes fires the onload event too soon, when the image has not been downloaded yet.
        // Add handler to document.ready event to resize when DOM is ready.
        $(document).ready(function () { resize(image, fitContainer, true); });
        return;
    }

    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;
    }
}
