function imageSwitchEx(lID, nID, cImagePath, cBigImagePath)
{
	var image = $('#image' + nID);
	var src = image.attr("src");
	if (typeof cImagePath != "undefined")
	{
		var overlay = $('#overlay' + nID);
		overlay.css("display", "block");
		objImage = new Image();
		objImage.onload = function() {
			imagePreloadedEx(nID, cImagePath, cBigImagePath);
		};
		objImage.src = cImagePath;
	}
	else {
		image.attr("src", images_arr[nID]);
	}
}

function imagePreloadedEx(nID, cImagePath, cBigImagePath)
{
   imagePreloaded(nID, cImagePath);
	if (nID == 0)
	{
		$('#zoom1').attr('href', cBigImagePath);
		$('#zoom1 img').attr('src', cImagePath);

		if ($('#zoom1').hasClass('cloud-zoom'))
		{
			$('#zoom1').data('zoom').destroy();
			$('#zoom1').CloudZoom();
		}
	}
}

var images_arr = new Array();
function imageSwitch(nID, cImagePath)
{
	var image = $('#image' + nID);
	var src = image.attr("src");
	if (typeof cImagePath != "undefined")
	{
		var overlay = $('#overlay' + nID);
		overlay.css("display", "block");
		objImage = new Image();
		objImage.onload = function() {
			imagePreloaded(nID, cImagePath);
		};
		objImage.src = cImagePath;
	}
	else {
		image.attr("src", images_arr[nID]);
	}
}

function imagePreloaded(nID, cImagePath)
{
	var overlay = $('#overlay' + nID);
	var image = $('#image' + nID);
	var src = image.attr("src");
	images_arr[nID] = src;
	image.attr("src", cImagePath);
	overlay.css("display", "none");
}

// Falls nVLKeys gesetzt ist und 1 ist, dann soll die Funktion die Vergleichsliste nicht aus der Session aufbauen
// Sondern die Keys der Artikel�bersicht nutzen
function showCompareList(nVLKeys)
{
	if(typeof(nVLKeys) == "undefined")
		nVLKeys = 0;

	myCallback = xajax.callback.create();
	myCallback.onComplete = function(obj) {
		data = obj.context.compareHTML;
		if (typeof data == 'string' && data.length > 0)
		{
			$.modal(data, {
				close: true,
				opacity: 30,
				appendTo: '#page',
				persist: true,
				onOpen: function (dialog) {
					dialog.overlay.fadeIn('slow', function () {
						dialog.data.hide();
						dialog.container.fadeIn('slow', function () {
							dialog.data.slideDown('slow');
						});
					});
				}
			});
		}
	}
	xajax.call('gibVergleichsliste', { parameters: [nVLKeys], callback: myCallback, context: this } );
	return false;
}

function setSelectionWizardAnswer(kMerkmalWert, kAuswahlAssistentFrage, nFrage, kKategorie)
{
    myCallback = xajax.callback.create();
	myCallback.onComplete = function(obj) {
        data = obj.context.response;
		console.log(data);
    }
    xajax.call('setSelectionWizardAnswerAjax', { parameters: [kMerkmalWert, kAuswahlAssistentFrage, nFrage, kKategorie], callback: myCallback, context: this } );
	return false;
}

function resetSelectionWizardAnswer(nFrage, kKategorie)
{
    myCallback = xajax.callback.create();
	myCallback.onComplete = function(obj) {
        data = obj.context.response;
		console.log(data);
    }
    xajax.call('resetSelectionWizardAnswerAjax', { parameters: [nFrage, kKategorie], callback: myCallback, context: this } );
	return false;
}

