+function ($) {
    'use strict';


    // deleteCookie PUBLIC CLASS DEFINITION
    // ==============================

    var DeleteCookie = function (element, cookie) {
        this.$element  = $(element);
        this.cookie = cookie || this.$element.data('cookie');
    };


    DeleteCookie.prototype.deleteCookie = function () {
        var host = (/^([\w|-]+\.)?(([\w|-]+)\.(.*))$/).exec(window.location.host)[2];
        if (host == 'co.uk') host = 'tractorpool.co.uk';
        $.removeCookie(this.cookie, {
            path: '/',
            domain: host
        });
    };

    // deleteCookie PLUGIN DEFINITION
    // ========================

    function Plugin() {
        return this.each(function () {
            var $this   = $(this);
            var data    = $this.data('tp.deleteCookie');
            if (!data) {
                $this.data('tp.deleteCookie', (data = new DeleteCookie(this)));
            }
            data.deleteCookie();
        });
    }

    var old = $.fn.deleteCookie;

    $.fn.deleteCookie = Plugin;
    $.fn.deleteCookie.Constructor = DeleteCookie;


    // deleteCookie NO CONFLICT
    // ==================

    $.fn.deleteCookie.noConflict = function () {
        $.fn.deleteCookie = old;
        return this;
    };

    // BUTTON DATA-API
    // ===============

    $(document)
        .on('click.tp.delete-cookie.data-api', '[data-toggle*="delete-cookie"]', function (e) {
            var $button = $(e.target);
            Plugin.call($button);
            return true;
        });

}(jQuery);

$('document').ready(function() {
  $('[data-toggle~="alert-close"]').click(function() {
    var url = $(this).attr('href');
    var $parent = $(this).parents('.alert');
    
    if (!url) {
      $parent.remove();
    }

    $.getJSON(url, {format: 'json'}, function(data, textStatus){
      if (textStatus == 'success') {
        $parent.remove();
      }
    });
    
    var $alertContainer = $(this).parents('.alert__container');
    if ( !($alertContainer.children().length > 1) ) {
        $alertContainer.remove();
    }    
    
    return false;
  });
});

function getIntFromField(field) {
  return parseInt(($(field).attr('value')).replace(/\D/g, ''));
}

function getFloatFromField(field) {
  return $(field).attr('value');
}

function roundFloat(number, precision) {
  return parseFloat(number).toFixed(precision || 2).replace(/0+$/, "").replace(/\.$/, "") * 1;
}


