$(document).ready(function() {
	// test js
	$("body").addClass("jsok");
	$("a[rel='external']").attr({target: "_blank"});
  $('#footer .bmedia a').ifixpng();
	
	$('table.table tr:odd').addClass('odd');
  $('table.table tr:even').addClass('even');

	//konfigurator
	
	$(".outdooridu").change(function(){
    var icid = $('input[name=type]:checked').val();
    $('#imgfreeband').load('configurator.php?jquery=1&action=cat&icid='+icid,'',function(){obsluha();});
    $('#accessories14').html('');
    $('#accessories8').html('');
		$('#accessories9').html('');
	  $('#accessories24').html('');
    $('#accessories26').html('');
    $('#accessories25').html('');
    $('#accessories28').html('');
    $('#accessories27').html('');	 
  });


	$("#cat").change(function(){
    var itid = $('#cat option:selected').val();
    $('#imgfreeband').load('configurator.php?jquery=1&action=freebandcat&itid='+itid,'',function(){obsluha();});
    $('#accessories14').html('');
    $('#accessories8').html('');
		$('#accessories9').html('');
		$('#accessories24').html('');
    $('#accessories26').html('');
    $('#accessories25').html('');
    $('#accessories28').html('');
    $('#accessories27').html('')
  });
  
  	
	
	$('#freebandcat').change(function(){
    var zone = $('#freebandcat option:selected').val();
    var cat = $('#cat option:selected').val();
    $('#imgfreeband').load('configurator.php?jquery=1&action=freebandspeed&zone='+zone+'&cat='+cat,'',function(){obsluha();});
    $('#freebandspeed').removeAttr("disabled");
    $('#relaylength').removeAttr('disabled');
    $('#vykon').removeAttr('disabled');
    $('#accessories14').html('');
    $('#accessories8').html('');
		$('#accessories9').html('');
		$('#accessories24').html('');
    $('#accessories26').html('');
    $('#accessories25').html('');
    $('#accessories28').html('');
    $('#accessories27').html('')
  });
	
	
	$('#freebandspeed').change(function(){
	  var itid = $('#freebandspeed option:selected').val();
    $('#imgfreeband').load('configurator.php?jquery=1&action=freeband&itid='+itid,'',function(){obsluha();});
    $('#antena1').removeAttr("disabled");
     $('#imgantena1').html('<p class=\"c\"><img src=\"front/img/config2.jpg\" alt=\"\" /></p>');
    $('#antena2').removeAttr("disabled");
     $('#imgantena2').html('<p class=\"c\"><img src=\"front/img/config2.jpg\" alt=\"\" /></p>');
    
	});

	$("#tabs").tabs({
			fx:{opacity:'toggle',duration:'fast'},
			cookie: {name:$('#tabs').attr('class'),expires:30}
	});

	$('#antena1').change(function(){
	  var itid = $('#antena1 option:selected').val();
    $('#imgantena1').load('configurator.php?jquery=1&action=antena&ant=1&itid='+itid,'',function(){obsluha();});
	});

	$('#antena2').change(function(){
	  var itid = $('#antena2 option:selected').val();
    $('#imgantena2').load('configurator.php?jquery=1&action=antena&ant=2&itid='+itid,'',function(){obsluha();});
    
	});	
	
  $('#relaylength, #ordera').change(function(){obsluha();});
  //$('#relaylength, #ordera').keyup(function(){ obsluha();});

  $('#vykon, #ordera').change(function(){ if(obsluhaVykon()){obsluha();}});
  //$('#vykon, #ordera').keyup(function(){ if(obsluhaVykon()){obsluha();}});

  $('#ordera').change(function(){cena();});
  $('#ordera').keyup(function(){ cena();});
	
	$('.configb').mouseover(function(){cena();});
 	$('.configb').click(function(){cena();});
   	
	$('.configc').mouseover(function(){cena();});
 	$('.configc').click(function(){cena();});	

  $('.detail input[name="interface"]').click(function(){itemdetailprice();});
	//$('.list input[name="interface"]').click(function(){itemlistprice();});
	
	$('.configbuy, .configpoptat').click(function(){
    var error = '';
    var icid = $('#freebandcat option:selected').val();
    var itid = $('#freebandspeed option:selected').val();
    var ant1 = $('#antena1 option:selected').val();
    var ant2 = $('#antena2 option:selected').val();
    var _LANG = $("#lang").attr("class");

    if(!icid){error = error + '<li>Vyberte připojení.</li>';};
    if(!itid){error = error + '<li>Vyberte rychlost.</li>';};
    if(!ant1){error = error + '<li>Vyberte velikost první antény.</li>';};
    if(!ant2){error = error + '<li>Vyberte velikost druhé antény.</li>';};

  	if (error != '') {
  		error = '<ul>' + error + '</ul>';
  		$('#error').html(error).show();
  		return false;
  	} else {
  		$('#error').hide();
  	}
      
  });
	
	$('input[name=shipping]').click(function(){TotalPrice();});
	
	
	$('#ordersubmitcheck').click(function(){
    if(!$('#iagree').attr('checked')){
      alert('You must agree to these trading terms.');
      return false;
    }  
  });
	
	
	// nyromodal
	$("a[href$='jpg'], a[href$='png'], a[href$='gif'], a[href$='bmp'], .nyromodal").nyroModal();
	$("a[href$='JPG'], a[href$='PNG'], a[href$='GIF'], a[href$='BMP']").nyroModal();
	$.nyroModalSettings({
		processHandler: function(settings) {$("#section object, #section embed").css("visibility","hidden");},
		endRemove: function(settings) {$("#section object, #section embed").css("visibility","visible");}
	});


	// print button
	 $('.print').prepend("<a href='#' class='printButt'>vytisknout stránku</a>");
     $('.printButt').click(function(){
   		window.print();
		return false;
	});




	
});




