$(function() {
	// if Mac, replace .exe with .dmg
 	if (navigator.userAgent.indexOf("Macintosh") !== -1) {
		var $tvEl = $('#footer a.tv');
		$tvEl.attr('href', $tvEl.attr('href').replace('.exe', '.zip'));
	}

	$('.inheritedlink').live('click', function(){
		var inheritedlinkClass = $('.skill.active').attr('class');
		var inheritedlinkClassStripped = inheritedlinkClass.replace('skill', '').replace('active', '');
		inheritedlinkClassStripped = $.trim(inheritedlinkClassStripped);
		var inheritedlink = $('.desc.' + inheritedlinkClassStripped).find('a.linktoinherit').attr('href');
		window.location.href = inheritedlink;

		return false;
	});

	// Assign links to dropdown menu, mobile
	doMobileStuff();
	
	$('#main img.size-thumbnail').parent().attr('rel', 'shadowbox[gallery]');
	
	Shadowbox.init({
		'overlayColor' : '#132531',
		'overlayOpacity' : '0.93'
	});
	
	$('#flickrImages a,#thumbnailsSmall a,#thumbnails a,a.touch').touchGallery();
	
	$('#flickrImages li:last-child a').addClass('cutoff');
		
	// Fade in project description
	$('#projects article').bind({
		mouseenter: function() {
			$(this).find('a.desc').fadeIn(300);
			
		},
		mouseleave: function() {
			$(this).find('a.desc').fadeOut(300);		
		}
	});
	
	//Show tweets
	$("#twitterBox").tweet({
		username: "interactieit",
		count: 3,
		loading_text: "tweets laden..."
	});

	$('a.button.contact').bind('click', function() {
		goToContactForm();
		
		return false;
	});

	$('li.prosjekt', $('#prosjekter')).mouseenter(function(){
		img = $(this).find('img:first');
		imgSRC = img.attr('src');
		imgREL = img.attr('rel');
		img.attr({'src' : imgREL, 'rel' : imgSRC});
		
	}).mouseleave(function(){
		img.attr({'rel' : imgREL, 'src' : imgSRC});
	});
	
	// Scroll to top
	$('a.top').click(function() {
		$('html,body').animate({scrollTop:0});
		return false;
	});

	// Tooltips
	$(function(){
		$("article.tooltip,a.tooltip,span.tooltip").not('.noclick').tipTip({
			defaultPosition: 'top',
			delay: 100,
			fadeIn: 300
		});
	});
	
	$('body.home').keydown(function(e){
		if(e.keyCode == 27){ 
			slideUpSkill();
		}
	});
	
	// Filter products	
	// if ($.browser.msie && $.browser.version < 9) {
		$('body.page-id-6 .skill').bind('click', function() {
			window.location.href = $(this).attr('rev');
		});
		// });
	// } else {
	// 		var $filterType = $('body.page-id-6 .skill');
	// 		var $applications = $('#products');
	// 
	// 		var $data = $applications.clone();
	// 	
	// 		if ($applications.length) {
	// 			var hash = window.location.hash.replace('#', '');
	// 		
	// 			if (hash) {
	// 				$('#products').fadeIn('fast');
	// 				// $('article.product#' + hash).addClass('highlight');
	// 			}		
	// 		
	// 			$filterType.click(function(e) {		
	// 				$filterType.removeClass('active').attr('rev', 'inactive');
	// 		
	// 				$(this).addClass('active').attr('rev', 'no');
	// 		
	// 				var skillpos = $('h1.subTitle').offset().top;
	// 			
	// 				$('html,body').animate({scrollTop: skillpos });
	// 
	// 
	// 				var $filteredData = $data.find('article[data-type~=' + $(this).attr('data-id') + ']');
	// 
	// 				if ($applications.is(':visible')) {
	// 					var dur = 650;
	// 				} else {
	// 					var dur = 0;
	// 				}
	// 			
	// 					// $applications.show();
	// 			
	// 					// $applications.show();
	// 				$applications.quicksand($filteredData, {
	// 					duration: dur,
	// 					adjustHeight: 'auto'
	// 				}, function() {
	// 					$applications.fadeIn();
	// 				});
	// 
	// 			    e.preventDefault(); 
	// 	
	// 			});
	// 		}
	// 	}
	
	// Download apps from project page	
	var $selectPlatform = $('#appDownload');
	
	if ($selectPlatform.length) {
		var $appDownloadButton = $('#appDownloadButton');
	
		$selectPlatform.bind('change', function() {
			var $platformLink = $('option:selected', $(this)).attr('value');
			
			if ($platformLink != '') {		
				$appDownloadButton.attr('rel', $platformLink).removeAttr('disabled');
			} else {
				$appDownloadButton.attr('disabled', 'disabled');
			}
		});
		
		$appDownloadButton.bind('click', function() {
			window.open($(this).attr('rel'));
			return false;
		})
	}	
	
	// Placeholder fix for IE
	if ($.browser.msie && $('body.home').length) {
		var elementsToTarget = 'input[type=text], textarea, input[type=email]';
		$(elementsToTarget).each(function(){
			var placeholder = $(this).attr('placeholder');
			$(this).val(placeholder);
		}).bind('focus', function(){
			if($(this).val() == $(this).attr('placeholder')){
				$(this).val(null);
			}
		}).bind('focusout', function(){
			if($(this).val() == ""){
				$(this).val($(this).attr('placeholder'));
			}
		});
	}
	
	// External links
	$('a[rel=external]').bind('click', function() {
		window.open(this.href);
		return false;
	});
		
	var timer;
	
	// Windows resize
	$(window).resize(function() {
		if (timer) { clearTimeout(timer); }
		timer = setTimeout(toggleDisplay, 100);
	})
	
	// Scroll function for local links
	$(".scroll").click(function(event){
		//prevent the default action for the click event
		event.preventDefault();

		//get the full url - like mysitecom/index.htm#home
		var full_url = this.href;

		//split the url by # and get the anchor target name - home in mysitecom/index.htm#home
		var parts = full_url.split("#");
		var trgt = parts[1];

		//get the top offset of the target anchor
		var target_offset = $("#"+trgt).offset();
		var target_top = target_offset.top-100;

		//goto that anchor by setting the body scroll top to anchor top
		$('html, body').animate({scrollTop:target_top}, 500);
	});
	
});

