var ns = document.layers ? true : false;
var ie = document.all && !window.opera ? true : false;;    // IEs
var dom = document.getElementById && !ie ? true : false;  // DOM-Browser

function addLoadEvent(func) {
  var wait=0;
  if(typeof addLoadEvent.arguments[1] != 'undefined') wait=addLoadEvent.arguments[1];
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
	var firstEvent=function(){
	  window.setTimeout(''+func+'',wait);
	}
	window.onload = function(){
	  firstEvent();
	   }
  } else {
	window.onload = function() {
	  if (oldonload) {
		oldonload();
	  }
	  if(typeof func == "function")  window.setTimeout(func,wait);
	}
  }
}
function addResizeEvent(func) {
  var oldonresize = window.onresize;
  if (typeof window.onresize != 'function') {
	window.onresize = func;
  } else {
	window.onresize = function() {
	  if (oldonresize) {
		oldonresize();
	  }
	   if(typeof func == "function")  func();
	}
  }
}
function sameHeight(ele1,ele2){
	if(typeof $j != 'function') return false;
	var h1=$j(ele1).height();
	var h2=$j(ele2).height();
	var pad1=parseInt($j(ele1).css('padding-top'))+parseInt($j(ele1).css('padding-bottom'));
	var pad2=parseInt($j(ele2).css('padding-top'))+parseInt($j(ele2).css('padding-bottom'));
	var h=h1>h2?h1:h2;
	$j(ele1).height(h-pad1);
	$j(ele2).height(h-pad2);

}

var force_std_popup = false;

function openPopup(id, center, p_top, p_left, p_width, p_height, typ) {
	if(typ == "gb" && force_std_popup == false) {
		if($('gb_'+(gbcounter-1))) $('gb_'+(gbcounter-1)).remove();

		var sL = $j(window).scrollLeft();
		var sT = $j(window).scrollTop();
		var wW = $j(window).width();
		var wH = $j(window).height();

		var gb = document.createElement("div");

		gb.className = "greyBoxPopup";
		if(center == '1') {
			p_top = Math.round((wH - p_height) / 2);
			if(p_top < 0) p_top = 10;

			p_left = Math.round((wW - p_width) / 2);
			if(p_left < 0) p_left = 10;
		}

		gb.style.top = p_top + sT + 'px';
		gb.style.left = p_left + sL + 'px';
		gb.id = "gb_"+gbcounter;


		var div_content = "<iframe src='/popup.php?nav_id="+id+"&typ=popup' id='gb_iframe' width='"+p_width+"' height='"+p_height+"' frameborder='0' scrolling='no'></iframe>";
		gb.innerHTML = div_content;
		$('gb_container').appendChild(gb);

		if(ie) $('gb_iframe').src = "/popup.php?nav_id="+id+"&typ=popup";

		if(isIEversion(6)) {
			$('gb_overlay').style.width = $j(document).width() - 18 + 'px';
			$('gb_overlay').style.height = $j(document).height()+ 'px';
		} else {
			$('gb_overlay').style.width = $j(document).width() + 'px';
			$('gb_overlay').style.height = $j(document).height() + 'px';
		}
		$j('#gb_overlay').show();
		gbcounter++;
	} else {
		if(center == '1') {
			p_top = Math.round((screen.height - p_height) / 2);
			if(p_top < 0) p_top = 10;

			p_left = Math.round((screen.width - p_width) / 2);
			if(p_left < 0) p_left = 10;
		}

		p_height = parseInt(p_height);

		window.open("/popup.php?nav_id="+id, "", "scrollbars=no, width="+p_width+", height="+p_height+", left="+p_left+", top="+p_top+", toolbar=no, status=no, location=no");
	}
}

function closeGBPopup() {
	if($('gb_'+(gbcounter-1))) $('gb_'+(gbcounter-1)).remove();
	$j('#gb_overlay').hide();
}

var gbcounter = 0;

