// ==========================
// PromoBanner
// ==========================

function PromoBanner(sPromoCanvasId, sPromoDisplayWindowId, iPlaceholderWidth, iPlaceholderHeight, slidesIds) {

    this.slideRepository = [];
    this.slide = [];

    this.placeholderWidth = iPlaceholderWidth;
    this.placeholderHeight = iPlaceholderHeight;

    this.color = {
        blue: '#46a0eb',
        pink: '#ef037e',
        orange: '#f89d15',
        purple: '#782779',
        black: 'Black'
    };

    this.init(sPromoCanvasId, sPromoDisplayWindowId, slidesIds);

}


PromoBanner.prototype.init = function (sPromoCanvasId, sPromoDisplayWindowId, slidesIds) {

    this.canvas = document.getElementById(sPromoCanvasId);
    this.canvas.style.position = 'relative';

    this.displayWindow = document.getElementById(sPromoDisplayWindowId);
    this.displayWindow.style.position = 'relative';
    this.displayWindow.style.width = this.placeholderWidth + 'px';
    this.displayWindow.style.height = this.placeholderHeight + 'px';

    this.buildSlideRepository();
    this.selectSlides(slidesIds);

    //this.initNextSlide();

    // Start the first slide.
    var self = this;
    setTimeout(function () { self.showNextSlide(1); }, 1500);

};


PromoBanner.prototype.selectSlides = function (slidesIds) {

    var i, slide;

    for (i = 0; i < slidesIds.length; i++) {

        slide = this.getSlideFromRepository(slidesIds[i]);

        if (slide) {
            this.slide.push(slide);
        }

    }

};


PromoBanner.prototype.getSlideFromRepository = function (sSlideId) {

    var i;

    for (i = 0; i < this.slideRepository.length; i++) {

        if (this.slideRepository[i].id === sSlideId) {
            return this.slideRepository[i];
        }

    }

};


PromoBanner.prototype.buildSlideRepository = function () {

    this.slideRepository.push(new PBSlideWordMess('wordmess', this));

    this.slideRepository.push(new PBSlideNormal('eugenevanbaal', this, '/images/promoBanner/eugenevanbaal.jpg', 6000, 1200, [
        { text: 'Eugene van Baal', color: this.color.blue, posx: 545, posy: 72, delay: 1500 },
        { text: 'Website + CMS', color: this.color.blue, posx: 565, posy: 102, delay: 2500 }
        ]));

    this.slideRepository.push(new PBSlideNormal('hansjanssen', this, '/images/promoBanner/hansjanssen.jpg', 6000, 1200, [
        { text: 'Hans Janssen Bedrijfsmakelaars', color: this.color.blue, posx: 540, posy: 110, delay: 1500 },
        { text: 'Website + CMS + RSS + Twitter', color: this.color.blue, posx: 560, posy: 140, delay: 2500 }
        ]));

    this.slideRepository.push(new PBSlideNormal('duycker', this, '/images/promoBanner/duycker.png', 6000, 1200));

    this.slideRepository.push(new PBSlideNormal('kinderfonds', this, '/images/promoBanner/kinderfonds.png', 6000, 1200));

    this.slideRepository.push(new PBSlideNormal('zoover', this, '/images/promoBanner/zoover.png', 6000, 1200));

    this.slideRepository.push(new PBSlideNormal('axitraxi', this, '/images/promoBanner/axitraxi.jpg', 6000, 1200, [
        { text: 'Axitraxi', color: this.color.blue, posx: 520, posy: 90, delay: 1500 },
        { text: 'Website + CMS + SEO + PDF + Mailblast Pro', color: this.color.blue, posx: 490, posy: 120, delay: 2500 }
        ]));

    this.slideRepository.push(new PBSlideNormal('beleefreizen', this, '/images/promoBanner/beleefreizen.jpg', 6000, 1200, [
        { text: 'BeleefReizen', color: this.color.blue, posx: 690, posy: 30, delay: 1500 },
        { text: 'Mailblast Pro', color: this.color.blue, posx: 710, posy: 60, delay: 2500 }
        ]));

    this.slideRepository.push(new PBSlideNormal('millingertheetuin', this, '/images/promoBanner/millingertheetuin.jpg', 6000, 1200, [
        { text: 'Millinger Theetuin', color: this.color.blue, posx: 690, posy: 30, delay: 1500 },
        { text: 'Website', color: this.color.blue, posx: 710, posy: 60, delay: 2500 }
        ]));

    this.slideRepository.push(new PBSlideNormal('savarijn', this, '/images/promoBanner/savarijn.jpg', 6000, 1200, [
        { text: 'Savarijn', color: this.color.blue, posx: 540, posy: 30, delay: 1500 },
        { text: 'Website + CMS + Mailblast Pro', color: this.color.blue, posx: 560, posy: 60, delay: 2500 }
        ]));

    this.slideRepository.push(new PBSlideNormal('vakantiereiswijzer', this, '/images/promoBanner/vakantiereiswijzer.png', 6000, 1200));

    this.slideRepository.push(new PBSlideNormal('forfarmers', this, '/images/promoBanner/forfarmers.png', 6000, 1200));

    this.slideRepository.push(new PBSlideNormal('stoetenslagh', this, '/images/promoBanner/stoetenslagh.png', 6000, 1200));

    this.slideRepository.push(new PBSlideNormal('duchenne', this, '/images/promoBanner/duchenne.png', 6000, 1200));

    this.slideRepository.push(new PBSlideNormal('alpenparks', this, '/images/promoBanner/alpenparks.png', 6000, 1200));

};


