var oldhash;
var ready = true;

var datas = new Object();
datas.Slogan = new Object();

var browserName=navigator.appName;

if (browserName!="Microsoft Internet Explorer")
{
    window.addEventListener("hashchange", chromeCheck, false);
}
function chromeCheck(hashh)
{
        if(hashh.newURL != undefined)
            {
              var len = hashh.newURL.indexOf("#");
              hashh = (hashh.newURL.substr(len + 1, hashh.newURL.length));

              if(len == -1)
                  {
                  window.location = window.location.href;
                  }
                  
                  var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
                  if(is_chrome)
                      {
                          load(hashh);
                      }
            //
            }
}
function load(hashh)
{
        
            
      
        
        
    
    hashh = unescape(hashh);
    hash = generateHash(hashh.split('/'));
    var url, slug, data;

    if (oldhash != hashh)
    {
         $("#werkwijzeslider").remove();

        oldhash = hashh;

        if(hash.project == "projecten")
        {
            //url = '/ajax/getprojectbanner';
            url = '/index.php/ajax/getcategorybanner';
            slug = hash.category;
            data = $.evalJSON(getData(url, slug));
            var list = generateProjectList(data.Projects, data.projecten, data.slug)
            SliderToggle(slug + "project", 250, getCategoryContent(slug + "project", list , null , hash.base, hash.category));
            loadPhotos(data);
            currentPhotoIndex = 0;
            if(data.Images.length < 2)
            {
                switchCategoryPhoto(0);
            }
            else
            {
                switchCategoryPhoto(1);
            }
        }

        if(hash.project == "productinfo")
        {
            url = '/index.php/ajax/getcategorybanner';
            slug = hash.category;
            data = $.evalJSON(getData(url, slug));
            SliderToggle(slug, 250, getCategoryContent(slug, data.content, data.contentr, hash.base, hash.category));
            loadPhotos(data);
            currentPhotoIndex = 0;
            switchCategoryPhoto(0);
        //setCategorydata(jsondata);
        //nextPhoto();
        }

        if(hash.project != "productinfo" && hash.project != "projecten")
        {
            url = '/index.php/ajax/getprojectbanner';
            slug = hash.project;
            data = $.evalJSON(getData(url, slug));
            SliderToggle(slug, 32, getProjectContent(slug, data.title, hash.base, hash.category, hash.project, data));
            loadPhotos(data);
            currentPhotoIndex = 0;
            switchCategoryPhoto(0);
        }

        $("#menu li").each(function(){
            var href = $(this).html();
            $(this).css({"color" : "white"});
            $(this).css({"text-decoration" : "underline"});

            if (href == hash.project)
            {
                $(this).css({"color" : "#FF9933"});
                $(this).css({"text-decoration" : "none"});
            }
        });


        $(".prodmenu_item a").each(function()
        {
            var href = $(this).attr("href");
            href = href.split("/");
            href = href[href.length - 2];
             $(this).parent("li").attr("id", "non");
            if (href == hash.category)
            {
                $(".prodmenu_item").not(this).css({"background-image": "url(/images/projectenmenu_bg.png)"});
                $(".prodmenu_item a").not(this).css({"color" : "white"});

                $(this).parent("li").css({"background-image": "url(/images/projectenmenu_bg_hover.png)"});
                $(this).parent("li").attr("id", "actief");
                $(this).css({"color" : "black"});
            }

        });
        var pageTracker = _gat._getTracker("UA-8598570-1");
        pageTracker._trackPageview();
        pageTracker._trackEvent("pagina", "page", hashh);
    }
Cufon.refresh();
}

function generateProjectList(projects, data, category)
{
    var list = "";

    list += "<table width=700>";
    for(var i = 0; i < projects.length; i++)
    {
      if((i % 2 == 0 && i != 1) || i == 2)
      list += "<tr>";

    list += "<td>";

	     if(projects[i].Images.length < 1)
	     {
          list += projects[i].title + " (geen foto's) <br />";
	     }
	     else
	     {
          list += "<a onselectstart='return false;' onclick='loadPage(\"/parkeergarages/" + category + "/" + projects[i].slug + "\");' >"+projects[i].title + "</a><br />";
	     }
      list += "</td>";



      if((i % 2 == 1 && i != 0) || i == 1)
      list += "</tr>";

    }


    list += "</table>";



    return data + "<br /><br />" + list;
}