$(document).ready(function () {
  /**
   * Feld Nettopreis deaktivieren
   *
   *
   **/

  /**
   * MG: 17.12.2008
   * Sonstige Hersteller Eingabe
   */
  var manufacturer_id = $("select#manufacturer_id").children(":selected").val();
  $("#manufacturer_id").change(function () {
    if (this.value == 0) {
      $("#row_mch_manufacturer_name").css("display", "block");
      $("input#mch_manufacturer_name").attr('disabled', false);
    } else {
      $("#row_mch_manufacturer_name").css("display", "none");
    }
  });

  if (manufacturer_id == 0) {
    $("input#mch_manufacturer_name").attr('disabled', false);
    $("#row_mch_manufacturer_name").css("display", "block");
  } else {
    $("#row_mch_manufacturer_name").css("display", "none");
    $("input#mch_manufacturer_name").attr('disabled', false);
  }

  /**
   *  Umrechnung von PS zu kW
   */
  $("input#MotorleistungPS").change(PStoKW);

  function PStoKW() {
    PS = parseInt($(this).attr('value'));
    if (isNaN(PS)) {
      $("input#424").attr('value', '');
      $(this).attr('value', '');
    } else {
      var kWUmrechnung = 0.73549875;
      if (window.tpClient.name == 'uk') {
        kWUmrechnung = 0.745700;
      }

      kW = (PS * kWUmrechnung).toFixed(0);
      $("input#424").attr('value', kW);
    }
  }

  /**
   *  Umrechnung von kW zu PS
   */
  $("input#424").change(KWtoPS);

  function KWtoPS() {
    kW = parseInt($("input#424").attr('value'));
    if (isNaN(kW)) {
      $("input#MotorleistungPS").attr('value', '');
      $(this).attr('value', '');
    } else {
      var PSUmrechnung = 1.3596216;
      if (window.tpClient.name == 'uk') {
        PSUmrechnung = 1.341022;
      }
      PS = (kW * PSUmrechnung).toFixed(0);
      $("input#MotorleistungPS").attr('value', PS);
    }
  }

  function getVatRate() {
    var mwst = parseFloat($("select#vat_rate_id").children(":selected").text());
    return (100 + (mwst || 0)) / 100;
  }

  $("#mch_price_brut").on("input propertychange", function () {
    var price_brut = parseFloat(this.value);
    if (isNaN(price_brut)) {
      this.value = null;
    } else {
      $("input#mch_price_net").val(roundFloat(price_brut / getVatRate(), 2));
    }
  });

  $("#mch_price_net").on("input propertychange", function () {
    var price_net = parseFloat(this.value);
    if (isNaN(price_net)) {
      this.value = null;
    } else {
      $("input#mch_price_brut").val(roundFloat(price_net * getVatRate(), 2));
    }
  });

  $("select#vat_rate_id").on('change', function () {
    var status = $('select#mch_offerer_status').val();
    if (status === 'private') {
      $("input#mch_price_brut").trigger('input');
    } else {
      $("input#mch_price_net").trigger('input');
    }
  });

  //VERMIETUNG
  /**
   *  Berechnung Nettopreis wenn Bruttopreis eingegeben bei VERMIETUNG
   */
  $("#renting_mrc_price_brut").on("input propertychange", function () {
    price_brut = getFloatFromField(this);

    if (isNaN(price_brut)) {
      $(this).attr('value', '');
    } else {
      $(this).attr('value', price_brut);
      mwst = $("select#renting_vat_rate_id").children(":selected").text();
      mwst_helper = (mwst / 100) + 1;
      if (isNaN(mwst_helper)) {
        $("input#renting_mrc_price_net").attr('value', price_brut);
      } else {
        price_net = (price_brut / mwst_helper).toFixed(2);
        $("input#renting_mrc_price_net").attr('value', price_net);
      }
    }
  });

  /**
   *  Berechnung Bruttopreis wenn Nettopreis eingegeben bei VERMIETUNG
   */
  $("#renting_mrc_price_net").on("input propertychange", function () {
    price_net = getFloatFromField(this);
    if (isNaN(price_net)) {
      $(this).attr('value', '');
    } else {
      $(this).attr('value', price_net);
      mwst = $("select#renting_vat_rate_id").children(":selected").text();
      mwst_helper = (mwst / 100) + 1;
      if (isNaN(mwst_helper)) {
        $("input#renting_mrc_price_brut").attr('value', price_net);
      } else {
        price_brut = (price_net * mwst_helper).toFixed(2);
        $("input#renting_mrc_price_brut").attr('value', price_brut);
      }
    }
  });

  /**
   *  Berechnung Preis, wenn MwSt-Satz geändert wird eingegeben bei VERMIETUNG
   */
  $("select#renting_vat_rate_id").change(function () {

    price_brut = getFloatFromField($("input#renting_mrc_price_brut"));
    if (isNaN(price_brut)) {} else {
      mwst = $(this).children(":selected").text();
      mwst_helper = (mwst / 100) + 1;
      if (isNaN(mwst_helper)) {
        $("input#renting_mrc_price_net").attr('value', price_brut);
      } else {
        price_net = (price_brut / mwst_helper).toFixed(2);
        $("input#renting_mrc_price_net").attr('value', price_net);
      }
    }
  });

  /*
   * Checkboxen, die disabled sind, wieder enablen, damit Werte
   * f�r die Formularverarbeitung ber�cksichtigt werden.
   */
  $('form#machine').submit(function () {
    $('input:checkbox').each(function () {
      if ($(this).attr('disabled') == true) {
        $(this).removeAttr('disabled');
      }
    });
  });

  $("select#currency_isocode").change(function () {
    displayCurrency();
  });
  $("select#renting_currency_isocode").change(function () {
    displayCurrency();
  });

  //Ausblenden von Vermietoptionen, wenn Checkbox für Vermietung nicht angehakt
  checkRentOptionsActive();

  function checkRentOptionsActive() {
    if ($("input#renting_rentable").is(':checked') || $("input#renting_rentable[type=\"hidden\"]").val() == 1) {
      showRentOptions();
    } else {
      hideRentOptions();
    }
  }

  $("input#renting_rentable").change(function () {
    if (this.checked) {
      showRentOptions();
    } else {
      hideRentOptions();
    }
  });

  function hideRentOptions() {
    $("input#renting_mrc_price_brut").parent().parent().hide();
    $("select#renting_vat_rate_id").parent().parent().hide();
    $("input#renting_mrc_price_net").parent().parent().hide();
    $("select#renting_classification_id").parent().parent().hide();
    $("textarea#renting_rnm_rent_conditions").parent().parent().hide();
  }

  function showRentOptions() {
    $("input#renting_mrc_price_brut").parent().parent().show();
    $("select#renting_vat_rate_id").parent().parent().show();
    $("input#renting_mrc_price_net").parent().parent().show();
    $("select#renting_classification_id").parent().parent().show();
    $("textarea#renting_rnm_rent_conditions").parent().parent().show();
  }

  KWtoPS();
  displayCurrency();

  function displayCurrency() {
    if ($("span#currency_isocode_net").length > 0) {
      $("span#currency_isocode_net").html($("select#currency_isocode").val());
    }
    if ($("span#renting_currency_isocode_net").length > 0) {
      $("span#renting_currency_isocode_net").html($("select#renting_currency_isocode").val());
    }
  }
});


