(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;
};

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];
};

function colorToHex(color) {
    if (color.substr(0, 1) === '#') {
        return color;
    }
    var digits = /(.*?)rgb\((\d+), (\d+), (\d+)\)/.exec(color);
    
    var red = parseInt(digits[2]);
    var green = parseInt(digits[3]);
    var blue = parseInt(digits[4]);
    
    var rgb = blue | (green << 8) | (red << 16);
    return digits[1] + '#' + rgb.toString(16);
};

// darkens / lightens colors
function darken( hexColor, factor ) {   
        if ( factor < 0 ) factor = 0;

        var c = hexColor;
        if ( c.substr(0,1) == "#" )
        {
            c = c.substring(1);
        }

        if ( c.length == 3 || c.length == 6 )
        {
            var i = c.length / 3;

            var f;  // the relative distance from white

            var r = parseInt( c.substr(0, i ), 16 );
            f = ( factor * r / (256-r) );
            r = Math.floor((256 * f) / (f+1));

            r = r.toString(16);
            if ( r.length == 1 ) r = "0" + r;

            var g = parseInt( c.substr(i, i), 16);
            f = ( factor * g / (256-g) );
            g = Math.floor((256 * f) / (f+1));
            g = g.toString(16);
            if ( g.length == 1 ) g = "0" + g;

            var b = parseInt( c.substr( 2*i, i),16 );
            f = ( factor * b / (256-b) );
            b = Math.floor((256 * f) / (f+1));
            b = b.toString(16);
            if ( b.length == 1 ) b = "0" + b;

            c =  r+g+b;
         }   

         return "#" + c;
} // end darken() function

jQuery.fn.bevel = function(method,factor) {
	// get border-color
	if ($(this).hasClass('beveled') && $(this).hasClass('outward')) {
		var border_color = colorToHex($(this).css('border-left-color'));		
	} else if ($(this).hasClass('beveled') && $(this).hasClass('inward')) {
		var border_color = colorToHex($(this).css('border-right-color'));		
	} else if ($(this).css('border-right-color')) {
		var border_color = colorToHex($(this).css('border-right-color'));		
	} else {
		border_color = '#777777';
	}
	
	if (border_color) {
		//console.log(border_color);
		var darker = darken(border_color,1 - factor);
		var lighter = darken(border_color,1 + factor);
		var middle = darken(border_color,1 + (factor/3));
		//console.log('darker: ' + darker + ' lighter: ' + lighter);
		$(this).addClass('beveled');
		$(this).removeClass('inward');
		$(this).removeClass('outward');
		$(this).addClass(method);
		switch (method){
			case 'outward':
				$(this).css('border-top-color',lighter);
				$(this).css('border-bottom-color',darker);
				$(this).css('border-right-color',middle);
				$(this).css('border-left-color',border_color);
				break;
			case 'inward':
			default:
				$(this).css('border-top-color',darker);
				$(this).css('border-bottom-color',lighter);
				$(this).css('border-left-color',middle);
				$(this).css('border-right-color',border_color);
			break;
		}
	} else {
		//console.log($(this));
	}
} // end bevel()

jQuery.fn.makeModal = function() {
	console.log($(this));
	$(this).modal({
		onOpen: function (dialog) {
			dialog.overlay.fadeIn('fast', function () {
				dialog.container.slideDown('fast', function () {
					dialog.data.fadeIn('fast');
				});
			});
		},
		onClose: function (dialog) {
			dialog.data.fadeOut('slow', function () {
				dialog.container.slideUp('fast', function () {
					dialog.overlay.fadeOut('fast', function () {
						$.modal.close(); // must call this!
					});
				});
			});
		}
	});
}
