(function($){ // jQuery -> $ safeguard
/* jLoader
 * @param url:string - url that request is made to
 * @param replace_or_append:string - 'replace' or 'append'
 * @param container_id:string - id of DOM element which response is associated with
 * @param cb:function - callback function for when request is completed
 * @param showAnim:object - animation object for jAnimator, used to show the content in container_id if given
 * @param hideAnim:object - animation object for jAnimator, used to hide the content in container_id if given
 *_________________________________________________________________________*/
jLoader = function(url,replace_or_append,container_id,cb,showAnim,hideAnim) {

	if( arguments.length < 3 ) {
		alert('need at least 3 args...');
		return;
	}

	var loader = $('#the_loader').clone().insertBefore('#the_loader').show();

	if( showAnim !== undefined )
		window._ANIMATIONS.showAmin = showAnim;
	if( hideAnim !== undefined )
		window._ANIMATIONS.hideAmin = hideAnim;

	if( typeof _urlAction_beforeRequest == 'function' )
		url = _urlAction_beforeRequest(url);

	$.ajaxQueue.get(url, {
		success : function(resp) {				// make async call to the <a>'s url
			loader.remove();

			if( replace_or_append == 'replace' )
				$('#'+container_id).replaceWith(resp).remove(); // * replace with the response
			else if( replace_or_append == 'append' )
				$('#'+container_id).append(resp);			// * replace with the response
			else if( replace_or_append == 'replace_inner' )
				$('#'+container_id).html(resp);			// * replace inside contents with the response

			if( cb !== undefined )
				cb(container_id);

			if( typeof _urlAction_afterRequest == 'function' )
				_urlAction_afterRequest(this.url);
		}
	});

	//$('ul').sortable(sortable_options);
	return false;	// dont actually follow the link
};
/* jFormer
 * @param form_id:string - id of form to submit
 * @param replace_or_append:string - 'replace' or 'append'
 * @param container_id:string - id of DOM element which response is associated with
 * @param method:string - 'post' or 'get'
 * @param cb:function - callback function for when request is completed
 *_________________________________________________________________________*/
jFormer = function(form_id,replace_or_append,container_id,method,cb) {

	if( arguments.length < 4 ) {
		alert('need 3');
		return;
	}

	var container = $('#'+container_id);
	var method = method || 'post'; // default value

// create and save the loading image

	var loader = $('#the_loader').clone().insertBefore('#the_loader').show();

	var _form = $('#'+form_id)
	.bind('form-pre-serialize', function(e) {		
    if (typeof tinyMCE != "undefined")
		  tinyMCE.triggerSave();
	});

	_form.ajaxForm({
		type: method,
		success: function(resp){
			loader.remove();

			if( replace_or_append == 'replace' )
				container.replaceWith(resp); // * replace with the response
			else if( replace_or_append == 'append' )
				container.append(resp);			// * replace with the response

			if( cb !== undefined )
			{
				cb(_form[0]); // pass the actual form
			}

			$('body').scrollTop(0);

			// do this later when we can be more specific about which url's call for animation
			if( typeof _urlAction_afterRequest == 'function' )
				_urlAction_afterRequest(this.url);
		}
	}).submit();
};
/* jAnimator
 * @param selector:string - id of form to submit
 * @param animObj:string - object that specifies properties of the animation
 * @param callb:function - optional function to be called when animation completes
 *_________________________________________________________________________*/
jAnimator = function(selector, animObj, callb) {

	var type = '',
	type_val = 0,
			 $el = (typeof selector == 'object')?selector:$(selector),
		 cssOb = {},
		 sp_fx = animObj.effect.split('_')[1],
     shide = animObj.effect.split('_')[0],
			side = (/^left$|^right$|^top$|^bottom$/.test(sp_fx) ? sp_fx : undefined);

	switch( animObj.effect ) {
		case 'show_fade':
					type = 'opacity';
			type_val = 'show';
		break;
		case 'show_left':
					type = 'left';
			$el.css('left', -$el.outerWidth());
		break;
		case 'show_right':
					type = 'left';
			$el.css('left', $el.outerWidth());
		break;
		case 'show_top':
					type = 'top';
			$el.css('top', -$el.outerHeight());
		break;
		case 'show_bottom':
					type = 'top';
			$el.css('top', $el.outerHeight());
		break;
		case 'hide_fade':
					type = 'opacity';
			type_val = 'hide';
		break;
		case 'hide_left':
					type = 'left';
			type_val = -$el.outerWidth();
		break;
		case 'hide_right':
					type = 'left';
			type_val = $el.outerWidth();
		break;
		case 'hide_top':
					type = 'top';
			type_val = -$el.outerHeight();
		break;
		case 'hide_bottom':
					type = 'top';
			type_val = $el.outerHeight();
		break;
		case 'scroll_top':
					type = 'scroll-top';
			type_val = 0;
		break;
	}

	if( side !== undefined )
		cssOb['border-'+side] = '1px solid white';

  if(shide==='show' && $el.is(':hidden'))
    $el.show();

	var _p = $el.parent().css(cssOb),
			_a = {};

	_a[type] = type_val;
	$el.animate(_a, {
		duration: animObj.duration,
		complete: function() {

      if(shide==='hide' && $el.is(':visible'))
        $el.hide();

			if( callb !== undefined )
				callb();

			for( var p in cssOb ) {
				_p.css(p, '');
			}
		}
	});
};

/* jSorter
 * @param node_id:number - id of nodes children we are sorting
 *_________________________________________________________________________*/
jSorter = function(node_id) {
	var hash = $.SortSerialize('sort_container_'+node_id).hash.replace(/sortDiv_/g,'');
	jLoader('node.php?op=save_children&_node_id='+node_id+'&'+hash, 'replace', 'li-'+node_id);
};

})(jQuery);
//
// little utility function
hash_url = function(url) { 

	var sp = url.split('?'),
			qs = sp[1],
  target = sp[0].split('/'),
    hash = { target: target[target.length-1] };

  if( qs !== undefined )
	{
  	if( qs.indexOf( '&' ) != -1 ) {
  		var qs_pairs = qs.split('&');
      for( var i=0; i < qs_pairs.length; ++i ) {
  			var sp_pair = qs_pairs[i].split('=');
  			hash[ sp_pair[0] ] = sp_pair[1];
      }
  	}
  }
	return hash;
};