function activateTab(tab){
  $j('#artice-tab-list > li').removeClass("selected");
  $j('#tab-li'+tab).addClass("selected");
  $j('.tabcontents > div').hide();
  $j('#article_tab_content'+tab).show();
}

function isIEversion(ver) {
	var browser = jQuery.browser;

	if(browser.msie == true && browser.version == ver) return true;
	else return false;
}

function number_format( number, decimals, dec_point, thousands_sep ) {
	var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals;
	var d = dec_point == undefined ? "," : dec_point;
	var t = thousands_sep == undefined ? "." : thousands_sep, s = n < 0 ? "-" : "";
	var i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
	return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
}

function displayLogin(){
  var sL = $j(window).scrollLeft();
  var sT = $j(window).scrollTop();
  var wW = $j(window).width();
  var wH = $j(window).height();

  var p_top = Math.round((wH - 200) / 2);
  if(p_top < 0) p_top = 10;

  var p_left = Math.round((wW - 500) / 2);
  if(p_left < 0) p_left = 10;

  var gb=$j("<iframe />");
  gb.attr("id","login_form_iframe");
  gb.attr("src","/bs_login.php");
  gb.attr("frameborder","0");
  gb.css({
	  width: "500px",
	  height: "220px",
	  top: p_top+'px',
	  left: p_left+'px',
	  position: "fixed",
	  zIndex: "5000",
	  backgroundColor: "#fff",
	  border: "1px solid #000"
	});
  if(isIEversion(6)) gb.css({position: "absolute"});

  /* der ie kann das nicht:
  var gb=$j.create('iframe',
	{
	  'src':'/bs_login.php',
	  'frameborder':'0',
	  'id':'login_form_iframe',
	  'style':'width:500px;height:220px;top:'+p_top+'px;left:'+p_left+'px;position:absolute;z-index:5000;background-color:#fff;border:1px solid #000;'
	},[""]
  );*/

  $j('#gb_container').append($j(gb));
  if(ie) $j('#login_form_iframe').attr('src','/bs_login.php');
  if(isIEversion(6)) window.setTimeout("$('login_form_iframe').src='/bs_login.php';",200);
  if(isIEversion(6) || isIEversion(8)) {
	  $j('#gb_overlay').css({width : $j(document).width() - 20 + 'px',
				 height : $j(document).height()+ 'px'
	  });
  } else {
	  $j('#gb_overlay').css({width : $j(document).width() + 'px',
				 height : $j(document).height()+ 'px'
	  });
  }
  $j('#gb_overlay').show();
}
function resizeObj(element_id,w,h,center){
  if($j('#'+element_id)){
	if(center){
	  var sL = $j(window).scrollLeft();
	  var sT = $j(window).scrollTop();
	  var wW = $j(window).width();
	  var wH = $j(window).height();

	  if(w>wW) w=wW-10;
	  if(h>wH) h=wH-10;

	  var p_top = Math.round((wH - h) / 2);
	  if(p_top < 0) p_top = 10;

	  var p_left = Math.round((wW - w) / 2);
	  if(p_left < 0) p_left = 10;

	  $j('#'+element_id).css({width:w,height:h,left:p_left,top:p_top});
	}else{
	  if(w>wW) w=wW-10;
	  if(h>wH) h=wH-10;
	  $j('#'+element_id).css({width:w,height:h});
	}
	var classes=$j('#'+element_id).attr('class').split(" ");
	$j.each(classes,function(c,n){
	  if(n.indexOf('UID')==0){
	// box...suche CLOSE...

	$j('.close'+n).css({
	  left: parseInt($j('#'+element_id).offset().left+$j('#'+element_id).width()+2)+"px"
	});
	if(center){
	  $j('.close'+n).css({
	  top: p_top+"px"
	});
	}
	  }
	});
  }
}
function hideLogin(){
  $j('#gb_overlay').hide();
  $j('#gb_container').html("");
}

