//set default view mode
	$defaultViewMode="full"; //full (fullscreen background), fit (fit to window), original (no scale)
	//cache vars
	$bg=$("#bg");
	$bgimg=$("#bg #bgimg");
	$preloader=$("#preloader");
	$outer_container=$("#outer_container");
	$outer_container_a=$("#outer_container a.thumb_link");
	$toolbar=$("#toolbar");
	$nextimage_tip=$("#nextimage_tip");
	
	var cat_menu_open = 0;

$(document).ready(function()
{
	$('#content-wrapper').css("left",($(window).width()/2)-($('#content-wrapper').width()/2));
	
	$("#search label").inFieldLabels();
	
	$('#cat_fotos_home div').click(function(){
		if($(this).attr("rel") == "opened")
		{
			SlidePanels("close");
			$(this).attr("rel","");
		}else{
			SlidePanels("open");
			$(this).attr("rel","opened");
		}
	}
	);
	
	$('#search_submit').click(function(){
		if($('#q').val().length>0)
		{
			window.location = 'search.php?q=' + $('#q').val();
		}
	});
	$('#q').keypress(function(event) {
	  if (event.which == '13') {
		 $('#search_submit').trigger('click');
	   }
	});
	
	$('#bg_options').click(function(){
		$('#bg_config').dialog({
			modal: true,
			width: '600px',
			minheight: '600px',
			buttons: {
				'Dynamische achtergrond': function(){
					$('#bg_config').html("<p>Uw voorkeur wordt nu opgeslagen.</p><p><img src='css_imgs/ajax-loader.gif'></p>");
					$.post('process_bg_prefs.php',{choice: "dynamic"},function(data){
						$('#bg_config').html("<p>Uw voorkeur is opgeslagen.</p>");
						$('#bg_config').dialog({
							modal: true,
							width: '600px',
							minheight: '400px',
							buttons: {
								'Ok': function(){
									$(this).dialog('close');
								}
							},
							close: function(){
								window.location = window.location;
							}
						});
					});
				},
				'Vaste achtergrond': function()
				{
					$('#bg_config').html("<p>Uw voorkeur wordt nu opgeslagen.</p><p><img src='css_imgs/ajax-loader.gif'></p>");
					$.post('process_bg_prefs.php',{choice: "fixed"},function(data){
						$('#bg_config').html("<p>Uw voorkeur is opgeslagen.</p>");
						$('#bg_config').dialog({
							modal: true,
							width: '600px',
							minheight: '400px',
							buttons: {
								'Ok': function(){
									$(this).dialog('close');
								}
							},
							close: function(){
								window.location = window.location;
							}
						});
					});
				}
			}
		});
	});

});
$(window).load(function() {

	$toolbar.data("imageViewMode",$defaultViewMode); //default view mode
	ImageViewMode($toolbar.data("imageViewMode"));
	//cache vars
	$customScrollBox=$("#customScrollBox");
	$customScrollBox_container=$("#customScrollBox .container");
	$customScrollBox_content=$("#customScrollBox .content");
	$dragger_container=$("#dragger_container");
	$dragger=$("#dragger");
	
	CustomScroller();
	
	//cache vars 2
	/*$customScrollBox2=$("#customScrollBox2");
	$customScrollBox_container2=$("#customScrollBox2 .container");
	$customScrollBox_content2=$("#customScrollBox2 .content");
	$dragger_container2=$("#dragger_container2");
	$dragger2=$("#dragger2");*/
	
	//CustomScroller2();
	
	function CustomScroller(){
		outerMargin=0;
		innerMargin=20;
		$customScrollBox.height($(window).height()-outerMargin);
		$dragger_container.height($(window).height()-innerMargin);
		visibleHeight=$(window).height()-outerMargin;
		if($customScrollBox_container.height()>visibleHeight){ //custom scroll depends on content height
			$dragger_container,$dragger.css("display","block");
			totalContent=$customScrollBox_content.height();
			draggerContainerHeight=$(window).height()-innerMargin;
			animSpeed=400; //animation speed
			easeType="easeOutCirc"; //easing type
			bottomSpace=1.05; //bottom scrolling space
			targY=0;
			draggerHeight=$dragger.height();
			$dragger.draggable({ 
				axis: "y", 
				containment: "parent", 
				drag: function(event, ui) {
					Scroll();
				}, 
				stop: function(event, ui) {
					DraggerOut();
				}
			});

			//scrollbar click
			$dragger_container.click(function(e) {
				var mouseCoord=(e.pageY - $(this).offset().top);
				var targetPos=mouseCoord+$dragger.height();
				if(targetPos<draggerContainerHeight){
					$dragger.css("top",mouseCoord);
					Scroll();
				} else {
					$dragger.css("top",draggerContainerHeight-$dragger.height());
					Scroll();
				}
			});

			//mousewheel
			$(function($) {
				$customScrollBox.bind("mousewheel", function(event, delta) {
					vel = Math.abs(delta*10);
					$dragger.css("top", $dragger.position().top-(delta*vel));
					Scroll();
					if($dragger.position().top<0){
						$dragger.css("top", 0);
						$customScrollBox_container.stop();
						Scroll();
					}
					if($dragger.position().top>draggerContainerHeight-$dragger.height()){
						$dragger.css("top", draggerContainerHeight-$dragger.height());
						$customScrollBox_container.stop();
						Scroll();
					}
					return false;
				});
			});

			function Scroll(){
				var scrollAmount=($("#customScrollBox .content").height()-(visibleHeight/bottomSpace))/(draggerContainerHeight-draggerHeight);
				var draggerY=$dragger.position().top;
				targY=-draggerY*scrollAmount;
				var thePos=$customScrollBox_container.position().top-targY;
				$customScrollBox_container.stop().animate({top: "-="+thePos}, animSpeed, easeType); //with easing
			}

			//dragger hover
			$dragger.mouseup(function(){
				DraggerOut();
			}).mousedown(function(){
				DraggerOver();
			});

			function DraggerOver(){
				$dragger.css("background", "url(css_imgs/round_custom_scrollbar_bg_over.png)");
			}

			function DraggerOut(){
				$dragger.css("background", "url(css_imgs/round_custom_scrollbar_bg.png)");
			}
		} else { //hide custom scrollbar if content is short
			$dragger,$dragger_container.css("display","none");
		}
	}
	
	//resize browser window functions
	$(window).resize(function() {
		FullScreenBackground("#bgimg"); //scale bg image
		$dragger.css("top",0); //reset content scroll
		$customScrollBox_container.css("top",0);
		$customScrollBox.unbind("mousewheel");
		$('#content-wrapper').css("left",($(window).width()/2)-($('#content-wrapper').width()/2));
		CustomScroller();
		//CustomScroller2();
		$('#maincontent.content-box').height($(window).height()-220-20);
		$('#maincontent.content-box .viewport').height($(window).height()-220-20-10);
		$('#maincontent.content-box').tinyscrollbar({sizethumb: 'auto' });
	});
	$('#content-wrapper').css("left",($(window).width()/2)-($('#content-wrapper').width()/2));
	LargeImageLoad($bgimg);
});
	
	//loading bg image
	$bgimg.load(function() {
		$('#content-wrapper').css("left",($(window).width()/2)-($('#content-wrapper').width()/2));
		LargeImageLoad($(this));
	});
	
	function LargeImageLoad($this){
		$preloader.fadeOut("fast"); //hide preloader
		$('#content-wrapper').css("left",($(window).width()/2)-($('#content-wrapper').width()/2));
		$this.removeAttr("width").removeAttr("height").css({ width: "", height: "" }); //lose all previous dimensions in order to rescale new image data
		$bg.data("originalImageWidth",$this.width()).data("originalImageHeight",$this.height());
		if($bg.data("newTitle")){
			$this.attr("title",$bg.data("newTitle")); //set new image title attribute
		}
		FullScreenBackground($this); //scale new image
		$bg.data("nextImage",$($outer_container.data("selectedThumb")).next().attr("href")); //get and store next image
		if(typeof itemIndex!="undefined"){
			if(itemIndex==lastItemIndex){ //check if it is the last image
				$bg.data("lastImageReached","Y");
				$bg.data("nextImage",$outer_container_a.first().attr("href")); //get and store next image
			} else {
				$bg.data("lastImageReached","N");
			}
		} else {
			$bg.data("lastImageReached","N");
		}
		$this.fadeIn("slow"); //fadein background image
		if($bg.data("nextImage") || $bg.data("lastImageReached")=="Y"){ //don't close thumbs pane on 1st load
			SlidePanels("close"); //close the left pane
		}
		NextImageTip();
		
	}

	//slide in/out left pane
	$("#arrow_indicator").click(function(){
		if($(this).attr("rel") == "opened")
		{
			SlidePanels("close");
			$(this).attr("rel","");
		}else{
			SlidePanels("open");
			$(this).attr("rel","opened");
		}
	}
	);
	
	//Clicking on thumbnail changes the background image
	$outer_container_a.click(function(event){
		event.preventDefault();
		var $this=this;
		$bgimg.css("display","none");
		$preloader.fadeIn("fast"); //show preloader
		//style clicked thumbnail
		$outer_container_a.each(function() {
    		$(this).children(".selected").css("display","none");
  		});
		$(this).children(".selected").css("display","block");
		//get and store next image and selected thumb 
		$outer_container.data("selectedThumb",$this); 
		$bg.data("nextImage",$(this).next().attr("href")); 	
		$bg.data("newTitle",$(this).children("img").attr("title")); //get and store new image title attribute
		itemIndex=getIndex($this); //get clicked item index
		lastItemIndex=($outer_container_a.length)-1; //get last item index
		$bgimg.attr("src", "").attr("src", $this); //switch image
	}); 

	//clicking on large image loads the next one
	$bgimg.click(function(event){
		var $this=$(this);
		if($bg.data("nextImage")){ //if next image data is stored
			$this.css("display","none");
			$preloader.fadeIn("fast"); //show preloader
			$($outer_container.data("selectedThumb")).children(".selected").css("display","none"); //deselect thumb
			if($bg.data("lastImageReached")!="Y"){
				$($outer_container.data("selectedThumb")).next().children(".selected").css("display","block"); //select new thumb
			} else {
				$outer_container_a.first().children(".selected").css("display","block"); //select new thumb - first
			}
			//store new selected thumb
			var selThumb=$outer_container.data("selectedThumb");
			if($bg.data("lastImageReached")!="Y"){
				$outer_container.data("selectedThumb",$(selThumb).next()); 
			} else {
				$outer_container.data("selectedThumb",$outer_container_a.first()); 
			}
			$bg.data("newTitle",$($outer_container.data("selectedThumb")).children("img").attr("title")); //get and store new image title attribute
			if($bg.data("lastImageReached")!="Y"){
				itemIndex++;
			} else {
				itemIndex=0;
			}
			$this.attr("src", "").attr("src", $bg.data("nextImage")); //switch image
		}
	});
	
	//function to get element index (fuck you IE!)
	function getIndex(theItem){
		for ( var i = 0, length = $outer_container_a.length; i < length; i++ ) {
			if ( $outer_container_a[i] === theItem ) {
				return i;
			}
		}
	}
	
	
	

	//next image balloon tip
	function NextImageTip(){
		if($bg.data("nextImage")){ //check if this is the first image
			$nextimage_tip.stop().css("right",20).fadeIn("fast").fadeOut(2000,"easeInExpo",function(){$nextimage_tip.css("right",$(window).width());});
		}
	}

	//slide in/out left pane function
	function SlidePanels(action){
		var speed=900;
		var easing="easeInOutExpo";
		if(action=="open"){
			//$("#arrow_indicator").fadeTo("fast",0);
			$("#arrow_indicator").html('<img src="css_imgs/sw_arrow_indicator_mirror.png" width="50" height="50"  />');
			$outer_container.stop().animate({left: 0}, speed,easing);
			$bg.stop().animate({left: 585}, speed,easing);
		} else {
			$("#arrow_indicator").html('<img src="css_imgs/sw_arrow_indicator.png" width="50" height="50"  />');
			$outer_container.stop().animate({left: -710}, speed,easing);
			$bg.stop().animate({left: 0}, speed,easing,function(){//$("#arrow_indicator").fadeTo("fast",1);
			});
		}
	}

