var selectamm =
{
	bodyHeight: jQuery('html').height(),
	headerHeight: jQuery('header').height(),
	sectionHeight: this.bodyHeight - this.headerHeight,
	windowHeight: jQuery(window).height()
}
	
jQuery(document).ready(function($)
{
	if(jQuery('body').hasClass('home'))
	{
		/* 
		*
		*	Homepage
		*
		*/
		// preload images and content
		/*
jQuery().preload(['/img/preload.gif'], function() {
			jQuery('#intro,#over,#diensten,#contact,#map').hide();
			jQuery('#content').prepend('<div id="preload">&nbsp;</div>');
			jQuery('#preload').css('height', (jQuery('html').height() - 183) + 'px');
			
			jQuery().preload(['/img/iphone.png','/img/imac2.png','/img/galaxy_tab.png','/img/htc_desire.png','/img/welcome_bg.png','/img/homepage_headings.png','/img/over_bg.png','/img/future_glow.png'], function()
			{
				homepageInit(function() {
					jQuery('#intro,#over,#diensten,#contact,#map').show();
					jQuery('#preload').fadeOut();
				});
			});
		});
*/
		jQuery('#intro,#over,#diensten,#contact,#map').hide();
		jQuery('#content').prepend('<div id="preload">&nbsp;</div>');
		jQuery('#preload').css('height', (jQuery('html').height() - 183) + 'px');
		
		jQuery(['/img/preload.gif']).preload({
			onFinish: function(e)
			{
				jQuery(['/img/iphone.png','/img/imac2.png','/img/galaxy_tab.png','/img/htc_desire.png','/img/welcome_bg.png','/img/homepage_headings.png','/img/over_bg.png','/img/future_glow.png']).preload({
					onFinish: function()
					{
						homepageInit(function()
						{
							jQuery('#intro,#over,#diensten,#contact,#map').show();
							jQuery('#preload').fadeOut();
							openLinksNewWindow();
						});
					}
				});
			}
		});
	}
	else if(jQuery('body').hasClass('portfolio'))
	{
		/* 
		*
		*	Portfolio
		*
		*/
		portfolioHeaderInit();
		portfolioInit();
		openLinksNewWindow();
	}
	
	// General init
	selectammInit();
});

