﻿// setup logging (Firebug/Chrome/IE8)
var log = (window.console && console.log) ? (console.log.apply ? function() { console.log.apply(console, arguments) } : console.log) : function() { };


var hash = document.location.hash.length > 0 ? document.location.hash.substr(1) : null;
var startExhibitorView = hash == "+exview";
var startupCompany = startExhibitorView ? null : hash;
var fileHosted = document.location.protocol == "file:";
var kiosk = hash == "+kiosk" || $.cookie("kiosk") == "1";
if (hash == "+nokiosk") {
    $.cookie("kiosk", "0");
    kiosk = false;
} else if (kiosk) {
    $.cookie("kiosk", "1");
}

var getlogos = hash == "+getlogos";
var maxAdvertisers = 4;
var maxKioskAdvertisers = 5;
var kioskTimeout = 60 * 1000;

// known elements
var $main;
var $leftbar;
var $leftscrollable;
var $lefttop;
var $topbar;
var $movediv;
var $movecontainer;
var $moveimage;
var $filterinput;
var $filterclear;
var $teaser;
var $teaserbg;

var companies; // initialized by server-side generated script

// map related
var images = []; // each image is object of {url, height, width}
var imageUrls; // initialized by server-side generated script
var currentImage;
var currentIndex = 0;


$(function() {
    logEvent("init");
    // setup know elements
    $main = $("#main");
    $leftbar = $("#leftbar");
    $lefttop = $("#left-top");
    $leftscrollable = $("#left-scrollable");
    $topbar = $("#topbar");
    $movediv = $("#movediv");
    $movecontainer = $("#movecontainer");
    $moveimage = $("img", $movediv);
    $filterinput = $("#filter-input");
    $filterclear = $("#filter-clear");

    $teaser = $("#teaser");
    $teaserbg = $("#teaser-bg");

    if (fileHosted || kiosk) {
        $(document.body).addClass("kiosk");
    }

    // show advertisers
    var shown = 0;
    while (getlogos || shown < (kiosk ? maxKioskAdvertisers : maxAdvertisers)) {
        var hidden = $("#sponsors td:hidden");
        if (hidden.length == 0) break;
        var toshow = hidden[Math.floor(Math.random() * hidden.length)];
        $(toshow).show();
        shown++;
    }

    if (kiosk) {
        showTeaser();
        window.setTimeout(function() {
            var lastMove;
            var teaserHidden = false;

            $().bind("mousemove keypress", function() {
                lastMove = new Date();
                if (!teaserHidden) {
                    teaserHidden = true;
                    hideTeaser();
                    //$filterinput[0].focus();

                    window.setInterval(function() {
                        if (lastMove.getTime() + kioskTimeout < new Date().getTime()) {
                            window.location.replace("#+kiosk");
                            window.location.reload(true);
                        }
                    }, 3000);
                }
            });
        }, 2000);

        $("#youarehere").show().css({ top: hereTopPercent + '%', left: hereLeftPercent + '%' });

        $(document).bind("contextmenu", function(e) {
            return false;
        });
    }

    if (getlogos) {
        $.each(companies, function(i, k) {
            if (k.logo) {
                var img = $('<img/>').attr('src', formatLogoUrl(k.logo));
                $('body').append(img);
            }
        });
    }

    // adjust size of elements on window resize
    $(window).resize(setupLayout);

    setupLayout();
    loadMapImages(initMap);
});

function showTeaser() {
    // center teaser
    $teaser.css({
        "top": $(window).height() / 2 - $teaser.height() / 2,
        "left": $(window).width() / 2 - $teaser.width() / 2
    });

    $teaserbg.css({ "opacity": "0.3" }).show();

    // show
    $teaser.show();
}

function hideTeaser() {
    $teaser.hide();
    $teaserbg.hide();
}

function setupLayout() {
    if ($("#header").css("display") != "nonse") {
        for (var i = 0; i < 2; i++) {
            // do twice
            $main.height($(window).height() - $main.offset().top - 11);
            $leftbar.height($main.height());
            $leftscrollable.height($main.height() - $lefttop.outerHeight());
            $topbar.css("left", $leftbar.width());
            $topbar.width($main.width() - $topbar.position().left);
            //        var mcwidth = $main.width();
            //        if (mcwidth > $movecontainer.width())
            $movecontainer.width($main.width()).height($main.height());

        }
    }
}

function loadMapImages(callback) {
    log("loadMapImages");
    var loadedImages = 0;
    $.each(imageUrls, function(i, imageUrl) {
        var image = { url: imageUrl };
        images.push(image);
        // preload image
        $(new Image()).load(function() {
            log("Loaded: " + this.src);
            image.height = this.height;
            image.width = this.width;
            loadedImages++;

            if (loadedImages == images.length) {
                callback();
            }
        }).attr("src", imageUrl);
    });
}

