/******************************************************
 Handles all layout stuff for Keukenhaven website
 
 Be sure to call prepareAnimations() first !!
******************************************************/

// The root URL of the website
// var root_url = "http://www.keukenhaven.nl/w/

// Should contain the menus defined in index.html
var menus = ["menu_overons", "menu_keukens", "menu_sanitair", "menu_kastenwanden"];

// Contains the animationlocks
var animationLock = new Array();

// In which menu is the cursor, or false if in none
var cursor_in_menu = false;

// Adapts the layout to the window size
function adaptToWindowSize()
{
    // Put all forms in center and hide them
    $$('div.form').each(function(item){
            centerAlign(item);
            item.setStyle('top', item.getParent().getSize().y / 2 - (item.getSize().y / 2));
    });
    

    $("curtain").setStyle('width', window.getSize().x); 
    
    centerAlign($('content'));
    centerAlign($('topbar'));
    centerAlign($('infobar'));
    
    // Element::getParent() gives trouble in Internet Explorer 6
    $("infobar").setStyle('top', Math.max(window.getSize().y - $("infobar").getSize().y - 5, 675));
    
    centerAlign($('buttonbar'));
    $("buttonbar").setStyle('top', $("infobar").getPosition().y - $("buttonbar").getSize().y - 10);
    

    centerAlign($('breadcrumbs'));
    //centerAlign($('greylinks'));
    centerAlign($('picture'));


    $("picture").setStyle('top', $("topbar").getPosition().y + $("topbar").getSize().y + 15);
    $("picture").setStyle('height', $("buttonbar").getPosition().y - 15 -  $("picture").getPosition().y);
    //$("smallcurtain").setStyle('top', $("topbar").getPosition().y + $("topbar").getSize().y + 10);
    //$("smallcurtain").setStyle('height', $("buttonbar").getPosition().y - 15 -  $("picture").getPosition().y);
    //$("smallcurtain").setStyle('left', $("picture").getStyle('left'));
    //$("smallcurtain").setStyle('width', $("picture").getStyle('width'));    


    $('left_of_content').setStyle('left', 0);
    $('left_of_content').setStyle('width', Math.max(0, $('content').getPosition().x));
    $('left_of_content').setStyle('height', Math.max($("infobar").getPosition().y + $("infobar").getSize().y, $("content").getSize().y))

    $('right_of_content').setStyle('left', $('content').getPosition().x + $('content').getSize().x);
    $('right_of_content').setStyle('right', 0);
    $('right_of_content').setStyle('height', Math.max($("infobar").getPosition().y + $("infobar").getSize().y, $("content").getSize().y))
    
    centerAlign($('messagedialog'));
    $('messagedialog').setStyle('top', $('messagedialog').getParent().getSize().y / 2 - ($('messagedialog').getSize().y / 2));
    
    $('external').setStyle('width', window.getSize().x - 40);
    $('external').setStyle('height', window.getSize().y - 40);
    $('external_iframe').setStyle('height', $('external').getSize().y - $('external_titlebar').getSize().y - 12);
    $('external_iframe').setStyle('width', $('external').getSize().x - 12);
    

    // y-coordinates for menus    
    menus.each(function(item, index, array) {
        // Element.dimensions() gives trouble in IE, so that's why this work around is required
        $(item).setStyle('display', 'block');
        $(item).setStyle('top', 10 - $(item).getSize().y);
        $(item).setStyle('display', 'none');
    });
        
}

// Capitalize first letter of each word
function capitalize(str) {
        newStr = '';
        str = str.split(' ');
        for(var c=0; c < str.length; c++)
                newStr += str[c].substring(0,1).toUpperCase() + str[c].substring(1,str[c].length) + ' ';
        return newStr;
}
        

// Clears all menu timeouts
function clearMenuTimeouts()
{
    menusTimeout.each(function(item) {
            clearTimeout(item);     
    });
}

function closeExternal()
{
    $('external_iframe').setProperty('src', 'loading_external.htm');
    $('curtain').fade(0);
    $('external').fade(0);
}

