var Cms;
if (!Cms) Cms = {};

/**
 * Skrypt ten nalezy zaimportowac do dokumentu (tag <script>)
 * przed zaimportowainem skryptow, ktore z niego korzystaja.
 * Stad warto umiescic go na gorze, zaraz po dolaczonych 
 * standardowych bibliotekach.
 * 
 * @author BS
 */

/**
 * Zwraca unikalne id zaczynajace sie od sBase.
 *
 * W calym dokumencie moze byc tylko jeden element
 * o danym id. Ta funkcja pozwala na uzyskanie
 * takiego unikalnego w skali dokumentu id.
 *
 * Gdy nie ma elementu o  
 *
 * @param   sBase string  Poczatek id
 * @return  string        sBase gdy nie ma elementu o id sBase,
 *                        sBase + N gdzie N jest liczba calkowita
 *                        w przeciwnym wypadku
 *
 * @uses Cms._uniqueId
 *
 */ 
Cms.getUniqueId = function(sBase) {
  var rval = sBase;
  var index = 0;
  while (document.getElementById(rval)) {
    rval = sBase + index;
    index++;
  }
  //alert("getUniqueId: " + rval + " (unique? " + (document.getElementById(rval) == null) + ")");
  return "" + rval;
}


/**
 * Tylko elementy spelniajace ten selektor beda
 * wykorzystywane przez skrypty.
 */ 
Cms.JS_ALLOWED_SELECTOR = '.JS';

/**
 * Elementy spelniajace ten selektor beda IGNOROWANE
 * przez skrypty.
 */ 
Cms.JS_FORBIDDEN_SELECTOR = '.NoJS';

/**
 * 
 * @param sSel string Selektor bazowy
 * @return string 
 */
Cms.jsSelector = function(sSel) {
  if (!sSel) {
    return sSel;
  }
  var sels = sSel.split(/\s*,\s*/);
  var rval = '';

  var allowedSel = Cms.JS_ALLOWED_SELECTOR || '';
  var forbiddenSel = Cms.JS_FORBIDDEN_SELECTOR ? ':not(' + Cms.JS_FORBIDDEN_SELECTOR + ')' : '';

  for (var i = 0; i < sels.length; i++) {
    var sel = sels[i];
    if (i > 0) {
      rval += ', ';
    }
    rval += sel + allowedSel + forbiddenSel;
  }
  return rval;
}

Cms.autoApply = function(cClass, sSelector, fApply) {
  var selector = Cms.jsSelector(sSelector);
  cClass.applyToDocument = function(sel) {
    if (typeof sel != 'string') {
      sel = selector;
    }
    $(sel).each(fApply || function(i, el) {
        var instance = new cClass(el);
      }
    )
  }
  $().ready(cClass.applyToDocument);
}


function deleteChild(id,childId)
{
  var item=document.getElementById(id);
  for(i=0;i<item.childNodes.length;i++)
  {
    if(item.childNodes[i].id==childId)
    {
      item.removeChild(item.childNodes[i]);
    }
  }
}

function toggleHide(id)
{
  var item=document.getElementById(id);
  if(item.style.display=='none')
  {
    item.style.display='block';
  }
  else
  {
    item.style.display='none';
  }
}

function verifyZagiel()
{
  var totalValueObj = jQuery('#form_value_total');
  if(!totalValueObj)
  {
    return false;
  }
  var totalValue = totalValueObj.val();
  if(totalValue>=limitValue)
  {
    jQuery('.zagiel-label').parent().show();
  }
  else
  {
    jQuery('.zagiel-label').parent().hide();
    var list = jQuery('#order-form input[type="radio"]');
    var selected = jQuery('#order-form input[type="radio"]:checked');
    if(selected.val()==3)
    {
        list.each(function(){
          if($(this).val()!=3)
          {
            $(this).attr('checked',true);
            return false;
          }
      });
    }
  }
}