function prevPhoto()
{
	if(photos.length > 1)
{
    if (ready == true)
    {
        ready = false;
        switchProjectPhoto(-1);
    }
}
}
function nextPhoto()
{
	if(photos.length > 1)
{
    if (ready == true)
    {
        ready = false;

        switchProjectPhoto(1);
    }
}
}
function prevProject(slug, cat, url)
{
    if (ready == true)
    {
        ready = false;
        var data = $.evalJSON(getData("/index.php/ajax/getprojects", slug, cat, "previous"));
        $.historyLoad(url + data.slug);
    }
}
function nextProject(slug, cat, url)
{
    if (ready == true)
    {
        ready = false;
        var data =  $.evalJSON(getData("/index.php/ajax/getprojects", slug, cat, "next"));
        if(data)
        {
        $.historyLoad(url + data.slug);
        }
        else
        {
                ready = true;
        }
    }
}
function loadPhotos(data)
{
    photos = new Array(data.Images.length);
    if(data.Slogan == null)
    {
         data.Slogan = new Object();
    }
    if(data.Slogan.title == null)
    {
        datas.Slogan.title = "";
    }

    if(data.Slogan != null)
    datas = data;
   
    for(var i =0; i < data.Images.length; i++)
    {
        photos[i] = data.Images[i].name;
    }

    
    for(var i = 0; i < photos.length; i++)
    {
        $.preloadImages("/images/projecten/" + photos[i]);
    }
}

function getData(url, slug, cat, direction)
{
    if (!direction)
        direction = "";
    if (!cat)
        cat = "";

    var ret = "";
    $.ajax({
        url: url,
        type: "POST",
        async: false,
        data: ({
            slug : slug,
            cat : cat,
            direction : direction
        }),
        success: function(data)
        {
            ret = data;
        }
    });
    return ret;
}
function generateHash(href) // generates hash from href
{
    var cat0 = href[href.length - 3];
    var cat1 = href[href.length - 2];
    var cat2 = href[href.length - 1];
    var h = {
        'base' : cat0 ,
        'category' : cat1,
        'project' : cat2
    };
    return h;
}
var activeContent, activeContentSlug, contentVisibleToUser, contentHeigh;
function loadPage(url)
{
    $.historyLoad(url);
}
function getCategoryContent(slug, content, contentr, base, category)
{
    var url1 = "/" + base + "/" + category + "/productinfo";
    var url2 = "/" + base + "/" + category + "/projecten";
    var categorymenu = '<div style="position:absolute; bottom:0px; height:0px; width:100%; background-color:black;" id="'+slug+'">\
  <span id="menu" style="width:150px; height:100%;  display;block; float:left; margin-right:10px; margin-top:20px;">\
    <hr style="background-color:white"><li style="margin-left:10px;list-style:none; cursor: pointer;" onselectstart="return false;" onclick="loadPage(\''+url1+'\')">productinfo</li>\
    <hr style="background-color:white"><li style="margin-left:10px;list-style:none; cursor: pointer;" onselectstart="return false;" onclick="loadPage(\''+url2+'\')">projecten</li>\
    <hr style="background-color:white"><li style="margin-left:10px;list-style:none; cursor: pointer;"><a href="/offerte">offerte aanvragen</a></li>\
  </span>';

    if(contentr)
    {
        categorymenu += '\
        <span style="width:350px; float:left; display:block" id="text">'+content+'</span>\
        <span style="width:350px; margin-left:15px; float:left; display:block" id="text"><br />'+contentr+'</span>';
    }
    else
    {
        categorymenu +=  '\
        <span style="width:100% float:left;" id="text">'+content+'</span>';
    }
    categorymenu += '<span style="position:absolute; top:0px; right:0px; z-index:20; display:block;"  onclick="toggleSlider(\''+slug+'\');"><img id="togg" src="/images/button_toggle.png" /></span>';
    categorymenu += '</div>';

    return categorymenu;
}
function getProjectContent(slug, text, base, category, project, data)
{

    var url = "/" + base + "/" + category + "/";
    var control = '<div id="control">  <div style="width:125px; float:left;"><a  onselectstart="return false;"  onclick="prevProject(\''+slug+'\', \''+category+'\', \''+url+'\');" id="prevProject"><img src="/images/arrow_prev2.png" alt="Vorige project" style="display:inline; vertical-align:middle; margin-top:3px; margin-left:9px; " /> <span style="font-size:12px;">Vorige project</span></a></div>  <div style="width:125px; float:left;"><a  onselectstart="return false;"  onclick="prevPhoto();" id="prevPhoto"><img src="/images/arrow_prev.png" alt="Vorige foto" style="display:inline; vertical-align:middle; margin-top:3px; margin-left:9px; " /> <span style="font-size:12px;">Vorige foto</span></a></div>  <div style="width:429px; float:left; text-align:center; font-size:12px; margin-top:9px;" id="photo_text"><span id="txt_0" style="margin-top:-2px; position:relative; display:block;">'+text+'</span></div>  <div style="width:135px; float:left; text-align:right;"><a   onselectstart="return false;" onclick="nextPhoto();" id="nextPhoto"><span style="font-size:12px; ">Volgende foto</span><img src="/images/arrow_next.png" alt="Volgende foto" style="display:inline; vertical-align:middle; margin-top:3px; margin-right:9px;" /></a></div>  <div style="width:135px; float:left; text-align:right;"><a  onselectstart="return false;"  onclick="nextProject(\''+slug+'\', \''+category+'\', \''+url+'\');" id="nextProject"><span style="font-size:12px;">Volgende project</span> <img src="/images/arrow_next2.png" alt="Volgende project" style="display:inline; vertical-align:middle; margin-top:3px; margin-right:9px;" /></a></div></div>';



if(data.Images)
{
if(data.Images.length < 2)
{
 var control = '<div id="control">  <div style="width:125px; float:left;"><a  onselectstart="return false;"  onclick="prevProject(\''+slug+'\', \''+category+'\', \''+url+'\');" id="prevProject"><img src="/images/arrow_prev2.png" alt="Vorige project" style="display:inline; vertical-align:middle; margin-top:3px; margin-left:9px; " /> <span style="font-size:12px;">Vorige project</span></a></div>  <div style="width:125px; float:left;">&nbsp;</div>  <div style="width:429px; float:left; text-align:center; font-size:12px; margin-top:9px;" id="photo_text"><span id="txt_0" style="margin-top:-2px; position:relative; display:block;">'+text+'</span></div>  <div style="width:135px; float:left; text-align:right;">&nbsp;</div>  <div style="width:135px; float:left; text-align:right;"><a  onselectstart="return false;"  onclick="nextProject(\''+slug+'\', \''+category+'\', \''+url+'\');" id="nextProject"><span style="font-size:12px;">Volgende project</span> <img src="/images/arrow_next2.png" alt="Volgende project" style="display:inline; vertical-align:middle; margin-top:3px; margin-right:9px;" /></a></div></div>';
}
}


    var categorymenu = '<div style="position:absolute; bottom:0px; height:0px; width:100%; background-color:black;" id="'+slug+'">\
    ' + control + '\
  </div>';


    return categorymenu;
}