PromoBanner.prototype.showNextSlide = function (iSlides) {

    if (this.slide.length === 0)
        return;

    if (!this.currentSlideIndex && this.currentSlideIndex != 0)
        this.currentSlideIndex = 0;
    else
        this.currentSlideIndex = this.getSiblingSlideIndex(this.currentSlideIndex, iSlides);

    this.slide[this.currentSlideIndex].start();

};


PromoBanner.prototype.setCurrentSlideIndex = function (slide) {

    this.currentSlideIndex = this.getSlideIndex(slide);

};


PromoBanner.prototype.getSlideIndex = function (slide) {

    for (var i = 0; i < this.slide.length; i++) {

        if (this.slide[i] == slide)
            return i;

    };

};


PromoBanner.prototype.getSiblingSlide = function (slide, iMove) {

    return this.slide[this.getSiblingSlideIndex(slide, iMove)];

};


PromoBanner.prototype.getSiblingSlideIndex = function (slide, iMove) {

    var slideIndex;

    if (typeof (slide) != 'number')
        slideIndex = this.getSlideIndex(slide);
    else
        slideIndex = slide;

    slideIndex += iMove;

    while (slideIndex >= this.slide.length || slideIndex < 0) {

        if (slideIndex >= this.slide.length)
            slideIndex -= this.slide.length;
        else if (slideIndex < 0)
            slideIndex = this.slide.length + slideIndex;

    };

    return slideIndex;

};


PromoBanner.prototype.initNextSlide = function () {

    this.getSiblingSlide(this.currentSlideIndex, 1).init();

};



function PBSlide() {

    this.startType = 'normal'; // Possible values: normal, slide.
    this.endType = 'normal'; // Possible values: normal, slide.
    this.pauseAfter = 1200;
    this.mainShowDuration = 5000;

    this.eventAction = [];

    this.event = {
        start: 'start',
        startMainShow: 'startMainShow',
        startHideAnim: 'startHideAnim',
        end: 'end'
    };

};


PBSlide.prototype.init = function () {

    if (this.slideElem)
        return;

    this.colorBlue = '#46a0eb';
    this.colorPink = '#ef037e';
    this.colorOrange = '#f89d15';
    this.colorPurple = '#782779';

    this.slideElem = this.buildSlideElement();

    this.promoBanner.displayWindow.appendChild(this.slideElem);

};


PBSlide.prototype.buildSlideElement = function () {

    var slideElem = document.createElement('div');
    slideElem.style.position = 'absolute';
    slideElem.style.top = '0px';
    slideElem.style.left = this.promoBanner.placeholderWidth + 'px';
    slideElem.style.width = this.promoBanner.placeholderWidth + 'px';
    slideElem.style.height = this.promoBanner.placeholderHeight + 'px';

    return slideElem;

};


PBSlide.prototype.start = function () {

    this.init();

    switch (this.startType) {

        case 'slide':
            this.showWithShiftAnim();
            break;

        default:
            this.show();

    };

    this.eventStart();

};


PBSlide.prototype.startMainShow = function () {

    this.eventFired(this.event.startMainShow);

    var self = this;
    setTimeout(function () { self.end(); }, this.mainShowDuration);

};


PBSlide.prototype.end = function () {

    this.eventFired(this.event.end);

    switch (this.endType) {

        case 'slide':
            this.hideWithShiftAnim();
            break;

        default:
            this.hide();

    };

};


