// PNG IE6 Fix (#include suilib_lite.js)
// Created in Shogo.Ru
var msie6 = !!(suilib.client.msie && navigator.appVersion && !navigator.appVersion.match(/MSIE 7/));
function fixBgPNG(el,param) {
  var tmp = el.currentStyle.backgroundImage.match(/url\("(.+\.png)"\)/i);
  if(tmp && msie6) {
    tmp = tmp[1];
    if(!param) param = 'scale';
    el.runtimeStyle.backgroundImage = 'none';
    el.runtimeStyle.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="' + tmp + '",sizingMethod="' + param + '")';
    $(el).filter('a',null,null,true).walkwith(function(lnk) {
      lnk.style.position = 'relative'; });
  }
}

var gbi = function(el) { !(document.getElementById(el)); }
suilib.ready(function() {
/*  if(msie6) {
    $(suilib.body).filter('img',null,null,true).walkwith(function(el) {
      var tmp = el.getAttribute('src');
      if(tmp.search && tmp.search(/\.png$/i)>=0) {
        el.src = 'i/sp.gif';
        el.runtimeStyle.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="' + tmp + '",sizingMethod="crop")'; }
    });
  }*/
});

// Show Positioned Element
function showPosDiv (src, targ, parameters) {
  var getsizes = function() {
    document.body.style.padding = 0;
    document.body.style.margin  = 0;
    var wW = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth || 0;
    var wH = window.innerHeight ||  document.documentElement.clientHeight || document.body.clientHeight || 0;
    var dW = Math.min(document.body.scrollWidth, wW), dH = Math.max(document.body.scrollHeight, wH);
    document.body.style.padding = '';
    document.body.style.margin  = '';
    return [wW,wH,dW,dH]; }

  var src = $(src), coords = src.offset(true), targ = $(targ), targW = 0, targH = 0, ie = suilib.client.msie, szs = (suilib.client.msie && !parameters) ? getsizes() : [];
  var display = targ.style.display;
  if (display != 'none' && display != null) {
    targW = targ.offsetWidth;
    targH = targ.offsetHeight; }
  else {
    var els = targ.style;
    var originalVisibility = els.visibility, originalPosition = els.position, originalDisplay = els.display;
    els.visibility = 'hidden';
    els.position = 'absolute';
    els.display = 'block';
    targW = targ.clientWidth;
    targH = targ.clientHeight;
    els.display = originalDisplay;
    els.position = originalPosition;
    els.visibility = originalVisibility; }

  if(parameters && typeof parameters=='string') {
    if(parameters=='hint') {
      targ.style.top = coords[1] + src.offsetHeight - 36 + 'px';
      var tsl = coords[0] + src.offsetWidth;
      targ.style.left = ((tsl >= 210) ? tsl + 5 : tsl + 35) + 'px';
    } else {
      var pAr = parameters.split(' ');
      targ.style.top = coords[1] + 'px'; targ.style.left = coords[0] + 'px';
      for (var i=0; i<pAr.length; i++) {
        switch(pAr[i]) {
          case 'top':
            targ.style.top = coords[1] - targH + 'px';
            break;
          case 'bottom':
            targ.style.top = coords[1] + src.offsetHeight + 'px';
            break;
          case 'left':
            targ.style.left = coords[0] - targW + 'px';
            break;
          case 'right':
            targ.style.left = coords[0] + src.offsetWidth + 'px';
            break; }
      }
    }
  }
  else {
    var scrW = ie ? szs[0] : window.innerWidth;
    var scrH = ie ? szs[3] : Math.max(document.body.scrollHeight, window.innerHeight);
    if((coords[1] + targH) >= scrH) targ.style.top = coords[1] - targH + 'px'; else targ.style.top = coords[1] + src.offsetHeight + 'px';
    if((coords[0] + targW) >= scrW) targ.style.left = coords[0] - targW + src.offsetWidth + 'px'; else targ.style.left = coords[0] + 'px'; }

  targ.show();
}


