// Javascript for Comic Marktplatz
// Relies on jQuery


/**
 * This returns an object with top, left, width, height, borderLeft,
 * borderTop, marginLeft, marginTop, scrollLeft, scrollTop, 
 * pageXOffset, pageYOffset.
 *
 * The top and left values include the scroll offsets but the
 * scrollLeft and scrollTop properties of the returned object
 * are the combined scroll offets of the parent elements 
 * (not including the window scroll offsets). This is not the
 * same as the element's scrollTop and scrollLeft.
 * 
 * For accurate readings make sure to use pixel values.
 *
 * @name offset  
 * @type Object
 * @param HTMLElement refElement The offset returned will be relative to this elemen.
 * @cat DOM
 * @author Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
 */
jQuery.fn.offset = function(refElem) {
  if (!this[0]) throw 'jQuery.fn.offset requires an element.';

  refElem = (refElem) ? jQuery(refElem)[0] : null;
  var x = 0, y = 0, elem = this[0], parent = this[0], sl = 0, st = 0;
  do {
    if (parent.tagName == 'BODY' || parent.tagName == 'HTML') {
      // Safari and IE don't add margin for static and relative
      if ((jQuery.browser.safari || jQuery.browser.msie) && jQuery.css(parent, 'position') != 'absolute') {
        x += parseInt(jQuery.css(parent, 'marginLeft')) || 0;
        y += parseInt(jQuery.css(parent, 'marginTop'))  || 0;
      }
      break;
    }

    x += parent.offsetLeft || 0;
    y += parent.offsetTop  || 0;

    // Mozilla and IE do not add the border
    if (jQuery.browser.mozilla || jQuery.browser.msie) {
      x += parseInt(jQuery.css(parent, 'borderLeftWidth')) || 0;
      y += parseInt(jQuery.css(parent, 'borderTopWidth'))  || 0;
    }

    // Need to get scroll offsets in-between offsetParents
    var op = parent.offsetParent;
    do {
      sl += parent.scrollLeft || 0;
      st += parent.scrollTop  || 0;
      parent = parent.parentNode;
    } while (parent != op);
  } while (parent);

  if (refElem) {
    var offset = jQuery(refElem).offset();
    x  = x  - offset.left;
    y  = y  - offset.top;
    sl = sl - offset.scrollLeft;
    st = st - offset.scrollTop;
  }

  // Safari and Opera do not add the border for the element
  if (jQuery.browser.safari || jQuery.browser.opera) {
    x += parseInt(jQuery.css(elem, 'borderLeftWidth')) || 0;
    y += parseInt(jQuery.css(elem, 'borderTopWidth'))  || 0;
  }

  return {
    top:  y - st,
    left: x - sl,
    width:  elem.offsetWidth,
    height: elem.offsetHeight,
    borderTop:  parseInt(jQuery.css(elem, 'borderTopWidth'))  || 0,
    borderLeft: parseInt(jQuery.css(elem, 'borderLeftWidth')) || 0,
    marginTop:  parseInt(jQuery.css(elem, 'marginTopWidth'))  || 0,
    marginLeft: parseInt(jQuery.css(elem, 'marginLeftWidth')) || 0,
    scrollTop:  st,
    scrollLeft: sl,
    pageYOffset: window.pageYOffset || document.documentElement.scrollTop  || document.body.scrollTop  || 0,
    pageXOffset: window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft || 0
  };
};

$.fn.message = function(text, cls) {
  $(this).after('<p class="' + cls + '">' + text + '</p>');
  return this;
};

$.fn.error = function(msg) {
  return $(this).message(msg, 'error');
};


// Focus first element
$.fn.focus_first = function() {
  var elem = $('input:visible', this).get(0);
  var select = $('select:visible', this).get(0);
  if (select && elem) {
    if (select.offsetTop < elem.offsetTop) {
      elem = select;
    }
  }
  var textarea = $('textarea:visible', this).get(0);
  if (textarea && elem) {
    if (textarea.offsetTop < elem.offsetTop) {
      elem = textarea;
    }
  }
  
  if (elem) {
    elem.focus();
  }
  return this;
}

///////////////////////////////////////
// Put everything together
///////////////////////////////////////


var CMP = {};

// Focus first field on form with class 'has_focus'
CMP.focus_first_element = function() {
  $('form.has_focus').focus_first();
};

// Hide/show sections of page
CMP.init_collapse = function() {
  $('.collapsible').each(function() {
    // Create anchor
    var _a = document.createElement('a');
    // Store data required on anchor itself
    _a.collapsed = false;
    _a.elementToCollapse = this;
    $(_a).href('#').addClass('collapselink');
    // If collapsed on startup: hide
    if ($(this).is('.collapsed')) {
      $(_a).html('Einblenden');
      _a.collapsed = true;
      $(this).css({display: 'none'});
    }
    else {
      $(_a).html('Ausblenden');
    }
    
    // Insert anchor
    $(this).before(_a);
    
    // Click handler
    $(_a).click(function(e) {
      // Click function: Toggle display!
      if (this.collapsed) {
        $(this.elementToCollapse).show();
        $(this).html('Ausblenden')
      }
      else {
        $(this.elementToCollapse).hide();
        $(this).html('Einblenden')
      }
      this.collapsed = !this.collapsed;
      e.preventDefault();
      e.stopPropagation();
    });
  });
} 