function toggle_shopping_cart(id) {
	$j('#basket_block_'+id).slideToggle('slow', function() {
		if($j('#vendor_inner_'+id).attr("class") == "vendor_inner")
			$j('#vendor_inner_'+id).attr("class", "vendor_inner_inactive");
		else
			$j('#vendor_inner_'+id).attr("class", "vendor_inner");
	});
}

function toggle_customer_info(id) {
	if(toggle_customer_info.arguments.length > 1) var edit = true;
	else var edit = false;

	$j('#customer_info_block_'+id).slideToggle('slow', function() {
		if($j('#customer_info_'+id).attr("class") == "customer_headline_span") {
			$j('#customer_info_'+id).attr("class", "customer_headline_span_inactive");
			var _dir = "out";
		} else {
			$j('#customer_info_'+id).attr("class", "customer_headline_span");
			var _dir = "in";
		}

		if(edit == true) Cashbox.toggleAddressLabels(id, _dir);
	});
}

function trim (zeichenkette) {
  return zeichenkette.replace (/^\s+/, '').replace (/\s+$/, '');
}

function objloading(obj,txt){
	var overlay=$j("<div>"+txt+"</div>");
	overlay.addClass('gb_doverlay');
	overlay.css({zIndex:999,backgroundColor:'#ffffff',textAlign:'center',left:0,opacity:'0.7',position:'absolute',top:'0',backgroundImage:'url(/xmedia/images/ajax-loader.gif)',backgroundPosition:'center',backgroundRepeat:'no-repeat'});
	if($j(obj)){
	  var p = $j(obj);
	  var offset = p.offset();
	  var totalWidth = p.width();
	  totalWidth += parseInt(p.css("padding-left"), 10) + parseInt(p.css("padding-right"), 10); //Total Padding Width
	  totalWidth += parseInt(p.css("margin-left"), 10) + parseInt(p.css("margin-right"), 10); //Total Margin Width
	  //totalWidth += parseInt(p.css("borderLeftWidth"), 10) + parseInt(p.css("borderRightWidth"), 10); //Total Border Width
	  var totalHeight = p.height();
	  totalHeight += parseInt(p.css("padding-top"), 10) + parseInt(p.css("padding-bottom"), 10); //Total Padding Width
	  totalHeight += parseInt(p.css("margin-top"), 10) + parseInt(p.css("margin-bottom"), 10); //Total Margin Width
	  //totalHeight += parseInt(p.css("borderTopWidth"), 10) + parseInt(p.css("borderBottomWidth"), 10); //Total Border Width

	  overlay.width(totalWidth + 'px');
	  overlay.height(totalHeight + 'px');


	  overlay.css({top:Math.floor(offset.top+1)+'px',left:Math.ceil(offset.left+1)+'px'});
	  $j('.body').append($j(overlay));
	}
}

function payBillViaAccount(question, id_ord_order, filename) {
	if(window.confirm(question)) {
		location.href = filename+'&pay='+id_ord_order;
	}
}

var idAccountTransfer = {
	checkAmount : function(amount) {
		jQuery.getJSON("ajax/mlm/mlm_id_account_transfer_101.php?action=checkAmount&amount="+amount, function(data) {
				if(data.error) {
					jQuery('#ajax_response').html(data.error);
				} else {
					if(jQuery('#tr_customer_nr').length > 0) {
						jQuery('#tr_customer_nr').show();
					}
					jQuery('#ajax_response').html('');
				}
			}
		);
	},

	lockReceiver : function(receiverID) {
		jQuery.getJSON("ajax/mlm/mlm_id_account_transfer_101.php?action=checkReceiver&receiverID="+receiverID, function(data) {
				if(data.error) {
					jQuery('#ajax_response').html(data.error);
					jQuery('#valid_receiver').html("");
				} else {
					content = "";
					if(data.success.name_1) content += "<b>" + data.success.name_1 + "</b><br />";
					if(data.success.name_2) content += data.success.name_2 + ", ";
					if(data.success.name_3) content += data.success.name_3;
					content += "<br />";
					if(data.success.street) content += data.success.street + "<br />";
					if(data.success.zip_code && data.success.location) content += data.success.zip_code + " " + data.success.location + "<br />";

					jQuery('#valid_receiver').html(content);
					jQuery('#ajax_response').html("");

					jQuery('#tr_transaction_text').show();
					jQuery('#tr_one_time_password').show();
					jQuery('#tr_send_money').show();

					receiverIsLocked = true;
				}
			}
		);
	},

	checkChars : function(val, max) {
		jQuery('#transaction_text_chars').html(val.length + " / " + max);
	}
}

