function to_s(obj){
  return JSON.stringify(obj);
}

function initUploadFolderSection(){
  jQuery("div.folder:not(.editable_folder)").click(function(){
    jQuery(this).siblings().slideToggle();
  });
  jQuery("#brochures").keyup(function(){
    var val = jQuery(this).val().toLowerCase();
    if(val.length > 1){
      //find all files with val in their name and copy them into the results list below, changing the id as we do so
      files = jQuery(".upload_folder .file").filter(function(index){
        return (jQuery(this).find(".file-name").html().toLowerCase().indexOf(val) > -1);
      });
      //amend "found x results" string
      jQuery("#filterCount").html(files.size().toString());
      jQuery("#filterVal").html(val);
      //show the results container
      jQuery("#filterResults").show();
      //empty the list of files, and repopulate it with the ones we found
      var results = jQuery("#filteredFiles");
      results.html('');
      files.each(function(i){
        var file = jQuery(this);
        file.clone().attr('id', file.attr("id")+"s").appendTo(results);
      });
    }
  });
}

function updateUploadFolderClass(){
  jQuery("#documents li.upload_folder").each(function(i){
    if(jQuery(this).find("li.file").size() > 0){
      jQuery(this).addClass('has_content').removeClass('no_content');
    } else {
      jQuery(this).addClass('no_content').removeClass('has_content');
    }
  });
}

function refreshMusicServiceUserCount(musicServiceId){
  jQuery.get("/music_service/"+musicServiceId+"/user_count", 
             function(data){ 
               jQuery("#music_service_"+musicServiceId+"_user_count").html(data);
               if(data != "0"){
                 setTimeout(function(){
                   refreshMusicServiceUserCount(musicServiceId);
                 }, 5000);
               }
             }, 
             "script");
}

function refreshMusicServiceSchoolCount(musicServiceId){
  jQuery.get("/music_service/"+musicServiceId+"/school_count", 
             function(data){ 
               jQuery("#music_service_"+musicServiceId+"_school_count").html(data);
               if(data != "0"){
                 setTimeout(function(){
                   refreshMusicServiceSchoolCount(musicServiceId);
                 }, 5000);
               }
             }, 
             "script");
}

function hideFaceboxCloseButton(){
  jQuery("div.footer a.close").parent().hide()
}

function setExpandable() {
  jQuery(".expander").click(function (event) {
    jQuery(event.target).siblings(".expandable").toggle();
    jQuery(event.target).toggleClass("expanded");
  });
}

function initializeDatepickers(){
  jQuery(".datepicker").datepicker({
    minDate: -1, 
    dateFormat: 'dd-mm-y', 
    firstDay: 1, 
    showOn: 'button', 
    buttonImage: '/images/mini_icons/calendar.gif', 
    buttonImageOnly: true 
  });  
}

function roundNumber(num, dec) {
	var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
	return result;
}

function addToBasket(asset_id) {
  jQuery.ajax({
    dataType: 'script',
    type: 'POST',
    data: 'asset_id=' + asset_id,
    url: '/selections'
  });
}

function clickHiddenSubmit(target){
//  alert(jQuery(target).html());
  jQuery(target).siblings('.submit-button').click();
}

function initTabs(){
  jQuery(".tab_labels .tab_label").click(function(){
    var label = jQuery(this);
    label.siblings().removeClass("selected");
    label.addClass("selected");
    var tab = jQuery("#"+label.attr("id").replace("_label", "_content"));
    tab.siblings().hide();
    tab.show();
  });
}

jQuery(document).ready(function () {
  initTabs();

  //used in forms where we have a hidden submit button and a clickable span which triggers the form submit by clicking the hidden button.  Easier to style basically, and avoids problems which seem to occur by having the span directly submit the form.
  //relies on the button having "submit-button" class and the span having "click-submit" class.
  jQuery('form.remote').submit(function (event) {
    input = jQuery(event.target).children('input[type=submit]');
    input.attr('disabled', true);
    input.attr('value', 'submitting');
    jQuery.ajax({
      async: true,
      data: jQuery.param(jQuery(event.target).serializeArray()),
      dataType: 'script',
      type: 'put',
      url: jQuery(event.target).attr('action')
    });
    return false;
  });
  
  setExpandable();
  //initialise datepicker
  try { initializeDatepickers(); } catch(e) {}
  
  function toggleHelpCookie() {
    if ( jQuery.cookie("show-help") == undefined ) { 
      jQuery.cookie("show-help","true", { expires: 30, path: '/'});
    } else {
      jQuery.cookie("show-help",null);
    }		        
  }
    
  jQuery(".cHelpClose").toggle(  		
	  function () {
    		jQuery.each([jQuery("#cHelpMain"), jQuery("#helpLinks")],function(){this.hide(1000)});
    		jQuery("#cHelpBox.not-home").removeClass("cHelpActive").addClass("cHelpHidden");
    		jQuery(".cHelpBoxLabel.home a span").text("Show");
        toggleHelpCookie();
  		},
  		
  		function () {
    		jQuery.each([jQuery("#cHelpMain"), jQuery("#helpLinks")],function(){this.show(1000)});
    		jQuery("#cHelpBox.not-home").removeClass("cHelpHidden").addClass("cHelpActive");
    		jQuery(".cHelpBoxLabel.home a span").text("Hide");
        toggleHelpCookie();    
  		}
 	);
});

