var SIDEBAR_WIDTH = 320;
var SIDEBAR_WIDTH_COLLAPSED = 30;

var fpMargins = {
    'left': 0,
    'right': 0,
    'top': 0,
    'bottom': 0
};
var fpDimensions = {
    'width': 0,
    'height': 0
};
var fShowSidebar = true;


// Register Floorplanner event handlers
function setEventHandlers() {
    fp.observe('LOADED', displayProjectInfo);
    fp.observe('CHANGED_PROJECT', displayProjectInfo);
    fp.observe('FINISHED', displayDesignInfo);
    fp.observe('LOAD_ERROR', displayLoadError);
    fp.observe('ADDED_OBJECT',
    function(pElement) {
        updateFurnitureElementCount(pElement, 1);
    });
    fp.observe('REMOVED_OBJECT',
    function(pElement) {
        updateFurnitureElementCount(pElement, -1);
    });
    fp.observe('SHOW_SIDEBAR', openSidebar);
    if (Floorplanner.Sidebar) {
        fp.observe("FINISHED", function() {
            setSizes();
            Floorplanner.Sidebar.afterLoad();
        });
    }
}

var fSidebarPosition = "right";

// on resize
Event.observe(window, "resize", setSizes);

// Resizing
Event.observe(window, "load",
function() {
    try {
        fpMargins.top = $('top').getHeight();
    } catch(e) {
        fpMargins.top = fpMargins.top || 0;
    }
    try {
        fpMargins.top += $('control').getHeight();
    } catch(e) {}
    try {
        fpMargins.bottom = ($('bottom')) ? 30: 0;
    } catch(e) {
        fpMargins.bottom = 0;
    }

    if (fSidebarPosition == "left") {
        try {
            fpMargins.left = $('sidebar').getWidth();
        } catch(e) {
            fpMargins.left = 0;
        }
    } else {
        try {
            fpMargins.right = $('sidebar').getWidth();
        } catch(e) {
            fpMargins.right = 0;
        }
    }


    try {
        fShowSidebar = $('sidebar').visible();
    } catch(e) {
        fShowSidebar = false;
    }
    if ($('bottom')) $('bottom').show();

    if (!Floorplanner.Sidebar) {
        setSizes();
    }
});

var fResizeTime = 0;

function setSizes() {
    // IE6 hack
    lCurrentTime = (new Date()).getTime();
    if (lCurrentTime - fResizeTime < 5) return;
    fResizeTime = lCurrentTime;


    if ($('sidebar')) {
        if (fSidebarPosition == "left") {
            $('sidebar').setStyle({
                left: '0px'
            })
            try {
                $('background').setStyle({
                    left: '320px',
                    right: '0px'
                })
            } catch(e) {}
            $('sidebar-collapsed').setStyle({
                float: 'left'
            });
            $('collapse-button-open').update("&laquo;");
            $('sidebar-collapsed').update("&raquo;");

            fpMargins.left = fShowSidebar ? SIDEBAR_WIDTH: SIDEBAR_WIDTH_COLLAPSED;

            try {
                $('control-floors').setStyle({
                    'position': 'absolute',
                    'margin': '0px 0px 0px ' + (fpMargins.left + 120) + 'px'
                });
            } catch(e) {}


        } else {
            fpMargins.right = fShowSidebar ? SIDEBAR_WIDTH: SIDEBAR_WIDTH_COLLAPSED;
        }

        fpDimensions.width = document.viewport.getWidth() - (fpMargins.left + fpMargins.right);
        fpDimensions.height = document.viewport.getHeight() - (fpMargins.top + fpMargins.bottom);
    } else {
        fpMargins.right = 0;
        fpDimensions.width = document.viewport.getWidth() - (fpMargins.left);
        fpDimensions.height = document.viewport.getHeight() - (fpMargins.top);
    }

    // set the main div
    if ($('fpcanvas')) {
        $('fpcanvas').setStyle({
            left: fpMargins.left + 'px',
            right: fpMargins.right + 'px',
            height: fpDimensions.height + 'px'
        });
        $('fpcanvas').show();
    }



    if ($('background')) {
        $('background').setStyle({
            left: fpMargins.left + 'px',
            right: fpMargins.right + 'px',
            height: fpDimensions.height + 'px',
            top: fpMargins.top + 'px'
        });
       
        $('background').show();
    }

    if ($('bottom')) {
        $('bottom').setStyle({
            top: (document.viewport.getHeight() - fpMargins.bottom) + 'px',
            width: fpDimensions.width + 'px',
            bottom: '0px'
        });
        if (fSidebarPosition == "left") {

            $('bottom').setStyle({
                'left': fpMargins.left + 'px'
            });
        }
    }

    if ($('sidebar')) {
        var lHeight = document.viewport.getHeight() - parseInt($('sidebar').getStyle("top"));
        if (lHeight > $('sidebar').getHeight()) {
            $('sidebar').setStyle({
                height: lHeight + 'px'
            });
        }
    }
}