function setOrderDeliveryCost()
{
  $.ajax({
    url: 'lib/helpers/ajax/get_delivery_cost.php?id='+$('#form_deliverers_id').val()+'&items='+$('#items').val()+'&value='+$('#form_value_brutto').val(),
    success: function(delivery_cost){
    if (delivery_cost != ""){
      var value_brutto = parseFloat($('#form_value_brutto').val());
      var value_payment = parseFloat($('#form_value_payment').val());
      var value_total = parseFloat(delivery_cost) +  value_brutto + value_payment;
      $('#form_value_total').attr('value', value_total);
      $('#value_delivery_cost').load('lib/helpers/ajax/render_price.php?value='+delivery_cost);
      $('#value_total').load('lib/helpers/ajax/render_price.php?value='+value_total);
      $('#form_value_delivery_cost').attr('value',delivery_cost);
      verifyZagiel();
    }
   }
  });
  return false;
}

function setPaymentValue(value)
{
  var value_brutto = parseFloat($('#form_value_brutto').val());
  var delivery_cost = parseFloat($('#form_value_delivery_cost').val());
  var value_total = delivery_cost +  value_brutto + parseFloat(value);
  $('#form_value_payment').attr('value', value);
  $('#form_value_total').attr('value', value_total);
  $('#payment_value_cost').load('lib/helpers/ajax/render_price.php?value='+value);
  $('#value_delivery_cost').load('lib/helpers/ajax/render_price.php?value='+delivery_cost);
  $('#value_total').load('lib/helpers/ajax/render_price.php?value='+value_total);
}

function search(id)
{
  $('#button_'+id).ajaxStart(function(){
    $(this).hide();
  });

  $.ajax({
    url: 'lib/helpers/ajax/good_search.php?ids=&base_goods=0&phrase='+$('#search_'+id).attr('value'),
    success: function(msg){
      if (msg != "")
      {
        $('#goods_id_'+id).empty();
        $('#goods_id_'+id).prepend(msg);
        refreshPrice($('#goods_id_'+id));
      }
   },
   complete: function(){
     $('#button_'+id).show();
   }
  });
  return false;
}

function refreshPrice(o)
{
  var good_id = o.val();
  var id = o.attr('id');
  if (id){
    var s = id.split("_");
    id = s[2];
    $('#price_brutto_'+id).ajaxStart(function(){
      $(this).css('background-color','yellow');
    });
    $.ajax({
      url: 'lib/helpers/ajax/good_price.php?id='+good_id,
        async: false,
        cache: false,
        success: function(price){
        if (price != "")
        {
          $('#price_brutto_'+id).attr('value', price);
          $('#quantity_'+id).attr('value', '1.00');
          $('#item_'+id).find('td').eq(5).html(price);
          $('#button_'+id).show();
        }
      },
      complete: function(){
        $('#price_brutto_'+id).css('background-color','#fff');
      }
   });
 }

  return false;

}

function addItem()
{
  o = $('#OrderList table:first');
  var good_id = o.find('tr:last select').attr('id').split("_")[2];
  $.ajax({
      url: 'lib/helpers/ajax/add_order_item.php?id='+good_id,
        success: function(tr){
        if (tr != "")
        {
           o.append(tr);
        }
      }
  });
  return false;
}

function toggleFilter(id)
{
  jQuery(id+' > ul').toggle(500);
  jQuery(id+' > div').toggle(500);
  
  if(jQuery(id+' > a > img').attr('src')=='layout/frontend/img/filter-expand.jpg')
  {
    jQuery(id+' > a > img').attr('src','layout/frontend/img/filter-collapse.jpg');
  }
  else
  {
    jQuery(id+' > a > img').attr('src','layout/frontend/img/filter-expand.jpg');
  }
}

function showAskPriceForm(id,prefix)
{
  if(prefix)
  {
    id='-'+prefix+id;
  }
  jQuery('#ask-price-anchor'+id).hide(500);
  jQuery('#ask-price-form'+id).show(500);
  return false;
}

function closeAskPriceForm(id,prefix)
{
  if(prefix)
  {
    id='-'+prefix+id;
  }
  jQuery('#ask-price-form'+id).hide(500);
  jQuery('#ask-price-anchor'+id).show(500);
  return false;
}
