	/*
 Depends on:
   - mootools 1.2
*/


			function paranda(value){
				var s = value.replace(' ','');
				return s.replace(',','.');
			}
			
      function calc(al, el){
  		  if($('totalprice')){
          var totprice = parseFloat($('totalprice').get('html'));
          var calc = document.getElementById('shoppingcart');
          calc.hind.value = totprice;
  				var makse = calc.sissemaks.value ? Math.ceil(totprice/100)*Math.ceil(calc.sissemaks.value) : 0;
  				var laen = Math.ceil(totprice-makse);
  				var kuud = parseInt(calc.aastad.value);
  				//var intress_ = (paranda(calc.intress.value)/100/12) + 1;
  				var intress_ = (totprice <= 130 ? 25 : (totprice <= 640 ? 22 : 20)) /100;
          //alert(intress_);
  				//alert(intress_)
  				if ( intress_ && kuud ){
  				  var pow=(1-Math.pow(intress_,-kuud))/(intress_-1);
  					calc.laen.value = Math.round(laen);
  					calc.kuumakse.value = Math.ceil(( laen ) * ( 1 + intress_  * kuud / 12 ) /kuud);
  					calc.lepingutasu.value = totprice > 2000 ? 0 : 0;
					  calc.sissemakse.value = Math.round(makse);
  					if (calc.kuumakse.value < 7 && al) {
  						alert('Minimaalne kuumakse on 7 EUR!');
  						if (el && el.options && el.options.length) {
  							el.options[0].selected = true;
  							//el.value = el.options[0].value;
  							var makse = calc.sissemaks.value ? Math.ceil(totprice/100)*Math.ceil(calc.sissemaks.value) : 0;
              	var laen = Math.ceil(totprice-makse);
              	var kuud = parseInt(calc.aastad.value);
              	var intress_ = (paranda(calc.intress.value)/100/12) + 1;
  														
  							var pow=(1-Math.pow(intress_,-kuud))/(intress_-1);
  							calc.laen.value = Math.round(laen);
          			//calc.kuumakse.value = Math.round(laen/pow);
					
					calc.kuumakse.value = Math.ceil(( laen ) * ( 1 + intress_  * kuud / 12 ) /kuud);
					
          			calc.lepingutasu.value = totprice > 2000 ? 0 :0 ;
  						}
  						return false;
  					}
  					if (calc.kuumakse.value < 7 && !al) {
  						calc.laen.value = calc.kuumakse.value = calc.sissemakse.value = '';
  					}
  				} else	{
  					calc.laen.value = calc.kuumakse.value = calc.sissemakse.value = '';
  				}
        }
  		  return true;
			}
      
      /*
        ids has array of item ids to show/hide
      */
      function toggleJarelmaks(ids,elem){
        //$(elem).checked = $(elem).checked == false ? true : false;    	 
    	 if ($('loan').checked == true ) {
    		 $('jarelmaksvalik').checked = true;
    	 } else {
    		 $('jarelmaksvalik').checked = false;
    	 }    	
        ids.each(function(el){
          if($(el)){
            $(el).setStyle('display',($(el).style.display == 'none' ? '' : 'none'));
          }
        });
      }
      function hideJarelmaks(ids, elem) {    	
    	
    	  $('jarelmaksvalik').checked = false;
    	  ids.each(function(el){
              if($(el)){
                $(el).setStyle('display','none');
              }
            });
      }




function ajaxUpdate(script,update,params,method,indicator){
    new Request({
      url:        script,
      method:     method,
      onRequest: function(request){
         if($(indicator)){
            $(indicator).setStyle('display','');
         }
      },
      evalScripts:  false,
      onComplete:   function(request){
         if($(indicator))
            $(indicator).setStyle('display','none');
      },
      onSuccess:  
         function(response) {
            if($(update)){
		            $(update).set('html', response);
		         }
        }
    }).send(params);
}


function cartAjax(url, params, spinner, resp, update) {
 var doStuff = new Request({
   url: url,
   update: update,
   method: 'get',
   onRequest: function(request){
      $(spinner).setStyles({'visibility':'visible'});
   },
   evalScripts:  false,
   onSuccess:  
      function(response) {
		      $(update).set('html', response);
   },
   onComplete: function(request){
      $(spinner).setStyles({'visibility' : 'hidden'});
      $(resp).setStyles({'visibility' : 'visible'});
      window.setTimeout("$('"+resp+"').setStyle('visibility','hidden');", 1000);
      window.location.href = 'index.php?page='+$('cart_page').value;
   }
 }).send(params);
}


