// JQuery
// use $j instead of $ (mootools in modx)

function __slidingblocks(){
	var newHash = $j(".slidermenu").children("li").children("a").attr("href"); // page independent!
	// SHOULD BE THE "SLIDERBLOCKS" item and remove "project-"
	return newHash != undefined;
}

function __newsItems(){
	return  $j("#nieuws #latest-news").length > 0;
}

var newsItems = null;

function SetNewsItem(number){

	if(newsItems!=null)
	{

	var articleHtml = "<h2>"+ newsItems[number].getElementsByTagName("title")[0].childNodes[0].nodeValue +"</h2>";
	var text = getElementTextNS('content', 'encoded', newsItems[number], 0);
	
	var textEnd = text.search('<span id="more-'); /*-- typical wordpress thingie */
	if(textEnd > -1)
	{
		articleHtml += text.substr(0,  textEnd); 
		articleHtml += '<a href="';
		articleHtml += newsItems[number].getElementsByTagName("link")[0].childNodes[0].nodeValue;
		articleHtml += '">Lees meer op onze blog &raquo;</a></p>';
	}
	else
	{
		articleHtml += text;
	}
	 $j("#latest-news-item").html( articleHtml );
	// sifr
	if(typeof sIFR == "function"){
		sIFR.replaceElement( "#nieuws h2", named({sFlashSrc:"http://www.kenneth-koh.com/assets/templates/studiokk/sifr/Swis721LtCnBT.swf", sColor:"#333333", sBgColor:"#FFFFFF", sWmode:"transparent", sCase:"upper", sFlashVars:"textalign=left&offsetTop=0"}) );
	 }
	}
	else
	{
		// Error occurred
	}
}

// This function is called when:
// 1. after calling $.historyInit();
// 2. after calling $.historyLoad();
// 3. after pushing "Go Back" button of a browser
//
// --> Either sliding functionality
//     or news items!
function Update(hash) {
  // hash doesn't contain the first # character.

  if(hash) {
    //
    //-- Sliding Funcitonality --//
    //
    //if(__slidingblocks()){
      var blockDiv = $j("#project-"+hash);
      if(blockDiv.length > 0)
      {
        var blockOffset = blockDiv.offset();
        var blocksOffset = $j("#sliderblocks").offset();
        var offsetLeft = blocksOffset.left - blockOffset.left; // some error in IE7??
        var offsetTop = blocksOffset.top - blockOffset.top;

        var animationDuration = Math.ceil(Math.abs(blockOffset.left * 0.3) + Math.abs(blockOffset.top * 0.3)); // 1500
        if(blockOffset.top < 0) { animationDuration *= 1.5; } // fix
        if(blockOffset.left < 0) { animationDuration *= 1.2; } // fix

	//alert( (blocksOffset.left - offsetLeft) + "/" + (blocksOffset.top - offsetTop));
        $j("#sliderblocks").animate( { top: offsetTop + "px", left : offsetLeft + "px"}, {duration: animationDuration , queue:false, easing:"easeInOutQuad" } ); // ,

        // fix blocks
        $j("#sliderblocks").children(".block").addClass("inactive");
        blockDiv.removeClass("inactive");

        // fix menu active item
        $j(".slidermenu").children("li").removeClass("active").children("a[href=#"+hash+"]").parent().addClass("active");
      }
    //}

    //
    //-- News items --//
    //
    if( __newsItems())
    {
      SetNewsItem(hash);
    }
  } else {
    // start page

	// if sliding blocks
	var newHash = $j(".slidermenu").children("li").children("a").attr("href"); // page independent!
	//
	if(__slidingblocks()){
		Go( newHash.substring(1) ); // remove the "#"
	}

	// else news items
	if( __newsItems())
	{
		Go("0"); // show the latest blog post!
	}

  }
}


function Go(hash){
  $j.historyLoad(hash);
}

