$(function() {

	$("#bubble").fadeIn(2000);
	
  	
	$('#product_description table:first tr:child:first').css("background-color","#C30008");
	$('#product_description table:first tr:child:first strong').css("color","#FFF");
	$('#product_description table:first tr:child:first strong').css("padding-left","8px");
	$('#product_description table:first tr td:first').attr("colspan",2);
	$('#product_description table:first tr td').css('border-bottom','1px solid #CCC'); 
	
	
	$('#product_description table:first tr td table tr td:first').css("font-size","20px");
	$('#product_description table:first tr td table tr td:first').css("color","#C30008");
	$('#product_description table:first tr td table tr td:first').attr("colspan",2);
	$('#product_description table:first tr td table tr td:first strong ').replaceWith($('#product_name').html());
	$('#product_description table tr td strong:contains("Sonderfunktionen")').css("font-size","20px");
	$('#product_description table tr td strong:contains("Sonderfunktionen")').css("color","#C30008");
	$('#product_description table tr td strong:contains("Sonderfunktionen")').css("font-weight","normal");
	
	$('#button_box_customerlogin').click( function(e) { $('#box_customerlogin').slideDown(500); $(this).slideUp(500); $('#uselogin').val(1); } );
	
	$('#payment').change( function()
	{ 
		if( $('#payment option:selected').val() == 'lastschrift' )
		{
			$('#bankdetails').show();
		}
		else
		{
			$('#bankdetails').hide();
		}
	} );
	
	$('#order').click( function(e) { if( !$('#agb').is(':checked') )  { alert('Bitte akzeptieren Sie die AGBs.');  return false; } } );
	

});

	var removeTemp = function() { $("#bubble").fadeOut('slow', function() { $(this).remove(); }); };
	window.setTimeout(removeTemp,7000);
	

function setStyle()
{
	
	$('#product_description table:last tr:child:first').css("background-color","#C30008");
	$('#product_description table:last tr:child:first strong').css("color","#FFF");
	$('#product_description table:last tr:child:first strong').css("padding-left","8px");
	$('#product_description table:last tr td:first').attr("colspan",2);
	$('#product_description table:last tr td').css('border-bottom','1px solid #CCC'); 
	
	
	$('#product_description table:first tr td table tr td:first').css("font-size","20px");
	$('#product_description table:first tr td table tr td:first').css("color","#C30008");
	$('#product_description table:first tr td table tr td:first').attr("colspan",2);
	$('#product_description table:first tr td table tr td:first strong ').replaceWith($('#product_name').html());
	$('#product_description table tr td strong:contains("Sonderfunktionen")').css("font-size","20px");
	$('#product_description table tr td strong:contains("Sonderfunktionen")').css("color","#C30008");
	$('#product_description table tr td strong:contains("Sonderfunktionen")').css("font-weight","normal");
	
}
	
	
function openSlide(e){
  var childUl=$('#'+e+' > ul')
  var targetSize=childUl[0].offsetHeight;
  var liCount=$('#'+e+' > ul >li').length;
  var time=liCount*50;
  $('#'+e).stop(true);
	$('#'+e).animate({height:targetSize+"px"},time);
}

function closeSlide(e){
  var liCount=$('#'+e+' > ul >li').length;
  var time=liCount*100;
  $('#'+e).stop(true);
	$('#'+e).animate({height:"18px"},time);
}

//generate Selects for TypesAttributes

var lastSelect="";

function getAttributesSelects(alias, name){
	getFinder(alias);
	$("#articletypebox").show(0);
	$("#loader").css("visibility","visible");
  document.getElementById('selectedType').value=alias;
  document.getElementById('selectedVal').innerHTML=name;
      
  $.post('/modules/mod_products/lib/response.php',{ type : "attributes" , typeAlias : alias },function(data){getAttributes_callback(data);},"json");
  
  
}

function getAttributesSelection(field)
{
  $.post('/modules/mod_products/lib/response.php',{ type : "attributes" , typeAlias : field },function(data){getAttributes_callback(data);},"json");
 
}