//Image scale function
function FullScreenBackground(theItem){
	var winWidth=$(window).width();
	var winHeight=$(window).height();
	var imageWidth=$(theItem).width();
	var imageHeight=$(theItem).height();
	if($toolbar.data("imageViewMode")!="original"){ //scale
		$(theItem).removeClass("with_border").removeClass("with_shadow"); //remove extra styles of orininal view mode
		var picHeight = imageHeight / imageWidth;
		var picWidth = imageWidth / imageHeight;
		if($toolbar.data("imageViewMode")!="fit"){ //image view mode: full
			if ((winHeight / winWidth) < picHeight) {
				$(theItem).css("width",winWidth).css("height",picHeight*winWidth);
			} else {
				$(theItem).css("height",winHeight).css("width",picWidth*winHeight);
			};
		} else { //image view mode: fit
			if ((winHeight / winWidth) > picHeight) {
				$(theItem).css("width",winWidth).css("height",picHeight*winWidth);
			} else {
				$(theItem).css("height",winHeight).css("width",picWidth*winHeight);
			};
		}
		//center it
		$(theItem).css("margin-left",((winWidth - $(theItem).width())/2)).css("margin-top",((winHeight - $(theItem).height())/2));
		
	} else { //no scale
		//add extra styles for orininal view mode
		$(theItem).addClass("with_border").addClass("with_shadow");
		//set original dimensions
		$(theItem).css("width",$bg.data("originalImageWidth")).css("height",$bg.data("originalImageHeight"));
		//center it
		$(theItem).css("margin-left",((winWidth-$(theItem).outerWidth())/2)).css("margin-top",((winHeight-$(theItem).outerHeight())/2));
	}
}

