$(document).ready(function(){

	/* Lav automatisk links i nicetables */
	$('table.nicetable>tbody>tr[href]').each(function(){
		url = $(this).attr('href')
		$('td', this).bind('click', function(){ location.href = url }).wrapInner('<a href="'+$(this).attr('href')+'"></a>');
	});
	
	
	/* Sæt automatisk overskrift ind på siderne */
	/*var overskrift = $('td.SubCategory1_Productmenu .Activ_Productmenu b').text();
	if (overskrift) {
	  $('#ProductList_TD').css('padding', '20px').prepend('<h1>'+overskrift+'</h1>');
	}*/
	
	
	/* Få menupunkter til at lyse op ved pegning på forsiden */
  if ($('.Text1_Frontpage').length>0) {
    
    $('img[alt="logo-mercruiser"]')
      .bind("mouseover", function(){ highlightMenu("Mercruiser"); })
      .bind("mouseout", function(){ unHighlightMenu("Mercruiser"); });
    $('img[alt="logo-omc"]')
      .bind("mouseover", function(){ highlightMenu("OMC"); })
      .bind("mouseout", function(){ unHighlightMenu("OMC"); });
    $('img[alt="logo-volvo"]')
      .bind("mouseover", function(){ highlightMenu("Volvo Penta"); })
      .bind("mouseout", function(){ unHighlightMenu("Volvo Penta"); });

    $('img[alt="Motor & Drev Olie"]')
      .bind("mouseover", function(){ highlightMenu("Motor & Drev Olie"); })
      .bind("mouseout", function(){ unHighlightMenu("Motor & Drev Olie"); });
    $('img[alt="Kemiprodukter"]')
      .bind("mouseover", function(){ highlightMenu("Kemiprodukter"); })
      .bind("mouseout", function(){ unHighlightMenu("Kemiprodukter"); });
    $('img[alt="V\u00e6rkt\u00f8j"]')
      .bind("mouseover", function(){ highlightMenu("V\u00e6rkt\u00f8j"); })
      .bind("mouseout", function(){ unHighlightMenu("V\u00e6rkt\u00f8j"); });
    $('img[alt="Reparation Manual"]')
      .bind("mouseover", function(){ highlightMenu("Reparation Manual"); })
      .bind("mouseout", function(){ unHighlightMenu("Reparation Manual"); });
    $('img[alt="Bolte & M\u00f8trikker"]')
      .bind("mouseover", function(){ highlightMenu("Bolte"); })
      .bind("mouseout", function(){ unHighlightMenu("Bolte"); });
    $('img[alt="B\u00e5dtilbeh\u00f8r"]')
      .bind("mouseover", function(){ highlightMenu("B\u00e5dtilbeh\u00f8r"); })
      .bind("mouseout", function(){ unHighlightMenu("B\u00e5dtilbeh\u00f8r"); });
    
  }
  
  function highlightMenu(title) {
    $('td.RootCategory_Productmenu a[title^="'+title+'"]')
        .css('color', '#f00')
        .parent()
        .css('background', '#eee')
        ;    
  }
  function unHighlightMenu(title) {
    $('td.RootCategory_Productmenu a[title^="'+title+'"]')
        .css('color', '')
        .parent()
        .css('background', '')
        ;    
  }




  /* RESTEN GÆLDER KUN FOR PRODUKTLISTE-SIDERNE */
  
  if ($("table.varelistevare").length>0) {

	  // Bestem produktkategoriens ID
  	var catidstr = $("td.Toolbar_Productlist a:contains('Anbefal')").attr("href");
  	var temp = ""+catidstr.match(/id=[0-9]+/im);
  	var catid = temp.match(/[0-9]+/);
	
  	// input's udenfor forms fjernes
  	$('table.TableLinesBG_Productlist>tbody>tr>td>input[type=hidden]').remove();


  	// DIAGRAMNUMRE

  	$("table.varelistevare").each(function(){
		
  		// Default diagramnummer
  		diagramnummer = '10000000';
		
  		// Find og gennemgå diagramnumre-koden
  		// syntax:    id=nummer,id=nummer, ...
  		// eksempel:  395=1,398=4,233=72
  		nummerpar = $(".diagramnumre", this).text().split(",");
		
  		for(i=0; i<nummerpar.length; i++) {
  			keyvalue = nummerpar[i].split("=");
			
  			// Hvis den fundne ID = den viste kategoris ID
  			if ($.trim(keyvalue[0])==catid) {
  				diagramnummer = $.trim(keyvalue[1]);
  				$(".CustomField1", this).text(diagramnummer);
  			}
			
  		}
		
  		// For efterfølgende sorterings skyld
  		$(this).parent().prepend('<span class="invisible">'+diagramnummer+'</span>');
		    
		
  	});


	
  	// SORTERING AF LISTE
	
  	$('table.ProductList_Custom_TBL:first').each(function() {
  
  		$table = $(this);

  		// Vælg alle rækkerne i tabellen
  	  var rows = $('table.ProductList_Custom_TBL:first > tbody > tr').get();

  		// Sorter rækkerne med følgende funktion som sorteringskriterie
  	  rows.sort(function(a, b) {
    
  	    var keyA = parseInt($('span.invisible', a).text());
  	    var keyB = parseInt($('span.invisible', b).text());
    
  	    if (keyA < keyB) return -1;
  	    if (keyA > keyB) return 1;
    
  	    return 0;
    
  	  });
	
  		// Tøm tabellen for rækker
      $('table.ProductList_Custom_TBL > tbody').empty();
      $('table.ProductList_Custom_TBL').empty();

  		$('table.ProductList_Custom_TBL').append("<tbody></tbody>");


  		// Sæt hver række ind i tabellen igen, denne gang i rigtig rækkefølge
  	  $.each(rows, function(index, row) {
  	    $('table.ProductList_Custom_TBL > tbody').append(row);
  	  });
				
  		// Fix zebra striberne - efter omrokeringen er det ikke hver anden række, der er farvet. Farverne fjernes, og tilføjes igen korrekt derefter.
  		$('table.ProductList_Custom_TBL > tbody > tr > td').removeClass();
  		$('table.ProductList_Custom_TBL > tbody > tr:even > td').addClass('BackgroundColor1_Productlist');
  		$('table.ProductList_Custom_TBL > tbody > tr:odd > td').addClass('BackgroundColor2_Productlist');
		  
  	});
	
	
	

		/* FIX KØB-KNAPPER */
		
		// Først konverteres de mystiske xxid-attributter tilbage til name-attributter
		$('td.BuyButton_Productlist input').each(function(){
      if ($(this).attr('xxid')) $(this).attr('name', $(this).attr('xxid'));
    });
    
	
  	var produktnummer  = '';
  	var produktnumrene = new Array();
  	var amounts        = new Array();

  	$("table.varelistevare").each(function(){
	
  		produktnummer = $('.product_number', this).text();
  		$(this).attr('name', produktnummer);
		
		  // Alle de af Dandomain malplacerede form-elementer fjernes...
  		$(this).parent('form').replaceWith('<div>'+$(this).html()+'</div>');
  		
  		// Og nye indsættes i stedet forsvarligt inde i en <td>
  		$('td.BuyButton_Productlist', this)
  		  .wrapInner('<form method="POST" action="/shop/basket.asp" name="myform'+produktnummer+'"></form>')
  		  ;
		  
		  // ProduktID-feltet udfyldes i samme omgang korrekt
  		$('td.BuyButton_Productlist input[name="ProductID"]', this).val(produktnummer);
  		$('td.BuyButton_Productlist input[name="AMOUNT"]', this).attr('id', 'amount'+produktnummer);
  		
		  produktnumrene.push(produktnummer);
		  //amounts.push($('td.BuyButton_Productlist input[name="AMOUNT"]', this));
		  
  	});
	
	  // Ligeledes udfyldes BuyReturnUrl-felterne korrekt
  	$('td.BuyButton_Productlist input[name="BuyReturnUrl"]').val(window.location.pathname);
	




	  /* TILBUD-SIDE */
	  var heading = $("span.Heading_ProductList:contains('TILBUD: ')");
	  if (heading.length>0) {
	    //alert("Du er på en tilbudsside");
	    $('td.BreadCrumb_ProductList').css('visibility', 'hidden');
	    
	    heading.parent().prepend('<div class="koeballe"><img src="/images/btn_koeballe.gif"><div class="message">Vent venligst...</div></div>');
	    $('.koeballe img').bind('click', function(){
	      
	      $('.koeballe .message').show();
	      
	      var result;
	      
	      for(i=0;i<(produktnumrene.length/2);i++) {
	        //amount = $('table.varelistevare[name='+produktnumrene[i]+'] input[name="AMOUNT"]').val();
	        amount = document.getElementById('amount'+produktnumrene[i]).value;
          if (!amount) amount = 1;
	        //alert(produktnumrene[i]+" "+amount);
	        result = putInBasket(produktnumrene[i], amount);
	        if (!result) break;
	      }
	      
	      if (result) window.location.reload();
	      
	    });
	    
	  }
	  
  
	}


});

function putInBasket(productid, amount){
  var batchwindow = window.open('', '','height=150,width=200,location=no,menubar=no,resizable=yes,status=no,toolbar=no');
  if (!batchwindow) {
    alert("Du skal sl\u00e5 blokering af popup-vinduer fra hvis du vil bruge denne funktion.");
    return false;
  } else {
    window.focus();
    var w = batchwindow.document;
    w.write('<html><head><title>Vent venligst...</title>');
	  w.write('<link rel="stylesheet" href="js.css">');
	  w.write('</head><body><p>Vent venligst mens varerne bliver lagt i din kurv.</p>');
	  w.write('<form name="myform'+productid+'" action="/shop/basket.asp" method="post">');
	  w.write('<input type="hidden" name="VerticalScrollPos" value="0">');
	  w.write('<input type="hidden" name="BuyReturnUrl" value="/shop/basket.asp">');
	  w.write('<input type="hidden" name="Add" value="1">');
	  w.write('<input type="hidden" name="ProductID" value="'+productid+'">');
	  w.write('<input type="hidden" name="AMOUNT" value="'+amount+'">');
	  w.write('<input type="submit" value="Send">');
	  w.write('</form></body></html>');
	  w.close();
	  w.forms[0].submit();
	  return true;
  }
}