function getPLZList()
{
	if ($('input.plz_input').length == 0 ||
		 $('select.country_input').length == 0)
		return;

	var plz = $('input.plz_input').val();
	var country = $('select.country_input').val();

	if (plz.length < 4 || country.length == 0)
		return;

	myCallback = xajax.callback.create();
	myCallback.onComplete = function(obj) {
		data = obj.context.plz_data;

		if ($('input.city_input').length <= 0)
			return;

		if ($('#form_city_dropdown').length || data.length > 0)
		{
			$('#form_city_dropdown').slideUp();
			$('#form_city_dropdown').remove();
		}

		if (data.length == 0)
			return;

		var dropdown = $('<div></div>')
			.attr('id', 'form_city_dropdown')
			.css({
				display: 'none',
				width: $('input.city_input').outerWidth(true),
				position: 'absolute',
				left: $('input.city_input').offset().left,
				top: $('input.city_input').offset().top + $('input.city_input').outerHeight(true),
				zIndex: 1004
			})
			.appendTo('body');

		var list = $('<ul></ul>');
		$.each(data, function(index, o) {
			var item = $('<li></li>').html(o.cOrt);
			item.click(function() {
				$('#form_city_dropdown').slideUp();
				$('input.city_input').val($(this).html());
			});
			list.append(item);
		});
		dropdown.append(list).slideDown();
	}
	xajax.call('gibPLZInfo', { parameters: [plz, country], callback: myCallback, context: this } );
}

/*
 *  shipping costs
 */
function calcShippingCosts(kArtikel_arr, container)
{
	myCallback = xajax.callback.create();
	myCallback.onComplete = function(obj) {
		data = obj.context.response;
		console.log(data);

		if ($(container).length == 0)
			return;

		if (typeof data == "object") {
			$(container).html(data.cText);
			$(container).slideDown(250);
		}
		else {
			$(container).hide();
		}
	}
	xajax.call('ermittleVersandkostenAjax', { parameters: [kArtikel_arr], callback: myCallback, context: this } );
}


/*
 *  extended design
 */
function switchStyle(ed, style)
{
   $('#styled_view > li').each(function(idx, item) {
      $(item).removeClass('list').removeClass('gallery').removeClass('mosaic');
      $(item).addClass(style);
   });

   $('#ed_list, #ed_gallery, #ed_mosaic').removeClass('active');
   $('#ed_' + style).addClass('active');

   xajax_setzeErweiterteDarstellung(ed);
}

/*
 *  overlay
 */
function set_overlay(id, pos, margin, image)
{
   $(id).load(function() {
      $(id).wrap('<span class="overlay_image_wrapper" />');
      var off = $(this).position();
      $(id).after('<div class="overlay_image overlay_image'+pos+'" style="top:'+(parseInt(off.top)+parseInt(margin))+'px;left:'+(parseInt(off.left)+parseInt(margin))+'px;width:'+ (parseInt($(this)[0].offsetWidth) - parseInt((margin*2))) +'px;height:'+ (parseInt($(this)[0].offsetHeight) - parseInt((margin*2))) +'px;background-image:url(\''+image+'\')" />');
   });
}

/*
 *  popups
 */
function show_popup(mixed, bData, bFast, fnCreated) {
   var dialog = bData ? mixed : '#popup' + mixed;
   $(dialog).modal({
		opacity: 30,
		appendTo: '#page',
		persist: true,
		close: true,
		onOpen: function (dialog) {
			dialog.overlay.fadeIn((typeof bFast != 'undefined' && bFast) ? 'fast' : 'slow', function () {
				dialog.data.hide();
				dialog.container.fadeIn((typeof bFast != 'undefined' && bFast) ? 'fast' : 'slow', function () {
					dialog.data.slideDown((typeof bFast != 'undefined' && bFast) ? 'fast' : 'slow');
					if (typeof fnCreated == 'function')
						fnCreated();
				});
			});
		},
		onShow: function (dialog) {

		}
	});
}

/*
 *  image popups
 */
