// Scripts (#include suilib_lite.js)
// Created in Shogo.Ru


// PNG IE6 Fix
var msie6 = !!(suilib.client.msie && navigator.appVersion && !navigator.appVersion.match(/MSIE 7/));
function fixBgPNG_c(el) {
  var tmp = el.currentStyle.backgroundImage.match(/url\("(.+\.png)"\)/i);
  if(tmp && msie6) {
    tmp = tmp[1];
    el.runtimeStyle.backgroundImage = 'none';
    el.runtimeStyle.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="' + tmp + '",sizingMethod="crop")';
    $(el).filter('a',null,null,true).walkwith(function(lnk) {
      lnk.style.position = 'relative'; });
  }
}
function fixBgPNG_s(el) {
  var tmp = el.currentStyle.backgroundImage.match(/url\("(.+\.png)"\)/i);
  if(tmp && msie6) {
    tmp = tmp[1];
    el.runtimeStyle.backgroundImage = 'none';
    el.runtimeStyle.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="' + tmp + '",sizingMethod="scale")';
    $(el).filter('a',null,null,true).walkwith(function(lnk) {
      lnk.style.position = 'relative'; });
  }
}

suilib.ready(function()
{
  // Highslide gallery
  if( 'hs' in window && hs.expand )
  {
    $(suilib.body).filter('a', 'highslide', null, true).walkwith(function(el)
    {
      (function(e)
      {
        e.returnValue = false;
        if( e.preventDefault )
          e.preventDefault();

        hs.expand(el);
      }).$('click', el);
    })
  }
});

suilib.ready(function() {
  if(msie6) {
    $(suilib.body).filter('img','pngfix',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")'; }
    });
  }
});


// Get Object's Sizes
var getSizes = function(el) {
  var display = el.style.display;
  if(display != 'none' && display != null) {
    return [el.offsetWidth, el.offsetHeight];
  } else {
    var cel = el.cloneNode(true);
    var els = cel.style;
    els.visibility = 'hidden';
    els.position = 'absolute';
    els.display = 'block';
    $(suilib.body).appendChild(cel);
    var w = cel.clientWidth, h = cel.clientHeight;
    cel.unset(true);
    return [w, h];
  }
}


// Show Positioned Element
function showPosDiv (src, targ, parameters) {
  var src = $(src), coords = src.offset(true), targ = $(targ), ie = suilib.client.msie, szs = (suilib.client.msie && !parameters) ? suilib.screensizes() : [], tzs = getSizes(targ);
  if(parameters && typeof parameters=='string') {
    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] - tzs[1] + 'px';
        break;
        case 'bottom':
          targ.style.top = coords[1] + src.offsetHeight + 'px';
        break;
        case 'left':
          targ.style.left = coords[0] - tzs[0] + '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] + tzs[1]) >= scrH) targ.style.top = coords[1] - tzs[1] + 'px'; else targ.style.top = coords[1] + src.offsetHeight + 'px';
    if((coords[0] + tzs[0]) >= scrW) targ.style.left = coords[0] - tzs[0] + src.offsetWidth + 'px'; else targ.style.left = coords[0] + 'px'; }

  targ.show();
}


// Element's Check
var gbi = function(el) { return !!document.getElementById(el); }


// Object Functions
var objTools = {
  $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) {
    var self = this;
    switch(typeof(hash)) {
      case 'string':
        return "'" + hash.replace(/[\x00-\x1f\\"]/g, function(chr){ return self.$replaceChars.apply(self, [chr]); }) + "'";
      case 'number':
        return isFinite(hash) ? String(hash) : 'null';
      case 'object':
        if(hash===null) return String(hash);
        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;
  },
  length: function(hash) {
    if(!hash || typeof(hash)!=='object') return null;
    var j = false;
    for(var i in hash) j++;
    return j;
  },
  clone: function(hash) {
    if(!hash || typeof(hash)!=='object') return hash;
    var newHash = hash.constructor();
    for(var i in hash) {
      newHash[i] = this.clone(hash[i]);
    }
    return newHash;
  }
}
function objLength(hash) { // для обратной совместимости
  return objTools.length(hash);
}


// 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 )
    {
      if(!required[i]['not_req'])
      {
        alert(required[i]['name']+' не может быть пустым!');
        $(required[i]['id']).focus();
        return false;
      }
    }
    if( required[i]['email'] && !$(required[i]['id']).value.match(/\S+@\S+\.\S+/) )
    {
      if($(required[i]['id']).value)
      {
        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 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;
      }
    }
  };
}();
