var oldPageSize = "";
function loadImages(pageSize){
	if(oldPageSize != pageSize){
		var allImages = new Array();
		$('.image_container').each(function(){
			
			if(oldPageSize != pageSize){

				var imgdata = jQuery.parseJSON($(this).attr('rel'));
				var insertObj = $(this);
				var imgholder = (imgdata[2]) ? imgdata[2] : false;
				if(insertObj.children('.'+pageSize+'img').length < 1){
					$.post(	'/wp-content/themes/culiversum/push-image.php',
							{ 
								imgid : imgdata[0],
								imgsize : imgdata[1][pageSize],
								pagesize : pageSize,
								overlay : imgholder
							}, 
							function(data){
					  				insertObj.append(data);
					  		}
					);
				}
			}
			
		});
		
		$('.vimeo').each(function(){
			var h = $(this).height(),
				w = $(this).width();
				
			if(pageSize == 'large'){
				$(this).width(403).height(h / w * 403);
			}else{
				$(this).width(328).height(h / w * 328);
			}
			
		});
		
		oldPageSize = pageSize
		
	}
	
}

function search(string){
	$.address.value(string);
}

function setLogoPos(kolom){

	kolom = ((kolom) ? kolom : (($('#logo').attr('pos')) ? $('#logo').attr('pos') : 1));

	$('#logo').animate({ 
		marginLeft: (($('body').hasClass('small')) ? 180 : 255) * (kolom - 1)
	},'fast').attr('pos',kolom);
}