function selectammInit()
{	
	// Menu clicking
	jQuery('nav a[href*=#],a[href="/"]').click(function()
	{
		var section = jQuery(this).attr('href').replace('/','');
		
		if(!jQuery('body').hasClass('home'))
		{
			// adjust nav
			jQuery('nav .active').removeClass('active');
			
			// hide footer
			jQuery('footer').fadeOut();
			
			// hide content
			jQuery('#content').fadeOut('normal', function()
			{
				jQuery('#content').empty();
				jQuery.ajax(
				{
					url: '/ajax/get_homepage_content',
					success: function(data)
					{	
						if(!Modernizr.multiplebgs)
						{
							jQuery("#content").append(innerShiv(data, false));
						}
						else
						{
							jQuery('#content').html(data);
						}
						// slide up portfolio heading if visible
						if(jQuery('section.portfolioheading').exists() && jQuery('.portfolioheading').css('display') == 'block')
						{
							var headerHeight = jQuery('header').css('minHeight');
							jQuery('.portfolioheading').fadeOut('normal', function()
							{
								homepageInit(function()
								{
									jQuery('header').animate({height: headerHeight}, 500, function()
									{
										jQuery('section.portfolioheading').remove();
										if(section != undefined && section != '')
										{
											jQuery('body').scrollTo(section, 500);
										}
									});
									jQuery('#content').fadeIn('fast');
									openLinksNewWindow();
									jQuery('#nav ul li:first').addClass('active');
								});
						
								
							});
						}
						else
						{
							homepageInit(function()
							{
								jQuery('#content').fadeIn('fast');
								openLinksNewWindow();
								jQuery('#nav ul li:first').addClass('active');
								jQuery('body').scrollTo(section, 500);
							});
						}
						
						// jQuery('#content').hide();
						// jQuery('#content').css({height: jQuery('#portfolio').height()}, 500);
					},
					dataType: 'html'
				});
			})
		}
		else
		{
			jQuery('body').scrollTo(section, 500);
		}
		
		return false;
	});
	
	// Portfolio
	jQuery('nav .portfolio a').bind('click', function()
	{
		jQuery(window).unbind('scroll');
		
		jQuery('nav .active').removeClass('active');
		jQuery('nav .portfolio').addClass('active');
		
		jQuery('#content').animate({height: '0px'}, 1000, null, function()
		{
			jQuery('#content').empty();
			jQuery.ajax(
			{
				url: '/ajax/get_portfolio_content',
				success: function(data)
				{
					if(!Modernizr.multiplebgs)
					{
						jQuery("#content").append(innerShiv(data, false));
						jQuery("#content").css('height', 'auto');
					}
					else
					{
						jQuery('#content').html(data);
					}
					
					if(!jQuery('body').hasClass('portfolio'))
					{
						jQuery('#content').hide();
						// jQuery('#content').css({height: jQuery('#portfolio').height()}, 500);
					}
				},
				dataType: 'html'
			});
			
			if(!jQuery('body').hasClass('portfolio'))
			{
				jQuery('#header').animate({height: '551px'}, 1000, null, function()
				{
					jQuery('#header .inside').addClass('loader');
					jQuery.ajax(
					{
						url: '/ajax/get_portfolio_header',
						success: function(data)
						{
							if(!Modernizr.multiplebgs)
							{
								jQuery("#header .inside").append(innerShiv(data, false));
							}
							else
							{
								jQuery("#header .inside").append(data);
							}
							
							jQuery('.portfolioheading').hide();
							
							var bgLoad = jQuery('#portfolio_items div:first').css('background-image').replace('url("', '');
							bgLoad = bgLoad.replace('")','');
							
							jQuery([bgLoad]).preload({
								onFinish: function()
								{	
									portfolioHeaderInit();
						    
									jQuery('#portfolio_overview').fadeIn('slow');
									jQuery('.portfolioheading').fadeIn('slow', function()
									{
										jQuery('#header .inside').removeClass('loader');
									});
								}
							});
							
							jQuery('body').attr('class', 'portfolio');
							jQuery('#content').fadeIn('slow', function()
							{
								jQuery('footer').show();
							});
						},
						dataType: 'html'
					});
				});	
			}
			
			document.title = 'Portfolio';
			jQuery('#content').css('height', 'inherit');
			openLinksNewWindow();
		});
		
		return false;
	});
}