function getFPDimensions() {
    return fpDimensions;
}

function getFPPositions() {
    return {
        'left': fpMargins.left,
        'right': fpDimensions.width + fpMargins.left,
        'top': fpMargins.top,
        'bottom': fpDimensions.height + fpMargins.top
    };
}

function getFPMargins() {
    return fpMargins;
}

function openSidebar(pOptions) {
    var lDuration = 0.3;
    if (pOptions && pOptions.duration != undefined) {
        lDuration = pOptions.duration;
    }

    if (!fShowSidebar) {
        toggleSidebar({
            'afterFinish': function() {
                fp.zoomAll();
            }
        });

    }
}

function toggleSidebar(pOptions) {
    var lDuration = 0.3;
    if (pOptions && pOptions.duration != undefined) {
        lDuration = pOptions.duration;
    }

    var lCallback = function() {}
    
    if (pOptions && pOptions.afterFinish) {
        lCallback = pOptions.afterFinish;
    }

    fShowSidebar = !fShowSidebar;
    if (fShowSidebar) {
        $('sidebar-collapsed').toggle();
        new Effect.SlideUp('sidebar', {
            scaleX: true,
            scaleY: false,
            scaleFrom: 0,
            scaleTo: 100,
            duration: lDuration,
            afterFinish: function() {
                lCallback.call();
                $('sidebar').show();
            }
        });
        setSizes();
    } else {
        new Effect.SlideUp('sidebar', {
            scaleX: true,
            scaleY: false,
            scaleFrom: 100,
            scaleMode: 'contents',
            scaleTo: 0,
            duration: lDuration,
            afterFinish: function() {
                lCallback.call();
                setSizes();
                $('sidebar-collapsed').toggle();
                $('sidebar').hide();
            }
        });
    }
}

function displayLoadError() {
    window.loadingErrorOccured = true;
    $('control').update('');
    if ($('design-loading')) {
        $('design-loading').update('<h2>Design loading error: please inform us!</h2>');
    }
}


function clearShapelist() {
    $('element-list').innerHTML = '';
}

function displayDesignInfo(pObject) {
    if ($('bottom') && !window.loadingErrorOccured) {
        if ($('design-loading')) $('design-loading').hide();
        if ($('project-right-content')) $('project-right-content').show();
        if ($('project-left-content')) $('project-left-content').show();

        clearShapelist();
        lShapes = fp.getShapes(true);
        for (var i = 0; i < lShapes.length; i++) {
            // renderShape(lShapes[i]);
            for (var j = 0; j < lShapes[i]['elements'].length; j++) {
                lElement = lShapes[i]['elements'][j];
                var lElementItem = $('element-' + lElement.id);
                if (lElementItem) {
                    updateFurnitureElementCount(lElement, 1);
                    // Add 1 to the count
                } else {
                    renderFurnitureElement(lElement);
                }
            }
        }
    }
}

function setLoading() {
    if ($('design-info')) $('design-info').hide();
    if ($('design-loading')) $('design-loading').show();
}

function removeShape(pShape) {
    new Effect.Fade('shape-' + pShape.hash);
}

function renderShape(pShape) {
    if (pShape.hash) {
        // TODO: measurement system opvragen!
        var lShapeItem = new Element('li', {
            id: 'shape-' + pShape.hash
        });
        //var lShapePreview = new Element('div', {id: 'shape-' + pShape.hash + '-preview'});
        //lShapeItem.appendChild(lShapePreview);
        lShapeItem.update(pShape.articleName + ' (' + pShape.area.toFixed(0) + ' m&sup2;)');
        $('shape-list').appendChild(lShapeItem);
        //fp.previewElement(lShapePreview.id, pShape.textureUrl, '60', '60', {});
    }
}