var mlm_translate = {

  /**
   * welche Elemente sollen übersetzt werden?
   **/
  stack : new Array(),

  /**
   * fügt ein element zum übersetzungs-stack hinzu
   * @param dom_element
   * @param id_base_translation {string} Optionale id; wird nichts angegeben, so wird der HTML-Inhalt gelesen
   **/
  get : function(dom_element, id_base_translation)
  {
	mlm_translate.stack[mlm_translate.stack.length] = { element: dom_element, id : id_base_translation };
  },

  /**
   * Alias für GET
   * @param dom_element
   * @param id_base_translation {string} Optionale id; wird nichts angegeben, so wird der HTML-Inhalt gelesen
   **/
  add : function(dom_element, id_base_translation)
  {
	mlm_translate.get(dom_element, id_base_translation);
  },

  /**
   * _onLoad-Action
   * arbeitet den Stack ab
   **/
  _onLoad : function()
  {
	jQuery.each(mlm_translate.stack, function(_n, _e)
	{
	  // wenn das Element existiert ...
	  if(jQuery(_e.element))
	  {
	// wenn kein key gegeben, dann den inhalt des element holen
	if(typeof _e.id == "undefined")
	{
	  _e.id = jQuery(_e.element).html();
	}
	if(_e.id != "")
	{
	  jQuery.getJSON("ajax/mlm/mlm_translate.php?id_base_translation="+_e.id, function(data) {
		if(data.error || data.length == 0)
		{
		  // von nichts kommt nichts...
		  //alert(data.error);
		}
		else{
		  jQuery(_e.element).html(data.translation);
		}
	  });
	}
	  }
	});
  }
}

/**
* Ersetzt auf der Artikeldetailseite den ersten Tab und den ersten Tab-Content
* @param string data Die Daten
*/
function updateArticleShopData(data) {
	if (data.length > 0) {
		// String to Json Object
		var data = eval('(' + data + ')');

		if (data.shop_tab_desc.length > 0) {
			jQuery('ul#artice-tab-list li#tab-li0 a').html(data.shop_tab_desc);
		}

		if (data.shop_html_desc.length > 0) {
			jQuery('div#article_tab_content0').html(data.shop_html_desc);
		}

		jQuery('ul#artice-tab-list li#tab-li0').show();
		activateTab('0');
	}
}

function hideArticleTabNull() {
	jQuery('ul#artice-tab-list li#tab-li0').hide();
	activateTab('1');
}

// OnLoad registrieren...
jQuery(document).ready(function(){
  mlm_translate._onLoad();
});

function in_array (needle, haystack, argStrict) {
	// Checks if the given value exists in the array
	//
	// version: 1004.2314
	// discuss at: http://phpjs.org/functions/in_array    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	// +   improved by: vlado houba
	// +   input by: Billy
	// +   bugfixed by: Brett Zamir (http://brett-zamir.me)
	// *     example 1: in_array('van', ['Kevin', 'van', 'Zonneveld']);    // *     returns 1: true
	// *     example 2: in_array('vlado', {0: 'Kevin', vlado: 'van', 1: 'Zonneveld'});
	// *     returns 2: false
	// *     example 3: in_array(1, ['1', '2', '3']);
	// *     returns 3: true    // *     example 3: in_array(1, ['1', '2', '3'], false);
	// *     returns 3: true
	// *     example 4: in_array(1, ['1', '2', '3'], true);
	// *     returns 4: false
	var key = '', strict = !!argStrict;
	if (strict) {
		for (key in haystack) {
			if (haystack[key] === needle) {
				return true;            }
		}
	} else {
		for (key in haystack) {
			if (haystack[key] == needle) {                return true;
			}
		}
	}
	 return false;
}

