function debug(txt){
	if($('#debug').length > 0){
		$('#debug').append(txt+"<br />").show();
	}else{
		$('body').prepend("<div id='debug'></div>");
	}
}

function setMap(){
	if($('#map').length > 0){
		$("#map").height($('#contacttxt').height() + 100).gMap({ markers: [{ latitude: 52.1009555,
	              longitude: 5.1141863,
	              html: "<b>Autobahn grafisch ontwerp</b>",
	              popup: false }],
	  	zoom: 14 });
	 }
}

function loadSliders(homeslider,prslider,cookieval){

	var countsliders = 0;
	if($('.homeslidercontainer').length > 0){
		
		$('.homeslidercontainer').html(homeslider);
		
		//$('#homeslider').cycle('destroy').attr('style','').children('.homeheader').attr('style','');
		$('#homeslider').cycle({ 
		    fx: 'scrollHorz', 
		    speed:    1000, 
		    timeout:  5000,
		    prev: '.prev',
		    next: '.next',
		    after: function(){
		    	$("#homeslider h1").each( function() { FLIR.replace(this, new FLIRStyle({mode:'static',cFont:'brnstdbl'}));});
   				$("#homeslider h4").each( function() { FLIR.replace(this, new FLIRStyle({mode:'wrap',cFont:'brnstdbd'}));});
   				if(!Modernizr.borderradius){
   					$('.bottomrightcorner_60').corner("br 60px");
   				}
		    }
		});
		countsliders++;
	}
	
	if($('.prslidercontainer').length > 0){
		
		$('.prslidercontainer').html(prslider);
		
		$('#pr_slideshow').cycle({ 
		    fx: 'scrollHorz', 
		    speed:    300, 
		    timeout:  5000,
		    prev: '.prev',
		    next: '.next' 
		});
		countsliders++;
	}
	loadImages(cookieval,countsliders);

}

var oldPageSize = "";
function loadImages(pageSize,countsliders){
	if(oldPageSize != pageSize || countsliders > 0){
		var allImages = new Array();
		$('.image_container').each(function(){
			
			if(oldPageSize != pageSize || $(this).hasClass('sliderimg')){

				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/autobahn/push-image.php',
							{ 
								imgid : imgdata[0],
								imgsize : imgdata[1][pageSize],
								pagesize : pageSize,
								overlay : imgholder
							}, 
							function(data){
					  				insertObj.append(data);
					  		}
					);
				}
			}
			
		});
		oldPageSize = pageSize
		
	}
	
}