function renderFurnitureElement(pElement) {
    var lGoogleLink = 'http://www.google.com/custom?hl=en&client=pub-2942593231206351&cof=FORID:1%3BAH:left%3BS:' +
    'http://www.floorplanner.com%3BCX:Floorplanner%3BL:http://www.floorplanner.nl/assets/FPlogo50.jpg' +
    '%3BLH:50%3BLP:1%3BVLC:%23663399%3BGALT:%23339933%3BDIV:%23336699%3B&adkw=' +
    'AELymgUM9slbnHw7BUxv3wbFyt6n66rzILT85ePsORzemu8tV7CMmo3nK5TXV5EMRMIUVn_JMaaMZ_GqvM' +
    'dXmiSqa0IH9_9vdqzlSVTd5e10xVNznzExN2QEPoFEUiMvnP59RZw2j33rlJlVWx1XZddltjj0mpByOg&cx=008247364682492430695:' +
    'zfzponsmplc&sa=N&oi=coopctx&resnum=0&ct=col1&cd=1&q=' + encodeURIComponent(pElement.name);

    var lArticle = (window.getArticleById) ? getArticleById(pElement.id) : null;

    // Do not display anything if articles are available but this element is not one opf the articles.
    if (window.getArticleById && !lArticle) return;

    var lEnableFlashPreview = false;

    if (lArticle && lArticle.articlePhotoUrl) {
        var lElementItemPreview = new Element('img', {
            src: lArticle.articlePhotoUrl,
            height: 60,
            width: 60,
            alt: pElement.articleName
        });
        lElementItemPreview.setStyle({
            'float': 'left',
            id: 'element-' + lArticle.id + '-preview',
            position: 'relative',
            top: '-10px',
            marginRight: '20px'
        });
    } else {
        var lElementItemPreview = new Element('div', {
            id: 'element-' + pElement.id + '-preview'
        });
        lEnableFlashPreview = true;
    }

    var lElementItem = new Element('li', {
        id: 'element-' + pElement.id
    }).update(lElementItemPreview);

    var lElementName = new Element('div', {
        'class': 'element-name'
    });

    if (lArticle) {
        if (lArticle.articleSourceUrl) {
            lElementName.update(new Element('a', {
                'target': '_blank',
                'href': lArticle.articleSourceUrl,
                'class': 'element-name'
            }).update(pElement.articleName));
        } else {
            lElementName.update(pElement.articleName);
        }
    } else {
        lElementName.update(pElement.name);
    }

    lElementName.insert(new Element('span', {
        id: 'element-' + pElement.id + '-count',
        'class': 'element-count'
    }));
    lElementItem.insert(lElementName);

    if (lArticle && pElement.articleDescription && pElement.articleDescription != "null") {
        var lDescription = new Element('p', {
            'class': 'description'
        }).update(pElement.articleDescription);
        lElementItem.insert(lDescription);
    }

    if (!window.getArticleById) {
        var lSearches = new Element('div', {
            'class': 'searches'
        });
        lSearches.insert(new Element('a', {
            href: lGoogleLink + "+more:products",
            target: 'blank'
        }).update('Similar products'));
        lSearches.insert('&nbsp;|&nbsp;');
        lSearches.insert(new Element('a', {
            href: lGoogleLink + "+more:tips_ideas",
            target: 'blank'
        }).update('Tips &amp; ideas'));
        lElementItem.insert(lSearches);
    }

    if (lArticle && lArticle.articlePrice) {
        var lPriceString = lArticle.articleCurrency + ' ' + parseFloat(lArticle.articlePrice).toFixed(2)
        lElementItem.insert(new Element('div', {
            'class': 'element-price'
        }).update(lPriceString));
    }

    lElementItem.insert(new Element('div').setStyle({
        'clear': 'left'
    }));
    $('element-list').insert(lElementItem);

    if (lEnableFlashPreview) {
        fp.previewElement(lElementItemPreview.id, pElement.url, '60', '60', {
            style: 'position: relative; top: -10px; float: left; margin-right: 20px;'
        });
    }

}



function updateFurnitureElementCount(pElement, pChange) {

    var lCountSpan = $('element-' + pElement.id + '-count');
    if (lCountSpan && lCountSpan.visible()) {
        if (lCountSpan.innerHTML == '') {
            var lElementCount = 1;
        } else {
            var lElementCount = parseInt(lCountSpan.innerHTML.match(/\((\d+)\)/)[1]);
        }

        lElementCount += pChange;

        if (lElementCount == 1) {
            lCountSpan.innerHTML = '';
        } else if (lElementCount == 0) {
            removeFurnitureElement(pElement);
        } else {
            lCountSpan.update('&nbsp;(' + lElementCount + ')');
        }
    } else {
        renderFurnitureElement(pElement);
    }

}


function removeFurnitureElement(pElement) {
    new Effect.Fade('element-' + pElement.id, {
        duration: 0.5,
        afterFinish: function() {
            $('element-list').removeChild($('element-' + pElement.id));
        }
    });
}

