﻿/// <reference path="/javascript/controls/LoginWindow.js"/>
/// <reference path="/javascript/jquery-1.4.2.min.js"/>

var _interval = 200;
var _maxItemCount = 8;
var _itemHeight = 105;
var _duration = 8000;

$(document).ready(function () {
    LoginWindow.Init(".btn-login");

    // Sadly, some options dont work with jQuery 1.4.2
    $('a.tip').qtip({
        content: {
            text: false // Use each elements title attribute
        },
        show: { delay: 0 },
        position: {
            corner: {
                tooltip: 'bottomLeft',
                target: 'topRight'
            }
        },
        style: {
            name: 'dark' // Style it according to the preset 'cream' style
        }
    });
});

function saveCurrentRegionSelection() {
    var regionIDs = [];
    var value;

    $("#region-frame li input:checked").each(function (i) {
        var regionID = parseInt($(this).closest("span").attr("regionid"));
        regionIDs[i] = regionID;
    });

    if (regionIDs.length > 0)
        value = regionIDs.join(',');
    else
        value = '';

    saveRegions(value);
}

function saveRegions(regions) {
    // Push them to the server
    $.ajax({
        type: "POST",
        url: "/Services/RegionService.asmx/SetRegions",
        data: "{Value : '" + regions + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function () {
            window.location = window.location;
            SearchBar.Reload();

            // Hide the colorbox
            $.colorbox.close();
        },
        error: function () {
            alert('error while storing regions');
        }
    });
}

function init(interval, maxItemCount) {
    _interval = interval;
    _maxItemCount = maxItemCount;

    $("#last-ads ul").append(
        $("<img/>")
            .attr("src", "/Images/loader.gif")
            .attr("alt", "loading...")
        );
    $("#last-ads").css("display", "block")
    FetchAds();
}

function FetchAds() {
    $.ajax({
        type: "POST",
        url: "/Services/AdService.asmx/GetNewAds",
        data: "{Count: 24}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            RenderAds(msg.d);

            createScrollTimer("#last-ads ul");
        }
    });
}

function RenderAds(ads) {
    var lastItem;

    $('#last-ads ul').html('');
    
    // prepend all the adds
    for (var i = ads.length - 1; i >= 0; i--) {
        var ad = ads[i];
        var currentItem;

        currentItem = $("<li/>")
            .attr("id", "ad-" + ad.ID)
            .append($("<a/>")
                .attr("href", ad.Link)
                .attr("class", "image")
                .append($("<img/>")
                    .attr("src", ad.ImageSource)
                    .attr("alt", ad.Title))
                )
            .append($("<div/>")
                .attr("class", "information")
                .append($("<a/>")
                    .attr("href", ad.Link)
                    .text(ad.ShortTitle))
                .append($("<span/>")
                    .attr("class", "date")
                    .text(ad.Date + " - "))
                .append($("<span/>")
                    .attr("class", "price")
                    .html(ad.Price))
                );

        if (lastItem == null) {
            $("#last-ads ul").prepend(currentItem);
        }
        else {
            lastItem.after(currentItem);
        }

        lastItem = currentItem;
    }
}

function createScrollTimer(elementID) {
    var element = $(elementID);
    var timerId;

    timerId = setTimeout(function () {
        createScroller(element, timerId);
    }, _interval);

    element.hover(
        function () {
            // stop the animation
            element.stop();
            // stop the timer
            clearTimeout(timerId);
        }, 
        function () {
            // stop the animation
            element.stop();
            // stop the timer
            clearTimeout(timerId);

            timerId = setTimeout(function () {
                // Start a new timer
                var location = element.data('nextLocation');
                createScroller(element, timerId, location);
            }, 500);
        }
    );
}

function createScroller(element, timer, location) {
    // Stop any current animation
    element.stop();

    var height = (7 * _itemHeight);
    var totalListHeight = element.height();
    var sequences = Math.ceil(totalListHeight / height) - 1;
    var duration = _duration;

    if(location == undefined) {
        location = element.data('nextLocation');

        if (location == undefined) { // Starting
            location = height;
        }
        else if ((location + height) < totalListHeight) { // Intermediate
            location = location + height;
        }
        else {
            location = 0; // At the end
        }
    }

    if (location == 0) {
        duration = duration * sequences;
    }

    // Store the next location
    element.data('nextLocation', location);

    // Animate
    element.animate({ 'margin-top': (location * -1) }, duration, function () {
        timer = setTimeout(function () {
            createScrollTimer(element, timer);
        }, _interval);
    });
}