$(document).ready(function(){

	var menuitems = new Array();
	menuitems['about_menu'] = 42;
	menuitems['cases_menu'] = 41;
	menuitems['contact_menu'] = 57;
	menuitems['shop_menu'] = 33;
	menuitems['graphic_menu'] = 44;
	menuitems['typography_menu'] = 68;
	menuitems['editorial_menu'] = 53;
	menuitems['campaign_menu'] = 52;
	menuitems['spatial_menu'] = 40;
	menuitems['identity_menu'] = 46;	
	menuitems['info_menu'] = 28;	

	menuitems['graphic'] = 164;
	menuitems['typography'] = 254;
	menuitems['editorial'] = 191;
	menuitems['campaign'] = 197;
	menuitems['spatial'] = 151;
	menuitems['identity'] = 171;	
	
	menuitems['grafisch'] = 181;
	menuitems['typografie'] = 230;
	menuitems['editorial'] = 191;
	menuitems['campagne'] = 204;
	menuitems['ruimtelijk'] = 219;
	menuitems['identiteit'] = 198;	
	
	menuitems['ontwerpproces_menu'] = 107;
	menuitems['grafisch_menu'] = 53;
	menuitems['typografie_menu'] = 67;
	menuitems['editorial_menu'] = 55;
	menuitems['campagne_menu'] = 59;
	menuitems['ruimtelijk_menu'] = 63;
	menuitems['identiteit_menu'] = 58;	
	menuitems['bureauprofiel_menu'] = 100;	

	menuitems['nl_menu'] = 16;
	menuitems['en_menu'] = 15;


	var homeslider = $('.homeslidercontainer').html();
	var prslider = $('.prslidercontainer').html();
	
	if(!Modernizr.borderradius){
		$('.topcorners').corner("top 10px");
		$('.bottomcorners').corner("bottom 10px");
		$('.toprightcorner').corner("tr 10px");
		$('.bottomrightcorner').corner("br 10px");
		$('.bottomrightcorner_35').corner("br 35px");
		$('.bottomrightcorner_60').corner("br 60px");
		$('.toprightcorner_75').corner("tr 75px");
		$('.smallcorners').corner("3px");
		$('.bottomrightcorner_15').corner("br 15px");
		$('.toprightcorner_15').corner("tr 15px");
	}
	
	
	$('.nav').find('a').hover(
		function(){
			$(this).stop().animate({
				color:'#7ad7fc'
			},'fast');
		},
		function(){
			if(!$(this).parent().hasClass('current_page_item')){
				$(this).stop().animate({
					color:'#c7dfe0'
				},'fast');
			}
		}
	);
	
	$('.subnav').find('a').hover(
		function(){
			$(this).stop().animate({
				color:'#7ad7fc'
			},'fast');
		},
		function(){
			if(!$(this).parent().hasClass('current-menu-item')){
				$(this).stop().animate({
					color:'#848484'
				},'fast');
			}
		}
	);
	
	$('#footer').hover(
		function(){
			$('#footerwrapper').stop().animate({
				opacity : 1
			},'fast');
		},
		function(){
			$('#footerwrapper').stop().animate({
				opacity : 0.25
			},'fast');
		}
	);
	
	$('.nav').find('li:last-child').css({'float':'right','border':0}).prev().css('border',0);
	//$('.nav').children('ul').append('');
	$('.extranav').appendTo($('.nav').children('ul'));
	
	$('.subnav').find('li:last-child').css('border',0);
	
	$('.pr_content').hover(
		function(){
			$(this).find('.pr_info').slideDown(100);
		},
		function(){
			$(this).find('.pr_info').slideUp(100);
		}
	).click(function(){
		var url = $(this).prev().children('a').attr('href');
		window.location = url;
	});
	
	/* RESIZING */
	
	$.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 ? 1909 : 1919) - scrollbarWidth;
		var medium = ($.browser.msie ? 1429 : 1439) - scrollbarWidth;
		
		/*
		if(winWidth > big){
			$body.removeClass("small").removeClass('medium').addClass("large");
			cookieval = "large";
		}else */ 
		if(winWidth > medium){
			$body.removeClass("small").removeClass('large').addClass("medium");
			cookieval = "medium";
		}else{
			$body.removeClass("large").removeClass('medium').addClass("small");
			cookieval = "small";
		}
		 	
		$(document).trigger("resizeComplete");
		resizeCookie.set(cookieval);
		loadSliders(homeslider,prslider,cookieval);
		setMap();
	}
	
	
	//loadSliders();
	resizeComplete();
	
	// EINDE RESIZE
	
		if(!$.browser.msie && !$.browser.opera){
		var blendImg = new Image();
		blendImg.onload = function() {
			function cloneImg(obj){
				obj
					.clone()
					.appendTo(obj.parent())
					.pixastic("blend", {
				        amount: 0.3,
				        mode: "multiply",
				        image: blendImg
				    });
			}
			
			$('.homeblock, .homeheader').find('.opacfader').find('img').each(function(){
				cloneImg($(this));
			});
			
			
			
			$('.homeblock, .homeheader').live('mouseover mouseout',function(event){
			
				var obj =  $(this).find('.imgsizeholder:visible');
				if ( event.type == "mouseover" ) {					
				   // Img nog niet gecloned
				   if(obj.children().length < 2){
				   		cloneImg(obj.children('img'));
				   }else if(obj.children().length == 2 && obj.children('canvas').length == 0){
				   // Iets fout gegaan met het multiplyen
				   		obj.children(':nth-child(2)').pixastic("blend", {
					        amount: 0.3,
					        mode: "multiply",
					        image: blendImg
					    });
				   }
				  // obj.children(':first-child').fadeOut('fast');
				  	obj.children(':first-child').stop().animate({
				  		'opacity' : 0
				  	},'fast');
				   
				} else {
				 	obj.children(':first-child').stop().animate({
				  		'opacity' : 1
				  	},'fast');  
				}
			});
			
			
			
		}
		blendImg.src = "/wp-content/themes/autobahn/images/bluemultiply.gif";
	}else{
		$('.homeblock, .homeheader').live('mouseover mouseout',function(event){
			if ( event.type == "mouseover" ){
				//var obj = ($.browser.msie) ? $(this).children('.opacfader').find('img') : $(this).children('.opacfader');
				$(this).children('.opacfader').find('img').animate({
					'opacity':0.7
				},'fast');
			}else{
				//var obj = ($.browser.msie) ? $(this).children('.opacfader').find('img') : $(this).children('.opacfader');
				$(this).children('.opacfader').find('img').animate({
					'opacity':1
				},'fast');
			}
		});
	}
	
	$('.homeblock').find('.opacfader').live('click',function(){
		var url = $(this).parents('.homeblock').find('h2').children('a').attr('href');
		window.location = url;
	});
	
	$('.homeheader').find('.opacfader').live('click',function(){
		var url = $(this).parents('.homeheader').find('h1').children('a').attr('href');
		window.location = url;
	});
	
	$('.homeblock').hover(
		function(){
			$(this).find('h2').children('a').css('background-position','-'+menuitems[$(this).find('h2').children('a').html().toLowerCase()]+'px 0');
		},
		function(){
			$(this).find('h2').children('a').css('background-position','0 0');
		}
	);


	$('.nav, .subnav, .homeblock h2').find('a').each(function(){
		
		var txt = $(this).html().toLowerCase();
		if(!$(this).parent().hasClass('hoverlink')) txt += '_menu';
		
		if(menuitems[txt]){
			$(this)
				//.attr('rel',menuitems[txt])
				.width(menuitems[txt])
				.css({'background-image':'url(/wp-content/themes/autobahn/images/font/'+txt+'.png)'});
			if(!$(this).parent().hasClass('hoverlink'))
				$(this).hover(
					function(){
						$(this).css('background-position','-'+menuitems[txt]+'px 0');
					},
					function(){
						if(($('body').hasClass('nl') && !$(this).hasClass('langNL')) || ($('body').hasClass('en') && !$(this).hasClass('langEN')))
							$(this).css('background-position','0 0');
					}
			)
		}
	});
	
	if($('.current_page_item').length > 0)
		$('.current_page_item').children('a').css('background-position','-'+menuitems[$('.current_page_item').children('a').html().toLowerCase() +'_menu']+'px 0');

	if($('.current-menu-item').length > 0)
		$('.current-menu-item').children('a').css('background-position','-'+menuitems[$('.current-menu-item').children('a').html().toLowerCase()+'_menu']+'px 0');
	
});
