//jQuery.easing.def = "easeInOutQuint";
/*
$(window).load(function() {
	LoadBgImg();
});
*/
$(document).ready(function() {

	/*
	setTimeout('$("#bgimg img").ResizeBackground()',1500);
	
	if($.browser.msie) {
		var tr = '';
	}
	
	$(window).resize(function() {
		$('#bgimg img').ResizeBackground();
	});
	*/

	$('#topbar h2').click(function(){
		location.href='index.php';
		return false;
	})	

	$('a#setback').click(function(){
		LoadBgImg();
		return false;
	})		

	//$(document).pngFix();
	SetForm();
	SetZoom();

	//---------------------------------------
	
	$('#triggerme').hide();

	$('input.subm').hover(function() {
	  $(this).addClass('hover');
	}, function() {
	  $(this).removeClass('hover');
	});

	$('#frm_cnt').ajaxForm({
			beforeSubmit: BeforeSendCnt,
			success		: SendSuccesCnt,
			clearForm	: false
	});

	function BeforeSendCnt(resp, stat)  {
		$('#loader').addClass('loading');
		$('#frm_cnt input[value=]').addClass('empt');
	}	
	
	function SendSuccesCnt(resp, stat)  {
		
		$('#loader').removeClass('loading');
		
		var json = eval('(' + resp + ')');
		
		if (json.send=='yes') {
			//--- als bericht verzonden is melding geven en alles resetten
			$('#inline_alert').html(json.msg);
			$('a#triggerme').trigger('click');
			//$('#mlr-alert').html(json.msg).fadeIn('slow', function(){ setTimeout( "$('#mlr-alert').fadeOut('slow')" ,3000)  });
			$('#frm_cnt input').removeClass('empt');
			$('#frm_cnt').resetForm();
			SetForm();
		}else{
			//--- als er een error is deze zichtbaar maken
			$('#frm_cnt input.empt').clearingInput();
			$('#frm_cnt input').removeClass('empt');
			$('#inline_alert').html(json.msg);
			$('a#triggerme').trigger('click');
		}		
		
	}

	//---------------------------------------

	var currharp = false;
	var curri = '999';
	var harpspeed = 400;
	$('.harp').hide();
	$('.harpwrap h2').click(function(e){
		
		if( curri==$('.harpwrap h2').index($(this)) ) {
			currharp.toggleClass('act');
			currharp.next().slideToggle(harpspeed);
		}else{
		
			if(currharp){
				currharp.removeClass('act');
				currharp.next().slideUp(harpspeed);
			}
			
			$(this).addClass('act');
			currharp = $(this);
			curri = $('.harpwrap h2').index($(this));
			currharp.next().slideToggle(harpspeed);	
		}	
		
	})
	
	//---------------------------------------
	
	SetProjectPages();

	var currproj = false;
	var currp = '';

	$('#projectlist li span').hover(function() {
		
		if(currp != $(this).find('a').attr('rel')) {
				
			currp = $(this).find('a').attr('rel');
		
			if(currproj){
				currproj.animate({marginTop: "0"}, 800);
			}
			currproj = $(this);
			$(this).animate({marginTop: "-19"}, 300);	
	
		}
	
	},function(){ return false; });


	$('#projectlist li span').click(function() {
		$(this).find('a.getinfo').trigger('click');										 
	});

	function GetProjectInfo(proj) {
		
		$("#projinfo").addClass('infoloading');
		
		$("#projinfo").find('div').fadeTo(300,0.2,function(){  
			$(this).load("kp_ajax/kp_get_projectinfo.php",{ id : proj }, function(){
				$("#projinfo").removeClass('infoloading');
				$(this).fadeTo(500,1);																  
			});								
		});

	}
	

	$('#projectlist a.getinfo').click(function(){
		var rel = $(this).attr('rel');
		GetProjectInfo(rel);
		return false;
	})
	
	$('#projectlist a.getimg').click(function(){	
			
		$('#projimg').fadeIn(500);		
		var rel = $(this).attr('rel');
		GetProjectInfo(rel);
	
		$('#projimg').load("kp_ajax/kp_get_projectimage.php",{ id : rel }, function(){
	
			//$(this).fadeTo(500,1);																  
		});	
		return false;
	})	


	$('a#close').live("click",function(){
		$('#projimg').fadeOut(500, function(){
			$('img',this).remove();									
		});			
		return false;
	})

	//---------------------------------------

	$(".tweet").tweet();
	
	var bgi = $('#bgimages a:random').attr('href');
	$.backstretch(bgi);
	
});

//--------------------------------------------------

function SetProjectPages() {
	
	var c = $('#projectlist li').size();
	var p = Math.ceil(c/12);
	
	for(i=1;i<=p;i++){
		$('#projnav').append('<a rel="'+ i +'">'+ i +'</a>');
	}
	
	$('#projnav a:first').addClass('act');
	
	$('#projnav a').click(function() {
		$('#projnav a').removeClass('act');						   
		$(this).addClass('act');					   
		var page = $(this).attr('rel') - 1;
		var prjhg = ( (10*page) + ($('#projectslider').height() * page) ) * -1;
		$('#projectlist').animate({marginTop: prjhg}, 800);
		$('a#close').trigger('click');
		return false;																	 
	})	
	
}

