 // Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

// Ajax.Responders.register({
//   onCreate: function() {
//     if($('busy') && Ajax.activeRequestCount>0)
//       Effect.Appear('busy',{duration:0.25,queue:'end'});
//   },
//   onComplete: function() {
//     if($('busy') && Ajax.activeRequestCount==0)
//       Effect.Fade('busy',{duration:0.25,queue:'end'});
//   }
// });


jQuery( document ).ajaxStart( function() {
	jQuery( '#spinner' ).show();
}).ajaxStop( function() {
	jQuery( '#spinner' ).hide();
});

function showRecaptcha(element, themeName) {
  Recaptcha.create("<%= ENV['RECAPTCHA_PUBLIC_KEY'] %>", element, {
        theme: themeName,
        tabindex: 0,
        callback: Recaptcha.focus_response_field
  });
}

function destroyRecaptchaWidget() {
  Recaptcha.destroy();
}

function SetupRenameForSectionsModal(manual_id) {
	jQuery('.edit_section_title_modal').each(function(e) {
		jQuery(this).editable('/admin/manuals/'+ manual_id + '/sections/' + jQuery(this).attr("id").split("_")[2], {
			name : "section[title]",
			submit : 'OK',
			submitdata: {_method: "put"},
			cancel  : 'Cancel',
			tooltip : 'Click to edit...',
			width: "300px"			})
	})
}

function SetupAuthorAssets(space_id){
  $('.editable_asset').change(function(){
    var check_value = $(this).attr("checked");
    var author_id = $(this).attr("author_id");
    var asset_type = $(this).attr("asset_type");
    var asset_id = $(this).attr("asset_id");
    var url = "/admin/spaces/" + space_id + "/asset_authors/";
    var ParamsJSON = {"asset_type" : asset_type, "asset_id": asset_id, "author_id" : author_id}
    if (check_value == false) {
      ParamsJSON["_method"] = "delete"; 
      url += author_id       
    };
    $.post(url, ParamsJSON);
  });
}

function ReorderReadings(element_id, manual_id, section_id) {
	jQuery(element_id).sortable({
	axis:'y',
	dropOnEmpty:false, 
	update:function(){
		jQuery.ajax({
			data:jQuery(this).sortable('serialize', {
				key:'reading_positions[]'}) + 
				'&_method=put',
				dataType:'script',
				type:'post',
				 url:'/admin/manuals/' + manual_id + '/reading_positions/' + section_id })}})
}

function ReorderSections(element_id, manual_id) {
	jQuery(element_id).sortable({
	axis:'y',
	tag: 'li',
	dropOnEmpty:false, 
	update:function(){
		jQuery.ajax({
			data:jQuery(this).sortable('serialize', {
				key:'section_positions[]'}) + 
				'&_method=put',
				dataType:'script',
				type:'post',
				 url:'/admin/section_positions/' + manual_id })}})
}


function InitializeManualEditPage(manual_id) {	
	SetupEditSections(manual_id);		
	SetupToggleLessons();		
	SetupAddRemoveLessons(manual_id);
	// SetupEditManualProperties(manual_id);	
	SetupReadingSorting(manual_id);	
	SetupHiddenCheckBox(manual_id);		   
}

function SetupHiddenCheckBox(manual_id) {
	jQuery('input:checkbox.hidden').click(function(e){
		jQuery.ajax({
				data:'section[hidden]=' + this.checked + '&_method=put', 
				dataType:'script', type:'post', 
				url:'/admin/manuals/' + manual_id + '/sections/' + $(this).attr("section_id") + '.js'
		})
	})
}

function SetupAssetsEdit(space_id) {
	jQuery('ul#current_assets').sortable({
				axis:'y',
				dropOnEmpty:false, 
				update:function(){
					jQuery.ajax({
						complete:function(request){
							jQuery('#current_assets').effect('highlight');
							jQuery('#current_assets li').removeClass("odd")
							jQuery('#current_assets li').removeClass("even")
							jQuery('#current_assets + li:odd').addClass("even")
						},
						data:jQuery('ul#current_assets').sortable('serialize', {
							key:'current_assets[]', expression : "(.+)"}) + 
							'&_method=put',
						dataType:'script',
						type:'post',
						url:'/admin/spaces/' + space_id + '/assets/1'
					})
				 }
	})
}

