/*
 Depends on:
   - mootools 1.2
*/

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'});
   },
   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);
   },
   evalScripts: false
 }).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);
}



window.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);
               }
            }
         }*/
      });
      el.addEvent('mouseover', function(e) {
         tooltip.show($('change_item').value,'120');
     });
      el.addEvent('mouseout', function(e) {
         this.style.cursor = 'auto';
         tooltip.hide();
     });
   });

   
   //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));         
         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);
            }
            tooltip.hide();
         }
      });
      el.addEvent('mouseover', function(e) {
         this.style.cursor = 'hand';
         this.style.cursor = 'pointer';
         tooltip.show($('delete_item').value,'120');
     });
      el.addEvent('mouseout', function(e) {
         this.style.cursor = 'auto';
         tooltip.hide();
     });
   });


   
/*   
   //handlers for the minus-plus buttons   
   
   //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 otpprice = parseFloat($('totprice_'+id).get('html'));
         var price = parseFloat($('price_'+id).get('html'));
         var count = $('count_'+id).value.length ? parseInt($('count_'+id).value) : 0;
         count = count + 1;
         var ntpprice = roundNumber(price,1);
         $('count_'+id).value = count;
         $('totprice_'+id).set('html',roundNumber(price*count,1));
         $('totalprice').set('html',roundNumber(totprice-otpprice+(price*count),2));         
         ajaxUpdate('index.php','','page='+page+'&ajax=1&id='+id+'&count='+count,'get','');
      });
   });

   //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 count = $('count_'+id).value.length ? parseInt($('count_'+id).value) : 0;
         count = count - 1;
         var ntpprice = roundNumber(price,2);
         $('count_'+id).value = count;
         $('totprice_'+id).set('html',roundNumber(price*count,1));
         $('totalprice').set('html',roundNumber(totprice-otpprice+price*count,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));         
            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();
                  }
                  $('cart').dispose();
                  $('msg').set('html',$('empty_msg').value);
               }
            }
         }
      });
   });
   */
 }
 
 
 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'));         
      });
   }
      
         
      /*
      // Hides the loading div, and shows the el div for
      // a period of four seconds.
      var showHide = function( el ){
	        fx.loading.set(0);
	        (fx[ el ]).start(0,1);
	        (function(){ (fx[ el ]).start(1,0); }).delay( 4000 );
      }

      // Listen for click events on the submit button.
      var url     =  $('form').getProperty('action');
      var method  =  $('form').getProperty('method');

      $('submit').addEvent('click', function(evt){
	        // Stops the submission of the form.
	        new Event(evt).stop();
	        // Sends the form to the action path,
	        // which is ’script.php’.
	        $('form').send({
            update: $('msg'),
            url: url,
            method: method,
		         onRequest: function(){
			         // Show loading div.
			         fx.loading.start( 0,1 );
		         },
		         onSuccess: function(response){
			         // Hide loading and show success for 3 seconds.
			         showHide('loading');
			         showHide('success');
		         },
		         onFailure: function(){
			         // Hide loading and show fail for 3 seconds.
			         showHide('loading');
			         showHide('fail');
		         }
	        });
      }); */
 }
});