// Creates a new Fx object for the passed div. whichLock is the name of the lock the animation
// should obey to. Type is the type of Fx. Options is passed to Fx constructor
// Valid args for type: Tween, Reveal
function createFx(type, whichLock, element, options)
{
    if (type == "Tween")
        fx = new Fx.Tween(element, options);
    if (type == "Reveal")
        fx = new Fx.Reveal(element, options);
    fx.addEvent("start", function(){
        if (animationLock[whichLock]) fx.cancel();
        else {
            // Animation locks should expire after a few seconds, because sometimes animations hang
            uid = new Date().getTime();
            animationLock[whichLock] = uid;
            setTimeout('if (animationLock["'+whichLock+'"] == '+uid+') animationLock["'+whichLock+'"] = false', 3000);
        }
    });
    fx.addEvent("complete", function(){animationLock[whichLock] = false;});
    return fx;
}

// Hides a menu
function dissolveMenu(menuName)
{  
    menusReveal[menuName].dissolve();
}

function genBreadcrumbs(contentName)
{
    var toreturn = '<a href="content/home.htm" class="breadcrumb" onclick="menuClick(\'home\');return false">Home</a>';
    
    if (contentName != 'home'){
        splitted_content = contentName.replace(/-/g, " ").split('_');
        if (splitted_content[0] == "over ons") {
            var link0 = "over-ons"; 
            var link1 = "welkom"; 
        } else {
            var link0 = splitted_content[0];
            var link1 = 'over-'+splitted_content[0];
        }
        toreturn += ' &gt; <a class="breadcrumb" href="content/'+link0+'_'+link1+'.htm" onclick="menuClick(\''+link0+'_'+link1+'\');return false">' + capitalize(splitted_content[0]) + '</a>';
        toreturn += ' &gt; <a class="breadcrumb" href="content/'+contentName+'.htm" onclick="menuClick(\''+contentName+'\');return false">' + capitalize(splitted_content[1]) + '</a>';
    }
    
    return toreturn;
}

// Hides current content and calls fn with args after that
function hideCurrentContent(fn, args)
{
    var innerContentDivTween = createFx("Tween", "photo_and_content",  $("inner_content_div"), {"duration": "normal","link":"chain"});
    if (fn != null) {
        var func = 
        innerContentDivTween.addEvent("complete", function() {fn.apply(this, args);});
    }
    innerContentDivTween.start('opacity', 0.9, 0);
}

// Prepares all layout work
function init(content)
{
    processLinks();
    
    // For revealing/dissolving the left menus
    menusReveal = new Array();
    for (menu in menus) {
        menusReveal[menus[menu]] = createFx("Reveal", "menu", $(menus[menu]), {"duration":"normal", "link":"chain"});
    }
    menusTimeout = new Array();
    
    $("curtain").fade("hide");
    
    $$(".dialog").each(function(item){
            item.setStyle('opacity', 0);
            item.setStyle('visiblity', 'hidden');
    })
    
    menus.each(function(item){$(item).setStyle('display', 'none')})
    
    // Register history stuff
    HM = new HistoryManager();
   
   HM.addEvent('content-changed',function(new_value){
           // Tell google analytics what we loaded
           if (enable_stats) _gaq.push(['_trackPageview', new_value])
           switchToContent(new_value);
   });
   HM.addEvent('dialog-changed',function(new_value){
           if (new_value == "none") {
               $('curtain').fade(0);
               $$('.dialog').each(function(item){
                       if (item.getStyle('opacity') > 0) item.fade(0);
               })
           } else if (new_value.substring(0, 5) == "form_"){
               // Tell google analytics what we loaded
               if (enable_stats) _gaq.push(['_trackPageview', new_value])
               $('curtain').fade(0.5);
               $(new_value).fade(0.9);      
           } else if (new_value == "messagedialog"){
               $('curtain').fade(0.5);
               $(new_value).fade(0.9);      
           } else {
               $('curtain').fade(0.5);
               $(new_value).fade(1);      
           }
   });
   

   HM.start();
   HM.set('content','home'); 
   HM.set('dialog', 'none');
   location.hash = '#{"content":"home","dialog":"none"}';
    
    // Show initial content
    $('picture').setStyle('opacity', 0);
    loadedContent = "";
     adaptToWindowSize();
    if (location.hash == "") HM.set('content','home'); 
    
}

function processLinks()
{
    // Remove href property of external
    $$('.external').each(function(item){
            if (Browser.Engine.trident){
               item.removeProperty('onclick');
               item.setProperty('target', '_blank');
            }
    })
}

// Determines whether at least two menus are visible
function nrMenusVisible()
{   
    var count = 0;
    menus.each(function(item){
            if (($(item).getStyle('opacity') == 1) && ($(item).getStyle('display') == 'block')) count = count + 1;
    });
    return count;
}