function SetupReadingSorting(manual_id) {
	jQuery('ul.readings').sortable({
				axis:'y',
				dropOnEmpty:false, 
				cursor:'drag',
				update:function(){
					jQuery.ajax({
						data:jQuery(this).sortable('serialize', {
							key:'reading_positions[]'}) + 
							'&_method=put',
							dataType:'script',
							type:'post',
							 url:'/admin/manuals/' + manual_id + '/reading_positions/' + $(this).attr("id").split("_")[3]
						})
				 }
	})
}



function SetupToggleLessons() {
	jQuery(".toggle_lessons").click(function (e) {
		e.preventDefault();
		var $container = jQuery('#lessons_' + this.id);
		$container.toggle();
		if ($container.is(':visible')) {
			jQuery(this).removeClass("collapsed");
		} else {
			jQuery(this).addClass("collapsed");
		}
	}
	);
}

function SetupLessonStatusEditor() {
	jQuery('.current_status').click(function(e) {
		jQuery(this).hide();
		if (jQuery("#status_label")) {
			jQuery("#status_label").hide();
		}
		var lesson_id = jQuery(this).attr("id").split("_")[1]
		jQuery('#status_editor_' + lesson_id).show();
	});
	jQuery('.cancel_status').click(function(e) {
		lesson_id = jQuery(this).parents('.status_editor').attr("id").split("_")[2];
		e.preventDefault();
		jQuery('#status_editor_' + lesson_id).hide();
		jQuery('#status_' + lesson_id).show();
		if (jQuery("#status_label")) {
			jQuery("#status_label").show();
		}
	});
}

function SetupLessonStatusEditorForManual() {
	jQuery('.current_status').click(function(e) {
		var lesson_id = jQuery(this).attr("id").split("_")[1]
		jQuery('#status_editor_' + lesson_id).show();
	});
	jQuery('.cancel_status').click(function(e) {
		lesson_id = jQuery(this).parents('.status_editor').attr("id").split("_")[2];
		e.preventDefault();
		jQuery('#status_editor_' + lesson_id).hide();
	});
}

function DisableEnterInField(field) {
	field = field || 'input';
	jQuery(field).keypress(function (e) {
		if (e.which == 13) {
			e.preventDefault();
		}
	});
}

function SetupAddRemoveLessons(manual_id) {
	jQuery('a.add_remove_lessons_button').click(function (e) {
		e.preventDefault();
		var split_array = (this.id.split("_"));
		var section_id_from_element = (split_array[split_array.length-1]);
		jQuery.get('/admin/manuals/' + manual_id + '/sections/' + section_id_from_element + '/lessons?format=js', function(data) {
			// create a modal dialog with the data from the ajax request
			jQuery(data).modal({
				containerId: 'addLessonsModalContainer'
				// close: false
			});
		});
	});
}

function SetupEditSections(manual_id) {
	jQuery('a.edit_sections').click(function (e) {
		e.preventDefault();
		jQuery.get('/admin/manuals/' + manual_id + '/sections/new?format=js', function(data) {
			jQuery(data).modal({
				
			});
			jQuery('#section_title').focus();
		});
	});
}

function SetupEditManualProperties(manual_id) {
	jQuery('a.edit_manual_properties').click(function (e) {
		e.preventDefault();
		jQuery.get('/admin/manuals/' + manual_id + '/edit?format=js', function(data) {
			jQuery(data).modal();
		})
	})
}




function ObserverAvailableLessonsSearch(url, form, update_element) {
	form = form || '#search';
	update_element = update_element || '#available_lessons';
	observer = jQuery(form).delayedObserver(0.5, function(element, value) {
		jQuery.ajax({
			data:jQuery(form).serialize(),
			success:function(request){
				jQuery(update_element).html(request);
			},
			type:'get',
			url:url
			
		})
	}) 
}





function ObserveForm(url, form, update_element) {
	form = form || '#search';
	update_element = update_element || '#available_lessons';
	observer = jQuery(form).delayedObserver(0.5, function(element, value) {
		jQuery.ajax({
			data:jQuery(form).serialize(),
			success:function(request){
				jQuery(update_element).html(request);
			},
			type:'get',
			url:url
		})
	})
}