function show_image(url) {
   var dialog = $('<div class="tcenter"><img src="'+url+'" />');
   $(dialog).modal({close: true, onOpen: function (dialog) {
      dialog.overlay.fadeIn('slow', function () {
         dialog.data.hide();
         dialog.container.fadeIn('slow', function () {
            dialog.data.slideDown('slow');
         });
      });
   }});
}

/*
 *  register available popups
 */
function register_popups() {
	if ($('.popup_image').length > 0)
	{
		$('.popup_image').each(function(idx, item) {
			$(item).bind('click', function() {
				var href = $(this).attr('href');
				show_image(href);
				return false;
			});
		});
	}

	if ($('.popup').length > 0)
	{
		$('.popup').each(function(idx, item) {
			$(item).bind('click', function() {
				show_popup($(this).attr('id'));
				return false;
			});
		});
	}
}

/*
 *  expander
 */
function register_expander() {
   $('.expander').each(function(idx, item) {
      var ex = '#ep_' + $(this).attr('id');
      var lnk = '#' + $(this).attr('id');

      $(this).click(function(e) {
         e.preventDefault();
         $(ex).toggle();
         $(lnk).toggleClass("active");
      });

      $(ex).mouseup(function() {
         return false;
      });

      $(document).mouseup(function(e) {
         if ($(lnk).hasClass("active"))
         {
            $(lnk).removeClass("active");
            $(ex).hide();
         }
      });
   });
}

/*
 *  switch style
 */
function switchStylestyle(styleName)
{
   $('link[@rel*=style][title]').each(function(i)
   {
      this.disabled = true;
      if (this.getAttribute('title') == styleName) this.disabled = false;
   });
   $.cookie('style', styleName, { expires: 7 });
}

function loadStyle()
{
   $('.styleswitch').click(function() {
		var newStyle = this.getAttribute("rel");
		$('body').fadeOut("fast", function()
		{
	      switchStylestyle(newStyle);
			$('body').fadeIn("fast");
		});
	   return false;
   });

   var style = $.cookie('style');
   if (style) switchStylestyle(style);
}

/*
 *  placeholder
 */
function setPlaceholder()
{
	$(".placeholder").each(function(idx, item)
	{
		var item = $(this);
		var text = item.attr("title");
		var form = item.parents("form:first");

		if (item.val() === "")
			item.val(text);

		item.bind("focus.placeholder", function(event) {
			if (item.val() === text)
				item.val("");
		});

		item.bind("blur.placeholder", function(event) {
			if (item.val() === "")
				item.val(text);
		});

		form.bind("submit.placeholder", function(event) {
			if (item.val() === text)
				item.val("");
		});
	});
}

function m_submit_form( nameAttr, valueAttr, formId ) {
	if (nameAttr) { $("#"+formId).prepend("<input type=\"hidden\" name=\"" + nameAttr + "\" value=\""+valueAttr+"\" />"); }
	$("#"+formId).submit();
	$(this).replaceWith("<span class=\"styledbutton\"><span>"+$(this).text()+"</span></span>");
}

function styleButtons() {
	$("button.cnt_button").each(function() {
		var btnContent = $(this).text();
		if($(this).attr('onclick')) {
			var onClickValue = $(this).attr('onclick');
		} else {
			var onClickValue = "m_submit_form('"+$(this).attr('name')+"', '"+$(this).text()+"', '"+$(this).parents('form').attr('id')+"')";
			//"document.getElementById('" + $(this).parents('form').attr('id') + "').submit(); return false";
		}
		//$(this).removeClass('submitbutton');
		$(this).replaceWith("<a "+($(this).attr('id') ? "id=\""+$(this).attr('id')+"\" " : "")+"class=\""+$(this).attr('class')+"\" href=\"#"+$(this).attr('name')+"\" onclick=\""+onClickValue+"\"><span>"+btnContent+"</span></a>");
	});
}

/*
 *  comment helpful element
 */
