$(document).ready(function(){ 
	
		window.reload_lock = 0;
		
		$('#spinner').hide();
	
/*		$("#tags span").each(function() {*/
		setupBoxClicks();
		
		$('#tag_toggle span').slider({
			orientation: "horizontal", 
			value: 1,
			min: 0,
			max: 1,
			step: 1,
			animate: true,
			change: function(event, ui) {
				$(".nav_button#selected").attr("id", "").css('background', 'url(/images/nav_button_white.png) no-repeat');
				window.location.hash = "/order/" + getSortOrder() + "/categories/" + getContentPrefs() + getTags();
				// reloadMix();
			}
			});
			
		$('#slide_to_send span').slider({
			orientation: "horizontal", 
			value: 0,
			min: 0,
			max: 1,
			step: 1,
			animate: true,
			change: function(event, ui) {
				sendEmail();
			}
			});
			
			$("#common li").css("width", width_sum($("#common li span")) + 730);
			$("#lesscommon li").css("width", width_sum($("#lesscommon li span")) + 980);
			$("#uncommon li").css("width", width_sum($("#uncommon li span")) + 1130);
			
			
		// $("input#search").bind("focus", function(e){
		//       $(this).css("background-position", "0px -43px");
		//     });
	

	
		$("#customize_icon").hover(function(){
			if ($("#mixing_board").is(":hidden")) {
			$("#mixing_board").slideDown();
			setTimeout("$('#tags ul').jparallax({mouseport: $('#tags'), mouseActiveOutside: true});",500);
			}
		});
		
		$("#mixing_board").mouseleave(function(){
			if ($("#mixing_board").is(":visible")) {
			$("#mixing_board").slideUp();
			}
		})
		
		
		$("#search_submit").click(function() {
			$(".nav_button#selected").attr("id", "").css('background', 'url(/images/nav_button_white.png) no-repeat');
			reloadMix();
			
		})
			
		$("#search").keypress(function(e){
			      if(e.which == 13){
			       $(".nav_button#selected").attr("id", "").css('background', 'url(/images/nav_button_white.png) no-repeat');
			reloadMix();
			       }
			      });

		
		
		// $('#tags ul').jparallax({mouseport: $('#tags'), mouseActiveOutside: true});
		$("#mixing_board").hide();
		
		$("li.nav_button").blend({speed:450, opacity:1});
		
		
		$(".tag_button").toggle(
			function () {
	    $(this).addClass("selected");
			$(".nav_button#selected").attr("id", "").css('background', 'url(/images/nav_button_white.png) no-repeat');
      window.location.hash = "/order/" + getSortOrder() + "/categories/" + getContentPrefs() + getTags();
      // reloadMix()
	  },
	  function () {
	    $(".nav_button#selected").attr("id", "").css('background', 'url(/images/nav_button_white.png) no-repeat');
			$(this).removeClass("selected");
			window.location.hash = "/order/" + getSortOrder() + "/categories/" + getContentPrefs() + getTags();
      // reloadMix();
	  });

		// change defaults for range, animate and orientation
		$.extend($.ui.slider.defaults, {
			animate: true,
			orientation: "vertical"
		});

		// setup graphic EQ
		$("#eq > span").each(function() {
			// read initial values from markup and remove that
			var value = parseInt($(this).text());
			$(this).empty();
			$(this).slider({
				value: value,
				min: 0,
				max: 1,
				step: 1,
				animate: true,
				orientation: "vertical",
				change: function(event, ui) {
					if (window.reload_lock != 1) {
					$(".nav_button#selected").attr("id", "").css('background', 'url(/images/nav_button_white.png) no-repeat');
          window.location.hash = "/order/" + getSortOrder() + "/categories/" + getContentPrefs() + getTags();
          }
          // reloadMix();
				}
				
			})
		});

	$('.inlineRadios input[type=radio]').prettyCheckboxes({'display':'inline'}, function(){
	
	});
	
	button_box_resizer();
	
	$('.inlineRadios input:radio').change(function(){ 
		$(".nav_button#selected").attr("id", "").css('background', 'url(/images/nav_button_white.png) no-repeat');
		reloadMix();
		 });
	

	$("#containment_wrapper").css('width', $("#button_box ul li").width() * $("#button_box ul li").children().size() * 0.5 + 00);
	
	// button_box_resizer();

	// $("#contact .content").css('height', '0px');

	$("a.contact_handle").toggle( 
			function () { 
				$("#contact .content").animate({height: "324px"}, {queue:false, duration: 800, easing: 'easeOutBounce'});
				$("a.contact_handle").text("close"); },
			function () { 
				$("#contact .content").animate({height: "0px"}, {queue:false, duration: 800, easing: 'easeOutBounce'});
				$("a.contact_handle").text("contact");
			}
		); 
		
		$("#slide_to_send").mousedown(function(){
		  if ($("textarea#contact").val() == "include your name and email address if you want a reply" || $("textarea#contact").val() == "") {
  		  alert('You need to enter a message before sending.')
  	  } 
		});
		

		$(".nav_button").each(function(){
			if ($(this).attr('id') == "selected") {
				$(this).css('background', 'url(/images/nav_button_yellow.png) no-repeat');
			} else {
				$(this).css('background', 'url(/images/nav_button_white.png) no-repeat');
			}
		});


     
});