//
// Centers the viewport.
//
function CenterViewport(){
  var documentHeight = $j(window).height();
  var headerHeight = $j("#header").height();
  var footerHeight = $j("#footer").height();

  var viewportHeight = documentHeight - headerHeight - footerHeight;
  var viewportWidth = $j(document.body).width();
  
  //alert(documentHeight+" "+ headerHeight+" "+viewportHeight+" "+footerHeight);

  $j("#viewport").height( viewportHeight ).width( viewportWidth );
  $j("#footer").css( { position:"fixed", top: documentHeight - footerHeight, left:"0px" } )


  // Center contact information
  var uspHeight = $j("#usp").height();
  var contactHeight = $j("#contact-content #information").height();
  var contactPosition = Math.max(0, Math.round((viewportHeight - uspHeight - contactHeight - 35) / 2) ) + "px"; // minus 35!
  $j("#contact-content").css({  position:"relative", top:contactPosition });
}
//
// Sets the layout of the blocks according to the given mode.
// where mode is one of the following
// * "horizontal"
// * "vertical"
// * "diagonal"
// * "map"
//
function SetBlockLayout(mode) // { options }
{
  var vertical = false;
  var horizontal = false;
  var map = false;

  if(mode=="horizontal" || mode == "diagonal"){ horizontal = true; }
  if( mode == "vertical" || mode == "diagonal"){ vertical = true; }
  if( mode == "map" ){ map = true; }

  var blocks = $j("#sliderblocks").children(".block");
  var blocksOffset = $j("#sliderblocks").offset();
  var blockMargin = 10;

  if(vertical || horizontal)
  {
    for(i = 0; i < blocks.length; i++){
    var block = $j(blocks.get(i));
    block.css("position", "absolute");

      if(i > 0)
      {
        var prev = $j(blocks.get(i-1));
        if(horizontal)
        {
          var offsetLeft = prev.offset().left + prev.width() - blocksOffset.left + blockMargin;
          block.css( "left", offsetLeft +"px" );
        }
        if(vertical)
        {
          var offsetTop = prev.offset().top + prev.height() - blocksOffset.top + blockMargin;
          block.css("top", offsetTop + "px" );
        }

      } else {
        if(horizontal){ block.css("left", "0px"); }
        if(vertical){ block.css("top", "0px"); }
      }
    }
  }
  else if (map)
  {
    // TODO
    var bound = Math.ceil(Math.sqrt(blocks.length));

    // requires a fixed block height and width [get from parameters]
    var randomBlock = $j(blocks.get(0));
    var blockWidth = randomBlock.width();
    var blockHeight = randomBlock.height();

    blockWidth += blockMargin;
    blockHeight += blockMargin;

    var id;
    var block;
    var offsetLeft;
    var offsetTop;

    for(y = 0; y < bound; y++){
      for(x = 0; x < bound; x++){
        id = x+bound*y;
        block = $j(blocks.get(id)); // get correct index!
        offsetLeft = blockWidth * x;
        offsetTop = blockHeight * y;

        block.css("position", "absolute");
        block.css("left", offsetLeft + "px");
        block.css("top", offsetTop + "px");

        if(id >= blocks.length){ break; }
      }
      if(id >= blocks.length){ break; }
    }
  }
}

//
// EventHandlers
//

$j(window).resize(CenterViewport);

$j(document).ready(function(){

	if(jQuery.browser.msie && jQuery.browser.version == "6.0"){
		//document.body.innerHTML = '<div id="error-notification"><ul><li><a href="http://www.firefox.com">Firefox</a></li><li><a href="http://www.opera.com">Opera</a></li><li><a href="http://www.microsoft.com/netherlands/windows/products/winfamily/ie/default.mspx">Internet Explorer 7</a></li> <li>  </li> <li> of ga naar onze <a href="http://www.kenneth-koh.com/blog/">blog</a></li> </ul></div>';
		window.location = "http://www.kenneth-koh.com/index.php?id=54";
		return;
	}

  //
  // center the viewport (init)
  //
  CenterViewport();
  //
  // set layout
  //
  if(mode){
    SetBlockLayout(mode);
  }
  
  //
  // initialize active menu element
  //
    $j("#slidermenu").children("li:first").addClass("active");
  //
  // initialize functions for the menu items
  //
  /*
  $j("#slidermenu").children().children("a").each( function(index) {
    this.href = "#" + this.parentNode.id;
  });
  */
  /*
    $j("#slidermenu").children().children("a").each( function(index){
        this.onmousedown = function(){
            var blockOffset = $j("#project-"+this.parentNode.id).offset();
            var blocksOffset = $j("#sliderblocks").offset();
            var offsetLeft = blocksOffset.left - blockOffset.left;
            var offsetTop = blocksOffset.top - blockOffset.top;

            $j("#sliderblocks").animate( { top: offsetTop, left : offsetLeft }, {duration:500, queue:false} ); // easing:"easeInExpo",

            // fix menu active item
            $j(this.parentNode.parentNode).children("li").removeClass("active");
            $j(this.parentNode).addClass("active");
        }
    });
  //*/


  //
  // Fixes Internet Explorer
  //
  
  // fix for menu items
  $j(".slidermenu").children("li").children("a[href|=#]").click(function(){
    var hash = this.href;
    hash = hash.replace(/^.*#/, '');
    $j.historyLoad(hash);
    return false;
  });
  
  //
  // fix PNG transparency for Internet Explorer 6
  //
  $j('img[@src$=.png], div.logo').ifixpng();
  //
  // thickbox shit
  //
  tb_init('a.thickbox, area.thickbox, input.thickbox');//pass where to apply thickbox
  imgLoader = new Image();// preload image
  imgLoader.src = tb_pathToImage;
  //
  // Google maps for contact... (does not work in IE7 if placed at end of document)
  //
  if (GBrowserIsCompatible()) {
	kkGmapInitialize();
  }
	//
	// Accordion
	$j("#over-ons-services").accordion();


  //
  // Initialize history
  //
  // The callback is called at once by present location.hash. 
  $j.historyInit(Update);




});