// Show the digitale showroom in exetrnal window
function showDigitaleShowroom()
{
    showExternal('Digitale Showroom', 'http://www.keukenhaven.nl/ds/index.php?width='+String($('external').getSize().x-12)+'&height='+String($('external').getSize().y-40));
}

function showExternal(title, url)
{
    $('external_titlebar').set('html', title);
    $('external_iframe').setProperty('src', url);
    showDialog('external');
}

// Moves an element to a position relative to its parent element. The element has to be absolute positioned
// Allowed values:
// x : left - center - right
// y : top - center - bottom
// offset : nr pixels to stay away from border
function positionElement(element, y, x, offset)
{
    var parent = $("picture");
    alert(parent);
    $(element).setStyle('position', 'absolute');
    alert(element);
    alert(x);
    alert(y);
    if (x == "left") $(element).setStyle('left', parent.getPosition().x + offset);
    if (x == "center") $(element).setStyle('left', parent.getPosition().x + parent.getSize().x / 2 - ($(element).getSize().x / 2) + offset);
    if (x == "right") $(element).setStyle('left', parent.getSize().x - $(element).getSize().x - offset);
    if (y == "top") $(element).setStyle('top', parent.getPosition().y + offset);
    if (y == "center") $(element).setStyle('top', parent.getPosition().y + parent.getSize().y / 2 - ($(element).getSize().y / 2) + offset);
    if (y == "bottom") $(element).setStyle('top', parent.getSize().y - $(element).getSize().y - offset);     
}

// Loads a new random picture and after the fade in it executes function fn with args
// Optional accepts a keyword that should be atrtached to the picture
function newRandomPictureSync(functionName, arg, keyword)
{
    var pictureTween = createFx("Tween", "photo_and_content", $("picture"), {"duration":"long", "link":"chain"});
    
    if ($("picture").getStyle("opacity") !=0 ) 
    {
        var picture_temp = new Element('div', {
            'id': 'picture_temp',
            'class': 'picture',
            'styles': {
                'background-image': $('picture').getStyle('background-image'),
                'opacity': 0.9,
                'top': $('picture').getStyle('top'),
                'left': $('picture').getStyle('left'),
                'height': $('picture').getStyle('height'),
                'z-index': 0
            }
        });
        picture_temp.inject($('picture'), 'after');
        $("picture").setStyle("z-index", "8");
        $("picture").fade("hide");
    }
   var myRequest3 = new Request({
        'url':'../ds/g2interface.php?getrandomphotourl=1&fillwindow=true&albumname=Website%20Pictures&maxwidth=' + $('picture').getSize().x + '&maxheight=' + $('picture').getSize().y + '&keyword=' + keyword,
        'method': 'GET',
        'async': false,
        'noCache': true,
        'onSuccess': function(responseText, responseXML){                 
            $('picture').setStyle('backgroundImage', 'url("http://www.keukenhaven.nl/ds/'+responseText+'")');
            pictureTween.addEvent("complete", function(){  
                if ($("picture_temp") != null) {
                    var TempPictureTween = new Fx.Tween($("picture_temp"), {"duration":"short", "link":"chain"});
                    TempPictureTween.addEvent("complete", function(){$("picture_temp").destroy();});
                    TempPictureTween.start("opacity", 0);
                }
                setTimeout('' + functionName + "('"+ arg + "')",  400);
            });
            pictureTween.start("opacity", 0, .9);
        },
        'onFailure': function(xhr) {
        }
   }).send();
}

// Shows the messagedialog with a message
function message(title, message)
{
    $('messagedialog_title').set('text', title);
    if (message) $('messagedialog_message').set('text', message);
    showDialog('messagedialog');
}


function menuClick(contentName)
{
    // A menu click means a content switch. Code here should be moved to other sections. Still, if there is a content switch in progress we better do nothing at all
    //if (animationLock["photo_and_content"]) return;
    
    // Hide all menus and show content
    clearMenuTimeouts();
    menus.each(function(item){
            dissolveMenu(item);
    });
    HM.set('content', contentName);
}

function overMenu(menuName)
{
    clearTimeout(menusTimeout[menuName]);
}