// Width and height for extended article info
var fancyExtendedArticleWidth = 800;
var fancyExtendedArticleHeihgt = 600;


// Automatische Fancybox
jQuery(document).ready(function() {
	jQuery('a').each(function(key, obj) {
		var rel = jQuery(this).attr('rel');
		var fancyboxes = ['fancybox', 'fancybox640', 'fancybox800', 'fancybox1024', 'fancyboxMax'];

		if (jQuery.inArray(rel, fancyboxes) >= 0) {
			var fancyWidth = fancyExtendedArticleWidth;
			var fancyHeight = fancyExtendedArticleHeihgt;

			switch (rel) {
				case 'fancybox640':
					fancyWidth 	= 640;
					fancyHeight = 480;
					break;

				case 'fancybox800':
					fancyWidth 	= 800;
					fancyHeight = 600;
					break;

				case 'fancybox1024':
					fancyWidth 	= 1024;
					fancyHeight = 768;
					break;

				case 'fancyboxMax':
					fancyWidth 	= jQuery(window).width();
					fancyHeight = jQuery(window).height();
					break;
			}

			jQuery(this).fancybox({
				centerOnScroll 	: true,
				type			: 'iframe',
				cyclic          : false,
				width			: fancyWidth,
				height	 		: fancyHeight,
				showNavArrows   : false
			});
		}
	});
});

// Automatische Colorbox
jQuery(document).ready(function() {
	jQuery('a').each(function(key, obj) {
		var rel = jQuery(this).attr('rel');
		var colorboxes = ['colorbox', 'colorbox640', 'colorbox800', 'colorbox1024', 'colorboxMax'];

		if (jQuery.inArray(rel, colorboxes) >= 0) {
			var colorWidth  = 800;
			var colorHeight = 600;

			switch (rel) {
				case 'colorbox640':
					colorWidth      = 640;
					colorHeight     = 480;
					break;

				case 'colorbox800':
					colorWidth      = 800;
					colorHeight     = 600;
					break;

				case 'colorbox1024':
					colorWidth      = 1024;
					colorHeight     = 768;
					break;

				case 'colorboxMax':
					colorWidth      = jQuery(window).width() - 100;
					colorHeight     = jQuery(window).height() - 100;
					break;
			}

			jQuery(this).colorbox({
				arrowKey    : false,
				loop        : false,
				iframe      : true,
				width       : colorWidth,
				height      : colorHeight
			});
		}
	});
});