function boxView(box) {
	$('#spinner').show();
	if ($("#featured_holder").is(":visible")) {
		$("#featured_holder").hide();
		window.featured = "visible";
	} 
	
  // window.location.hash = "#top";
	$("#mix_holder").hide();
	
	$('#infscr-loading').hide();
	$("#back_button").show();
	$(".thing_holder").show();
  $("#back_button a").attr("href", window.location.hash);
  window.address_lock = 1;
	$("#top").attr("name", box.attr("title"));
	window.current_hash = box.attr('id');
	window.location.hash = box.attr("title");
	
	if (box.hasClass(".photoset") ) {
		$('#spinner').show();
		$.ajax({
						url: "/things/photos/" + box.attr("id"),
						success: function(data) {
							$('#spinner').hide();
							$(".thing_holder").append(data);
						}
					});
				} else {
				
		$(".thing_holder").append("<div class='box thing "+box.attr("category")+"'>" + box.html() + "</div>" + "<iframe id='" + box.attr("id") + "-comments' src ='/things/" + box.attr("id") + "/comments/' width='100%' height='0'></iframe>");
	
		$(".thing_holder").append("<p class='loading_comments'>Loading comments..</p>");

	
		setTimeout("var cHeight = $('iframe').contents().find('body').height();", 1500);
		setTimeout("$('iframe').height(cHeight + 700);",1900);
		setTimeout("$('.loading_comments').hide();",2000);
		setTimeout("window.address_lock = 2;",2000);
		
		
		// box.remove();
		$('#spinner').hide();
	}
	
	$("#back_button a").click(function(){
	  backButton();
    
	});
	
}


function backButton () {
  $("#back_button").hide();
	$(".thing_holder").hide();
	if (window.featured == "visible") {
	$("#featured_holder").show();
	}
	if ($("#mix_holder").children().size() == 0) {
    // reloadMix(window.current_url);
	}
	$("#mix_holder").show();
	var hash = $(".thing_holder .box").attr("id");
	$(".thing_holder").empty();
	window.lock = 0;
	$('#infscr-loading').show();
	window.location.hash = window.current_hash;
	setTimeout("window.address_lock = 0;",1000);
  setTimeout("window.lock = 0;",1000);
}


function setupBoxClicks() {
	$(".box").click(function(){
	  window.lock = 2;
		boxView($(this));
	});
}



function sendEmail() {
	if ($("#slide_to_send span").slider('option', 'value') == 1) { 
		$("#slide_to_send").css("background-position", "0px -21px");
		var spamFilter = "ct/create"
		if ($("textarea#contact").val() != "include your name and email address if you want a reply" && $("textarea#contact").val() != "") {
		  $.post("/conta" + spamFilter, "message=" + $("textarea#contact").val());
		  $("textarea#contact").val("");
	  }
    
    
    
	};
}