//image view mode function - full or fit
function ImageViewMode(theMode){
	$toolbar.data("imageViewMode", theMode); //store new mode
	FullScreenBackground($bgimg); //scale bg image
	//re-style button
	if(theMode=="full"){
		$toolbar.html("<span class='lightgrey'>IMAGE VIEW MODE &rsaquo;</span> FULL");
	} else if(theMode=="fit") {
		$toolbar.html("<span class='lightgrey'>IMAGE VIEW MODE &rsaquo;</span> FIT");
	} else {
		$toolbar.html("<span class='lightgrey'>IMAGE VIEW MODE &rsaquo;</span> ORIGINAL");
	}
}

$('#expand_cats').click(function(){
	if(cat_menu_open == 0)
	{
		$('#cat_menu').show("blind","slow");
		cat_menu_open = 1;
	}else{
		$('#cat_menu').hide("blind","slow");
		cat_menu_open = 0;
	}
});

$(document).ready(function(){
	$('a[rel=fancybox]').fancybox({'type' : 'image'});
	$('a[rel=gr_img]').fancybox({
		margin: 14
	});
	$('.load_more').click(function(){
		var cat_id = $(this).attr('rel');
		var pic_ids = new Array(3);
		var i = 0;
		$(this).parent('div').children('a[rel=gr_img]').each(function(){
			pic_ids[i] = $(this).attr('id');
			i++;
		});
		if($('div #cat_' + cat_id + ' span').html().length == 0)
		{
			$('div #cat_' + cat_id + ' .loader').fadeIn();
			$.post('ajax.php',{category_id: cat_id, id1: pic_ids[0], id2: pic_ids[1], id3: pic_ids[2]},function(data){
				if(data)
				{
					$('div #cat_' + cat_id + ' .loader').fadeOut();
					$('div #cat_' + cat_id + ' span').html(data);
					$('div #cat_' + cat_id + ' span').fadeIn();
					$('a[rel=gr_img]').fancybox({
						margin: 14
					});
				}
			});
			$('div #cat_' + cat_id + ' .load_more').fadeOut("fast",function(){
				$('div #cat_' + cat_id + ' .load_less').fadeIn();
			});
		}else{
			$('div #cat_' + cat_id + ' span').fadeIn();
			$('div #cat_' + cat_id + ' .load_more').fadeOut("fast",function(){
				$('div #cat_' + cat_id + ' .load_less').fadeIn();
			});
		}
	});
	$('.load_less').click(function(){
		var cat_id = $(this).attr('rel');
		$('div #cat_' + cat_id + ' span').fadeOut();
		$('div #cat_' + cat_id + ' .load_more').fadeIn("fast",function(){
			$('div #cat_' + cat_id + ' .load_less').fadeOut();
		});
		
	});
	
	$('#maincontent.content-box').height($(window).height()-220-20);
	$('#maincontent.content-box .viewport').height($(window).height()-220-20-10);
	$('#maincontent.content-box').tinyscrollbar({sizethumb: 'auto' });
});