var lastAttrSelect=null;

function getAttributes_callback(data){

	
    
	document.getElementById('articles').innerHTML="";
	document.getElementById("articleAttributes").innerHTML="";
	
	
	if(data){
		var html="";
		var style="";
		lastAttrSelect=new Array;
		lastAttrSelect.length=data.msg.length;
		for(var i=0;i<lastAttrSelect.length;i++){
			lastAttrSelect[i]=0;
		}
		for(var i=0;i<data.msg.length;i++){
			html+="<div class=\"type_item\"><strong class=\"bold\">"+data.msg[i].name+"</strong>";
			if(data.msg[i].values.length>0){
        html+='<input type="hidden" id="lastSelected_'+i+'" value="0" />';
        
        if(i==0)
        {
        	style='style="background-color:#FFF9E1;color:#C30008;font-weight:bold;"'
        }
        else
        {
        	style='style="background-color:#FFF9E1;"'
        }
        
				html+='<select id="attr_'+i+'" '+style+' class="selectbox_types" onClick="getArticles('+i+');">';
				html+='<option value="'+data.msg[i].id+'" >keine Angabe</option>';
				for(var h=0;h<data.msg[i].values.length;h++){
					html+='<option value="'+data.msg[i].id+'" >'+data.msg[i].values[h].attributes_value+'</option>';
				}
				html+='</select></div>';
			}
		}
		document.getElementById("articleAttributes").innerHTML=html;
		getArticles("x");
		
		
	}
	
}


function getArticles(index){
	
  if(index=="ordering"){
    var last=document.getElementById("lastOrdering");
    var act=document.getElementById("ordering");
  }else if(index!="x"){
    var last=document.getElementById("lastSelected_"+index);
    var act=document.getElementById("attr_"+index);
	}
  if(index=="x" || last.value!=act.selectedIndex){
    if(index!="x"){
      last.value=act.selectedIndex;
    }
    if(document.getElementById('ordering')){
      var ordering=document.getElementById('ordering').options[document.getElementById('ordering').selectedIndex].value;
    }else{
      var ordering=0;
    }
  
    document.getElementById('articles').innerHTML="";
    var query="";
    var typeId=document.getElementById('selectedType').value;
    for(var i=0;i<lastAttrSelect.length;i++){
      if(document.getElementById('attr_'+i)){
        attribute=document.getElementById('attr_'+i);
        query+=attribute.options[attribute.selectedIndex].value+"##sep1##"+attribute.options[attribute.selectedIndex].text+"##sep2##";
      }
    }
    
		var actCategory='nocatselected';
		
		if(document.getElementById('actCategory')){
			actCategory=document.getElementById('actCategory').value;
		}
		
$("#loader").css("visibility","visible");
    query=query.substring(0,query.length-8);
    $.post('/modules/mod_products/lib/response.php',{ category : actCategory ,type : "articles" , query : query , typeId : typeId, ordering : ordering },function(data){	
$("#loader").css("visibility","hidden");getArticles_callback(data);},"json");
	}
	
	
}

