var $theHolder = $('#holder');
var $theWrapper = $('#wrapper');

$theHolder.find('div').each(function () {
	var position = $(this).position();	
	$(this).attr('pleft',position.left);
	if($.browser.className != 'msie7') {
		$(this).attr('ptop',position.top);	
	} 
});
//$('#preLoadSocials>div').each(function(){
//	var h = $(this).find('.head').height();
//	$(this).attr('h',h);
//}); 
//POSITION TOP FIX FOR IE7//////////////////////////////////////
if($.browser.className == 'msie7') {
    $theHolder.find('div:eq(0), div:eq(1), div:eq(2), div:eq(3)').attr('ptop', '0');
    $theHolder.find('div:eq(4), div:eq(5), div:eq(6), div:eq(7)').attr('ptop', '627');
    $theHolder.find('div:eq(8), div:eq(9), div:eq(10), div:eq(11)').attr('ptop', '1254');
    $theHolder.find('div:eq(12), div:eq(13), div:eq(14), div:eq(15)').attr('ptop', '1881');
}

if ($theHolder.length) { var holderLeft = $theHolder.position().left; }
if ($theWrapper.length) { var contTop = $theWrapper.offset().top; }

function item(id) {
	this.id=id;
	this.topItem=null;
	this.rightItem=null;
	this.bottomItem=null;
	this.leftItem=null;
}

var item1 = new item(1);
var item2 = new item(2);
var item3 = new item(3);
var item4 = new item(4);
var item5 = new item(5);
var item6 = new item(6);
var item7 = new item(7);
var item8 = new item(8);
var item9 = new item(9);
var item10 = new item(10);
var item11 = new item(11);
var item12 = new item(12);
var item13 = new item(13);
var item14 = new item(14);
var item15 = new item(15);
var item16 = new item(16);

var rightArrow = $('#right');
var leftArrow = $('#left');
var topArrow = $('#top');
var bottomArrow = $('#bottom');
var cartItems = $('#cart #items');

item1.rightItem = item2;
item1.bottomItem = item5;

item2.leftItem = item1;
item2.rightItem = item3;
item2.bottomItem = item6;

item3.leftItem = item2;
item3.rightItem = item4;
item3.bottomItem = item7;

item4.leftItem = item3;
item4.bottomItem = item8;

item5.topItem = item1;
item5.rightItem = item6;
item5.bottomItem = item9;

item6.topItem = item2;
item6.bottomItem = item10;
item6.leftItem = item5;
item6.rightItem = item7;

item7.topItem = item3;
item7.bottomItem = item11;
item7.leftItem = item6;
item7.rightItem = item8;

item8.topItem = item4;
item8.bottomItem = item12;
item8.leftItem = item7;

item9.topItem = item5;
item9.bottomItem = item13;
item9.rightItem = item10;

item10.topItem = item6;
item10.bottomItem = item14;
item10.leftItem = item9;
item10.rightItem = item11;

item11.topItem = item7;
item11.bottomItem = item15;
item11.leftItem = item10;
item11.rightItem = item12;

item12.topItem = item8;
item12.bottomItem = item16;
item12.leftItem = item11;

item13.topItem = item9;
item13.rightItem = item14;

item14.topItem = item10;
item14.rightItem = item15;
item14.leftItem = item13;

item15.topItem = item11;
item15.rightItem = item16;
item15.leftItem = item14;

item16.topItem = item12;
item16.leftItem = item15;