//-----------------------------------------------------------------------------
// objTools
//-----------------------------------------------------------------------------
var objTools = {
  print: function(hash) {
    if(!hash || typeof(hash)!=='object') return null;
    return 'var data = ' + this.parse(hash) + ';';
  },
  $specialChars: {
    '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"' : '\\"', '\\': '\\\\'
  },
  $replaceChars: function(chr) {
    return this.$specialChars[chr] || '\\u00' + Math.floor(chr.charCodeAt() / 16).toString(16) + (chr.charCodeAt() % 16).toString(16);
  },
  parse: function(hash) {
    switch(typeof(hash)) {
      case 'string':
        return "'" + hash.replace(/[\x00-\x1f\\"]/g, this.$replaceChars) + "'";
      case 'number':
        return isFinite(hash) ? String(hash) : 'null';
      case 'object':
        var string = [];
        if(hash.length) {
          for(var i=0,l=hash.length; i<l; i++) {
            if(typeof hash[i]=='undefined') continue;
            string.push(this.parse(hash[i]));
          }
          return '[' + String(string) + ']';
          break;
        }
        for(var i in hash) {
          var json = this.parse(hash[i]);
          if(json) string.push(this.parse(i) + ':' + json);
        }
        return '{' + string + '}';
      default: return String(hash);
    }
    return null;
  }
}
//-----------------------------------------------------------------------------


//-----------------------------------------------------------------------------
// parse_price(data)
//-----------------------------------------------------------------------------
function parse_price(data)
{
  var offset = 0;
  var new_data = "";
  var data = String(data).replace(/,/, '.');

  if( String(data).indexOf('.') != -1 )
    data = String(Math.ceil(data));

  if( data.indexOf('.') != -1 || data.length < 4)
    return data;
  else
    offset = data.length;

  while( offset > 2 )
  {
    new_data = data.substr(offset-3, 3)+" "+new_data;
    offset -= 3;
  }
  if( offset < 3 )
    new_data = data.substr(0, offset)+" "+new_data;

  new_data = new_data.replace(/ $/, '');
  return new_data;
}
//-----------------------------------------------------------------------------
// Functions from SUILib_lite
function $HAR(resp) { // (handle ajax response) стандартный вывод сообщений об ошибках
  var result = false, defmsg = 'Произошла неизвестная ошибка!';
  if(resp && resp.responseJS) {
    switch(resp.responseJS.status) {
      case 'ok': result = true;
      break;
      case 'error': alert(resp.responseJS.message || defmsg);
      break;
      default: alert(defmsg);
    }
    if(resp.responseJS.evaluate) eval(resp.responseJS.evaluate);
    if(resp.responseJS.debug) alert('[debug]:\n'+resp.responseJS.debug);
  }
  return result;
}

function check_required(required)
{
  for( var i = 0; i < required.length; i++ )
  {
    if( !$(required[i]['id']).value.trim().length )
    {
      alert(required[i]['name']+' не может быть пустым!');
      $(required[i]['id']).focus();
      return false;
    }
    if( required[i]['email'] && !$(required[i]['id']).value.match(/\S+@\S+\.\S+/) )
    {
      alert(required[i]['name']+' содержит некорректное значение!');
      $(required[i]['id']).focus();
      return false;
    }
    if( required[i]['numeric'] && !$(required[i]['id']).value.match(/[\d]+/) )
    {
      alert(required[i]['name']+' содержит некорректное значение!');
      $(required[i]['id']).focus();
      return false;
    }
    if( required[i]['group_1_2_3'] && !$(required[i]['id']).value.match(/(1|2|3)(,(1|2|3))*/) )
    {
      alert(required[i]['name']+' содержит некорректное значение!');
      $(required[i]['id']).focus();
      return false;
    }
  }
  return true;
}

function objLength(hash) {
  if(!hash || typeof(hash)!=='object') return null;
  var result = false;
  for(var i in hash) result++;
  return result;
}

function array2hash(obj) {
  if( !obj )
    return obj;

  if( !(obj instanceof Array) )
    return obj;

  if( obj.length == 0 )
    return {};

  var new_obj = {};
  for( var i = 0; i < obj.length; i++ )
    new_obj[i] = obj[i];

  return new_obj;
}

var data_cacher = function()
{
  var data = {};

  return {
    'cache': function(url)
    {
      if( url in data )
        return false;
      else
      {
        data[url] = new Image();
        data[url].src = url;
        return true;
      }
    }
  };
}();


//-----------------------------------------------------------------------------
// set_cookie(name, value, exp_y, exp_m, exp_d, path, domain, secure)
//-----------------------------------------------------------------------------
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;
}
//-----------------------------------------------------------------------------


//-----------------------------------------------------------------------------
// delete_cookie(cookie_name)
//-----------------------------------------------------------------------------
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();
}
//-----------------------------------------------------------------------------


//-----------------------------------------------------------------------------
// get_cookie(cookie_name)
//-----------------------------------------------------------------------------
function get_cookie(cookie_name)
{
  var results = document.cookie.match ( '(^|;) ?' + cookie_name + '=([^;]*)(;|$)' );

  if( results )
    return ( unescape ( results[2] ) );
  else
    return null;
}
//-----------------------------------------------------------------------------


// JS Image Changer (Modified)
function pchanger(pics, id, effect, inter) {
  if(!pics) return false;
  var imgcache = {}, el = ($(id) || $('pics_container')), interval = (inter*1000 || 1500);
  var cur = (el.firstChild.tagName==='IMG') ? el.firstChild : el.firstChild.firstChild, sizes = getSizes(cur);
  for(var i=0,l=pics.length; i<l; i++) {
    imgcache[i] = new Image();
    imgcache[i].src = pics[i]; }

  var run = function() {
    var cur = (el.firstChild.tagName==='IMG') ? el.firstChild : el.firstChild.firstChild, j = 0;
    for(var i=0,l=pics.length; i<l; i++) if(imgcache[i].src == cur.src && imgcache[i+1]) j = i + 1;
    var ns = imgcache[j].src, iw = sizes[0], ih = sizes[1];
    if(effect) {
      if(st) clearTimeout(st);
      $(el).setstyle('width:'+iw+'px;height:'+ih+'px');
      switch(effect) {
      case 'fade':
        $(cur.parentNode).add('img', {'src':ns, 'width':iw, 'height':ih, 'style':'display:none;'});
        var imgs = $(cur.parentNode).filter('img', null, null, true);
        $(imgs[0]).animate(.3, {opacity:[100, 0]}, function(){
          $(imgs[0]).hide();$(imgs[1]).show(.3, 'fade');$(imgs[0]).unset()});
      break;
      case 'morph': default:
        $(el).setstyle('position:relative');
        $(cur.parentNode).add('img', {'src':ns, 'width':iw, 'height':ih, 'style':'position:absolute;z-index:100;top:0;left:0;'});
        var imgs = $(cur.parentNode).filter('img', null, null, true);
        $(imgs[1]).setstyle('opacity:0;');
        if(suilib.client.msie) {
          $(imgs[1]).hide();
          $(imgs[1]).show(.5, 'fade'); }
        $(imgs[1]).animate(.5, {opacity:[0, 100]}, function(){
          $(imgs[0]).unset();});
      break; }
    } else {
      cur.src = ns; }
    st = setTimeout(run, interval);
  }

  var st = setTimeout(run, interval);
}