function toggleSlider(slug)
{
    var heightt = $("#" + slug).height();
    if(heightt >= 250)
    {
        $("#" + slug).animate({
        height:20
        }, {
            queue:true,
            duration:1000
        });

        $("#togg").attr("src", "/images/button_toggle1.png");
    }
    else
    {
        $("#" + slug).animate({
        height:250
        }, {
            queue:true,
            duration:1000
        });
        $("#togg").attr("src", "/images/button_toggle.png");
    }


}

$.preloadImages = function()
{
    for (var i = 0; i<arguments.length; i++)
    {
            $.imgpreload(arguments[i],
            {
                each: function()
                {
                       
                },
                all: function()
                {
                        // this = array of new image objects
                        // callback executes when all images are loaded
                }
        });
    }
}

function SliderToggle(slug, _contentHeight, menu)
{
    if (activeContent == slug) return; // if this content is already visible, do nothing
    activeContent = slug;
  
    if ((activeContentSlug != '') && (contentVisibleToUser)) // If a contentframe is shown on the screen, make it disappear
    {
        var current_vak = activeContentSlug;
        $('#' + current_vak).animate({
            opacity: 0,
            height:0
        }, 1000, function()
        {
            $(this).remove();
        });

    }
    activeContentSlug = slug;
    
    $("#contentHolder").append(menu);

    
    

    setTimeout(function()
    {
        $("#" + slug).animate({
        opacity: 0.8,
        height:_contentHeight,
        backgroundColor:"black"
    }, {
        queue:true,
        duration:1000
    });
       ready = true;
    }, 500 );
    contentVisibleToUser = true;
}
function pageload(hash) // jquery plugin loader
{
    if(hash) // first load WITH hash
    {
        if($.browser.msie)
        {
            hash = encodeURIComponent(hash);
        }
        load(hash);
    }
    else // start page without hash
    {
        window.location.reload();
    }
}
var photos, newPhotoIndex, _newPhotoName, _currentPhotoName, currentPhotoIndex;

