jQuery.ajaxSetup({ 
  'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")}
})


$(document).ready(function(){	
	setTimeout('fadeNotice()',3000);
	$('a.contact').click(function(e){
		e.preventDefault();
		$('#contact').modal();
	});
  $('button').attr('onfocus', "blur()"); // Fix annoying Firefox dotted outline
  $(":submit").attr('onfocus', "blur()"); // Fix annoying Firefox dotted outline
});

function fadeNotice(){
	jQuery('#notice').fadeOut('slow')
}


$.fn.clearForm = function() {
  return this.each(function() {
	var type = this.type, tag = this.tagName.toLowerCase();
	if (tag == 'form')
	  return $(':input',this).clearForm();
	if (type == 'text' || type == 'password' || tag == 'textarea')
	  this.value = '';
	else if (type == 'checkbox' || type == 'radio')
	  this.checked = false;
	else if (tag == 'select')
	  this.selectedIndex = -1;
  });
};

function SetCurrentMarkedList() {
	// $('#current_marked_list').change(function() {
	// 	$('#only_search_marked').attr('checked', 'checked');
	// 	self.location='/tracks?marked_list=' + $(this).val() + "&" + $("#search").serialize();
	// })
	$('#current_marked_list li a').click(function(e){
		e.preventDefault();
		$list_id = $(this).attr("id").split("_")[2]
		// $('#only_search_marked').attr('checked', 'checked');
		// $('#search_marked_list_id').val($list_id)
		self.location = '/tracks?marked_list=' + $list_id // + "&reset=true"
	})
}


function EditMarkedList(marked_list_id) {
	$('.mark_track').live("click", function() {
		var track_id = $(this).attr("track_id");
		if ($(this).is(':checked')) {
			$.post(
				'/marked_lists/' + marked_list_id + '/tracks',
				{'authenticity_token':_token, 'track_id':track_id}, 
				null,
				'script'
			)
		} else {
			$.post(
				'/marked_lists/'  + marked_list_id + '/tracks/' + track_id,
				{'authenticity_token':_token, '_method':'delete'},
				null,
				'script'
			)
		}					
	})
}

function CheckMarkedListNotLoggedIn() {
  $('.mark_track').click(function() {
    var track_id = $(this).attr("id").split("_")[1]
    document.location = ('/signup?marked_track_id=' + track_id)
  })
}

function ShowSelect(object){
	field_id = $(object).attr('type')
	select_box = '#search_' + field_id + 's'
	$(select_box).show()
}


function AddAttribute(object){
	field_id = $(object).attr('type')
	value_id = $(object).attr('item_id')
	select_box = '#search_' + field_id + 's'
	
	if ($(select_box + " option[value=" + value_id + "]").length) {
	
	} else {
		$(select_box).append('<option value="' + value_id + '">' + $(object).html() + '</option>' )
		var list = $(select_box + "> option")
		$(list).tsort();
	}
	
}

function RemoveAttributes(object){
	field_id = $(object).attr('type');
	value_id = $(object).attr('item_id');
	select_box = '#search_' + field_id + 's';
	$(select_box).empty();
}

function RemoveAttribute(object){
  field_id = $(object).attr('type');
	value_id = $(object).attr('item_id');
	select_box = '#search_' + field_id + 's';
	option_field = $(select_box + ' option[value=' + value_id + ']');
	option_field.remove();
	if ($(select_box).children("option").length == 0) {
	  $(select_box).hide();
	}
}

function SetupDeleteMultiSelect(){
	$('.multi_select').keydown(function(e){
			if (e.keyCode == 8) {
				e.preventDefault();
				var sel_options = $(this).children("option:selected")
				$.each(sel_options, function(object){
				  var item_id = (this.value);
				  var select_id = $(this).parent('select').attr('id');
				  checkbox_id = "#" + select_id + "_" + item_id
				  option =  $(checkbox_id)
				  option.attr('checked', '')
				  setCriteriaParentClass(option);
					$(this).remove();
				})
				if ($(this).children("option").length == 0) {
					$(this).hide();
				}
			}
		});
}

function SetupSubmitMultiSelects(){
	$('#search_submit').click(function(e){
		$('.multi_select option').each(function(){
			$(this).attr({
				selected : true
			})
		})
	})
}