function declog(x) {
	return (Math.log(x))/(Math.log(10));
}

function obsluha(){

  obsluhaVykon();  

	var o13 = $('#pasmo').val();
	var o14 = $('#vykon').val();
	var o15 = $('#citlivost').val();
	var o16 = $('#relaylength').val();
	var o17 = $('#velikost1').val();
	var o18 = $('#velikost2').val();
	if(o13 && o14 && o15 && o16 && o17 && o18){
    rezerva();
  }
  else{
  $('#dostupnost').val('-');
    
  }

  cena();

}

function obsluhaVykon(){

  var vykonMax = parseInt($('#vykonmax').val());
  var vykon = parseInt($('#vykon').val());
  var _LANG = $("#lang").attr("class");
  //alert(vykon+" > "+vykonMax);
  
  if(vykon > vykonMax || vykon == 'NaN')
  {

    error = '<li>Maximální výkon spoje je '+ vykonMax +' dBm.</li>';
		$('#error').html('<ul>' + error + '</ul>').show();
    $('#vykon').val(vykonMax);
    
    return false;
  }
  else
  {
    $('#error').hide();
    return true;
  }



}

function itemdetailprice(){

  var _LANG = $("#lang").attr("class");
  var interfaceprice = 0;  
  var itemprice = parseFloat($('#itemprice').val());

  ifids = $('#ifids').val();
  if(ifids){
    ifd = ifids.split(';');
    for (var key in ifd) {
      if($('#interface14_'+ifd[key]).is(':checked')){
        price = parseFloat($('#price14_'+ifd[key]).val()); 
        interfaceprice = parseFloat(price);
      }
      
    }
  }  
  
  var price = itemprice+interfaceprice;
  $('#itemdetailprice').html(FormatNumberBy3(price, ".", " ")+' Kč');

  
}