//preload script images
var images=["css_imgs/ajax-loader_dark.gif","css_imgs/round_custom_scrollbar_bg_over.png"];
$.each(images, function(i) {
  images[i] = new Image();
  images[i].src = this;
});

//JQUERY INFIELD LABELS
/*
 * In-Field Label jQuery Plugin
 * http://fuelyourcoding.com/scripts/infield.html
 *
 * Copyright (c) 2009 Doug Neiner
 * Dual licensed under the MIT and GPL licenses.
 * Uses the same license as jQuery, see:
 * http://docs.jquery.com/License
 *
 * @version 0.1
 */
(function($){
	
    $.InFieldLabels = function(label,field, options){
        // To avoid scope issues, use 'base' instead of 'this'
        // to reference this class from internal events and functions.
        var base = this;
        
        // Access to jQuery and DOM versions of each element
        base.$label = $(label);
        base.label = label;

 		base.$field = $(field);
		base.field = field;
        
		base.$label.data("InFieldLabels", base);
		base.showing = true;
        
        base.init = function(){
			// Merge supplied options with default options
            base.options = $.extend({},$.InFieldLabels.defaultOptions, options);

			// Check if the field is already filled in
			if(base.$field.val() != ""){
				base.$label.hide();
				base.showing = false;
			};
			
			base.$field.focus(function(){
				base.fadeOnFocus();
			}).blur(function(){
				base.checkForEmpty(true);
			}).bind('keydown.infieldlabel',function(e){
				// Use of a namespace (.infieldlabel) allows us to
				// unbind just this method later
				base.hideOnChange(e);
			}).change(function(e){
				base.checkForEmpty();
			}).bind('onPropertyChange', function(){
				base.checkForEmpty();
			});
        };

		// If the label is currently showing
		// then fade it down to the amount
		// specified in the settings
		base.fadeOnFocus = function(){
			if(base.showing){
				base.setOpacity(base.options.fadeOpacity);
			};
		};
		
		base.setOpacity = function(opacity){
			base.$label.stop().animate({ opacity: opacity }, base.options.fadeDuration);
			base.showing = (opacity > 0.0);
		};
		
		// Checks for empty as a fail safe
		// set blur to true when passing from
		// the blur event
		base.checkForEmpty = function(blur){
			if(base.$field.val() == ""){
				base.prepForShow();
				base.setOpacity( blur ? 1.0 : base.options.fadeOpacity );
			} else {
				base.setOpacity(0.0);
			};
		};
		
		base.prepForShow = function(e){
			if(!base.showing) {
				// Prepare for a animate in...
				base.$label.css({opacity: 0.0}).show();
				
				// Reattach the keydown event
				base.$field.bind('keydown.infieldlabel',function(e){
					base.hideOnChange(e);
				});
			};
		};

		base.hideOnChange = function(e){
			if(
				(e.keyCode == 16) || // Skip Shift
				(e.keyCode == 9) // Skip Tab
			  ) return; 
			
			if(base.showing){
				base.$label.hide();
				base.showing = false;
			};
			
			// Remove keydown event to save on CPU processing
			base.$field.unbind('keydown.infieldlabel');
		};
      
		// Run the initialization method
        base.init();
    };
	
    $.InFieldLabels.defaultOptions = {
        fadeOpacity: 0.5, // Once a field has focus, how transparent should the label be
		fadeDuration: 300 // How long should it take to animate from 1.0 opacity to the fadeOpacity
    };
	

    $.fn.inFieldLabels = function(options){
        return this.each(function(){
			// Find input or textarea based on for= attribute
			// The for attribute on the label must contain the ID
			// of the input or textarea element
			var for_attr = $(this).attr('for');
			if( !for_attr ) return; // Nothing to attach, since the for field wasn't used
			
			
			// Find the referenced input or textarea element
			var $field = $(
				"input#" + for_attr + "[type='text']," + 
				"input#" + for_attr + "[type='password']," + 
				"textarea#" + for_attr
				);
				
			if( $field.length == 0) return; // Again, nothing to attach
			
			// Only create object for input[text], input[password], or textarea
            (new $.InFieldLabels(this, $field[0], options));
        });
    };
	
})(jQuery);
