var alennus;
var alennus2;
var yht_hinta;

$(document).ready(function() {
  updateMedialaskuri(true);
  
  if(document.location.href.indexOf('laheta-kampanja')) {
    liitaMedialaskuriData();
  }
  
  if($('.hintaperusteet').size() > 1) {
    $('.hintaperusteet').hide();
  }
  else {
    $('.hintaperusteet tr:eq(3) td').hide();
    hinta = $('.hintaperusteet tr:eq(3) td:last').text();
    
    $('.hintaperusteet tr').each(function() {
      i = $(this).find('td:eq(1)').text();
      
      if(i.indexOf("Tarjous") != -1 || i.indexOf(" - ") != -1 || i.indexOf("-") != -1) {
        hinta = "Tarjous";
      }
    });
    
    if(hinta == "0 ?") {
      hinta = "Tarjous";
    }
    
    yht_hinta = hinta;
    $('#hintaNayttaja').html(hinta);
  }
});

function updateMedialaskuri(init) {
  if(init) {
    keksi = $.cookie('medialaskuri');
    
    if(keksi == "" || keksi == null) {
      keksi = '<table></table><div id="alennus">0</div><div id="alennus2">0</div>';
    }
    
    $('#medialaskuri-taulukko').html(keksi);
  }
  
  /* Creation of box */
  var boksixhtml = '<table  cellpadding="0" cellspacing="0" class="ostoskoritaulu"><tr><th colspan="2">Kampanjan yhteenveto</th></tr>';
  
  var yhteensa = 0;
  var vuokrat_yhteensa = 0;
  
  if(init) {
    alennus = $('#medialaskuri-taulukko #alennus').text();
    alennus2 = $('#medialaskuri-taulukko #alennus2').text();
  }
  else {
    alennus = parseInt($('#alennusInput').val());
    alennus2 = parseInt($('#alennusInput2').val());
  }
  
  if(alennus == "") {
    alennus = 0;
  }
  if(alennus2 == "") {
    alennus2 = 0;
  }
  
  cant_sum = false;
  
  $('#medialaskuri-taulukko tr').each(function(i) {
    if($(this).find('td:eq(1)').text() == "Tarjous") {
      cant_sum = true;
    }
    
    boksixhtml += '<tr><td class="left_col">'+$(this).find('td:eq(0)').text()+'</td><td>'+$(this).find('td:eq(1)').text()+'<div class="roskis"><a href="#" onclick="removeFromMedialaskuri('+i+');"></a></div></td></tr>';
    
    yhteensa += parseInt($(this).find('td:eq(1)').text());
    vuokrat_yhteensa += parseInt($(this).find('td:eq(3)').text());
  });
  
  vuokra_alennettuna = vuokrat_yhteensa - (vuokrat_yhteensa*alennus/100);
  vuokra_alennettuna = vuokra_alennettuna - (vuokra_alennettuna*alennus2/100);
  vuokraa_alennetaan = vuokrat_yhteensa-vuokra_alennettuna;
  
  yhteensa = Math.round(yhteensa - vuokraa_alennetaan);
  
  if(cant_sum) {
    yhteensa = "Tarjous";
  }
  
  boksixhtml += '<tr><td colspan="2" style="padding-left: 10px;"><br/><form action="#" method="post">Alennus<input maxlength="3" type="text" id="alennusInput" name="alennus" value="'+alennus+'" onchange="updateMedialaskuri();" />%<br/><br/>Muu alennus<input maxlength="3" type="text" id="alennusInput2" name="alennus2" value="'+alennus2+'" onchange="updateMedialaskuri();" />%<br/><br/>Yhteensä: '+yhteensa+' ?<br/><br/></form></td></tr></table></table>';
  
  /* Update boksixhtml to DOM */
  
  $('#medialaskuri-box').html(boksixhtml);
  
  $('#medialaskuri-taulukko #alennus').html(alennus);
  $('#medialaskuri-taulukko #alennus2').html(alennus2);
  cookieMedialaskuri();
}

function removeFromMedialaskuri(i) {
  $('#medialaskuri-taulukko tr:eq('+i+')').remove();
  
  cookieMedialaskuri();
  
  updateMedialaskuri();
}