function itemlistprice(id){

  var _LANG = $("#lang").attr("class");
  var interfaceprice = 0;
  var itemprice = parseFloat($('#itemprice'+id).val());

  ifids = $('#ifids'+id).val();
  if(ifids){
    ifd = ifids.split(';');
    for (var key in ifd) {
      if($('#interface14'+id+'_'+ifd[key]).is(':checked')){
        price = parseFloat($('#price14'+id+'_'+ifd[key]).val()); 
        interfaceprice = parseFloat(price);
      }
    }
  }
  var price = itemprice+interfaceprice;

  $('#itemlistprice'+id).html(FormatNumberBy3(price, ".", " ")+' Kč');

}

function cena_accessories(idrow, idcat){

  var totalprice = 0;
  
  ids = $('#'+idrow).val();
  if(ids){
    items = ids.split(';');
    for (var key in items) {
      price = $('#price'+idcat+'_'+items[key]).val(); 
      pcs   = $('#pcs'+idcat+'_'+items[key]).val();
      if(pcs>0){
        totalprice += price * pcs;
      }
    }
  }
  
  return totalprice;
}

function cena(){

  var price = 0;
  var pcs = 0;
  var interfaceprice = 0;
  var accssprice = 0;
  var cids = '';
  var psids = '';

  ifids = $('#ifids').val();
  if(ifids){
    ifd = ifids.split(';');
    for (var key in ifd) {
      if($('#interface14_'+ifd[key]).is(':checked')){
        price = parseFloat($('#price14_'+ifd[key]).val()); 
        interfaceprice += price;
      }
      
    }
  }  
  
  
  /* 8  	^---  Zdroje                      psids */
  accssprice += cena_accessories('psids', 8);
  /* 9 	  ^--- 	Kabely                      cids */
  accssprice += cena_accessories('cids', 9);
  /* 24 	^--- 	Svorkovnice                 sids */
  accssprice += cena_accessories('sids', 24);
  /* 26 	^--- 	Redukce                     rrids */
  accssprice += cena_accessories('rrids', 26);
  /* 25 	^--- 	Rekognoskační aparatura     rids */
  accssprice += cena_accessories('rids', 25);
  /* 28 	^--- 	Konektory                   kids */
  accssprice += cena_accessories('kids', 28);
  /* 27 	^--- 	Ostatní                     oids */
  accssprice += cena_accessories('oids', 27);


  var freeband_price = parseFloat($('#freeband_price').val());
  var antena1_price  = parseFloat($('#antena1_price').val());
  var antena2_price  = parseFloat($('#antena2_price').val());
  
  if (isNaN(freeband_price)){freeband_price=0;}
  if (isNaN(antena1_price)){antena1_price=0;}
  if (isNaN(antena2_price)){antena2_price=0;}

  var price = freeband_price + antena1_price + antena2_price + interfaceprice + accssprice;
  if(price == 0){ price = '-';}
 
  //pocitani ceny v zavislosti na checkboxech 
  var ordera  = $('#ordera').is(':checked');
  var orderps = $('#orderps').is(':checked');
  var orderc  = $('#orderc').is(':checked');

  
  var userprice = freeband_price + interfaceprice;
  if(ordera)  { userprice += antena1_price; userprice += antena2_price; }
  if(orderps) { userprice += powersuplyprice; }
  if(orderc)  { userprice += cableprice; }
  
  if(userprice == 0){ userprice = '-'; }
  
  $('#totalprice').html(FormatNumberBy3(price, ".", " "));
  $('#totaluserprice').html(FormatNumberBy3(userprice, ".", " "));

}