/**
  * setzt die Defaults aus data an passende Formularfelder im Container
  **/
 jQuery.fn.setDefaults = function(data)
 {
	 var _stacked = new Array();

	 jQuery.each(jQuery(this).find(":input"), function(n,e)
	 {
		 var _k = jQuery(e).attr("name");
		 var _arrRegx = /(\w+)\[(\w+)\]/;
		 var _arrTReg = /(\w+)\[(\w+)\]\[%num%]\[(\w+)\]/;
		 var _arrDReg = /(\w+)\[(\w+)\]\[(\w+)\]/;

		 if(_arrRegx.test(_k))
		 {
			 var _key1 = RegExp.$1;
			 var _key2 = RegExp.$2;

			 if(typeof data[_key1] != "undefined"
				&& typeof data[_key1][_key2] != "undefined")
			 {
				 if(_arrTReg.test(_k))
				 {
					 var _key3 = RegExp.$3;

					 // mehrfacher Wert... %num% "clonen" ...
					 var _parent = jQuery(e).parent();
					 if(!in_array(_parent.attr("id"), _stacked))
					 {
						 // Liste aufr�umen
						 var clean_function = _parent.data('clean');
						 if(typeof clean_function != "undefined" && clean_function !== null)
						 {
							 eval(clean_function+"()");
						 }

						 // nur hinzuf�gen, wenn die parent-id noch nicht durchlaufen wurde (zeilenweise)
						 _stacked.push(_parent.attr("id"));
						 // Am Parent-Objekt muss eine "create" Funktion h�ngen; dieser wird der Datensatz als
						 // erster Parameter �bergeben. Diese Funktion sollte dann den %num% Datensatz durch den
						 // Key entsprechend erweitern...
						 var create_function = _parent.data('create');
						 if(typeof create_function != "undefined" && create_function !== null)
						 {
							 for(n in data[_key1][_key2])
							 {
								 eval(create_function + "(" + "data['"+_key1+"']['"+_key2+"']["+n+"]" + ")");
							 }
						 }
					 }
				 }
		 else if(_arrDReg.test(_k))
		 {
		 var _key3 = RegExp.$3;
		 if(typeof data[_key1][_key2][_key3] != "undefined"){
			 if(jQuery(e).attr("type") == "radio" || jQuery(e).attr("type") == "checkbox")
			 {
			 if(jQuery(e).val() == data[_key1][_key2][_key3])
				 jQuery(e).attr("checked",true);
			 //jQuery(e).find("[value='"+data[_key1][_key2][_key3]+"']").attr("checked",true);
			 //alert(data[_key1][_key2][_key3]);
			 }else{
			 jQuery(e).val(data[_key1][_key2][_key3]);
			 }
		 }
		 }
				 else{ // einfacher Wert ...
					 jQuery(e).val(data[_key1][_key2]);
				 }
			 }
		 }
		 else
		 {
			 if(typeof data[_k] != "undefined")
			 {
				 jQuery(e).val(data[_k]);
			 }
		 }
	 });
 }

 /**
  * �bernimmt die Formularwerte in ein JS-Objekt
  * unsterst�tzt:
  *   name="key"
  *   name="key[sub]"
  * ..mehrdimensionale Array m�ssten noch implementiert werden
  * !! Achtung, der aktuelle Wert wird im Objekt �berschrieben !!
  * setzt nur vorhandene Elemente!
  **/
 jQuery.fn.applyValuesTo = function(obj, applyToUndefined)
 {
	 jQuery.each(jQuery(this).find(":input"), function(n,e)
	 {
		 var _k = jQuery(e).attr("name");
		 var _arrRegx = /(\w+)\[(\w+)\]/;
		 if(_arrRegx.test(_k))
		 {
			 var _key1 = RegExp.$1;
			 var _key2 = RegExp.$2;
			 if(typeof applyToUndefined != "undefined" ||
				(typeof obj[_key1] != "undefined"
				&& typeof obj[_key1][_key2] != "undefined"))
			 {
				 obj[_key1][_key2] = jQuery(e).val();
			 }
		 }
		 else
		 {
			 if(typeof applyToUndefined != "undefined"
				|| typeof obj[_k] != "undefined")
			 {
				 obj[_k] = jQuery(e).val();
			 }
		 }
	 });
 }

/**
 * Removes whitespaces from an input value
 */
function trimFieldValue(field)
{
	jQuery(field).val(jQuery(field).val().trim());
}

jQuery.fn.inputValidationMinMax = function(failure_func)
{
  var input = jQuery(this);
  var value = input.val();
  if(input.attr('min'))
  {
	if(parseInt(input.attr('min'))>parseInt(value))
	{
	  input.val(input.attr('min'));
	  if(typeof failure_func != 'undefined')
		eval(failure_func);
	}
  }
  if(input.attr('max'))
  {
	if(parseInt(input.attr('max'))<parseInt(value))
	{
	  input.val(input.attr('max'));
	  if(typeof failure_func != 'undefined')
		eval(failure_func);
	}
  }
}