function AdjustMenuHeights(){
  $('ul.sf-menu').superfish({
    // dropShadows: false 
    delay:         800,
    speed:         'normal',
	firstOnClick: true,
    onBeforeShow:        function(){
      var parent = $(this).parents("li")
      if (parent.length) {
      	li_height = 25
        offset = $(parent.get(0)).offset().top
        win_height = $(window).height() + $(window).scrollTop()
        number_of_children = $(this).children("li").length
        list_height = number_of_children * li_height
        if (list_height > 400) {
				list_height = 400
			} 
        total_height = list_height + offset
        if (total_height > win_height) {
          difference = win_height - total_height - 10
          $(this).css({"top": difference + "px"})  
        }
      }
    },
	onShow: function(){
		if ($.browser.msie & $(this).hasClass('first'))  $("div.exclude").hide();
	},
	onHide: function(){
		if ($.browser.msie & $(this).hasClass('first')) $("div.exclude").show();
	}
	
  });
}

function SetupAdvancedSearch(){
	SetupExcludes();
	AdjustMenuHeights();
	$('a.search_menu_item').click(function(e){
		e.preventDefault();
		AddAttribute(this);
		ShowSelect(this);
	})
	
	// $('a.search_menu_group').click(function(e){
	//     e.preventDefault();
	//     var sibs = $(this).parent('li').eq(0).nextAll('li') 
	//     $.each(sibs, function(){
	//       AddAttribute($(this).children('a').eq(0));
	//     })
	//     ShowSelect(this);
	//   })
  // SetupSubmitMultiSelects();
	SetupDeleteMultiSelect();
	$('#collection_insert').keypress(function(e){
		if (e.keyCode == 13 || e.keyCode == 9){
			e.preventDefault();
      var text = $(this).val().toUpperCase();
      AddCollectionFromText(text);
		}
	})
	if (!$("#search_duration_start").val().length) { inlineFieldLabel("min", "#search_duration_start"); }
	if (!$("#search_duration_end").val().length) { inlineFieldLabel("max", "#search_duration_end"); }
	$("form#advanced_search").submit(function(e){
	  text = $('#collection_insert').val().toUpperCase();
	  if (text.length > 0 && text != "ENTER TRACK PREFIX") {
	    AddCollectionFromText(text);
	  }
	  $('.multi_select option').each(function(){
			$(this).attr({
				selected : true
			})
		})
		if ($("#search_duration_start").val() == "min") { 
			 $("#search_duration_start").val('')
		}
		if ($("#search_duration_end").val() == "max") { 
			 $("#search_duration_end").val('')
		}

	})
	$("ul.search_menu input").change(function(e){
	  var parent = $(this).parent("li.search_value");
	  if ($(this).attr("checked") == true ) {
	    $(this).attr('checked', 'checked')
      AddAttribute(parent);
      ShowSelect(parent);
      setCriteriaParentClass(this);
    } else {
      RemoveAttribute(parent);
      setCriteriaParentClass(this);
    }
	})
	$("a.search_menu_group").click(function(e){
	  e.preventDefault();
	  var siblings = $(this).parent("li.group_title").siblings()
	  if (siblings.children("input:checked").length == siblings.children("input").length) {
	    setAdvancedCheckbox(siblings, false);
	  } else {
	    setAdvancedCheckbox(siblings, true)
	  }
	  setCriteriaParentClass(this);
	})
	
}

function AddCollectionFromText(text){
	// Find the li element that matches
  // var menu_item = $('#collection_search_menu a.search_menu_item').filter(function(){ return $(this).text() == text;}) 
  var menu_item = $('#collection_search_menu label').filter(function(){ return $(this).text() == text;})
	if ( menu_item.length ) {
	  
	  menu_item = menu_item.parent("li.search_value");
		AddAttribute(menu_item);
		input = menu_item.children('input')
		input.attr('checked', 'checked')
		setCriteriaParentClass(menu_item);
		$('select#search_collections').show()
		$(this).val('')		
	} else {
		alert("There is no collection " + text)
	}
}

function SetupExcludes(){
	$('.exclude input').click(function(){
		parent_div = $(this).parents("div.search_term").eq(0)
		if ($(this).is(":checked")) {
			parent_div.addClass("exclude_attribute")
		} else {
			parent_div.removeClass("exclude_attribute")
		}
	})
}