function rezerva() {

	var o13 = $('#pasmo').val();
	var o14 = $('#vykon').val();
	o14 = o14.replace("\,","\.");
	var o15 = $('#citlivost').val();
	o15 = o15.replace("\,","\.");
	var o16 = $('#relaylength').val();
	o16 = o16.replace("\,","\.");
	var o17 = $('#velikost1').val();
	var o18 = $('#velikost2').val();
	var o19 = 0;

	o14 = parseFloat(o14);
	o15 = parseFloat(o15);
	o16 = parseFloat(o16);
	o19 = parseFloat(o19);
	$('#error').html('');
	var error = '';

	if (isNaN(o14)) {error = error + '<li>Výkon není zadán jako číslo.</li>';o14=0;};
	if (isNaN(o15)) {error = error + '<li>Prahová citlivost není zadána jako číslo.</li>';o15=0;};
	if (isNaN(o16)) {error = error + '<li>Délka trasy není zadána jako číslo.</li>';o16=0;};
	if (isNaN(o19)) {error = error + '<li>Zisk konvertoru není zadán jako číslo.</li>';o19=0;};
	if (error != '') {
		error = '<ul>' + error + '</ul>';
		$('#error').html(error).show();
	} else {
		$('#error').hide();
	}

	var u22 = 3/o13*0.1;
	var u23 = 3.14*((o17/2)*(o17/2));
	var u24 = 3.14*((o18/2)*(o18/2));
/*
	alert('u22: ' + u22);
	alert('u23: ' + u23);
	alert('u24: ' + u24);
*/
	var o22 = declog((4*3.14)/(u22*u22)*0.5*u23)*10;
	var o23 = declog((4*3.14)/(u22*u22)*0.5*u24)*10;

	if (o13 == 10 && o17 == 1.2) {o22 = 40;}
	if (o13 == 10 && o18 == 1.2) {o23 = 40;}

	var o24 = 92.44+20*(declog(1*(o13*1000/1000)));
	var o25 = o24+20*declog(o16);
	var o30 = o14-o25+o22+o23-o15;
	var o31 = (o14+o22);
	var o32 = o14+o22+o23-o25;
	var o33 = (o32+o19)*1;
	var o34 = o33+108.75;
	if(o13==10 || o13==11 || o13==13 || o13==15){            //1 – 10,11,13,15 GHz
    var C = 1;
  }
  else if(o13==17){                                       //2 – 17 GHz
   var C = 2;
  }
  else if(o13==18){                                       //3 – 18 GHz
   var C = 3;
  }  
  else if(o13==23 || o13==26 || o13==38){                 //4 – 23,26,38 GHz
   var C = 4;
  } 
  else if(o13==24){                                       //5 – 24 GHz
   var C = 5;
  }
  else{
    var C = 1;
  }
	var o37= 100*(1-(2.5*(Math.pow(10,-9))*C*o13*1000* (Math.pow(o16,3))*(Math.pow(10,(-o30/10)))));
	var o38 =(525600-((o37/100)*525600));

	var spoj = $('#spoj').val();
	if (spoj == 5) { var rssi = (7/160)*o32+(25/8); }
	if (spoj == 6) { var rssi =(33/1325)*o32+(3224/1325); }
	if (spoj > 6) { var rssi = (11/175)*o32+(198/35); }

	if (spoj == 1 || spoj == 2) { var rssi = '-'; } // doplnit vzorecek
	if (spoj == 3) { var rssi = o32/13.889+5.7599; }  // doplnit vzorecek
	if (spoj == 4) { var rssi = o32/12.121+6.6; }  // doplnit vzorecek

	if (Math.abs(rssi) == 'Infinity' || isNaN(rssi)) rssi = '-'; else rssi = rssi.toFixed(3);
	$('#rssi').val(rssi);

	if (Math.abs(o22) == 'Infinity') o22 = '-'; else o22 = Math.round(o22);
	if (Math.abs(o23) == 'Infinity') o23 = '-'; else o23 = Math.round(o23);
	if (Math.abs(o24) == 'Infinity') o24 = '-'; else o24 = o24.toFixed(3);
	if (Math.abs(o25) == 'Infinity') o25 = '-'; else o25 = o25.toFixed(3);
	if (Math.abs(o30) == 'Infinity') o30 = '-'; else o30 = o30.toFixed(3);
	if (Math.abs(o31) == 'Infinity') o31 = '-'; else o31 = o31.toFixed(3);
	if (Math.abs(o32) == 'Infinity') o32 = '-'; else o32 = o32.toFixed(3);
	if (Math.abs(o33) == 'Infinity') o33 = '-'; else o33 = o33.toFixed(3);
	if (Math.abs(o34) == 'Infinity') o34 = '-'; else o34 = o34.toFixed(3);
	if (Math.abs(o37) == 'Infinity') o37 = '-'; else o37 = o37.toFixed(4);
	if (Math.abs(o38) == 'Infinity') o38 = '-'; else o38 = o38.toFixed(4);;

	if(o30>19) {
		$('#result').attr('class', 'ok');
	} else if ((o30>15)&&(o30<19)) {
		$('#result').attr('class', 'almost');
	} else {
		$('#result').attr('class', 'ko');
	}

	$('#ziskvysant').val(o22);
	$('#ziskprijant').val(o23);
  $('#utlumkm').val(o24);
  $('#utlumtrasa').val(o25);
	$('#rezerva').html(o30);
	$('#eirp').val(o31);
	$('#urovennavystupu').val(o32);
	$('#urovensignalu').val(o33);
	$('#merenyvykon').val(o34);
	$('#dostupnost').html(o37+'%');
	$('#nedostupnost').html(o38);
}