function cookieMedialaskuri() {
  /* Update to cookie */
  $.cookie('medialaskuri', $('#medialaskuri-taulukko').html());
}

function liitaMedialaskuriData() {
  var yhteenveto = "";
  var yhteensa = 0;
  var yhteensa_alennettuna = 0;
  var vuokrat_yhteensa = 0;
  var tuotannot_yhteensa = 0;
  
  cant_sum = false;
  
  $('#medialaskuri-taulukko tr').each(function(i) {
    /*
    if($(this).find('td:eq(2)').text() != "null") {
      hintaperuste = "\n   Hintaperuste: "+$(this).find('td:eq(2)').text();
    }
    else {
      hintaperuste = "";
    }*/
    
    var rivi = {
      vuokra: parseInt($(this).find('td:eq(3)').text()),
      kiinnitys: parseInt($(this).find('td:eq(4)').text()),
      tuotanto: parseInt($(this).find('td:eq(5)').text())
    };
    
    if(!rivi.kiinnitys) {
      rivi.kiinnitys = 0;
    }
    
    
    if($(this).find('td:eq(1)').text() == "Tarjous") {
      cant_sum = true;
    }
    
    yhteensa += parseInt($(this).find('td:eq(1)').text());
    vuokrat_yhteensa += rivi.vuokra;
    tuotannot_yhteensa += rivi.tuotanto;
    
    
    yhteenveto += (i+1)+'. '+$(this).find('td:eq(0)').text()+"\n==========================================\nVuokra: "+rivi.vuokra+" EUR\n";
    
    var alennettu_1 = (rivi.vuokra - (rivi.vuokra*alennus/100));
    var alennettu_2 = Math.floor(alennettu_1 - (alennettu_1*alennus2/100) + rivi.kiinnitys);
    yhteenveto += "Alennus -"+alennus+"%: -"+Math.round(rivi.vuokra*alennus/100)+" EUR\n";
    yhteenveto += "Muu Alennus -"+alennus2+"%: -"+Math.round(alennettu_1*alennus2/100)+" EUR\n";
    
    yhteensa_alennettuna += alennettu_2;
    
    yhteenveto += "Kiinnitys ja huolto: "+$(this).find('td:eq(4)').text()+" EUR\n";
    yhteenveto += "Yhteensä: "+alennettu_2+" EUR\n\n";
    yhteenveto += "Tuotanto: "+$(this).find('td:eq(5)').text()+" EUR\n\n";
  });
  
  if(cant_sum) {
    yhteensa = "Tarjous";
  }
  
  yhteenveto += "==========================================\nKaikki yhteensä: " + (yhteensa_alennettuna + tuotannot_yhteensa) +" EUR";
  
  vuokra_alennettuna = vuokrat_yhteensa - (vuokrat_yhteensa*alennus/100);
  vuokra_alennettuna = vuokra_alennettuna - (vuokra_alennettuna*alennus2/100);
  
  alennus = Math.round((vuokraa_alennetaan/vuokrat_yhteensa)*100);
  
  vuokraa_alennetaan = vuokrat_yhteensa-vuokra_alennettuna;
  
  yhteensa = Math.round(yhteensa - vuokraa_alennetaan);
  
  /*
  if(alennus != "" && !cant_sum) {
    yhteenveto += "\n-"+alennus+"% alennuksella: "+yhteensa+" ?";
  }
  */
  
  $('#yhteenveto').val(yhteenveto);
}

function vaihdaHintaperuste(select) {
  // Piilotetaan divit joita ei ole valittu
  $('.hintaperusteet').not(':eq('+(select.selectedIndex - 1)+')').hide();
  
  // Näytetään valittu divi
  $('.hintaperusteet:eq('+(select.selectedIndex - 1)+')').show();
  
  // Piilotetaan viimeinen rivi, yhteensä
  $('.hintaperusteet:eq('+(select.selectedIndex - 1)+') tr:eq(3) td').hide();
  
  hintafoo = $('.hintaperusteet:eq('+(select.selectedIndex - 1)+') tr:eq(3) td:last').text();
  
  $('.hintaperusteet:eq('+(select.selectedIndex - 1)+') tr').each(function() {
    i = $(this).find('td:eq(1)').text();
    
    if(i.indexOf("Tarjous") != -1 || i.indexOf(" - ") != -1 || i.indexOf("-") != -1) {
      hintafoo = "Tarjous";
    }
  });
  
  if(hintafoo == "0 ?") {
    hintafoo = "Tarjous";
  }
  
  yht_hinta = hintafoo;
  $('#hintaNayttaja').html(hintafoo);
}