_gallery = function(mode) {
	$('img.main_image').onImagesLoaded();
	var imgs = $('div#slideshow_images').children();
	_next=function(){
		idx = (idx===(imgs.length-1) ? 0 : idx+1);

		var n_img = imgs.eq(idx).clone();

		$('div.compact_ajax_gallery')
		.find('.main_image').fadeOut(1000, function(){

			$(this).removeClass('main_image').addClass('prev_image');

			if( n_img.is('a') )
				n_img.addClass('main_image').find('img').addClass('main_image');
			else
				n_img.addClass('main_image');

			n_img.onImagesLoaded(function() {
				$('.prev_image').remove();
				$('div.compact_ajax_gallery').html(n_img).find('.main_image').fadeIn(1000);
			});
		});
	};

	setInterval(_next,5000);
};


jQuery.fn.onImagesLoaded = function(_cb, dbg) { 
  return this.each(function() {
    dbg = dbg || 0;

    var $imgs = (this.tagName.toLowerCase()==='img')?$(this):$('img',this),
        _cont = this,
            i = 0,
    _done=function() {
      if( typeof _cb === 'function' ) _cb(_cont);
    };

    if( $imgs.length ) {
      $imgs.each(function() {
        var _img = this,
        _checki=function(e) {
          if((_img.complete) // for opera <3
          || (_img.readyState=='complete'&&e.type=='readystatechange') )
          {
            if( ++i===$imgs.length ) _done();
          }
          else if( _img.readyState === undefined ) // dont for IE
          {
            $(_img).attr('src',$(_img).attr('src'));
          }
        }; // _checki

        $(_img).bind('load readystatechange', function(e){_checki(e);});
        _checki({type:'readystatechange'});
      });
    } else _done();
  });
};

jQuery.fn.id = function() {
  return $(this).attr('id').split('-')[1];
};