PBSlide.prototype.showWithShiftAnim = function () {

    this.shiftSlideShow(this.slideElem, this.promoBanner.placeholderWidth, 0, 400);

};


PBSlide.prototype.hideWithShiftAnim = function () {

    this.shiftSlideHide(this.slideElem, 0, -(this.promoBanner.placeholderWidth), 400);

};


PBSlide.prototype.show = function () {

    this.slideElem.style.left = '0px';

    this.startMainShow();

};


PBSlide.prototype.hide = function () {

    this.slideElem.style.display = 'none';

    this.eventEnd();

};


PBSlide.prototype.destroy = function () {

    // Remove element from HTML.
    if (this.slideElem)
        this.promoBanner.displayWindow.removeChild(this.slideElem);

    this.slideElem = null;

};


PBSlide.prototype.shiftSlideShow = function (slide, iStartPos, iEndPos, tTot, iTime) {

    var iTimeIncrement = 40;
    var lTot = iEndPos - iStartPos;

    if (!iTime)
        iTime = 0;

    var iTimeLeft = tTot - iTime;

    var iPos = (lTot * Math.pow(iTimeLeft, 2)) / Math.pow(tTot, 2);

    slide.style.left = iEndPos - Math.round(iPos) + 'px';

    if (iTime < tTot) {

        iTime += iTimeIncrement;

        var self = this;

        setTimeout(function () {

            self.shiftSlideShow(slide, iStartPos, iEndPos, tTot, iTime);

        }, iTimeIncrement);

    } else {

        this.eventShowWithShiftAnimEnd();

    };

};


PBSlide.prototype.shiftSlideHide = function (slide, iStartPos, iEndPos, tTot, iTime) {

    var iTimeIncrement = 40;
    var lTot = iEndPos - iStartPos;

    if (!iTime)
        iTime = 0;

    var iTimeLeft = tTot - iTime;

    var iPos = (lTot * Math.pow(iTime, 2)) / Math.pow(tTot, 2);

    slide.style.left = iStartPos + Math.round(iPos) + 'px';

    if (iTime < tTot) {

        iTime += iTimeIncrement;

        var self = this;

        setTimeout(function () {

            self.shiftSlideHide(slide, iStartPos, iEndPos, tTot, iTime);

        }, iTimeIncrement);

    } else {

        this.eventHideWithShiftAnimEnd();

    };

};


PBSlide.prototype.addEventAction = function (eventAction) {

    this.eventAction.push(eventAction);

    //    console.log(eventAction.eventId);

};


PBSlide.prototype.eventFired = function (eventId) {

    //    console.log(eventId);

    for (var i = 0; i < this.eventAction.length; i++) {

        //        console.log('Event ' + eventId + ' - ' + this.eventAction[i].eventId + '- match = ' + (this.eventAction[i].eventId === eventId));

        if (this.eventAction[i].eventId === eventId)
            this.eventAction[i].action();

    };

};


PBSlide.prototype.eventStart = function () {

    this.eventFired('start');

    this.promoBanner.setCurrentSlideIndex(this);

    if (this.promoBanner.slide.length > 1)
        this.promoBanner.getSiblingSlide(this, 1).init();

};


PBSlide.prototype.eventEnd = function () {

    this.destroy();

    var self = this;
    setTimeout(function () { self.promoBanner.showNextSlide(1); }, this.pauseAfter);

};


PBSlide.prototype.eventShowWithShiftAnimEnd = function () {

    this.startMainShow();

};


PBSlide.prototype.eventHideWithShiftAnimEnd = function () {

    this.eventEnd();

};


PBSlideNormal.prototype = new PBSlide();
PBSlideNormal.prototype.constructor = PBSlideNormal;

function PBSlideNormal(sId, promoBanner, sImageSource, iMainShowDuration, iPauseAfter, arrayLabels) {

    this.id = sId;
    this.promoBanner = promoBanner;
    this.imageSource = sImageSource;
    this.label = arrayLabels || [];
    this.pauseAfter = iPauseAfter;
    this.mainShowDuration = iMainShowDuration;

    this.startType = 'slide'; // Possible values: normal, slide.
    this.endType = 'slide'; // Possible values: normal, slide.

    this.eventAction = [];

};


