jQuery.noConflict();

jQuery(document).ready(function() {

  jQuery('.rounded').corners();

  jQuery('#button_view_dokumentacia').click(function () {
    jQuery('.content_shown').removeClass('content_shown').fadeOut(300, function() {;
      jQuery('#product_view_documents').fadeIn(300).addClass('content_shown');
    });
  });

  jQuery('#button_view_produkt').click(function () {
    jQuery('.content_shown').removeClass('content_shown').fadeOut(300, function() {
      jQuery('#product_view_content').fadeIn(300).addClass('content_shown');
    });
  });

  jQuery('#button_view_doplnky').click(function () {
    jQuery('.content_shown').removeClass('content_shown').fadeOut(300, function () {
      jQuery('#product_view_doplnky').fadeIn(300).addClass('content_shown');
    });
  });  

  <!-- CATEGORY_TREE -->
  <!--jQuery("#category_tree_vyrobcovia").css("display","none"); -->
  jQuery("#tree_controls_sortiment").click(function () {
    jQuery("#category_tree_vyrobcovia").fadeOut(500, function() {
      jQuery("#category_tree_sortiment").fadeIn(500);
    });
    jQuery("#tree_controls_sortiment").css({'color' : '#c00'});
    jQuery("#tree_controls_vyrobcovia").css({'color' : '#444'});
  })
  jQuery("#tree_controls_vyrobcovia").click(function () {
    jQuery("#category_tree_sortiment").fadeOut(500, function() {
      jQuery("#category_tree_vyrobcovia").fadeIn(500);
    });
    jQuery("#tree_controls_vyrobcovia").css({'color' : '#c00'});
    jQuery("#tree_controls_sortiment").css({'color' : '#444'});
  })

  var category_tree = jQuery.cookie('category_tree');
  if (category_tree == 'sortiment') {
    jQuery("#category_tree_vyrobcovia").css("display","none");
    jQuery("#category_tree_sortiment").show();
    jQuery("#tree_controls_sortiment").css({'color' : '#c00'});
    jQuery("#tree_controls_vyrobcovia").css({'color' : '#444'});
  }
  if (category_tree == 'vyrobcovia') {
    jQuery("#category_tree_sortiment").css("display","none");
    jQuery("#category_tree_vyrobcovia").show();
    jQuery("#tree_controls_sortiment").css({'color' : '#444'});
    jQuery("#tree_controls_vyrobcovia").css({'color' : '#c00'});
  }
  <!-- /CATEGORY_TREE -->

  <!-- MENU -->

  jQuery("#button_submenu_obchodna_agenda").click(function () {
    jQuery(".submenu_current").hide().removeClass("submenu_current");
    jQuery("#submenu_obchodna_agenda").addClass("submenu_current").fadeIn();
  });

  jQuery("#button_submenu_specialna_ponuka").click(function () {
    jQuery(".submenu_current").hide().removeClass("submenu_current");
    jQuery("#submenu_specialna_ponuka").addClass("submenu_current").fadeIn();
  })


  jQuery("#menubutton_cenniky").click(function () {
    lastMenu = jQuery.cookie('submenu');
    jQuery.cookie('submenu','#submenu_cenniky');
    jQuery(lastMenu).fadeOut(500, function() {
      jQuery("#submenu_cenniky").fadeIn(500);
    });
  })

  jQuery("#menubutton_specialna_ponuka").click(function () {
    lastMenu = jQuery.cookie('submenu');
    jQuery.cookie('submenu','#submenu_specialna_ponuka');
    jQuery(lastMenu).fadeOut(500, function() {
      jQuery("#submenu_specialna_ponuka").fadeIn(500);
    });
  })
  <!-- MENU -->

  <!-- URL-SPECIFIC MAPPER -->
  var urlPath = jQuery.url.attr("path").split("/");
  var urlSplit = urlPath;
  var controller = urlSplit[1];
  var action = urlSplit[2];
  var id = urlSplit[3];
  var jss = id.split("?");
  var js_action = jss[1];
  
  <!-- URL-GROUP: /objednavky, /dodacie_listy, /faktury, /cenove_ponuky, /saldo, /doprava -->
  if ((controller == "objednavky") || (controller == "dodacie_listy") || (controller == "faktury") || (controller == "saldo" || (controller == "cenove_ponuky") || (controller == "doprava"))) {
    jQuery("#menubutton_obchodna_agenda").addClass("submenu_selected");
    jQuery("#table_dodacie_listy tr:odd td").addClass("table_cell_odd");
    jQuery("#table_dodacie_listy tr:even td").addClass("table_cell_even");
    jQuery("#submenu_obchodna_agenda").show(500);
    if (controller == "cenove_ponuky") {
      jQuery("#button_submenu_cenove_ponuky").addClass("submenu_selected");
      if (action == "view") {
        jQuery("#date_picker").datepicker();
      }
    }
  }
  <!-- /URL-GROUP: /objednavky, /dodacie_listy, /faktury, /cenove_ponuky, /saldo, /doprava -->

  <!-- URL: /katalog -->
  if (controller == "katalog") {
    jQuery("#menubutton_katalog").addClass("submenu_selected");
    if ((action == "dopredaj") || (action == "oblubene")) {
      jQuery("#submenu_katalog").show(500);
      jQuery("#menubutton_katalog").removeClass("submenu_selected");
      jQuery("#menubutton_specialna_ponuka").addClass("submenu_selected");
    }
    if (action == "oblubene") {
      jQuery("* > #button_favourite").hide();
    }
    if (action == "view") {
      if (jQuery.url.param("show_doplnky") == 'true') {
        jQuery('#product_view_content').removeClass('content_shown').hide();
        jQuery('#product_view_doplnky').addClass('content_shown').show();
      }
    }
  }

  <!-- URL /katalog/oblubene -->

  <!-- /URL /katalog/oblubene -->

  <!-- URL /katalog/view -->
  <!-- URL: /katalog -->

  <!-- URL: /objednavky/ -->
  if (controller == "objednavky") {
    jQuery("#objednavky input[type=text]").datepicker();
    jQuery("#submenu_obchodna_agenda").show(500);
    if (action == "list") {
      jQuery("#button_submenu_objednavky_list").addClass("submenu_selected");
    }
  }
  <!-- /URL: /objednavky/ -->

  <!-- URL: /cenove_ponuky -->
  if (controller == "cennik") {
    jQuery("#menubutton_cenniky").addClass("submenu_selected");
  }
  <!-- /URL: /cennik -->

  <!-- URL: /profile/ -->
  if (urlPath == '/profile') {
    jQuery("#profile_form").validate({
      rules: {
        "customer[email]": "email",
        "customer[fax]": "digits",
        "customer[tel]": "digits"
      }
    });
  }
  <!-- /URL: /profile/ -->

  <!-- URL: /cennik -->
  if (controller == "cennik") {
    jQuery("#menubutton_cenniky").addClass("submenu_selected");
  }
  <!-- /URL: /cennik -->

  if (controller == "shoppingcart") {
    if (action == "order") {
        jQuery("#order_requestedDelivery").datepicker()
    }
  }
  
  if (controller == "profile") {
    jQuery("#menubutton_profil").addClass("submenu_selected");
  }

  if (controller == "shoppingcart") {
    if (action == "order") {
      jQuery("#button_order_stredisko_rozvoz").click(function() {
        jQuery("#dummy").load("/shoppingcart/order/7")
        jQuery("a[class='odber_active']").removeClass("odber_active", function() {
        jQuery(this).addClass("odber")
        });
        jQuery("#button_order_stredisko_rozvoz").addClass("odber_active");
      })
    }
    
  }
  
})