// Bring up "Really delete" message
CMP.init_confirm_delete = function() {
  $('input.deletebutton').click(function(e) {
    if (confirm("Element wirklich löschen?") == false) {
      e.preventDefault();
      e.stopPropagation();
    }
  });
}

CMP.init_thumbnail_lens = function() {
  // if there's a thumbnail image, show full size on mouseover
  $('img.thumbnail').hover(
    // Mousein
    function() {
      // "this" is the image rolled over
      if (this.img_lens == null) {
        this.img_lens = document.createElement('img');
        document.body.appendChild(this.img_lens);
        this.img_lens.src = this.src;
        $(this.img_lens).addClass('thumbail_lens');
        var offset = $(this).offset(); 
        $(this.img_lens).css({
          position: 'absolute', 
          left: (offset.left + offset.width + 20) + 'px', 
          top: offset.top + 'px',
          'z-index': 100
        });
      }
        
      $(this.img_lens).fadeIn("slow");
    },
    // Mouseout
    function() {
      if (this.img_lens) {
        $(this.img_lens).remove();
        this.img_lens = null;
      }
    }  
  ); // end hover
};

CMP.init_ad_status_buttons = function() {
	$('div.ad_menu//input[@type="submit"]').each( function() {
		CMP.init_ad_status_button(this);
	}); 
}

CMP.init_ad_status_button = function(elem) {
	$(elem).click(function(e) {
	    // The update function, store this, to access it in there!
	    var _$_ = this;
	    function as_update(json_doc) {
	      var json = eval(json_doc);
	      if (json.status.isError) {
	        $(_$_).error(json.status.message);
	      }
	      else {
		  	var div = $(_$_).parents('div.ad_menu'); 
		  	div.html(json.menu);
			$('input[@type="submit"]', div).each( function() {
				CMP.init_ad_status_button(this);
			});
	      }
		  CMP.ajax_stop();                      
	    };
		
		// Process the click on input
		CMP.ajax_start(this);
    	$.post(
	      '/ann/process_status_a', 
	      {
	        btnname: this.name
	      }, 
	      as_update
	    );		

		e.preventDefault();
		e.stopPropagation();
	});	
}

CMP.init_cart_buttons = function() {
	$('div.ad_cart_menu//input[@type="image"]').each( function() {
		CMP.init_cart_button(this);
	}); 
}

CMP.init_cart_button = function(elem) {
  $(elem).click(function(e) {
    // The update function, store this, to access it in there!
    var _$_ = this;
    function cb_update(json_doc) {
      var json = eval(json_doc);
      if (json.status.isError) {
        $(_$_).error(json.status.message);
      }
      else {
        $('#cart_top_menu').html(json.icon_code);
		var div = $(_$_).parents('div.ad_cart_menu'); 
	  	div.html(json.button_code);
		$('input[@type="image"]', div).each( function() {
			CMP.init_cart_button(this);
		});
      }
	  CMP.ajax_stop();                      
    };
    
    // Process the click on input
	CMP.ajax_start(this);
    $.post(
      '/cart/process_a', 
      {
	  	btnname: this.name
      }, 
      cb_update
    );
    
    // Do effect and stop event
	e.preventDefault();
    e.stopPropagation();
  });
};

var __price_new = "";

CMP.init_price_new = function() {
	var price_box = $('input#price').get(0);
	var state_select = $('select#id_state').get(0);
	
	if (price_box && state_select) {
		$(state_select).bind('change', function(e) {
			var option = this.options[this.selectedIndex];
			if (option) {
				if (option.text.substring(0, 3) == "Neu") {
					if (__price_new) {
						$(price_box).val(__price_new);
					}
				}
			}
		});
	} 
};

CMP.ajax_start = function(elem) {
	$('body').css({cursor:'wait'});
	var offset = $(elem).offset();
	var left = offset.left + 40;
	var top = offset.top - 20;
	$('#ajax_busy').css({position: 'absolute', left: left + 'px', top: top + 'px'}).show(); 
};

CMP.ajax_stop = function() { 
	$('body').css({cursor:'default'});
	$('#ajax_busy').hide(); 
};


CMP.init_ajax_busy = function() {
	$('#ajax_busy').ajaxStart(function(){
		$('body').css({cursor:'wait'});
		$(this).show(); 
	}).ajaxStop(function(){ 
		$('body').css({cursor:'default'});
		$(this).hide(); 
	});
};

$(document).ready(function() {
  //CMP.init_confirm_delete();
  CMP.init_thumbnail_lens();  
  CMP.init_cart_buttons();
  CMP.init_collapse();
  CMP.init_ad_status_buttons();
  CMP.init_price_new();
  //CMP.init_ajax_busy();
});

$(window).load(function() {
  CMP.focus_first_element();  
});
