var _w = window;

_w.TIMEVARS = {
  show: 200,
  hide: 140,
  beforeHide: 700,
  beforeShow: 400,
  tabShow: 300,
  deleteFadeOut: 500
};

_w.FADEVARS = {
  deleteIconOpacity: 0.7,
  thumbOpacity: .8
};
_w.COLORVARS = {
  slideAnimationBorderColor : '#999',
  expandLIColor: '#FFE4B3',
  collapseLIColor: '#FFE4B3'
};
_w.OPTIONS = {
  thumb_fadeOnHover: false
};

(function($){ // jQuery -> $ safeguard

/* callback functions used with jLoader
 * ***********************************************/

//jLoader = function(url,replace_or_append,container_id,cb,showAnim,hideAnim) {
jModal = function(url, container_id) {
  if( $(container_id).length === 0 ) // create div if not exist
    $('body').append($('<div id="'+container_id+'"></div>'));

  jLoader(url, 'replace', container_id, function() {
    $('#'+container_id).modal();
  });
};

show_alert_div = function(){
  $('#alert_div').load('alert_div.php',{},function(){
    $(this).modal();
  });
};

show_editor_div = function(){

  if (typeof tinyMCE != "undefined") {
    for(id in tinyMCE.editors) {
      tinyMCE.execCommand('mceRemoveControl', false, id);
    }
  } else
    alert('not initialized');

  // init the mce editor textareas
  $('.mceEditor').each(function(idx){
    this.id = 'mce_editor_'+idx;
    tinyMCE.execCommand('mceAddControl', false, this.id);
  });

  _w.UPLOADERS = { initd: false };
	$('ul#tabs-nav li:last').addClass('last');
	var t = $('#editor_div div.thingy #tabs_wrapper');
  t.tabs({
    select : function(e, ui) {
      if(  ! $('.aUploaderForm').length ) {
				alert('You must submit the main form before uploading images.')
				return false;
			}
      else if( !_w.UPLOADERS.initd && 
      (ui.tab.hash === '#tab-thingy_images' || ui.tab.hash === '#tab-thingy_files') )
      {
        $('.aUploaderForm').aUploader();
      }
    }
  }).tabs('select',0);

	$('.rounded').slideDown(_w.TIMEVARS.tabShow).corners('top-left top-right 3px');

	Date.firstDayOfWeek = 0;
	Date.format = 'mm/dd/yyyy';
	
	$('.date_picker').datePicker({
		clickInput:true,
		startDate:'01/01/1996'
		});

};

_toggleThumbSorter = function(field_name) {
  var a = $('#sort-'+field_name+'-thumbs');
  if( a.length ) a.fadeTo(500, (a.is(':visible')?0:1));
};

/* used to hook specific urls before/after jLoader/jFormer calls
 * *****************************************************************/
_urlAction_beforeRequest = function(url) {
  var url_hash = hash_url(url);

  // take action depending on the page
  switch( url_hash['target'] )
  {
    case 'editor_div.php':
      jAnimator('#editor_div', { effect: 'hide_fade', duration: 250 });
    break;
  }

  switch( url_hash['op'] )
  {
    case 'get':
    break;
    case 'save_children':
      url += '&' +
        $('#sort_container_'+url_hash['_node_id'])
          .sortable('serialize');
    break;
  }
  return url;
};
_urlAction_afterRequest = function(url) {
  var url_hash = hash_url(url);

  // take action depending on the page
  switch( url_hash['target'] )
  {
    case 'editor_div.php':
      jAnimator('#editor_div', {effect:'show_fade', duration:250}, show_editor_div);
    break;
  }
  // take action depending on the query string bits
  if( 'op' in url_hash ) {
    var node_id = url_hash['_node_id'];
    switch( url_hash['op'] )
    {
      case 'delete':
      case 'delete_confirmed':
        show_alert_div();
      case 'expand':
        $('#li-'+node_id)
          .css('background-color','#FFE4B3');
				setTimeout( function() {
					$('#li-'+node_id)
        	  .animate({backgroundColor:'white'},{duration:1000});
				}, 60);
      break;
      case 'collapse':
        $('#li-'+node_id)
          .css('background-color','#FFE4B3');
				setTimeout( function() {
	        $('#li-'+node_id)
	          .animate({backgroundColor:'white'},{duration:1000});
				}, 60);
      break;
      case 'sort_children':
        $('#sort_container_'+url_hash['_node_id'])
          .sortable({ 
            forcePlaceholderSize: 1,
            placeholder: 'sortHelper'
          });
      break;
    }
  }
};

initCropper = function(id, type, hw_obj) {

  $('#the_loader').show();
  $.ajax({
    url   : 'asyncCropper.php',
    type  : 'post',
    data  : {
      'op'     : 'init',
      'id'     : id,
      'type'   : type,
      'height' : hw_obj['h'],
      'width'  : hw_obj['w']
    },
    dataType : 'json',
    success  : function(json_re) { $('#the_loader').hide();

      $('#cropper_div').html(json_re.html)
      $('#image2crop').onImagesLoaded(function(_this) {
        var hw_sc = [ json_re.scaled_w, json_re.scaled_h ],
             x1 = (_this.width - hw_sc[0]) / 2,
             y1 = (_this.height - hw_sc[1]) / 2,
            sel = [x1,y1,x1+hw_sc[0],y1+hw_sc[1]],
        sel_obj = {x:sel[0],y:sel[1],w:sel[2],h:sel[3]},
           jcropt = {
             aspectRatio : hw_sc[0] / hw_sc[1],
             setSelect : sel,
             onSelect  : function(c) {
               showPreview(c, _this.width, _this.height);
               setCrop(c);
             },
             onChange : function(c) {
               showPreview(c, _this.width, _this.height);
               setCrop(c);
             }
           };

        $(_this).Jcrop(jcropt);
        setCrop(sel_obj);

        if( type === 'thumb' )
          showPreview(sel_obj, _this.width, _this.height);

        var _ii = setInterval(function(){
          if( $('div.jcrop-holder').length ) {
            // ome ack chit ight ere - show it
            if( type === 'thumb' ) {
              $('div#image2crop_wrapper').css({paddingLeft:50,marginBottom:10,'float':'left'});
            }
            else 
              $('div#image2crop_wrapper').css({paddingLeft:0,width:_this.width+'px'})

            $('#cropper_div').hide().css('left',0).fadeIn('fast');

            clearInterval(_ii);
          }
        }, 10);
      });
    }
  });
};

function showPreview(coords, img_width, img_height) {
  var rx = 100 / coords.w;
  var ry = 100 / coords.h;

  $('#thumb_preview').css({
    width: Math.round(rx * img_width) + 'px',
    height: Math.round(ry * img_height) + 'px',
    marginLeft: '-' + Math.round(rx * coords.x) + 'px',
    marginTop: '-' + Math.round(ry * coords.y) + 'px'
  });
};

setCrop = function(c) {
  var f = $('form#crop_form');
  f.find('input[name=crop_x1]').val(c.x);
  f.find('input[name=crop_y1]').val(c.y);
  f.find('input[name=crop_width]').val(c.w);
  f.find('input[name=crop_height]').val(c.h);
}
saveCrop = function(img_id) {
  var type = $('form#crop_form input[name=type]').val();
  $.ajax({ url : 'asyncCropper.php',
    type : 'post',
    dataType : 'json',
    data : 'id='+img_id+'&'+$('#crop_form').serialize(),
    success : function(json) {
      cancelCrop(); // re-use this to close the div
      $('div.viewImage#'+type+'-'+img_id)
      .parent('div.iSize').removeClass('sel')
        .end()
      .click();
    }
  });
};
cancelCrop = function() {
  $('div#cropper_div').fadeOut('fast',function(){
    $(this).html('').css('left','-9999px').show();
  });
};

$.fn.onImagesLoaded = function(_cb) {
  return this.each(function(){

	  var _p = this,
        _i = 0,
      imgs = (this.tagName.toLowerCase()==='img') ? $(this) : $('img', this);

    if( imgs.length ) {
      imgs.each(function() {

        $(this).bind('load readystatechange', function(e) {

          if( this.complete
          || (this.readyState=='complete' && e.type=='readystatechange') ) {

            if( ++_i===imgs.length ) /* all of them are done */ {
              if( typeof _cb === 'function' ) 
                _cb(this);

              $(_p).trigger('images-loaded');
            }
          }
        })
        .bind('error', function() {
//          console.log('error');
        });

        this.src = this.src;
      });
    } else
    if( typeof _cb === 'function' )
      _cb(imgs.length);
  });
};

$.fn.myccordion = function(slide) {
  if( !$(this).hasClass('myccordion') ) {
    
    var _a = $(this),
     slide = slide || true;

    _a.addClass('myccordion')
    .find('div.acco.hide').hide()
      .end().show()
    .find('h3').click(function() {

      $('h3',_a).removeClass('sel');
      $(this).addClass('sel');

      _a.find('div.acco:visible').slideUp();
      $('a.ii').removeClass('sel');

      var link = $(this).find('a.ii').addClass('sel');
      $('#'+link.attr('href').split('#')[1]).slideDown();
    }).end()
    .find('div.iSize:last').css('border-bottom','none')
      .end()
    .find('div.iSize div.label')
    .click(function(){$(this).next('div.viewImage').click();})
      .end()
    .find('div.iSize div.viewImage')
    .click(function() {

      if( $(this).parents('div.iSize').is('.sel') ) 
        return;

      $('div.iSize').removeClass('sel');
      var iSize = $(this).parents('div.iSize').addClass('sel'),
             sp = $(this).attr('id').split('-'),
           type = sp[0],
           __id = sp[1],
           $m_i = $('div.mainImage'),
              w = $m_i.width(),
              h = $m_i.height();

      $m_i.fadeOut('fast',function(){
        var d = new Date,
         _img = $('img', this)
          .attr('src','image_size.php?id='+__id+'&type='+type+'&w='+w+'&h='+h+'&q='+d.valueOf());

        $(this).onImagesLoaded(function(){
          $m_i.fadeIn();
          var ih = _img.height(),
              mt = (h - ih) / 2;

          _img.css('margin-top',mt+'px');
        });
      });
    });
  }
};

})(jQuery);