function SetupTour(){
	// when the DOM is ready...
	$(document).ready(function () {
		var $panels = $('#slider .scrollContainer > div');
		var $container = $('#slider .scrollContainer');

		// if false, we'll float all the panels left and fix the width 
		// of the container
		var horizontal = true;

		// float the panels left if we're going horizontal
		if (horizontal) {
		  $panels.css({
		    'float' : 'left',
		    'position' : 'relative' // IE fix to ensure overflow is hidden
		  });

		  // calculate a new width for the container (so it holds all panels)
		  $container.css('width', $panels[0].offsetWidth * $panels.length);
		}

		// collect the scroll object, at the same time apply the hidden overflow
		// to remove the default scrollbars that will appear
		var $scroll = $('#slider .scroll').css('overflow', 'hidden');

		// apply our left + right buttons
		$scroll
		  .before('<img class="scrollButtons left" src="/images/Tour/prev_arrow.gif" />')
		  .after('<img class="scrollButtons right" src="/images/Tour/next_arrow.gif" />');

		// handle nav selection
		function selectNav() {
		  $(this)
		    .parents('ul:first')
		      .find('a')
		        .removeClass('selected')
		      .end()
		    .end()
		    .addClass('selected');
		}

		$('#slider .navigation').find('a').click(selectNav);

		// go find the navigation link that has this target and select the nav
		function trigger(data) {
		  var el = $('#slider .navigation').find('a[href$="' + data.id + '"]').get(0);
		  selectNav.call(el);
		}

		if (window.location.hash) {
		  trigger({ id : window.location.hash.substr(1) });
		} else {
		  $('ul.navigation a:first').click();
		}

		// offset is used to move to *exactly* the right place, since I'm using
		// padding on my example, I need to subtract the amount of padding to
		// the offset.  Try removing this to get a good idea of the effect
		var offset = parseInt((horizontal ? 
		  $container.css('paddingTop') : 
		  $container.css('paddingLeft')) 
		  || 0) * -1;


		var scrollOptions = {
		  target: $scroll, // the element that has the overflow

		  // can be a selector which will be relative to the target
		  items: $panels,

		  navigation: '.navigation a',

		  // selectors are NOT relative to document, i.e. make sure they're unique
		  prev: 'img.left', 
		  next: 'img.right',

		  // allow the scroll effect to run both directions
		  axis: 'xy',

		  onAfter: trigger, // our final callback

		  offset: offset,

		  // duration of the sliding effect
		  duration: 500,

		  // easing - can be used with the easing plugin: 
		  // http://gsgd.co.uk/sandbox/jquery/easing/
		  easing: 'swing'
		};

		// apply serialScroll to the slider - we chose this plugin because it 
		// supports// the indexed next and previous scroll along with hooking 
		// in to our navigation.
		$('#slider').serialScroll(scrollOptions);

		// now apply localScroll to hook any other arbitrary links to trigger 
		// the effect
		$.localScroll(scrollOptions);

		// finally, if the URL has a hash, move the slider in to position, 
		// setting the duration to 1 because I don't want it to scroll in the
		// very first page load.  We don't always need this, but it ensures
		// the positioning is absolutely spot on when the pages loads.
		scrollOptions.duration = 1;
		$.localScroll.hash(scrollOptions);

	});
}

function embedQuickIntro(html){
	$(html).modal({
       position: [100,],
       closeHTML: "<a href='#' class='closeModal'>Close</a>"
     });
}

function insertVideo(id, video){
	$(document).ready(function(){
		$(id).html(video)
	});
}

function	SetSSLForm (){
		if (SSLAllowed() == true) {
			$('input#space_require_ssl').enable();
		} else {
			$('input#space_require_ssl').attr("checked", false).disable();
		}
		if ($('input#space_require_ssl').is(':checked')) {
			$('input#space_host_mapping').disable();
		} else {
			$('input#space_host_mapping').enable();
		}
	}
function SSLAllowed () {
	if ($('input#space_protected').is(':checked') && $('input#space_host_mapping').val().length == 0) {
		return true
	} else {
		return false 
	}
}

function SetupSpaceForm() {
	SetSSLForm();
	$('input#space_protected').change(function() {
		SetSSLForm();
	});
	$('input#space_require_ssl').change(function() {
		SetSSLForm();
	});

	$('input#space_host_mapping').blur(function() {
		SetSSLForm();
	});
}


function clearForm(form) {
  // iterate over all of the inputs for the form
  // element that was passed in
  $(':input', form).each(function() {
    var type = this.type;
    var tag = this.tagName.toLowerCase(); // normalize case
    // it's ok to reset the value attr of text inputs,
    // password inputs, and textareas
    if (type == 'text' || type == 'password' || tag == 'textarea')
      this.value = "";
    // checkboxes and radios need to have their checked state cleared
    // but should *not* have their 'value' changed
    else if (type == 'checkbox' || type == 'radio')
      this.checked = false;
    // select elements need to have their 'selectedIndex' property set to -1
    // (this works for both single and multiple select elements)
    else if (tag == 'select')
      this.selectedIndex = -1;
  });
};