/* 
*
*	Homepage Initialisation
*
*/
function homepageInit(callback)
{
	// Check if homepage has home bodyclass
	if(!jQuery('body').hasClass('home'))
	{
		jQuery('body').attr('class', 'home');
	}
	
	// hide footer
	if(jQuery('footer').css('display') == 'block')
	{
		jQuery('footer').hide();
	}
	
	// Set variables
	$window = jQuery(window);
	jQuery('[data-type="background"]').each(function()
	{
		jQuery(this).data('title', jQuery(this).attr('data-title'));
		jQuery(this).data('Xposition', jQuery(this).attr('data-Xposition'));
		
		if(jQuery(this).attr('data-speed'))
		{
			var speed = new Array();
			speed = jQuery(this).attr('data-speed').split(',');
			jQuery(this).data('speed', speed);
		}
		
		if(jQuery(this).attr('data-offsetY'))
		{
			var offsetY = new Array();
			offsetY = jQuery(this).attr('data-offsetY').split(',');
			jQuery(this).data('offsetY', offsetY);
		}
		
		if(jQuery(this).attr('data-offsetX'))
		{
			var offsetX = new Array();
			offsetX = jQuery(this).attr('data-offsetX').split(',');
			jQuery(this).data('offsetX', offsetX);
		}
	});
	
	/* 
	*
	*	Events
	*
	*/
	jQuery('section[data-type="background"],article[data-type="background"]').each(function(){
	// $('[data-type="background"]').each(function(){
	
		var $self = jQuery(this),
			offsetCoords = $self.offset(),
			topOffset = offsetCoords.top;
		
		// IE Check 
		if(!Modernizr.multiplebgs)
		{
			var bgs = new Array(),
				bgPositions = new Array();
			
			switch(jQuery(this).attr('id'))
			{
				case 'intro':
					bgs = Array('../img/iphone.png', '../img/imac2.png', '../img/galaxy_tab.png', '../img/htc_desire.png');
					bgPositions = Array('55% 630px', '65% 0', '90% 320px', '105% 0');
					break;
				case 'over':
					bgs = Array('../img/3sixtyfive.png', '../img/studiedate.png', '../img/schipholtaxi.png', '../img/over_bg.png');
					bgPositions = Array('16% 100px', '25% -200px', '25% 300px', '15% 150px');
					break;
			}
			
			if(bgs.length > 0)
			{
				for(var i=0;i<bgs.length;i++)
				{
					var content = $self.html();
					$self.html('<div style="background: url(' + bgs[i] + ') ' + bgPositions[i] + ' no-repeat; width: 100%; height: 100%; float: left;" class="bg_' + i + '">' + content + '</div>');
				}	
			}
		}
		
	    jQuery(window).bind('scroll', function()
	    {
			if ( ($window.scrollTop() + $window.height()) > ($self.offset().top) && ( ($self.offset().top + $self.height()) > $window.scrollTop() ) )
			{
				if($window.scrollTop() > ($self.offset().top-1))
				{
					document.title = $self.data('title');
				}
				
				if($self.data('offsetX') != undefined && $self.data('offsetY') != undefined)
				{
					if (Modernizr.multiplebgs)
					{
						var coords = getBgCoords($self, $window);
						$self.css({ backgroundPosition: coords });
					}
					else
					{
						getIEBgCoords($self, $window);
					}
				}
			};
		});	
	});
	
	// Map scroll up
	jQuery('#mapshadow a').click(function()
	{
		if(jQuery(this).hasClass('up'))
		{
			jQuery('#map').css('height', (selectamm.windowHeight-30) + 'px');
			jQuery('.home').scrollTo(jQuery('#map'), {duration: 500, onAfter: function()
			{
				google.maps.event.trigger(map, 'resize');
			}});
			
			/*
jQuery('#map').animate({height: selectamm.windowHeight + 'px'}, 1, null, function()
			{
				jQuery('.home').scrollTo(jQuery('#map'), 500);
			});
*/
			
			jQuery(this).removeClass('up');
			jQuery(this).addClass('down');
		}
		else
		{
			jQuery('#map').animate({height: 200 + 'px'}, 500, null, function()
			{
				google.maps.event.trigger(map, 'resize');
			});
			jQuery(this).addClass('up');
			jQuery(this).removeClass('down');
		}
		
		// google.maps.event.trigger(map, 'resize');
		
		
		return false;
	});
	
	// Reamore links
	jQuery('a.readmore').each(function()
	{
		jQuery(this).click(function()
		{
			var $readmore = jQuery(this).parent().parent().find('div.readmore');
			if($readmore.css('display') == 'none')
			{
				$readmore.slideDown('slow');
				jQuery(this).text('Toon minder');
			}
			else
			{
				$readmore.slideUp('slow');
				jQuery(this).text('Lees verder');
			}
			
			return false;
		});
	});
	
	// Add place holders to contact form
	if(!Modernizr.input.placeholder)
	{
		addInputPlaceholders();
	}
	
	// Vcard animation
	jQuery('#vcardlink').click(function()
	{	
		jQuery(this).find('img').animate(
		{
			marginLeft: '100px',
			marginTop: '-50px',
			width: '50%',
			height: '50%'
		}, 500, function()
		{
			jQuery(this).animate(
			{
				marginTop: '450px',
				marginLeft: '200px',
				width: '0%',
				height: '0%'
			}, 300, function()
			{
				window.location = "vcard.php";
			});
		});
		
		return false;
	});
	
	// vcard 2 form
	jQuery('.contactform a').click(function()
	{
		if(jQuery('#vcard').css('display') == 'block')
		{
			var fadeDuration = 500;
			jQuery('#vcard').fadeToggle(fadeDuration, null, function()
			{
				jQuery('#contactform').fadeToggle(fadeDuration);
			});
			
			jQuery(this).text('Klik hier voor het visitekaartje');
		}
		else
		{
			jQuery('#contactform').fadeToggle(fadeDuration, null, function()
			{
				jQuery('#vcard').fadeToggle(fadeDuration);
			});
			
			jQuery(this).text('Of Klik hier voor het contactformulier');
		}
		
		return false;
	});
	
	jQuery('#contactform div.submit input').click(function()
	{
		var fields = new Array(),
			values = new Array(),
			i = 0;
		
		jQuery('#contactform .input input,#contactform .input textarea').each(function()
		{
			jQuery(this).removeClass('error');
			fields[i] = jQuery(this).attr('id');
			values[i] = jQuery(this).val();
			i++;
		});
		
		$.ajax({
			type: 'POST',
			url: '/contacts/ajax_validate',
			dataType: 'json',
			data: {
				field: fields,
				value: values
			},
			success: function(bla)
			{
				var count = 0;
				for(var key in bla)
				{
					jQuery('#' + key).addClass('error');
					// jQuery('#' + key).after('<div class="error-message" id="'+ key +'-exists">' + bla[key] + '</div>');
					count++;
				}
				
				if(count == 0)
				{
					jQuery('#contactform').addClass('done');
					jQuery('#contactform').html('<p>Dankjewel!<br /><span>We nemen zo snel mogelijk contact met je op.</span></p>');
				}
			}
		});
		
		return false;
	});
	
	if(callback != undefined)
	{
		callback();
	}
	
	var map = new initMaps();
	var latlng = new google.maps.LatLng(52.385117,4.637458);
	
	marker = new google.maps.Marker(
	{
		map: map,
		draggable: true,
		position: latlng,
		visible: true,
		icon: new google.maps.MarkerImage('http://selecta-multimedia.nl/img/marker.png', new google.maps.Size(67, 107), new google.maps.Point(0,0)),
		shadow: new google.maps.MarkerImage(
			'http://selecta-multimedia.nl/img/marker_shadow.png',
			new google.maps.Size(67, 16),
			new google.maps.Point(0,0),
			new google.maps.Point(34, 6),
			new google.maps.Size(67, 16))

	});
	
	google.maps.event.addListener(marker, 'click', toggleBounce);
}