jQuery(function($){ /* onload */

  // the_site menu events....
  $('li.node > div.node_header') // sliding menus
  .live('mouseover', function(e) { //mouseover/mouseenter\\
    var node_header = $(this);
    var m_offset = node_header.find('.arrow').width() + node_header.find('.node_name').width() + 10;

    // make the parent node menu go away...
    var pli = node_header.parent('li.nodeMenuActive');
    if( pli.length && pli.data('hide_timeout') === undefined )
      pli.trigger('mouseout');

    if( node_header.data('hide_timeout') != undefined ) {
      clearTimeout(node_header.data('hide_timeout'));
      node_header.removeData('hide_timeout');
    }
    else {
      // this nodes menu is active...
      node_header.addClass(' nodeMenuActive');
      // add a class for the active menu for easy removal...
      node_header.data('show_timeout', setTimeout(function(){
        node_header.removeData('show_timeout')
        .find('.node_menu:first')
          .addClass('activeMenu')
          .animate({left:m_offset,opacity:'show'},{
            duration: _w.TIMEVARS.show,
            complete: function() {
            }
          }); // slide out the node menu
      }, _w.TIMEVARS.beforeShow) );
    }
  })
  .live('mouseout', function(e) { //mouseout/mouseleave\\

    var node_header = $(this);
    var tid = node_header.data('show_timeout');

    if( tid != undefined ) {
      clearTimeout(tid);
      node_header.removeData('show_timeout');
    }
    else if( node_header.hasClass('nodeMenuActive') ) {
      node_header.data('hide_timeout', setTimeout(function() {
        // this node is no longer active
        node_header.removeClass('nodeMenuActive')
        .find('.activeMenu:first')
        .removeClass('activeMenu')
          .animate({left:20,opacity:'hide'},{
            duration: _w.TIMEVARS.hide, 
            complete: function() {
            }
          });

        // remove the flag for mouseover...
        node_header.removeData('hide_timeout');

      }, _w.TIMEVARS.beforeHide) );
    }
    // check if the moving to the parent, must manually trigger the event...
    $(e.relatedTarget).parent('.node_header').parent('li.node').trigger('mouseover');
  });

  $('.valign')
  .each(function(){
    var _this = $(this);
    var _par  = _this.parent();
    var h = _this.height();
    var ph = _par.height();
    var mh = (ph-h) / 2;
    $(this).css('margin-top', mh);
  });
  // init ----------------------------------
	// animate to offset
  var nm = $('#node_menu_0'),
      _p = nm.parent('.node_header'),
 _offset = _p.find('.node_name').width() + _p.find('.arrow').width() + 10;
  nm.animate({left:_offset,opacity:'show'},{ duration: _w.TIMEVARS.show });

}); // onload //



