// 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(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'; });
  }
}

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',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")'; }
    });
  }
});*/

// 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 getScreenSizes = 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), ie = suilib.client.msie, szs = (suilib.client.msie && !parameters) ? getScreenSizes() : [], 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;
  }
}


// Dynamic Tabs
var tabs = {
  init: function(args) {
    if(!args.apply) return false;
    var allNodes = args.apply.length ? $(suilib.body).filter('*',null,null,true) : [];
    var len = allNodes.length;
    for(var i=0; i<args.apply.length; i++) {
      this.all[i] = {};
      if(!args.apply[i].els && !args.apply[i].hds) continue;
      if(typeof args.apply[i].els=='string') {
        var tmp = [];
        for(var j=0; j<len; j++)
          if(allNodes[j] && allNodes[j].className && allNodes[j].className.split(' ').hasa(args.apply[i].els)!==false)
            tmp.push(allNodes[j]);
        this.all[i].els = tmp;
      } else if(typeof args.apply[i].els=='object' && args.apply[i].els.length)
        this.all[i].els = args.apply[i].els;
      if(args.apply[i].hds) {
        if(typeof args.apply[i].hds=='string') {
          var tmp = [];
          for(var j=0; j<len; j++) 
            if(allNodes[j] && allNodes[j].className && allNodes[j].className.split(' ').hasa(args.apply[i].hds)!==false)
              tmp.push(allNodes[j]);
          this.all[i].hds = tmp;
        } else if(typeof args.apply[i].hds=='object' && args.apply[i].hds.length)
          this.all[i].hds = args.apply[i].hds;
      }
      if(args.apply[i].open && this.all[i].els) {
        if(typeof args.apply[i].open=='string')
          this.all[i].open = $(args.apply[i].open);
        else if(typeof args.apply[i].open=='number' && args.apply[i].open<=this.all[i].els.length)
          this.all[i].open = $(this.all[i].els[args.apply[i].open-1]);
      }
      this.all[i].callback = (args.apply[i].callback || suilib.anonymous);
      this.buildTabs(this.all[i]);
    }
  },

  all: [],
  cls: ['tab', 'tab_act', 'tab_hover'],

  buildTabs: function(tArr) {
    var tHd = [], len = tArr.els ? tArr.els.length : tArr.hds.length;
    for(var i=0; i<len; i++) {
      var el = tArr.els ? $(tArr.els[i]) : null, hd = false;
      if(tArr.hds) hd = $(tArr.hds[i]); else hd = el.filter('*',null,null,true)[0];
      tHd.push(hd);
      if(!tArr.hds) el.parentNode.insertBefore(hd, $(tArr.els[0]));
      if(tArr.open && el==tArr.open) tArr.open = hd;
      if(el) el.hide();
    }

    var handlerClick = [], handlerOver = [], handlerOut = [];
    for(var i=0; i<tHd.length; i++) {
      handlerClick[i] = (function(){tabs.openTab(tArr, tHd, arguments.callee.obj);});
      handlerOver[i]  = (function(){var el = arguments.callee.obj, allCls = (el.className.split(' ') || []); if(allCls.hasa(tabs.cls[1])===false) el.classReplace('tab_hover', tabs.cls);});
      handlerOut[i]   = (function(){var el = arguments.callee.obj, allCls = (el.className.split(' ') || []); if(allCls.hasa(tabs.cls[1])===false) el.classReplace('tab', tabs.cls);});
      handlerClick[i].obj = handlerOver[i].obj = handlerOut[i].obj = tHd[i];
      handlerClick[i].$('click', tHd[i]);
      handlerOver[i].$('mouseover', tHd[i]);
      handlerOut[i].$('mouseout', tHd[i]);
    }

    //var prior_tab = get_cookie('tab');
    var tab_to_open = tArr.open ? tArr.open : tHd[0];
    //if(prior_tab && document.getElementById(prior_tab))
      //tab_to_open = $(prior_tab);
    if(document.location.hash != '')
    {
      var hash = document.location.hash.replace(/^#/, '');
      if(document.getElementById('tab_'+hash))
        tab_to_open = $('tab_'+hash);
    }
    this.openTab(tArr, tHd, tab_to_open);
  },

  openTab: function(tArr, tHd, tOpen) {
    var id = tOpen.getAttribute('id');
    // save selected tab in cookie
    if(id) {
      set_cookie("tab", id, null, null, null, "/");
      document.location.hash = '#'+id.replace('tab_', '');
    }
    var index = 0;
    for(var i=0; i<tHd.length; i++) {
      var allCls = (tHd[i].className.split(' ') || []);
      if(tHd[i]==tOpen) {
        if(allCls.hasa(tabs.cls[1])!==false) return false;
        tHd[i].classReplace('tab_act', this.cls);
        index = i;
      } else {
        if(allCls.hasa(tabs.cls[0])!==false) continue;
        tHd[i].classReplace('tab', this.cls);
        if(tArr.els) $(tArr.els[i]).hide();
      }
    }
    var el = tArr.els ? tArr.els[index] : null;
    if(tArr.callback) tArr.callback(tHd[index], el, index+1);
    if(el) $(tArr.els[index]).show();
  }
}


// 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, runtype, effect, inter, interanim) {

  if(!pics || (pics.length==1 && !runtype)) return false;
  var el = ($(id) || $('pics_container')), rt = runtype || false, interval = (inter*1000 || 1500);
  var cur = (el.firstChild.tagName==='IMG') ? el.firstChild : el.firstChild.firstChild, sizes = getSizes(cur);
  var jto = { time : interanim || (interval - interval/3)/1000, transition : 'easeNone' };

  if(el.getAttribute('rotating')) return; else el.setAttribute('rotating','true');

  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(pics[i].match(/(?:\/|)([^\/]+)$/)[1]==cur.src.match(/(?:\/|)([^\/]+)$/)[1] && pics[i+1]) j = i + 1;
    var ni = new Image(), iw = sizes[0], ih = sizes[1];

    ni.onload = function() {
      if(effect) {
        var old_el = 'position:' + (el.style.position || 'static'),
            old_im = 'position:' + (el.style.position || 'static') + ';z-index:' + (el.style.zIndex || 0);
        var $callback = function(img) {
          if(rt) {
            el.removeAttribute('rotating');
            $(el).setstyle(old_el);
            $(img).setstyle(old_im);
          }
        };

        $(el).setstyle('width:'+iw+'px;height:'+ih+'px');
        switch(effect) {
        case 'fadeIn':
          $(cur.parentNode).add('img', {'src':ni.src, 'width':iw, 'height':ih});
          var imgs = $(cur.parentNode).filter('img', null, null, true);
          $(imgs[1]).setstyle('opacity:0');
          $(imgs[0]).unset();
          if('jTweener' in window) $(imgs[1]).tweener({opacity : 1}).tween(jto); else $(imgs[1]).animate(.5, {opacity:[0, 100]});
        break;
        case 'fadeOut':
          $(cur.parentNode).add('img', {'src':ni.src, 'width':iw, 'height':ih, 'style':'display:none'});
          var imgs = $(cur.parentNode).filter('img', null, null, true);

          var callback = function(){
            $(imgs[1]).show();
            $(imgs[0]).unset();
          };
          if('jTweener' in window) $(imgs[0]).tweener({opacity : 0, onComplete : callback}).tween(jto); else $(imgs[0]).animate(.7, {opacity:[100, 0]}, callback);
        break;
        case 'flyIn':
          if('jTweener' in window) {
            $(el).setstyle('position:relative');
            $(cur.parentNode).add('img', {'src':ni.src, 'width':iw, 'height':ih, 'style':'position:absolute;z-index:100;top:0;left:'+iw/3+'px'});
            var imgs = $(cur.parentNode).filter('img', null, null, true);
            $(imgs[1]).setstyle('opacity:0');
            $(imgs[1]).tweener({left : 0, opacity : 1, onComplete : function(){$(imgs[0]).unset();$callback(imgs[1]);} }).tween(jto);
          }
        break;
        case 'flyOut':
          if('jTweener' in window) {
            $(el).setstyle('position:relative');
            $(cur.parentNode).add('img', {'src':ni.src, 'width':iw, 'height':ih, 'style':'position:absolute;z-index:100;top:0;left:0'});
            var imgs = $(cur.parentNode).filter('img', null, null, true);
            $(imgs[0]).setstyle('position:absolute;z-index:101;left:0;top:0');
            $(imgs[0]).tweener({left : -iw/3, opacity : 0, onComplete : function(){$(imgs[0]).unset();$callback(imgs[0]);} }).tween(jto);
          }
        break;
        case 'morph': default:
          $(el).setstyle('position:relative');
          $(cur.parentNode).add('img', {'src':ni.src, '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');

          var callback = function() {
            $(imgs[0]).unset();
            $callback(imgs[1]);
          };
          if('jTweener' in window) $(imgs[1]).tweener({opacity : 1, onComplete : callback}).tween(jto); else $(imgs[1]).animate(.5, {opacity:[0, 100]}, callback);
        break; }
      } else {
        cur.src = ni.src;
      }
      if(!rt) st = setTimeout(run, interval);
    }
    ni.src = pics[j];
  };

  if(rt) run(); else var st = setTimeout(run, interval);
}