$(function(){
    
    var $data_fields = $("[data-for-completeness]");
    var $description = $("#426");
    var $completeness_description = $("[data-content=\"completeness-description\"]");
    var $images = $('[data-controller="offer--images"]');
    var $completeness_index = $('.progress[data-complete]');

    if (!($data_fields.length && $description.length && $completeness_description.length && $images.length)) {
        return;
    }

    var settings = tpConfig("modules.offer.machinelist.completionIndex");
    for(var key in settings) {
        settings[key] = parseInt(settings[key]);
    }
    
    var imageScores = [
        settings.percentForFirstImage,
        settings.percentForSecondImage,
        settings.percentForFollowingImages
    ];

    $data_fields.on("change", updateCompleteness);
    $description = $("#426").on("keyup", updateCompleteness);
    $images.on("image-uploaded image-deleted images-loaded", setTimeout.bind(null, updateCompleteness, 300));
    
    function getImagesScore() {
        var count = $('[data-target="offer--images.images-container"]', $images).children().length;
        var score = 0;
        for (var i = 0; i < Math.min(count, 3); i++) {
            score += imageScores[i];
        }
        return score;
    }

    function getAttributesScore() {
        var filled_count = $data_fields.filter(function() {
            return (this.tagName === "SELECT") ? this.value > 0 : !!this.value;
        }).length;
        var total_count = $data_fields.length;
        var score = Math.round(parseInt(settings.percentForDynamicAttributes) * filled_count / total_count);
        return score;
    }

    function getDescriptionScore() {
        var word_count = $description.val().split(/\s+/).length;
        var score = Math.min(word_count * settings.percentPerWordInDescription, settings.percentMaximumPerWordInDescription);
        return score;
    }

    function updateCompleteness() {
        var score = getImagesScore() + getAttributesScore() + getDescriptionScore();
        var textkey = (score < parseInt(settings.step2)) 
            ? 'tpWeb.frontend.global.addMachineMachineData.label.completenessOfDescriptionNegativeInfo' 
            : 'tpWeb.frontend.global.addMachineMachineData.label.completenessOfDescriptionPositiveInfo';
        $completeness_description.text(translate(textkey, {value: score + "%"}));
        $completeness_index.attr("data-complete", score);
    }

    updateCompleteness();
});
$("document").ready (function ()
{
  $("#deleteMachine").click (function ()
  {
    return confirm("Wollen Sie dieses Angebot wirklich löschen?");
  });
});
/**
 * Ergaenzt den Baum um das "auf - zuklappen" Feature
 * @author Markus Gulmann
 */
function showGroupCategories()
{
    var id = $(this).attr('id').replace('head_category_','');
    $("#div_category_"+id).children().each(function (i) { $(this).toggle();} );
   
    $("#show_category_"+id).toggle();


}