function getArticles_callback(data){
	
	var html="";
	var cat=document.getElementById('param1').value;
	var mod=document.getElementById('module').value;
	var typ=document.getElementById('selectedType').value;
	
	for(var i=0;i<data.msg.length;i++)
	{
		var art=data.msg[i].alias;
		
		html+='<div class=\"box product_main_box\">';
		
		html+='<div class=\"product_main_head\">';
		html+='<h4><a href=\"/'+art+'/'+cat+'/'+typ+'/'+mod+'\">'+data.msg[i].name+'</a></h4>';
		html+='</div>';

		html+='<div class=\"product_main_content\">';
		html+='<div class=\"product_main_thn\"><a href=\"/'+art+'/'+cat+'/'+typ+'/'+mod+'\"><img src="/'+data.msg[i].pics[0].path+'thn_'+data.msg[i].pics[0].filename+'" alt=""/></a></div>';
		html+='<div class="\product_main_details\">';
		html+= data.msg[i].short_description+'&nbsp;<strong><a href=\"/'+art+'/'+cat+'/'+typ+'/'+mod+'\">mehr...</a></strong>';
		html+='<ul class=\"types\">';
		
		for(var x=0;x<data.msg[i].attributes.length;x++){
		
			html+='<li><strong>'+data.msg[i].attributes[x].name+':</strong> '+data.msg[i].attributes[x].attributes_value+'</li>';		
		}

		html+='</ul>';
		
		html+='</div>';
		html+='</div>';
		
		var tax=data.msg[i].tax
			/*
    	var absTax=Math.floor(data.msg[i].tax);
   		var restTax=(data.msg[i].tax-absTax)*100;
    	if(restTax<100)
    	{
      		var tax=String((Math.round(restTax)/100)+absTax).replace(".",",");
		
    	}else{
			
     		var tax=String(absTax+1)+",00";
    	}
    	*/
	    html+='<div class=\"product_main_price\"><h5>'+data.msg[i].price.replace(".",",")+' EUR</h5><p class=\"tax\">inkl. MwSt. '+tax+' &euro;</p>';
	   	html+='<form action=\"/products/'+cat+'/\" method=\"post\">';
	   	html+='<input type=\"hidden\" id=\"product_id\" name=\"articles_key\" value=\"'+data.msg[i].articles_key+'\" />';
		html+='<input type=\"hidden\" name=\"article_type\" value=\"'+cat+'\" />';
		html+='<input type=\"hidden\" id=\"myOriPrice\" value=\"'+data.msg[i].price+'\" />';
		html+='<input type=\"hidden\" id=\"myOriUnitText\" value=\"Preis pro\" />';
		html+='<p class=\"articlenumber\">ART-NR: '+data.msg[i].article_code+'</p>&nbsp;&nbsp;';
	   	html+='<input type=\"text\" class=\"amount\" name=\"amount\" value=\"1\" />&nbsp;&nbsp;<input type=\"submit\" id=\"cart\" name=\"cart\" value=\"In den Warenkorb\" /></form>';
	   	html+='</div>';
		html+='<p class=\"clear\"></p>';
		html+='</div>';
	}
	document.getElementById('articles').innerHTML=html;
  $('#orderSelect').show();
}


//article details

function getDetailAttributesSelects(typeAlias){

		$.post('/modules/mod_products/lib/response.php',{ type : "attributes" , typeAlias : typeAlias },function(data){getDetailAttributes_callback(data);},"json");
		setStyle();
}


function isAttribute(attributesKey,attributesValue){
	var cnt=parseInt(document.getElementById('attrCount').value);
	for(var i=0; i<cnt; i++){
		var key=document.getElementById('attrKey_'+i).value;
		var val=document.getElementById('attrVal_'+i).value;
		if(attributesKey==key && attributesValue==val){
			return true;
		}
	}
	
	return false;
}

function getDetailAttributes_callback(data){

	document.getElementById('attrSwitcher').innerHTML="";
	if(data){
		var html="";
		lastAttrSelect=new Array;
		lastAttrSelect.length=data.msg.length;
		for(var i=0;i<lastAttrSelect.length;i++){
			lastAttrSelect[i]=0;
		}
		html+='<table style="width:100%">';
		for(var i=0;i<data.msg.length;i++)
		{
	
			
			
			html+='<tr>';
			html+='<td width="40%"><span class="switcherAttribute strong bold">'+data.msg[i].name+'</span></td>';
			html+='<td width="60%" align="left">';
			if(data.msg[i].values.length>0){
        html+='<select class="dynselect" id="attr_'+i+'" onclick="getSingleArticle(this.options[this.selectedIndex],'+i+',this.selectedIndex);">';
				for(var h=0;h<data.msg[i].values.length;h++){
					html+='<option '+(isAttribute(data.msg[i].id,data.msg[i].values[h].attributes_value)==true?'selected="selected"':'')+' value="'+data.msg[i].id+'" >'+data.msg[i].values[h].attributes_value+'</option>';
          if(isAttribute(data.msg[i].id,data.msg[i].values[h].attributes_value)==true){
            var attrIndex=h;
          }
        }
        html+='</select>';
        html+='<input type="hidden" id="lastSelected_'+i+'" value="'+attrIndex+'" />';
			}
			html+='</td>';
			html+='</tr>';
		}
		html+='</table>';
		html+='<input type="hidden" id="attributesCount" value="'+data.msg.length+'" />';
		document.getElementById("attrSwitcher").innerHTML=html;
	}
}