function lisaaMedialaskuriin() {
  if($('.hintaperusteet:visible').size() == 0) {
    alert("Ei hintaperustetta valittuna");
    return(false);
  }
  
  $('#medialaskuri-taulukko table').append('<tr><td>'+$('.mdl_nimi').text()+'</td><td>'+yht_hinta+'</td><td>'+$('.mdl_hintaperuste').val()+'</td><td>'+$('.hintaperusteet:visible .mdl_vuokra').text()+'</td><td>'+$('.hintaperusteet:visible .mdl_huolto').text()+'</td><td>'+$('.hintaperusteet:visible .mdl_tuotanto').text()+'</td></tr>');
  
  updateMedialaskuri();
  
  return(false);
}


$(document).ready(function() {
  $(".kategoria").hover(function() {
    $(this).addClass("kategoria_hover");
  }, function() {
    $(this).removeClass("kategoria_hover");
  });

  $(".kategoria").hover(function() {
    $(this).children("a").css("color", "#fff");
  }, function() {
    $(this).children("a").css("color", "#004f87");
  });


$(".media_ymparisto_text").hover(function() {
    $(this).addClass("media_hover");
  }, function() {
    $(this).removeClass("media_hover");
  });


$('.kategoria, .media_ymparisto_text, .sarja').Tooltip();



});





/*
 * Tooltip - jQuery plugin  for styled tooltips
 *
 * Copyright (c) 2006 Jörn Zaefferer, Stefan Petre
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 */