function isValidEmailAddress(emailAddress) {
	var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
	return pattern.test(emailAddress);
};

function toggleDisplay() {	
	doMobileStuff();
}

function doMobileStuff() {	
	var width = $(window).width(),
		$selectMobilenav = $('#mobileNav'),
		options = '',
		currentUrl = location.href;

	if (width < 768 && $selectMobilenav.html() == '') {
		$('#projects article').unbind('mouseenter mouseleave');

		$('#footer a.phone').attr('href', 'tel:0643198314');
				
		$('#nav a').each(function() {
			var link = $(this).attr('href'),
				title = $(this).text(),
				selected = false;
			
			if (link == currentUrl) {
				selected = ' selected="selected"'; 
			}
	
			options += '<option value="' + link + '" ' + selected + '>' + title + '</option>';
		});
	
		$selectMobilenav.append(options).bind('change', function() {
			var $pageLink = $('option:selected', $(this)).attr('value');
		
			if ($pageLink != '') {
				window.location.href = $pageLink;
				return false;
			}
		
		});
	}
}

(function($) {
  $.fn.sorted = function(customOptions) {
    var options = {
      reversed: false,
      by: function(a) { return a.text(); }
    };
    $.extend(options, customOptions);
    $data = $(this);
    arr = $data.get();
    arr.sort(function(a, b) {
      var valA = options.by($(a));
      var valB = options.by($(b));
      if (options.reversed) {
        return (valA < valB) ? 1 : (valA > valB) ? -1 : 0;				
      } else {		
        return (valA < valB) ? -1 : (valA > valB) ? 1 : 0;	
      }
    });
    return $(arr);
  };
})(jQuery);