function switchCategoryPhoto(toPhotoIndex)
{
    newPhotoIndex = toPhotoIndex;
    if(datas.Slogan.title == undefined)
    {
        datas.Slogan.title = "";
    }
    if (photos.length > newPhotoIndex)
    {
        
        _newPhotoName = underscoreIt(photos[newPhotoIndex]); // the new div name

        if ($("#" + _newPhotoName).length == 0)
        {
            //alert(datas.Slogan.title);

            html = '\
        <div id="'+_newPhotoName+'" style="display:none; opacity:0; position:absolute; top:58px; left0px;">\n\
          <img src="/images/projecten/'+photos[newPhotoIndex]+'" style="width:949px; height:395px;"/>\n\
            <div id="slogan" style="font-size:32px; width:600px; position:absolute; text-align:right; right:20px; top:12px;">\n\
            <h1>' + datas.Slogan.title + '</h1>\n\
            </div>\n\
        </div>';
            $("#photoSlider").append(html);
            
        }
        if ($("#photoSlider").children().length > 1)
            {
                $("#default, .contenttekst").fadeOut(function() {
                    $(this).remove();
                    $(".contenttekst").remove();

                });

               
            }
        $("#" + _newPhotoName).animate({
            opacity: 1
        }, 1000, function ()
        {
            
             $("#" + _currentPhotoName).fadeOut(function() {
                    $(this).remove();
                });
            _currentPhotoName = _newPhotoName;
            currentPhotoIndex = newPhotoIndex;
        });
         
        
    }
  
}
function switchProjectPhoto(toPhotoIndex)
{

    newPhotoIndex = calculatePhoto(currentPhotoIndex,toPhotoIndex); // the index in array photos to switch to
    _currentPhotoName = underscoreIt(photos[currentPhotoIndex]); // the current filename, dots are replaced by underscores, so it represents the div-name
    _newPhotoName = underscoreIt(photos[newPhotoIndex]); // the new div name

    nextPhotoIndex = calculatePhoto(currentPhotoIndex,toPhotoIndex); // calculate the second next/previous image, to preload it

   
    
    if ($("#" + _newPhotoName).length==0)
    {
        html = '\
        <div id="'+_newPhotoName+'" style="display:none; opacity:0; position:absolute; top:58px; left0px;">\n\
          <img src="/images/projecten/'+photos[newPhotoIndex]+'" alt="" style="width:949px; height:395px;"/>\n\
        </div>';
        $("#photoSlider").append(html);
    }

   
    $("#" + _newPhotoName).animate({
        opacity: 1
    }, 500, function ()

    {
         $("#" + _currentPhotoName).animate({
        opacity: 0
    }, 500);

            ready = true;
                currentPhotoIndex = newPhotoIndex; // the new index is from now on the current index
            $("#" + _currentPhotoName).remove();
        });



}
// this function determines the next photoFileName from the photos array
// currentPhotoIndex: the current Photo Index number from the photos array
// indexNumberCalculate: add or substract this number to the currectPhotoIndex      and way to difficult for a simple function
function calculatePhoto(currentPhotoIndex,indexNumberCalculate) {
    newIndex = currentPhotoIndex + indexNumberCalculate;
    if (newIndex >= photos.length) newIndex -= photos.length;
    if (newIndex < 0) newIndex += photos.length;
    return newIndex;
}
$.fn.hoverClass = function(c) {
    return this.each(function(){
        $(this).hover(
            function() {
                $(this).addClass(c);
            },
            function() {
                $(this).removeClass(c);
            }
            );
    });
};
function underscoreIt(str)
{
    str = str.replace(/\//gi,'_')
    str = str.replace(/\./g,'_');
    return str;
}
function onBefore(curr, next, opts) 
{
    var index = opts.currSlide;
} 
function onAfter(curr, next, opts) 
{
var src = $(next).attr("rel");
$("#info").html("" + src + "");

  var index = opts.currSlide;
  $('#prev')[index == 0 ? 'hide' : 'show']();

if($('#prev')[index] == "")
{
  $('#prev').after("<div id='prevspacer' style='width:99px; height:27px; float:left; '></div>");
}
else
{
$("#prevspacer").remove();
}

  $('#next')[index == opts.slideCount - 1 ? 'hide' : 'show']();
  $("#werkwijzeslider").animate({marginTop : -25, height : 50}, 0);
} 

$(document).ready(function()
{
    $.historyInit(pageload);   // loading module history

$('#default').cycle({
    fx: 'fade', // choose your transition type, ex: fade, scrollUp, shuffle, etc...
    prev:   'a#prev', 
    next:   'a#next', 
    before:   onBefore, 
after: onAfter,
    timeout: 5000
});




     $(".prodmenu_item").mouseover(function(){

      $(this).css({"background-image": "url(/images/projectenmenu_bg_hover.png)"});
      $(this).children("a").css({"color" : "black"});
    }).mouseout(function(){
        if($(this).attr("id") != "actief")
            {
                 $(this).css({"background-image": "url(/images/projectenmenu_bg.png)"});
                 $(this).children("a").css({"color" : "white"});
            }
      
    });



    $(".prodmenu_item").children().click(function()   // catching link clicks
    {
        if(ready == true)
        {            
            ready = false;
            var hash = generateHash($(this).attr("href").split('/'));
            $.historyLoad('/'+hash.base + '/' + hash.category + '/' + hash.project);
        }
    });



    $("#projectenLinks li").children().click(function()   // catching link clicks
    {
        if(ready == true)
        {
            ready = false;
            var hash = generateHash($(this).attr("href").split('/'));
            $.historyLoad('/'+hash.base + '/' + hash.category + '/' + hash.project);
        }
    });

});