//--------------------------------------------------

function SetZoom() {
	$('a.zoom').colorbox({opacity:0.70});
	$("a#triggerme").colorbox({opacity:0.70, width:"320px", inline:true, href:"#inline_alert"});
}

function SetForm() {
	$('input:text:[value=""]').clearingInput();
	$('textarea').clearingInput();
}

//--------------------------------------------------

function loadimg(image,wrap) {		
	var img = new Image();
	$(img).load(function () {   
		$(this).hide();
		wrap.find('.imgholder').append(this);
		$(this).fadeIn(600);
	})
	.attr('src', image);
 }

//--------------------------------------------------

function LoadBgImg() {
	
	var bgi = $('#bgimages a:random').attr('href');
	
	$('#bgimg img').remove();
	
	var img = new Image();
	$(img).load(function () {   
		$(this).hide();
		$('#bgimg').append(this);
		$(this).fadeIn(1500);
		$('#bgimg img').ResizeBackground();
	})
	.error(function () {
		LoadBgImg()
		//alert('Image could nog be loaded.');
	})
	.attr('src', bgi);
}

(function($) {

	var srch = '';
	var srcw = '';

	$.fn.ResizeBackground = function(options){
	
		srch === '' ? srch = $(this).height() : '' ;
		srcw === '' ? srcw = $(this).width() : '' ;
		
		var ratio = srch / srcw; 
		var scl = srcw / srch;
		
		var winh = $(window).height();
		var winw = $(window).width();
		
		// hoger dan breed
		if(winh>winw) {
			
			newh = winh;
			neww = Math.floor(newh * scl);
		
		}
		
		// breder dan hoog
		if(winw>winh) {
			
			neww = winw;
			newh = Math.floor(neww * ratio);
			
			if(newh<winh) {
				newh = winh;
				neww = Math.floor(newh * scl);
			}
		
		}		
		
		if(neww > winw ) {
			var posx = Math.floor(-1 * (neww - winw));
		}else{
			var posx = 0;
		}
		
		if(winw<961) {
			var posx = $(this).css('margin-left');
		}		
		
		$(this).width(neww).height(newh).css({
			'height' : newh,
			'width' : neww,
			'margin-left' : posx
		});
		
		var rationew = $(window).height()/ $(window).width()
		
	}	
	
})(jQuery);


(function($) {
 
  $.fn.tweet = function(o){
    var s = {
      username: "dngine",
      count: 3,
      loading_text: null,
      query: null
    };

    $.fn.extend({
      linkUrl: function() {
        var returning = [];
        var regexp = /((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)/gi;
        this.each(function() {
          returning.push(this.replace(regexp,"<a href=\"$1\" target=\"_blank\">$1</a>"))
        });
        return $(returning);
      },
      linkUser: function() {
        var returning = [];
        var regexp = /[\@]+([A-Za-z0-9-_]+)/gi;
        this.each(function() {
          returning.push(this.replace(regexp,"<a href=\"http://twitter.com/$1\" target=\"_blank\">@$1</a>"))
        });
        return $(returning);
      },
      linkHash: function() {
        var returning = [];
        var regexp = / [\#]+([A-Za-z0-9-_]+)/gi;
        this.each(function() {
          returning.push(this.replace(regexp, ' <a href="http://search.twitter.com/search?q=&tag=$1&lang=all" target="_blank">#$1</a>'))
        });
        return $(returning);
      }
    });

    function relative_time(time_value) {
      var parsed_date = Date.parse(time_value);
      var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
      var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
      if(delta < 60) {
      return 'less than a minute ago';
      } else if(delta < 120) {
      return 'a minute ago';
      } else if(delta < (45*60)) {
      return (parseInt(delta / 60)).toString() + ' minutes ago';
      } else if(delta < (90*60)) {
      return 'an hour ago';
      } else if(delta < (24*60*60)) {
      return (parseInt(delta / 3600)).toString() + ' hours ago';
      } else if(delta < (48*60*60)) {
      return '1 day ago';
      } else {
      return (parseInt(delta / 86400)).toString() + ' days ago';
      }
    }

    if(o) $.extend(s, o);
    return this.each(function(){
      var list = $('<ul class="tweet_list">').appendTo(this);
      if(typeof(s.username) == "string"){
        s.username = [s.username];
      }
      var query = '';
      if(s.query) {
        query += 'q='+s.query;
      }
      query += '&q=from:'+s.username.join('%20OR%20from:');
      var url = 'http://search.twitter.com/search.json?&'+query+'&rpp='+s.count+'&callback=?';
      if (s.loading_text) $(this).append(loading);
      $.getJSON(url, function(data){
        if (s.loading_text) loading.remove();
        $.each(data.results, function(i,item){

          //var date = '<em class="tweet_date">'+relative_time(item.created_at)+'</em>';
          var text = $([item.text]).linkUrl().linkUser().linkHash()[0];

		  $('<li></li>').html(text).appendTo('.tweet_list');

        });
   
      });

    });
  };
})(jQuery);