function setMeasurementSystem(pMeasurementSystem) {
    fp.setMeasurementSystem(pMeasurementSystem);
    displayMeasurementSystem(pMeasurementSystem);
    saveMesaurementSystem(pMeasurementSystem);
    return false;
}

function saveMesaurementSystem(pMeasurementSystem) {
    if (fp.getCurrentUserId() != null) {
        new Ajax.Request('/account/update', {
            method: 'POST',
            parameters: 'user[measurement_system]=' + pMeasurementSystem.toUpperCase()
        });
    }
}

function displayMeasurementSystem(pCurrentMS) {
    var lOtherMS = (pCurrentMS == 'imperial') ? 'metric': 'imperial';

    $('measurementsystem-' + pCurrentMS).addClassName('active');
    if ($('measurementsystem-' + lOtherMS).hasClassName('active'))
    $('measurementsystem-' + lOtherMS).removeClassName('active');
}

/**
   * Displays the information about the project and its floors on the current page.
   */
function displayProjectInfo(pObject) {

    $('control-loading').style.display = 'none';
    $('control-content').style.display = 'block';


    var lProject = fp.getProject();

    // Show floors in control-bar
    if (!fp.isEmptyProject() && $('control-floors')) {
        $('control-floors').innerHTML = '';
        lProject.floors.each(function(lFloor) {

            var floorNameLength = 17;
            var floorNameOriginal = lFloor.name;
            var floorName = floorNameOriginal;

            // truncate the floor name
            if (floorNameOriginal.length > floorNameLength) {
                floorName = floorName.substring(0, floorNameLength) + '...';
            }

            var lFloorElement = new Element('a');

						// don't display the arrow if the floor has just 1 design
						// and we're NOT in 'edit' mode
						
						if (lFloor.designs.length == 1 && fp.getState() != 'edit') {
							lFloorElement.update(floorName);
						}							
						else {
							lFloorElement.update(floorName + ' <small>&#9660;</small>');
						}
						
            lFloorElement.title = floorNameOriginal;

            Event.observe(lFloorElement, 'mouseover',
            function() {
                if (fp.getCurrentView() == "2d") {
                    //var lOffset = fShowSidebar ? fpMargins.left : 0;
                    var lOffsetParent = parseInt(this.parentNode.parentNode.parentNode.style.marginLeft);
                    if (!lOffsetParent)
                    lOffsetParent = 0;

                    var lPos = this.parentNode.parentNode.offsetLeft + lOffsetParent - fpMargins.left;

                    fp.showForm('SELECT_DESIGN', {
                        floorId: lFloor.id,
                        xPos: lPos
                    });
                }
                return false;
            });

            Event.observe(lFloorElement, 'mouseout',
            function() {
                //$('floors_' + lFloor.id).removeClassName('over');
                });

            Event.observe(lFloorElement, 'click',
            function() {
                if (fp.fCurrentView == "2d") {
                    fp.loadFloor(lFloor.id);
                } else {
                    fp.ensure2d();
                    var lOffset = fShowSidebar ? fpMargins.left: 0;
                    fp.showForm('SELECT_DESIGN', {
                        floorId: lFloor.id,
                        xPos: Element.positionedOffset(this.parentNode)[0] + lOffset
                    });
                }
                return false;
            });


            var lListItem = new Element('li', {
                'class': 'floor',
                'id': 'floors_' + lFloor.id
            });
            if (lFloor.active) {
                Element.addClassName(lListItem, 'current');
            }
            else {
                Element.addClassName(lListItem, 'dotted');
            }
            /*  border-left: 1px dashed #ccc;
                    border-right: 1px dashed #ccc;*/

            var lTextElement = new Element('div', {
                'class': 'text'
            });
            lTextElement.appendChild(lFloorElement);
            var lOverlayElement = new Element('div', {
                'class': 'overlay'
            });

            lListItem.appendChild(lTextElement);
            lListItem.appendChild(lOverlayElement);

            // set the width of the floor list item
            if (floorNameOriginal.length > 15) {
                /*
                                        lListItem.style.width       = '200px';
                    lTextElement.style.width    = '200px';
                    lOverlayElement.style.width = '200px';
                                        */
            }

            $('control-floors').appendChild(lListItem);
        });
    }

    if ($('control-measurementsystem')) $('control-measurementsystem').show();
    displayMeasurementSystem(fp.getMeasurementSystem());

    // hack for Firefox, else sizes will be calculated without scrollbar
    setSizes();
}