function getSingleArticle(option,field,index){
  var last=document.getElementById('lastSelected_'+field);
  var act=index;
  if(last.value!=act){
    last.value=act;
    var cnt=document.getElementById('attributesCount').value;
    var attrQuery="";
    for(var i=0;i<cnt;i++){
      var element=document.getElementById('attr_'+i);
      var attrName=element.options[element.selectedIndex].text;
      var attrKey=element.options[element.selectedIndex].value;
      attrQuery+=attrKey+"##sep1##"+attrName+"##sep2##";
    }
    attrQuery=attrQuery.substring(0,(attrQuery.length-8));
    $.post('/modules/mod_products/lib/response.php',{ type : "singleArticles" , query : attrQuery , fixedAttr : option.value+'##sep1##'+option.text},function(data){getSingleArticle_callback(data);},"json");
  }
}

function getSingleArticle_callback(data){
	if(data.msg.length>0){
		document.getElementById('product_id').value=data.msg[0].articles_key;
		document.getElementById('product_name').innerHTML=data.msg[0].name;
		document.getElementById('product_price').innerHTML='<span id="allPrice">'+data.msg[0].price+'</span>'+"&nbsp;&euro;";
		document.getElementById('product_description').innerHTML=data.msg[0].description_html;
		document.getElementById('product_code').innerHTML='Artikelnummer: '+data.msg[0].article_code;
    document.getElementById('myOriPrice').innerHTML=data.msg[0].price;
    document.getElementById('myOriUnitText').innerHTML=data.msg[0].reference_unit;
		//switch files (data.msg[0].files)
    var filesHtml="";
    for(var i=0;i<data.msg[0].files.length;i++){
      filesHtml+='<li><img class="icon" src="/images/icons/pdf.gif" />&nbsp;&nbsp;<a href="/'+data.msg[0].files[i].path+data.msg[0].files[i].filename+'">'+data.msg[0].files[i].filename+'</a></li>';
    }
    document.getElementById('articleFiles').innerHTML=filesHtml;
        
    //switch connected articles (data.msg[0].connectedArt)
    var connectedHtml='<h4 class="product_addon">Gleich mitbestellen!</h4><p class="clear"></p>';
    for(var i=0;i<data.msg[0].connectedArt.length;i++){
      connectedHtml+='<input type="checkbox" class="checkbox" name="addon[]" value="'+data.msg[0].connectedArt[i].articles_key+'" onclick="changePriceInfo(this);" id="conPrice_'+data.msg[0].connectedArt[i].price*100+'"/>&nbsp;&nbsp;<a target="_blank" title="'+data.msg[0].connectedArt[i].name+'" href="/'+data.msg[0].connectedArt[i].alias+'/'+data.msg[0].connectedArt[i].cat_alias+'/'+data.msg[0].connectedArt[i].type_alias+'/products">'+data.msg[0].connectedArt[i].name+'</a> &ndash; <strong class="bold">'+data.msg[0].connectedArt[i].price+' &euro;</strong><br />';
    }
    document.getElementById('connectedArticles').innerHTML=connectedHtml;
    
    //switch discount (data.msg[0].discount)
    
    var discountHtml='';
		document.getElementById("discountBox").innerHTML='';
		for(var i=0;i<data.msg[0].discount.length;i++){
			discountHtml+='<div class="discount_col_left">'+data.msg[0].discount[i].discount_amount+'</div>';
			discountHtml+='<div class="discount_col_right">'+data.msg[0].discount[i].discount_value+'</div>';
			discountHtml+='<div class="discount_col_right">'+floatRound((data.msg[0].price/100)*(data.msg[0].discount[i].discount_value))+' &euro;</div>';
			discountHtml+='<p class="clear"></p>';
		}
		document.getElementById("discountBox").innerHTML=discountHtml;
		
    //switch images (data.msg[0].pics)
    var picsHtml='<ul id="images" class="jcarousel-skin-tango">';
    for(var i=0;i<data.msg[0].pics.length;i++){
    	picsHtml+='<li><a href="/'+data.msg[0].pics[i].path+'full_'+data.msg[0].pics[i].filename+'"><img src="/'+data.msg[0].pics[i].path+'normal_'+data.msg[0].pics[i].filename+'" alt="" /></a></li>';
    }
		picsHtml+='</ul>';
		document.getElementById('product_image').innerHTML=""
    if(data.msg[0].pics.length>0){
    	document.getElementById('product_image').innerHTML=picsHtml;
    	jQuery('#images').jcarousel( { scroll: 1 } );
    }
    attributesHtml="";
		for(var i=0;i<data.msg[0].attributes.length;i++){
			attributesHtml+='<li><strong>'+data.msg[0].attributes[i].name+'</strong>:&nbsp;'+data.msg[0].attributes[i].attributes_value+'</li>';
			document.getElementById('attrKey_'+i).value=data.msg[0].attributes[i].attributes_key;
			document.getElementById('attrVal_'+i).value=data.msg[0].attributes[i].attributes_value;
		}
		document.getElementById('product_attributes').innerHTML=attributesHtml;
		getDetailAttributesSelects(document.getElementById('param2').value);
		
		//switch ParameterTables
		if(data.msg[0].paramsTable=='leer'){
			$('#parameterWrapper').hide();
		}else{
			document.getElementById('parameterWrapper').innerHTML='';
			document.getElementById('parameterWrapper').innerHTML+=''+
			'<p class="cb"></p>' +
			'<div class="cb box product_main_box_description">' +
			'<div class="cb product_main_head">' +
			'<h4 class="product_headline">Zusatzinfo</h4>' +
			'<br />' +
			'</div>' +
			'<div class="cb space_20">' +
			'<p class="clear">&nbsp;</p>' +
			data.msg[0].paramsTable +
			'</div>' +
			'</div>';
			$('#parameterWrapper').show();
		}
		
	}else{
		alert('Keinen passenden Artikel gefunden...');
	}
}

