﻿function fadeAndShowElements() {
    var periodCount = arguments.length / 2;
    var classNames = [];
    var times = [];
    for (var i = 0; i < periodCount; i++) {
        classNames[i] = arguments[i * 2];
        times[i] = arguments[i * 2 + 1];
    }

    var register = function(period) {
        var time = times[period];
        $(document).oneTime(time, function() {
            var nextPeriod = (period + 1) % periodCount;

            $(classNames[period]).fadeOut("slow", function() {
                $(classNames[nextPeriod]).fadeIn("slow");
            });

            register(nextPeriod);
        });
    };
    register(0);
}

function OfferCarousel(carouselId) {
    // public variables
    this.applicationPath = "/";
    this.category = "Kaikki";
    this.totalItems = undefined;
    this.offerId = null;

    // private members
    var self = this;
    var pageSize = 4;
    var currentPage = 1;
    var animating = false;

    var htmlEscape = function(s) {
        return $('<div/>').text(s).html();
    };

    var createUrl = function(path) {
        return (self.applicationPath != "/") ? (self.applicationPath + path) : path;
    };

    var createOfferHtml = function(offer) {

        var discount = "";
        var price = "";
        var offerPriceClass = "offerPrice";

        if (offer.discountPercentage && offer.discountPercentage != "0") {
            if (offer.notZero) {
                discount = "<div class='fadableOfferDiscount' style='display: none'>-" + offer.discountPercentage + "%</div>";
                offerPriceClass = "offerPrice fadableOfferPrice";
            }
            else {
                discount = "<div class='offerDiscount'>-" + offer.discountPercentage + "%</div>";
            }
        }
        if (offer.notZero) {
            price = "<div class='" + offerPriceClass + "'>" +
                    "<p class='offerEuros'>" + htmlEscape(offer.euros) +
                    "<span class='offerCents'>" + htmlEscape(offer.cents) + "<em>" + htmlEscape(offer.unit) + "</em></span>" +
                    "</p>" +
                    "</div>";
        }

        var link = createUrl("/Tarjoukset/?Kategoria=" + self.category + "&Tarjous=" + offer.id);

        var yellowLabelStart = "";
        var yellowLabelEnd = "";
        var yellowLabelBgStyle = "";

        if (offer.yellowLabel != "") {
            var yellowLabelPath = createUrl("/img/yellowLabels/" + offer.yellowLabel);
            yellowLabelBgStyle = "style='background-image: url(" + yellowLabelPath + ")'";
            yellowLabelStart = "<div class='yellowLabel'>";
            yellowLabelEnd = "</div>";
        }

        var validity = "";
        if (!offer.pirkkaNew && offer.validityEnd != "") {
            validity = "<div class='additionalInfo offerValid'>Voimassa " + offer.validityEnd + " asti</div></div>";
        }

        return "<div class='carouselOffer' " + yellowLabelBgStyle + " >" + yellowLabelStart + "<div class='carouselOfferImgContainer'><div class='carouselOfferImg'><span></span><a href='" + link + "'><img src='" + offer.image + "' /></a></div></div>" +
            "<div class='offerHeadings'><a href='" + link + "'>" +
            "<span class='offerHeading1'>" + htmlEscape(offer.title1) + "</span><br />" +
            "<span class='offerHeading2'>" + htmlEscape(offer.title2) + "</span><br />" +
            "</a></div>" +
            price +
            discount +
            yellowLabelEnd +
            validity;
    };

    var createTooltip = function(tooltipId, offer) {
        var pics = "";
        if (offer.pirkka) {
            pics += "<br /><br /><img src='" + createUrl("/img/pirkkaWhite.png") + "' alt='' />";
        }
        if (offer.pirkka && offer.plussa) {
            pics += "<br />";
        }
        if (offer.plussa) {
            pics += "<br /><img src='" + createUrl("/img/plussaWhite.png") + "' alt='' />";
        }
        var description = "<p>" + offer.description + pics + "</p>";
        var discount = (offer.discountPercentage && offer.discountPercentage != "0") ? ("<p class='discount'>Alennus " + offer.discountPercentage + "%</p>") : "";
        var html = "<div id='" + tooltipId + "' class='offerTooltip'>" +
            "<div class='tooltipInfo'>" + description + discount;

        if (!offer.pirkkaNew && offer.validityPeriod != null && offer.validityPeriod != "") {
            html += "<span class='additionalInfo'>" + offer.validityPeriod + "</span>";
        }
        html += "</div><div class='tooltipBottom'></div>";
        $("#tooltips").append(html);
    };

    var parseOffer = function(offer) {
        var price = offer.find("price");
        return {
            id: offer.find("id").text(),
            title1: offer.find("title1").text(),
            title2: offer.find("title2").text(),
            image: offer.find("image").text(),
            description: offer.find("description").text(),
            validityPeriod: offer.find("validityPeriod").text(),
            validityEnd: offer.find("validityEnd").text(),
            pirkka: offer.find("pirkka").text().toLowerCase() == "true",
            pirkkaNew: offer.find("pirkkaNew").text().toLowerCase() == "true",
            plussa: offer.find("plussa").text().toLowerCase() == "true",
            discountPercentage: offer.find("discountPercentage").text(),
            euros: price.find("euros").text(),
            cents: price.find("cents").text(),
            notZero: price.find("notZero").text().toLowerCase() == "false",
            unit: price.find("unit").text(),
            yellowLabel: offer.find("yellowLabel").text()
        };
    };

    var updatePageCount = function() {
        $(".totalPages").text(pageCount() || 1);
    };

    var createOffersFromXml = function(carousel, xml) {
        self.totalItems = parseInt(jQuery('total', xml).text());
        carousel.size(self.totalItems);

        updatePageCount();

        jQuery('offer', xml).each(function(i) {
            var index = carousel.first + i;
            var tooltipId = "offerTooltip" + index;
            var offer = parseOffer(jQuery(this));

            var item = carousel.add(index, createOfferHtml(offer));

            createTooltip(tooltipId, offer);

            $(".carouselOffer", item).tooltip("#" + tooltipId, "#offerTooltipContainer");
        });
    };

    var pageCount = function() {
        return 1 + Math.floor((self.totalItems - 1) / pageSize);
    };

    var nextButton = function() {
        return jQuery(".offerNextButton");
    };

    var previousButton = function() {
        return jQuery(".offerPrevButton");
    };

    var init = function(carousel) {
        nextButton().bind('click', function() {
            if (!animating && currentPage < pageCount()) {
                animating = true;
                $(".currentPage").text(++currentPage);
                carousel.next();
            }
            return false;
        });

        previousButton().bind('click', function() {
            if (!animating && currentPage > 1) {
                animating = true;
                $(".currentPage").text(--currentPage);
                carousel.prev();
            }
            return false;
        });
    };

    var nextCallback = function(c, ct, enable) {
        nextButton().toggleClass("disabledNextButton", !enable);
    };

    var prevCallback = function(c, ct, enable) {
        previousButton().toggleClass("disabledPrevButton", !enable);
    };

    var loadCallback = function(carousel, state) {
        if (carousel.has(carousel.first, carousel.last)) return;

        var count = carousel.last - carousel.first + 1;
        var args = {
            category: self.category,
            first: carousel.first - 1,
            count: count + (pageSize * 4), // ask for some extra
            time: new Date().getTime() // create unique url for every request
        };

        if (self.offerId != null) {
            args = { offerId: self.offerId };
        }

        jQuery.get(createUrl("/Ajax/Offers.ashx"), args,
                function(xml) { createOffersFromXml(carousel, xml); },
                'xml');
    };

    // public methods

    this.register = function() {
        jQuery(document).ready(function() {
            jQuery(carouselId).jcarousel({
                initCallback: init,
                itemLoadCallback: loadCallback,
                buttonNextCallback: nextCallback,
                buttonPrevCallback: prevCallback,
                visible: pageSize,
                scroll: pageSize,
                size: self.totalItems,
                itemVisibleOutCallback: function() { animating = false; }
            });

            updatePageCount();
        });
    };
    
    return this;
}