function register_helpful() {
	$(".use_helpful").each(function() {
		var a = $(this).attr('id');
		if (!$('#' + a).hasClass('jsenabled'))
			$('#' + a).addClass('jsenabled');

		$(this).mouseenter(function() {
			$('#' + a).addClass('active');
			$('#' + a + ' p.helpfully').fadeIn(250);
		}).mouseleave(function() {
			$('#' + a + ' p.helpfully').fadeOut(100);
			$('#' + a).removeClass('active');
		});
	});
}

function add_url_param(url, params) {
   var newAdditionalURL = '';
   var tempArray = url.split('?');
   var baseURL = tempArray[0];
   var aditionalURL = tempArray[1]; 
   var temp = '';
   
   if (aditionalURL) {
      var tempArray = aditionalURL.split('&');
      for (var i in tempArray) {
         newAdditionalURL += temp + tempArray[i];
         temp = '&';
      }
   }
   
   var finalURL = baseURL + '?' + newAdditionalURL + temp + params;
   return finalURL;
}

/*
 *  vat info
 */
function register_vatinfo() {
   if ($('.vat_info a').length > 0) {
      $('.vat_info a').each(function(idx, item) {
         $(item).bind('click', function() {
            var url = add_url_param($(this).attr('href'), 'exclusive_content=1');
            open_window(url);
            return false;
         });
      });
   }
}

/*
 *  submit default on key enter
 */
function submit_default_enter() {
	$('form').each(function() {
		$('input').keypress(function(e) {
			if(e.which == 10 || e.which == 13)
				this.form.submit();
		});
	});
}

/*
 *  window popup
 */
function open_window(url, width, height) {

	width = width || 1000;
	height = height || 650;

	var left = (screen.width - width) / 2;
	var top = (screen.height - height) / 2;

	var opt = "width=" + width + ",height=" + height + ",top=" + top + ",left=" + left + ",scrollbars=yes,location=no,directories=no,status=no,menubar=no,toolbar=no,resizable=no,dependent=no";
   
	var wnd = window.open(url, "mypopup", opt);
   
   wnd.resizeTo(width, height);
   wnd.moveTo(left, top);
   wnd.focus();
   
	return false;
}

/*
 *  format file size
 */
function formatSize(size) {

   var fileSize = Math.round(size / 1024);
   var suffix   = 'KB';
   
   if (fileSize > 1000)
   {
      fileSize = Math.round(fileSize / 1000);
      suffix   = 'MB';
   }
   
   var fileSizeParts = fileSize.toString().split('.');
   fileSize = fileSizeParts[0];
   
   if (fileSizeParts.length > 1)
      fileSize += '.' + fileSizeParts[1].substr(0,2);

   fileSize += suffix;
   
   return fileSize;
}

function ws_script(){

	$('input.paymethod').change(function(){
		ci = $(this).attr('id');
		$('input.paymethod').each(function(){
			currId = $(this).attr('id');
			if(ci == currId){
				$('label[for='+currId+'] p').show();	
			}else{
				$('label[for='+currId+'] p').hide();
			}		
		});
	});
}

/*
 *  document ready
 */
$(document).ready(function() {
   register_popups();
   register_expander();
   $(".tooltip").tipTip();

   $("#suggest").focus().autocomplete([]);

   // highlight input labels
   $(':input').focus(function() {
      var id = $(this).attr('id');
      $("label[for$='"+id+"']").addClass('active');
   }).blur(function() {
      var id = $(this).attr('id');
      $("label[for$='"+id+"']").removeClass('active');
   });

   // ie outline fix
   $('a').focus(function() {
      $(this).attr("hideFocus", "hidefocus");
   });

	// maintenance
	if ($('#maintenance_mode').length > 0)
		$('#maintenance_mode').delay(5000).slideUp(500);

	// remove focus from input
	$('#submit_search').focus();
	
	ws_script();

	submit_default_enter();
	register_helpful();
   register_vatinfo();
	setPlaceholder();
	image_preview();
});