/* 
*
*	Portfolio Header Initialisation
*
*/
function portfolioHeaderInit()
{
	var $panels = jQuery('#portfolio_items > div');
    var $container = jQuery('#portfolio_items');

    var horizontal = true;
	if (horizontal) {
        $panels.css({
            'float' : 'left',
            'position' : 'relative'
        });
		
        $container.css('width', jQuery('#portfolio_items > div:first').width() * $panels.length);
    }

    var $scroll = jQuery('#portfolio_overview').css('overflow', 'hidden');
    jQuery('#portfolio_items').css('overflow', 'hidden');
	
	var scrollOptions = {
        target: $scroll,
        items: $panels,
		axis: 'x',
		duration: 500,
		easing: 'swing',
		onBefore: function(eventoBj, targetEl, targetScroll)
		{
			jQuery('#portfolio_items .active').removeClass('active');
			var activeDiv = jQuery(targetEl).attr('id');
			jQuery('#' + activeDiv).addClass('active');
			
			if(jQuery('#portfolio_items').hasClass('zero'))
			{
				this.duration = 1;
				jQuery('#portfolio_items').removeClass('zero');
			}
			else
			{
				this.duration = 500;
				this.stop = true;
			}
		}
    };
	
    jQuery('#portfolio_overview').serialScroll(scrollOptions);
	jQuery.localScroll(scrollOptions);
    
    // Bind navigation events
    jQuery('#portfolio_prev').click(function()
	{
		$container.trigger('prev');
		return false;
	});
	
	jQuery('#portfolio_next').click(function()
	{
		$container.trigger('next');
		return false;
	});
	
	bindPortfolioItems();
}