function set_cookie ( name, value, exp_y, exp_m, exp_d, path, domain, secure )
{
  var cookie_string = name + "=" + escape ( value );

  if ( exp_y )
  {
    var expires = new Date ( exp_y, exp_m, exp_d );
    cookie_string += "; expires=" + expires.toGMTString();
  }

  if ( path )
        cookie_string += "; path=" + escape ( path );

  if ( domain )
        cookie_string += "; domain=" + escape ( domain );
  
  if ( secure )
        cookie_string += "; secure";
  
  document.cookie = cookie_string;
}


function delete_cookie ( cookie_name )
{
  var cookie_date = new Date ( );  // current date & time
  cookie_date.setTime ( cookie_date.getTime() - 1 );
  document.cookie = cookie_name += "=; expires=" + cookie_date.toGMTString();
}


function get_cookie ( cookie_name )
{
  var results = document.cookie.match ( '(^|;) ?' + cookie_name + '=([^;]*)(;|$)' );

  if ( results )
    return ( unescape ( results[2] ) );
  else
    return null;
}

function gup( name ){
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}


function mouseX(evt) {
if (evt.pageX) return evt.pageX;
else if (evt.clientX)
   return evt.clientX + (document.documentElement.scrollLeft ?
   document.documentElement.scrollLeft :
   document.body.scrollLeft);
else return null;
}

function mouseY(evt) {
if (evt.pageY) return evt.pageY;
else if (evt.clientY)
   return evt.clientY + (document.documentElement.scrollTop ?
   document.documentElement.scrollTop :
   document.body.scrollTop);
else return null;
}         


function getCursorCoords(event){
  /*
    gets the values of the current mouse position
    http://www.evolt.org/article/Mission_Impossible_mouse_position/17/23335/index.html
  */
  var result = new Array();
  var x = 0;
  var y = 0;
  var ev = event || window.event;
  var isOpera = (navigator.userAgent.indexOf('Opera') != -1);
  var isIE = (!isOpera && navigator.userAgent.indexOf('MSIE') != -1)
  
  if (ev.pageX || ev.pageY){
    x = ev.pageX;
    y = ev.pageY;
  } else if (ev.clientX || ev.clientY){
    x = ev.clientX;
    y = ev.clientY;
    if (isIE){
         x += document.documentElement.scrollLeft;
         y += document.documentElement.scrollTop;
    }
  }
  result[0] = x;
  result[1] = y;
  return result;
}


function roundNumber(num, dec) {
	return Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
}