(function($) {
    var showingTip = false;

    $.fn.tooltip = function(data, container) {
        // create container if necessary
        if ($(container).length == 0)
            $('<div id="' + container.slice(1) + '"></div>').appendTo("body");

        // initialize our tooltip and our data container and also the close box
        $(container).css({
            position: "absolute",
            display: "inline"
        }).hide();

        $(data).hide();

        // use the list item as parent
        var parent = $(this).parent();

        $(parent).bind("mouseover", function(e) {
            e.preventDefault();

            if (showingTip) return false;
            showingTip = true;

            // create the data...
            $(data).clone(true).show().appendTo(container);

            // ...and move the container to correct position
            var offset = parent.offset();
            var tip = $(container);
            tip.css({
                top: offset.top - (tip.height() + 5),
                left: offset.left
            }).show();

            return false;
        });

        $(parent).bind("mouseout", function(e) {
            $(container).hide().empty();
            showingTip = false;
            return false;
        });
    };

})(jQuery);


function addTransparentCss(applicationPath) {
    if (applicationPath == "/")
        applicationPath = "";
    var headtag = document.getElementsByTagName('head')[0];
    if (headtag) {
        var linktag = document.createElement('link');
        linktag.type = 'text/css';
        linktag.rel = 'stylesheet';
        linktag.href = applicationPath + '/css/transparent.css';
        headtag.appendChild(linktag);
    }
}

function closeCampaignPopup(campaignId) {
    $("#popupCampaign").hide();
    popupCampaignDisplayed(campaignId);
    return false;
}