function theNewGrid(initialItem){
	getCart();
	var _theGrid = this;
	this.currentItem = null;
	
	var easingType = 'swing';
	var shortTime = 1000;
	var longTime = 1000;
	var anmt = $theHolder;
	
	this.init = function()	{
		topArrow.click(function(){
			_theGrid.moverUp();
			return false;
		})
		rightArrow.click(function(){
			_theGrid.moverRight();
			return false;
		})
		bottomArrow.click(function(){
			_theGrid.moverDown();
			return false;
		})
		leftArrow.click(function(){
			_theGrid.moverLeft();
			return false;
		})
	}
	
	this.setItem = function(item) {
		this.currentItem = item;
			topArrow.hideMe();
			rightArrow.hideMe();
			bottomArrow.hideMe();
			leftArrow.hideMe();
		if(null!=this.currentItem.topItem) {
			topArrow.showMe();
		}
		if(null!=this.currentItem.rightItem) {
			rightArrow.showMe();
		}
		if(null!=this.currentItem.bottomItem) {
			bottomArrow.showMe();
		}
		if(null!=this.currentItem.leftItem) {
			leftArrow.showMe();
		}
	}
//	function animateIt(time,e,toItem,fromItem){
//		var notZero = toItem.id-1;
//		var pLeft = anmt.children('div').eq(notZero).attr('pleft');
//		var pTop  = anmt.children('div').eq(notZero).attr('ptop');
//		var toLeft = holderLeft - pLeft;
//		var toTop = contTop - pTop;
//		var preloaded = $('#preLoadSocials');
//		var socials = $('#socials');
//			preloaded.find('div#iidee'+fromItem.id).removeClass('inview').fadeOut(1000);
//			socials.fadeOut('fast', function () {
//				var url = encodeURIComponent(location.href.split('?')[0] + '?startidee=' + toItem.id);
//				socials.find('.fb iframe').attr('src', 'http://www.facebook.com/plugins/like.php?href=' + url + '&amp;layout=button_count&amp;show_faces=false&amp;width=300&amp;action=like&amp;font=arial&amp;colorscheme=light&amp;height=21');
//				socials.find('.twitter iframe').attr('src', 'http://platform0.twitter.com/widgets/tweet_button.html?_=1303281466413&count=horizontal&lang=en&text=BURENDAG%20DEV&url=' + url);
//			});
//			if(anmt.is(':animated') < 1){
//				anmt.animate({
//					left: toLeft+'px',
//					top: toTop+'px'
//					}, time, e, function(){
//						_theGrid.setItem(toItem);
//						socials.fadeIn();
//						preloaded.find('div#iidee'+toItem.id).addClass('inview').fadeIn(1000, function(){});
//				});
//			}
//	}
	function addNow(el){
		var loader = $('#cart .loading');
		$.ajax({
			url: '/bwsockets/10001/burendag/home',
			type: 'POST',
			data: {idea:el},
			beforeSend: function(){
				loader.fadeIn('slow');
			},
			dataType:'json',
			error: function(){
				alertWindow('Fout!', 'Er heeft zich een fout voorgedaan probeer het nogmaals.');
			},
			success: function(data){
				switch(data.status.statuscode){
					case 0: 
					break;
					case 1:
						getCart();
					break;
					case 2: 
						loader.fadeOut();
						alertWindow(data.status.headers, data.status.messages);
					break;
					case 4: 
						loader.fadeOut();
						alertWindow(data.status.headers, data.status.messages);
					break;
					case 8:
						loader.fadeOut();
						alertWindow(data.status.headers, data.status.messages);
					break;
					case 16:
						loader.fadeOut();
					break;
					default: 
					break;
				}
			}
		});
	} //addNow
	
	function getCart(){	
		var loader = $('#cart .loading');
		var cartP = $('#cart p.SignaCaps-Black');
		var cartSpan = $('#cart .head span.SignaNormal-Bold')
		$.ajax({
			url: '/bwsockets/10002/burendag/home/',
			dataType:'json',
			error: function(){
				alertWindow('Fout!', 'Er heeft zich een fout voorgedaan, probeer het nogmaals.');
			},
			success: function(data){
				switch(data.status.statuscode){
					case 0: 
					break;
					case 1:
						cartItems.empty();													  
								$(data.data).each(function(){
									var id = this.ideaid;
									var title = this.title;
									var desc = this.description;
									
										$('<li itemid="'+id+'" class="clearfix"><div class="idea'+id+'"></div><h2><a class="idee'+id+' goIdea">'+title+'</a></h2><a class="delete">[X] uit lijst halen</a></li>').prependTo(cartItems).find('a.goIdea').click(function(){
										var b = parseInt($(this).parents('li').attr('itemid'));	
										var c = eval('item'+b);
										if(_theGrid.currentItem.id != b){
											animateIt(longTime, easingType, c, _theGrid.currentItem);
										} 
										});	
									
									$('#printCart').removeClass('disabled');
									cartItems.find('a.delete').unbind('click').click(function(){
										var b = parseInt($(this).parents('li').attr('itemid'));											 	
										deleteFromCart(b);	
										loader.fadeIn('slow');
									});
									
								});
						
						loader.hideMe();
						CheckIdeaCart();
						checkScrollBar();
						
						if($(data.data).length == 1){
							cartP.html('je hebt <span class="digit">1</span> idee bewaard');
							cartSpan.html("Bekijk, deel en print het hier"); 
						} else {	
							cartP.html('je hebt <span class="digit">'+$(data.data).length+'</span> idee&euml;n bewaard');
							cartSpan.html("Bekijk, deel en print ze hier"); 
						}
						if($.browser.name == 'msie'){Cufon.refresh();}
					break;
					case 2: 
						loader.fadeOut();
						alertWindow(data.status.headers, data.status.messages);
					break;
					case 4: 						
						cartItems.empty();			 
						$('#printCart').addClass('disabled');
						$('<li class="clearfix noIdeas"><span>Er bevinden zich geen ideeen in het mandje</span></li>').prependTo(cartItems);
						loader.hideMe();
						CheckIdeaCart();
						cartP.html('je hebt <span class="digit"> 0 </span> idee&euml;n bewaard');
						cartSpan.html(''); 
					break;
					case 8:
						loader.fadeOut();
						alertWindow(data.status.headers, data.status.messages);
					default: 
					break;
				}
			}
		});
	}
	
	function deleteFromCart(el){
		var loader = $('#cart .loading');
		$.ajax({
			url: '/bwsockets/10004/burendag/home',
			type: 'POST',
			beforeSend: function(){
					
				},
			data: {idea:el},
			dataType:'json',
			error: function(){
				alertWindow('Fout!', 'Er heeft zich een fout voorgedaan, probeer het nogmaals.');
			},
			success: function(data){
				switch(data.status.statuscode){
					case 0: 
					break;
					case 1:
						getCart();
					break;
					case 2: 
						loader.fadeOut('slow');
						alertWindow(data.status.headers, data.status.messages);
					break;
					case 4: 
						loader.fadeOut('slow');
						alertWindow(data.status.headers, data.status.messages);
					break;
					case 8:
						loader.fadeOut('slow');
						alertWindow(data.status.headers, data.status.messages);
					break;
					case 16:
						loader.fadeOut('slow');
						alertWindow(data.status.headers, data.status.messages);
					break;
					default: 
					break;
				}
			}
		});
	}
	
	this.moverUp = function(){
		if(null!=_theGrid.currentItem.topItem) {
			animateIt(shortTime, easingType, _theGrid.currentItem.topItem, _theGrid.currentItem);	
		}
	}
	this.moverRight = function(){
		if(null!=_theGrid.currentItem.rightItem) {
			animateIt(shortTime, easingType, _theGrid.currentItem.rightItem, _theGrid.currentItem);	
		}
	}
	this.moverDown = function(){
		if(null!=_theGrid.currentItem.bottomItem) {
			animateIt(shortTime, easingType, _theGrid.currentItem.bottomItem, _theGrid.currentItem);	
		}
	}
	this.moverLeft = function(){
		if(null!=_theGrid.currentItem.leftItem) {
			animateIt(shortTime, easingType, _theGrid.currentItem.leftItem, _theGrid.currentItem);		
		}
	}
	this.init();
	animateIt(longTime, easingType, initialItem, initialItem);
	
	
	$('a.addToCart').click(function(){	
		if($('#cart .expandable').is(':hidden')){
				$('#cart a.toggleNext').trigger('click');
			}							
		var el = parseInt($(this).attr('ideaid'));
		addNow(el);
	});
	
//	$('#preLoadSocials .idea a.toggle').click(function(){
//		$(this).toggleClass('open');											   
//		var a = $(this).parents('.idea').find('.head');
//		var aa = $(this).parents('.idea')
//		var b = $(this).parents('.idea').attr('h');
//		var bb = (+b) + 25;
//		if (a.height() < 205){
//			a.animate({
//				height: '300px'
//			}, 'fast');
//			aa.animate({
//			   height: '330px'		   
//			}, 'fast');
//		} else {
//			a.animate({
//				height: b+'px'
//			}, 'fast');
//			aa.animate({
//				height: bb+'px'
//			}, 'fast');	
//		}
//		return false;
//	});
	
	
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////OUTSIDE///THE///GRID///////////////////////////////////////////////////////////////////////

var currentIdea = $.url.param('startidee'); //$.url.attr("anchor")
if ('undefined' == typeof currentIdea || currentIdea != parseInt(currentIdea))
	currentIdea = 11;

var initialItem = window['item' + currentIdea];
if ('undefined' == typeof initialItem)
	initialItem = item11;

// Deze functie wordt in home.asp uitgevoerd nadat de preloader is geladen in de fadeOut functie
//	var theNewGridInstance = new theNewGrid(initialItem);

function CheckIdeaCart(){
	if (cartItems.find('li').length < 1){
		$('#cart a.toggleNext').addClass('hide');
	} else {
		$('#cart a.toggleNext').removeClass('hide');			
	}
}

function toggleShoutBox(){
	var inner = $('#shoutbox .inner');
	if(inner.is(':animated') < 1){
		inner.animate({
			height: 'toggle'
		}, 1000);
	}
}
function checkScrollBar() {
	if ($('#cart #scrollBarNow').height() > 180){
		$('#scrollBarNow').jScrollPane({
			scrollbarWidth: 28
		});	
	}
}
function limitChars(textid, limit, infodiv){
	var text = $('#'+textid).val();
	var textlength = text.length;
	if(textlength > limit){
		$('#'+textid).val(text.substr(0,limit));
		return false;
	} else if ( textlength == 0) {
			return false;
		}
	else {
		return true;
	}
}

function countDays (){
	today=new Date()
	var burendag=new Date(today.getFullYear(), 8, 24) //Month is 0-11 in JavaScript
	if (today.getMonth()==8 && today.getDate()>24) {//if Christmas has passed already
		burendag.setFullYear(burendag.getFullYear()+1) //calculate next year's Christmas
	}	
		var one_day=1000*60*60*24;
		var diff = Math.ceil((burendag.getTime()-today.getTime())/(one_day));	
		
		$('#slideIt .countdown span.days').html(diff);
}
function getTweets() {
	var loader = $('#shoutbox .inner .loading');
	loader.fadeIn('slow');
	$(".tweet").empty().tweet({
		query: '#burendag2011',
		avatar_size: 48,
		count: 14,
		loading_text: "bezig met laden..."
	});
}
function getTweetsBurenBabbel() {
	$("#burenbabbel .twt").empty().tweet({
		query: '#burendag2011',
		avatar_size: 48,
		count: 1,
		loading_text: "bezig met laden..."
	});
}
function alertWindow(h, t){
	$('#alertWindow').fadeIn('slow');
		$('#alertWindow h4').text(h[0]);
		$('#alertWindow p').text(t[0]);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////EXECUTE///THE///FUNCTIONS//////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

$('#cart a.toggleNext').click(function(){
	var t = $(this);							
	var a = $(this).siblings('.expandable');
	if(a.is(':animated') < 1){
		a.slideToggle("fast", function(){
			t.toggleClass('open');						   
			checkScrollBar();
		});
	}
});
$('#alertWindow a.close').click(function(){
	$('#alertWindow').fadeOut('slow');
});
$('.triggeraboutBD').click(function(){
	$('#aboutBD').trigger('click');
});
$('#aboutBD').click(function(){
	if($('#shoutbox').is(':visible')){$('#burenbabbel>a.open').trigger('click');}						 
	$('#openBD').slideToggle();
});
$('#openBD a.lip').click(function(){
	$('#aboutBD').trigger('click');
});

$('button#shoutSelf').not(':animated').click(function(){
	toggleShoutBox();
});

$('#burenbabbel>a.open').click(function(){
	getTweets();
	if($('#openBD').is(':visible')){$('#openBD').slideUp();}
	$('#shoutbox').slideToggle();
});
$('#shoutbox a.toggleShoutbox').click(function(){
	$('#burenbabbel>a.open').trigger('click');
	return false;
});

$('#shoutToTwitter').submit(function () {
	var url = $(this).attr('action');
	var data = { secret: $('#scrt').val(), message: $('#msg').val() };
	var text = $('#msg').val();
	var textlength = text.length;
	var loader = $('#shoutbox .inner .loading');

	if (textlength > 0) {
		$.ajax({
			type: 'POST',
			url: url,
			data: data,
			dataType: 'json',
			beforeSend: function () {
				loader.fadeIn('slow');
			},
			success: function (data) {
				//alert(data.status.statuscode);
				switch (data.status.statuscode) {
					case 0:
						break;
					case 1:
						getTweets();
						getTweetsBurenBabbel();
						$('#msg').val('');
						break;
					case 2:
						loader.fadeOut('slow');
						alertWindow(data.status.headers, data.status.messages);
						break;
					case 4:
						loader.fadeOut('slow');
						alertWindow(data.status.headers, data.status.messages);
						break;
					case 8:
						loader.fadeOut('slow');
						alertWindow(data.status.headers, data.status.messages);
					default:
						break;
				}
			}
		});
	}
	return false;
});

$('#msg').keyup(function(){
	limitChars('msg', 126, 'msg-info');
})
/*$('#slideIt').cycle({
	fx: 'scrollLeft',
	timeout: 12000,
	speed: 2000
});*/
if($('#slideIt input.jQ_spend').val() == 0) {
	$("#slideIt").easySlider({
		auto: true,
		continuous: true ,
		controlsShow: false,
		speed: 500,
		pause: 12000000
	});
} else {
	$("#slideIt").easySlider({
		auto: true,
		continuous: true ,
		controlsShow: false,
		speed: 500,
		pause: 12000
	});
}
$('#shoutbox .inner a.up').click(function(){
	$('#shoutbox .tweet').stop().scrollTo('-=232px', 800);
	return false;
});
$('#shoutbox .inner a.down').click(function(){
	$('#shoutbox .tweet').stop().scrollTo('+=232px', 800);
	return false;
});
$('#metamenu li').each(function(i){
	$(this).addClass('item'+i);
});
$('#requestMoney a').click(function(){
	$('#cart p.SignaCaps-Black span.digit').text('12');
	if($.browser.name == 'msie') {Cufon.refresh();}
});
if(jQuery().jqTransform){
	$('form.transform').jqTransform({imgPath:'jqtransformplugin/img/'});
}
if($.url.param('winkelwagen') == 'open') {$('#cart a.toggleNext').trigger('click');}
$('#nieuwsbrief').submit(function(){
		var voornaam = $('input#Firstname_').val();
		var tussenvoegsel = $('input#Infix_').val();
		var achternaam = $('input#Lastname_').val();
		$('input#naam').val(voornaam + ' ' + tussenvoegsel + ' ' + achternaam);
	});

$('#nieuwsbrief').validate({
		errorElement: "label",
		errorPlacement: function(error, element) {
				error.appendTo( element.parents("div.formRow").next("div.error") );
			},
		rules: {
		    Firstname_: {
                required: true
            },
			Lastname_: {
				required: true
			},
			email: {
				email: true, 
				required: true
			},
			list: {required:true}
		},
		messages: {
            Firstname_: "Vul tenminste een naam in",
			email: {
				required: "Vul je e-mailadres in",
				email:"Vul een geldige e-mail in"},
			Lastname_: "Vul je achternaam in",
			list: "Kies een van de opties"
		}
	});


countDays();
CheckIdeaCart();
getTweetsBurenBabbel();
function waitPreloadPage() { //DOM
        if (document.getElementById) {
            //document.getElementById('prepage').style.visibility='hidden';
            //$('#preloader').css('display', 'none');
            document.body.style.overflow = 'visible';
            $('#prepage').fadeOut('slow', function () {
				//alert('loaded 1');									
				var theNewGridInstance = new theNewGrid(initialItem);
            });
        } else {
            if (document.layers) { //NS4
                //document.prepage.visibility = 'hidden';
                $('#preloader').css('display', 'none');
                document.body.style.overflow = 'visible';
                ('#prepage').fadeOut('slow', function () {
					alert('loaded 2');								   	
                });
            } else { //IE4
                //document.all.prepage.style.visibility = 'hidden';
                $('#preloader').css('display', 'none');
                document.body.style.overflow = 'visible';
                $('#prepage').fadeOut('slow', function () {
					alert('loaded 3');									
                });
            }
        }
    }

$(document).ready(function(){
    waitPreloadPage();
});