document.addEvent('domready', function() {

 if($('shoppingcart')){
   var formid = $('shoppingcart');
   //submitting form via Ajax
      var url    = formid.getProperty('action')+'&ajax=1&';
      var method = formid.getProperty('method');
      
      $('submit_form_module').addEvent('click', function(evt){
	        // Stops the submission of the form.
         $('make_cart_empty').name='emptyb'; //backing up so that making empty does not show up
	        new Event(evt).stop();
         new Request.HTML ({
	           url: url,
            evalScripts:  false,
	           method: method,
	           update: $('form_module_msg'),
            onRequest: function(){
               $('form_module_spinner').style.display = '';
            },
	           onComplete: function(msg) {
               if($('cartissempty')){
                  $('cart').dispose();
                  $('msg').set('html','<h2>'+$('empty_msg_sent').value+'</h2>'+$('empty_msg').value);
               } else {
                  $('form_module_msg').set('HTML',msg);
                  $('form_module_spinner').style.display = 'none';
               }
            }
         }).post(formid);
         $('make_cart_empty').name='empty'; //restoring
      });



 
   //if the shopping cart-form is active  
   /*
      getting all the product ids, adding onclick-handlers for -+ signs,
      adding keyup-handler to amount fields. Handlers must then change the total
      amount and amount after count of items 
      Ids:
         price_<?= $prd ?> - price of one product line
         totprice_<?= $prd ?> - the price multiplied by amount
         totalprice - the total amount to be paid
   index.php?page=<?=$_GET['page']?>&id='+pid+'&count='+count
   */
   var page = parseInt($('cartpage').value);
   var elems = $('shoppingcart').getElements('input[name^=count_]');
   var ids = [];
   //just getting prd ids
   elems.each(function(el){
      //getting the real product id
      var id = el.id.split('_')[1];
      ids[ids.length] = id;
   });
   
   elems.each(function(el){
      //getting the real product id
      var id = el.id.split('_')[1];
      var oldval = parseFloat($('count_'+id).value).toFixed(2);
      el.addEvent('keyup', function(e) {
         /*
            1. updating UI - both text with sums and total amount
            2. doing Ajax background request to change the session variables         
         
         We need to have the old total price, to get it from the total sum and to add
         the new sum
         */
         var val = this.value.length == 0 ? 0 : parseInt(this.value);
         var totprice = parseFloat($('totalprice').get('html'));
         var otpprice = parseFloat($('totprice_'+id).get('html'));
         var price = parseFloat($('price_'+id).get('html'));
         //new prices
         var ntpprice = roundNumber(price*val,2);
         if(parseInt(this.value) > 0){
            $('totprice_'+id).set('html',(price*val).toFixed(2));
            $('totalprice').set('html',(totprice-otpprice+(price*val)).toFixed(2));         
            ajaxUpdate('index.php','','page='+page+'&ajax=1&id='+id+'&count='+val,'get','');
         } 
         /*else {
            ev = new Event(e);
            if(ev.code != 8 && e.code != 22){
               $('totalprice').set('html',(totprice-otpprice));         
               ajaxUpdate('index.php','','page='+page+'&ajax=1&del='+id,'get','');
               $('row_'+id).dispose();
               //also checking if no other elements are set
               var elems = $('shoppingcart').getElements('input[id^=amountplus_]');
               if(!elems.length){
                  if($('errmsg')){
                     $('errmsg').dispose();
                  }
                  $('cart').dispose();
                  $('msg').set('html',$('empty_msg').value);
               }
            }
         }*/
      });
   });

   
   //making empty
   $('make_cart_empty').addEvent('click', function(evt){
	     // Stops the submission of the form.
	     new Event(evt).stop();
         new Request.HTML ({
	           url: url,
	           method: method,
	           update: $('form_module_msg'),
            evalScripts:  false,
            onRequest: function(){
            },
	           onComplete: function(msg) {
 	         }
         }).post(formid);
      $('cart').dispose();
      $('msg').set('html',$('empty_msg').value);
  });


      //delete
   var elems = $('shoppingcart').getElements('img[id^=delete-]');
   elems.each(function(el){
      //getting the real product id
      var id = el.id.split('-')[1];
      el.addEvent('click', function(e) {
         var count = parseInt($('count-'+id).value);
         var price = parseFloat($('price-'+id).get('html'));
         var totprice = parseFloat($('totalprice').get('html'));         
         $('totalprice').set('html',(totprice-(price*count)).toFixed(2));         
         //var price2 = parseFloat($('price2-'+id).get('html'));
         //var totprice2 = parseFloat($('totalprice2').get('html'));         
         //$('totalprice2').set('html',(totprice2-(price2*count)).toFixed(2)); 
         ajaxUpdate('index.php','','page='+page+'&ajax=1&del='+id,'get','');
         $('row-'+id).dispose();
         //also checking if no other elements are set
         if($('cart')){
            var elems = $('shoppingcart').getElements('img[id^=delete-]');
            if(!elems.length){
               if($('errmsg')){
                  $('errmsg').dispose();
               }
               $('cart').dispose();
               $('msg').set('html',$('empty_msg').value);
            }
         }
         this.style.cursor = 'auto';
         tooltip.hide();

         if($('totalprice')){
         var newtot = parseFloat($('totalprice').get('html'));
         //if(newtot > 64 && $('apply_payment').style.display === 'none'){
            //$('apply_payment').setStyle('display','');
         //   if($('jarelmaks').style.display == 'none' && $('jarelmaksvalik').checked == true){
              if ($('jarelmaks').style.display == 'none' && $('loan').checked == true) {
              toggleJarelmaks(['jarelmaks','field_23','field_24','field_25','field_26','field_27','field_28','field_29','field_30'],false);
            }
         //}        
         }


          calc();
          
         return false;
      });
      el.addEvent('mouseover', function(e) {
         tooltip.show($('delete_item').value,'120');
     });
      el.addEvent('mouseout', function(e) {
         this.style.cursor = 'auto';
         tooltip.hide();
     });
   });

   
    //plus
   var elems = $('shoppingcart').getElements('input[id^=amountplus-]');
   elems.each(function(el){
      //getting the real product id
      var id = el.id.split('-')[1];
      el.addEvent('click', function(e) {
         var totprice = parseFloat($('totalprice').get('html'));
         //var totprice2 = parseFloat($('totalprice2').get('html'));
         var otpprice = parseFloat($('totprice-'+id).get('html'));
         //var otpprice2 = parseFloat($('totprice2-'+id).get('html'));
         var price = parseFloat($('price-'+id).get('html'));
         //var price2 = parseFloat($('price2-'+id).get('html'));
         var count = $('count-'+id).value.length ? parseInt($('count-'+id).value) : 0;
         count = count + 1;
         var ntpprice = price.toFixed(2);
         //var ntpprice2 = price2.toFixed(2);
         $('count-'+id).value = count;
         $('totprice-'+id).set('html',(price*count).toFixed(2));
         $('totalprice').set('html',(totprice-otpprice+(price*count)).toFixed(2));         
         //$('totprice2-'+id).set('html',(price2*count).toFixed(2));
         //$('totalprice2').set('html',(totprice2-otpprice2+(price2*count)).toFixed(2));         
         ajaxUpdate('index.php','','page='+page+'&ajax=1&id='+id+'&count='+count,'get','');

         if($('totalprice')){
         var newtot = parseFloat($('totalprice').get('html'));
         //if(newtot > 64 && $('apply_payment').style.display === 'none'){
            //$('apply_payment').setStyle('display','');
            //if($('jarelmaks').style.display == 'none' && $('jarelmaksvalik').checked == true){
            if ($('jarelmaks').style.display == 'none' && $('loan').checked == true) {
              toggleJarelmaks(['jarelmaks','field_23','field_24','field_25','field_26','field_27','field_28','field_29','field_30'],false);
            }
        // }
         }        
         
          calc();
      });
      el.addEvent('mouseover', function(e) {
         tooltip.show($('change_item').value,'120');
     });
      el.addEvent('mouseout', function(e) {
         this.style.cursor = 'auto';
         tooltip.hide();
     });
   });

   //minus
   var elems = $('shoppingcart').getElements('input[id^=amountminus-]');
   elems.each(function(el){
      //getting the real product id
      var id = el.id.split('-')[1];
      var oldval = parseInt($('count-'+id).value);
      el.addEvent('click', function(e) {
         var totprice = parseFloat($('totalprice').get('html'));         
         var otpprice = parseFloat($('totprice-'+id).get('html'));
         var price = parseFloat($('price-'+id).get('html'));
         //var totprice2 = parseFloat($('totalprice2').get('html'));         
         //var otpprice2 = parseFloat($('totprice2-'+id).get('html'));
         //var price2 = parseFloat($('price2-'+id).get('html'));
         var count = $('count-'+id).value.length ? parseInt($('count-'+id).value) : 0;
         count = count - 1;
         var ntpprice = price.toFixed(2);
         //var ntpprice2 = price2.toFixed(2);
         $('count-'+id).value = count;
         $('totprice-'+id).set('html',(price*count).toFixed(2));
         $('totalprice').set('html',(totprice-otpprice+price*count).toFixed(2));         
         //$('totprice2-'+id).set('html',(price2*count).toFixed(2));
         //$('totalprice2').set('html',(totprice2-otpprice2+price2*count).toFixed(2));         
         if(parseInt($('count-'+id).value) > 0){
            ajaxUpdate('index.php','','page='+page+'&ajax=1&id='+id+'&count='+count,'get','');
         } else {
            $('totalprice').set('html',(totprice-otpprice));         
           //$('totalprice2').set('html',(totprice2-otpprice2));         
            ajaxUpdate('index.php','','page='+page+'&ajax=1&del='+id,'get','');
            $('row-'+id).dispose();
            //also checking if no other elements are set
            if($('cart')){
               var elems = $('shoppingcart').getElements('input[id^=amountplus-]');
               if(!elems.length){
                  if($('errmsg')){
                     $('errmsg').dispose();
                  }
                  this.style.cursor = 'auto';
                  tooltip.hide();
                  $('cart').dispose();
                  $('msg').set('html',$('empty_msg').value);
               }
            }
         }

         if($('totalprice')){
         var newtot = parseFloat($('totalprice').get('html'));
         //if(newtot <= 64 && $('apply_payment').style.display == ''){
           // $('apply_payment').setStyle('display','none');
            if($('jarelmaks').style.display == ''){            
              toggleJarelmaks(['jarelmaks','field_23','field_24','field_25','field_26','field_27','field_28','field_29','field_30'],false);
            }
        // }
         }
         calc();
      });
      el.addEvent('mouseover', function(e) {
         tooltip.show($('change_item').value,'120');
     });
      el.addEvent('mouseout', function(e) {
         this.style.cursor = 'auto';
         tooltip.hide();
     });
   });
  
   
   

 }
 
 
 if($('form_module')){
   var url    = $('form_module').getProperty('action')+'&ajax=1';
   var method = $('form_module').getProperty('method');
   if(!$('notajaxset')){         

      $('submit_form_module').addEvent('click', function(evt){
	        // Stops the submission of the form.
	        new Event(evt).stop();
         new Request.HTML ({
	           url: url,
            evalScripts:  false,
	           method: method,
	           update: $('form_module_msg'),
            onRequest: function(){
               $('form_module_spinner').style.display = '';
            },
	           onComplete: function(msg) {
               if($('messagesent')){
                  $('form_module').dispose();
                  $('msg').set('html','<span style="color:green;font-weight:bold;">'+$('msg_sent').value+'</span>');
               } else {
                  $('form_module_spinner').style.display = 'none';
               }
 	         }
         }).post($('form_module'));         
      });
   }
      
         

 }
});