function initMap() {

    log("initMap " + currentIndex);
    currentImage = images[currentIndex];
    $moveimage.attr("src", currentImage.url);
    initializeMoveDiv();
    initializeFilter();

    $("#companies-list > div").mouseover(function() { $("." + this.id).addClass("list-hover"); }).
        mouseout(function() { $(".list-hover").removeClass("list-hover"); });

    $("#companies-list > div > *").click(function() {
        var username = this.parentNode.id.substr(1);
        if ($(this).hasClass("i")) {
            var company = companies[username];
            setFilter(company.industry);
        } else if (this.tagName == "A") {
            showCompany(username);
        } else if (this.tagName == "INPUT") {
            toggleAgenda(username);
        }
        return false;
    });

    $movediv.click(function(e) {
        var boothElmenet = $(e.target).hasClass("b") ? e.target : ($(e.target.parentNode).hasClass("b") ? e.target.parentNode : null);
        if (boothElmenet) {
            var username = boothElmenet.className.split(' ')[1].substr(1);
            if (username) showCompany(username);
        };
    });

    $(".b").hover(function() {
        var booth = this.firstChild.data;
        var company = $("u", this).text();
        $("#tooltip-booth").text(booth);
        $("#tooltip-company").text(company);
        var offset = $(this).offset();
        var tooltip = $("#tooltip");
        tooltip.css({ top: offset.top - tooltip.outerHeight() - 2, left: offset.left - 5 }).show();
        //tooltip.css({ top: offset.top + $(this).outerHeight() + 4, left: offset.left + $(this).outerWidth() + 4 }).show();
    }, function() { $("#tooltip").hide(); });

    // show company if any
    if (startupCompany) {
        showCompany(startupCompany);
    }
    if (startExhibitorView) {
        toggleExhibitorView();
    }

    restoreAgendaFromCookie();
}

function getScreenCenter() {
    return { x: $main.width() / 2, y: $main.height() / 2 }
}

function getCompanyBooths(username) {
    var booths = [];
    $(".c" + username).each(function() { booths.push($(this).html().replace(/\<u\>.+$/i, "")); });
    if (booths.length == 1)
        return "Booth " + booths[0];
    else if (booths.length > 1)
        return "Booths: " + booths.join(", ");
    else // no booths
        return "Booth N/A";
}

function toggleExhibitorView() {
    $(["platinum", "gold", "corporate", "prime", "deluxe", "sponsor"]).each(function() {
        if ($("." + this).length == 1) $(".legend-" + this).hide();
    });

    $("body").toggleClass("exview");
    if ($("body").hasClass("exview")) {
        location.replace("#+exview");
    } else {
        location.replace("#");
    }

    setupLayout();
}

var db;
function logEvent(eventType, eventArgs) {
    if (fileHosted && window.google && google.gears) {
        if (!db) {
            db = google.gears.factory.create('beta.database');
            db.open('database-floorplan');
            db.execute('create table if not exists FPLog (EventType text, EventArg text, CreatedDate int)');
        }
        db.execute('insert into FPLog values (?, ?, ?)',
            [eventType, eventArgs ? eventArgs.toString() : null, new Date().getTime()]);
    } else if (PageMethods && PageMethods.LogEvent) {
        PageMethods.LogEvent(eventType, eventArgs ? eventArgs : null);
    }
}

var agenda = [];
function addToAgenda(usernames, restoreMode) {
    var usernames = $.isArray(usernames) ? usernames : [usernames];
    $.each(usernames, function() {
        agenda.push(this.toString());
        $("#c" + this).addClass("fav");
        $(".c" + this).addClass("fav");
    });
    updatePopupAgenda();
    updateAgendaFilter();
    if (!restoreMode) {
        applyFilter();
        setAgendaCookie();
        $.each(usernames, function() {
            logEvent("agendaadd", this.toString());
        });
    }
}

function removeFromAgenda(username) {
    agenda = $.grep(agenda, function(val) { return val != username; });
    $("#c" + username).removeClass("fav");
    $(".c" + username).removeClass("fav");
    updatePopupAgenda();
    updateAgendaFilter();
    applyFilter();
    setAgendaCookie();
}

function addAllToAgenda() {
    var allVisible = [];
    $("#companies-list div:visible:not(.fav)").each(function() {
        var username = this.id.substr(1);
        allVisible.push(username);
    });

    addToAgenda(allVisible);
}

function clearAgenda() {
    agenda = [];
    $(".fav").removeClass("fav");
    updatePopupAgenda();
    updateAgendaFilter();
    applyFilter();
    setAgendaCookie();
}

function toggleAgenda(username) {
    if ($.inArray(username, agenda) != -1)
        removeFromAgenda(username);
    else
        addToAgenda(username);
}

function setAgendaCookie() {
    var cookieValue = agenda.join(";");
    var expDate = new Date();
    expDate.setDate(expDate.getDate() + 200);
    $.cookie("fpagenda", cookieValue, { path: '/', expires: expDate });
}

function restoreAgendaFromCookie() {
    var value = $.cookie("fpagenda");
    if (value) {
        var usernames = value.split(";");
        for (var i = 0; i < usernames.length; i++) {
            if (companies[usernames[i]]) addToAgenda(usernames[i], true);
        }
    }
}

function updateAgendaFilter() {
    //$('#filter-agenda').text("Show Starred (" + agenda.length + ")"); //agenda.length > 0 ?  : "My Agenda"
    $('#starred-count').text(agenda.length); //agenda.length > 0 ?  : "My Agenda"
}

function floorplan_print(selected) {
    logEvent(selected ? "printsel" : "printall");
    if (selected) {
        $("body").addClass("print-selected");
    } else {
        $("body").removeClass("print-selected");
    }
    window.print();
}