$(document).ready(function()
{
   $(".link_category_hide_all").hide();
   
   $(".div_category_hide").hide();
   //Span ben�tigt, weil der IE7 sonst das click element nicht ausf�hren kann
   $("span.head_category").click(showGroupCategories);
   //li f�r opera / firefox etc. ben�tigt
   $(".head_category").click(showGroupCategories);
    
   $("#hide_category_all").hide();

   // Link, um alle Kategorien auszuklappen
   $('#show_category_all').click(function () {
	  $("#hide_category_all").show();
	  $('#show_category_all').hide();
   	  $(".category_hide").show();
   	  $('.link_category_show_all').hide();
   	  $('.link_category_hide_all').show();
   	  return false;
   });

   // Link, um alle Kategorien auszuklappen
   $('#hide_category_all').click(function () {
	  $("#hide_category_all").hide();
	  $("#show_category_all").show();
   	  $(".category_hide").hide();
   	  $('.link_category_show_all').show();
   	  $('.link_category_hide_all').hide();
   	  return false;
   });
   
   $(".link_category_show_all").click(function (i) {
   	var id = $(this).attr('id').replace('show_category_','');
   	// Kategorie komplett anzeigen
   	$("#div_category_"+id).children().each(function (i) { $(this).show();} );
   	// Anzeigen-Button der Kategorie verbergen
   	$(this).hide();
    $("#hide_category_"+id).show();
   	return false;
   }); 
   
      //
   // Ausblenden aller Unterpunkte einer Kategorie
   //
   $(".link_category_hide_all").click(function (i) {
   	var id = $(this).attr('id').replace('hide_category_','');
   	// Kategorie komplett anzeigen
   	$("#div_category_"+id).children().each(function (i) { $(this).hide();} );
   	// Anzeigen-Button der Kategorie verbergen
   	$(this).hide();
   	// Zuklappen-Button anzeigen
   	$("#show_category_"+id).show();
   	return false;
   }); 
   
});
$("document").ready(
function()
{
	var cookiemap = {
		"filter": 2,
		"status": 3,
		"results": 4,
		"listmodus": 5,
		"sort": 6,
		"sortby": 7,
		"netgross": 8,
		"exportinterface": 9
	};

	function setCookieValue(key, value) {
		var raw = $.cookie('machinelistfilter') || "";
		var parsed = {};
		raw.split(":").forEach(function(raw) {
			var parts = raw.split("=");
			if (parts.length == 2) {
				parsed[parts[0]] = parts[1];
			}
		});
		var index = cookiemap[key];
		parsed[index] = value;
		var parts = [];
		Object.keys(parsed).forEach(function(index){
			parts.push(index + "=" + parsed[index]);
		});
		setCookie(parts.join(":"));
	}

    function setCookie(value) {
        var host = (/^([\w|-]+\.)?(([\w|-]+)\.(.*))$/).exec(window.location.host)[2];
        if (host == 'co.uk') host = 'tractorpool.co.uk';
        // 10 years
        $.cookie('machinelistfilter', value, {
            expires : 30 * 12 * 10,
            path : '/',
            domain : host
        });

    }


	$("#listmodus_select").change(function ()
	{
		var newvalue = $(this).val().match(/listmodus\/(.*?)\//)[1];

		var isset = false;
		var oldvalues = [];
		var host = window.location.host;
		var cookievalue= "";
		try{
			oldvalues =  $.cookie('machinelistfilter').split(":");
			for (i = 0; i < oldvalues.length; i++) {
				if (oldvalues[i].split('=')[0] == "5") {
					oldvalues[i] = "5="+newvalue;
					isset = true;
				}
			}
		}
		catch(e){
		}

		for(i = 0; i< oldvalues.length; i++)
		{
			cookievalue += oldvalues[i] + ":";
		}

		if(!isset)
		{
			cookievalue += "5="+newvalue;
		}
		else
		{
			cookievalue=	cookievalue.substr(0, cookievalue.length-1);
		}
        setCookie(cookievalue);
		return false;
	});



	$("#sort_select").change(function ()
	{
		var sort = $(this).val().replace(/^(.*\/sort\/)(\w+)(.*)$/, "$2");
		var sortby = $(this).val().replace(/^(.*\/sortby\/)(\w+)(.*)$/, "$2");
		
		var url = location.host +prependLanguageIsocodeToUrl(location.pathname)
			.replace(/\/sort\/\w+/, "")
			.replace(/\/sortby\/[-_\w]+/, "");

		if (sort) {
			setCookieValue("sort", sort);
			url += "/sort/" + sort;
		}
		if (sortby) {
			setCookieValue("sortby", sortby);
			url += "/sortby/" + sortby
		}
		if (url.substr(-1, 1) !== "/") {
			url += "/";
		}
		url = url.replace(/\/\/+/, "/");
		location.href = location.protocol + "//" + url + location.hash;
		return false;
	});




    $("#price_view_select").change(function ()
	{
    	var newvalue = $(this).val().match(/netgross\/(.*?)\//)[1];

		var isset = false;
		var oldvalues = [];
		var host = window.location.host;
		var cookievalue= "";
		try{
			oldvalues =  $.cookie('machinelistfilter').split(":");
			for (i = 0; i < oldvalues.length; i++) {
				if (oldvalues[i].split('=')[0] == "8") {
					oldvalues[i] = "8="+newvalue;
					isset = true;
				}
			}
		}
		catch(e){
		}

		for(i = 0; i< oldvalues.length; i++)
		{
			cookievalue += oldvalues[i] + ":";
		}

		if(!isset)
		{
			cookievalue += "8="+newvalue;
		}
		else
		{
			cookievalue=	cookievalue.substr(0, cookievalue.length-1);
		}

        setCookie(cookievalue);
		location.href = prependLanguageIsocodeToUrl($(this).val());
		return false;
	});

        $("#status_select").change(function ()
	{
                if($(this).val() == '#') return false;

                var newvalue = null;
                var match = $(this).val().match(/status\/(.*?)\//);
                var cookieIndex = "3";
                var cookieIndexToNull = "9"; // exportinterface
                if(match == null) {
                    match = $(this).val().match(/exportinterface\/(.*?)\//);
                    cookieIndex = "9"; // exportinterface
                    cookieIndexToNull = "3";
                }

                if(match == null) return false;
                else newvalue = match[1];

		var isset = false;
		var oldvalues = [];
		var host = window.location.host;
		var cookievalue= "";
		try{
			oldvalues =  $.cookie('machinelistfilter').split(":");
			for (i = 0; i < oldvalues.length; i++) {
				if (oldvalues[i].split('=')[0] == cookieIndex) {
                                    oldvalues[i] = cookieIndex+"="+newvalue;
                                    isset = true;
				} else if (oldvalues[i].split('=')[0] == cookieIndexToNull) {
                                    oldvalues.splice(i, 1); // Element entfernen
                                }
			}
		}
		catch(e){
		}

		for(i = 0; i< oldvalues.length; i++)
		{
			cookievalue += oldvalues[i] + ":";
		}

		if(!isset)
		{
			cookievalue += cookieIndex+"="+newvalue;
		}
		else
		{
			cookievalue=	cookievalue.substr(0, cookievalue.length-1);
		}

        setCookie(cookievalue);

		location.href = prependLanguageIsocodeToUrl($(this).val());
		return false;
	});

	$(".count_select").change(function ()
    {
		var newvalue = $(this).val().match(/results\/(.*?)\//)[1];

		var isset = false;
		var oldvalues = [];
		var host = window.location.host;
		var cookievalue= "";
		try{
			oldvalues =  $.cookie('machinelistfilter').split(":");
			for (i = 0; i < oldvalues.length; i++) {
				if (oldvalues[i].split('=')[0] == "4") {
					oldvalues[i] = "4="+newvalue;
					isset = true;
				}
			}
		}
		catch(e){
		}

		for(i = 0; i< oldvalues.length; i++)
		{
			cookievalue += oldvalues[i] + ":";
		}

		if(!isset)
		{
			cookievalue += "4="+newvalue;
		}
		else
		{
			cookievalue=	cookievalue.substr(0, cookievalue.length-1);
		}

        setCookie(cookievalue);
		location.href = prependLanguageIsocodeToUrl($(this).val());
		return false;
    });

    function setMachinelistFilter()
    {
        var newvalue = $("#filter").val();

        				var isset = false;
        				var oldvalues = [];
        				var cookievalue= "";
        				try{
        					oldvalues =  $.cookie('machinelistfilter').split(":");
        					for (i = 0; i < oldvalues.length; i++) {
        						if (oldvalues[i].split('=')[0] == "2") {
        							oldvalues[i] = "2="+newvalue;
        							isset = true;
        						}
        					}
        				}
        				catch(e){
        				}

        				for(i = 0; i< oldvalues.length; i++)
        				{
        					cookievalue += oldvalues[i] + ":";
        				}

        				if(!isset)
        				{
        					cookievalue += "2="+newvalue;
        				}
        				else
        				{
        					cookievalue=	cookievalue.substr(0, cookievalue.length-1);
        				}

                        setCookie(cookievalue);


                        location.href = encodeURI($("#filter").val());
    }

    $("#filter").keypress(function(e) {
        var code = e.keyCode || e.which;
        if (code == 13) {
            setMachinelistFilter();
        }
    });

	$("#btnMachinelistFilter").click(function () {
            setMachinelistFilter();
	});


         $("#checkAllMachines").change(function(){

             if ($(this).attr('checked')) {
                     $("input[id^='machineCheckbox']").each( function () {
                         $(this).attr('checked', true);
                     });
             }
             else {
                    $("input[id^='machineCheckbox']").each( function () {
                        $(this).attr('checked', false);
                    });
             }
         });



});

