

//***************************************************
// setting zoom and form clearance
//***************************************************

function SetZoom() {
	//--- add a colorbox wrapper for custom alerts
	var colorwrap = $("<div />").css({display: "none"});
	var color = $("<div />").attr("id", "inline_alert").appendTo(colorwrap);
	var trigger = $("<a />").attr("href", "#").attr("class", "triggerme").attr("id", "triggerme").css({display: "none"});
	$('body').append(colorwrap);
	$('body').append(trigger);
	
	//--- setup the colorboxzoom itself
	$('a.zoom').colorbox({opacity:0.5});
	$("a#mlr-alert").colorbox({opacity:0.5, width:"400px", inline:true, href:"#inline_alert"});
	//--- colorbox used for collezione collection
	$("a#triggerme").colorbox({
		opacity: 0.5, 
		inline: true, 
		href: "#inline_alert",
		onClosed: function(){$('#inline_alert').html('');}
	});	
	
}

function SetForm() {
	$('form.clear input.txt').clearingInput();
	$('form.clear textarea').clearingInput();
}


//***************************************************
// jquery goodness
//***************************************************
$(document).ready(function() {	

	SetZoom();
	SetForm();
	
	$("#twitter").tweet();

	//***************************************************
	// MAINNAV
	//***************************************************
	
	$('.nav>li').has('ul').hover(function() {
		$('ul',this).stop(true, true).slideDown(400);
		$('a:first',this).addClass('par');
	},function(){
		$('.nav ul').stop(true, true).delay(200).slideUp(400,function(){
	  		$(this).prev('a').removeClass('par');
		});
	})
	.find('a:first').css('cursor','default').addClass('noclick');
	$('.nav ul').hide();
	$('.nav ul a.act').parent('li').parent('ul').parent('li').find('a').addClass('act');
	$('.nav ul a').prepend('&rsaquo; ');


	// sitemap
	$('#sitemap>li').has('ul').find('a:first').css('cursor','default').addClass('noclick');


	// sidenavigation in widgets
	$('.sidenav ul').not('.open').hide();
	
	$('.sidenav>li').has('ul').click(function() {
		$('ul',this).slideToggle(400);
	})
	.find('a:first').addClass('noclick');
	
	$('.sidenav ul a.active').parent('li').parent('ul').parent('li').find('a').addClass('active');
	

	//###########################################
	// FEATURED SLIDER
	//###########################################
	var pos = 0;
	var pmax = $('#featured-list li').length - 1;
	var timerid = 0;
	
	$('#featured-list li').click(function(e){
		var _this = $(this);
		pos = $('#featured-list li').index($(this));
		h = -1*(pos*( $('#featured').height() ));
		$('#featured-imgs').animate({ marginTop: h }, 1200,function(){
			$('#featured-list li').removeClass('act');
			_this.addClass('act');
		});
		$('#featured-list').data('pos',pos);
		e.preventDefault();
		clearTimeout(timerid);
		SetSlider();
	});
	
	function SetSlider() {
		timerid = setTimeout(function(){    
		    var pos = $('#featured-list').data('pos')+1;
		    pos>pmax ? pos=0 : '';
		    $('#featured-list li').eq(pos).trigger('click');
		    $('#featured-list').data('pos',pos);
		}, 5000 ); 
	
	}
	$('#featured-list li').eq(pos).addClass('act').trigger('click');
	
	$('#featured-list li').hover(function(){
		$(this).addClass('hover');
	},function(){
		$(this).removeClass('hover');
	});
	

	//*********************************
	// SEND CONTACTFORM
	//*********************************
	$('input.subm').hover(function() {
	  $(this).addClass('hover');
	}, function() {
	  $(this).removeClass('hover');
	});
	
	$('input.subm').bind('click',function(){
		$(this).parent().addClass('loading');							 
	});	
	

	function BeforeSendCnt()  {
		$('input:text[value=""]').addClass('empt');
	}	
	
	function SendSuccesCnt(json,stat,xhr,frm)  {
				
		$('.loader').removeClass('loading');
		
		if (json.err=='no' && json.msg!='') {
		
			$('#inline_alert').html(json.msg);
			$('#triggerme').trigger('click');
			$('input',frm).removeClass('empt');
			frm.resetForm();
			SetForm();
		
		}else{ // als er een error is deze zichtbaar maken
						
			$('.clear input.empt').clearingInput();
			$('input',frm).removeClass('empt');
			$('#inline_alert').html(json.msg);
			$('#triggerme').trigger('click');
		
		}		
		
	}
	
	$('.ajaxform').ajaxForm({
			beforeSubmit: BeforeSendCnt,
			success: SendSuccesCnt,
			dataType: 'json',
			clearForm: false
	});
	
 
	//*********************************
	// NO CLICK PREVENT DEFAULT
	//*********************************
	$('a.noclick,a.noswitch').bind('click',function(e){
		e.preventDefault();
	});


	//*********************************
	// MAILCHIMP NEWSLETTER
	//*********************************

	$('#subscription').submit(function() {
		
		$('#newsletter .loader').show();
		
		$.ajax({
			url: 'kp_ajax/mailchimp.php',
			data: 'ajax=true&email=' + escape($('#mc_email').val()),
			success: function(msg) {
				$('#newsletter .loader').hide();
				$('#inline_alert').html(msg);
				$('#triggerme').trigger('click');
			}
		});
	
		return false;
	});
	
	
	//*********************************
	// STANDARD TABLE STUFF
	//*********************************
	$('table.tblStd').each(function(){
		$('tr:first',this).addClass('thead');
		$('tr:odd',this).addClass('odd')
	});
	
	//*********************************
	// PRODUCTLIST
	//*********************************	
	var prodwidth = -1 * ($('.products li').width()+2);
	
	$('.products li').hover(function(){
		$('.descr',this).stop(true,true).animate({'left':'0px'}, 300);
		$('.info',this).stop(true,true).animate({'left': prodwidth}, 300);
	},function(){
		$('.descr',this).stop(true,true).animate({'left': prodwidth}, 300);
		$('.info',this).stop(true,true).animate({'left':'0px'}, 300);
	});
	
	
	//*********************************
	// WEER WIDGET
	//*********************************	
	if($("#weather").length > 0) {
		$.simpleWeather({
			location: 'Vlissingen',
			success: function(weather) {
				
				html = '<div class="inner">';
					html += '<h3>'+weather.city+', Nederland</h3>';
					html += '<img style="float:left;" width="150px" src="'+weather.image+'">';
					html += '<p>'+weather.temp+'&deg; '+weather.units.temp+'<br /><span>'+weather.currently+'</span></p>';
					html += '<a href="'+weather.link+'" target="_blank">Bekijk weersverwachting &raquo;</a>';
				html += '</div>';
				
				$("#weather").html(html);
			},
			error: function(error) {
				$("#weather").html('<p>'+error+'</p>');
			}
		});
	}
	
	
	$('.toggle').hide();
	
	$('.toggleswitch').click(function(){
	
		$(this).next().slideToggle(400);
	
	});


});



(function($) {
  $.fn.tweet = function(o){
    var s = {
      username: "verbakelvuurw",
      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);
      //alert(parsed_date);
      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);