PBSlideNormal.prototype.init = function () {

    var label2, label, i;

    if (this.slideElem)
        return;

    function placeImage(placeholder, sSource, iWidth, iHeight, iTop, iLeft) {

        var image = document.createElement('img');
        image.src = sSource;
        image.style.width = iWidth + 'px';
        image.style.height = iHeight + 'px';
        image.style.position = 'absolute';
        image.style.top = iTop + 'px';
        image.style.left = iLeft + 'px';

        placeholder.appendChild(image);

    };

    this.slideElem = this.buildSlideElement();
    //    this.slideElem.style.backgroundColor = this.promoBanner.color.orange;

    placeImage(this.slideElem, this.imageSource, this.promoBanner.placeholderWidth, this.promoBanner.placeholderHeight, 0, 0);

    label2 = [];

    for (i = 0; i < this.label.length; i++) {

        label = new PBLabel(this.slideElem, this.label[i].text, this.label[i].color, this.promoBanner.color.black, 16, this.label[i].posx, this.label[i].posy, false, false, true, this.label[i].delay);

        this.addEventAction({ self: label, eventId: 'startMainShow', action: function () {

            this.self.showElement();

        }
        });

    };

    this.promoBanner.displayWindow.appendChild(this.slideElem);

};


PBSlideWordMess.prototype = new PBSlide();
PBSlideWordMess.prototype.constructor = PBSlideWordMess;

function PBSlideWordMess(sId, promoBanner) {

    this.id = sId;
    this.promoBanner = promoBanner;

    this.startType = 'normal'; // Possible values: normal, slide.
    this.endType = 'slide'; // Possible values: normal, slide.
    this.pauseAfter = 500;
    this.mainShowDuration = 11000;

};


PBSlideWordMess.prototype.addItems = function () {

    function randOrd() { return (Math.round(Math.random()) - 0.5); };

    var wordBase = [
    'Facebook',
    'RSS',
    'Website',
    'HTML',
    'Twitter',
    '.Net',
    'ASP',
    'PHP',
    'Google',
    'JavaScript',
    'XML',
    'XHTML',
    'SEO',
    'Webapplicatie',
    'SAAS',
    'E-mail',
    'Flash',
    'CSS',
    'SQL',
    'XSLT',
    'PDF',
    'Cookie',
    'Cache',
    'CMS',
    'Sitemap',
    'XML Schema',
    'Wireframe',
    'Interactieontwerp',
    'Analytics',
    'AdWords',
    'Atom',
    'MySQL',
    'LinkedIn',
    'Database',
    'Ajax',
    'XSL-FO',
    'Bloggen',
    '404',
    'Semantic web',
    'Webservice',
    'Applet',
    'Java',
    'Soap',
    'SVG',
    'PNG',
    'Encoding',
    'OOP',
    'DNS',
    'YouTube',
    'Mobile',
    'DOM',
    'URL',
    'API',
    'Xpath',
    'XForms',
    'Namespaces',
    'Widget',
    'UTF8',
    'FTP',
    'HTTP',
    'HTTPS',
    'SSL',
    'DocBook',
    'Server',
    'Client',
    'Browser',
    'Mailclient',
    'Pagerank',
    '403',
    'Actionscript',
    'Apache',
    'Bandwidth',
    'Buffer',
    'C#',
    'Cache',
    'CDN',
    'Chrome',
    'Class Diagram',
    'Cloud Computing',
    'Compatibility',
    'Cross Browser Support',
    'Debugging',
    'Doctype',
    'Documentation',
    'Encryption',
    'Entity-relationship model',
    'Embedding',
    'Event Handling',
    'Firefox',
    'Firewall',
    'Flow Charts',
    'Forum',
    'Framework',
    'Gateway',
    'Globalisation',
    'HTML 5',
    'I/O',
    'IIS',
    'Interface',
    'Internet Explorer',
    'IP',
    'JSON',
    'Load balancing',
    'Logging',
    'Meta data',
    'MVC',
    'Packet',
    'Page hits',
    'Perl',
    'Port',
    'Proxy',
    'Python',
    'Requirements',
    'Ruby',
    'SaaS',
    'Security',
    'Session',
    'Scripting',
    'Sequence Diagram',
    'Security Testing',
    'Stress Testing',
    'Software Scalability',
    'Scaling up',
    'Scaling out',
    'Software design patterns',
    'TCP',
    'Templates',
    'Time out',
    'TLS',
    'Typography',
    'UML',
    'Unicode',
    'Use Cases',
    'Use Case Diagram',
    'User Experience',
    'UX Testing',
    'W3C',
    'Web 2.0',
    'Wordpress'
    ];

    // Shuffle the array.
    wordBase.sort(randOrd);

    // Double the array, because there are to few words at this moment.
    word = wordBase.concat(wordBase);

    var color = [
        this.promoBanner.color.blue,
        this.promoBanner.color.orange,
        this.promoBanner.color.pink,
        this.promoBanner.color.purple
    ];

    var label = [];

    // The big last label.
    var finalLabel = new PBLabel(this.slideElem, 'Bel Tekwerk.', this.promoBanner.color.orange, this.promoBanner.color.black, 60, 485, 105, true, true, true, 1000);

    var i = word.length;
    var k = i;

    var newLabel = new PBLabelRandom(this.slideElem, word[0], color[Math.floor(Math.random() * color.length)], 'Black', 16, true, finalLabel, 0);

    label.push(newLabel);

    do {
        var j = k - i;

        if (j > 0) {

            newLabel = new PBLabelRandom(this.slideElem, word[j], color[Math.floor(Math.random() * color.length)], 'Black', 16, true, newLabel, j / k);
            label.push(newLabel);

        };

    } while (--i);

    var l = label.length;

    do {

        label[l - 1].init();

    } while (--l);

    finalLabel.init();

    // Initiate all by initiating the last label.
    newLabel.showElement();

};