function reloadMix(customPath, searchQuery) {
	// $('#infscr-loading').show();
	
	if (window.reload_lock != 1) {
		var finalPath;
		if (customPath != "home") {
			$("#featured_holder").hide();
			window.featured = "hidden";
		}
		// if (customPath) {
			// 	customPath = $("li." + customPath).attr('path')
			// }
			// 
			// if (window.location.hash) {
				// 	customPath = window.location.hash;
				// }

				// customPath = $("li.nav_button#selected").attr('title');
				// alert(customPath);
				if (getContentPrefs()){
					$('.thing_holder').empty();
					$('#mix_holder').remove();
					if (customPath){
						finalPath = customPath;
					} else {
						finalPath = "/order/" + getSortOrder() + "/categories/" + getContentPrefs() + getTags();
					}
					$('#spinner').show();
					$(".box").remove();
					$('#infscr-loading').text('One Sec, Loading..');
					box = $('<div id="mix_holder" />');  
					box
					.appendTo( "#mix_wrapper" )
					.load( finalPath + '?js=true&query=' + $("#search").val() + " .box",null,
					function() {
						// debugger;
						window.lock = 0;
						$('#mix_holder').masonry({
							itemSelector: '.box:visible',
							singleMode: true,
							saveOptions: true,
							columnWidth: 300,
							resizeable: false
						});
						setupBoxClicks();
						$("#search").val(null);

						window.current_path = finalPath;
						// alert(window.location.hash);
						window.location.hash = finalPath;
						$('#spinner').hide();
						$("#back_button").hide();
						console.log(window.location.hash);
						if ($(this).find('.box').size() < 40 && window.location.hash != "#home"){
							window.lock = 2;
							$('#infscr-loading').text("That's All Folks!");
						} else {
							window.lock = 1;
							$('#infscr-loading').text("Scroll Down for More");
						}

					});
					
					// $("body").attr('path', $("li#selected.nav_button").attr('path'));
					
					
					window.page = 2;
					// $(window).bind('scroll.infscr');


					// infScroll();
				}
			}
		}

function width_sum(elements) {
	var total_width = 0;
	elements.each(function(){ total_width = total_width + $(this).width()});
	return total_width;
	
}

function getCurrentPath() {
	
}

function getTags() {
	var tags = "/tags/";
	$(".tag_button.selected").each(function() {
	tags += $(this).text() + ",";
	})
	if ($(".tag_button.selected").children().size() > 0){
	return tags.substring(0,tags.length - 1);} else {
		return ""
	}
}

function getSortOrder() {
	return $(".inlineRadios input:radio[checked*='true']").val()
}

function getContentPrefs(){
	var params = '';
	if ($("#notes_toggle").slider('option', 'value') != undefined){
		
	if ($("#notes_toggle").slider('option', 'value') == 1) {params += "notes,"};
	if ($("#bookmarks_toggle").slider('option', 'value') == 1) {params += "bookmarks,"};
	if ($("#videos_toggle").slider('option', 'value') == 1){ params += "videos,"};
	if ($("#music_toggle").slider('option', 'value') == 1) {params += "music,"};
	if ($("#photos_toggle").slider('option', 'value') == 1) {params += "photos,"};
	return params.substring(0,params.length - 1);}
	else return null;
}

function matchMixerToPath() {
	var path = $("li#selected.nav_button").attr('path');
	window.reload_lock = 1;
	if (path.indexOf("notes") > 0) {$("#notes_toggle").slider('value', 1)} else {$("#notes_toggle").slider('value', 0)};
	if (path.indexOf("videos") > 0) {$("#videos_toggle").slider('value', 1)} else {$("#videos_toggle").slider('value', 0)};
	if (path.indexOf("bookmarks") > 0) {$("#bookmarks_toggle").slider('value', 1)} else {$("#bookmarks_toggle").slider('value', 0)};
	if (path.indexOf("music") > 0) {$("#music_toggle").slider('value', 1)} else {$("#music_toggle").slider('value', 0)};
	if (path.indexOf("photos") > 0) {$("#photos_toggle").slider('value', 1)} else {$("#photos_toggle").slider('value', 0)};
	
	window.reload_lock = 0;
}