// Event: enter button
function overMenuButton(menuName)
{
    cursor_in_menu = menuName;
    
    // Show menu
    clearTimeout(menusTimeout[menuName]);
    revealMenu(menuName);
    
    // If menu is not visible in half a sec we try again
    setTimeout('if (($("'+menuName+'").getStyle("display") == "none") && (cursor_in_menu == "'+menuName+'")) overMenuButton("'+menuName+'")', 500);
}

function outMenu(menuName)
{
    menusTimeout[menuName] = setTimeout("dissolveMenu('"+menuName+"')", 250);
}

// If the mouse leaves a button, we set a timeout to remove the menu. The user must get to the menu fast!
function outMenuButton(menuName)
{
    cursor_in_menu = false;

    menusTimeout[menuName] = setTimeout("dissolveMenu('"+menuName+"')", 250);
}

// Places a element excactly in the center of its parent element concerning the x-dimension
function centerAlign(element)
{
    element.setStyle('left', element.getParent().getSize().x / 2 - element.getSize().x / 2); 
}

// Reveals a menu
function revealMenu(menuName)
{
    // Reveal if not visible
    if($(menuName).getStyle('display') != 'block')
        menusReveal[menuName].reveal();
}

// Shows content having the name contentName
// This is equal to the menu name concatenated with the a mark and submenuname without spaces
function showContent(contentName){
    var myHTMLRequest = new Request.HTML({
           'url': 'http://www.keukenhaven.nl/w/content/' + contentName + '.php',
           'method': 'GET',
           'onSuccess': function(responseTree, responseElements, responseHTML, responseJavaScript){
               responseElements.each(function(item){
                       if (item.getProperty('id') == "inner_content_div_for_iframe") {
/*                           
                           // For everyone except IE
                           var newinner = $("inner_content_div").innerHTML = item.innerHTML.replace(/src="..\//g, 'src="').replace(/href="..\//g, 'href="');

                           // IE
                           newinner = newinner.replace(/src="http:\/\/www.keukenhaven.nl\//g, 'src="http://www.keukenhaven.nl/w/').replace(/href="http:\/\/www.keukenhaven.nl\//g, 'href="http://www.keukenhaven.nl/w/');
                           newinner = newinner.replace(/src="http:\/\/keukenhaven.nl\//g, 'src="http://www.keukenhaven.nl/w/').replace(/href="http:\/\/keukenhaven.nl\//g, 'href="http://www.keukenhaven.nl/w/');
 */                         
                           $("inner_content_div").innerHTML = item.innerHTML;
                           
                           $("breadcrumbs").innerHTML = genBreadcrumbs(contentName);
                           
                           // Let's hide all divs of gebruik_en_onderhoud. Will only do something on the relevant page
                           $$('.gebruik_en_onderhoud').setStyle('display', 'none');
                           
                            // Remove href property of links
                           processLinks();
                           adaptToWindowSize();
                       }
               });
               var innerContentDivTween = createFx("Tween", "photo_and_content",  $("inner_content_div"), {"duration": "normal","link":"chain"});
               innerContentDivTween.start("opacity", 0, 0.9);
           }
   }).send();
   loadedContent = contentName;
}

// Hides the dialog: element
function hideDialog(element){
    $('body').setStyle('overflow', 'auto');
    HM.set('dialog', 'none');
}

// Shows the dialog: element
function showDialog(element){
    window.scrollTo(0,0);
    $('body').setStyle('overflow', 'hidden');
    HM.set('dialog', element);
}

// Uses showContent() to show a new content, but first hides the current content and replaces the
// background picture
function switchToContent(contentName)
{    
    // Determine keyword of the photo that should be at the back
    var keyword = contentName.substring(0, contentName.indexOf("_"))
    if (keyword == "over-ons") keyword = "keuken";
    else if (keyword == "keukens") keyword = "keuken";
    else if (keyword == "kastenwanden") keyword = "schuifdeurkast";
    else if (keyword == "sanitair") keyword = "sanitair";
    else keyword = "";
    
    if (loadedContent != "") {
        hideCurrentContent(newRandomPictureSync, ["showContent", contentName, keyword]);
    } else {
        newRandomPictureSync('showContent', contentName, keyword);
    }
}

/*--------------------------------------------------------------
 Dit is om content in te voegen van Gebruik en Onderhoud
 -------------------------------------------------------------*/

function setGOContent(which)
{
    $$('.gebruik_en_onderhoud').setStyle('display', 'none');
    $(which).setStyle('display', 'block');
}

 
 