PBSlideWordMess.prototype.eventStart = function () {

    this.promoBanner.setCurrentSlideIndex(this);

    if (this.promoBanner.slide.length > 1)
        this.promoBanner.getSiblingSlide(this, 1).init();

    this.addItems();

};



function PBItem() {

    this.posX;
    this.posY;
    this.centerX = false;
    this.centerY = false;

};


PBItem.prototype.getBaseElement = function (sElemName) {

    var baseElem = document.createElement(sElemName);
    baseElem.style.position = 'absolute';

    return baseElem;

};


PBItem.prototype.positionElement = function (baseElem) {

    var posX = this.posX;
    var posY = this.posY;

    if (this.centerX)
        posX -= (0.5 * baseElem.offsetWidth);

    if (this.centerY)
        posY -= (0.5 * baseElem.offsetHeight);

    baseElem.style.top = posY + 'px';
    baseElem.style.left = posX + 'px';

};


PBItem.prototype.buildElement = function () {

    this.elem = this.getElement();

};


PBItem.prototype.getElement = function () {

    return this.getBaseElement('p');

};


PBItem.prototype.drawElement = function () {

    this.placeholder.appendChild(this.elem);

    this.positionElement(this.elem);

};


PBItem.prototype.showElement = function () {

    if (!this.elem)
        this.init();

    if (this.delay) {
        var self = this;
        setTimeout(function () {

            self.elem.style.visibility = 'visible';

        }, this.delay);

    } else {

        this.elem.style.visibility = 'visible';

    };

};



PBLabel.prototype = new PBItem();
PBLabel.prototype.constructor = PBLabel;

function PBLabel(placeholder, sText, sBackgroundColor, sTextColor, iFontSize, iPosX, iPosY, bCenterX, bCenterY, bRoundedCorners, iDelay) {

    this.placeholder = placeholder;
    this.text = sText;
    this.backgroundColor = sBackgroundColor;
    this.textColor = sTextColor;
    this.fontSize = (iFontSize ? iFontSize : 12);
    this.posX = iPosX;
    this.posY = iPosY;
    this.centerX = bCenterX;
    this.centerY = bCenterY;
    this.roundedCorners = bRoundedCorners;
    this.delay = iDelay;

};


PBLabel.prototype.init = function () {

    this.buildElement();

    this.drawElement();

};


PBLabel.prototype.getElement = function () {

    var elem = this.getBaseElement('p');

    elem.appendChild(document.createTextNode(this.text));
    elem.style.backgroundColor = this.backgroundColor;
    elem.style.color = this.textColor;
    elem.style.padding = '0.2em 0.3em 0.2em 0.3em';
    elem.style.fontSize = this.fontSize + 'px';
    elem.style.fontWeight = 'bold';
    elem.style.textTransform = 'uppercase';
    elem.style.whiteSpace = 'nowrap';
    elem.style.margin = '0px';
    elem.style.lineHeight = '1em';
    elem.style.visibility = 'hidden';

    if (this.roundedCorners)
        elem.style.borderRadius = '0.2em';

    return elem;

};