// eshop - non jQuery
var previous = 0;
function SavePrev(id)
{
    previous = document.getElementById("count"+id).value;
}

function ReCount(id)
{
     var url = 'recount.php';
     var newCount = document.getElementById("count"+id).value;
     var price = document.getElementById("totalprice").value;
     
    newCount = parseInt(newCount);
    if(isNaN(newCount) || newCount <= 0) {
      document.getElementById("count"+id).value = 0;
      document.getElementById("count"+id).value = previous;
    } else {
      if (window.ActiveXObject){
        httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
      }
      else{
        httpRequest = new XMLHttpRequest();
      }
     
      url = url + '?biid='+id+'&count='+newCount+'&price='+price;

      httpRequest.open("GET", url, true);
      httpRequest.onreadystatechange= function () {processRequest(); } ;
      httpRequest.send(null);
    }     
}

function TotalPrice()
{
    var url = 'recount.php';
    var shipping =  $('input[name=shipping]:checked').val();//document.getElementById("shipping").value;
    var payment =   $('input[name=payment]:checked').val();//document.getElementById("payment").value;
    var price =     $('input[name=totalprice]').val();//document.getElementById("totalprice").value;
    
    if (window.ActiveXObject){
      httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else{
      httpRequest = new XMLHttpRequest();
    }
    
    url = url + '?price='+price+'&shipping='+shipping+'&payment='+payment;

    httpRequest.open("GET", url, true);
    httpRequest.onreadystatechange= function () {processRequest(); } ;
    httpRequest.send(null);   
}


function processRequest()
{
  if (httpRequest.readyState == 4)
  {
    if(httpRequest.status == 200)
    {
      var count = document.getElementById("count");
      
      eval(httpRequest.responseText);
    }
    else
    {
        alert("Chyba pri nacitani stanky"+ httpRequest.status +":"+ httpRequest.statusText);
    }
  }
}



function FormatNumberBy3(num, decpoint, sep) {
  sep = ";psbn&";
  if (arguments.length == 2) { sep = ","; }
  if (arguments.length == 1) { sep = ","; decpoint = "."; }
  num = num.toString();
  a = num.split(decpoint);
  x = a[0];
  y = a[1];
  z = "";

  if (typeof(x) != "undefined") {
    for (i=x.length-1;i>=0;i--) z += x.charAt(i);
    z = z.replace(/(\d{3})/g, "$1" + sep);
    if (z.slice(-sep.length) == sep) z = z.slice(0, -sep.length);
    x = "";
    for (i=z.length-1;i>=0;i--)
      x += z.charAt(i);
    if (typeof(y) != "undefined" && y.length > 0){
      x += ",";
      if(y.charAt(0)>0) x += y.charAt(0); else x += "0";
      if(y.charAt(1)>0) x += y.charAt(1); else x += "0";
    }
  }
  return x;
}