function inlineFieldLabel (label, inputid)
{
  var fieldLabel = label;         // string to put in your text input
  var textInput = $(inputid)  // your text input field
 
  if (!textInput.val()) {
	  /* add the field label css class to the form field and set the value */
	  textInput.addClass("intra-field-label").val(fieldLabel);

	  /* remove the placeholder string when field gets focus */
	  textInput.focus(function()
	   {
	      if(this.value == fieldLabel )
	      {
	         $(this).removeClass("intra-field-label").val("");
	      };
	   });

	  /* add the field label string when field looses focus */
	  textInput.blur(function()
	   {
	      if(this.value == "")
	      {
			$(this).addClass("intra-field-label").val(fieldLabel);
	      };
	   });

	   /* if the field is set to the fieldLabel on submit, clear the field */
	   $('form').submit(function()
	   {
	      if(textInput.val() == fieldLabel)
	      {
	         textInput.removeClass("intra-field-label").val("");
	      };
	   });
	}

}

function pauseOthers(obj) {
	if (obj.state == true) {
		$('div.track embed').not("#" +obj.id).each(function (i) {
			this.sendEvent("PLAY", "false");
		})
	}
};
function playerReady(thePlayer) {
	window.document[thePlayer.id].addControllerListener("PLAY","pauseOthers");
}

function SetupEditBoxForSingleTrack() {
	jQuery(document).ready(function(){
		$('a.attribute_menu_item').click(function(e){
			field_id = $(this).attr('type')
			value_id = $(this).attr('item_id')
			$("#track_" + field_id).val(value_id)
			var parent_li = $(this).parents('li.menu_title').eq(0)
			var label_text = ($(this).text())
			$(parent_li).children('span.menu_title').html('<a href="#">' + label_text + '</a>')
			return false;
		})
		$('a.has_many_attribute').click(function(e){
			field_id = $(this).attr('type')
			value_id = $(this).attr('item_id')
			select_box = '#track_' + field_id
			if ($(select_box + " option[value=" + value_id + "]").length) {
		
			} else {
				$(select_box).append('<option value="' + value_id + '">' + $(this).html() + '</option>' )
				var list = $(select_box + "> option")
				$(list).tsort();
			}
			return false;
		})
		$('.multi_select').keydown(function(e){
				if (e.keyCode == 8) {
					e.preventDefault();
					var sel_options = $(this).children("option:selected")
					$.each(sel_options, function(){
						$(this).remove();
					})
				}
			});
		$('form#edit_single_track').submit(function(e){
			e.preventDefault();	
			SubmitTrackEditForm();
		})
	});
}

function SubmitTrackEditForm(){
	$('.multi_select option').each(function(){
		$(this).attr({
			selected : true
		})
	})
	var base_url = $('form#edit_single_track').attr("action")
	$.post(base_url, $("form#edit_single_track").serialize(), function(){}, "script")
}

function BasicSearchSuperfish(){
	$('ul.sf-menu').superfish({
		// dropShadows: false 
		delay:         800,
		speed:         'normal',
		firstOnClick: true,
		onBeforeShow: function(){
			var parent = $(this).parents("li")
	      if (parent.length) {
	      	li_height = 25
	        offset = $(parent.get(0)).offset().top
	        win_height = $(window).height() + $(window).scrollTop() - 70
	        number_of_children = $(this).children("li").length
	        list_height = number_of_children * li_height
	        if (list_height > 400) {
					list_height = 400
					$(this).addClass("too_tall")
				} 
	        total_height = list_height + offset
	        if (total_height > win_height) {
	          difference = win_height - total_height
	          $(this).css({"top": difference + "px"})  
	        }
	      }
		}
	});
}



function SetupFlashPlayer(width){
  width = width || 215
	$('a.play_track').click(function(e){
		e.preventDefault();
		// remove other players and restore the play icon
		$('div.track div.player').each(function (i) {
			parent_div = $(this).parents('span.play')
			$(parent_div).children('a.play_track').show();
			$(this).remove();
		})
		// get the enclosing span
		span = $(this).parents('span.play')
		// hide the play icon
		$(this).hide();	
		var song_id = $(this).attr("song_id")
		var song_duration = $(this).attr("song_duration")
		var song_url = $(this).attr("href")
		
		$("div#track-container-" + song_id).addClass("auditioned");
		
		// create a div where we will write the palyer to
		$(span).prepend('<div class="player" id="player_div_' + song_id + '"></div>')
		player_div = $(this).children('div.player')[0]
		var so = new SWFObject('/player.swf','embeded_player_' + song_id, width,'20','9');
		so.addParam('allowscriptaccess','always');
		so.addParam('flashvars','&duration=' + song_duration + '&file=' + song_url + '&type=mp3&autostart=true&skin=/simple.swf');
		// write the player to the divscore
		$(player_div).append(so.write('player_div_' + song_id));
		$.post("/auditioned_tracks", { track_id : song_id })		
	})
}