PBLabel.prototype.animElement = function () {

    var self = this;

    //    setTimeout(function () { self.shakeElement(); }, Math.floor(Math.random() * (1000)));

};


PBLabel.prototype.hideElement = function () {

    this.elem.style.display = 'none';

};


PBLabel.prototype.moveElement = function () {

    if (this.displacement == 2)
        this.displacement = -2;
    else
        this.displacement = 2;


    this.elem.style.top = this.posY + this.displacement + 'px';
    this.elem.style.left = this.posX + this.displacement + 'px';

};


PBLabel.prototype.shakeElement = function () {

    var self = this;

    this.posY = this.elem.offsetTop;
    this.posX = this.elem.offsetLeft;

    setInterval(function () { self.moveElement(); }, 50);

};


PBLabelRandom.prototype = new PBLabel();
PBLabelRandom.prototype.constructor = PBLabelRandom;

function PBLabelRandom(placeholder, sText, sBackgroundColor, sTextColor, iFontSize, bRoundedCorners, nextLabel, fIndexFactor) {

    this.placeholder = placeholder;
    this.text = sText;
    this.backgroundColor = sBackgroundColor;
    this.textColor = sTextColor;
    this.fontSize = iFontSize;
    this.nextLabel = nextLabel;
    this.indexFactor = fIndexFactor;
    this.roundedCorners = bRoundedCorners;

};


PBLabelRandom.prototype.drawElement = function () {

    this.placeholder.appendChild(this.elem);

    this.positionElement(this.elem);

};


PBLabelRandom.prototype.showElement = function () {

    if (this.nextLabel) {

        var self = this;
        setTimeout(function () {

            self.nextLabel.showElement();

        }, 100 * Math.log(this.indexFactor * 2));

    };

    if (this.delay) {
        var self = this;
        setTimeout(function () {

            self.elem.style.visibility = 'visible';

        }, this.delay);

    } else {

        this.elem.style.visibility = 'visible';

    };

};


PBLabelRandom.prototype.positionElement = function (baseElem) {

    function getRandomPos(iMin, iMax) {

        return iMin + Math.floor(Math.random() * (iMax - iMin));

    };

    var iMarginX = 24;
    var iMarginY = 8;

    baseElem.style.top = getRandomPos(iMarginY, 210 - baseElem.offsetHeight - iMarginY) + 'px';
    baseElem.style.left = getRandomPos(iMarginX, 970 - baseElem.offsetWidth - iMarginX) + 'px';

};


// ==========================
// Menu
// ==========================

function Menu(sPlaceholderId, sBaseUrl) {

    this.placeholderId = sPlaceholderId;
    this.imagePath = sBaseUrl + '/images/layout';
    this.menuRoot;

};


Menu.prototype.init = function () {

    this.placeholder = document.getElementById(this.placeholderId);

    this.menuRoot.passObjects(this);

    this.menuRoot.init();

    this.preloadImages();

};


Menu.prototype.preloadImages = function () {

    function buildImage(sSrc) {

        var image = document.createElement('img');
        image.src = sSrc;

        return image;

    };

    var preloadBox = document.createElement('div');
    preloadBox.style.visibility = 'hidden';

    preloadBox.appendChild(buildImage(this.imagePath + '/submenu_bg.png'));

    this.placeholder.appendChild(preloadBox);

};



function MenuItem(sId, sImageId, sName, sTargetUrl, arrayMenuItem, bSelected, iWidth, sPayoff) {

    this.id = sId;
    this.name = sName;
    this.targetUrl = sTargetUrl;
    this.selected = bSelected;
    this.width = iWidth;
    this.payoff = sPayoff;

    this.menuItem = arrayMenuItem;

};


MenuItem.prototype.initChildren = function (menuItems) {

    var n, bLastItem;

    n = menuItems.length;

    if (n > 0) {

        do {

            bLastItem = (n == menuItems.length);

            menuItems[n - 1].init(bLastItem);

        } while (--n);

    }

};