/* 
*
*	Portfolio Content Initialisation
*
*/
function portfolioInit()
{	
	if(jQuery('#image_scroll').exists())
	{
		var $panels = jQuery('#image_scroll ul > li');
		var $container = jQuery('#image_scroll ul');
		
	    $panels.css({
	        'float' : 'left',
	        'position' : 'relative'
	    });
		
		var width = ($panels[0].offsetWidth * $panels.length);
	    $container.css('width', width + "px");
	
	    var $scroll = jQuery('#image_scroll').css('overflow', 'hidden');
	    jQuery('.screens').css('overflow', 'hidden');
		
		var scrollOptions2 = {
	        target: $scroll,
	        items: $panels,
			axis: 'x',
			duration: 500,
			easing: 'swing',
			onAfter: function(anchor, settings)
			{
				var screen = jQuery(anchor).attr('class');
				jQuery('.pointers li.active').removeClass('active');
				jQuery('.pointers li.' + screen).addClass('active');
			}
	    };
		
		// Create UL element
		jQuery('#images').append('<ul class="pointers"></ul>');
		
		// Add classes to each list item
		for(i=0; i < $panels.length; i++)
		{
			var num = i+1;
			jQuery($panels[i]).addClass("screen_" + num);
			jQuery('<li class="screen_'+num+'"><a href="#">'+num+'</a></li>').appendTo('#images .pointers');
		}
		
		// Make first item active
		jQuery('#images .pointers li:first').addClass('active');
		
		
		// Adjust width and height to the first image
		var imgWidth = jQuery('#images .screens li img:first').width();
		var imgHeight = jQuery('#images .screens li img:first').height();
		
		jQuery('body.portfolio #images .screens li img').each(function()
		{
			jQuery(this).css('width', imgWidth);
			jQuery(this).css('height', imgHeight);
		});
		
	    jQuery('#image_scroll').serialScroll(scrollOptions2);
		// jQuery.localScroll(scrollOptions2);
	    scrollOptions2.duration = 1;
	    
	    jQuery('.pointers li').each(function()
	    {
	    	jQuery(this).find('a').bind('click', function()
	    	{
	    		jQuery('.pointers li.active').removeClass('active');
	    		jQuery(this).parent().addClass('active');
	    		
	    		var goto = (jQuery(this).text() - 1);
	    		jQuery('#image_scroll ul').trigger( 'goto', [ goto ] );
	    		
	    		return false;
	    	});
	    });
	    
	   	jQuery('.screens li').each(function()
	    {
	    	jQuery(this).find('a').bind('click', function()
	    	{
	    		jQuery('#image_scroll ul').trigger('next');
	    		
	    		return false;
	    	});
	    });
	
	}
}

function bindPortfolioItems()
{
	jQuery('.kjrw a').bind('click', function()
	{
		var el = jQuery('#portfolio_items .active');
		getPortfolioItem('kjrw', el);
		return false;
	});
	jQuery('.visualinstructions a').bind('click', function()
	{
		var el = jQuery('#portfolio_items .active');
		getPortfolioItem('visualinstructions', el);
		return false;
	});
	jQuery('.pom a').bind('click', function()
	{
		var el = jQuery('#portfolio_items .active');
		getPortfolioItem('pom', el);
		return false;
	});
}