(function($) {
  
  // the tooltip element
  var helper,
    // it's title part
    tTitle,
    // it's body part
    tBody,
    // it's url part
    tUrl,
    // the current tooltipped element
    current,
    // the title of the current element, used for restoring
    oldTitle,
    // timeout id for delayed tooltips
    tID;
  
  // the public plugin method
  $.fn.Tooltip = function(settings) {
    // setup configuration
    // TODO: allow multiple arguments to extend, see bug #344
    settings = $.extend($.extend({}, arguments.callee.defaults), settings || {});
  
    // there can be only one tooltip helper
    if( !helper ) {
      // create the helper, h3 for title, div for url
      helper = $('<div id="tooltip"><h3></h3><p class="body"></p><p class="url"></p></div>')
        // hide it at first
        .hide()
        // move to top and position absolute, to let it follow the mouse
        .css({ position: 'absolute', zIndex: 3000 })
        // add to document
        .appendTo('body');
        
      // save references to title and url elements
      tTitle = $('h3', helper);
      tBody = $('p:eq(0)', helper);
      tUrl = $('p:eq(1)', helper);

    }
    
    // bind events for every selected element with a title attribute
    $(this).filter('[@title]')
      // save settings into each element
      // TODO: pass settings via event system, not yet possible
      .each(function() {
        this.tSettings = settings;
      })
      // bind events
      .bind("mouseover", save)
      .bind(settings.event, handle);
    return this;
  };
  
  // main event handler to start showing tooltips
  function handle(event) {
    // show helper, either with timeout or on instant
    if( this.tSettings.delay )
      tID = setTimeout(show, this.tSettings.delay);
    else
      show();
    
    // if selected, update the helper position when the mouse moves
    if(this.tSettings.track)
      $('body').bind('mousemove', update);
      
    // update at least once
    update(event);
    
    // hide the helper when the mouse moves out of the element
    $(this).bind('mouseout', hide);
  }
  
  // save elements title before the tooltip is displayed
  function save() {
    // if this is the current source, or it has no title (occurs with click event), stop
    if(this == current || !this.title)
      return;
    // save current
    current = this;
    
    var source = $(this),
      settings = this.tSettings;
      
    // save title, remove from element and set to helper
    oldTitle = title = source.attr('title');
    source.attr('title','');
    if(settings.showBody) {
      var parts = title.split(settings.showBody);
      tTitle.html(parts.shift());
      tBody.empty();
      for(var i = 0, part; part = parts[i]; i++) {
        if(i > 0)
          tBody.append("<br/>");
        tBody.append(part);
      }
      if(tBody.html())
        tBody.show();
      else
        tBody.hide();
    } else {
      tTitle.html(title);
      tBody.hide();
    }
    
    // if element has href or src, add and show it, otherwise hide it
    href = (source.attr('href') || source.attr('src'));
    if( settings.showURL && href )
      tUrl.html(href.replace('http://', '')).show();
    else 
      tUrl.hide();
    
    // add an optional class for this tip
    if( settings.extraClass ) {
      helper.addClass(settings.extraClass);
    }
    // fix PNG background for IE
    if (settings.fixPNG && $.browser.msie ) {
      helper.each(function () {
        if (this.currentStyle.backgroundImage != 'none') {
          var image = this.currentStyle.backgroundImage;
          image = image.substring(5, image.length - 2);
          $(this).css({
            'backgroundImage': 'none',
            'filter': "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=crop, src='" + image + "')"
          });
        }
      });
    }
  }
  
  // delete timeout and show helper
  function show() {
    tID = null;
    helper.show();
    update();
  }
  
  /**
   * callback for mousemove
   * updates the helper position
   * removes itself when no current element
   */
  function update(event)  {
    // if no current element is available, remove this listener
    if( current == null ) {
      $('body').unbind('mousemove', update);
      return; 
    }
    
    var left = helper[0].offsetLeft;
    var top = helper[0].offsetTop;
    if(event) {
      // get the current mouse position
      function pos(c) {
        var p = c == 'X' ? 'Left' : 'Top';
        return event['page' + c] || (event['client' + c] + (document.documentElement['scroll' + p] || document.body['scroll' + p])) || 0;
      }
      // position the helper 15 pixel to bottom right, starting from mouse position
      left = pos('X') + 15;
      top = pos('Y') + 15;
      helper.css({
        left: left + 'px',
        top: top + 'px'
      });
    }
    
    var v = viewport(),
      h = helper[0];
    // check horizontal position
    if(v.x + v.cx < h.offsetLeft + h.offsetWidth) {
      left -= h.offsetWidth + 20;
      helper.css({left: left + 'px'});
    }
    // check vertical position
    if(v.y + v.cy < h.offsetTop + h.offsetHeight) {
      top -= h.offsetHeight + 20;
      helper.css({top: top + 'px'});
    }
  }
  
  function viewport() {
    var e = document.documentElement || {},
      b = document.body || {},
      w = window;

    return {
      x: w.pageXOffset || e.scrollLeft || b.scrollLeft || 0,
      y: w.pageYOffset || e.scrollTop || b.scrollTop || 0,
      cx: min( e.clientWidth, b.clientWidth, w.innerWidth ),
      cy: min( e.clientHeight, b.clientHeight, w.innerHeight )
    };

    function min() {
      var v = Infinity;
      for( var i = 0;  i < arguments.length;  i++ ) {
        var n = arguments[i];
        if( n && n < v ) v = n;
      }
      return v;
    }
  }
  
  // hide helper and restore added classes and the title
  function hide() {
    // clear timeout if possible
    if(tID)
      clearTimeout(tID);
    // no more current element
    current = null;
    helper.hide();
    // remove optional class
    if( this.tSettings.extraClass ) {
      helper.removeClass( this.tSettings.extraClass);
    }
    
    // restore title and remove this listener
    $(this)
      .attr('title', oldTitle)
      .unbind('mouseout', hide);
      
    // remove PNG background fix for IE
    if( this.tSettings.fixPNG && $.browser.msie ) {
      helper.each(function () {
        $(this).css({'filter': '', backgroundImage: ''});
      });
    }
  }
  
  // define global defaults, editable by client
  $.fn.Tooltip.defaults = {
    delay: 250,
    event: "mouseover",
    track: false,
    showURL: true,
    showBody: null,
    extraClass: null,
    fixPNG: false
  };

})(jQuery);