MenuItem.prototype.init = function (bLast) {

    this.initChildren(this.menuItem);

    this.box = document.createElement('div');
    this.box.style.cursor = 'pointer';
    this.box.onclick = createMethodReference(this, this.click);
    this.box.style.padding = '7px 13px 6px 13px';
    this.box.style.position = 'relative';

    if (bLast) {
        this.box.style.borderBottomLeftRadius = '5px';
        this.box.style.borderBottomRightRadius = '5px';
    }

    this.box.onmouseover = createMethodReference(this, this.mouseOver);
    this.box.onmouseout = createMethodReference(this, this.mouseOut);

    this.link = document.createElement('a');
    this.link.className = 'link';
    this.link.style.margin = '0px';
    this.link.style.whiteSpace = 'nowrap';
    this.link.appendChild(document.createTextNode(this.name));

    if (this.targetUrl)
        this.link.href = this.targetUrl;

    this.box.appendChild(this.link);

    if (this.payoff.length > 0) {

        payoffPar = document.createElement('p');
        payoffPar.appendChild(document.createTextNode(this.payoff));
        payoffPar.style.marginBottom = '0px';
        payoffPar.style.whiteSpace = 'nowrap';

        this.box.appendChild(payoffPar);

    }

};


MenuItem.prototype.click = function (menu) {

    location.href = this.targetUrl;

};


MenuItem.prototype.passObjects = function (menu) {

    // Add rootobject to this object.
    this.menu = menu;

    // Call the same method for the children.
    var n = this.menuItem.length;

    if (n > 0) {

        do {

            this.menuItem[n - 1].passObjects(menu);

        } while (--n);

    };

};


MenuItem.prototype.getMenuItemById = function (sId) {

    var n = this.menuItem.length;

    if (n > 0) {

        do {

            if (this.menuItem[n - 1].id === sId) {

                return this.menuItem[n - 1];

            } else {

                var subMenuItem = this.menuItem[n - 1].getMenuItemById(sId);

                if (subMenuItem)
                    return subMenuItem;

            };

        } while (--n);

    };

};


MenuItem.prototype.mouseOver = function (e) {

    this.box.style.backgroundColor = '#46a0eb';
    this.link.style.textDecoration = 'underline';

};


MenuItem.prototype.mouseOut = function (e) {

    this.box.style.backgroundColor = 'transparent';
    this.link.style.textDecoration = 'none';

};


RootMenuItem.prototype = new MenuItem();

function RootMenuItem(arrayMenuItem) {

    this.menuItem = arrayMenuItem;

};


RootMenuItem.prototype.init = function (bLast) {

    this.initChildren(this.menuItem);

};



MainMenuItem.prototype = new MenuItem();

function MainMenuItem(sId, sImageId, sName, sTargetUrl, arrayMenuItem, bSelected, iWidth) {

    this.id = sId;
    this.name = sName;
    this.targetUrl = sTargetUrl;
    this.selected = bSelected;
    this.width = iWidth;

    this.margin = 38; // Space between menuitems.

    this.menuItem = arrayMenuItem;

};


MainMenuItem.prototype.init = function (bLast) {

    this.initChildren(this.menuItem);

    this.placeholder = document.getElementById('P' + this.id);

    this.link = document.getElementById('M' + this.id);
    this.link.onmouseover = createMethodReference(this, this.mouseOver);
    this.link.onmouseout = createMethodReference(this, this.mouseOut);

};


MainMenuItem.prototype.mouseOver = function (e) {

    if (this.menuItem.length > 0 && !this.submenuBox)
        this.showSubmenu();

};


MainMenuItem.prototype.mouseOut = function (e) {

    if (this.submenuBox && this.checkMouseLeave(this.submenuBox, e) && this.checkMouseLeave(this.link, e))
        this.removeSubmenu();

};


MainMenuItem.prototype.mouseOverSubmenu = function () {



};


MainMenuItem.prototype.mouseOutSubmenu = function (e) {

    if (this.submenuBox && this.checkMouseLeave(this.submenuBox, e) && this.checkMouseLeave(this.link, e))
        this.removeSubmenu();

};


MainMenuItem.prototype.showSubmenu = function () {

    if (!this.submenuBox)
        this.drawSubmenu();

    this.menu.placeholder.appendChild(this.submenuBox);

    this.submenuShowing = true;

};