/* 
*
*	Functions
*
*/
function getBgCoords($self, $window)
{	
	var str = "";
	for(var i=0;i<$self.data('offsetX').length;i++)
	{
		var yPos = -($window.scrollTop() / $self.data('speed')[i]);
		var newyPos = $self.data('offsetY')[i] - yPos;
		str += $self.data('offsetX')[i] + " " + newyPos + "px, ";
	}
	
	if($self.attr('id') == 'over-inner')
	{
		str += "top center";
	}
	else
	{
		str += "bottom center";
	}
	
	return str;
}
function getIEBgCoords($self, $window)
{
	var speed = $self.data('speed');
	
	switch($self.attr('id'))
	{
		case 'intro':
			bgs = Array('../img/iphone.png', '../img/imac2.png', '../img/galaxy_tab.png', '../img/htc_desire.png');
			posX = Array('55%', '65%', '90%', '105%');
			posY = Array(630, 0, 320, 0);
			break;
		case 'over':
			bgs = Array('../img/3sixtyfive.png', '../img/studiedate.png', '../img/schipholtaxi.png', '../img/over_bg.png');
			posX = Array('16%', '20%', '23%', '15%');
			posY = Array(-200, 650, 250, 150);
			speed = Array(3, -6, 8);
			break;
	}
	
	if(bgs.length > 0)
	{
		for(var i=0;i<bgs.length;i++)
		{
			var yPos = -($window.scrollTop() / parseFloat(speed[i]));
			var newyPos = (posY[i] - yPos);
			var id = $self.attr('id');
			jQuery('#' + id + ' .bg_' + i).css('background', 'url(' + bgs[i] + ') ' + posX[i] + ' ' + newyPos + 'px no-repeat');
		}
	}
}
function setActiveClass(eventoBj, targetEl, targetScroll)
{
	jQuery('#portfolio_items .active').removeClass('active');
	var activeDiv = jQuery(targetEl).attr('id');
	jQuery('#' + activeDiv).addClass('active');
}

function getPortfolioItem(className, el)
{
	var scrollIndex = jQuery('#portfolio_items .' + className).index();
	var contentHeight = jQuery('#content section').height();
	
	// Check for classes 
	jQuery('#portfolio_items .details').each(function()
	{
		if(activeClass = jQuery(this).getMatchingClass('*=_active'))
		{
			jQuery('.' + activeClass).removeClass(activeClass.toString());
		}
	});
	
	jQuery('#portfolio_items').trigger('goto', [scrollIndex]);
	
	jQuery('#portfolio_items .' + className).addClass('loader');
	
	jQuery('#content').css('height', contentHeight);
	jQuery('#content section').fadeOut(300);
	
	// Load page
	jQuery.ajax({
		url: '/ajax/get_portfolio_item/' + className,
		success: function(html)
		{
			jQuery(['/img/portfolio/' + className + '_header_active.png']).preload(
			{
				onFinish: function()
				{
					// Fade out loader and fade in image
					jQuery('#portfolio_items .' + className).animate({opacity: 0}, 300, function()
					{
						var activeEl = jQuery('#portfolio_items .loader');
						jQuery(activeEl).removeClass('loader');
						jQuery(activeEl).addClass(className + '_active');
						jQuery(activeEl).animate({opacity: 1.0}, 700);
						
						if(!Modernizr.multiplebgs)
						{
							jQuery("#content").empty();
							jQuery("#content").append(innerShiv(html, false));
						}
						else
						{
							jQuery('#content').html(html);
						}
						jQuery('#content section').hide();
						jQuery('#content section').fadeIn(700);
						
						jQuery('#content').css('height', 'auto');
						document.title = jQuery('#content h2:first').text();
						portfolioInit();
						openLinksNewWindow();
						
					});
				}
			});
		}
	});
}
function openLinksNewWindow()
{
	jQuery('a').each(function()
	{
		var a = new RegExp('/' + window.location.host + '/');
		if(!a.test(this.href))
		{
			jQuery(this).click(function(event)
			{
				event.preventDefault();
				event.stopPropagation();
				window.open(this.href, '_blank');
			});
		}
	});
}
function roundNumber(number, digits)
{
	var multiple = Math.pow(10, digits);
	var rndedNum = Math.round(number * multiple) / multiple;
	return rndedNum;
}

function initMaps()
{
	var mapCenter = new google.maps.LatLng(52.387177,4.637458);
	var latlng = new google.maps.LatLng(52.388177,4.637458);
	
	// var latlng = new google.maps.LatLng(-34.397, 150.644);
	var myOptions = {
		zoom: 14,
		center: latlng,
		mapTypeId: google.maps.MapTypeId.ROADMAP,
		mapTypeControl: false
	};
	
	return new google.maps.Map(document.getElementById("mapcontent"), myOptions);
}