function updateSearchCheckbox(object){
  var search_term = $(object).siblings("label").text();
  var parent_div = $(object).parents("div.search_term").eq(0);
  var object_to_update = parent_div.find("a.title");
  title_array = (object_to_update.attr("title").length > 0) ? object_to_update.attr("title").split(", ") : null;
  if ($(object).attr("checked") == true ) {
    addLabelToSearchForm(object_to_update, search_term);
    setCriteriaParentClass(object);
  } else {
    removeLabelFromSearchForm(object_to_update, search_term);
    setCriteriaParentClass(object);
  }
}



function setCheckBox(array, status){
  search_labels = []
  array.each(function(){
    $(this).children("input").attr("checked", status);
    search_labels.push($(this).children("label").text());
  })
  sample_element = array.eq(0)
  search_anchor = getSearchAnchor(sample_element);
  if (status == true) {
    addLabelToSearchForm(search_anchor, search_labels);
    setCriteriaParentClass(sample_element)
  } else {
    removeLabelFromSearchForm(search_anchor, search_labels);
    setCriteriaParentClass(sample_element)
  }
}

function setAdvancedCheckbox(array, status){
  // array is a list of li elements
  array.each(function(){
    $(this).children("input").attr("checked", status);
    // add/remove element from list
    if (status == true) {
      AddAttribute(this);
      ShowSelect(this);
      // setCriteriaParentClass(this);
    } else {
      RemoveAttribute(this);
    }
    // update menu
  })
}

function setCriteriaParentClass (child_object) {
  object = $(child_object).parents("li.search_group").eq(0);
  if ($(object.find("input:checked")).length > 0) {
    object.addClass("active_search_criteria");
  } else {
    object.removeClass("active_search_criteria");
  };
}

function addLabelToSearchForm(object, label){
  title_array = getTitleArray(object)
  if (title_array == null) {
    setSearchAnchorTitle(object, label);
  } else {
    mergeTitles(title_array, label);
    setSearchAnchorTitle(object, title_array);
  }
  setSearchLabel(object);
}

function removeLabelFromSearchForm(object, label){
  title_array = getTitleArray(object)
  if (title_array != null) {
    removeTitles(title_array, label)
    setSearchAnchorTitle(object, title_array);
    setSearchLabel(object);
  }
}

function removeTitles(array, labels){
  if ($.isArray(labels)) {
    $.each(labels, function(index, value){ 
      if (!$.inArray(value, array)) { array.splice(array.indexOf(value), 1);};
    })
  } else {
    array.splice(array.indexOf(labels), 1);
  }
}

function mergeTitles(array, labels){
  if ($.isArray(labels)) {
    $.each(labels, function(index, value){ 
      if (!$.inArray(value, array)) { array.push(value)};
    })
  } else {
    array.push(labels);
  }
}

function getSearchAnchor(object){
  if (!(object.jquery)) {object = $(object)};  
  parent_div = $(object).parents("div.search_term").eq(0);
  return parent_div.find("a.title");
}

function setSearchAnchorTitle(object, labels){
  if ($.isArray(labels)) {
    labels.sort();
    object.attr("title", labels.join(", "));
  } else {
    object.attr("title", labels);
  }
}

function setSearchLabel(object) {
  title_array = getTitleArray(object)
  if ((title_array != null) && (title_array.length > 0)) {
    display_text = object.attr("title").substring(0,27);
    if (display_text.length >= 27) { display_text = display_text + "..."};
  } else {
    display_text = "All";
    object.removeClass("active_search");
    // object.attr("title", "");
  }
  object.text(display_text);
}

function getTitleArray(object){ 
  if (object.attr("title").length > 0) {
    return object.attr("title").split(", ");
  } else {
    return null;
  }
}

function restAttributeCriteria (object) {
  if (!(object.jquery)) {object = $(object)};   
	field_id = object.attr('type');
	$("#search_" + field_id + "s").empty();
	$('#search_exclude_' + field_id + "s").val(0);
	$('input:checkbox').attr('checked', false);
	anchor = getSearchAnchor(object);
	anchor.attr("title", null);
	setSearchLabel(anchor);
	object.parent("li").siblings("li.active_search_criteria").removeClass("active_search_criteria");
}