$(function() {
	
	/****************************************************************************************
	* INIT
	****************************************************************************************/
	
	$('.nav').append('<div class="clear"></div>').children('ul').children('li').each(function(i){
		$(this).addClass('navcolnr_'+(i+1));
	});
	$('.nav > ul > li > a').each(function(){
		var txt = $(this).text();
		$(this).replaceWith('<span>'+txt+'</span>');
	});
	
	$('#searchfield').live('focus',function(){
		if($(this).val() == "zoek nieuws") $(this).val('');
	}).live('blur',function(){
		if($(this).val() == "") $(this).val('zoek nieuws');
	});
	
	
	/****************************************************************************************
	* ADDRESS
	****************************************************************************************/
	var hostname,
		init;
	$.address.init(function() {
	
			
			hostname = 'http://'+window.location.hostname;
			var request_uri = $.address.baseURL().replace(hostname,''); //"http://localhost"; //$.address.baseURL();
			
			if(request_uri){
				refresh_to = hostname + '/#!' + request_uri + '/';
				window.location = refresh_to;
			}else{
				$('#section').css('opacity',100);
			}	
	
			title = document.title;
	
			$('a[target!="_blank"]').address(function() { //.nav a, .jqa
	            return $(this).attr('href').replace(hostname + '/', '');
	        }); 
			
			init = true;
			
			
			
			//$('#section').find('.col:first-child').addClass('activeCol');

									
	    }).change(function(event) {
	    	
	    	var pathArr = $.address.pathNames();
	    	var pathUri = $.address.value();
	    	var pathStr = $.address.path();
			var qS = $.address.queryString();
			
			$('.nav > ul ul a.active').removeClass('active');
			$('a[href="'+hostname+pathStr+'"]').addClass('active');
			
			var names = $.map(event.pathNames, function(n) {
	             if(!strpos(n,'.php')) return n.substr(0, 1).toUpperCase() + n.substr(1);
	         });
	         
			 var newTitle = title + " | " + names.join(' | ');
			 $.address.title(newTitle);
			
			var allowed = [];
					
			if(pathStr != "/"){ // && !init
				$('#loader').show();
				
				var getVars =  (qS) ? $.extend({}, convert_qs(qS), { url: pathStr }) : { url: pathStr };

				$.post('/wp-content/themes/culiversum/ajaxrequest.php', getVars,
					function(data){
						$('#loader').hide();
						var data = jQuery.parseJSON(data),
							kolom = (data[0]) ? data[0] : 1,
							contenthtml = data[1],
							col = $('.colnr_'+kolom),
							navcol = $('.navcolnr_'+kolom),
							content = col.children('.columncontent'),
							homenews = col.children('.homenews');
							
							if(homenews.is(':visible')){
								homenews.fadeOut('fast',function(){
									content.hide().html(contenthtml).fadeIn('fast');
								});
							}else{
								content.fadeOut('fast',function(){
									content.hide().html(contenthtml).fadeIn('fast');
								});
							}
							
							$('.colnr_'+kolom).siblings().each(function(){
								var c = $(this).children('.columncontent'),
									h = $(this).children('.homenews');
									
								if(c.is(':visible')){
									c.fadeOut('fast',function(){
										h.fadeIn('fast');
									});
								}
							});
							
							if(!$('.activeCol').hasClass('colnr_'+kolom)){
							
							$('.activeCol').removeClass('activeCol');
							
								// document size
								var small = ($('body').hasClass('small')) ? true : false;
	
									setLogoPos(kolom);
									
									col
										.animate({
											width: (small) ? 328 : 403
										},'fast',function(){
											$('.nextCol').removeClass('nextCol');
											$(this).removeClass('unactiveCol').addClass('activeCol').attr('style','').next().addClass('nextCol');
										})
										.siblings()
										.animate({
											width: (small) ? 158 : 233
										},'fast',function(){
											$(this).removeClass('activeCol').addClass('unactiveCol').attr('style','');
										});
									
									navcol
										.animate({
											width: (small) ? 323 : 398
										},'fast',function(){
											$(this).removeClass('unactiveNavcol').addClass('activeNavcol').attr('style','');
										})
										.siblings()
										.animate({
											width: (small) ? 153 : 228
										},'fast',function(){
											$(this).removeClass('activeNavcol').addClass('unactiveNavcol').attr('style','');
										});
							
							}
					
						});
					
					}else{
					
						var small = ($('body').hasClass('small')) ? true : false,
							col = $('.activeCol')
							content = col.children('.columncontent'),
							homenews = col.children('.homenews');
							navcol = $('.activeNavcol');
						
						content.fadeOut('fast',function(){
							homenews.fadeIn('fast');
							col.animate({
								width: (small) ? 158 : 233
							},'fast',function(){
								$(this).removeClass('activeCol').addClass('unactiveCol').attr('style','');
								$('.nextCol').removeClass('nextCol');

							});
							navcol.animate({
								width: (small) ? 153 : 228
							},'fast',function(){
								$(this).removeClass('activeNavcol').addClass('unactiveNavcol').attr('style','');
							});													
						});
						
						setLogoPos(1);

					}
								
					init = false;
	});
	
	/****************************************************************************************
	* RESIZE
	****************************************************************************************/

	$.cookie = function(name, value, options) {
        if (typeof value != 'undefined') { // name and value given, set cookie
            options = options || {};
            if (value === null) {
                value = '';
                options = $.extend({}, options); // clone object since it's unexpected behavior if the expired property were changed
                options.expires = -1;
            }
            var expires = '';
            if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
                var date;
                if (typeof options.expires == 'number') {
                    date = new Date();
                    date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
                } else {
                    date = options.expires;
                }
                expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
            }
            // NOTE Needed to parenthesize options.path and options.domain
            // in the following expressions, otherwise they evaluate to undefined
            // in the packed version for some reason...
            var path = options.path ? '; path=' + (options.path) : '';
            var domain = options.domain ? '; domain=' + (options.domain) : '';
            var secure = options.secure ? '; secure' : '';
            document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
        } else { // only name given, get cookie
            var cookieValue = null;
            if (document.cookie && document.cookie != '') {
                var cookies = document.cookie.split(';');
                for (var i = 0; i < cookies.length; i++) {
                    var cookie = $.trim(cookies[i]);
                    // Does this cookie string begin with the name we want?
                    if (cookie.substring(0, name.length + 1) == (name + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        }
    };
    
    $.ScrollBar = {

        width: null,

        getWidth: function() {
            if (this.width == null) this.width = this.calculateWidth();

            return this.width;
        },

        calculateWidth: function() {

            var inner = document.createElement('p');
            inner.style.width = "100%";
            inner.style.height = "200px";

            var outer = document.createElement('div');
            outer.style.position = "absolute";
            outer.style.top = "0px";
            outer.style.left = "0px";
            outer.style.visibility = "hidden";
            outer.style.width = "200px";
            outer.style.height = "150px";
            outer.style.overflow = "hidden";
            outer.appendChild(inner);

            document.body.appendChild(outer);
            var w1 = inner.offsetWidth;
            outer.style.overflow = "scroll";
            var w2 = inner.offsetWidth;
            if (w1 == w2) w2 = outer.clientWidth;

            document.body.removeChild(outer);

            return (w1 - w2);
        }
    };
	
	$(window).resize(doResize);		

	var 
	    resizeTimer = null,
	    resizeCookie = {
	        key : "pageSize",
	        val : null,
	        opts : {
	            path : "/"
	        },
	        
	        init : function(){
	            this.val = this.get();
	        },
	        
	        //returns null if cookie does not exist
	        get : function(){
	            return $.cookie(this.key);
	        },
	        
	        set : function(val){
	            this.val = val;
	           	$.cookie(this.key, this.val, this.opts);
	        }
	    };
	    resizeCookie.init();
	    
	function doResize()
	{
		clearTimeout(resizeTimer);
		resizeTimer = setTimeout(resizeComplete, 200);
	}
	
	function resizeComplete() {
	    
		var $html = $("html");
		var $body = $("body");
		var winWidth = $(window).width();
		var adminBarHeight = ($('#wpadminbar').length > 0) ? $('#wpadminbar').height() : 0;
		var scrollbarWidth = ($(window).height() < $("body").height() + adminBarHeight) ? $.ScrollBar.getWidth() : 0;
					
		var big = ($.browser.msie ? 1640 : 1650) - scrollbarWidth;
		//var medium = ($.browser.msie ? 1600 : 1440) - scrollbarWidth;
		
		/*if(winWidth > big){
			$body.removeClass("small").removeClass('medium').addClass("large");
			cookieval = "large";
		}else 
		*/if(winWidth > big){
			$body.removeClass("small").addClass('large');
			cookieval = "large";
		}else{
			$body.removeClass("large").addClass("small");
			cookieval = "small";
		}
		 	
		$(document).trigger("resizeComplete");
		resizeCookie.set(cookieval);
		loadImages(cookieval);
		setLogoPos();
	}
	
	
	//loadSliders();
	resizeComplete();
	
	/****************************************************************************************
	* EINDE RESIZE
	****************************************************************************************/

	
	/****************************************************************************************
	* REST
	****************************************************************************************/

	$('.nav').hoverIntent({
		over: function(){
			$(this)
				.children('ul')
				.find('ul')
				.slideDown('fast');
			if($.browser.msie){
				$(this).css('background-color','white');
			}else{
				animate_bg($(this), 0, 10);
			}
		},
		out: function(){
			$(this)
				.children('ul')
				.find('ul')
				.slideUp('fast');
			if($.browser.msie){
				$(this).css('background','none');
			}else{
				animate_bg($(this), 10, 0);
			}

		},
		timeout: 1000
	});
	
			
});


function animate_bg(ele, from, to) {
    ele.css("background-color", "rgba(255, 255, 255, " + (from += from > to ? -1 : 1) / 10 + ")"); 
    if(from != to)  
        setTimeout(function() { animate_bg(ele, from, to) }, 20);
}
