var list_href = {};
var cur_href = 0;
// -------------------------------
/*jQuery.fn.extend({
        myload: function( url, callback ) {
    //$('#loading').show();
    callback = callback || function(){};
    this.load(url, callback);
    //this.load(url, function() { $.each( this, callback); $('#loading').hide(); })
    return this;
  }
});*/
var main_title = 's-mart';
var empty_list = '<div class="filter"><b class="tleft"></b><b class="bleft"></b><b class="tright"></b><b class="bright"></b></div><div class="scrollHolder items" id="dv_items"><div id="itemList" class="flexcroll"></div></div>';
function set_win_title()
{  
  document.title = main_title + ': ' + $('input.title:last').attr('value');
  if ($('input.title:last').hasClass('title404')) {
    $('#a404').bind('click', function() {
      $('#header .logo a').trigger('click');
      return false;
    });
    $('#b404').bind('click', function() {
      history.go(-1);
      return false;
    });
  }
}
function stat_url(url)
{  
  url = url.replace(/^#/, '/');
  try { 
    var pageTracker = _gat._getTracker("UA-7996471-1");
    pageTracker._trackPageview(url); 
  } catch(e) {}  
}
function show_conflict()
{
  return false;
  if ($('#show_conflict').length == 0) return;
  var last_href = modal_link('/conflict/');
  $('div.selectedItem[@rel=c]').hide();
  $('div.container:last').hide().each(function() {
    var el = document.createElement('div');
    $(el).attr('id', 'container').attr('class', 'container').attr('rel', 'conflict').insertAfter($(this)).load(last_href, function() {
      set_win_title();
      //page_func();
      conflict_func();      
      Custom.init();
    });
  });    
  set_href('/conflict/');
}
var fpar = 'fr=1';
var fpar2 = 'fr2=0';
var def_search = '';
window.allowLoading = false;
if (document.location.pathname != '/') {
  document.location.replace(document.location.pathname.replace(/^\//, '/#'));
}
if (document.location.hash == '' || document.location.hash == '#home/')
{
  $(document).bind('ready', function() {  
    set_win_title();
    $('#loading').hide();window.allowLoading = true;show_conflict()
  });
  window_go_hidden('#home/');
  list_href[++cur_href] = '#home/';
  //document.title = main_title + ': Главная';
}
else if (/search\/(.*)/.test(document.location.hash))
{
  def_search = RegExp.$1;
  $(document).bind('ready', function() {  
    set_win_title();
    $('#loading').hide();window.allowLoading = true;show_conflict();
    if (def_search) {
      $('#searchField').attr('value', def_search);
      //search_submit();
    }
  });
  window_go_hidden('#home/');
  list_href[++cur_href] = '#home/';
}
else if (/history/.test(document.location.hash))
{
  $(document).bind('ready', function() {   
    var last_href = modal_link('/history/');
    $('div.selectedItem[@rel=c]').hide();
    $('div.container:last').hide().each(function() {
      var el = document.createElement('div');
      $(el).attr('id', 'container').attr('class', 'container').attr('rel', 'history').insertAfter($(this)).load(last_href, function() {
        set_win_title();
        page_func();
        cart_func_history();
        page_func_history();
        $('#loading').hide();window.allowLoading = true;show_conflict()
      });
    });    
    set_href('/history/');
  });
}
else if (/shipment/.test(document.location.hash))
{
  $(document).bind('ready', function() {   
    var last_href = modal_link('/shipment/');
    $('div.selectedItem[@rel=c]').hide();
    $('div.container:last').hide().each(function() {
      var el = document.createElement('div');
      $(el).attr('id', 'container').attr('class', 'container').insertAfter($(this)).load(last_href, function() {
        set_win_title();
        page_func();
        $('div.container:last .flexcroll').each(function() {fleXenv.fleXcrollMain(this)});
        $('#loading').hide();window.allowLoading = true;
      });
    });  
    set_href('/shipment/');  
  });
}
else if (/faq/.test(document.location.hash))
{
  $(document).bind('ready', function() {   
    var last_href = modal_link('/faq/');
    $('div.selectedItem[@rel=c]').hide();
    $('div.container:last').hide().each(function() {
      var el = document.createElement('div');
      $(el).attr('id', 'container').attr('class', 'container').insertAfter($(this)).load(last_href, function() {
        set_win_title();
        page_func();
        $('div.container:last .flexcroll').each(function() {fleXenv.fleXcrollMain(this)});
        $('#loading').hide();window.allowLoading = true;
      });
    });  
    set_href('/faq/');  
  });
}
else if (/about/.test(document.location.hash))
{
  $(document).bind('ready', function() {   
    var last_href = modal_link('/about/');
    $('div.selectedItem[@rel=c]').hide();
    $('div.container:last').hide().each(function() {
      var el = document.createElement('div');
      $(el).attr('id', 'container').attr('class', 'container').insertAfter($(this)).load(last_href, function() {
        set_win_title();
        page_func();
        $('div.container:last .flexcroll').each(function() {fleXenv.fleXcrollMain(this)});
        $('#loading').hide();window.allowLoading = true;
      });
    });  
    set_href('/about/');  
  });
}
else if (/(conflict|pay|profile|logout)/.test(document.location.hash))
{
  $(document).bind('ready', function() {
    window_go_hidden('#home/');
    set_href(document.location.hash);
    $('#loading').hide();window.allowLoading = true;show_conflict()
  })
}
else if (/^#([^\/]+)\/([^\/]+)\/$/.test(document.location.hash))
{
  $(document).bind('ready', function() {    
    $('#in_container').html(empty_list).load(modal_link(hash_href(document.location.hash)), function() {
      set_win_title();
      items_domodal();
      list_func();
      $('div.container:last .flexcroll').each(function() {fleXenv.fleXcrollMain(this)});
      $('#service #breabcrumbs').replaceWith($('div.container:last #breabcrumbs'));
      search_tree();
      $('#loading').hide();window.allowLoading = true;show_conflict()
    })
    $('#searchRoot').attr('value', hash_href(document.location.hash));
    set_href(document.location.hash);
  });
} 
else if (/^#([^\/]+)\/$/.test(document.location.hash))
{
  $(document).bind('ready', function() {    
    $('#in_container').load(modal_link2(hash_href(document.location.hash)), function() {
      set_win_title();
      index_domodal();
      subcat_domodal();
      $('#service #breabcrumbs').replaceWith($('div.container:last #breabcrumbs'));
      search_tree();
      $('#loading').hide();window.allowLoading = true;show_conflict()
    });
    $('#searchRoot').attr('value', hash_href(document.location.hash));
    set_href(document.location.hash);
  });
}
else if (/^#([^\/]+)\/([^\/]+)\/([^\/]+)\.html$/.test(document.location.hash))
{
  $(document).bind('ready', function() {    
    $('div.container:last').hide().each(function() {
      var el = document.createElement('div');
      fpar = 'fr=1';
      fpar2 = 'fr2=0';
      $(el).attr('id', 'container').attr('class', 'container').insertAfter($(this)).load(modal_link(add_params(hash_href(document.location.hash), fpar+'&' + fpar2)),  function() {
        set_win_title();
        $('#service #breabcrumbs').replaceWith($('div.container:last #breabcrumbs'));
        search_tree();
        item_func();
        $('#dv_detailsSide .flexcroll').each(function() {fleXenv.fleXcrollMain(this)});
        $('#loading').hide();window.allowLoading = true;show_conflict()
      });
    });
    var tstr = hash_href(document.location.hash);
    tstr = tstr.replace(/\/([^\/]+)\.html$/, '/');
    $('#searchRoot').attr('value', tstr);
    set_href(document.location.hash);
  });
}
else
{
  $(document).bind('ready', function() {
    window_go_hidden('#home/');
    set_href(document.location.hash);
    $('#loading').hide();window.allowLoading = true;show_conflict()
  })
}
if (!def_search) {
  $(document).bind('ready', function() {  
    $('#searchField').attr('value', '');
  });
}
function hash_href(link)
{
  link = link.replace(/^#/, '/');
  return link;
}
function set_href_over(link)
{
  link = link.replace(/^http:\/\/[^\/]+/, '');
  link = link.replace(/^\//, '#');
  if (link == '#') link = '#home/';
  list_href[cur_href] = link;
  stat_url(link);
  window_go(link)
}
function set_href(link)
{
  link = link.replace(/^http:\/\/[^\/]+/, '');
  link = link.replace(/^\//, '#');
  if (link == '#') link = '#home/';
  list_href[++cur_href] = link;
  stat_url(link);
  /*str = '';
  for(var i in list_href)
  {
        str = str + i + ' => ' + list_href[i] + "\n";
  }
  alert(str);*/
  //unFocus.History.addHistory(link)
  //document.location.replace(link);
  window_go(link);
  return;
  if (link == '#conflict') {
    window_go_hidden(link);
  } else {
    window_go(link);
  }
}
function window_go(link)
{
  unFocus.History.addHistory(link.substring(1));
  /*if ($.browser.msie) {
    document.location.replace(link);
  } else {
    document.location.href = link;
  }*/
}
function window_go_hidden(link)
{
  document.location.replace(link);
  /*
  if ($.browser.msie) {
    document.location.href = link;
  } else {
    document.location.replace(link);
  }*/
}
function historyListener(hash)
{
  //alert('#' + hash + ' != ' +  list_href[cur_href]);
  if ('#' + hash != list_href[cur_href]) {
    $('div.selectedItem').hide();
    if ('#' + hash == list_href[cur_href-1] && $('.container:last a.close').length > 0) {
      $('.container:last a.close').trigger('click');
    } else if (/history/.test(document.location.hash)) {
      var last_href = modal_link('/history/');
      list_href[++cur_href] = '#' + hash;
      $('div.selectedItem[@rel=c]').hide();
      $('div.container:last').hide().each(function() {
        var el = document.createElement('div');
        $(el).attr('id', 'container').attr('class', 'container').attr('rel', 'history').insertAfter($(this)).load(last_href, function() {
          set_win_title();
          page_func();
          cart_func_history();
          page_func_history();
        });
      });
    } else if (/shipment/.test(document.location.hash)) {
      var last_href = modal_link('/shipment/');
      list_href[++cur_href] = '#' + hash;
      $('div.selectedItem[@rel=c]').hide();
      $('div.container:last').hide().each(function() {
        var el = document.createElement('div');
        $(el).attr('id', 'container').attr('class', 'container').insertAfter($(this)).load(last_href, function() {
          set_win_title();
          page_func();
          $('div.container:last .flexcroll').each(function() {fleXenv.fleXcrollMain(this)});
        }); 
      });
    } else if (/faq/.test(document.location.hash)) {
      var last_href = modal_link('/faq/');
      list_href[++cur_href] = '#' + hash;
      $('div.selectedItem[@rel=c]').hide();
      $('div.container:last').hide().each(function() {
        var el = document.createElement('div');
        $(el).attr('id', 'container').attr('class', 'container').insertAfter($(this)).load(last_href, function() {
          set_win_title();
          page_func();
          //$('#dv_detailsSide .flexcroll').each(function() {fleXenv.fleXcrollMain(this)});
        }); 
      });
    } else if (/about/.test(document.location.hash)) {
      var last_href = modal_link('/about/');
      list_href[++cur_href] = '#' + hash;
      $('div.selectedItem[@rel=c]').hide();
      $('div.container:last').hide().each(function() {
        var el = document.createElement('div');
        $(el).attr('id', 'container').attr('class', 'container').insertAfter($(this)).load(last_href, function() {
          set_win_title();
          page_func();
          //$('#dv_detailsSide .flexcroll').each(function() {fleXenv.fleXcrollMain(this)});
        }); 
      });
    } else if (/conflict/.test(document.location.hash)) { 
      list_href[++cur_href] = '#' + hash;     
      var last_href = modal_link('/conflict/');
      $('div.container:last').hide().each(function() {
        var el = document.createElement('div');
        $(el).attr('id', 'container').attr('class', 'container').attr('rel', 'conflict').insertAfter($(this)).load(last_href, function() {
          set_win_title();
          //page_func();
          conflict_func();      
          Custom.init();
        });
      });    
    } else if (/pay/.test(document.location.hash)) {
      while ($('div.container:last').attr('rel') != 'home') page_close_nohistory();
      var last_href = modal_link('/pay/');
      list_href[++cur_href] = '#' + hash;
      $('div.selectedItem[@rel=c]').hide();
      $('div.container:last').hide().each(function() {
        var el = document.createElement('div');
        $(el).attr('id', 'container').attr('class', 'container').attr('rel', 'pay').insertAfter($(this)).load(last_href, function() {
          set_win_title();
          page_func();
          pay_func();    
          cart_func_pay();
          Custom.init();
        });
      });    
    } else if (/profile/.test(document.location.hash)) {
      var last_href = modal_link('/profile/');
      list_href[++cur_href] = '#' + hash;
      $('div.selectedItem[@rel=c]').hide();
      $('div.container:last').hide().each(function() {
        var el = document.createElement('div');
        $(el).attr('id', 'container').attr('class', 'container').attr('rel', 'profile').insertAfter($(this)).load(last_href, function() {
          set_win_title();
          page_func();
          profile_func();        
          Custom.init();
        });
      }); 
    } else if (/^([^\/]+)\/([^\/]+)\/([^\/]+)\.html$/.test(hash)) { 
        fpar2 = 'fr2=0';
        if ($('div.container:last #dv_detailsSide').length) {
          list_href[cur_href] = '#' + hash;
          $('div.container:last').load(modal_link(add_params('/' + hash, fpar+'&' + fpar2)),  function() {
            set_win_title();
            $('#service #breabcrumbs').replaceWith($('div.container:last #breabcrumbs'));
            search_tree();
            item_func();
            $('#dv_detailsSide .flexcroll').each(function() {fleXenv.fleXcrollMain(this)});
          });
        } else {
          list_href[++cur_href] = '#' + hash;
          $('div.container:last').hide().each(function() {
            var el = document.createElement('div');
            fpar = 'fr=2';
            fpar2 = 'fr2=0';
            if ($('div.container:last #mainList li.active').length) {
              fpar = 'fr=6';
            }
            else if ($('div.container:last #mainList').length) {
              fpar = 'fr=1';
            }
            $(el).attr('id', 'container').attr('class', 'container').insertAfter($(this)).load(modal_link(add_params('/' + hash, fpar+'&' + fpar2)),  function() {
              set_win_title();
              $('#service #breabcrumbs').replaceWith($('div.container:last #breabcrumbs'));
              search_tree();
              item_func();
              $('#dv_detailsSide .flexcroll').each(function() {fleXenv.fleXcrollMain(this)});
            });
          });
          var tstr = hash_href(document.location.hash);
          tstr = tstr.replace(/\/([^\/]+)\.html$/, '/');
          $('#searchRoot').attr('value', tstr);
        }    
    } else if (/^home\/$/.test(hash)) { // не доработано
      while ($('div.container:last').attr('rel') != 'home') page_close_nohistory();
      cur_href = 1;
      list_href[cur_href] = '#' + hash;
      if (/[^ \t]{2,}/.test(document.getElementById('searchField').value)) {
        _search_close();
        search_close();
      }
      $('#mainList li').removeClass('active');
      if ($('#categorySelect').length) {
        $('#categorySelect').load(modal_link('/'), function() {
          set_win_title();
          index_domodal_();
        });
      } else {
        $('#in_container').load(modal_link2('/'), function() {
          set_win_title();
          index_domodal();
        });
      }
      $('#searchRoot').attr('value', '/');
      $('#breabcrumbs').html('');
      search_width();
    } else if (/^([^\/]+)\/([^\/]+)\/$/.test(hash)) { // не доработано
      while ($('div.container:last').attr('rel') != 'home') page_close_nohistory();
      list_href[++cur_href] = '#' + hash;
      $('#in_container').html(empty_list).load(modal_link('/' + hash), function() {
        set_win_title();
        items_domodal();
        list_func();
        $('div.container:last .flexcroll').each(function() {fleXenv.fleXcrollMain(this)});
        $('#service #breabcrumbs').replaceWith($('div.container:last #breabcrumbs'));
        search_tree();
      })
      $('#searchRoot').attr('value', '/' + hash);
    } 
    else if (/^([^\/]+)\/$/.test(hash)) { // не доработано
      while ($('div.container:last').attr('rel') != 'home') page_close_nohistory();
      list_href[++cur_href] = '#' + hash;
      $('#in_container').load(modal_link2('/' + hash), function() {
        set_win_title();
        index_domodal();
        subcat_domodal();
        $('#service #breabcrumbs').replaceWith($('div.container:last #breabcrumbs'));
        search_tree();
      });
      $('#searchRoot').attr('value', '/' + hash);
    } else {
      list_href[++cur_href] = '#' + hash;
//      alert('Не там где нужно: ' + hash);
    }
  } else {
  }
  return false;
}
unFocus.History.addEventListener('historyChange', historyListener);

//window.setTimeout(function() {
//  if (document.location.hash != list_href[cur_href]) document.location.replace(list_href[cur_href]);
//}, 100);
function restore_href()
{
/*  str = 'Restore' + "\n --------------------- \n";
  for(var i in list_href)
  {
        str = str + i + ' => ' + list_href[i] + "\n";
  }
  alert(str);*/
  if (cur_href > 1) {
    cur_href--;
    window_go(list_href[cur_href]);
    //history.back();
    //document.location.replace(list_href[cur_href]); 
  } else {
    cur_href++;
    list_href[cur_href] = '#home/';
    window_go('#home/');
  }
}
function htmlspecialchars(str)
{
  return str.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/'/g, '&#039;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}
function add_params(link, par)
{
  return /\?/.test(link) ? link + '&' + par : link + '?' + par;
}
function modal_link(link)
{
  return /\?/.test(link) ? link + '&modal=1' : link + '?modal=1';
}
function modal_link2(link)
{
  return /\?/.test(link) ? link + '&modal=1&smodal=1' : link + '?modal=1&smodal=1';
}
function modal_link3(link)
{
  return /\?/.test(link) ? link + '&modal=1&smodal=1' : link + '?modal=1&xmodal=1';
}
$(document).bind('ready', function() {
  index_domodal();
  subcat_domodal();
  items_domodal();
});
function index_domodal()
{
  $('#header .logo a').bind('click', function() {
    if (window.show_conflict && window.show_conflict == true) return false;
    if ($('div.container[@rel=home]').length)
    {
      while ($('div.container:last').attr('rel') != 'home') page_close();
      if (/[^ \t]{2,}/.test(document.getElementById('searchField').value)) {
        $('#close').trigger('click');
      }      
      $('#mainList li').removeClass('active');
      $('#mainList li[@rel=' + $(this).attr('rel') + ']').addClass('active');
      if ($('#categorySelect').length) {
        $('#categorySelect').load(modal_link($(this).attr('href')), function() {
          set_win_title();
          index_domodal_();
        });
      } else {
        $('#in_container').load(modal_link2($(this).attr('href')), function() {
          set_win_title();
          index_domodal();
        });
      }
      set_href($(this).attr('href'));
      $('#searchRoot').attr('value', $(this).attr('href'));
      $('#breabcrumbs').html('');
      search_width();
      return false;
    }
  });
  $('#mainList a').bind('click', function() {
      $('#mainList li').removeClass('active');
      $(this).parent().addClass('active');
      $('#categorySelect').load(modal_link($(this).attr('href')), function() {
        set_win_title();
        subcat_domodal();
        $('#service #breabcrumbs').replaceWith($('div.container:last #breabcrumbs'));
        search_tree();
      });
      $('#searchRoot').attr('value', $(this).attr('href'));
      set_href($(this).attr('href'));
      return false;
  });
  index_domodal_();
}
function index_domodal_()
{
  $('#categorySelect div a[@rel]').bind('click', function() {
      $('#mainList li').removeClass('active');
      $('#mainList li[@rel=' + $(this).attr('rel') + ']').addClass('active');
      $('#categorySelect').load(modal_link($(this).attr('href')), function() {
        set_win_title();
        subcat_domodal();
        $('#service #breabcrumbs').replaceWith($('div.container:last #breabcrumbs'));
        search_tree();
      });
      set_href($(this).attr('href'));
      $('#searchRoot').attr('value', $(this).attr('href'));
      return false;
  });
}
function subcat_domodal()
{
  $('#categorySelect a.sub').bind('click', function() {
      set_href($(this).attr('href'));
      $('#searchRoot').attr('value', $(this).attr('href'));
      $('#in_container').html(empty_list).load(modal_link($(this).attr('href')), function() {
        set_win_title();
        items_domodal();
        list_func();
        $('div.container:last .flexcroll').each(function() {fleXenv.fleXcrollMain(this)});
        $('#service #breabcrumbs').replaceWith($('div.container:last #breabcrumbs'));
        search_tree();
      })
      return false;
  });
}
function items_domodal()
{
}
var last_sid = null;
function do_show()
{
  var t2 = $('#itemList table');
  $(t2).hide();
  $(t2).find('tr.in').removeClass('alt').removeClass('invis');
  $(t2).find('a.dos').removeClass('dact');
  $('#filter ul').each(function() {
    if ($(this).find('a.inactive').length > 0) {
      $(this).find('a').not('.inactive').each(function() {
        $('#itemList tr.' + this.id).addClass('invis');
      });
      $(this).find('a.inactive').each(function() {
        last_sid = this.id;
        $('#itemList').find('a.dos').each(function() { if (this.id == last_sid) $(this).addClass('dact')});
      });
    }
  });
  t2.each(function() {
    var acti = 0;
    var t = $(this);
    t.find('tr.in').not('.invis').each(function() {
      if (++acti%2 == 1) $(this).addClass('alt') ;
    });
    t.find('th span').html(acti);
    if (acti) t.show(); else t.hide();
  });
  $('#filter ul a').each(function() {
    var cnt = $('#itemList tr.' + this.id).not('.invis').length;
    if (cnt) {
      $(this).find('span').html(cnt);
      $(this).parent().removeClass('invis');
    } else {
      $(this).parent().addClass('invis');
    }
  });
  $('#filter ul').each(function() {
    if ($(this).find('li').not('.invis').not('.rinvis').length > 1) {
      $(this).removeClass('invis');
    } else {
      $(this).addClass('invis');
    }
  })
  $('div.in_container:last .flexcroll').each(function() {fleXenv.fleXcrollMain(this)});
  //$('#itemList').each(function() {fleXenv.fleXcrollMain(this)});
  //$('#filter').each(function() {fleXenv.fleXcrollMain(this)});
}
function checkForm(frm, arr, mes)
{
  if (!frm || !frm.elements)
  {
    alert('Форма не определена');
    return false;
  }
  el = null;
  err = '';
  for(i in arr)
  {
    if (frm.elements[i])
    switch(frm.elements[i].type)
    {
      case 'text':
      case 'textarea':
      case 'password':
      case 'hidden':
      case 'file':
        if (frm.elements[i].value == '' || frm.elements[i].value == '0')
        {
          if (!el) el = frm.elements[i];
          err += arr[i] + "\n";
        }
        else if ((i == 'email') && (!/^[^@]+@[^@]+$/.test(frm.elements[i].value)))
        {
          if (!el) el = frm.elements[i];
          err += arr[i] + ' | Формат: email@somethere.org' + "\n";
        }       
        break;
      case 'select-one':
        if (frm.elements[i].value == '' || frm.elements[i].value == '0')
        {
          if (!el) el = frm.elements[i];
          err += arr[i] + "\n";
        }
        break;
    }
  }
  if (err == '')
  { 
    frm.onsubmit = function() {return false;}
    return true;
  }
  else
  {
    try { el.focus(); } catch(e) {}
    if (!mes) mes = 'Пожалуйста заполните обязательные поля'
    alert(mes + ":\n-----------------------------------\n" + err + "-----------------------------------");
    return false;
  }
}
function fserialize(frm)
{
  var str = '';
  for( var i=0; i<frm.elements.length; i++)
  {
    if (!frm.elements[i].name || frm.elements[i].disabled) continue;
    switch(frm.elements[i].type)
    {
      case 'text':
      case 'password':
      case 'textarea':
      case 'hidden':
      case 'select-one':
        if (frm.elements[i].value != '')
        {
          str += '&'+frm.elements[i].name+'='+encodeURIComponent(frm.elements[i].value);
        }
        break;
      case 'checkbox':
      case 'radio':
        if (frm.elements[i].checked)
        {
          str += '&' + frm.elements[i].name+'='+encodeURIComponent(frm.elements[i].value);
        }
        break;
    }
  }
  return str;
}
$(document).bind('keydown', function(event) {
    var key = event.charCode ? event.charCode : event.keyCode;
    if (key == 27) {
      if ($('.visible .buttons a.cancel').length > 0) {
        $('.visible .buttons a.cancel').trigger('click');
      } else if ($('.selectedItem:visible').length > 0) {
        $('.selectedItem:visible').hide();
      } else if ($('#cities').is(':visible')) {
        $('#cities').hide().removeClass('citpos1').removeClass('citpos2').removeClass('citpos3').prev().hide();
      } else {
        $('div.container:last .content .buttons a.close').trigger('click');
      }
    }
  });
$(document).bind('ready', function() {
  $('#footer a.cityname').bind('click', function() {
    if ($('#cities').hasClass('citpos1')) {
      $('#cities').hide().removeClass('citpos1').prev().hide();
    } else {
      $('#cities_wrap').show().next().show().removeClass('citpos2').removeClass('citpos3').addClass('citpos1').find('.flexcroll').each(function() {fleXenv.fleXcrollMain(this)});
    }
    return false;
  });
  $('#cities_wrap').add('#body_wrap').bind('click', function(){
    $('#cities').hide().removeClass('citpos1').removeClass('citpos2').removeClass('citpos3').prev().hide();
  })
  $('#cities a').bind('click', function() {
    $('#cities a').removeClass('act');
    $(this).addClass('act');
    $('a.cityname').html($(this).html());
    var rel = $(this).attr('rel').split('|');
    $('#dv_cart').load('/cart_pre.php?set_city=' + rel[0] + '&rand=' + Math.random(), function() {
      $('div.container:last #dv_cart .flexcroll').each(function() {fleXenv.fleXcrollMain(this)});
      cart_func();
      if ($('div.container[@rel=pay]').length) {
        reload_paycart();
        if (!window.ship_address) $('#addr_place').load('/pay.php?action=ship_address', addr_place);
        window.ship_address = false;
      }
    });
    if (rel[1]) {
      $('#footer p .p1').hide().next().show().html(rel[1]);
      $('#phone .p1').hide().next().show().html(rel[1]);
    } else {
      $('#footer p .p1').show().next().hide().html('');
      $('#phone .p1').show().next().hide().html('');
    }
    if (rel[2]) {
      $('#footer p .p2').hide().next().show().html('<a href="mailto:'+rel[2]+'">'+rel[2]+'</a>');
    } else {
      $('#footer p .p2').show().next().hide().html('');
    }
    $('#cities').hide().removeClass('citpos1').removeClass('citpos2').removeClass('citpos3').prev().hide();
    if ($('div.container[@rel=pay]').length) {
      if ($(this).hasClass('office')) {
        $('#payinfo ul.paytype li.start a').removeClass('disabled').addClass('control');
      } else {
        $('#payinfo ul.paytype li.start a').removeClass('control').addClass('disabled');
        if ($('#payinfo ul.paytype li.start a').hasClass('active')) {
          $('#payinfo ul.paytype li.end a').trigger('click');
        }
      }
      if ($('#cities a.act').hasClass('office') && !$('#payinfo ul.paytype a.active').parent().hasClass('end') && !$('#payinfo ul.time a.active').length) {        
        $('#payinfo ul.time li a').removeClass('disabled').addClass('control');
        $('#payinfo ul.time li.start a').addClass('active').next().attr('disabled', false);
      }
      if ((!$('#cities a.act').hasClass('office') || $('#payinfo ul.paytype a.active').parent().hasClass('end')) && $('#payinfo ul.time a.active').length) {     
        $('#payinfo ul.time li a').removeClass('control').addClass('disabled').removeClass('active').next().attr('disabled', true);
      }
      if (!$('#payinfo ul.paytype a.active').parent().prev().hasClass('end')) {
        if ($(this).hasClass('main')) {
          $('#payinfo ul.date a.dis_nk').removeClass('disabled');
        } else {
          if ($('#payinfo ul.date a.dis_nk').hasClass('active')) {
            $('#payinfo ul.date a.dis_nk').addClass('disabled').removeClass('act').parent().next().find('a').trigger('click');//.addClass('active');
          } else {
            $('#payinfo ul.date a.dis_nk').addClass('disabled');
          }
        }
      }
    }
    return false;
  });
});
function close_popups()
{
  if ($('#cities').is(':visible')) {
    $('#cities').hide().removeClass('citpos1').removeClass('citpos2').removeClass('citpos3').prev().hide();
  }
}
function clickcity(id)
{
  $('#cities a.q'+id).each(function() {
    if (!$(this).hasClass('act')) {
      $('#cities a').removeClass('act');
      $(this).addClass('act');
      $('a.cityname').html($(this).html());
      var rel = $(this).attr('rel').split('|');
      if (rel[1]) {
        $('#footer p .p1').hide().next().show().html(rel[1]);
      } else {
        $('#footer p .p1').show().next().hide().html('');
      }
      if (rel[2]) {
        $('#footer p .p2').hide().next().show().html('<a href="mailto:'+rel[2]+'">'+rel[2]+'</a>');
      } else {
        $('#footer p .p2').show().next().hide().html('');
      }
      $('#cities').hide().removeClass('citpos1').removeClass('citpos2').removeClass('citpos3').prev().hide();
    }
  })
}
function clickcurr(id)
{
  if ((id!=0 && $(document.body).hasClass('cr1')) || (id==0 && !$(document.body).hasClass('cr1'))) {
    $(document.body).toggleClass('cr1').toggleClass('cr2');
    $('#filter ul.clist a.inactive').removeClass('inactive');
    do_show();
  }
}
function getClassParent(obj, c) {
    while ( (!obj.hasClass(c)) && ( obj.size() != 0 ) ) {
        obj = obj.parent();
    }
    return obj;
}
function addr_place()
{  
  $('#payinfo .addressIn input.styled').bind('change', dis_addresses);
  $('#payinfo .payIn input.styled').bind('change', recalccart_pay);
  $('#payinfo .payIn input[@type=text]').bind('keyup', check_orderform).bind('keyup', check_orderform_).bind('blur', check_orderform__).bind('focus', function() {$(this).removeClass('error')});
  $('#payinfo .payIn input[@type=radio]').bind('change', check_orderform).bind('keyup', check_orderform_).bind('blur', check_orderform__).bind('focus', function() {$(this).removeClass('error')});
  $('#payinfo .payIn label').add('#payinfo .payIn input').bind('click', function() {
    getClassParent($(this), 'payIn').find('.styled').attr('checked', true);
    Custom.clear();
    dis_addresses();
    check_orderform();
    recalccart_pay();
  }); 
  $('#payinfo #address a.addr').bind('click', function() {
    $(this).parent().parent().addClass('hide').next().removeClass('hide');
    return false
  });    
  var lab = $('#payinfo .payIn input[@checked]').length ? $('#payinfo .payIn input[@checked]').parent() : $('#payinfo .payIn input[@type=hidden]').parent();
  if (lab.hasClass('payt7')) {
    $('#payinfo ul.paytype li.start a span').html('Менеджеру');
    $('#terminal font').html('Картой Visa / MasterCard через терминал');
    $('#dv_orderedItems .delivery').addClass('termdis2');
  } else {
    $('#payinfo ul.paytype li.start a span').html('Курьеру');
    $('#terminal font').html('Картой Visa / MasterCard курьеру с терминалом');
    $('#dv_orderedItems .delivery').removeClass('termdis2');
  }
  Custom.init();
  check_orderform();
}
function addr_place2()
{
  $('#profile #address a.addr').bind('click', function() {
    $(this).parent().parent().addClass('hide').next().removeClass('hide');
    return false
  });
  $('#profile #address input[@type=text]').bind('keyup', profile_check).bind('keyup', profile_check_).bind('blur', profile_check__).bind('focus', function() {$(this).removeClass('error')});;
  profile_check();
}