function draggable_nav() {
	
	
	var left_offset =  $("#containment_wrapper").width() - $("#right_edge").offset().left + 120;
	if (left_offset < 0) {
		left_offset = -7;
	}
	$("#button_box ul").draggable({ axis: 'x', containment: [$("#left_edge").offset().left - left_offset,0, $("#left_edge").offset().left + 7, 0] });
}

function button_box_resizer() {
	
	var window_width = $(window).width();
	if (window_width > 1887) {
		$("#button_box").width(1630);
		$("#customize_icon").css({left: 1740});
		$("#mixing_board").width(1760);
		$("#container").width(1800);
		$("#mixing_board .right").width(920);
	}
	if (window_width < 1877 && window_width > 1579) {
		$("#button_box").width(1330);
		$("#customize_icon").css({left: 1438});
		$("#mixing_board").width(1465);
		$("#container").width(1560);
		$("#nav .wrapper").width(1580);
		$("#mixing_board .right").width(700);
		$("#featured").width(1475);
	}
	if (window_width < 1579 && window_width > 1250) {
		$("#button_box").width(1060);
		$("#customize_icon").css({left: 1167});
		$("#mixing_board").width(1165);
		$("#container").width(1205);
		$("#featured").width(1180);
		$("#nav .wrapper").width(1280);
		$("#mixing_board .right").width(500);
	}
	if (window_width < 1240 && window_width > 947) {
		$("#button_box").width(713);
		$("#mixing_board").width(865);
		$("#customize_icon").css({left: 830});
		$("#container").width(910);
		$("#nav .wrapper").width(920);
		$("#mixing_board .right").width(290);
		$("#featured").width(875);
	}
	
	$('#mix_holder').masonry({
       itemSelector: '.box:visible',
				singleMode: true,
				saveOptions: true,
				columnWidth: 300,
				resizeable: false
   });


	// if (window_width < 947) {
	// 	$("#button_box").width(515);
	// 	$("#mixing_board").width(565);
	// 	$("#mixing_board .right").width(550);
	// 	$("#container").width(590);
	// 	$("#nav .wrapper").width(625);
	// 	$("div#tags img#tag_fade_right").css("left", 530);
	// }
	

}

// 
// function infScroll() {
// 	        $('#mix_holder').infinitescroll({
// 		                       navSelector  : "#page_nav",    // selector for the paged navigation 
// 		                       nextSelector : "#page_nav a",    // selector for the NEXT link (to page 2)
// 		                       itemSelector : ".box",       // selector for all items you'll retrieve
// 		                       loadingImg : '/images/loader.gif',
// 		                       donetext  : "No more pages to load.",
//                            bufferPx  : 5,
// 		                       debug: true,
// 		                       errorCallback: function() { $('#infscr-loading').animate({opacity: .8},2000).fadeOut('normal');     // fade out the error message after 2 seconds
// 		           
// 		                           }
// 		                   },
// 		                       // call masonry as a callback.
// 		                       function() { $('#mix_holder').masonry({ appendedContent: $(this) }); }
// 		                   );
// }


function iScroll() {
	window.lock = 1;
	
	var finalPath;

	box = $('<div class="new_content" />');  
	customPath = $("li#selected.nav_button").attr('title');
	if (!window.current_path) {
		if (customPath != undefined){
			window.current_path = customPath;
		} else {
			window.current_path = "/order/" + getSortOrder() + "/categories/" + getContentPrefs() + getTags();
		}
		
		window.location.hash = finalPath;
		// window.current_path  = finalPath;
	}
	$('#infscr-loading').text('One Sec, Loading..');
	if (window.current_path.substring(window.current_path.length -1, window.current_path.length) == " "){
	finalPath = window.current_path.substring(0, window.current_path.length- 1) }
	else {
		finalPath = window.current_path;
	}
	
	window.location.hash = finalPath;
	window.current_path  = finalPath;
	
  box
    .appendTo( "#mix_holder" )
    .load(  finalPath + '?js=true&query=' + $("#search").val() + "&page=" + window.page + " .box",null,
		function() { 
			if ($(this).children().size() == 0) {
				window.lock = 2;
				$('#infscr-loading').text("That's All, Folks!");
				$('#spinner').hide();
			} else {
			
			$('#mix_holder').masonry({ appendedContent: $(this) });
			setupBoxClicks();
				$('#spinner').hide();

				if ($(this).find('.box').size() != 40){
				$('#infscr-loading').text("That's All Folks!");
				window.lock = 2;
				} else {
					$('#infscr-loading').text("Scroll Down for More");
				}
				
			$("#mix_holder").height($("#mix_holder").height() + 100);
			 	}
			
		
		});
	

	
	window.page++;
	
}

