$.amy = {};
$.amy.globalMedia = [];

var offset = 0;
var i = 0;

$(document).ready(function() {
	function returnMedia() {
    	$('#result').empty();
    	$('#result').removeData('masonry');
    	$('#result').append($($.amy.globalMedia)).masonry( { columnWidth: 100 }, function() { });
    	//$('.tag').corner("8px");
    	$.amy.globalMedia = [];
    }
	
	$('a.meerladen').click(function(e){
		var terms = split( $("#search_input").val() );
		offset = offset + 50;
		terms.pop();
		terms.push( e.target.title );
		terms.push( "" );
 		dataString = terms.join( ", " );
		$.ajax({
  			url: encodeURI('http://www.weloveitwhenaplancomestogether.com/amy/api/search/keywords/'+ offset +'/50/' + dataString),
  			dataType: 'json',
  			error: function(XMLHttpRequest, textStatus, data) { },
  			success: function(data, textStatus, XMLHttpRequest) {
  				$('div#search').html("");
  				$(data.keys).each(function() { loadTags(this); });
  				$(data.media).each(function() { loadMedia(this.media_id); });
  				$('#result').append( $($.amy.globalMedia) ).masonry( { appendedContent: $($.amy.globalMedia) } , function() { });
  				//$('.tag').corner("8px");
  				$.amy.globalMedia = [];
  				//returnMedia();
  			}	
		});
	});
	
	
	$('.tag').live('click', function(e) {
 		e.preventDefault();			
 		$.manageAjax.clear('someAjaxProfileName', {shouldAbort: true});
 		$('#result').empty();
    	$('#result').removeData('masonry');
 		offset = 0;
 		if(!$(this).hasClass("tag_active")) {
 		var terms = split( $("#search_input").val() );
		terms.pop();
		terms.push( e.target.title );
		terms.push( "" );
 		dataString = terms.join( ", " );
 		$("#search_input").val(dataString);
 			$.ajax({
  				url: encodeURI('http://www.weloveitwhenaplancomestogether.com/amy/api/search/keywords/0/50/' + dataString),
  				dataType: 'json',
  				error: function(XMLHttpRequest, textStatus, data) { },
  				success: function(data, textStatus, XMLHttpRequest) {
  					$('div#search').html("");
  					
  					$(data.keys).each(function() { loadTags(this); });
  					$(data.media).each(function() { loadMedia(this.media_id); });
  				}	
			});
 		} else {
 			var terms = split( $("#search_input").val() );
 			terms = removeByElement( terms, e.target.title );
 			dataString = terms.join( ", " );
 			$("#search_input").val(dataString);
 			$.ajax({
  				url: encodeURI('http://www.weloveitwhenaplancomestogether.com/amy/api/search/keywords/0/50/' + dataString),
  				dataType: 'json',
  				error: function(XMLHttpRequest, textStatus, data) { },
  				success: function(data, textStatus, XMLHttpRequest) {
  					$('div#search').html("");
  					
  					$(data.keys).each(function() { loadTags(this); });
  					$(data.media).each(function() { loadMedia(this.media_id); });
  				}	
			});
 		}
 		return false;
	});

	$.ajax({
  		url: encodeURI('http://www.weloveitwhenaplancomestogether.com/amy/api/search/keywords/0/50/'),
  		dataType: 'json',
  		error: function(XMLHttpRequest, textStatus, data) { },
  		success: function(data, textStatus, XMLHttpRequest) {
  			$('div#search').html("");
  			
  			/*logo vooraan toevoegen
  			var temp = $('<div id="weloveit" class="media_item"><h1>We love it<br />when a<br />plan comes<br />together.</h1>Ontwerp.Studio.<br /><br /><br /><a href="http://www.andriesreitsma.nl" target="_blank">Andries Reitsma</a><br/><a href="http://www.eslitapilatu.nl" target="_blank">Esli Tapilatu</a><br/><a href="http://www.fabianhijlkema.nl" target="_blank">Fabian Hijlkema</a><br/><br />Langestraat 144-7<br />9712 MH Groningen<br />the Netherlands<br /><br /><a href="mailto:hello@weloveitwhenaplancomestogether.com">E-mail us</a></div>');
  			var temp2 = temp.get(0);
  			$.amy.globalMedia.push( temp2 );*/
  			
  			$(data.keys).each(function() { loadTags(this); });
  			$(data.media).each(function() {
  				loadMedia(this.media_id);
  			});
  		}
	});

	function removeByElement(arrayName,arrayElement) {
    	for(var i=0; i<arrayName.length;i++ ) { 
        	if(arrayName[i]==arrayElement)
            arrayName.splice(i,1); 
      	} 
      	return arrayName;
	}


	$("#search_input").watermark("Search by entering keywords:");
	
    $('#search_input').bind('keydown', function(e) {
    	var dataString = $(this).val();
       	if(e.keyCode==32 || e.keyCode==8) {
       			$.ajax({
  					url: encodeURI('http://www.weloveitwhenaplancomestogether.com/amy/api/search/keywords/0/50/' + dataString),
  					dataType: 'json',
  					error: function(XMLHttpRequest, textStatus, data) { },
  					success: function(data, textStatus, XMLHttpRequest) {
  						$('div#search').html("");
  						$(data.keys).each(function() { loadTags(this); });
  						$(data.media).each(function() { loadMedia(this.media_id); });
  						//returnMedia();
  					}	
				});
       	}
       	
    });
    
    //create an ajaxmanager named someAjaxProfileName
	var someManagedAjax = $.manageAjax.create('someAjaxProfileName', {
		queue: true, 
		cacheResponse: true,
		abortOld: true
	});
    
    function loadMedia(media_id, footer_show) {
    	$.manageAjax.add('someAjaxProfileName', {
  			url: encodeURI('http://www.weloveitwhenaplancomestogether.com/amy/api/media/show/' + media_id),
  			dataType: 'json',
  			async: true,
  			error: function(XMLHttpRequest, textStatus, data) {
  			},
  			complete: function(XMLHttpRequest, textStatus) { 
  				$('#result').append( $($.amy.globalMedia) ).masonry( { columnWidth: 70, appendedContent: $($.amy.globalMedia) } , function() { });
  				//$('.tag').corner("8px");
  				$.amy.globalMedia = [];
  				$.fn.showFooter();
 			},
  			success: function(data, textStatus, XMLHttpRequest) {
  				var tags = "";
  				var activetags = Array();
  				activetags.pop();
  				//Get active tags
  				$("div#search > .tag").each(function(index) {
  					activetags.push($(this).text());
  				});
  				$.each(data.combine, function(key, val) {
  					if(jQuery.inArray(val,activetags) > -1) {
						tags = tags + '<a class="tag tag'+key+' tag_active" title="' + val + '" href="">' + val + '</a>';
					} else {
    					tags = tags + '<a class="tag tag'+key+' tag_grey" title="' + val + '" href="">' + val + '</a>';
    				}
  				});
  				var media_box = $('<div class="media_item" id="media_'+media_id+'">loading...</div>');
  				media_box.css("width",(Math.round(data.media_attr.width / 100) * 100));
  				var media = media_box.html('<div class="media_content"><img width="'+ data.media_attr.width +'" height="'+ data.media_attr.height +'" alt="'+ data.media_title +'" title="'+ data.media_title +'" src="http://data.weloveitwhenaplancomestogether.com/'+ data.media_file +'" /><h4>'+ data.media_title +'</h4><span class="text">'+ data.media_desc +'</span><span class="tags">'+ tags +'</tags></div>');
  				$.amy.globalMedia.push(media.get(0));
  				  			}
		});
    }
    
    
    function loadTags(tag) {
    	$('div#search').append('<a class="tag tag'+ tag.key_id +' tag_active" title="' + tag.key_name + '" href="#">' + tag.key_name + '</a>');
  		//$('.tag').corner("8px");
    }
    
    function split( val ) {
		return val.split( /,\s*/ );
	}
	function extractLast( term ) {
		return split( term ).pop();
	}

		$( "#search_input" )
		
			.bind( "keydown", function( event ) {
				if ( event.keyCode === $.ui.keyCode.TAB &&
						$( this ).data( "autocomplete" ).menu.active ) {
					event.preventDefault();
				}
				
			})
			.autocomplete({
				source: function( request, response ) {
					var search = extractLast(request.term);
					$.getJSON( "http://www.weloveitwhenaplancomestogether.com/amy/api/search/suggest/"+search, response );
				},
				search: function() {
					// custom minLength
					var term = extractLast( this.value );
					if ( term.length < 1 ) {
						return false;
					}
				},
				focus: function() {
					// prevent value inserted on focus
					return false;
				},
				select: function( event, ui ) {
					var terms = split( this.value );
					// remove the current input
					terms.pop();
					// add the selected item
					terms.push( ui.item.label );
					// add placeholder to get the comma-and-space at the end
					terms.push( "" );
					dataString = terms.join( " " );
					$.ajax({
  						url: encodeURI('http://www.weloveitwhenaplancomestogether.com/amy/api/search/keywords/0/50/' + dataString),
  						dataType: 'json',
  						error: function(XMLHttpRequest, textStatus, data) { },
  						success: function(data, textStatus, XMLHttpRequest) {
  							$('div#search').html("");
  							$(data.keys).each(function() { loadTags(this); });
  							$(data.media).each(function() { loadMedia(this.media_id); });
  							returnMedia();
  						}	
				});
					this.value = terms.join( ", " );
					return false;
					
				}
			});
    
    
	
});

jQuery.fn.showFooter = function() {
	$.fn.checkWindowSize();
    if($(document).height() > windowHeight) {
    	$('#footer').show();
    };

};

jQuery.fn.checkWindowSize = function() {
	var myWidth = 0, myHeight = 0;
	if( typeof( window.innerWidth ) == 'number' ) {
		//Non-IE
		myWidth = window.innerWidth;
		myHeight = window.innerHeight;
	}
	else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
		//IE 6+ in 'standards compliant mode'
		myWidth = document.documentElement.clientWidth;
		myHeight = document.documentElement.clientHeight;
	}
	else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
		//IE 4 compatible
		myWidth = document.body.clientWidth;
		myHeight = document.body.clientHeight;
	}
	windowHeight = myHeight;
	windowWidth = myWidth;
};



