/**************************
* 
* Andchir - http://wdevblog.net.ru
* Shopkeeper 0.9.1 - shopping cart for MODx
* 
**************************/

var shkHelper;

(function($){

shkHelper = '<div id="stuffHelper"><div><b id="stuffHelperName"></b></div>'
  +"\n"+'<div class="shs-count" id="stuffCount">'+langTxt['count']+' <input type="text" size="2" name="count" value="1" maxlength="3" />'
  +'</div><div><button class="shk-but" id="confirmButton">'+langTxt['continue']+'</button> '
  +"\n"+'<button class="shk-but" id="cancelButton">'+langTxt['cancel']+'</button></div></div>'
  +"\n";

$.fn.setCounterToField = function(opt){
  st = $.extend({style:'default',wrapdiv:false}, opt);
  var imgpath = 'assets/snippets/shopkeeper/style/'+st.style+'/img/';
  function checkKey(e){
    var key_code = e.which ? e.which : e.keyCode;
    return (key_code>47&&key_code<58)||key_code==8 ? true : false;
  };
  function changeCount(field,action){
    var count = parseInt($(field).attr('value'));
    var num = action==1 ? count+1 : count-1;
    if(num>=1)
      $(field).val(num);
  };
  var countButs = '<img class="field-arr-up" src="'+imgpath+'arr_up.gif" width="17" height="9" alt="" />'
                + '<img class="field-arr-down" src="'+imgpath+'arr_down.gif" width="17" height="9" alt="" />'+"\n";
  var field = $(this);
  if(st.wrapdiv)
    $(this).wrap('<div></div>');
  $(this)
  .css({'height':'16px','border':'1px solid #888','vertical-align':'bottom','text-align':'center','padding':'1px 2px','font-size':'13px'})
  .after(countButs)
  .keypress(function(e){return checkKey(e);});
  $(this).next('img').click(function(){
    changeCount(field,1);
  })
  .css({'cursor':'pointer','margin':'0 0 11px 1px','vertical-align':'bottom'})
  .next('img').click(function(){
    changeCount(field,2);
  })
  .css({'cursor':'pointer','margin':'0 0 1px -17px','vertical-align':'bottom'});
};


$.fn.shopkeeper = function(options){
  settings = $.extend({
    counterField: false,
    style: 'default'
  }, options);
  $(this).each(function(i){
    var parent = this;
    var thisForm = $('form',this);
    if(settings.counterField){
      if($("input[name='shk-count']",this).is(':hidden')==false){
        $("input[name='shk-count']",this).setCounterToField({style:settings.style});
      }
    }
    $(thisForm).submit(function(){
      $('select.addparam,input.addparam:checked',parent).each(function(){
        jQuery.additOpt(this);
      });
      toCart(thisForm);
      return false;
    });
    return this;
  });
};



if (navigator.cookieEnabled==false){
  alert(langTxt['cookieError']);
}


function showHelper(elem,name,noCounter,func){
  if(debug){
    log.info('showHelper()');
  }
  $('#stuffHelper').remove();
  $('body').append(shkHelper);
  $('#cancelButton').click(function(){
    $('#stuffHelper').fadeOut(300,function(){$(this).remove()});
    return false;
  });
  $('#confirmButton').click(function(){
    func();
    return false;
  });
  if(noCounter){
    $('#stuffCount').remove();
  }else{
    $('input:text','#stuffCount').setCounterToField();
  }
  var elHelper = $('#stuffHelper');
  var btPos = getCenterPos(elHelper,elem);
  if(name){
    $('#stuffHelperName').text(name);
  }else{
    $('#stuffHelperName').remove();
  }
  $('#stuffHelper').css({'top':btPos.y+'px','left':btPos.x+'px'}).fadeIn(500);
};


function showLoading(show){
  if(debug){
    log.info('showLoading(), show='+show);
  }
  if(typeof(noLoader)=='undefined'){
    if(show==true){
      $('body').append('<div id="shkLoading"></div>');
      var loader = $('#shkLoading');
      var shopCart = $('#shopCart');
      var btPos = getCenterPos(loader,shopCart);
      $('#shkLoading').css({'top':btPos.y+'px','left':btPos.x+'px'}).fadeIn(300);
    }else{
      $('#shkLoading').fadeOut(300,function(){
        $(this).remove();
      });
    }
  }
}


function getPosition(elem){
  var el = $(elem).get(0);
	var p = {x: el.offsetLeft, y: el.offsetTop};
	while (el.offsetParent){
		el = el.offsetParent;
		p.x += el.offsetLeft;
		p.y += el.offsetTop;
		if (el != document.body && el != document.documentElement){
			p.x -= el.scrollLeft;
			p.y -= el.scrollTop;
		}
	}
	return p;
};


function getCenterPos(elA,elB){
  posB = new Object();
  cntPos = new Object();
  posB = getPosition(elB);
  var correct;
  cntPos.y = Math.round(($(elB).outerHeight()-$(elA).outerHeight())/2)+posB.y;
  cntPos.x = Math.round(($(elB).outerWidth()-$(elA).outerWidth())/2)+posB.x;
  if(cntPos.x+$(elA).outerWidth()>$(window).width()){
    cntPos.x = Math.round($(window).width()-$(elA).outerWidth())-2;
  }
  if(cntPos.x<0){
    cntPos.x = 2;
  }
  return cntPos;
};


function ajaxRequest(params){
  if(debug){
    log.debug('ajaxRequest(), params='+params);
  }
  $.ajax({
    type: "POST",
    cache: false,
    url: 'assets/snippets/shopkeeper/ajax-action.php',
    data: params,
    success: function(data){
      showLoading(false);
      if(window.location.href.indexOf('/'+orderFormPage)>-1){
        $('#butOrder').hide();
      }
      var cartHeight = $('#shopCart').height();
      $('#shopCart').replaceWith(data);
      setCartActions();
      var cartheightNew = $('#shopCart').height();
      animCartHeight(cartHeight,cartheightNew);
    }
  });
}


function deleteItem(num,el){
  thisAction = function(){
    if(debug){
      log.debug('deleteItem(), num='+num);
    }
    if(num!='all'){
      showLoading(true);
      var getParams = '&action=delete&index='+num+'&cart_type='+cartType+'&cart_tpl='+cartTpl[0]+'&cart_row_tpl='+cartTpl[1]+'&currency='+currency+'&link_allow='+linkAllow+'&nocounter='+noCounter+'&change_price='+changePrice+'&order_page='+orderFormPage;
      ajaxRequest(getParams);
    }else{
      emptyCart();
    }
    $('#stuffHelper').fadeOut(500,function(){
      $(this).remove();
    });
  };
  showHelper(el,langTxt['confirm'],true,thisAction);
  $('#confirmButton').text(langTxt['yes']);
};


function recountItem(num,el){
  thisAction = function(){
    var count = $('input:text','#stuffCount').val();
    $('#stuffHelper').fadeOut(500,function(){
      $(this).remove();
    });
    showLoading(true);
    var getParams = '&action=recount&index='+num+'&count='+count+'&cart_type='+cartType+'&cart_tpl='+cartTpl[0]+'&cart_row_tpl='+cartTpl[1]+'&currency='+currency+'&link_allow='+linkAllow+'&nocounter='+noCounter+'&change_price='+changePrice+'&order_page='+orderFormPage;
    ajaxRequest(getParams);
    if(debug){
      log.debug('recountItem(): num:'+num+', count:'+count);
    }
  };
  showHelper(el,false,false,thisAction);
  $('input:text','#stuffCount').val(parseInt($(el).text().replace(/\D* /,'')));
};


function setCartActions(){
  if(debug){
    log.info('setCartActions()');
  }
  var rows = $('a.shk-del','#shopCart');
  if($(rows).size()>0){
    var c = $(rows).size()-1;
    $(rows).each(function(i,n){
      $('a.shk-count:eq('+i+')').click(function(){
        recountItem(c-i,this);
        return false;
      });
      $('a.shk-del:eq('+i+')').click(function(){
          deleteItem(c-i,this);
          return false;
      });
    });
  }
    $('#butEmptyCart').click(function(){
      deleteItem('all',this);
      return false;
    });
    if(window.location.href.indexOf('/'+orderFormPage)>-1){
      $('#butOrder').hide();
    }
};


function fillCart(thisForm,count){
  if(debug){
    log.info('fillCart()');
  }
  var shopCart = $('#shopCart');
  showLoading(true);
  var stuffCount = count!='' ? '&count='+count : '';
  var getParams = '&action=fill_cart&cart_type='+cartType+'&cart_tpl='+cartTpl[0]+'&cart_row_tpl='+cartTpl[1]+'&currency='+currency+'&link_allow='+linkAllow+'&nocounter='+noCounter+'&change_price='+changePrice+'&order_page='+orderFormPage+stuffCount;
  var formData = $(thisForm).serialize();
  ajaxRequest(getParams+'&'+formData);
};



function toCart(thisForm){
  var el = $("input[name='shk-submit'],button[name='shk-submit']",thisForm).eq(0);
  var name = $("input[name='shk-name']",thisForm).val();
  thisAction = function(){
    var count = $('#stuffCount').is('*') ? parseInt($('input:text','#stuffCount').val()) : '';
    if(flyToCart=='image'){
      var parent = $(thisForm).parents(clStuffCont);
      var image = $('img.shk-image:first',parent);
      if($(image).size()>0){
        var cart = $('#shopCart');
        var btPos = getPosition(image);
        var cartPos = getCenterPos(image,cart);
        $('img.shk-image:first',parent)
        .clone(true)
        .appendTo('body')
        .css({'top':btPos.y+'px','position':'absolute','left':btPos.x+'px','opacity':0.75})
        .animate({
          top: cartPos.y+'px',
          left: cartPos.x+'px'
        },700).fadeOut(500,function(){
          $(this).remove();
          fillCart(thisForm,count);
        });
      }else{
        fillCart(thisForm,count);
      }
    }
    if(flyToCart=='helper'){
      var elHelper = $('#stuffHelper');
      var cart = $('#shopCart');
      var cartPos = getCenterPos(elHelper,cart);
      $('#stuffHelper').animate({
        top: cartPos.y+'px',
        left: cartPos.x+'px'
      }).fadeOut(500,function(){
        $(this).remove();
        fillCart(thisForm,count);
      });
    }else{
      if(flyToCart!='image'){
        fillCart(thisForm,count);
      }
      setTimeout(function(){
        $('#stuffHelper').fadeOut(500,function(){
          $('#stuffHelper').remove();
        });
      },1000);
    }
    if(debug){
      log.debug('toCart(), name='+name);
    }
  };
  switch(flyToCart){
    case 'helper':
      showHelper(el,name,noCounter,thisAction);
    break;
    default:
      thisAction();
      showHelper(el,langTxt['addedToCart'],true,thisAction);
      $('#confirmButton,#cancelButton').hide();
    break;
  }
};


jQuery.additOpt = function(elem){
  var thisName = $(elem).attr('name');
  var thisNameArr = thisName.split('__');
  $('#add_'+thisNameArr[1]).remove();
  var additPriceSum = 0;
  var parent = $(elem).parents(clStuffCont);
  $('select.addparam,input.addparam:checked',parent).each(function(){
    var value = $(this).val();
    var valArr = value.split('__');
    var price = valArr[1]!='' ? parseInt(valArr[1]) : 0;
    additPriceSum += price;
    if(debug) log.debug('additOpt(): item id='+thisNameArr[1]+', name='+valArr[0]+', price='+price);
  });
  if(additPriceSum!=''&&!isNaN(additPriceSum)&&!changePrice){
    $('.shk-price:first',parent).after('<sup id="add_'+thisNameArr[1]+'" class="price-add">+'+additPriceSum+'</sup>');
    if(debug) log.debug('additOpt(): item id='+thisNameArr[1]+', additPriceSum='+additPriceSum);
  }else if(!isNaN(additPriceSum)&&changePrice){
    var priceTxt = $('.shk-price:first',parent);
    var curPrice = $(priceTxt).is(":has('span')") ? $('span',priceTxt).text().replace(/\D* /,'') : $(priceTxt).text().replace(/\D* /,'');
    var newPrice = parseFloat(curPrice)+additPriceSum;
    $(priceTxt).empty().append('<span style="display:none;">'+curPrice+'</span>'+newPrice);
    $("input[name='shk-price']",parent).val(newPrice);
    if(debug) log.debug('additOpt(): item id='+thisNameArr[1]+', curPrice='+curPrice+', newPrice='+newPrice);
  }
};


function emptyCart(){
  if(debug){
    log.info('emptyCart()');
  }
  showLoading(true);
  ajaxRequest('&action=empty&cart_tpl='+cartTpl[0]);
};


function animCartHeight(curH,newH){
  $('#shopCart')
  .css({'height':curH+'px','overflow':'hidden'})
  .animate({height:newH+'px'},500,function(){
    $(this).css({'overflow':'visible','height':'auto'});
  });
}


$(document).ready(function(){
  setCartActions();
  if(window.location.href.indexOf('/'+orderFormPage)>-1){
    $('#butOrder').hide();
  }
  //if(window.location.href.indexOf('/'+gotoid)>-1){
  //  emptyCart();
  //}
  $('select.addparam,input.addparam:checked').each(function(){
    jQuery.additOpt(this);
  });
  if(debug){
    log.info('window.location.href = '+window.location.href);
    log.info('navigator.userAgent = '+navigator.userAgent);
  }
});

})(jQuery);


if($.browser.msie && $.browser.version=='6.0'){
  document.execCommand("BackgroundImageCache",false,true);
}

