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

var sorting_tabs = false;
var new_spinner = true;

document.observe('dom:loaded',function() {
	Event.observe(document.body, 'click', function(event) {
		var element = Event.element(event);
		
		// Tab sorting
		if (element.getOffsetParent().hasClassName("sortable")){
			if (sorting_tabs) {
				sorting_tabs = false;
	    	Event.stop(event);
	    }
	  }
	
		// Ajax pagination for language and comments widgets
		var img = new Image;
		img.src = '/images/shared/loader.gif';
		function createSpinner() {
			return new Element('img', { src: img.src, 'class': 'spinner' });
		}
		
		if (element.match('.language_widget a') || element.match('.comments_widget a') ||
				element.match('.invite_widget a')) {
			
			if(new_spinner) {
      	element.up(0).insert(createSpinner());
				new_spinner = false;
			}
			
      new Ajax.Request(element.href, { method: 'get', 
			onComplete: function(transport) {
				new_spinner = true;
			}});
      Event.stop(event);
    }
	});
});

function update_photo_order_numbers(skip) {
	var count = 1;
	$$('.position').each(function(e) {
		if(skip == null) { skip = ''; }
		if(skip != e.up().id) {
			e.update(count);
			count++;
		}
	});
}

function update_accordion_order_numbers(skip, element) {
	var count = 1;
	$$(element).each(function(e) {
		if(skip == null) { skip = ''; }
		if(skip != e.up().id) {
			e.update('Day ' + count);
			count++;
		}
	});
}

function removeJunk(s) {
 /*
 ** Remove NewLine, CarriageReturn and Tab characters from a String
 **   s  string to be processed
 ** returns new string
 */
 r = "";
 for (i=0; i < s.length; i++) {
   if (s.charAt(i) != '\n' &&
       s.charAt(i) != '\r' &&
       s.charAt(i) != '\t') {
     r += s.charAt(i);
     }
   }
 return r;
}

function monitor_image_processing(image, style) {
	jQuery('.no_js_'+image).hide();
	jQuery('.js_'+image).show();
	setTimeout(function() {
		jQuery.ajax({
			url: '/javascripts/image_processing/' + image + '/' + style,
			success: function(response) {
				if (response != '') {
					max_width = /max_width=(\d*)/g.exec(response)
					if (max_width != null) {
						max_width = 'style=\"max-width:'+ max_width[1] +'px;\"'
					}
					jQuery('.processing_'+image).html('<img src="'+ response +'" '+ max_width +'/>');
				} else {
					monitor_image_processing(image, style);
				}
			}
		});
	}, 1000);
}