/*
 *  overlay
 */
function set_overlay(id, pos, margin, image)
{  
   $(id).load(function() {
      $(id).wrap('<div class="overlay" />');
      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+'\')" />');
   });
}

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() {
	/* macht Probleme (leitet button-klicks auf Startseite um), erstmal deaktiviert */
/*	
 	$(".article_actions button.submitbutton").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).parents('form').attr('id')+"\" onclick=\""+onClickValue+"\"><span>"+btnContent+"</span></a>"); 
	});
*/
}




/*
 *  Modal Dialog Helper Function
 */
function show_modal(modal_id) {
   var dialogid = '#' + modal_id;
	$(document).ready(function(){
		var triggerid= modal_id + 'trigger';
		$(dialogid).before('<a id="'+triggerid+'" href="'+dialogid+'" class="hidden"></a>');

		$('#'+triggerid).fancybox({
			'hideOnContentClick': true, 
			'onClosed'		: function() {
				$(dialogid).remove();
			}
		});

		//trigger click to load fancybox
		$('#'+triggerid).trigger('click');
	});
}

function show_popup(mixed, bData, bFast, fnCreated) {
   var dialog = bData ? mixed : '#popup' + mixed;
   $(dialog).fancybox({
		'hideOnContentClick': true, 
		'onClosed'		: function() {
			$(dialog).remove();
		}
	});
}


function setModalBindings() {
	$(document).ready(function(){
		$("a.modal_popup").fancybox({
			'titleShow': false, 
			'enableEscapeButton': true, 
			'showCloseButton': true, 
			'transitionIn': 'elastic'
		});
		
		$("a.zoomable").fancybox({
			'titleShow': true, 
			'titlePosition': 'inside', 
			'hideOnContentClick': true, 
			'transitionIn': 'elastic', 
			'transitionOut': 'elastic'
		});
		
		if ($('.popup').length > 0)
		{
			$('.popup').each(function(idx, item) {
				$(item).bind('click', function() {
					show_popup($(this).attr('id'));
					return false;
				});
			});
		}
		
		if ($('.vat_info a').length > 0) { 
			$('.vat_info a').each(function(idx, item) {
				$(item).bind('click', function() {
					open_window( add_url_param($(this).attr('href'), 'exclusive_content=1') );
					return false; 
				});
			});
		}
	});
}

function initTips() { 
	$(".tooltip, .vat_info .tooltitle").tipTip();
}


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


/*
 *  window popup
 */
function open_window(url, width, height) {
	width = width || 680;
	height = height || 495;
	
	$.fancybox({
		'padding'		: 0,
		'autoScale'		: false,
		'transitionIn'	: 'none',
		'transitionOut'	: 'none',
		'title'			: this.title,
		'width'			: width,
		'height'		: height,
		'href'			: url,
		'type'			: 'ajax'
	});
	return false;
}


//Falls nVLKeys gesetzt ist und 1 ist, dann soll die Funktion die Vergleichsliste nicht aus der Session aufbauen
//Sondern die Keys der Artikeluebersicht nutzen
function showCompareList(nVLKeys, bWarenkorb)
{
	if(typeof(nVLKeys) == "undefined")
		nVLKeys = 0;
	
	if(typeof(bWarenkorb) == "undefined")
		bWarenkorb = 1;

	myCallback = xajax.callback.create();
	myCallback.onComplete = function(obj) {
		data = obj.context.compareHTML;
		if (typeof data == 'string' && data.length > 0)
		{
			$.fancybox(data, { 
				//'hideOnContentClick': true, 
				'autoScale'		: true
			});
		}
	}
	xajax.call('gibVergleichsliste', { parameters: [nVLKeys, bWarenkorb], 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;
}

/*
 *  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 increaseQuantity(obj, min, max) {
   var val = parseInt($(obj).val());
   
   if (typeof max == 'number')
      if (val + 1 > parseFloat(max))
         return false;
   
   $(obj).val(++val);
   $(obj).trigger('change');
   return false;
}

function decreaseQuantity(obj, min, max) {
   var val = parseInt($(obj).val());
   
   if (typeof min == 'number')
      if (val - 1 < parseFloat(min))
         return false;
   
   $(obj).val(--val);
   $(obj).trigger('change');
   return false;
}

function register_sidebox_autoscroll() {
   $(".sidebox").last().each(function(idx, item) {
      if ($(this).hasClass('autoscroll')) {
         var top = $(item).offset().top;

         $(item).css({
            'width' : $(item).width(),
            'position' : 'absolute',
            'height' : 'auto',
            'top' : top
         });
         
         $(window).scroll(function() {        
            var offset = $(document).scrollTop();
            var max = $('#content').offset().top + $('#content').outerHeight();
            
            if (offset < top) offset = top;
            if (offset > top) offset += 10;
               
            var maxoff = offset + $(item).outerHeight();
            
            if (maxoff <= max) {
               $(item).stop();
               $(item).animate({top: offset}, 250, 'swing');
            }
         });
      }
   });
}

$(document).ready(function(){
	styleButtons();
	setModalBindings();
	initTips();
	// execute cronjob
	//xajax_executeCron();
});