PQHandler = function() {
	var id;
	this.init = function(pqId) {
		id = pqId;
		console.info('initialized');
		var container = jQuery('.offer-container');
		jQuery.getJSON('/cenove_ponuky/get_data', {id: pqId}, function(data, status, xhr) {
			if (data.success == true) {
				console.info(data);
				if (data.data.length > 0) {
					var content = '<table class="price-quote">';
					content+='<tr>'+
										'<th></th>'+
										'<th>Kód tovaru</th>'+
										'<th>Názov</th>'+
										'<th>Mn.</th>'+
										'<th>Vaša zľava</th>'+
										'<th>DMOC</th>'+
										'<th>Jedn. cena bez DPH</th>'+
										'<th>Celkom bez DPH</th>'+
										'<th>Moja marža</th>'+
										'<th>Ponúknutá cena ceľkom bez DPH</th>'+
										'<th>Ponúknutá zľava z DMOC</th>'+
										'<th>Zmazať</th>'+
									 '</tr>';
					jQuery.each(data.data, function(index, line) {
						var row = '<tr id="price-quote-offer-' + line.empiriaCode + '">'+
											'<td><input type="checkbox" ' + (line.isSelected == 1 ? 'checked' : '') + '/></td>'+
											'<td>' + line.productCode + '</td>'+
											'<td><a href="/katalog/view/' + line.empiriaCode + '">' + line.name + '</a></td>'+
											'<td class="nowrap"><input type="text" class="offer-line-amount" size=3 onkeyup="PriceQuote.updateAmount(this)" value="' + line.amount + '"/>&nbsp;' + line.unit + '</td>'+
											'<td>' + line.discountRate.toFixed(2) + '&nbsp;&#37;</td>'+
											'<td class="offer-line-base-price">' + line.basePriceNoVAT.toFixed(3) + '</td>'+
											'<td class="price-quote-price-unit">' + line.offerPriceUnitNoVAT.toFixed(3) + '</td>'+
											'<td class="price-quote-price-total-no-vat">' + line.offerPriceTotalNoVAT.toFixed(2) + '</td>'+
											'<td class="nowrap"><input type="text" class="offer-line-my-margin-rate" size=6 onkeyup="PriceQuote.updateAmount(this)" value="' + line.myMarginRate.toFixed(2) + '"/>&nbsp;&#37;</td>'+
											'<td class="nowrap"><input type="text" class="offer-line-offer-price-total" size=7 onkeyup="PriceQuote.updatePrice(this)" value="' + line.offerPriceTotalNoVAT.toFixed(2) + '"/></td>'+
											'<td class="nowrap"><input type="text" class="offer-line-offer-price-discount" size=6 value="' + line.myListPriceDiscountRate.toFixed(2) + '"/>&nbsp;&#37;</td>'+
											'<td><a href="/cenove_ponuky/destroy_item/' + data.data[index].id + '"><img src="/images/icons/trash.png"></a></td>'+
											'</tr>'
						content+= row;
					})			
					content+='</table>';
					container[0].innerHTML = content;
				} else {
					var msg = 'Cenová ponuka neobsahuje žiadne položky'
					container.text(msg);
				}
			}
		})
	};
	
	this.updateAmount = function(el) {
		 row = el.parentNode.parentNode,
				quantity = parseFloat(jQuery('input.offer-line-amount', row)[0].value),				
				basePrice = parseFloat(jQuery('td.offer-line-base-price', row)[0].innerHTML),
				price = parseFloat(jQuery('td.price-quote-price-unit', row)[0].innerHTML),
				priceTotalEl = jQuery('td.price-quote-price-total-no-vat', row)[0],
				priceOfferTotalEl = jQuery('input.offer-line-offer-price-total', row)[0],
				offeredDiscountEl = jQuery('input.offer-line-offer-price-discount', row)[0],
				marginRate = parseFloat(jQuery('input.offer-line-my-margin-rate', row)[0].value),
				offeredUnitPrice = (price + (price * (marginRate / 100))),
				customerDiscount = (1 - (offeredUnitPrice / basePrice)) * 100;
		priceTotalEl.innerHTML = (quantity * price).toFixed(2);
		priceOfferTotalEl.value = (offeredUnitPrice * quantity).toFixed(2);
		offeredDiscountEl.value = customerDiscount.toFixed(2);
	};
	
	this.updatePrice = function(el) {
		 row = el.parentNode.parentNode,
				quantity = parseFloat(jQuery('input.offer-line-amount', row)[0].value),				
				basePrice = parseFloat(jQuery('td.offer-line-base-price', row)[0].innerHTML),
				price = parseFloat(jQuery('td.price-quote-price-unit', row)[0].innerHTML),
				priceTotalEl = jQuery('td.price-quote-price-total-no-vat', row)[0],
				priceOfferTotalEl = jQuery('input.offer-line-offer-price-total', row)[0],
				offeredDiscountEl = jQuery('input.offer-line-offer-price-discount', row)[0],
				marginRateEl = jQuery('input.offer-line-my-margin-rate', row)[0],
				marginRate = parseFloat(marginRateEl.value),
				offeredUnitPrice = (price + (price * (marginRate / 100))),
				customerDiscount = (1 - (offeredUnitPrice / basePrice)) * 100;
		priceOfferTotal = parseFloat(priceOfferTotalEl.value);
		myMarginRate = ((priceOfferTotal / parseFloat(priceTotalEl.innerHTML)) * 100) - 100
		marginRateEl.value = myMarginRate.toFixed(3)
	}
}

PriceQuote = new PQHandler;