function changePriceInfo(article){
  var price=parseFloat(article.id.substring(9));
  var allPrice=parseFloat(String(document.getElementById('allPrice').innerHTML).replace(/,/g,"."));
  
  if(article.checked==true){
    allPrice+=(price/100);
  }else{
    allPrice-=(price/100);
  }
  if(allPrice-parseInt(allPrice)==0){
    allPrice=String(allPrice)+".00";
  }else{
    allPrice=String(allPrice);
    if(allPrice.substring(allPrice.indexOf('.').length>3)){
      allPrice=allPrice.substring(0,(allPrice.indexOf('.')+3));
    }
    
  }
  
  //allPrice=String(allPrice).replace(/\./g,",");
  document.getElementById('allPrice').innerHTML=allPrice;
  
  if(allPrice!=document.getElementById('myOriPrice').value){
    document.getElementById('product_reference_unit').innerHTML="Gesamtpreis";
  }else{
    document.getElementById('product_reference_unit').innerHTML=document.getElementById('myOriUnitText').value;
  }
  
}


function floatRound(x) {
  var k = (Math.round(x * 100) / 100).toString();
  k += (k.indexOf('.') == -1)? '.00' : '00';
  k=(k.substring(0, k.indexOf('.') + 3))
  var p = k.indexOf('.');
  return k.substring(0, p) + ',' + k.substring(p+1, p+3);
}