MainMenuItem.prototype.drawSubmenu = function () {

    this.submenuBox = document.createElement('div');
    this.submenuBox.style.position = 'absolute';
    this.submenuBox.style.top = (this.placeholder.offsetTop + this.link.offsetHeight).toString() + 'px';
    this.submenuBox.style.left = (this.placeholder.offsetLeft + this.margin - 27).toString() + 'px';
    this.submenuBox.style.backgroundImage = 'url(' + this.menu.imagePath + '/submenu_bg.png)';
    this.submenuBox.style.zIndex = '50';
    this.submenuBox.style.padding = '10px 0px 0px 0px';
    this.submenuBox.style.borderTopRightRadius = '6px';
    this.submenuBox.style.borderBottomLeftRadius = '6px';
    this.submenuBox.style.borderBottomRightRadius = '6px';
    this.submenuBox.style.borderBottom = '1px solid silver';
    this.submenuBox.style.borderLeft = '1px solid #eee';
    this.submenuBox.style.borderRight = '1px solid #eee';
    this.submenuBox.onmouseover = createMethodReference(this, this.mouseOverSubmenu);
    this.submenuBox.onmouseout = createMethodReference(this, this.mouseOutSubmenu);

    var n = k = this.menuItem.length;

    do {
        var i = k - n;

        this.submenuBox.appendChild(this.menuItem[i].box);

    } while (--n);

};


MainMenuItem.prototype.removeSubmenu = function () {

    this.menu.placeholder.removeChild(this.submenuBox);

    this.submenuBox = null;

    this.submenuShowing = false;

};


MainMenuItem.prototype.containsDOM = function (container, containee) {

    var isParent = false;

    do {
        if ((isParent = container == containee)) break;
        containee = containee.parentNode;
    } while (containee != null);

    return isParent;

};


MainMenuItem.prototype.checkMouseEnter = function (element, e) {

    if (!e) var e = window.event;

    if (element.contains && e.fromElement) {
        return !element.contains(e.fromElement);
    } else if (e.relatedTarget) {
        return !this.containsDOM(element, e.relatedTarget);
    };

};


MainMenuItem.prototype.checkMouseLeave = function (element, e) {

    if (!e) var e = window.event;

    if (element.contains && e.toElement) {
        return !element.contains(e.toElement);
    } else if (e.relatedTarget) {
        return !this.containsDOM(element, e.relatedTarget);
    };

};



// =================================
// GoogleMap
// =================================

function GoogleMap(sPlaceholderId, sAddress, sMarkerUrl) {

    this.address = sAddress;
    this.markerUrl = sMarkerUrl;
    this.zoom = 8;
    this.placeholderId = sPlaceholderId;

    this.init();

};


GoogleMap.prototype.init = function () {

    var myOptions = {
        zoom: this.zoom,
        disableDefaultUI: true,
        navigationControl: true,
        navigationControlOptions: {
            style: google.maps.NavigationControlStyle.DEFAULT
        },
        mapTypeControl: true,
        mapTypeControlOptions: {
            style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
        },
        streetViewControl: false,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    var map = new google.maps.Map(document.getElementById(this.placeholderId), myOptions);
    var geoCoder = new google.maps.Geocoder();

    geoCoder.geocode({ 'address': this.address }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {

            map.setCenter(results[0].geometry.location);

            var image = new google.maps.MarkerImage('http://www.tekwerk.be/images/layout/googlemaps_marker.png',
                new google.maps.Size(70, 98),
                new google.maps.Point(0, 0),
                new google.maps.Point(19, 49));

            var marker = new google.maps.Marker({
                map: map,
                position: results[0].geometry.location,
                icon: image
            });

        } else {

            Debug('Geocode was not successful for the following reason: ' + status);

        };
    });

};



// ==========================
// Overig
// ==========================

function writeEmail(sDomain, sAlias, sDisplayText) {

    if (!sDomain)
        sDomain = 'tekwerk.nl';

    sEmail = sAlias + '\u0040' + sDomain;

    if (!sDisplayText)
        sDisplayText = sEmail;

    document.write('<a title="' + sEmail + '" href="mailto:' + sAlias + '\u0040' + sDomain + '">' + sDisplayText + '</a>');

};


function setCookie(name, value, expire) {
    document.cookie = name + "=" + escape(value) + ((expire == null) ? "" : ("; expires=" + expire.toUTCString()));
};


function getCookie(Name) {
    var search = Name + "=";
    if (document.cookie.length > 0) {
        // if there are any cookies 
        offset = document.cookie.indexOf(search);
        if (offset != -1) {
            // if cookie exists 
            offset += search.length;
            // set index of beginning of value
            end = document.cookie.indexOf(";", offset);
            // set index of end of cookie value
            if (end == -1) end = document.cookie.length;
            return unescape(document.cookie.substring(offset, end));
        } else {
            return '';
        };
    };
};


function createMethodReference(object, method) {

    if (!(method instanceof Function))
        method = object[method];

    return function () {
        method.apply(object, arguments);
    };

};


function Debug(sLine) {

    console.log(sLine);

};