function toggleBounce()
{	
	if (marker.getAnimation() != null)
	{
		marker.setAnimation(null);
	}
	else
	{
		marker.setAnimation(google.maps.Animation.BOUNCE);
	}
}

/*
*
*	Add placeholders to form elements
*
*/
function addInputPlaceholders()
{
	jQuery('[placeholder]').focus(function()
	{
		var input = jQuery(this);
		if (input.val() == input.attr('placeholder'))
		{
			input.val('');
			input.removeClass('placeholder');
		}
	}).blur(function()
	{
		var input = jQuery(this);
		if (input.val() == '' || input.val() == input.attr('placeholder'))
		{
			input.addClass('placeholder');
			input.val(input.attr('placeholder'));
		}
	}).blur();
	
	jQuery('[placeholder]').parents('form').submit(function()
	{
		jQuery(this).find('[placeholder]').each(function()
		{
			var input = jQuery(this);
			if (input.val() == input.attr('placeholder'))
			{
				input.val('');
			}
		})
	});
}

/* 
*
*	jQuery Plugins
*
*/
jQuery.fn.exists = function(){return jQuery(this).length>0;}

jQuery.fn.getMatchingClass = function(selector)
{
	var regex, _class, tmp;
	if(jQuery(this)[0] != null)
	{
		tmp = jQuery(this)[0].className;
	}
	else
	{
		return false;
	}
	_class = selector;
	_class = _class.replace(/(\^|\*|\$)?=/i, '');
	_class = _class.replace(/\"/g, '');
	if (selector.indexOf('$=') != -1) {
		regex = new RegExp('[\\s]+' + _class + '$', 'g');
	} else if (selector.indexOf('^=') != -1) {
		regex = new RegExp('^' + _class + '[\\s]+', 'g');
	} else if (selector.indexOf('*=') != -1) {
		regex = new RegExp('[a-zA-z0-9_\\-]*' + _class + '[a-zA-z0-9_\\-]*', 'g');
	} else if (selector.indexOf('=') != -1) {
		regex = new RegExp('^' + _class + '$', 'g');
	} else return false;
	return tmp.match(regex);
}

/*
jQuery.fn.preload = function (images, callback) {
    var count = images.length;
    var loaded = 0;
    
    if(count === 0)
    {
        callback();
    }
    
    jQuery(images).each(function()
    {
		console.log('loaded: ' + loaded + ' - ' + this);
		
		jQuery('<img>').attr('src', this).load(function()
        {
			loaded++;
            console.log('loaded2: ' + loaded);
            if (loaded === count)
            {
                callback();
            }
        });
    });
};
*/

/*
if (typeof jQuery != "undefined")
{
	(function($){

		function preload(imgs,settings)
		{
			// settings = { each:Function, all:Function }
			if (settings instanceof Function) { settings = {all:settings}; }

			// use of typeof required
			// https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Operators/Special_Operators/Instanceof_Operator#Description
			if (typeof imgs == "string") { imgs = [imgs]; }

			var loaded = [];
			var t = imgs.length;
			var i = 0;

			for (i; i<t; i++)
			{
				var img = new Image();
				$(img).bind('load', function()
				{
					loaded.push(this);
					if (settings.each instanceof Function) { settings.each.call(this); }
					if (loaded.length>=t && settings.all instanceof Function) { settings.all.call(loaded); }
				});

				img.src = imgs[i];
			}
		}

		// extend jquery (because i love jQuery)
		$.preload = preload;

		// public
		$.fn.preload = function(settings)
		{
			settings = $.extend({},$.fn.preload.defaults,(settings instanceof Function)?{all:settings}:settings);

			this.each(function()
			{
				var elem = this;

				preload($(this).attr('src'),function()
				{
					if (settings.each instanceof Function) { settings.each.call(elem); }
				});
			});

			// declare urls and loop here (loop a second time) to prevent
			// pollution of above closure with unnecessary variables

			var urls = [];

			this.each(function()
			{
				urls.push($(this).attr('src'));
			});

			var selection = this;

			preload(urls,function()
			{
				if (settings.all instanceof Function) { settings.all.call(selection); }
			});

			return this;
		};

		// public
		$.fn.preload.defaults =
		{
			each: null // callback invoked when each image in a group loads
			, all: null // callback invoked when when the entire group of images has loaded
		};

	})(jQuery);
}
*/
;(function( $ ){

	var $preload = $.preload = function( original, settings ){
		if( original.split ) // selector
			original = $(original);

		settings = $.extend( {}, $preload.defaults, settings );
		var sources = $.map( original, function( source ){
			if( !source ) 
				return; // skip
			if( source.split ) // URL Mode
				return settings.base + source + settings.ext;
			var url = source.src || source.href; // save the original source
			if( typeof settings.placeholder == 'string' && source.src ) // Placeholder Mode, if it's an image, set it.
				source.src = settings.placeholder;
			if( url && settings.find ) // Rollover mode
				url = url.replace( settings.find, settings.replace );
			return url || null; // skip if empty string
		});

		var data = {
			loaded:0, // how many were loaded successfully
			failed:0, // how many urls failed
			next:0, // which one's the next image to load (index)
			done:0, // how many urls were tried
			/*
			index:0, // index of the related image			
			found:false, // whether the last one was successful
			*/
			total:sources.length // how many images are being preloaded overall
		};
		
		if( !data.total ) // nothing to preload
			return finish();
		
		var imgs = $(Array(settings.threshold+1).join('<img/>'))
			.load(handler).error(handler).bind('abort',handler).each(fetch);
		
		function handler( e ){
			data.element = this;
			data.found = e.type == 'load';
			data.image = this.src;
			data.index = this.index;
			var orig = data.original = original[this.index];
			data[data.found?'loaded':'failed']++;
			data.done++;

			// This will ensure that the images aren't "un-cached" after a while
			if( settings.enforceCache )
				$preload.cache.push( 
					$('<img/>').attr('src',data.image)[0]
				);

			if( settings.placeholder && orig.src ) // special case when on placeholder mode
				orig.src = data.found ? data.image : settings.notFound || orig.src;
			if( settings.onComplete )
				settings.onComplete( data );
			if( data.done < data.total ) // let's continue
				fetch( 0, this );
			else{ // we are finished
				if( imgs && imgs.unbind )
					imgs.unbind('load').unbind('error').unbind('abort'); // cleanup
				imgs = null;
				finish();
			}
		};
		function fetch( i, img, retry ){
			// IE problem, can't preload more than 15
			if( img.attachEvent /* msie */ && data.next && data.next % $preload.gap == 0 && !retry ){
				setTimeout(function(){ fetch( i, img, true ); }, 0);
				return false;
			}
			if( data.next == data.total ) return false; // no more to fetch
			img.index = data.next; // save it, we'll need it.
			img.src = sources[data.next++];
			if( settings.onRequest ){
				data.index = img.index;
				data.element = img;
				data.image = img.src;
				data.original = original[data.next-1];
				settings.onRequest( data );
			}
		};
		function finish(){
			if( settings.onFinish )
				settings.onFinish( data );
		};
	};

	 // each time we load this amount and it's IE, we must rest for a while, make it lower if you get stack overflow.
	$preload.gap = 14; 
	$preload.cache = [];
	
	$preload.defaults = {
		threshold:2, // how many images to load simultaneously
		base:'', // URL mode: a base url can be specified, it is prepended to all string urls
		ext:'', // URL mode:same as base, but it's appended after the original url.
		replace:'' // Rollover mode: replacement (can be left empty)
		/*
		enforceCache: false, // If true, the plugin will save a copy of the images in $.preload.cache
		find:null, // Rollover mode: a string or regex for the replacement
		notFound:'' // Placeholder Mode: Optional url of an image to use when the original wasn't found
		placeholder:'', // Placeholder Mode: url of an image to set while loading
		onRequest:function( data ){ É }, // callback called every time a new url is requested
		onComplete:function( data ){ É }, // callback called every time a response is received(successful or not)
		onFinish:function( data ){ É } // callback called after all the images were loaded(or failed)
		*/
	};

	$.fn.preload = function( settings ){
		$preload( this, settings );
		return this;
	};

})( jQuery );