function loadCallback() {
	
}

$(window).load(function(){ 

	draggable_nav();
	
	$('#mix_holder').masonry({
       itemSelector: '.box:visible',
				singleMode: true,
				saveOptions: true,
				columnWidth: 300,
				resizeable: false
   });

	window.page = 2;


		window.lock = 0;
	  window.address_lock = 0;
		

	
		$(window).scroll(function(){
						if ($(window).scrollTop() - ($(document).height() - $(window).height()) < -100 && window.lock != 2){
							window.lock = 0;
						}
			
		        if  ($(window).scrollTop() == $(document).height()  - $(window).height()){
				
							 if (window.lock == 0 && $(".box").size() > 0){
							$('#spinner').show();
							$('#infscr-loading').text('One Sec, Loading..');
		          iScroll();
						
							
						}
		        }
		});


     $.address.change(function(event) {  
        
         if (window.address_lock == 0){
           window.lock = 1;
           reloadMix(event.value);
           window.lock = 0;
         }
         if (window.address_lock == 2){
           backButton();
         }
         
     });
    

		
		//run masonry when window is resized
		$(window).resize(function() {
			// $('#mix_holder').masonry();
			button_box_resizer();
				if ($(window).width() > 947) {
/*					$("#mixing_board .right").css("width", "35%");*/
					$("div#tags img#tag_fade_right").css("left", "93%");
			/*		$("#tags ul").jparallax({mouseport: $("#tags")});*/
				
				}
			$('#button_box ul').draggable('destroy');
			draggable_nav(); 
			
		});
			
		$(".note h3 a").bigTarget({clickZone : 'div:eq(0)'});
		$(".bookmark h3 a").bigTarget({clickZone : 'div:eq(0)'});
		
    // customPath = $("li#selected.nav_button").attr('title');
    // if (!window.location.hash && ( $('body').attr('path') != "thing" || $('body').attr('path') != "home") ) {
    //  if (customPath != undefined){
    //    window.location.hash = customPath;
    //    window.current_path = customPath;
    //  }
    // }
		
    window.current_path = window.location.hash.substring(1,window.location.hash.length);
		
		
		if ($(".nav_button[title=" + window.current_path + "]").hasClass(".nav_buton") != false) {
			$(".nav_button#selected").attr("id", "").css('background', 'url(/images/nav_button_white.png) no-repeat');
			$(".nav_button[title=" + window.current_path + "]").attr('id', "selected").css('background', 'url(/images/nav_button_yellow.png) no-repeat');
      // setTimeout("reloadMix(window.current_path)", 300)
		} else
	  
	  if ( window.current_path != "") {
	    
	    if ($(".nav_button" + "." + window.current_path).size() == 1 || window.current_path == "home") {
	      reloadMix(window.current_path);
	    } else
	    
			$.ajax({
							url: "/things/show/" + window.location.hash.substring(1,window.location.hash.length),
							success: function(data) {
								box = $(data).find(".box");
								if (box.size() == 1){
								  window.current_path = "home";
								  window.featured = "visible";
								  window.lock = 2;
								  window.current_hash == "home";
								  boxView(box);
								  $('#spinner').hide();
								  $('#infscr-loading').text("Scroll Down for More");
								} 
							}
						});
      } else {
        window.featured = "visible";
        
        window.location.hash = "home";
        $("#featured_holder").show();
        // reloadMix("home");
        
      }
		
		
});




